- Replace the static nginx site with a small Node server: serves public/, stores plays on a /data volume and exposes a JSON API. Writes need a shared UPLOAD_PASSWORD; unpublished plays are hidden without it. - Page photos (shrunk to <=1.15 MP JPEG in the browser) are transcribed one request per page by a Claude vision model (claude-haiku-5-5 by default, CLAUDE_MODEL to change) into the play markup, then stitched together: speaker spellings unified, gaps in page numbers marked as missing pages, failed pages flagged. DAILY_PAGE_LIMIT caps spend. - New pages: library (play menu), add (upload + progress), editor (text next to the photos, checks for [?] readings and one-off names, publish, delete). The reader loads plays from the API and remembers the chosen role per play; old /?postava= links still work. - PDF export: text now flows across original pages and prints at the on-screen size, so A4 sheets are full instead of half empty; page numbers in the footer. - docker-compose.yml + .env.example for one-click deploys; the 1931 play moves to seed/ and is copied into an empty volume on first start. - Tests: parser leniency, transcription assembly, API end to end with a stubbed Claude client. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
166 lines
7 KiB
JavaScript
166 lines
7 KiB
JavaScript
import { api, withLogin, getPassword, askPassword, esc, $ } from "./api.js";
|
||
import { parsePlay, speakers, lint } from "./parse.js";
|
||
|
||
const id = new URLSearchParams(location.search).get("id");
|
||
const enc = encodeURIComponent(id);
|
||
let meta;
|
||
let savedText = "";
|
||
let img = 1;
|
||
let leaving = false;
|
||
|
||
const dirty = () => $("text").value !== savedText
|
||
|| $("title").value !== meta.title || $("note").value !== (meta.note || "") || $("published").checked !== meta.published;
|
||
|
||
function showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; }
|
||
|
||
function check() {
|
||
let pages;
|
||
try { pages = parsePlay($("text").value); }
|
||
catch (err) { $("summary").textContent = err.message; return; }
|
||
const real = pages.filter((p) => !p.missing);
|
||
const cast = speakers(pages);
|
||
$("summary").textContent = `${real.length} stran, ${cast.length} postav: ${cast.map((c) => c.name).join(", ") || "—"}`;
|
||
const issues = [
|
||
...(meta.failedPages || []).map((f) => ({ page: null, image: f.image, message: `Fotku ${f.image} se nepodařilo přepsat: ${f.error}` })),
|
||
...lint(pages),
|
||
];
|
||
// Names used only once are often misreadings of another name.
|
||
for (const c of cast) if (c.count === 1 && cast.length > 2) issues.push({ page: null, find: `@${c.name}`, message: `Postava „${c.name}“ mluví jen jednou – překlep?` });
|
||
$("issues").innerHTML = issues.length
|
||
? issues.slice(0, 200).map((x, i) => `<li><button class="link" data-i="${i}">${x.page && x.page !== "?" ? `str. ${esc(x.page)}: ` : ""}${esc(x.message)}</button></li>`).join("")
|
||
: `<li class="muted">Žádné problémy nenalezeny.</li>`;
|
||
$("issues").onclick = (e) => {
|
||
const b = e.target.closest("button[data-i]");
|
||
if (!b) return;
|
||
const x = issues[Number(b.dataset.i)];
|
||
if (x.image) showImage(x.image);
|
||
else jumpTo(x.find || (x.page && x.page !== "?" ? `=${x.page}` : null), x.message.match(/„(.*)“/)?.[1]);
|
||
};
|
||
$("retry").hidden = !(meta.failedPages?.length && !meta.edited);
|
||
}
|
||
|
||
// Select `needle` (or the line containing `inner`) in the textarea and scroll it into view.
|
||
function jumpTo(needle, inner) {
|
||
const ta = $("text");
|
||
const v = ta.value;
|
||
let at = -1;
|
||
if (needle) at = needle.startsWith("=") ? (`\n${v}`).indexOf(`\n${needle}\n`) : v.indexOf(needle);
|
||
if (at < 0 && inner) at = v.indexOf(inner);
|
||
if (at < 0) return;
|
||
const len = (needle && v.startsWith(needle, at) ? needle : inner || "").length;
|
||
ta.focus();
|
||
ta.setSelectionRange(at, at + len);
|
||
// scroll: put the selected line about a third from the top
|
||
const lineNo = v.slice(0, at).split("\n").length - 1;
|
||
const lh = parseFloat(getComputedStyle(ta).lineHeight) || 20;
|
||
ta.scrollTop = Math.max(0, lineNo * lh - ta.clientHeight / 3);
|
||
}
|
||
|
||
// Drafts' photos need the password header, which <img src> can't send, so fetch them as blobs.
|
||
let imgUrl = null;
|
||
async function showImage(n) {
|
||
if (!meta.images) return;
|
||
img = Math.min(meta.images, Math.max(1, n));
|
||
$("photo-box").hidden = false;
|
||
const shown = img;
|
||
api(`plays/${enc}/images/${img}`, { raw: true }).then((r) => r.blob()).then((b) => {
|
||
if (shown !== img) return; // user already moved on
|
||
if (imgUrl) URL.revokeObjectURL(imgUrl);
|
||
imgUrl = URL.createObjectURL(b);
|
||
$("img").src = imgUrl;
|
||
}).catch((err) => showError(`Fotku se nepodařilo načíst: ${err.message}`));
|
||
$("img-label").textContent = `fotka ${img} / ${meta.images}`;
|
||
$("img-prev").disabled = img === 1;
|
||
$("img-next").disabled = img === meta.images;
|
||
}
|
||
|
||
// The page number the model read from photo n, to find it in the text.
|
||
function pageOfImage(n) {
|
||
const text = $("text").value;
|
||
const markers = [...text.matchAll(/^=(.+)$/gm)].map((m) => m[1]);
|
||
return markers[n - 1];
|
||
}
|
||
|
||
async function save() {
|
||
showError("");
|
||
$("save").disabled = true;
|
||
try {
|
||
await withLogin(async () => {
|
||
if ($("text").value !== savedText) {
|
||
meta = await api(`plays/${enc}/text`, { method: "PUT", body: $("text").value, type: "text/plain; charset=utf-8" });
|
||
savedText = $("text").value;
|
||
}
|
||
meta = await api(`plays/${enc}`, { method: "PATCH", body: { title: $("title").value, note: $("note").value, published: $("published").checked } });
|
||
});
|
||
$("saved").textContent = `Uloženo ${new Date().toLocaleTimeString("cs-CZ", { hour: "2-digit", minute: "2-digit" })}`;
|
||
check();
|
||
} catch (err) {
|
||
showError(`Uložení se nepovedlo: ${err.message}`);
|
||
} finally {
|
||
$("save").disabled = false;
|
||
}
|
||
}
|
||
|
||
async function waitForJob() {
|
||
$("text").readOnly = true;
|
||
$("save").disabled = true;
|
||
$("progress").hidden = false;
|
||
while (meta.status === "processing") {
|
||
const p = meta.progress || { done: 0, total: meta.images };
|
||
$("status").textContent = `Přepisuji stranu ${Math.min(p.done + 1, p.total)} z ${p.total}… (stránku můžete zavřít, přepis poběží dál)`;
|
||
$("bar").value = p.total ? p.done / p.total : 0;
|
||
await new Promise((r) => setTimeout(r, 2000));
|
||
meta = await api(`plays/${enc}`);
|
||
}
|
||
$("progress").hidden = true;
|
||
$("text").readOnly = false;
|
||
$("save").disabled = false;
|
||
savedText = await api(`plays/${enc}/text`);
|
||
$("text").value = savedText;
|
||
if (meta.jobError) showError(`Přepis se nepovedl: ${meta.jobError}`);
|
||
check();
|
||
}
|
||
|
||
async function main() {
|
||
if (!id) { location.replace("./"); return; }
|
||
if (!getPassword() && !(await askPassword("Upravovat hry může jen ten, kdo zná heslo."))) { location.replace("./"); return; }
|
||
meta = await withLogin(() => api(`plays/${enc}`));
|
||
$("preview").href = `read.html?hra=${enc}`;
|
||
$("title").value = meta.title;
|
||
$("note").value = meta.note || "";
|
||
$("published").checked = meta.published;
|
||
document.title = `${meta.title} – úpravy`;
|
||
savedText = await api(`plays/${enc}/text`);
|
||
$("text").value = savedText;
|
||
if (meta.images) showImage(1);
|
||
check();
|
||
|
||
let timer;
|
||
$("text").addEventListener("input", () => { clearTimeout(timer); timer = setTimeout(check, 400); });
|
||
$("text").addEventListener("keydown", (e) => {
|
||
if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); save(); }
|
||
});
|
||
$("save").addEventListener("click", save);
|
||
$("img-prev").addEventListener("click", () => showImage(img - 1));
|
||
$("img-next").addEventListener("click", () => showImage(img + 1));
|
||
$("img-jump").addEventListener("click", () => { const p = pageOfImage(img); if (p) jumpTo(`=${p}`); });
|
||
$("retry").addEventListener("click", async () => {
|
||
try {
|
||
meta = await withLogin(() => api(`plays/${enc}/transcribe`, { method: "POST" }));
|
||
await waitForJob();
|
||
} catch (err) { showError(err.message); }
|
||
});
|
||
$("delete").addEventListener("click", async () => {
|
||
if (!confirm(`Opravdu smazat hru „${meta.title}“ i s fotkami? Nejde to vrátit.`)) return;
|
||
try {
|
||
await withLogin(() => api(`plays/${enc}`, { method: "DELETE" }));
|
||
leaving = true;
|
||
location.replace("./");
|
||
} catch (err) { showError(err.message); }
|
||
});
|
||
window.addEventListener("beforeunload", (e) => { if (!leaving && meta.status !== "processing" && dirty()) e.preventDefault(); });
|
||
|
||
if (meta.status === "processing") await waitForJob();
|
||
}
|
||
|
||
main().catch((err) => showError(err.status === 404 ? "Hra nenalezena." : err.message));
|