Files
texrra-engine/examples/native_editor/code_editor.js
T

316 lines
12 KiB
JavaScript

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();
},
};
}