200 lines
7.0 KiB
JavaScript
200 lines
7.0 KiB
JavaScript
import { iconSvg } from "../icons/icons.js";
|
|
import { mountMarkdown } from "./markdown.js";
|
|
import { mountCodeEditor } from "./code-editor.js";
|
|
import { escapeText } from "./text-runtime.js";
|
|
export function normalizeDocumentPath(value = "/") {
|
|
const parts = String(value).split("/").filter(Boolean);
|
|
if (
|
|
parts.length > 20 ||
|
|
parts.some((part) => part === ".." || part === "." || part.length > 128)
|
|
)
|
|
return null;
|
|
return "/" + parts.join("/");
|
|
}
|
|
export function mountDocuments(
|
|
root,
|
|
{ files, path = "/", onNavigate, hrefForPath, notify, t = (ru) => ru } = {},
|
|
) {
|
|
if (!(files instanceof Map))
|
|
throw new TypeError("Documents need a Map of path to file");
|
|
const abort = new AbortController(),
|
|
{ signal } = abort;
|
|
let editor,
|
|
markdown,
|
|
timer,
|
|
disposed = false;
|
|
path = normalizeDocumentPath(path);
|
|
const item = path && files.get(path),
|
|
name = path?.split("/").at(-1) || t("Документы", "Documents");
|
|
function download(value) {
|
|
const blob = new Blob([value], { type: "text/plain;charset=utf-8" }),
|
|
url = URL.createObjectURL(blob),
|
|
link = document.createElement("a");
|
|
link.href = url;
|
|
link.download = name;
|
|
link.click();
|
|
setTimeout(() => URL.revokeObjectURL(url), 30000);
|
|
}
|
|
function error(message) {
|
|
notify?.(message, { type: "error" });
|
|
}
|
|
root.classList.add("documents-workspace");
|
|
const toolbar = `<div class="documents-toolbar"><span class="demo-label">${t("Тестовые документы · изменения в текущей вкладке", "Sample documents · changes stay in this tab")}</span><label class="document-open">${iconSvg("upload", { size: 16 })}<span>${t("Открыть .md", "Open .md")}</span><input type="file" accept=".md,.markdown,.txt" data-document-open></label>${item ? `<button type="button" data-document-download>${iconSvg("download", { size: 16 })}<span>${t("Скачать", "Download")}</span></button>` : ""}</div>`;
|
|
if (item) {
|
|
const isMarkdown = ["markdown", "md"].includes(item.language);
|
|
root.innerHTML =
|
|
toolbar +
|
|
`<div class="document-panes ${isMarkdown ? "document-split" : ""}"><div data-document-editor></div>${isMarkdown ? `<section class="document-preview"><h2>${t("Просмотр Markdown", "Markdown preview")}</h2><div data-markdown-preview></div></section>` : ""}</div>`;
|
|
if (isMarkdown) {
|
|
markdown = mountMarkdown(root.querySelector("[data-markdown-preview]"), {
|
|
source: item.content,
|
|
t,
|
|
});
|
|
markdown.ready.catch(() =>
|
|
error(t("Не удалось загрузить просмотр.", "Could not load preview.")),
|
|
);
|
|
}
|
|
editor = mountCodeEditor(root.querySelector("[data-document-editor]"), {
|
|
value: item.content,
|
|
language: item.language,
|
|
label: name,
|
|
t,
|
|
notify,
|
|
onSave: download,
|
|
onChange: (value) => {
|
|
item.content = value;
|
|
clearTimeout(timer);
|
|
if (markdown)
|
|
timer = setTimeout(
|
|
() =>
|
|
markdown
|
|
.setSource(value)
|
|
.catch(() =>
|
|
error(
|
|
t(
|
|
"Не удалось обновить просмотр.",
|
|
"Could not refresh preview.",
|
|
),
|
|
),
|
|
),
|
|
120,
|
|
);
|
|
},
|
|
});
|
|
root
|
|
.querySelector("[data-document-download]")
|
|
.addEventListener("click", () => download(editor.getValue()), { signal });
|
|
root.querySelector("[data-markdown-preview]")?.addEventListener(
|
|
"click",
|
|
(event) => {
|
|
const link = event.target.closest("a[href]");
|
|
if (
|
|
!link ||
|
|
event.ctrlKey ||
|
|
event.metaKey ||
|
|
event.shiftKey ||
|
|
event.altKey ||
|
|
link.target === "_blank"
|
|
)
|
|
return;
|
|
const raw = link.getAttribute("href");
|
|
if (!raw || raw.startsWith("#") || /^[a-z][a-z\d+.-]*:/i.test(raw))
|
|
return;
|
|
const next = normalizeDocumentPath(
|
|
decodeURIComponent(
|
|
new URL(raw, "https://documents.invalid" + path).pathname,
|
|
),
|
|
);
|
|
if (next && files.has(next) && onNavigate) {
|
|
event.preventDefault();
|
|
onNavigate(next);
|
|
}
|
|
},
|
|
{ signal },
|
|
);
|
|
} else {
|
|
const prefix = path === "/" ? "/" : path + "/",
|
|
children = new Map();
|
|
if (path)
|
|
for (const [file] of files) {
|
|
if (file.startsWith(prefix)) {
|
|
const rest = file.slice(prefix.length),
|
|
segment = rest.split("/")[0];
|
|
if (segment)
|
|
children.set(segment, {
|
|
folder: rest.includes("/"),
|
|
path: prefix + segment,
|
|
});
|
|
}
|
|
}
|
|
root.innerHTML =
|
|
toolbar +
|
|
`<div class="document-file-list">${
|
|
children.size
|
|
? [...children]
|
|
.sort(([a], [b]) => a.localeCompare(b))
|
|
.map(
|
|
([label, entry]) =>
|
|
`<a href="${escapeText(hrefForPath?.(entry.path) || "#")}" data-document-path="${escapeText(entry.path)}">${iconSvg(entry.folder ? "folder" : "document", { size: 20 })}<span>${escapeText(label)}</span><small>${entry.folder ? t("Папка", "Folder") : ""}</small></a>`,
|
|
)
|
|
.join("")
|
|
: `<div class="empty-state"><h2>${t("Папка не найдена", "Folder not found")}</h2><p>${t("Вернитесь к документам через хлебные крошки.", "Return to documents using the breadcrumbs.")}</p></div>`
|
|
}</div>`;
|
|
root.querySelectorAll("[data-document-path]").forEach((link) =>
|
|
link.addEventListener(
|
|
"click",
|
|
(event) => {
|
|
if (
|
|
onNavigate &&
|
|
!event.ctrlKey &&
|
|
!event.metaKey &&
|
|
!event.shiftKey &&
|
|
!event.altKey
|
|
) {
|
|
event.preventDefault();
|
|
onNavigate(link.dataset.documentPath);
|
|
}
|
|
},
|
|
{ signal },
|
|
),
|
|
);
|
|
}
|
|
root.querySelector("[data-document-open]").addEventListener(
|
|
"change",
|
|
async (event) => {
|
|
const file = event.target.files?.[0];
|
|
if (!file) return;
|
|
if (file.size > 131072) {
|
|
error(
|
|
t(
|
|
"Для этого редактора выберите файл до 128 КБ.",
|
|
"Choose a file up to 128 KB for this editor.",
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
try {
|
|
const content = await file.text();
|
|
if (disposed) return;
|
|
if (content.split("\n").length > 4000) throw new RangeError();
|
|
const next = "/imports/" + file.name.replace(/[\\/]/g, "_");
|
|
files.set(next, { language: "markdown", content });
|
|
onNavigate?.(next);
|
|
} catch {
|
|
if (!disposed)
|
|
error(t("Не удалось открыть файл.", "Could not open the file."));
|
|
}
|
|
},
|
|
{ signal },
|
|
);
|
|
return {
|
|
dispose() {
|
|
disposed = true;
|
|
clearTimeout(timer);
|
|
abort.abort();
|
|
editor?.dispose();
|
|
markdown?.dispose();
|
|
},
|
|
};
|
|
}
|