theater-reader/public/reader.js
agent 46aa1236ed Let people add plays from photos; library, editor, compose; full-page PDF
- 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
2026-11-03 09:43:32 +00:00

215 lines
9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { parsePlay, speakers, joinLines, tidySpacing } from "./parse.js";
import { api, getPassword, esc, $ } from "./api.js";
const FONTS = [
{ id: "courier", label: "Psací stroj", family: "'Courier Prime', 'Courier New', monospace", mono: true },
{ id: "atkinson", label: "Nejčitelnější", family: "'Atkinson Hyperlegible', system-ui, sans-serif" },
{ id: "lexend", label: "Lexend (dyslexie)", family: "Lexend, system-ui, sans-serif" },
{ id: "literata", label: "Knižní", family: "Literata, Georgia, serif" },
{ id: "system", label: "Systémové", family: "system-ui, -apple-system, 'Segoe UI', sans-serif" },
];
const STORE_KEY = "theater-reader:v1";
const DEFAULTS = { roles: {}, role: "", font: "atkinson", size: 19, layout: "flow", theme: "light" };
let settings = loadSettings();
let play = null; // meta of the open play
let pages = [];
let mine = []; // the selected role's speech elements, in order
let current = -1;
function loadSettings() {
let saved = {};
try { saved = JSON.parse(localStorage.getItem(STORE_KEY)) || {}; } catch { /* private mode etc. */ }
const s = { ...DEFAULTS, ...saved };
// ?postava=Lída lets a director send each actor a ready link
const q = new URLSearchParams(location.search);
s.urlRole = q.get("postava"); // the role is remembered per play, a link can override it
return s;
}
function save() {
if (play) settings.roles = { ...settings.roles, [play.id]: settings.role };
const { role, urlRole, ...stored } = settings;
try { localStorage.setItem(STORE_KEY, JSON.stringify(stored)); } catch { /* ignore */ }
const q = new URLSearchParams(location.search);
if (settings.role) q.set("postava", settings.role); else q.delete("postava");
if (play) q.set("hra", play.id);
const qs = q.toString();
history.replaceState(null, "", qs ? `?${qs}` : location.pathname);
}
function renderPart(part, flow) {
const cls = { text: "t", stage: "stage", verse: "verse" }[part.kind];
let html;
if (part.kind === "verse" || !flow) html = part.lines.map(esc).join("<br>");
else html = esc(tidySpacing(joinLines(part.lines)));
return `<p class="${cls}">${html}</p>`;
}
function renderBlock(b, flow, role) {
const parts = (ps) => ps.map((p) => renderPart(p, flow)).join("");
switch (b.type) {
case "speech": {
const isMine = role && b.speaker === role;
return `<div class="speech${isMine ? " mine" : ""}${b.cont ? " cont" : ""}" data-speaker="${esc(b.speaker)}">
<div class="who">${b.cont ? "" : esc(b.speaker)}</div><div class="say">${parts(b.parts)}</div></div>`;
}
case "direction":
return `<div class="speech direction"><div class="who"></div><div class="say">${parts(b.parts)}</div></div>`;
case "scene":
return `<p class="scene">${flow ? esc(tidySpacing(joinLines(b.lines))) : b.lines.map(esc).join("<br>")}</p>`;
case "center":
return `<p class="center">${esc(b.text)}</p>`;
case "gap":
return `<div class="gap"></div>`;
}
return "";
}
function renderScript() {
const flow = settings.layout === "flow";
const html = pages.map((p) => {
if (p.missing) {
return `<section class="page missing"><div class="pnum">-${esc(p.num.replace("-", "–"))}-</div>
<p class="missing-note">Strana ${esc(p.num.replace("-", "–"))} v předloze chybí.</p></section>`;
}
return `<section class="page" data-page="${esc(p.num)}"><div class="pnum">-${esc(p.num)}-</div>
${p.blocks.map((b) => renderBlock(b, flow, settings.role)).join("")}</section>`;
}).join("");
$("script").innerHTML = html;
mine = [...document.querySelectorAll(".speech.mine")];
current = -1;
updateCounter();
}
function updateCounter() {
const nav = $("lines-nav");
const reading = document.body.classList.contains("reading");
nav.hidden = !reading && !settings.role;
nav.classList.toggle("no-role", !settings.role);
$("counter").textContent = settings.role
? `${current >= 0 ? current + 1 : "–"} / ${mine.length}`
: "";
}
function go(delta) {
if (!mine.length) return;
if (current < 0) {
// start from the first own line below the top of the viewport
const idx = mine.findIndex((el) => el.getBoundingClientRect().top > 80);
current = delta > 0 ? (idx < 0 ? mine.length - 1 : idx) : Math.max(0, (idx < 0 ? mine.length : idx) - 1);
} else {
current = Math.min(mine.length - 1, Math.max(0, current + delta));
}
mine.forEach((el, i) => el.classList.toggle("current", i === current));
mine[current].scrollIntoView({ behavior: "smooth", block: "center" });
updateCounter();
}
function applyLook() {
const font = FONTS.find((f) => f.id === settings.font) || FONTS[1];
const root = document.documentElement;
root.style.setProperty("--script-font", font.family);
root.style.setProperty("--script-size", `${settings.size}px`);
root.dataset.theme = settings.theme;
root.dataset.mono = font.mono ? "1" : "0";
root.dataset.layout = settings.layout;
$("size").value = settings.size;
$("size-out").textContent = `${settings.size} px`;
}
function fillControls() {
$("fonts").innerHTML = FONTS.map((f) => `
<label class="font-card" style="font-family:${f.family}">
<input type="radio" name="font" value="${f.id}"${f.id === settings.font ? " checked" : ""}>
<span class="font-name">${f.label}</span>
<span class="font-sample">Příliš žluťoučký kůň úpěl ďábelské ódy.</span>
</label>`).join("");
document.querySelector(`input[name=layout][value=${settings.layout}]`).checked = true;
document.querySelector(`input[name=theme][value=${settings.theme}]`).checked = true;
}
function fillRoles() {
const roles = speakers(pages);
if (settings.role && !roles.some((r) => r.name === settings.role)) settings.role = "";
$("role").innerHTML = `<option value="">— žádná —</option>` + roles
.map((r) => `<option value="${esc(r.name)}"${r.name === settings.role ? " selected" : ""}>${esc(r.name)} (${r.count})</option>`)
.join("");
}
async function loadPlay(id) {
play = await api(`plays/${encodeURIComponent(id)}`);
settings.role = settings.urlRole ?? settings.roles?.[play.id] ?? "";
document.title = `${play.title} – Divadelní čtečka`;
$("play-title").textContent = play.title;
$("play-note").textContent = play.note || "";
if (getPassword()) {
$("edit-link").href = `edit.html?id=${encodeURIComponent(play.id)}`;
$("edit-link").hidden = false;
}
pages = parsePlay(await api(`plays/${encodeURIComponent(id)}/text`));
fillRoles();
renderScript();
save();
}
function setReading(on) {
document.body.classList.toggle("reading", on);
updateCounter();
if (on) $("script").focus({ preventScroll: true });
}
function exportPdf() {
const before = document.title;
// the browser proposes the document title as the PDF file name
document.title = [play?.title.replace(/\s*\(.*\)/, ""), settings.role].filter(Boolean).join(" – ");
window.print();
document.title = before;
}
function wire() {
$("role").addEventListener("change", (e) => { settings.role = e.target.value; renderScript(); save(); });
$("fonts").addEventListener("change", (e) => { settings.font = e.target.value; applyLook(); save(); });
$("size").addEventListener("input", (e) => { settings.size = +e.target.value; applyLook(); save(); });
document.querySelectorAll("input[name=layout]").forEach((r) =>
r.addEventListener("change", (e) => { settings.layout = e.target.value; applyLook(); renderScript(); save(); }));
document.querySelectorAll("input[name=theme]").forEach((r) =>
r.addEventListener("change", (e) => { settings.theme = e.target.value; applyLook(); save(); }));
$("read").addEventListener("click", () => setReading(true));
$("exit-read").addEventListener("click", () => setReading(false));
$("export").addEventListener("click", exportPdf);
$("next").addEventListener("click", () => go(1));
$("prev").addEventListener("click", () => go(-1));
const resize = (d) => { settings.size = Math.min(30, Math.max(14, settings.size + d)); applyLook(); save(); };
$("smaller").addEventListener("click", () => resize(-1));
$("larger").addEventListener("click", () => resize(1));
document.addEventListener("keydown", (e) => {
if (e.target.matches("input, select, textarea")) return;
if (e.key === "Escape") setReading(false);
else if (e.key === "j" || e.key === "ArrowDown" && e.altKey) go(1);
else if (e.key === "k" || e.key === "ArrowUp" && e.altKey) go(-1);
});
}
async function main() {
applyLook();
fillControls();
wire();
const id = new URLSearchParams(location.search).get("hra");
try {
if (id) await loadPlay(id);
else {
// no play chosen (old link): open the first one
const plays = await api("plays");
if (!plays.length) { location.replace("./"); return; }
await loadPlay(plays[0].id);
}
} catch (err) {
const msg = err.status === 404 ? "Tato hra neexistuje nebo ještě není zveřejněná." : `Text se nepodařilo načíst: ${err.message || err}`;
$("script").innerHTML = `<p class="error">${esc(msg)} <a href="./">Zpět na seznam her</a></p>`;
}
}
main();