Files
pages/assets/editor/src/editor.js
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

488 lines
13 KiB
JavaScript

import { EditorView, keymap, lineNumbers } from "@codemirror/view";
import { EditorState } from "@codemirror/state";
import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
import {
bracketMatching,
defaultHighlightStyle,
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 } from "@replit/codemirror-vim";
const pagesWikiTheme = EditorView.theme({
".cm-selectionBackground": {
backgroundColor: "rgba(255, 216, 102, 0.48) !important",
},
"&.cm-focused .cm-selectionBackground": {
backgroundColor: "rgba(255, 216, 102, 0.58) !important",
},
".cm-selectionLayer .cm-selectionBackground": {
backgroundColor: "rgba(255, 216, 102, 0.58) !important",
},
".cm-content ::selection": {
backgroundColor: "rgba(255, 216, 102, 0.48) !important",
color: "#ffffff !important",
},
});
let vimMode = "INSERT";
function languageExtension(mode) {
switch (String(mode || "").toLowerCase()) {
case "html":
return html();
case "markdown":
return markdown();
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;
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;
}
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}}" },
{ label: "{{children:/}}", type: "function", apply: "{{children:/}}" },
{ label: "{{children:/ exclude=/draft}}", type: "function", apply: "{{children:/ exclude=/draft}}" },
],
};
}
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 =
() => {
save();
setTimeout(quit, 120);
};
// 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) {
view.dom.addEventListener(
"keydown",
(ev) => {
if (ev.key === "Escape" || (ev.ctrlKey && ev.key === "[")) {
setEditorMode("NORMAL");
return;
}
if (vimMode === "NORMAL") {
if (ev.key === "i" || ev.key === "a" || ev.key === "o" || ev.key === "O") {
setEditorMode("INSERT");
return;
}
if (ev.key === "R") {
setEditorMode("REPLACE");
return;
}
if (ev.key === "v" || ev.key === "V") {
setEditorMode("VISUAL");
return;
}
}
if (vimMode === "VISUAL" && ev.key === "Escape") {
setEditorMode("NORMAL");
}
},
true
);
view.dom.addEventListener(
"focusin",
() => {
if (!vimMode) {
setEditorMode("INSERT");
}
}
);
}
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 = {
createViewer(target, text, mode, minimap) {
const extensions = [
lineNumbers(),
syntaxHighlighting(defaultHighlightStyle),
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 keymapName =
String(options.keymap || "default").toLowerCase();
const extensions = [
lineNumbers(),
history(),
bracketMatching(),
closeBrackets(),
pagesWikiTheme,
EditorView.lineWrapping,
EditorView.updateListener.of((update) => {
if (update.docChanged) {
schedulePagesWikiPreview(update.view);
}
}),
];
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(defaultHighlightStyle));
}
if (options.autocomplete !== false) {
extensions.push(
autocompletion({
activateOnTyping: true,
override: mode === "markdown"
? [markdownCompletions]
: undefined,
})
);
}
const language = languageExtension(mode);
if (language) {
extensions.push(language);
}
const view =
new EditorView({
state: EditorState.create({
doc: initialText,
extensions,
}),
parent: target,
});
attachStatusBar(view);
if (keymapName === "vim") {
attachVimModeTracking(view);
attachPagesWikiExFallback(view);
}
return view;
},
};
function attachPagesWikiExFallback(view) {
let active = false;
let buffer = "";
function save() {
if (window.PagesEditor && window.PagesEditor.saveNow) {
window.PagesEditor.saveNow();
}
}
function quit() {
location.href =
window.PagesWikiCurrentPath || "/";
}
view.dom.addEventListener(
"keydown",
(ev) => {
if (!active && vimMode === "NORMAL" && ev.key === ":") {
active = true;
buffer = "";
return;
}
if (!active) {
return;
}
if (ev.key === "Escape" || (ev.ctrlKey && ev.key === "[")) {
active = false;
buffer = "";
return;
}
if (ev.key === "Enter") {
const cmd =
buffer.trim();
active = false;
buffer = "";
if (cmd === "w") {
ev.preventDefault();
save();
return;
}
if (cmd === "q") {
ev.preventDefault();
quit();
return;
}
if (cmd === "wq" || cmd === "x") {
ev.preventDefault();
save();
setTimeout(quit, 120);
return;
}
return;
}
if (ev.key.length === 1) {
buffer += ev.key;
}
if (ev.key === "Backspace") {
buffer =
buffer.slice(0, -1);
}
},
true
);
}
let pagesWikiPreviewTimer = null;
function schedulePagesWikiPreview(view) {
const textarea =
document.getElementById("editor");
if (textarea) {
textarea.value =
view.state.doc.toString();
}
if (pagesWikiPreviewTimer) {
clearTimeout(pagesWikiPreviewTimer);
}
pagesWikiPreviewTimer =
setTimeout(
() => {
if (
window.PagesEditor &&
window.PagesEditor.renderPreview
) {
window.PagesEditor.renderPreview();
}
},
350
);
}