From e0d9b3a91fd6dbe50580771a1ba9758fcb289a25 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Wed, 2 Dec 2026 11:30:04 +0800 Subject: [PATCH] Add workbench recompile, LaTeX assistance, and selectable preview --- desktop/README.md | 5 + desktop/src-tauri/Cargo.lock | 2 +- desktop/src-tauri/Cargo.toml | 2 +- desktop/src-tauri/tauri.conf.json | 2 +- examples/native_editor/app.js | 87 ++++++- examples/native_editor/code_editor.css | 83 +++++++ examples/native_editor/code_editor.js | 315 ++++++++++++++++++++++++ examples/native_editor/index.html | 2 + examples/native_editor/main.rs | 54 +++- examples/native_editor/preview_view.css | 105 ++++++++ examples/native_editor/preview_view.js | 152 ++++++++++++ examples/native_editor/text_layer.rs | 278 +++++++++++++++++++++ 12 files changed, 1059 insertions(+), 28 deletions(-) create mode 100644 examples/native_editor/code_editor.css create mode 100644 examples/native_editor/code_editor.js create mode 100644 examples/native_editor/preview_view.css create mode 100644 examples/native_editor/preview_view.js create mode 100644 examples/native_editor/text_layer.rs diff --git a/desktop/README.md b/desktop/README.md index dd6967d..d3a07a9 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -20,6 +20,11 @@ Fedora Ghostscript 及 bubblewrap,随后由原生引擎读取生成的 PDF。 WSL 中需要已有的 TeX Live bibtex 和 kpsewhich。模板中新增的引文及 更换引用样式命令在重新打开保存的源项目时读取。 +0.1.3 的预览工具栏可重新编译、缩放或恢复适合宽度。重新编译 +使用当前项目主文件,带上编辑区里的未保存修改,包括通过 input 或 +include 纳入的子文件。编辑区按 LaTeX 语法着色,并提示常用命令、 +环境和项目文件。已发布的横排正文支持选取和复制。 + ## 构建 在引擎仓库根目录使用已经完成定向回归的原生 release 构建回执,准备 diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 063ed3a..3e04ade 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -3237,7 +3237,7 @@ dependencies = [ [[package]] name = "texrra-desktop" -version = "0.1.2" +version = "0.1.3" dependencies = [ "serde_json", "tauri", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 4e03846..1978698 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "texrra-desktop" -version = "0.1.2" +version = "0.1.3" edition = "2024" rust-version = "1.92" license = "MIT OR Apache-2.0" diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 4251b00..1eb5177 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Texrra", - "version": "0.1.2", + "version": "0.1.3", "identifier": "org.texrra.desktop", "build": { "frontendDist": "../startup" diff --git a/examples/native_editor/app.js b/examples/native_editor/app.js index 46d73a0..03c7f3b 100644 --- a/examples/native_editor/app.js +++ b/examples/native_editor/app.js @@ -1,3 +1,6 @@ +import { attachCodeEditor } from '/code_editor.js'; +import { attachPreviewView } from '/preview_view.js'; + const workspace = document.querySelector("#workspace"); if (workspace) attachWebControls(); @@ -15,8 +18,10 @@ const fileTree = document.querySelector("#file-tree"); const edits = new Map(); const fileViews = new Map(); const EDIT_IDLE_MS = 70; +const TEXT_LAYER_IDLE_MS = 180; const PREVIEW_SOCKET_RETRY_MS = 1000; let files; +let projectFiles = []; let activeFile; let sequence = 0; let publishedRevision = null; @@ -29,9 +34,24 @@ let previewSocketUrl; let previewSocket; let previewSocketRetryAt = 0; let pendingSocketPreview; +let textLayerTimer; +let textLayerRequest; +let textLayerRevision; const projectPrefix = location.pathname.startsWith("/p/") ? location.pathname.slice(0, -1) : ""; const previewDraft = new URLSearchParams(location.hash.slice(1)).get("preview") !== "published"; +const codeEditor = attachCodeEditor(source, { getFileNames: () => projectFiles }); +const previewView = attachPreviewView(pages); +const recompile = document.createElement("button"); +recompile.type = "button"; +recompile.id = "recompile"; +recompile.className = "btn small"; +recompile.textContent = "重新编译"; +recompile.setAttribute("aria-keyshortcuts", "Control+Enter Meta+Enter"); +recompile.disabled = true; +previewView.toolbar.prepend(recompile); +recompile.addEventListener("click", manualCompile); + function attachWebControls() { const button = document.createElement("button"); button.type = "button"; @@ -87,6 +107,7 @@ function selectFile(filename) { source.setSelectionRange(view?.start ?? 0, view?.end ?? 0, view?.direction ?? "none"); source.scrollTop = view?.top ?? 0; source.scrollLeft = view?.left ?? 0; + codeEditor.sync(); if (fileTree) { for (const row of fileTree.children) { const selected = row.dataset.path === activeFile; @@ -102,7 +123,7 @@ function showError(message) { errorPanel.hidden = false; } -function pageImage(page) { +function pageFrame(page) { const img = new Image(); img.alt = `第 ${page.index + 1} 页`; img.dataset.index = page.index; @@ -111,12 +132,12 @@ function pageImage(page) { img.style.aspectRatio = "auto"; } img.src = URL.createObjectURL(new Blob([page.svg], { type: "image/svg+xml" })); - return img; + return previewView.wrap(img, page); } -function revokeDetached(images) { - for (const image of images) { - if (!image.isConnected) URL.revokeObjectURL(image.src); +function revokeDetached(frames) { + for (const frame of frames) { + if (!frame.isConnected) URL.revokeObjectURL(frame.querySelector("img").src); } } @@ -125,10 +146,10 @@ function applyPages(update, replacements) { 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); + for (const frame of replacements) { + const old = pages.children[Number(frame.dataset.index)]; + if (old) old.replaceWith(frame); + else pages.append(frame); } while (pages.children.length > update.page_count) pages.lastElementChild.remove(); } @@ -145,6 +166,32 @@ function restorePublishedPages() { else document.body.dataset.visibleRevision = publishedRevision; pdf.hidden = publishedRevision === null; draft = null; + if (publishedRevision !== null && textLayerRevision !== publishedRevision) { + requestPreviewText(publishedRevision); + } +} + +function requestPreviewText(revision) { + clearTimeout(textLayerTimer); + textLayerRequest?.abort(); + const request = new AbortController(); + textLayerRequest = request; + // Text extraction runs after the SVG is published and quiet, so it stays + // off the visible editing path. Discard data if another revision appears. + textLayerTimer = setTimeout(async () => { + try { + const response = await fetch(projectPrefix + "/text-layer?revision=" + revision, + { signal: request.signal }); + if (!response.ok) return; + const result = await response.json(); + if (!request.signal.aborted && !draft && publishedRevision === revision && result.revision === revision) { + previewView.setTextPages(result.pages); + textLayerRevision = revision; + } + } catch { + // The visual preview can still be used when its optional text layer is unavailable. + } + }, TEXT_LAYER_IDLE_MS); } function acceptPublication(revision, previous) { @@ -153,6 +200,7 @@ function acceptPublication(revision, previous) { pdf.href = projectPrefix + `/pdf?revision=${revision}`; pdf.hidden = false; draft = null; + requestPreviewText(revision); } async function publicationStatus(edit, revision) { @@ -271,8 +319,8 @@ async function compile(edit, submitted, changes) { 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())); + for (const page of update.pages) replacements.push(pageFrame(page)); + await Promise.all(replacements.map((frame) => frame.querySelector("img").decode())); if (edit !== sequence) { revokeDetached(replacements); return; @@ -359,6 +407,11 @@ function queueCompile(immediate = false) { }, prompt ? 0 : EDIT_IDLE_MS); } +function manualCompile() { + if (recompile.disabled || composing) return; + recordEdit(true); +} + function recordEdit(forceCompile = false) { const changed = source.value !== (edits.get(activeFile) ?? files.get(activeFile)); if (changed) edits.set(activeFile, source.value); @@ -377,6 +430,7 @@ function replaceSourceRange(text, start, end, selectionStart, selectionEnd, dire } if (source.value === before) source.setRangeText(text, start, end, "end"); source.setSelectionRange(selectionStart, selectionEnd, direction); + codeEditor.sync(); recordEdit(); } @@ -453,6 +507,7 @@ async function openProject() { if (!response.ok) throw new Error("无法打开源文件"); const project = await response.json(); files = new Map(Object.entries(project.files)); + projectFiles = project.project_files ?? [...files.keys()]; if (fileTree) { document.querySelector("#project-title").textContent = project.name; for (const filename of files.keys()) { @@ -476,9 +531,15 @@ async function openProject() { sequence = project.sequence; advertisePreviewSocket(project.preview_socket); save.disabled = false; + recompile.disabled = false; + recompile.title = "重新编译主文件 " + project.name + "(Ctrl/Cmd+Enter)"; save.addEventListener("click", saveSources); document.addEventListener("keydown", (event) => { - if (composing || event.isComposing) return; + if (event.defaultPrevented || composing || event.isComposing) return; + if ((event.ctrlKey || event.metaKey) && event.key === "Enter") { + event.preventDefault(); + if (!event.repeat) manualCompile(); + } if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") { event.preventDefault(); if (!save.disabled) saveSources(); @@ -509,7 +570,7 @@ async function openProject() { recordEdit(); }); source.addEventListener("keydown", (event) => { - if (event.key !== "Tab" || composing || event.isComposing + if (event.defaultPrevented || event.key !== "Tab" || composing || event.isComposing || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return; event.preventDefault(); indentSource(); diff --git a/examples/native_editor/code_editor.css b/examples/native_editor/code_editor.css new file mode 100644 index 0000000..85adbf1 --- /dev/null +++ b/examples/native_editor/code_editor.css @@ -0,0 +1,83 @@ +.latex-editor { + position: relative; + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + min-height: 0; +} +.latex-editor > textarea { + position: relative; + flex: 1; + min-height: 0; +} +.latex-editor-mirror { + position: absolute; + box-sizing: border-box; + overflow: hidden; + overflow-wrap: break-word; + white-space: pre-wrap; + visibility: hidden; + pointer-events: none; + color: var(--latex-editor-color, #1f2329); +} +.latex-editor.latex-highlighted:not(.latex-composing) > .latex-editor-mirror { + visibility: visible; +} +.latex-editor.latex-highlighted:not(.latex-composing) > textarea { + color: transparent !important; + background-color: transparent !important; + caret-color: var(--latex-editor-color, #1f2329); +} +.latex-editor > textarea::selection { + color: var(--latex-editor-color, #1f2329); + background: #c9dbfb; +} +.latex-command { color: #3454a3; } +.latex-comment { color: #50704e; } +.latex-math { color: #96375d; } +.latex-delimiter { color: #704694; } + +.latex-completions { + position: fixed; + z-index: 52; + box-sizing: border-box; + min-width: 11rem; + max-width: calc(100vw - 16px); + padding: 4px; + overflow: hidden; + border: 1px solid #d7dee8; + border-radius: 8px; + background: #fff; + color: #1f2329; + box-shadow: 0 5px 20px #17203324; + font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; +} +.latex-completions > [role="option"] { + padding: 4px 8px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + border-radius: 4px; + cursor: pointer; +} +.latex-completions > [aria-selected="true"], +.latex-completions > [role="option"]:hover { + color: #203c81; + background: #e8eefc; +} +@media (forced-colors: active) { + .latex-editor.latex-highlighted:not(.latex-composing) > .latex-editor-mirror { + visibility: hidden; + } + .latex-editor.latex-highlighted:not(.latex-composing) > textarea { + color: CanvasText !important; + background-color: Canvas !important; + caret-color: CanvasText; + } + .latex-completions > [aria-selected="true"] { + forced-color-adjust: none; + color: HighlightText; + background: Highlight; + } +} diff --git a/examples/native_editor/code_editor.js b/examples/native_editor/code_editor.js new file mode 100644 index 0000000..cf2ff60 --- /dev/null +++ b/examples/native_editor/code_editor.js @@ -0,0 +1,315 @@ +const COMMANDS = [ + "begin", "end", "documentclass", "usepackage", "section", "subsection", "subsubsection", + "paragraph", "label", "ref", "eqref", "pageref", "cite", "citep", "citet", "nocite", + "textbf", "textit", "texttt", "emph", "textcolor", "footnote", "item", "centering", + "caption", "includegraphics", "input", "include", "bibliography", "bibliographystyle", + "addbibresource", "printbibliography", "maketitle", "tableofcontents", "newcommand", + "renewcommand", "newenvironment", "setlength", "hspace", "vspace", "newline", "noindent", + "frac", "dfrac", "sqrt", "sum", "prod", "int", "lim", "left", "right", "mathrm", "mathbf", + "mathcal", "mathbb", "operatorname", "overline", "underbrace", "partial", "infty", "times", + "alpha", "beta", "gamma", "delta", "epsilon", "theta", "lambda", "mu", "pi", "sigma", + "phi", "omega", "neq", "leq", "geq", "rightarrow", "cdot", "toprule", "midrule", + "bottomrule", "multicolumn", "cline", "hline", "verb", "url", "href", +]; +const ENVIRONMENTS = [ + "document", "abstract", "equation", "equation*", "align", "align*", "aligned", "gather", + "gather*", "multline", "cases", "matrix", "pmatrix", "bmatrix", "figure", "figure*", + "table", "table*", "tabular", "tabularx", "sidewaystable", "itemize", "enumerate", + "description", "center", "minipage", "quote", "verbatim", "lstlisting", "proof", "theorem", +]; +const FILE_TYPES = { + input: /\.tex$/i, + include: /\.tex$/i, + includegraphics: /\.(?:pdf|eps|png|jpe?g)$/i, + bibliography: /\.bib$/i, + addbibresource: /\.bib$/i, +}; +const TOKEN = /\\verb\*?([^\w\s])(?:(?!\1)[^\n])*\1|%[^\n]*|\\(?:[A-Za-z@]+|[^\n]|(?=\n|$))|\$\$?|[{}[\]&_^]/g; +const TEXT_STYLE = [ + "font-family", "font-size", "font-style", "font-weight", "font-variant", "font-stretch", + "line-height", "letter-spacing", "word-spacing", "text-indent", "text-align", "direction", + "font-kerning", "font-feature-settings", "font-variation-settings", "tab-size", + "padding-top", "padding-right", "padding-bottom", "padding-left", +]; +let nextPopup = 0; + +function tokenStyle(token) { + if (token.startsWith("%")) return "latex-comment"; + if (token.startsWith("\\")) return "latex-command"; + return /^[$_^&]/.test(token) ? "latex-math" : "latex-delimiter"; +} + +function completion(textarea, fileNames) { + const { selectionStart: caret, selectionEnd, value } = textarea; + if (caret !== selectionEnd) return null; + const startOfLine = caret ? value.lastIndexOf("\n", caret - 1) + 1 : 0; + const before = value.slice(startOfLine, caret); + const tokens = Array.from(before.matchAll(TOKEN)); + if (tokens.some(([token]) => token.startsWith("%"))) return null; + const after = value.slice(caret); + const group = before.match(/\\([A-Za-z]+)(?:\[[^\[\]\n]*\])?\{([^{}\n]*)$/); + let prefix, candidates, suffix, following; + const commandGroup = group && tokens.some((token) => token.index === group.index); + if (commandGroup && (group[1] === "begin" || group[1] === "end")) { + prefix = group[2]; + candidates = ENVIRONMENTS; + suffix = after.match(/^[A-Za-z*]*/)[0]; + following = after[suffix.length] === "}" ? "" : "}"; + } else if (commandGroup && Object.hasOwn(FILE_TYPES, group[1])) { + const command = group[1]; + prefix = group[2].split(",").at(-1).trimStart(); + candidates = [...new Set(Array.from(fileNames(), (name) => String(name)) + .filter((name) => FILE_TYPES[command].test(name)) + .map((name) => ["include", "input", "bibliography"].includes(command) + ? name.replace(/\.(?:tex|bib)$/i, "") : name))].sort(); + suffix = after.match(/^[^,{}\n]*/)[0]; + following = ""; + } else { + const command = before.match(/\\([A-Za-z@]*)$/); + if (!command || tokens.at(-1)?.index !== command.index) return null; + prefix = command[1]; + candidates = COMMANDS; + suffix = after.match(/^[A-Za-z@]*/)[0]; + following = ""; + } + const items = candidates.filter((item) => + item.startsWith(prefix) && (item !== prefix + suffix || following)).slice(0, 8); + return items.length ? { start: caret - prefix.length, end: caret + suffix.length, following, items } : null; +} + +export function attachCodeEditor(textarea, { getFileNames = () => [] } = {}) { + const frame = document.createElement("div"); + frame.className = "latex-editor"; + const style = getComputedStyle(textarea); + frame.style.setProperty("--latex-editor-color", style.color); + frame.style.backgroundColor = style.backgroundColor; + const mirror = document.createElement("div"); + mirror.className = "latex-editor-mirror"; + mirror.setAttribute("aria-hidden", "true"); + for (const name of TEXT_STYLE) { + mirror.style.setProperty(name, style.getPropertyValue(name)); + } + textarea.before(frame); + frame.append(mirror, textarea); + + const menu = document.createElement("div"); + menu.className = "latex-completions"; + menu.id = "latex-completions-" + ++nextPopup; + menu.hidden = true; + menu.setAttribute("role", "listbox"); + menu.setAttribute("aria-label", "LaTeX 补全"); + document.body.append(menu); + textarea.setAttribute("aria-autocomplete", "list"); + textarea.setAttribute("aria-controls", menu.id); + + let rendered; + let positions = []; + let animation; + let composing = false; + let inserting = false; + let showSuggestions = false; + let suggestions; + let selected = 0; + + function dismiss() { + showSuggestions = false; + suggestions = undefined; + menu.hidden = true; + textarea.removeAttribute("aria-activedescendant"); + } + + function paint() { + const value = textarea.value; + if (rendered !== value) { + rendered = value; + positions = []; + const contents = document.createDocumentFragment(); + const append = (text, start, className) => { + if (!text) return; + const node = document.createTextNode(text); + positions.push({ start, node }); + if (className) { + const span = document.createElement("span"); + span.className = className; + span.append(node); + contents.append(span); + } else { + contents.append(node); + } + }; + let offset = 0; + for (const match of value.matchAll(TOKEN)) { + append(value.slice(offset, match.index), offset); + append(match[0], match.index, tokenStyle(match[0])); + offset = match.index + match[0].length; + } + append(value.slice(offset) + "\u200b", offset); + mirror.replaceChildren(contents); + } + mirror.style.insetInlineStart = textarea.clientLeft + "px"; + mirror.style.top = textarea.clientTop + "px"; + mirror.style.width = textarea.clientWidth + "px"; + mirror.style.height = textarea.clientHeight + "px"; + mirror.style.whiteSpace = textarea.wrap === "off" ? "pre" : "pre-wrap"; + mirror.scrollTop = textarea.scrollTop; + mirror.scrollLeft = textarea.scrollLeft; + } + + function caretPosition() { + const caret = textarea.selectionStart; + let index = positions.length - 1; + while (index && positions[index].start > caret) index--; + const { start, node } = positions[index]; + const range = document.createRange(); + range.setStart(node, caret - start); + range.collapse(true); + return range.getBoundingClientRect(); + } + + function placeMenu() { + const caret = caretPosition(); + const field = textarea.getBoundingClientRect(); + if (caret.left < field.left || caret.left > field.right || + caret.bottom < field.top || caret.top > field.bottom) { + dismiss(); + return; + } + const { innerWidth: width, innerHeight: height } = window; + const x = Math.min(caret.left, width - menu.offsetWidth - 8); + const below = caret.bottom + 6; + const y = below + menu.offsetHeight <= height - 8 ? below : caret.top - menu.offsetHeight - 6; + menu.style.left = Math.max(8, x) + "px"; + menu.style.top = Math.max(8, y) + "px"; + } + + function updateSelection(index) { + selected = (index + menu.children.length) % menu.children.length; + for (const [i, option] of Array.from(menu.children).entries()) { + option.setAttribute("aria-selected", String(i === selected)); + } + textarea.setAttribute("aria-activedescendant", menu.children[selected].id); + } + + function render() { + animation = undefined; + paint(); + if (!showSuggestions || composing || textarea.readOnly || textarea.disabled || + document.activeElement !== textarea) return; + const next = completion(textarea, getFileNames); + if (!next) { + dismiss(); + return; + } + const previous = suggestions?.items[selected]; + suggestions = next; + const options = next.items.map((value, index) => { + const option = document.createElement("div"); + option.id = menu.id + "-" + index; + option.dataset.index = index; + option.setAttribute("role", "option"); + option.textContent = value; + return option; + }); + menu.replaceChildren(...options); + menu.hidden = false; + updateSelection(Math.max(0, next.items.indexOf(previous))); + placeMenu(); + } + + function schedule() { + animation ??= requestAnimationFrame(render); + } + + function accept(index) { + if (!suggestions || composing) return; + const current = completion(textarea, getFileNames); + const choice = suggestions.items[index]; + if (!current?.items.includes(choice)) { + dismiss(); + return; + } + const { start, end, following } = current; + const previous = textarea.value; + const text = choice + following; + const top = textarea.scrollTop; + const left = textarea.scrollLeft; + dismiss(); + textarea.setSelectionRange(start, end); + inserting = true; + try { + // The user-initiated browser edit joins the textarea's native undo history. + try { document.execCommand("insertText", false, text); } catch { /* use the range API below */ } + if (textarea.value === previous) { + textarea.setRangeText(text, start, end, "end"); + textarea.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: text })); + } + } finally { + inserting = false; + } + textarea.scrollTop = top; + textarea.scrollLeft = left; + schedule(); + } + + textarea.addEventListener("compositionstart", () => { + composing = true; + frame.classList.add("latex-composing"); + dismiss(); + }); + textarea.addEventListener("compositionend", () => { + composing = false; + frame.classList.remove("latex-composing"); + schedule(); + }); + textarea.addEventListener("input", (event) => { + if (composing || event.isComposing) return; + showSuggestions = !inserting && event.inputType?.startsWith("insert"); + if (!showSuggestions) dismiss(); + schedule(); + }); + textarea.addEventListener("scroll", schedule, { passive: true }); + textarea.addEventListener("blur", dismiss); + textarea.addEventListener("pointerdown", dismiss); + textarea.addEventListener("keydown", (event) => { + if (event.isComposing || composing || event.keyCode === 229) return; + const manual = event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.code === "Space"; + const unmodified = !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey; + if (manual) { + showSuggestions = true; + schedule(); + } else if (!menu.hidden && unmodified) { + switch (event.key) { + case "ArrowDown": updateSelection(selected + 1); break; + case "ArrowUp": updateSelection(selected - 1); break; + case "Enter": + case "Tab": accept(selected); break; + case "Escape": dismiss(); break; + case "ArrowLeft": + case "ArrowRight": + case "Home": + case "End": + dismiss(); + return; + default: return; + } + } else { + return; + } + event.preventDefault(); + event.stopImmediatePropagation(); + }, true); + menu.addEventListener("pointerdown", (event) => event.preventDefault()); + menu.addEventListener("click", (event) => { + const option = event.target.closest("[data-index]"); + if (option) accept(Number(option.dataset.index)); + }); + new ResizeObserver(schedule).observe(textarea); + frame.classList.add("latex-highlighted"); + schedule(); + return { + sync() { + dismiss(); + schedule(); + }, + }; +} diff --git a/examples/native_editor/index.html b/examples/native_editor/index.html index 91755be..0fd72f2 100644 --- a/examples/native_editor/index.html +++ b/examples/native_editor/index.html @@ -37,6 +37,8 @@ header { flex-wrap: wrap; gap: .3rem 1rem; } } + +
Texrra 原生预览 正在打开文档 diff --git a/examples/native_editor/main.rs b/examples/native_editor/main.rs index 6aa59b2..c46e999 100644 --- a/examples/native_editor/main.rs +++ b/examples/native_editor/main.rs @@ -34,6 +34,7 @@ mod preview_socket; mod projects; mod resource_capture; mod saved_project; +mod text_layer; mod thread_usage; const MAX_EDIT_BODY: u64 = 2 * 1024 * 1024; @@ -348,21 +349,26 @@ fn main() -> Result<(), Box> { for request in server.incoming_requests() { let url = request.url().to_owned(); let path = url.as_str(); - if let (&Method::Get, Some(assets)) = (request.method(), &web) { - if let Some((kind, bytes)) = assets.file(path) { + if request.method() == &Method::Get { + const JS: &str = "text/javascript; charset=utf-8"; + const CSS: &str = "text/css; charset=utf-8"; + let editor_asset = match path { + "/app.js" => Some((JS, SCRIPT)), + "/code_editor.js" => Some((JS, include_str!("code_editor.js"))), + "/code_editor.css" => Some((CSS, include_str!("code_editor.css"))), + "/preview_view.js" => Some((JS, include_str!("preview_view.js"))), + "/preview_view.css" => Some((CSS, include_str!("preview_view.css"))), + _ => None, + }; + if let Some((kind, body)) = editor_asset { + respond(request, 200, kind, body.into()); + continue; + } + if let Some((kind, bytes)) = web.as_ref().and_then(|assets| assets.file(path)) { respond(request, 200, kind, bytes); continue; } } - if path == "/app.js" && request.method() == &Method::Get { - respond( - request, - 200, - "text/javascript; charset=utf-8", - SCRIPT.into(), - ); - continue; - } let mut session_path = path; if let Some(library) = &library { if path == "/" && request.method() == &Method::Get { @@ -492,6 +498,9 @@ fn main() -> Result<(), Box> { "name": entry.strip_prefix(run.as_path()).unwrap().to_string_lossy(), "source": std::str::from_utf8(&file.data)?, "files": files, + "project_files": declared.iter() + .filter_map(|path| path.strip_prefix(run.as_path()).ok()?.to_str()) + .collect::>(), "sequence": queue.current.load(Ordering::Acquire), "preview_socket": id.as_deref().map_or_else( || "/preview-socket".to_owned(), |id| format!("/p/{id}/preview-socket"), @@ -584,6 +593,20 @@ fn main() -> Result<(), Box> { ), } } + (&Method::Get, path) if path.starts_with("/text-layer?revision=") => { + let revision = path["/text-layer?revision=".len()..].parse::().ok(); + if let Some(document) = compiler.latest().filter(|doc| Some(doc.revision()) == revision) { + std::thread::spawn(move || { + reply(request, 200, json!(text_layer::for_document(&document))); + }); + } else { + reply( + request, + 409, + json!({ "error": "This preview revision is no longer current" }), + ); + } + } (&Method::Get, path) if path.starts_with("/source-map?revision=") => { let revision = path["/source-map?revision=".len()..].parse::().ok(); match compiler @@ -615,6 +638,14 @@ impl WebAssets { fn load(path: &Path) -> std::io::Result { let index = fs::read_to_string(path.join("index.html"))?; let dashboard = index.replace("src=\"/app.js\"", "src=\"/library.js\""); + let index = index.replace("src=\"/app.js\"", "type=\"module\" src=\"/app.js\"") + .replace( + "", + concat!( + "", + "", + ), + ); Ok(Self { dashboard: dashboard.into_bytes(), index: index.into_bytes(), @@ -628,7 +659,6 @@ impl WebAssets { "/styles.css" => Some(("text/css; charset=utf-8", self.styles.clone())), "/favicon.svg" => Some(("image/svg+xml", self.favicon.clone())), "/fonts.css" => Some(("text/css; charset=utf-8", Vec::new())), - "/app.js" => Some(("text/javascript; charset=utf-8", SCRIPT.into())), _ => None, } } diff --git a/examples/native_editor/preview_view.css b/examples/native_editor/preview_view.css new file mode 100644 index 0000000..bdb14e3 --- /dev/null +++ b/examples/native_editor/preview_view.css @@ -0,0 +1,105 @@ +.texrra-preview-controls { + display: flex; + flex: none; + flex-wrap: wrap; + justify-content: flex-end; + align-items: center; + gap: .35rem; + padding: .3rem .65rem; + background: #fff; + border-bottom: 1px solid #d9e0e6; + font: 13px/1.3 system-ui, sans-serif; +} + +.texrra-preview-sticky { + position: sticky; + top: 0; + left: 0; + z-index: 1; + margin-bottom: .65rem; +} + +.texrra-preview-controls button { + min-width: 1.9rem; + min-height: 1.9rem; + padding: .15rem .45rem; + border: 1px solid #cbd5df; + border-radius: .3rem; + background: #fff; + color: #17222d; + font: inherit; + cursor: pointer; +} + +.texrra-preview-controls button:hover:not(:disabled), +.texrra-preview-controls button[aria-pressed="true"] { + background: #eaf1f7; +} + +.texrra-preview-controls button:focus-visible { + outline: 2px solid #1972a4; + outline-offset: 2px; +} + +.texrra-preview-controls button:disabled { + opacity: .48; + cursor: default; +} + +.texrra-preview-controls output { + min-width: 3rem; + text-align: center; + font-variant-numeric: tabular-nums; +} + +#pages.texrra-preview-pages { + --texrra-fit-width: 820px; + width: max(100%, var(--texrra-zoom-width, 0px)); + grid-template-columns: minmax(0, var(--texrra-zoom-width, var(--texrra-fit-width))); +} + +#pages.texrra-preview-web { + --texrra-fit-width: var(--page-width, 210mm); +} + +.texrra-preview-page { + position: relative; + min-width: 0; +} + +.texrra-preview-web > .texrra-preview-page { + width: min(100%, var(--texrra-zoom-width, var(--texrra-fit-width))); +} + +#pages .texrra-preview-page > img { + display: block; + width: 100%; + user-select: none; +} + +.texrra-preview-has-text { + container-type: inline-size; +} + +.texrra-preview-text { + position: absolute; + inset: 0; + color: transparent; + forced-color-adjust: none; + pointer-events: none; + font: 1px/1 Arial, sans-serif; + user-select: text; +} + +.texrra-preview-text > span { + position: absolute; + display: block; + white-space: pre; + transform-origin: left top; + pointer-events: auto; +} + +.texrra-preview-text ::selection { + color: transparent; + background: #2978df59; +} diff --git a/examples/native_editor/preview_view.js b/examples/native_editor/preview_view.js new file mode 100644 index 0000000..7aa3d02 --- /dev/null +++ b/examples/native_editor/preview_view.js @@ -0,0 +1,152 @@ +const minimumZoom = 50; +const maximumZoom = 250; +const zoomStep = 25; + +function button(label, title) { + const node = document.createElement("button"); + node.type = "button"; + node.title = title; + node.setAttribute("aria-label", title); + node.textContent = label; + return node; +} + +function sameTextPage(previous, next) { + return previous?.width === next.width + && previous.height === next.height + && previous.lines.length === next.lines.length + && previous.lines.every((line, index) => { + const other = next.lines[index]; + return line.text === other.text && line.x === other.x && line.y === other.y + && line.width === other.width && line.height === other.height; + }); +} + +function centerOfPage(scroller, pages) { + const bounds = scroller.getBoundingClientRect(); + const x = bounds.left + scroller.clientLeft + scroller.clientWidth / 2; + const y = bounds.top + scroller.clientTop + scroller.clientHeight / 2; + for (const page of pages.children) { + const rect = page.getBoundingClientRect(); + if (rect.top > y) break; + if (rect.bottom >= y && rect.width && rect.height) { + return { page, x, y, u: (x - rect.left) / rect.width, v: (y - rect.top) / rect.height }; + } + } + return null; +} + +export function attachPreviewView(pages) { + const scroller = pages.parentElement; + const panel = pages.closest(".preview-panel"); + pages.classList.add("texrra-preview-pages"); + if (panel) pages.classList.add("texrra-preview-web"); + + const toolbar = document.createElement("div"); + toolbar.className = "texrra-preview-controls"; + toolbar.setAttribute("role", "group"); + toolbar.setAttribute("aria-label", "预览工具"); + const zoomOut = button("−", "缩小预览"); + const zoomIn = button("+", "放大预览"); + const zoomValue = document.createElement("output"); + const fit = button("适合宽度", "适合预览区宽度"); + toolbar.append(zoomOut, zoomValue, zoomIn, fit); + if (panel) scroller.before(toolbar); + else { + toolbar.classList.add("texrra-preview-sticky"); + scroller.prepend(toolbar); + } + + let zoom = 100; + let measure; + const textByFrame = new WeakMap(); + + function resize() { + if (zoom === 100) { + pages.style.removeProperty("--texrra-zoom-width"); + return; + } + const style = getComputedStyle(scroller); + const available = scroller.clientWidth + - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight); + pages.style.setProperty("--texrra-zoom-width", + "calc(min(" + Math.max(0, available) + "px, var(--texrra-fit-width)) * " + zoom / 100 + ")"); + } + + function updateControls() { + zoomOut.disabled = zoom === minimumZoom; + zoomIn.disabled = zoom === maximumZoom; + zoomValue.value = zoom + "%"; + fit.setAttribute("aria-pressed", String(zoom === 100)); + } + + function setZoom(next) { + if (next === zoom || next < minimumZoom || next > maximumZoom) return; + const anchor = centerOfPage(scroller, pages); + zoom = next; + resize(); + updateControls(); + if (anchor) { + const rect = anchor.page.getBoundingClientRect(); + scroller.scrollLeft += rect.left + rect.width * anchor.u - anchor.x; + scroller.scrollTop += rect.top + rect.height * anchor.v - anchor.y; + } + } + + zoomOut.addEventListener("click", () => setZoom(zoom - zoomStep)); + zoomIn.addEventListener("click", () => setZoom(zoom + zoomStep)); + fit.addEventListener("click", () => setZoom(100)); + new ResizeObserver(resize).observe(scroller); + updateControls(); + + function wrap(image, page) { + const frame = document.createElement("div"); + frame.className = "texrra-preview-page"; + frame.dataset.index = page.index; + image.draggable = false; + frame.append(image); + return frame; + } + + function setText(frame, page) { + const previous = textByFrame.get(frame); + if (sameTextPage(previous, page)) return; + frame.querySelector(".texrra-preview-text")?.remove(); + textByFrame.set(frame, page); + if (page.lines.length === 0 || !(page.width > 0 && page.height > 0)) { + frame.classList.remove("texrra-preview-has-text"); + return; + } + + if (measure === undefined) { + measure = document.createElement("canvas").getContext("2d"); + if (measure) measure.font = "100px Arial, sans-serif"; + } + const layer = document.createElement("div"); + layer.className = "texrra-preview-text"; + for (const line of page.lines) { + if (!line.text || !(line.width > 0 && line.height > 0)) continue; + const text = document.createElement("span"); + // Absolutely positioned siblings don't create a line break in copied text. + text.textContent = line.text + "\n"; + text.dir = "auto"; + text.style.left = (100 * line.x / page.width) + "%"; + text.style.top = (100 * line.y / page.height) + "%"; + text.style.fontSize = (100 * line.height / page.width) + "cqw"; + const width = (measure?.measureText(line.text).width ?? 0) * line.height / 100; + if (width > 0) text.style.transform = "scaleX(" + line.width / width + ")"; + layer.append(text); + } + frame.classList.add("texrra-preview-has-text"); + frame.append(layer); + } + + function setTextPages(textPages) { + for (const page of textPages) { + const frame = pages.children[page.index]; + if (frame?.dataset.index === String(page.index)) setText(frame, page); + } + } + + return { toolbar, wrap, setTextPages }; +} diff --git a/examples/native_editor/text_layer.rs b/examples/native_editor/text_layer.rs new file mode 100644 index 0000000..6dfee9f --- /dev/null +++ b/examples/native_editor/text_layer.rs @@ -0,0 +1,278 @@ +//! Selectable text for a committed preview. The existing page paint is unchanged. + +use texrra_engine::native::CompiledDocument; +use texrra_tex_core::{ + render::{DisplayItem, DisplayList}, + source_map::{Bounds, MappedPaint, PageMap}, + type1::glyph_unicode_text, +}; + +#[derive(serde::Serialize)] +pub(super) struct TextLayer { + revision: u64, + pages: Vec, +} + +#[derive(serde::Serialize)] +struct TextPage { + index: usize, + width: f64, + height: f64, + lines: Vec, +} + +#[derive(serde::Serialize)] +struct TextLine { + x: f64, + y: f64, + width: f64, + height: f64, + text: String, +} + +struct Glyph { + left: f64, + top: f64, + right: f64, + bottom: f64, + baseline: f64, + size: f64, + text: String, +} + +pub(super) fn for_document(document: &CompiledDocument) -> TextLayer { + let pages = document + .pages + .iter() + .zip(&document.source_map.pages) + .map(|(page, map)| text_page(page, map)) + .collect(); + TextLayer { + revision: document.revision(), + pages, + } +} + +fn text_page(page: &DisplayList, map: &PageMap) -> TextPage { + let [_, _, width, height] = map.bounds_bp(Bounds { + x: 0, + y: 0, + width: map.width, + height: map.height, + }); + let mut lines = Vec::new(); + let mut run = None::; + for glyph in map + .entries + .iter() + .filter_map(|entry| glyph_at(page, map, entry)) + { + if let Some(current) = &mut run + && current.continues(&glyph) + { + current.push(glyph); + continue; + } + if let Some(current) = run.replace(Run::new(glyph)) { + lines.push(current.finish()); + } + } + if let Some(current) = run { + lines.push(current.finish()); + } + TextPage { + index: map.page_index, + width, + height, + lines, + } +} + +fn glyph_at(page: &DisplayList, map: &PageMap, entry: &MappedPaint) -> Option { + let from_sp = |value| page.units.bp(value) * f64::from(page.magnification) / 1000.0; + let [left, top, width, height] = map.bounds_bp(entry.bounds); + let (x, y, size, advance, position_tolerance, text) = match page.items.get(entry.item_index)? { + DisplayItem::NativeGlyph { + x, + y, + size, + slot, + font, + paint, + character, + } => { + let text = paint + .as_ref() + .and_then(|paint| paint.encoding.get(usize::from(*slot))) + .and_then(|name| glyph_unicode_text(name)); + // For remapped fonts the retained character can be more accurate + // than the original glyph name. Prefer a full name-derived ligature + // when its first character agrees with the resolved character. + let text = match text { + Some(text) if text.starts_with(*character) => text, + _ if *character != '\u{fffd}' => character.to_string(), + _ => return None, + }; + let design_size = from_sp(font.size_sp()); + let size_bp = from_sp(*size); + if design_size <= 0.0 { + return None; + } + let advance = from_sp(font.advance(*slot)) * size_bp / design_size; + (*x, *y, size_bp, advance, 0.02, text) + } + DisplayItem::OpenTypeGlyph { + x, + y, + size, + advance, + text, + .. + } => { + let size = from_sp(*size); + (*x, *y, size, from_sp(*advance), 0.2 * size, text.clone()) + } + _ => return None, + }; + + let baseline = from_sp(y); + let bottom = top + height; + // The current DOM overlay is horizontal. The source map has already + // projected graphics state and crop boxes; exclude glyphs whose final + // projected box cannot be identified with the horizontal placement. + if size <= 0.0 + || width <= 0.0 + || height <= 0.0 + || height > size * 1.5 + || advance <= 0.0 + || (left - from_sp(x)).abs() > position_tolerance + || (width - advance).abs() > position_tolerance.max(size * 0.03) + || baseline < top - 0.02 + || baseline > bottom + 0.02 + { + return None; + } + let text = copy_text(&text); + if text.trim().is_empty() { + return None; + } + Some(Glyph { + left, + top, + right: left + width, + bottom, + baseline, + size, + text, + }) +} + +fn copy_text(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for ch in text.chars() { + match ch { + 'ff' => out.push_str("ff"), + 'fi' => out.push_str("fi"), + 'fl' => out.push_str("fl"), + 'ffi' => out.push_str("ffi"), + 'ffl' => out.push_str("ffl"), + 'ſt' => out.push_str("ſt"), + 'st' => out.push_str("st"), + ch if !ch.is_control() => out.push(ch), + _ => {} + } + } + out +} + +struct Run { + left: f64, + top: f64, + right: f64, + bottom: f64, + baseline: f64, + last_left: f64, + last_right: f64, + last_size: f64, + text: String, +} + +impl Run { + fn new(glyph: Glyph) -> Self { + Self { + left: glyph.left, + top: glyph.top, + right: glyph.right, + bottom: glyph.bottom, + baseline: glyph.baseline, + last_left: glyph.left, + last_right: glyph.right, + last_size: glyph.size, + text: glyph.text, + } + } + + fn continues(&self, glyph: &Glyph) -> bool { + let em = self.last_size.min(glyph.size); + // Long horizontal moves indicate independent blocks or table cells. + // Keep paint order across those blocks and therefore across columns. + (self.baseline - glyph.baseline).abs() <= 0.02 + && glyph.left >= self.last_left - em * 0.2 + && glyph.left - self.last_right <= em * 1.25 + } + + fn push(&mut self, glyph: Glyph) { + let em = self.last_size.min(glyph.size); + // TeX interword glue is between positioned glyphs, not an item. + if glyph.left - self.last_right >= em * 0.15 { + self.text.push(' '); + } + self.text.push_str(&glyph.text); + self.left = self.left.min(glyph.left); + self.top = self.top.min(glyph.top); + self.right = self.right.max(glyph.right); + self.bottom = self.bottom.max(glyph.bottom); + self.last_left = glyph.left; + self.last_right = glyph.right; + self.last_size = glyph.size; + } + + fn finish(self) -> TextLine { + TextLine { + x: self.left, + y: self.top, + width: self.right - self.left, + height: self.bottom - self.top, + text: self.text, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keeps_interword_glue_and_separates_distant_columns() { + let glyph = |left: f64, text: &str| Glyph { + left, + top: 5.0, + right: left + 5.0, + bottom: 12.0, + baseline: 11.0, + size: 10.0, + text: copy_text(text), + }; + let mut run = Run::new(glyph(10.0, "A")); + let adjacent = glyph(15.0, "ffi"); + assert!(run.continues(&adjacent)); + run.push(adjacent); + let next_word = glyph(23.0, "x"); + assert!(run.continues(&next_word)); + run.push(next_word); + assert!(!run.continues(&glyph(110.0, "B"))); + let line = run.finish(); + assert_eq!(line.text, "Affi x"); + assert_eq!((line.x, line.width), (10.0, 18.0)); + } +}