Files
pages/assets/editor/src/editor.js
T

418 lines
14 KiB
JavaScript

import { EditorView, keymap, lineNumbers, highlightActiveLine, highlightActiveLineGutter } from "@codemirror/view";
import { EditorState } from "@codemirror/state";
import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
import {
bracketMatching,
HighlightStyle,
StreamLanguage,
syntaxHighlighting,
} from "@codemirror/language";
import {
autocompletion,
completionKeymap,
closeBrackets,
closeBracketsKeymap,
} from "@codemirror/autocomplete";
import { html } from "@codemirror/lang-html";
import { markdown } from "@codemirror/lang-markdown";
import { javascript } from "@codemirror/lang-javascript";
import { python } from "@codemirror/lang-python";
import { json } from "@codemirror/lang-json";
import { css } from "@codemirror/lang-css";
import { sql } from "@codemirror/lang-sql";
import { yaml } from "@codemirror/lang-yaml";
import { go } from "@codemirror/lang-go";
import { rust } from "@codemirror/lang-rust";
import { java } from "@codemirror/lang-java";
import { cpp } from "@codemirror/lang-cpp";
import { shell } from "@codemirror/legacy-modes/mode/shell";
import { toml } from "@codemirror/legacy-modes/mode/toml";
import { vim, Vim, getCM } from "@replit/codemirror-vim";
import { tags, highlightTree } from "@lezer/highlight";
// Stable semantic styles instead of selectors for generated Lezer class names.
// CSS variables follow the selected Wiki theme without rebuilding the document.
const pagesWikiHighlightStyle = HighlightStyle.define([
{tag: tags.heading, class: "pw-syntax-heading"},
{tag: [tags.link, tags.url], class: "pw-syntax-link"},
{tag: tags.emphasis, class: "pw-syntax-emphasis"},
{tag: tags.strong, class: "pw-syntax-strong"},
{tag: [tags.keyword, tags.operatorKeyword], class: "pw-syntax-keyword"},
{tag: [tags.tagName, tags.typeName, tags.monospace], class: "pw-syntax-type"},
{tag: [tags.string, tags.special(tags.string)], class: "pw-syntax-string"},
{tag: [tags.number, tags.bool, tags.null, tags.attributeName], class: "pw-syntax-number"},
{tag: tags.comment, class: "pw-syntax-comment"},
{tag: [tags.variableName, tags.propertyName], class: "pw-syntax-variable"},
{tag: tags.function(tags.variableName), class: "pw-syntax-function"},
{tag: tags.operator, class: "pw-syntax-operator"},
{tag: tags.invalid, class: "pw-syntax-invalid"},
]);
const pagesWikiTheme = EditorView.theme({
".cm-selectionBackground": {
backgroundColor: "var(--editor-selection) !important",
},
"&.cm-focused .cm-selectionBackground": {
backgroundColor: "var(--editor-selection) !important",
},
".cm-selectionLayer .cm-selectionBackground": {
backgroundColor: "var(--editor-selection) !important",
},
".cm-content ::selection": {
backgroundColor: "var(--editor-selection) !important",
color: "var(--fg) !important",
},
});
let vimMode = "INSERT";
const languageAliases = {js:'javascript', ts:'typescript', py:'python', sh:'shell', bash:'shell', zsh:'shell', yml:'yaml', md:'markdown', c:'cpp', 'c++':'cpp', xml:'html', htm:'html'};
function languageExtension(mode) {
mode = String(mode || "").toLowerCase();
switch (languageAliases[mode] || mode) {
case "html":
return html();
case "markdown":
return markdown({codeLanguages: info => {
const mode = info.trim().split(/\s+/)[0].toLowerCase();
if (['md','markdown'].includes(mode)) return null;
const support = languageExtension(mode);
return support?.language || support;
}});
case "javascript":
return javascript({ jsx: true });
case "typescript":
return javascript({ jsx: true, typescript: true });
case "python":
return python();
case "json":
return json();
case "css":
return css();
case "sql":
return sql();
case "yaml":
return yaml();
case "go":
return go();
case "rust":
return rust();
case "java":
return java();
case "cpp":
return cpp();
case "shell":
return StreamLanguage.define(shell);
case "toml":
return StreamLanguage.define(toml);
default:
return null;
}
}
function attachMinimap(view, minimap, text) {
if (!minimap) {
return;
}
const lines = text.split("\n");
const count = Math.max(lines.length, 1);
const step = Math.max(1, Math.ceil(count / 2000));
for (let index = 0; index < count; index += step) {
const line = document.createElement("span");
line.className = "content-code-minimap-line";
line.style.top = (index / count * 100) + "%";
const length = (lines[index] || "").trimEnd().length;
line.style.width = Math.min(96, Math.max(3, length * 1.4)) + "%";
minimap.appendChild(line);
}
const viewport = document.createElement("span");
viewport.className = "content-code-minimap-viewport";
minimap.appendChild(viewport);
const scroller = view.scrollDOM;
const update = () => {
const scrollHeight = Math.max(scroller.scrollHeight, 1);
viewport.style.top =
(scroller.scrollTop / scrollHeight * 100) + "%";
viewport.style.height =
Math.min(100, scroller.clientHeight / scrollHeight * 100) + "%";
};
scroller.addEventListener("scroll", update, { passive: true });
new ResizeObserver(update).observe(scroller);
minimap.addEventListener("pointerdown", (event) => {
const rect = minimap.getBoundingClientRect();
const ratio = Math.max(
0,
Math.min(1, (event.clientY - rect.top) / rect.height),
);
scroller.scrollTop =
ratio * scroller.scrollHeight - scroller.clientHeight / 2;
});
update();
}
function setEditorMode(mode) {
vimMode = mode;
document.body.dataset.editorMode = mode.toLowerCase();
const el =
document.getElementById("editor-vim-mode");
if (!el) {
return;
}
const cls =
"mode-" + mode.toLowerCase();
el.innerHTML =
"<strong class=\"" + cls + "\">" + mode + "</strong>";
}
function markdownCompletions(context) {
const word =
context.matchBefore(/[A-Za-z#`\-\[\]\{\}:\/]*/);
if (!word || (word.from === word.to && !context.explicit)) {
return null;
}
if (!context.explicit && !word.text.startsWith("{{")) return null;
return {
from: word.from,
options: [
{ label: "# ", type: "keyword", apply: "# " },
{ label: "## ", type: "keyword", apply: "## " },
{ label: "### ", type: "keyword", apply: "### " },
{ label: "- ", type: "keyword", apply: "- " },
{ label: "```text", type: "snippet", apply: "```text\n\n```" },
{ label: "```go", type: "snippet", apply: "```go\n\n```" },
{ label: "```bash", type: "snippet", apply: "```bash\n\n```" },
{ label: "[link](url)", type: "snippet", apply: "[text](url)" },
{ label: "{{children}}", type: "function", apply: "{{children}}", boost: 5 },
{ label: "{{children:/}}", type: "function", apply: "{{children:/}}" },
{ label: "{{children:/ exclude=/draft}}", type: "function", apply: "{{children:/ exclude=/draft}}" },
].map(option => option.label.startsWith("{{") ? {...option, apply(view, completion, from, to) {
// Existing close-bracket text is part of this macro replacement.
const tail = view.state.sliceDoc(to, to + 2).match(/^\}{1,2}/)?.[0] || "";
view.dispatch({changes:{from,to:to+tail.length,insert:option.label},selection:{anchor:from+option.label.length}});
}} : option),
};
}
function installVimCommands() {
if (!Vim || !Vim.defineEx || window.PagesWikiVimCommandsInstalled) {
return;
}
window.PagesWikiVimCommandsInstalled = true;
const save =
() => {
if (window.PagesEditor && window.PagesEditor.saveNow) {
window.PagesEditor.saveNow();
}
};
const quit =
() => {
location.href =
window.PagesWikiCurrentPath || "/";
};
const saveQuit = async () => {
if (await window.PagesEditor?.saveNow()) quit();
};
// Register both canonical and short names.
Vim.defineEx("write", "w", save);
Vim.defineEx("w", "w", save);
Vim.defineEx("quit", "q", quit);
Vim.defineEx("q", "q", quit);
Vim.defineEx("wq", "wq", saveQuit);
Vim.defineEx("x", "x", saveQuit);
}
function attachVimModeTracking(view) {
// Observe actual Vim transitions, including A/I/c/operator motions and
// command-line searches, rather than guessing the mode from individual keys.
getCM(view)?.on("vim-mode-change", event => {
const mode = String(event.mode || "normal").toUpperCase();
setEditorMode(mode);
view.dom.classList.toggle("pageswiki-vim-visual", mode === "VISUAL");
});
}
function attachStatusBar(view) {
const cursorEl =
document.getElementById("editor-cursor");
function updateCursor() {
if (!cursorEl) {
return;
}
const head =
view.state.selection.main.head;
const line =
view.state.doc.lineAt(head);
cursorEl.textContent =
"Ln " +
line.number +
", Col " +
String(head - line.from + 1);
}
updateCursor();
setEditorMode(vimMode || "INSERT");
view.dom.addEventListener("keyup", updateCursor);
view.dom.addEventListener("mouseup", updateCursor);
view.dom.addEventListener("focusin", updateCursor);
}
window.PagesWikiEditor = {
highlightCodeBlock(code, mode) {
mode = String(mode || '').toLowerCase();
const language = languageExtension(mode);
const text = code.textContent;
// Projection only: never change canonical HTML, unlabelled/plain text,
// or large samples. Large code files retain the windowed viewer.
if (!language || text.length > 32768) return false;
const parser = (language.language || language).parser;
const fragment = document.createDocumentFragment();
let offset = 0;
highlightTree(parser.parse(text), pagesWikiHighlightStyle, (from, to, classes) => {
if (from > offset) fragment.append(document.createTextNode(text.slice(offset, from)));
const span = document.createElement('span'); span.className = classes;
span.textContent = text.slice(from, to); fragment.append(span); offset = to;
});
fragment.append(document.createTextNode(text.slice(offset)));
code.replaceChildren(fragment);
return true;
},
createViewer(target, text, mode, minimap) {
const extensions = [
lineNumbers(),
syntaxHighlighting(pagesWikiHighlightStyle),
pagesWikiTheme,
EditorState.readOnly.of(true),
EditorView.editable.of(false),
];
const language = languageExtension(mode);
if (language) {
extensions.push(language);
}
const view = new EditorView({
state: EditorState.create({
doc: text,
extensions,
}),
parent: target,
});
attachMinimap(view, minimap, text);
return view;
},
create(target, initialText, mode, options = {}) {
const mobile = window.matchMedia("(pointer: coarse) and (hover: none)").matches;
const keymapName = mobile ? "default" : String(options.keymap || "default").toLowerCase();
const extensions = [
lineNumbers(),
highlightActiveLine(),
highlightActiveLineGutter(),
history(),
bracketMatching(),
closeBrackets(),
pagesWikiTheme,
EditorView.lineWrapping,
EditorView.updateListener.of((update) => {
if (update.docChanged) {
schedulePagesWikiPreview(update.view);
}
}),
];
if (options.preserveLineEndings) {
// Split only at LF, keeping any CR bytes in the document. This
// preserves mixed LF/CRLF CSV sources instead of rewriting them.
extensions.push(EditorState.lineSeparator.of("\n"));
}
if (keymapName === "vim") {
installVimCommands();
extensions.push(vim());
setEditorMode("NORMAL");
} else {
setEditorMode("INSERT");
}
extensions.push(
keymap.of([
...defaultKeymap,
...historyKeymap,
...completionKeymap,
...closeBracketsKeymap,
])
);
if (options.syntax !== false) {
extensions.push(syntaxHighlighting(pagesWikiHighlightStyle));
}
if (options.autocomplete !== false) {
extensions.push(
autocompletion({
activateOnTyping: true,
override: mode === "markdown"
? [markdownCompletions]
: undefined,
})
);
}
const language = languageExtension(mode);
if (language) {
extensions.push(language);
}
if (mode === "html" || mode === "markdown") {
extensions.push(EditorState.languageData.of(() => [{closeBrackets:{brackets:["(", "[", "'", '"', "`"]}}]));
}
const view =
new EditorView({
state: EditorState.create({
doc: initialText,
extensions,
}),
parent: target,
});
attachStatusBar(view);
if (keymapName === "vim") {
attachVimModeTracking(view);
}
return view;
},
};
function schedulePagesWikiPreview(view) {
const textarea = document.getElementById("editor");
if (textarea) {
textarea.value =
view.state.doc.toString();
textarea.dispatchEvent(new Event("input", {bubbles:true}));
}
}