174 lines
15 KiB
TypeScript
174 lines
15 KiB
TypeScript
import { escapeHtml as e } from "../../html.ts";
|
|
import { fmt, LANG_NAMES, LANGS, type Dict, type Lang } from "./i18n/index.ts";
|
|
import { flatten, label, MAX_DEPTH, type SectionNode } from "./tree.ts";
|
|
|
|
export const LIBRARY_CSS = `:root{--bg:#f7f6f2;--fg:#1d1d1b;--muted:#5d5d58;--card:#fff;--line:#e2e0d8;--accent:#2f5d50;--warn:#9a3412}
|
|
@media (prefers-color-scheme:dark){:root{--bg:#141413;--fg:#ecebe6;--muted:#a3a29b;--card:#1e1e1c;--line:#33332f;--accent:#8cc1b0;--warn:#fdba74}}
|
|
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
main{max-width:880px;margin:0 auto;padding:32px 16px}a{color:var(--accent)}h1{margin:8px 0}.lead,.meta,.note{color:var(--muted)}
|
|
nav.top{display:flex;gap:16px;flex-wrap:wrap;font-size:.875rem;justify-content:space-between}nav.top span a{margin-left:8px}
|
|
form.search{display:flex;gap:8px;margin:16px 0 24px}form.search input{flex:1}
|
|
input,select,textarea,button{font:inherit;padding:6px 10px;border:1px solid var(--line);border-radius:6px;background:var(--card);color:var(--fg)}
|
|
button{cursor:pointer;border-color:var(--accent);color:var(--accent)}textarea{width:100%;min-height:120px}
|
|
details{margin:4px 0}details>div,ul.toc ul{margin-left:20px}summary{cursor:pointer;font-weight:600}
|
|
ul{padding-left:20px}ul.toc{list-style:none;padding-left:0}.items{list-style:"📖 ";padding-left:24px}
|
|
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:20px;margin:16px 0}
|
|
.error{border:1px solid var(--warn);color:var(--warn);border-radius:8px;padding:8px 12px}.ok{color:var(--accent)}
|
|
.tag{display:inline-block;border:1px solid var(--line);border-radius:999px;padding:0 8px;margin:0 4px 4px 0;font-size:.875rem}
|
|
.btn{display:inline-block;margin:8px 8px 0 0;padding:8px 16px;border:1px solid var(--accent);border-radius:8px;text-decoration:none}
|
|
.inline{display:inline-flex;gap:6px;margin:2px 8px 2px 0;align-items:center}.hidden{opacity:.55}
|
|
label{display:block;margin:10px 0 2px}label.check{display:flex;gap:6px;margin:2px 0;font-weight:normal}
|
|
.f input[type=text],.f input[type=url]{width:100%}table{border-collapse:collapse;width:100%}td,th{border-bottom:1px solid var(--line);padding:6px;text-align:left}
|
|
.d1{padding-left:20px}.d2{padding-left:40px}.d3{padding-left:60px}.d4{padding-left:80px}`;
|
|
|
|
export interface ItemView {
|
|
id: string;
|
|
title: string;
|
|
author: string;
|
|
edition: string;
|
|
language: string;
|
|
annotation: string;
|
|
tags: string[];
|
|
linkUrl: string | null;
|
|
fileName: string | null;
|
|
fileSize: number | null;
|
|
fileAccess: "public" | "closed";
|
|
rightsBasis: "own" | "licensed" | "public_domain" | null;
|
|
status: "draft" | "published";
|
|
sectionIds: string[];
|
|
}
|
|
|
|
interface ShellOpts { lang: Lang; title: string; switchPath?: string }
|
|
|
|
function shell(t: Dict, o: ShellOpts, inner: string): string {
|
|
const langs = o.switchPath
|
|
? `<span>${e(t.languages)}:${(Object.keys(LANGS) as Lang[])
|
|
.map((l) => (l === o.lang ? ` <strong>${e(LANG_NAMES[l])}</strong>` : ` <a href="${e(withLang(o.switchPath as string, l))}" hreflang="${l}">${e(LANG_NAMES[l])}</a>`))
|
|
.join("")}</span>`
|
|
: "";
|
|
return `<!doctype html><html lang="${e(t.htmlLang)}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>${e(o.title)}</title><link rel="stylesheet" href="/library/library.css"></head><body><main>
|
|
<nav class="top"><span><a href="/">${e(t.home)}</a> · <a href="/library">${e(t.title)}</a></span>${langs}</nav>${inner}</main></body></html>`;
|
|
}
|
|
|
|
const withLang = (path: string, lang: Lang): string => `${path}${path.includes("?") ? "&" : "?"}lang=${lang}`;
|
|
const err = (msg: string | undefined) => (msg ? `<p class="error" role="alert">${e(msg)}</p>` : "");
|
|
|
|
// ---------- публичная часть ----------
|
|
|
|
function itemLink(i: ItemView): string {
|
|
const by = i.author ? ` <span class="meta">— ${e(i.author)}</span>` : "";
|
|
return `<li><a href="/library/items/${e(i.id)}">${e(i.title)}</a>${by}</li>`;
|
|
}
|
|
|
|
export function renderCatalog(t: Dict, lang: Lang, tree: SectionNode[], itemsBySection: Map<string, ItemView[]>, search?: { q: string; found: ItemView[] }): string {
|
|
const node = (n: SectionNode): string => {
|
|
const items = itemsBySection.get(n.id) ?? [];
|
|
const inner = `${items.length ? `<ul class="items">${items.map(itemLink).join("")}</ul>` : ""}${n.children.map(node).join("")}`;
|
|
const title = e(label(n));
|
|
if (!inner) return `<div class="leaf">${title}</div>`;
|
|
return `<details${n.depth === 0 ? " open" : ""}><summary>${title}</summary><div>${inner}</div></details>`;
|
|
};
|
|
const q = search?.q ?? "";
|
|
const form = `<form class="search" method="get" action="/library" role="search"><input type="search" name="q" value="${e(q)}" aria-label="${e(t.searchLabel)}" placeholder="${e(t.searchLabel)}" maxlength="100"><button type="submit">${e(t.searchButton)}</button></form>`;
|
|
const body = search
|
|
? `<h2>${e(fmt(t.searchResults, { q }))}</h2>${search.found.length ? `<ul class="items">${search.found.map(itemLink).join("")}</ul>` : `<p>${e(t.nothingFound)}</p>`}<p><a href="/library">${e(t.allLibrary)}</a></p>`
|
|
: `<h2>${e(t.tocHeading)}</h2>${tree.map(node).join("")}`;
|
|
const switchPath = search ? `/library?q=${encodeURIComponent(q)}` : "/library";
|
|
return shell(t, { lang, title: t.title, switchPath }, `<h1>${e(t.title)}</h1><p class="lead">${e(t.lead)}</p>${form}${body}`);
|
|
}
|
|
|
|
export function renderItem(t: Dict, lang: Lang, i: ItemView, sections: SectionNode[], opts: { editor: boolean }): string {
|
|
const row = (k: string, v: string) => (v ? `<div><span class="meta">${e(k)}:</span> ${e(v)}</div>` : "");
|
|
const tags = i.tags.length ? `<div><span class="meta">${e(t.tags)}:</span> ${i.tags.map((x) => `<span class="tag">${e(x)}</span>`).join("")}</div>` : "";
|
|
const secs = sections.length ? `<div><span class="meta">${e(t.sections)}:</span><ul>${sections.map((s) => `<li>${e(label(s))}</li>`).join("")}</ul></div>` : "";
|
|
const ann = i.annotation ? `<h2>${e(t.annotation)}</h2>${i.annotation.split(/\n{2,}/).map((p) => `<p>${e(p.trim())}</p>`).join("")}` : "";
|
|
const link = i.linkUrl ? `<a class="btn" href="${e(i.linkUrl)}" rel="noopener noreferrer nofollow">${e(t.openLink)}</a>` : "";
|
|
const file = i.fileName ? `<a class="btn" href="/library/items/${e(i.id)}/file">${e(t.download)}</a>${i.fileAccess === "closed" ? `<p class="note">${e(t.closedFileNote)}</p>` : ""}` : "";
|
|
const draft = i.status === "draft" ? `<p class="error">${e(t.draftNote)}</p>` : "";
|
|
const back = opts.editor ? ` · <a href="/library/editor/items/${e(i.id)}">${e(t.backToEditor)}</a>` : "";
|
|
return shell(
|
|
t,
|
|
{ lang, title: `${i.title} — ${t.title}`, switchPath: `/library/items/${i.id}` },
|
|
`${draft}<article class="card"><h1>${e(i.title)}</h1>${row(t.author, i.author)}${row(t.edition, i.edition)}${row(t.language, i.language)}${tags}${secs}${ann}<p>${link}${file}</p></article><p><a href="/library">${e(t.allLibrary)}</a>${back}</p>`,
|
|
);
|
|
}
|
|
|
|
export function renderMessage(t: Dict, lang: Lang, title: string, text: string): string {
|
|
return shell(t, { lang, title }, `<h1>${e(title)}</h1><p>${e(text)}</p><p><a href="/library">${e(t.allLibrary)}</a></p>`);
|
|
}
|
|
|
|
// ---------- редактор ----------
|
|
|
|
const csrfInput = (csrf: string) => `<input type="hidden" name="csrf" value="${e(csrf)}">`;
|
|
|
|
export function renderLogin(t: Dict, lang: Lang, opts: { error?: string; disabled?: boolean }): string {
|
|
const form = opts.disabled
|
|
? ""
|
|
: `<form method="post" action="/library/editor/login" class="f"><label for="pw">${e(t.password)}</label><input id="pw" type="password" name="password" autocomplete="current-password" required><p><button type="submit">${e(t.loginButton)}</button></p></form>`;
|
|
return shell(t, { lang, title: t.loginTitle, switchPath: "/library/editor" }, `<h1>${e(t.loginTitle)}</h1><p class="lead">${e(opts.disabled ? t.editorOff : t.loginLead)}</p>${err(opts.error)}${form}`);
|
|
}
|
|
|
|
export function renderEditor(t: Dict, lang: Lang, csrf: string, tree: SectionNode[], items: ItemView[], opts: { error?: string; saved?: boolean }): string {
|
|
const act = (n: SectionNode, action: string, text: string) =>
|
|
`<form method="post" action="/library/editor/sections/${e(n.id)}" class="inline">${csrfInput(csrf)}<input type="hidden" name="action" value="${action}"><button type="submit">${e(text)}</button></form>`;
|
|
const node = (n: SectionNode): string => {
|
|
const addChild =
|
|
n.depth < MAX_DEPTH - 1
|
|
? `<form method="post" action="/library/editor/sections" class="inline">${csrfInput(csrf)}<input type="hidden" name="parent" value="${e(n.id)}"><input type="text" name="title" required maxlength="200" aria-label="${e(t.newTitle)}" placeholder="${e(t.newTitle)}"><button type="submit">${e(t.addChild)}</button></form>`
|
|
: "";
|
|
const rename = `<form method="post" action="/library/editor/sections/${e(n.id)}" class="inline">${csrfInput(csrf)}<input type="hidden" name="action" value="rename"><input type="text" name="title" value="${e(n.title)}" required maxlength="200" aria-label="${e(t.newTitle)}"><button type="submit">${e(t.rename)}</button></form>`;
|
|
const hide = n.selfHidden ? act(n, "restore", t.restore) : act(n, "hide", t.hide);
|
|
return `<li${n.hidden ? ' class="hidden"' : ""}><details><summary>${e(label(n))}${n.hidden ? ` <em>(${e(t.hiddenMark)})</em>` : ""}</summary><div>${rename}${act(n, "up", t.up)}${act(n, "down", t.down)}${hide}${addChild}</div></details>${n.children.length ? `<ul class="toc">${n.children.map(node).join("")}</ul>` : ""}</li>`;
|
|
};
|
|
const all = flatten(tree);
|
|
const opt = (n: SectionNode) => `<option value="${e(n.id)}">${"— ".repeat(n.depth)}${e(label(n))}</option>`;
|
|
const move = `<h3>${e(t.moveHeading)}</h3><form method="post" action="/library/editor/move" class="f">${csrfInput(csrf)}<label for="mv-what">${e(t.moveWhat)}</label><select id="mv-what" name="section" required>${all.map(opt).join("")}</select><label for="mv-where">${e(t.moveWhere)}</label><select id="mv-where" name="parent"><option value="">${e(t.topLevel)}</option>${all.filter((n) => n.depth < MAX_DEPTH - 1).map(opt).join("")}</select><p><button type="submit">${e(t.moveButton)}</button></p></form>`;
|
|
const addPart = `<form method="post" action="/library/editor/sections" class="inline">${csrfInput(csrf)}<input type="text" name="title" required maxlength="200" aria-label="${e(t.newTitle)}" placeholder="${e(t.newTitle)}"><button type="submit">${e(t.addPart)}</button></form>`;
|
|
const status = (i: ItemView) => (i.status === "published" ? t.statusPublished : t.statusDraft);
|
|
const list = items.length
|
|
? `<table><tbody>${items.map((i) => `<tr><td><a href="/library/editor/items/${e(i.id)}">${e(i.title)}</a></td><td>${e(i.author)}</td><td>${e(status(i))}</td></tr>`).join("")}</tbody></table>`
|
|
: `<p class="note">${e(t.noMaterials)}</p>`;
|
|
const top = `<form method="post" action="/library/editor/logout" class="inline">${csrfInput(csrf)}<a href="/library">${e(t.openCatalog)}</a> <button type="submit">${e(t.logout)}</button></form>`;
|
|
return shell(
|
|
t,
|
|
{ lang, title: t.editorTitle, switchPath: "/library/editor" },
|
|
`<h1>${e(t.editorTitle)}</h1><p class="lead">${e(t.editorLead)}</p>${top}${err(opts.error)}${opts.saved ? `<p class="ok" role="status">${e(t.saved)}</p>` : ""}
|
|
<h2>${e(t.materialsHeading)}</h2><p><a class="btn" href="/library/editor/items/new">${e(t.newMaterial)}</a></p>${list}
|
|
<h2>${e(t.tocHeading)}</h2>${addPart}<ul class="toc">${tree.map(node).join("")}</ul>${move}`,
|
|
);
|
|
}
|
|
|
|
export function renderItemForm(t: Dict, lang: Lang, csrf: string, tree: SectionNode[], item: ItemView | null, opts: { error?: string; saved?: boolean; values?: Partial<ItemView> }): string {
|
|
const v: Partial<ItemView> = { ...(item ?? {}), ...(opts.values ?? {}) };
|
|
const text = (name: string, lbl: string, value: string | null | undefined, type = "text", max = 300, required = false) =>
|
|
`<label for="f-${name}">${e(lbl)}</label><input id="f-${name}" type="${type}" name="${name}" value="${e(value ?? "")}" maxlength="${max}"${required ? " required" : ""}>`;
|
|
const radio = (name: string, value: string, lbl: string, checked: boolean) =>
|
|
`<label class="check"><input type="radio" name="${name}" value="${value}"${checked ? " checked" : ""}> ${e(lbl)}</label>`;
|
|
const selected = new Set(v.sectionIds ?? []);
|
|
const secs = flatten(tree)
|
|
.map((n) => `<label class="check d${n.depth}"><input type="checkbox" name="sections" value="${e(n.id)}"${selected.has(n.id) ? " checked" : ""}> ${e(label(n))}${n.hidden ? ` (${e(t.hiddenMark)})` : ""}</label>`)
|
|
.join("");
|
|
const action = item ? `/library/editor/items/${e(item.id)}` : "/library/editor/items";
|
|
const main = `<form method="post" action="${action}" class="f">${csrfInput(csrf)}
|
|
${text("title", t.fieldTitle, v.title, "text", 300, true)}${text("author", t.author, v.author)}${text("edition", t.edition, v.edition, "text", 200)}${text("language", t.language, v.language, "text", 60)}
|
|
<label for="f-annotation">${e(t.annotation)}</label><textarea id="f-annotation" name="annotation" maxlength="5000">${e(v.annotation ?? "")}</textarea>
|
|
${text("tags", t.fieldTags, (v.tags ?? []).join(", "), "text", 1000)}${text("link", t.fieldLink, v.linkUrl, "url", 2000)}
|
|
<fieldset><legend>${e(t.fieldAccess)}</legend>${radio("access", "public", t.accessPublic, v.fileAccess !== "closed")}${radio("access", "closed", t.accessClosed, v.fileAccess === "closed")}</fieldset>
|
|
<fieldset><legend>${e(t.sections)}</legend>${secs}</fieldset>
|
|
<fieldset><legend>${e(t.status)}</legend>${radio("status", "draft", t.statusDraft, v.status !== "published")}${radio("status", "published", t.statusPublished, v.status === "published")}</fieldset>
|
|
<p><button type="submit">${e(t.save)}</button></p></form>`;
|
|
const file = item
|
|
? `<h2>${e(t.fileHeading)}</h2>${item.fileName ? `<p>${e(fmt(t.currentFile, { name: item.fileName, size: Math.ceil((item.fileSize ?? 0) / 1024) }))}</p><form method="post" action="/library/editor/items/${e(item.id)}/file/remove" class="inline">${csrfInput(csrf)}<button type="submit">${e(t.removeFile)}</button></form>` : ""}
|
|
<form method="post" action="/library/editor/items/${e(item.id)}/file" enctype="multipart/form-data" class="f">${csrfInput(csrf)}<label for="f-file">${e(t.fieldFile)}</label><input id="f-file" type="file" name="file" accept=".pdf,.epub,application/pdf,application/epub+zip" required>
|
|
<fieldset><legend>${e(t.fieldRights)}</legend>${radio("rights", "own", t.rightsOwn, item.rightsBasis === "own")}${radio("rights", "licensed", t.rightsLicensed, item.rightsBasis === "licensed")}${radio("rights", "public_domain", t.rightsPublicDomain, item.rightsBasis === "public_domain")}</fieldset>
|
|
<p><button type="submit">${e(t.upload)}</button></p></form>`
|
|
: "";
|
|
const links = `<p><a href="/library/editor">${e(t.backToEditor)}</a>${item ? ` · <a href="/library/items/${e(item.id)}">${e(t.preview)}</a>` : ""}</p>`;
|
|
return shell(
|
|
t,
|
|
{ lang, title: `${item?.title ?? t.newMaterial} — ${t.editorTitle}`, switchPath: item ? `/library/editor/items/${item.id}` : "/library/editor/items/new" },
|
|
`<h1>${e(item?.title ?? t.newMaterial)}</h1>${links}${err(opts.error)}${opts.saved ? `<p class="ok" role="status">${e(t.saved)}</p>` : ""}${main}${file}`,
|
|
);
|
|
}
|