// Play editor: one original page at a time, next to its photo, plus a // click-through review of the words the model was unsure of. // // The play is still stored as one markup file; here it is split at the page // markers (=N / !N) into page objects and joined back on save. meta.photos // says which photo belongs to which page marker, in text order. import { api, withLogin, getPassword, askPassword, authButton, esc, $ } from "./api.js"; import { parsePlay, speakers, lint, plainText } from "./parse.js"; import { toJpeg } from "./photos.js"; const id = new URLSearchParams(location.search).get("id"); const enc = encodeURIComponent(id); let cfg, meta; let pages = []; // [{ key, num, missing, body, photo }] let cur = 0; let saved = { text: "", photos: "" }; let leaving = false; let nextKey = 1; // ---- text <-> pages function splitPages(text, photos, images) { const out = []; let page = null; for (const line of text.replace(/\r/g, "").split("\n")) { if (/^[=!]/.test(line)) { page = { key: nextKey++, num: line.slice(1).trim(), missing: line[0] === "!", lines: [] }; out.push(page); } else { if (!page) { page = { key: nextKey++, num: "?", missing: false, lines: [] }; out.push(page); } page.lines.push(line); } } let k = 0; for (const [i, p] of out.entries()) { p.body = p.lines.join("\n").replace(/^\n+|\s+$/g, ""); delete p.lines; // plays transcribed before meta.photos existed: the n-th page is the n-th photo p.photo = photos ? photos[i] ?? null : !p.missing && k < images ? ++k : null; } return out; } const joinPages = () => pages.map((p) => `${p.missing ? "!" : "="}${p.num}${p.body ? `\n${p.body}` : ""}`).join("\n") + "\n"; const photoList = () => pages.map((p) => p.photo ?? null); const isDirty = () => joinPages() !== saved.text || JSON.stringify(photoList()) !== saved.photos || $("title").value !== meta.title || $("note").value !== (meta.note || "") || $("published").checked !== meta.published; const markSaved = () => { saved = { text: joinPages(), photos: JSON.stringify(photoList()) }; }; const UNC = /\{([^{}\n]*)\}/g; const uncertainIn = (body) => [...body.matchAll(UNC)]; const isFailed = (p) => /^>\(Stranu se nepodařilo přepsat/m.test(p.body); const pageInt = (num) => (/^\d+/.test(num) ? parseInt(num, 10) : null); const plural = (n, one, few, many) => `${n} ${n === 1 ? one : n >= 2 && n <= 4 ? few : many}`; const label = (p) => (p.num && p.num !== "?" ? p.num : "?"); function showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; if (msg) $("error").scrollIntoView({ block: "nearest" }); } function changed() { $("saved").textContent = isDirty() ? "Neuložené změny" : $("saved").dataset.at || ""; } // ---- photos (drafts' photos need the password header, so fetch them as blobs) const photoUrls = new Map(); function photoUrl(n) { if (!photoUrls.has(n)) photoUrls.set(n, api(`plays/${enc}/images/${n}`, { raw: true }).then((r) => r.blob()).then((b) => URL.createObjectURL(b)) .catch((err) => { photoUrls.delete(n); throw err; })); return photoUrls.get(n); } async function setPhoto(imgEl, n) { imgEl.removeAttribute("src"); imgEl.dataset.n = n || ""; if (!n) return; try { const url = await photoUrl(n); if (imgEl.dataset.n === String(n)) imgEl.src = url; // still the wanted photo } catch (err) { showError(`Fotku se nepodařilo načíst: ${err.message}`); } } // ---- rendering function renderList() { $("page-list").innerHTML = pages.map((p, i) => { const n = uncertainIn(p.body).length; const cls = [i === cur && "current", p.missing && "missing", isFailed(p) && "failed"].filter(Boolean).join(" "); const title = p.missing ? "chybí v originále" : isFailed(p) ? "přepis se nepovedl" : n ? `${n} nejistých slov` : ""; return `
  • `; }).join(""); $("page-list").querySelector(".current")?.scrollIntoView({ block: "nearest", inline: "nearest" }); } function renderPage() { const p = pages[cur]; const has = Boolean(p); $("editor").classList.toggle("empty", !has); if (!has) return; $("num").value = p.num; $("missing").checked = p.missing; $("prev").disabled = cur === 0; $("next").disabled = cur === pages.length - 1; $("missing-hint").hidden = !p.missing || Boolean(p.body); $("hl-wrap").hidden = p.missing && !p.body; $("text").value = p.body; paintText(); $("reread").hidden = !(cfg.transcription && p.photo); $("reread").textContent = isFailed(p) ? "Zkusit přepsat znovu" : "Přepsat znovu z fotky"; $("reread").classList.toggle("primary", isFailed(p)); // photo $("photo-select").innerHTML = `` + Array.from({ length: meta.images }, (_, i) => ``).join(""); $("photo-select").value = p.photo || ""; $("photo-pane").hidden = !meta.images; $("editor").classList.toggle("no-photos", !meta.images); $("photo-empty").hidden = Boolean(p.photo); $("img").hidden = !p.photo; $("img").alt = `Fotka strany ${label(p)}`; $("photo-frame").classList.remove("zoomed"); setPhoto($("img"), p.photo); // other photos of the same page, left out after transcription const dups = (meta.duplicates || []).filter((d) => d.page === p.num && d.image !== p.photo); $("dup-note").hidden = !dups.length; $("dup-note").innerHTML = dups.length ? `Tato strana byla nahraná vícekrát; použitá je fotka ${p.photo ?? "?"}. ` + dups.map((d) => ``).join(" · ") : ""; } // The highlight layer behind the textarea marks the {uncertain} words. function paintText() { const ta = $("text"); const v = ta.value; let html = ""; let last = 0; for (const m of v.matchAll(UNC)) { html += esc(v.slice(last, m.index)) + `${esc(m[0])}`; last = m.index + m[0].length; } $("hl-back").innerHTML = html + esc(v.slice(last)) + "\n "; ta.style.height = "auto"; ta.style.height = `${Math.max(ta.scrollHeight, 320)}px`; } function check() { const text = joinPages(); const parsed = parsePlay(text, { plain: true }); const real = parsed.filter((p) => !p.missing); const cast = speakers(parsed); const unsure = pages.reduce((n, p) => n + (p.missing ? 0 : uncertainIn(p.body).length), 0); const issues = [ ...pages.flatMap((p, i) => (isFailed(p) ? [{ i, message: "přepis se nepovedl" }] : [])), ...lint(parsePlay(text)).map((x) => ({ i: pages.findIndex((p) => p.num === x.page), message: x.message })), ]; // Names used only once are often misreadings of another name. for (const c of cast) if (c.count === 1 && cast.length > 2) issues.push({ i: pages.findIndex((p) => plainText(p.body).split("\n").some((l) => l.trim() === `@${c.name}`)), message: `postava „${c.name}“ mluví jen jednou – překlep?` }); $("summary").textContent = `${plural(real.length, "strana", "strany", "stran")}, ${plural(cast.length, "postava", "postavy", "postav")}` + `${cast.length ? `: ${cast.map((c) => c.name).join(", ")}` : ""}${issues.length ? ` · ${plural(issues.length, "upozornění", "upozornění", "upozornění")}` : ""}`; $("issues").innerHTML = issues.length ? issues.slice(0, 200).map((x, k) => `
  • `).join("") : `
  • Žádné problémy nenalezeny.
  • `; $("issues").onclick = (e) => { const b = e.target.closest("button[data-k]"); if (b && issues[b.dataset.k].i >= 0) go(issues[b.dataset.k].i); }; $("retry").hidden = !(meta.failedPages?.length && !meta.edited && cfg.transcription); $("review-bar").hidden = !unsure; $("review-count").textContent = unsure === 1 ? "Model si není jistý 1 slovem." : `Model si není jistý ${unsure} slovy.`; changed(); } function go(i) { if (!pages.length) return; cur = Math.max(0, Math.min(pages.length - 1, i)); renderList(); renderPage(); } // Keep pages in page-number order; unnumbered ones stay after the page before them. function sortPages() { const keep = pages[cur]; let anchor = -1; const keyed = pages.map((p, idx) => { const n = pageInt(p.num); if (n !== null) anchor = n; return { p, idx, key: n !== null ? n : anchor + 0.5 }; }); keyed.sort((a, b) => a.key - b.key || a.idx - b.idx); pages = keyed.map((k) => k.p); cur = pages.indexOf(keep); } // Put a page in, filling a "missing" marker for its number if there is one // (a range !5-8 is split around it). function insertPage(page) { const n = pageInt(page.num); if (n !== null) { const at = pages.findIndex((p) => p.missing && !p.body && rangeOf(p.num)?.includes(n)); if (at >= 0) { const [a, b] = rangeOf(pages[at].num).bounds; const parts = []; if (a < n) parts.push({ key: nextKey++, num: a === n - 1 ? `${a}` : `${a}-${n - 1}`, missing: true, body: "", photo: null }); parts.push(page); if (n < b) parts.push({ key: nextKey++, num: n + 1 === b ? `${b}` : `${n + 1}-${b}`, missing: true, body: "", photo: null }); pages.splice(at, 1, ...parts); cur = pages.indexOf(page); return; } } pages.splice(cur + 1, 0, page); cur += 1; sortPages(); } function rangeOf(num) { const m = /^(\d+)(?:\s*-\s*(\d+))?$/.exec(num); if (!m) return null; const a = Number(m[1]), b = Number(m[2] || m[1]); return { bounds: [a, b], includes: (n) => n >= a && n <= b }; } // ---- review of uncertain words let review = { items: [], i: 0, changed: false }; function collectUncertain() { const items = []; pages.forEach((p, pi) => { if (p.missing) return; for (const m of uncertainIn(p.body)) { items.push({ pi, start: m.index, raw: m[0], options: m[1].split("|").map((s) => s.trim()).filter(Boolean) }); } }); return items; } // Starts at the current page; "again" goes back over the skipped ones from the top. function openReview(again = false) { review.items = collectUncertain(); review.i = again ? 0 : Math.max(0, review.items.findIndex((x) => x.pi >= cur)); review.changed = false; if (!$("review").open) $("review").showModal(); showReviewItem(); } function showReviewItem() { // skip over items already passed over in this round const item = review.items[review.i]; $("review-item").hidden = !item; $("review-done").hidden = Boolean(item); if (!item) { const left = collectUncertain().length; $("review-done-text").textContent = left ? `Hotovo. Označen${left === 1 ? "é zůstalo 1 přeskočené slovo" : `ých zůstává ${plural(left, "", "přeskočená slova", "přeskočených slov").trim()}`}.` : "Hotovo, všechna nejistá slova jsou zkontrolovaná."; $("review-again").hidden = !left; $("review-finish").focus(); return; } const p = pages[item.pi]; const remaining = review.items.length - review.i; $("review-where").textContent = `Strana ${label(p)} · zbývá ${remaining}`; // context: the line with the word, and its neighbours const body = p.body; const lineStart = body.lastIndexOf("\n", item.start - 1) + 1; let lineEnd = body.indexOf("\n", item.start); if (lineEnd < 0) lineEnd = body.length; const lines = body.split("\n"); const lineNo = body.slice(0, item.start).split("\n").length - 1; const show = (s) => esc(s.replace(UNC, (m, inner) => inner.split("|")[0])); const before = lines[lineNo - 1], after = lines[lineNo + 1]; $("review-context").innerHTML = (before !== undefined ? `
    ${show(before)}
    ` : "") + `
    ${show(body.slice(lineStart, item.start))}${esc(item.options[0] || "")}${show(body.slice(item.start + item.raw.length, lineEnd))}
    ` + (after !== undefined ? `
    ${show(after)}
    ` : ""); $("review-fix").value = item.options[0] || ""; $("review-alts").innerHTML = item.options.length > 1 ? `Možnosti: ` + item.options.map((o) => ``).join("") : ""; $("review-prev").disabled = review.i === 0; $("review-fix").focus(); $("review-fix").select(); // photo, zoomed to about where the line is (typescript lines are evenly spaced) const box = $("review-photo"); $("review-nophoto").hidden = Boolean(p.photo); $("review-img").hidden = !p.photo; $("review-band").hidden = !p.photo; const place = () => { const img = $("review-img"); if (!img.naturalHeight) return; const frac = (lineNo + 1.5) / (lines.length + 3); // a little margin top and bottom const y = frac * img.clientHeight; $("review-band").style.top = `${y - 0.03 * img.clientHeight}px`; $("review-band").style.height = `${0.06 * img.clientHeight}px`; const col = (item.start - lineStart) / Math.max(1, Math.max(...lines.map((l) => l.length))); box.scrollTo({ top: y - box.clientHeight / 2, left: (0.1 + 0.8 * col) * img.clientWidth - box.clientWidth / 2, behavior: "smooth" }); }; $("review-img").onload = place; if ($("review-img").dataset.n === String(p.photo) && $("review-img").complete) place(); else setPhoto($("review-img"), p.photo); } function resolveItem(value) { const item = review.items[review.i]; const p = pages[item.pi]; if (p.body.slice(item.start, item.start + item.raw.length) !== item.raw) return; // text changed underneath p.body = p.body.slice(0, item.start) + value + p.body.slice(item.start + item.raw.length); review.changed = true; // later items on the same page moved const shift = value.length - item.raw.length; review.items.splice(review.i, 1); for (const x of review.items) if (x.pi === item.pi && x.start > item.start) { x.start += shift; } showReviewItem(); } async function closeReview() { if ($("review").open) $("review").close(); renderList(); renderPage(); check(); if (review.changed) { review.changed = false; await save(); } } // ---- saving and server actions async function save() { showError(""); $("save").disabled = true; try { await withLogin(async () => { const text = joinPages(); if (text !== saved.text) meta = await api(`plays/${enc}/text`, { method: "PUT", body: text, type: "text/plain; charset=utf-8" }); meta = await api(`plays/${enc}`, { method: "PATCH", body: { title: $("title").value, note: $("note").value, published: $("published").checked, photos: photoList(), duplicates: meta.duplicates } }); markSaved(); }); $("saved").dataset.at = `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 reread() { const p = pages[cur]; if (p.body && !isFailed(p) && !confirm("Text této strany se nahradí novým přepisem z fotky. Pokračovat?")) return; const btn = $("reread"); btn.disabled = true; btn.textContent = "Přepisuji…"; try { const r = await withLogin(() => api(`plays/${enc}/images/${p.photo}/transcribe`, { method: "POST" })); p.body = r.body; if ((!p.num || p.num === "?") && r.num !== "?") { p.num = r.num; sortPages(); } renderList(); renderPage(); check(); } catch (err) { showError(err.message); } finally { btn.disabled = false; renderPage(); } } async function addFromPhoto(file) { showError(""); const lbl = $("add-photo-label"); lbl.classList.add("busy"); try { const jpeg = await toJpeg(file); const n = meta.images + 1; meta = await withLogin(() => api(`plays/${enc}/images/${n}`, { method: "PUT", body: jpeg, type: "image/jpeg" })); let page = { key: nextKey++, num: "?", missing: false, body: "", photo: n }; if (cfg.transcription) { lbl.firstChild.textContent = "Přepisuji…"; const r = await api(`plays/${enc}/images/${n}/transcribe`, { method: "POST" }); page = { ...page, num: r.num, body: r.body }; } const same = pages.findIndex((p) => !p.missing && p.num === page.num && page.num !== "?"); if (same >= 0 && confirm(`Strana ${page.num} už v textu je. Nahradit ji novým přepisem? (Zrušit = přidat ji jako další stranu.)`)) { pages[same] = { ...page, key: pages[same].key }; cur = same; } else insertPage(page); renderList(); renderPage(); check(); if (!cfg.transcription) $("num").focus(); } catch (err) { showError(err.message); } finally { lbl.classList.remove("busy"); lbl.firstChild.textContent = "+ Z fotky"; } } async function waitForJob() { $("editor").classList.add("busy"); $("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; $("editor").classList.remove("busy"); $("save").disabled = false; await loadText(); if (meta.jobError) showError(`Přepis se nepovedl: ${meta.jobError}`); } async function loadText() { const text = await api(`plays/${enc}/text`); pages = splitPages(text, meta.photos, meta.images); // uploaded without transcription: start with one empty page per photo if (!text.trim() && meta.images) pages = Array.from({ length: meta.images }, (_, i) => ({ key: nextKey++, num: String(i + 1), missing: false, body: "", photo: i + 1 })); markSaved(); go(Math.min(cur, pages.length - 1)); check(); } // ---- wiring function wire() { $("page-list").addEventListener("click", (e) => { const b = e.target.closest("button[data-i]"); if (b) go(Number(b.dataset.i)); }); $("prev").addEventListener("click", () => go(cur - 1)); $("next").addEventListener("click", () => go(cur + 1)); let timer; $("text").addEventListener("input", () => { pages[cur].body = $("text").value; paintText(); clearTimeout(timer); timer = setTimeout(() => { renderList(); check(); }, 400); changed(); }); $("num").addEventListener("change", () => { pages[cur].num = $("num").value.trim().replace(/^[=!]/, "") || "?"; sortPages(); renderList(); renderPage(); check(); }); $("missing").addEventListener("change", () => { pages[cur].missing = $("missing").checked; renderList(); renderPage(); check(); }); $("photo-select").addEventListener("change", () => { pages[cur].photo = Number($("photo-select").value) || null; renderPage(); changed(); }); $("photo-frame").addEventListener("click", (e) => { const f = $("photo-frame"); if ($("img").hidden) return; const r = $("img").getBoundingClientRect(); const fx = (e.clientX - r.left) / r.width, fy = (e.clientY - r.top) / r.height; f.classList.toggle("zoomed"); if (f.classList.contains("zoomed")) f.scrollTo(fx * $("img").clientWidth - f.clientWidth / 2, fy * $("img").clientHeight - f.clientHeight / 2); }); $("dup-note").addEventListener("click", (e) => { const b = e.target.closest("button[data-dup]"); if (!b) return; const p = pages[cur]; const d = meta.duplicates.find((x) => x.image === Number(b.dataset.dup) && x.page === p.num); // swap: the photo shown now becomes the left-out one [d.image, p.photo] = [p.photo, d.image]; [d.body, p.body] = [p.body, d.body]; d.kept = p.photo; renderList(); renderPage(); check(); }); $("reread").addEventListener("click", reread); $("remove").addEventListener("click", () => { const p = pages[cur]; if (p.body && !confirm(`Smazat stranu ${label(p)} i s jejím textem?`)) return; if (pages.length === 1) Object.assign(p, { num: "1", missing: false, body: "", photo: null }); // keep one page to type into else pages.splice(cur, 1); go(Math.min(cur, pages.length - 1)); check(); }); $("add-blank").addEventListener("click", () => { const n = pageInt(pages[cur]?.num || ""); insertPage({ key: nextKey++, num: n !== null ? String(n + 1) : "?", missing: false, body: "", photo: null }); renderList(); renderPage(); check(); $("text").focus(); }); $("add-photo").addEventListener("change", (e) => { const f = e.target.files[0]; e.target.value = ""; if (f) addFromPhoto(f); }); $("title").addEventListener("input", changed); $("note").addEventListener("input", changed); $("published").addEventListener("change", changed); $("save").addEventListener("click", save); document.addEventListener("keydown", (e) => { if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); save(); } if (e.altKey && !$("review").open && (e.key === "ArrowLeft" || e.key === "ArrowRight")) { e.preventDefault(); go(cur + (e.key === "ArrowLeft" ? -1 : 1)); } }); // review $("review-start").addEventListener("click", () => openReview()); $("review-form").addEventListener("submit", (e) => { e.preventDefault(); if (review.items[review.i]) resolveItem($("review-fix").value); }); $("review-alts").addEventListener("click", (e) => { const b = e.target.closest("[data-alt]"); if (b) resolveItem(b.dataset.alt); }); $("review-skip").addEventListener("click", () => { review.i++; showReviewItem(); }); $("review-prev").addEventListener("click", () => { review.i = Math.max(0, review.i - 1); showReviewItem(); }); $("review-again").addEventListener("click", () => openReview(true)); $("review-finish").addEventListener("click", closeReview); $("review-close").addEventListener("click", closeReview); $("review").addEventListener("cancel", (e) => { e.preventDefault(); closeReview(); }); $("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" && isDirty()) e.preventDefault(); }); } async function main() { if (!id) { location.replace("./"); return; } cfg = await api("config"); await authButton($("auth"), { uploads: cfg.uploads, onChange: (inn) => { if (!inn) { leaving = true; location.replace("./"); } } }); 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`; wire(); await loadText(); if (meta.status === "processing") await waitForJob(); } main().catch((err) => showError(err.status === 404 ? "Hra nenalezena." : err.message));