theater-reader/public/app.js
agent 2608d10dd2 Add theater reader web app with the 1931 play transcription
Static app (no build step) served by unprivileged nginx in a container:
choose a font, size and theme, pick a character to highlight their lines
and step through them, read in a distraction-free mode, or export a PDF
via the print dialog (one page per original page).

Includes the transcription of typescript pages 5-27 (pages 1-4 and 7
are missing in the original), a parser with node:test tests, and
self-hosted OFL fonts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
2026-10-29 23:14:19 +00:00

211 lines
8.8 KiB
JavaScript
Raw 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";
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 = { play: "", role: "", font: "atkinson", size: 19, layout: "flow", theme: "light" };
const $ = (id) => document.getElementById(id);
let settings = loadSettings();
let plays = [];
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);
if (q.has("postava")) s.role = q.get("postava");
if (q.has("hra")) s.play = q.get("hra");
return s;
}
function save() {
try { localStorage.setItem(STORE_KEY, JSON.stringify(settings)); } catch { /* ignore */ }
const q = new URLSearchParams(location.search);
if (settings.role) q.set("postava", settings.role); else q.delete("postava");
if (plays.length > 1 && settings.play) q.set("hra", settings.play); else q.delete("hra");
const qs = q.toString();
history.replaceState(null, "", qs ? `?${qs}` : location.pathname);
}
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
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() {
const play = plays.find((p) => p.id === settings.play) || plays[0];
settings.play = play.id;
$("play-note").textContent = play.note || "";
const res = await fetch(`plays/${play.file}`);
if (!res.ok) throw new Error(`plays/${play.file}: HTTP ${res.status}`);
pages = parsePlay(await res.text());
fillRoles();
renderScript();
save();
}
function setReading(on) {
document.body.classList.toggle("reading", on);
updateCounter();
if (on) $("script").focus({ preventScroll: true });
}
function exportPdf() {
const play = plays.find((p) => p.id === settings.play);
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(); });
$("play").addEventListener("change", (e) => { settings.play = e.target.value; loadPlay(); });
$("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();
try {
plays = await (await fetch("plays/index.json")).json();
if (plays.length > 1) {
$("play-field").hidden = false;
$("play").innerHTML = plays.map((p) => `<option value="${esc(p.id)}">${esc(p.title)}</option>`).join("");
$("play").value = settings.play || plays[0].id;
}
await loadPlay();
} catch (err) {
$("script").innerHTML = `<p class="error">Text se nepodařilo načíst: ${esc(String(err.message || err))}</p>`;
}
}
main();