522 lines
18 KiB
JavaScript
522 lines
18 KiB
JavaScript
const workspace = document.querySelector("#workspace");
|
|
if (workspace) attachWebControls();
|
|
|
|
const source = document.querySelector("#source");
|
|
const pages = document.querySelector("#pages");
|
|
const status = document.querySelector("#status, #preview-status");
|
|
const error = document.querySelector("#error, #preview-error-text");
|
|
const errorPanel = document.querySelector("#error, #preview-error");
|
|
const pdf = document.querySelector("#pdf");
|
|
const save = document.querySelector("#save");
|
|
const saved = document.querySelector("#saved, #file-panel-foot");
|
|
const selector = document.querySelector("#project-files");
|
|
const name = document.querySelector("#name, #open-file-path");
|
|
const fileTree = document.querySelector("#file-tree");
|
|
const edits = new Map();
|
|
const fileViews = new Map();
|
|
const EDIT_IDLE_MS = 70;
|
|
const PREVIEW_SOCKET_RETRY_MS = 1000;
|
|
let files;
|
|
let activeFile;
|
|
let sequence = 0;
|
|
let publishedRevision = null;
|
|
let draft = null;
|
|
let composing = false;
|
|
let compileTimer;
|
|
let lastTypingAt = -Infinity;
|
|
let promptCompilePending = false;
|
|
let previewSocketUrl;
|
|
let previewSocket;
|
|
let previewSocketRetryAt = 0;
|
|
let pendingSocketPreview;
|
|
const projectPrefix = location.pathname.startsWith("/p/") ? location.pathname.slice(0, -1) : "";
|
|
const previewDraft = new URLSearchParams(location.hash.slice(1)).get("preview") !== "published";
|
|
|
|
function attachWebControls() {
|
|
const button = document.createElement("button");
|
|
button.type = "button";
|
|
button.id = "save";
|
|
button.className = "btn";
|
|
button.disabled = true;
|
|
button.textContent = "保存源文件";
|
|
document.querySelector(".file-tools").replaceChildren(button);
|
|
|
|
const download = document.createElement("a");
|
|
download.id = "pdf";
|
|
download.className = "btn small";
|
|
download.download = "";
|
|
download.hidden = true;
|
|
download.textContent = "下载 PDF";
|
|
document.querySelector("#export-pdf").replaceWith(download);
|
|
|
|
const back = document.querySelector("#back-button");
|
|
back.hidden = !location.pathname.startsWith("/p/");
|
|
back.addEventListener("click", () => { location.href = "/"; });
|
|
document.querySelector("#toggle-engine").hidden = true;
|
|
document.querySelector("#header-actions").textContent = "原生 Beta";
|
|
document.querySelector("footer").textContent = "Ctrl/Cmd+S 保存源码副本";
|
|
document.querySelector("#source").disabled = true;
|
|
document.querySelector("#file-panel-foot").setAttribute("role", "status");
|
|
document.querySelector("#file-panel-foot").style.overflowWrap = "anywhere";
|
|
workspace.hidden = false;
|
|
}
|
|
|
|
function selectFile(filename) {
|
|
if (filename === activeFile) return;
|
|
if (activeFile !== undefined) {
|
|
if (composing) {
|
|
// Let the platform commit the old file before replacing its buffer.
|
|
source.blur();
|
|
if (composing) {
|
|
composing = false;
|
|
queueCompile(true);
|
|
}
|
|
}
|
|
fileViews.set(activeFile, {
|
|
start: source.selectionStart,
|
|
end: source.selectionEnd,
|
|
direction: source.selectionDirection,
|
|
top: source.scrollTop,
|
|
left: source.scrollLeft,
|
|
});
|
|
}
|
|
activeFile = filename;
|
|
name.textContent = filename;
|
|
source.value = edits.get(filename) ?? files.get(filename);
|
|
const view = fileViews.get(filename);
|
|
source.setSelectionRange(view?.start ?? 0, view?.end ?? 0, view?.direction ?? "none");
|
|
source.scrollTop = view?.top ?? 0;
|
|
source.scrollLeft = view?.left ?? 0;
|
|
if (fileTree) {
|
|
for (const row of fileTree.children) {
|
|
const selected = row.dataset.path === activeFile;
|
|
row.classList.toggle("active", selected);
|
|
row.setAttribute("aria-pressed", selected);
|
|
}
|
|
}
|
|
}
|
|
|
|
function showError(message) {
|
|
status.textContent = "编译失败";
|
|
error.textContent = message;
|
|
errorPanel.hidden = false;
|
|
}
|
|
|
|
function pageImage(page) {
|
|
const img = new Image();
|
|
img.alt = `第 ${page.index + 1} 页`;
|
|
img.dataset.index = page.index;
|
|
if (workspace) {
|
|
img.className = "page";
|
|
img.style.aspectRatio = "auto";
|
|
}
|
|
img.src = URL.createObjectURL(new Blob([page.svg], { type: "image/svg+xml" }));
|
|
return img;
|
|
}
|
|
|
|
function revokeDetached(images) {
|
|
for (const image of images) {
|
|
if (!image.isConnected) URL.revokeObjectURL(image.src);
|
|
}
|
|
}
|
|
|
|
function applyPages(update, replacements) {
|
|
const previous = [...pages.children];
|
|
if (update.base_revision === null) {
|
|
pages.replaceChildren(...replacements);
|
|
} else {
|
|
for (const image of replacements) {
|
|
const old = pages.children[Number(image.dataset.index)];
|
|
if (old) old.replaceWith(image);
|
|
else pages.append(image);
|
|
}
|
|
while (pages.children.length > update.page_count) pages.lastElementChild.remove();
|
|
}
|
|
document.body.dataset.visibleRevision = update.revision;
|
|
return previous;
|
|
}
|
|
|
|
function restorePublishedPages() {
|
|
if (!draft) return;
|
|
const discarded = [...pages.children];
|
|
pages.replaceChildren(...draft.previous);
|
|
revokeDetached(discarded);
|
|
if (publishedRevision === null) delete document.body.dataset.visibleRevision;
|
|
else document.body.dataset.visibleRevision = publishedRevision;
|
|
pdf.hidden = publishedRevision === null;
|
|
draft = null;
|
|
}
|
|
|
|
function acceptPublication(revision, previous) {
|
|
revokeDetached(previous);
|
|
publishedRevision = revision;
|
|
pdf.href = projectPrefix + `/pdf?revision=${revision}`;
|
|
pdf.hidden = false;
|
|
draft = null;
|
|
}
|
|
|
|
async function publicationStatus(edit, revision) {
|
|
while (edit === sequence) {
|
|
const response = await fetch(projectPrefix + `/publication?revision=${revision}`);
|
|
const result = await response.json();
|
|
if (!response.ok || result.state === "failed") throw new Error(result.error);
|
|
if (result.state === "published") return result;
|
|
await new Promise((resolve) => setTimeout(resolve, 40));
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function completeSocketPreview(reply) {
|
|
const pending = pendingSocketPreview;
|
|
pendingSocketPreview = undefined;
|
|
pending?.resolve(reply);
|
|
}
|
|
|
|
function retirePreviewSocket(socket) {
|
|
if (previewSocket !== socket) return;
|
|
previewSocket = undefined;
|
|
previewSocketRetryAt = performance.now() + PREVIEW_SOCKET_RETRY_MS;
|
|
completeSocketPreview(null);
|
|
socket.close();
|
|
}
|
|
|
|
function connectPreviewSocket() {
|
|
if (!previewSocketUrl || previewSocket || performance.now() < previewSocketRetryAt) return;
|
|
let socket;
|
|
try {
|
|
socket = new WebSocket(previewSocketUrl);
|
|
} catch {
|
|
previewSocketRetryAt = performance.now() + PREVIEW_SOCKET_RETRY_MS;
|
|
return;
|
|
}
|
|
previewSocket = socket;
|
|
socket.addEventListener("close", () => retirePreviewSocket(socket));
|
|
socket.addEventListener("error", () => retirePreviewSocket(socket));
|
|
socket.addEventListener("message", ({ data }) => {
|
|
if (previewSocket !== socket || !pendingSocketPreview) return;
|
|
try {
|
|
const reply = JSON.parse(data);
|
|
if (reply.sequence !== pendingSocketPreview.sequence
|
|
|| !Number.isInteger(reply.status) || reply.status < 200 || reply.status > 599
|
|
|| !reply.body || typeof reply.body !== "object") {
|
|
retirePreviewSocket(socket);
|
|
return;
|
|
}
|
|
completeSocketPreview(reply);
|
|
} catch {
|
|
retirePreviewSocket(socket);
|
|
}
|
|
});
|
|
}
|
|
|
|
function advertisePreviewSocket(path) {
|
|
if (typeof WebSocket !== "function" || path !== projectPrefix + "/preview-socket") return;
|
|
const url = new URL(path, location.href);
|
|
url.protocol = location.protocol === "https:" ? "wss:" : "ws:";
|
|
previewSocketUrl = url.href;
|
|
connectPreviewSocket();
|
|
}
|
|
|
|
function requestSocketPreview(payload) {
|
|
connectPreviewSocket();
|
|
const socket = previewSocket;
|
|
// The native socket handles one request at a time. An edit that supersedes
|
|
// this request goes straight to HTTP so it can cancel the existing work.
|
|
if (!socket || socket.readyState !== WebSocket.OPEN || pendingSocketPreview) return null;
|
|
return new Promise((resolve) => {
|
|
pendingSocketPreview = { sequence: payload.sequence, resolve };
|
|
try {
|
|
socket.send(JSON.stringify(payload));
|
|
} catch {
|
|
retirePreviewSocket(socket);
|
|
}
|
|
});
|
|
}
|
|
|
|
async function requestHttpPreview(payload) {
|
|
const response = await fetch(projectPrefix + "/preview", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(payload),
|
|
});
|
|
return { status: response.status, body: await response.json() };
|
|
}
|
|
|
|
async function compile(edit, submitted, changes) {
|
|
const replacements = [];
|
|
try {
|
|
const payload = {
|
|
sequence: edit,
|
|
visible_revision: publishedRevision,
|
|
files: changes,
|
|
preview_draft: previewDraft,
|
|
};
|
|
const socketReply = requestSocketPreview(payload);
|
|
let response;
|
|
if (socketReply) {
|
|
response = await socketReply;
|
|
if (edit !== sequence) return;
|
|
if (!response) {
|
|
// The native server may have accepted the edit before the disconnect.
|
|
// Retry the same local changes with a fresh sequence to supersede it.
|
|
edit = ++sequence;
|
|
payload.sequence = edit;
|
|
}
|
|
}
|
|
response ??= await requestHttpPreview(payload);
|
|
if (edit !== sequence) return;
|
|
const result = response.body;
|
|
if (response.status < 200 || response.status >= 300) throw new Error(result.error);
|
|
const update = result.update;
|
|
if (result.sequence !== edit || (update.base_revision !== null && update.base_revision !== publishedRevision)) {
|
|
throw new Error("预览版本与当前页面不一致");
|
|
}
|
|
for (const page of update.pages) replacements.push(pageImage(page));
|
|
await Promise.all(replacements.map((page) => page.decode()));
|
|
if (edit !== sequence) {
|
|
revokeDetached(replacements);
|
|
return;
|
|
}
|
|
const previous = applyPages(update, replacements);
|
|
if (result.pending_publication) {
|
|
draft = { previous };
|
|
pdf.hidden = true;
|
|
status.textContent = "正在写入文件";
|
|
} else {
|
|
acceptPublication(update.revision, previous);
|
|
}
|
|
errorPanel.hidden = true;
|
|
await new Promise(requestAnimationFrame);
|
|
await new Promise(requestAnimationFrame);
|
|
if (edit !== sequence) return;
|
|
const sample = {
|
|
sequence: edit,
|
|
revision: update.revision,
|
|
changed: update.pages.map((page) => page.index + 1),
|
|
count: update.page_count,
|
|
compileMs: result.compile_ms,
|
|
engineMs: result.ready_ms,
|
|
admissionAndQueueMs: result.admission_and_queue_ms,
|
|
phases: result.phases,
|
|
visibleMs: performance.now() - submitted,
|
|
steps: result.steps,
|
|
reusedSteps: result.reused_steps,
|
|
reusedSuffixSteps: result.reused_suffix_steps,
|
|
discardedSuffixAttemptSteps: result.discarded_suffix_attempt_steps,
|
|
executedSteps: result.executed_steps,
|
|
reusedFrontier: result.reused_frontier,
|
|
replayedCalls: result.replayed_calls,
|
|
pendingPublication: result.pending_publication === true,
|
|
};
|
|
window.dispatchEvent(new CustomEvent("texrra-preview-painted", { detail: sample }));
|
|
if (result.pending_publication) {
|
|
const committed = await publicationStatus(edit, update.revision);
|
|
if (edit !== sequence || !committed) return;
|
|
acceptPublication(update.revision, draft.previous);
|
|
window.dispatchEvent(new CustomEvent("texrra-preview-published", {
|
|
detail: {
|
|
sequence: edit,
|
|
revision: update.revision,
|
|
compileMs: committed.compile_ms,
|
|
publicationMs: committed.publication_ms,
|
|
},
|
|
}));
|
|
}
|
|
status.textContent = `${sample.count} 页 · ${Math.round(sample.visibleMs)} 毫秒`;
|
|
} catch (failure) {
|
|
revokeDetached(replacements);
|
|
if (edit === sequence) {
|
|
restorePublishedPages();
|
|
showError(failure.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
function invalidatePreview() {
|
|
++sequence;
|
|
clearTimeout(compileTimer);
|
|
compileTimer = undefined;
|
|
promptCompilePending = false;
|
|
restorePublishedPages();
|
|
}
|
|
|
|
function queueCompile(immediate = false) {
|
|
const submitted = performance.now();
|
|
// Edits arriving before the first dispatch share its prompt submission.
|
|
const prompt = immediate || promptCompilePending || submitted - lastTypingAt >= EDIT_IDLE_MS;
|
|
invalidatePreview();
|
|
if (!immediate) lastTypingAt = submitted;
|
|
promptCompilePending = prompt;
|
|
const edit = sequence;
|
|
if (status.textContent !== "正在编译") status.textContent = "正在编译";
|
|
compileTimer = setTimeout(() => {
|
|
if (edit !== sequence || composing) return;
|
|
compileTimer = undefined;
|
|
promptCompilePending = false;
|
|
compile(edit, submitted, Object.fromEntries(edits));
|
|
}, prompt ? 0 : EDIT_IDLE_MS);
|
|
}
|
|
|
|
function recordEdit(forceCompile = false) {
|
|
const changed = source.value !== (edits.get(activeFile) ?? files.get(activeFile));
|
|
if (changed) edits.set(activeFile, source.value);
|
|
if (changed || forceCompile) queueCompile(forceCompile);
|
|
}
|
|
|
|
function replaceSourceRange(text, start, end, selectionStart, selectionEnd, direction) {
|
|
source.focus({ preventScroll: true });
|
|
source.setSelectionRange(start, end);
|
|
const before = source.value;
|
|
try {
|
|
// Use the browser's editing command when available so insertion is undoable.
|
|
document.execCommand("insertText", false, text);
|
|
} catch {
|
|
// The range API also works when the editing command is unavailable.
|
|
}
|
|
if (source.value === before) source.setRangeText(text, start, end, "end");
|
|
source.setSelectionRange(selectionStart, selectionEnd, direction);
|
|
recordEdit();
|
|
}
|
|
|
|
function indentSource() {
|
|
const start = source.selectionStart;
|
|
const end = source.selectionEnd;
|
|
if (start === end) {
|
|
replaceSourceRange(" ", start, end, start + 2, start + 2, "none");
|
|
return;
|
|
}
|
|
const firstLine = start === 0 ? 0 : source.value.lastIndexOf("\n", start - 1) + 1;
|
|
const selection = source.value.slice(firstLine, end);
|
|
const indented = selection.split("\n").map((line, index, lines) =>
|
|
index === lines.length - 1 && line === "" ? line : " " + line
|
|
).join("\n");
|
|
replaceSourceRange(indented, firstLine, end, start + 2,
|
|
end + indented.length - selection.length, source.selectionDirection);
|
|
}
|
|
|
|
function addFormulaButtons() {
|
|
const heading = document.querySelector(".editor-panel .panel-head, .edit .file");
|
|
if (!heading) return;
|
|
const group = document.createElement("span");
|
|
group.setAttribute("role", "group");
|
|
group.setAttribute("aria-label", "插入公式");
|
|
group.style.display = "inline-flex";
|
|
group.style.gap = ".35rem";
|
|
group.style.marginInlineStart = ".5rem";
|
|
group.style.whiteSpace = "nowrap";
|
|
for (const [label, open, close] of [
|
|
["行内公式", "$", "$"],
|
|
["独立公式", "\\[\n", "\n\\]"],
|
|
]) {
|
|
const button = document.createElement("button");
|
|
button.type = "button";
|
|
button.className = "btn small";
|
|
button.textContent = label;
|
|
button.addEventListener("click", () => {
|
|
if (composing || source.disabled || source.readOnly) return;
|
|
const start = source.selectionStart;
|
|
const end = source.selectionEnd;
|
|
const selection = source.value.slice(start, end);
|
|
replaceSourceRange(open + selection + close, start, end,
|
|
start + open.length, end + open.length, source.selectionDirection);
|
|
});
|
|
group.append(button);
|
|
}
|
|
heading.append(group);
|
|
}
|
|
|
|
async function saveSources() {
|
|
save.disabled = true;
|
|
saved.hidden = false;
|
|
saved.textContent = "正在保存源文件";
|
|
try {
|
|
const response = await fetch(projectPrefix + "/save", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ sequence, files: Object.fromEntries(edits) }),
|
|
});
|
|
const result = await response.json();
|
|
if (!response.ok) throw new Error(result.error);
|
|
saved.textContent = "已保存源文件至 " + result.directory;
|
|
} catch (failure) {
|
|
saved.textContent = "保存失败:" + failure.message;
|
|
} finally {
|
|
save.disabled = false;
|
|
}
|
|
}
|
|
|
|
async function openProject() {
|
|
try {
|
|
const response = await fetch(projectPrefix + "/project");
|
|
if (!response.ok) throw new Error("无法打开源文件");
|
|
const project = await response.json();
|
|
files = new Map(Object.entries(project.files));
|
|
if (fileTree) {
|
|
document.querySelector("#project-title").textContent = project.name;
|
|
for (const filename of files.keys()) {
|
|
const row = document.createElement("button");
|
|
row.type = "button";
|
|
row.className = "btn tree-row file-row";
|
|
row.style.width = "100%";
|
|
row.dataset.path = filename;
|
|
row.textContent = filename;
|
|
row.title = filename;
|
|
row.addEventListener("click", () => selectFile(filename));
|
|
fileTree.append(row);
|
|
}
|
|
}
|
|
selectFile(project.name);
|
|
source.disabled = false;
|
|
source.setAttribute("autocapitalize", "off");
|
|
source.setAttribute("autocorrect", "off");
|
|
source.setAttribute("autocomplete", "off");
|
|
addFormulaButtons();
|
|
sequence = project.sequence;
|
|
advertisePreviewSocket(project.preview_socket);
|
|
save.disabled = false;
|
|
save.addEventListener("click", saveSources);
|
|
document.addEventListener("keydown", (event) => {
|
|
if (composing || event.isComposing) return;
|
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
|
|
event.preventDefault();
|
|
if (!save.disabled) saveSources();
|
|
}
|
|
});
|
|
if (selector && files.size > 1) {
|
|
for (const filename of files.keys()) selector.add(new Option(filename, filename));
|
|
selector.value = activeFile;
|
|
selector.hidden = false;
|
|
name.hidden = true;
|
|
selector.addEventListener("change", () => selectFile(selector.value));
|
|
}
|
|
source.addEventListener("compositionstart", () => {
|
|
composing = true;
|
|
invalidatePreview();
|
|
});
|
|
source.addEventListener("compositionend", () => {
|
|
if (!composing) return;
|
|
composing = false;
|
|
recordEdit(true);
|
|
});
|
|
source.addEventListener("input", (event) => {
|
|
if (composing) return;
|
|
if (event.isComposing) {
|
|
invalidatePreview();
|
|
return;
|
|
}
|
|
recordEdit();
|
|
});
|
|
source.addEventListener("keydown", (event) => {
|
|
if (event.key !== "Tab" || composing || event.isComposing
|
|
|| event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return;
|
|
event.preventDefault();
|
|
indentSource();
|
|
});
|
|
queueCompile(true);
|
|
} catch (failure) {
|
|
showError(failure.message);
|
|
}
|
|
}
|
|
|
|
openProject();
|