Add Markdown editor, server statistics and content navigation
This commit is contained in:
1 parent
03c590e172
commit
1819f35f91
52 files changed
+7190
-28
No files matched your search
@@ -0,0 +1,227 @@
|
||||
import { iconSvg } from "../icons/icons.js";
|
||||
import {
|
||||
escapeText,
|
||||
highlightedCode,
|
||||
codeLanguages,
|
||||
normalizeLanguage,
|
||||
} from "./text-runtime.js";
|
||||
let sequence = 0;
|
||||
export function mountCodeEditor(
|
||||
root,
|
||||
{
|
||||
value = "",
|
||||
language = "plaintext",
|
||||
label = "editor.txt",
|
||||
readOnly = false,
|
||||
onChange = () => {},
|
||||
onSave,
|
||||
notify,
|
||||
t = (ru) => ru,
|
||||
} = {},
|
||||
) {
|
||||
const id = `code-editor-${++sequence}`,
|
||||
abort = new AbortController(),
|
||||
{ signal } = abort;
|
||||
let disposed = false,
|
||||
timer,
|
||||
revision = 0,
|
||||
captureTab = true,
|
||||
accepted = "";
|
||||
const valid = (text) =>
|
||||
text.length <= 131072 && text.split("\n").length <= 4000;
|
||||
if (!valid(String(value)))
|
||||
throw new RangeError(
|
||||
"Editor supports up to 131072 characters and 4000 lines",
|
||||
);
|
||||
root.classList.add("code-editor");
|
||||
root.innerHTML = `<div class="code-editor-toolbar"><label for="${id}">${escapeText(label)}</label><div><select aria-label="${t("Язык кода", "Code language")}">${codeLanguages.map((name) => `<option value="${name}">${name === "plaintext" ? t("Текст", "Plain text") : name}</option>`).join("")}</select><button type="button" data-code-copy aria-label="${t("Копировать код", "Copy code")}" title="${t("Копировать код", "Copy code")}">${iconSvg("copy", { size: 16 })}</button></div></div><div class="code-editor-viewport"><div class="code-editor-gutter" aria-hidden="true"><pre></pre></div><div class="code-editor-layer"><pre aria-hidden="true"><code></code></pre><textarea id="${id}" aria-label="${escapeText(label)}" spellcheck="false" autocapitalize="off" autocomplete="off" autocorrect="off" wrap="off" maxlength="131072" ${readOnly ? "readonly" : ""}></textarea></div></div><div class="code-editor-status"><span data-code-position></span><button type="button" data-code-tab aria-pressed="true" title="Ctrl M">${t("Tab: отступ", "Tab: indent")}</button><span data-code-message role="status"></span></div>`;
|
||||
const input = root.querySelector("textarea"),
|
||||
pre = root.querySelector(".code-editor-layer pre"),
|
||||
code = pre.querySelector("code"),
|
||||
lines = root.querySelector(".code-editor-gutter pre"),
|
||||
select = root.querySelector("select"),
|
||||
position = root.querySelector("[data-code-position]"),
|
||||
message = root.querySelector("[data-code-message]"),
|
||||
tab = root.querySelector("[data-code-tab]");
|
||||
input.value = accepted = String(value);
|
||||
select.value = codeLanguages.includes(normalizeLanguage(language))
|
||||
? normalizeLanguage(language)
|
||||
: "plaintext";
|
||||
function locate() {
|
||||
const before = input.value.slice(0, input.selectionStart).split("\n");
|
||||
position.textContent = t(
|
||||
`Строка ${before.length}, столбец ${before.at(-1).length + 1}`,
|
||||
`Line ${before.length}, column ${before.at(-1).length + 1}`,
|
||||
);
|
||||
}
|
||||
function syncScroll() {
|
||||
pre.scrollTop = input.scrollTop;
|
||||
pre.scrollLeft = input.scrollLeft;
|
||||
lines.style.transform = `translateY(${-input.scrollTop}px)`;
|
||||
}
|
||||
async function paint() {
|
||||
const ticket = ++revision,
|
||||
text = input.value + (input.value.endsWith("\n") ? " " : "");
|
||||
code.textContent = text;
|
||||
lines.textContent = Array.from(
|
||||
{ length: input.value.split("\n").length },
|
||||
(_, index) => index + 1,
|
||||
).join("\n");
|
||||
locate();
|
||||
syncScroll();
|
||||
try {
|
||||
const html = await highlightedCode(text, select.value);
|
||||
if (!disposed && ticket === revision) {
|
||||
code.innerHTML = html;
|
||||
syncScroll();
|
||||
}
|
||||
} catch {
|
||||
if (!disposed && ticket === revision) code.textContent = text;
|
||||
}
|
||||
}
|
||||
function changed() {
|
||||
if (!valid(input.value)) {
|
||||
input.value = accepted;
|
||||
message.textContent = t(
|
||||
"Превышен размер редактора.",
|
||||
"Editor size limit exceeded.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
accepted = input.value;
|
||||
revision++;
|
||||
clearTimeout(timer);
|
||||
code.textContent = input.value;
|
||||
lines.textContent = Array.from(
|
||||
{ length: input.value.split("\n").length },
|
||||
(_, index) => index + 1,
|
||||
).join("\n");
|
||||
locate();
|
||||
syncScroll();
|
||||
onChange(input.value);
|
||||
timer = setTimeout(paint, 70);
|
||||
}
|
||||
function insert(text) {
|
||||
input.focus();
|
||||
const start = input.selectionStart,
|
||||
end = input.selectionEnd;
|
||||
if (!document.execCommand("insertText", false, text)) {
|
||||
input.setRangeText(text, start, end, "end");
|
||||
changed();
|
||||
}
|
||||
}
|
||||
function toggleTab() {
|
||||
captureTab = !captureTab;
|
||||
tab.setAttribute("aria-pressed", String(captureTab));
|
||||
tab.textContent = captureTab
|
||||
? t("Tab: отступ", "Tab: indent")
|
||||
: t("Tab: переход", "Tab: focus");
|
||||
}
|
||||
input.addEventListener("input", changed, { signal });
|
||||
input.addEventListener("scroll", syncScroll, { signal });
|
||||
input.addEventListener("click", locate, { signal });
|
||||
input.addEventListener("keyup", locate, { signal });
|
||||
input.addEventListener(
|
||||
"keydown",
|
||||
(event) => {
|
||||
if (event.isComposing) return;
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "m") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleTab();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
(event.ctrlKey || event.metaKey) &&
|
||||
event.key.toLowerCase() === "s" &&
|
||||
onSave
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onSave(input.value);
|
||||
return;
|
||||
}
|
||||
if (readOnly) return;
|
||||
if (event.key === "Tab" && captureTab) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const start = input.selectionStart,
|
||||
end = input.selectionEnd;
|
||||
if (start === end && !event.shiftKey) {
|
||||
insert(" ");
|
||||
return;
|
||||
}
|
||||
const first = input.value.lastIndexOf("\n", start - 1) + 1,
|
||||
last = input.value.indexOf("\n", Math.max(start, end - 1)),
|
||||
finish = last < 0 ? input.value.length : last;
|
||||
const selected = input.value
|
||||
.slice(first, finish)
|
||||
.split("\n")
|
||||
.map((line) =>
|
||||
event.shiftKey ? line.replace(/^( {1,2}|\t)/, "") : " " + line,
|
||||
)
|
||||
.join("\n");
|
||||
input.setSelectionRange(first, finish);
|
||||
insert(selected);
|
||||
input.setSelectionRange(first, first + selected.length);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
event.key === "Enter" &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.altKey
|
||||
) {
|
||||
event.preventDefault();
|
||||
const before = input.value
|
||||
.slice(0, input.selectionStart)
|
||||
.split("\n")
|
||||
.at(-1),
|
||||
indent = /^[ \t]*/.exec(before)[0];
|
||||
insert("\n" + indent + (/[\[{]\s*$/.test(before) ? " " : ""));
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
select.addEventListener("change", paint, { signal });
|
||||
tab.addEventListener("click", toggleTab, { signal });
|
||||
root.querySelector("[data-code-copy]").addEventListener(
|
||||
"click",
|
||||
async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(input.value);
|
||||
if (!disposed) {
|
||||
message.textContent = t("Скопировано", "Copied");
|
||||
notify?.(t("Код скопирован.", "Code copied."), { type: "success" });
|
||||
}
|
||||
} catch {
|
||||
if (!disposed)
|
||||
message.textContent = t("Не удалось скопировать.", "Could not copy.");
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
paint();
|
||||
return {
|
||||
getValue: () => input.value,
|
||||
setValue(text, { emit = false } = {}) {
|
||||
text = String(text);
|
||||
if (!valid(text)) throw new RangeError("Editor limit exceeded");
|
||||
input.value = accepted = text;
|
||||
paint();
|
||||
if (emit) onChange(text);
|
||||
},
|
||||
setLanguage(name) {
|
||||
select.value = codeLanguages.includes(normalizeLanguage(name))
|
||||
? normalizeLanguage(name)
|
||||
: "plaintext";
|
||||
paint();
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
revision++;
|
||||
clearTimeout(timer);
|
||||
abort.abort();
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user