From debf1aa8bc061201cbe6ba27a477fd925a94e917 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 4 Nov 2026 16:15:27 +0000 Subject: [PATCH] Edit plays page by page, with a review of uncertain words The editor shows one original page next to its photo, with a page list, page number and missing toggle, and highlights {uncertain} words. The review dialog steps through them with the photo zoomed to about the right line. Pages can be re-read from their photo or added from a new photo, which fills a !N missing marker. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt --- AGENTS.md | 14 +- README.md | 5 +- public/app.css | 157 ++++++++++++-- public/edit.html | 113 +++++++--- public/edit.js | 542 ++++++++++++++++++++++++++++++++++++++--------- 5 files changed, 679 insertions(+), 152 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2ebe005..7b989d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,15 +10,17 @@ UI language is Czech. - `server/main.mjs`: HTTP server, routing, static files, auth (`x-upload-password` header vs `UPLOAD_PASSWORD`), daily page cap, background transcription job. - `server/store.mjs`: plays on disk, `DATA_DIR/plays//{meta.json,play.txt,img/NNN.jpg}`. Atomic writes; per-play lock for meta updates. - `server/providers.mjs`: `makeProvider(env)` returns `{ name, model, transcribe(jpeg) }` for OpenRouter or Anthropic. Errors become `PageError`s whose message is shown in the editor. OpenRouter retries 408/429/5xx and network errors itself. -- `server/transcribe.mjs`: `splitPage` → `normalizeSpeakers` → `assemble` turn the per-photo answers into one play file. `server/prompt.mjs` holds the prompt (shared by both providers), which teaches the markup below. -- `public/`: four pages: `index.html` library (`library.js`), `read.html` reader (`reader.js`), `add.html` upload (`add.js`: shrinks photos to ≤1.15 MP JPEG in the browser), `edit.html` editor (`edit.js`). `api.js` holds the fetch and password helpers. `parse.js` is the markup parser, shared with the server tests. +- `server/transcribe.mjs`: `splitPage` → `normalizeSpeakers` → `assemble` turn the per-photo answers into one play file: sorted by the page number read off each photo, repeats of a page dropped (kept in `meta.duplicates`), and `meta.photos` recording which photo belongs to which page marker. `server/prompt.mjs` holds the prompt (shared by both providers), which teaches the markup below. +- `public/`: four pages: `index.html` library (`library.js`), `read.html` reader (`reader.js`), `add.html` upload (`add.js`: shrinks photos to ≤1.15 MP JPEG in the browser), `edit.html` editor (`edit.js`: splits the text at page markers and edits one page at a time beside its photo; review dialog for `{uncertain}` words). `api.js` holds the fetch, password and login-button helpers, `photos.js` the in-browser JPEG shrinking and duplicate-photo fingerprint. `parse.js` is the markup parser, shared with the server tests. - `seed/`: plays copied into an empty data volume on first start. - `public/fonts/`: self-hosted woff2 + OFL licences, made by `tools/fetch_fonts.py` (keep its `FAMILIES` and `FONTS` in `reader.js` in step). ## API `GET /api/config`, `POST /api/login`, `GET|POST /api/plays`, `GET|PATCH|DELETE /api/plays/:id`, `GET|PUT /api/plays/:id/text`, -`GET|PUT /api/plays/:id/images/:n` (raw `image/jpeg` body), `POST /api/plays/:id/transcribe` (202, then poll the meta's `progress`). +`GET|PUT /api/plays/:id/images/:n` (raw `image/jpeg` body), `POST /api/plays/:id/transcribe` (202, then poll the meta's `progress`), +`POST /api/plays/:id/images/:n/transcribe` (one photo, answers `{ num, body }` and leaves the text alone; the editor inserts it). +`PATCH` takes `title`, `note`, `published`, `photos` (photo number or `null` per page marker, in text order) and `duplicates`. Everything that writes needs the password. Unpublished plays answer 404 without it. Transcription refuses once the text has been edited by hand, so it can't overwrite corrections. @@ -49,6 +51,8 @@ One directive per line; blank lines are ignored. The text keeps the typescript's line breaks, spelling and missing spaces ("dobře.Ale"). The "running text" mode joins hyphenated words (`nepří-` / `jemné`, also the typist's `ne -` / `spokojenců`) and adds the missing spaces. **A dash that really is punctuation at the end of a line must be typed as `–` (en dash)**, or it gets joined to the next word. -`[?]` after a word marks an uncertain reading. The editor lists them. +`{word}` marks an uncertain reading and `{word|other}` adds the model's alternative; the reader shows the first one, and the +editor's review dialog steps through them. (The older `word[?]` form is converted when transcribing.) -To add a missing page to a play, e.g. page 7 of the 1931 play, open it in the editor and replace `!7` with `=7` and the page's text. +To add a missing page to a play, e.g. page 7 of the 1931 play, open it in the editor and use *+ Z fotky*: the photo is +transcribed and fills the `!7` marker. Without a photo, select page 7, untick *v originále chybí* and type the text. diff --git a/README.md b/README.md index 8811c46..161dab8 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,10 @@ A link like `read.html?hra=hra-1931&postava=Lída` opens a play with the charact **Adding plays** (anyone with the upload password): -1. *Přidat hru*: give the title and pick a photo of each page. +1. *Přihlásit* (top right) with the upload password, then *+ Přidat hru*: give the title and pick a photo of each page. The same photo picked twice is skipped. 2. Each photo is read by a vision model, through OpenRouter (default `google/gemini-3.1-flash-lite`) or the Anthropic API (`claude-haiku-5-5`), and turned into the script markup: speakers, stage directions, page numbers. Missing pages are noticed from gaps in the page numbers. -3. The editor shows the text next to the photos and lists things to check (uncertain words marked `[?]`, characters who speak only once, pages that failed). Fix, tick *Zveřejněno*, save. +3. Pages are put in order by the page number on each photo, so upload order doesn't matter, and a page photographed twice is used once (the clearer transcription wins; the editor lets you switch to the other one). +4. The editor shows one page at a time next to its photo. Words the model wasn't sure of are highlighted, and *Projít nejistá slova* steps through them one by one with the photo zoomed to about the right line: Enter accepts, a click picks the model's other reading. A page that failed or a page found later (*+ Z fotky*, which fills a `!7` "missing" marker) can be transcribed on its own. Fix, tick *Zveřejněno*, save. ## Deploying diff --git a/public/app.css b/public/app.css index 438ea44..1654ea7 100644 --- a/public/app.css +++ b/public/app.css @@ -290,7 +290,7 @@ button.link { border: 0; background: none; padding: 0; font: inherit; color: var .play-meta { font-size: 12.5px; color: var(--muted); } .badge { font-size: 12px; font-weight: 600; padding: 1px 8px; border-radius: 999px; background: var(--hl); color: var(--fg); vertical-align: 2px; } -dialog.login { border: 1px solid var(--line); border-radius: 12px; background: var(--bg); color: var(--fg); padding: 20px; width: min(380px, calc(100vw - 32px)); } +dialog.login { border: 1px solid var(--line); border-radius: 12px; background: var(--bg); color: var(--fg); padding: 20px; width: min(400px, calc(100vw - 32px)); } dialog.login h2 { margin: 0 0 8px; font-size: 18px; } dialog::backdrop { background: rgba(0, 0, 0, 0.4); } @@ -320,31 +320,144 @@ form.busy .dropzone, form.busy .thumb-tools { pointer-events: none; opacity: 0.6 .meta-row .grow { flex: 1 1 260px; } .field.toggle { display: flex; align-items: center; gap: 8px; padding-bottom: 8px; } .field.toggle span { margin: 0; } -.editor { display: grid; grid-template-columns: minmax(0, 1fr) minmax(300px, 0.8fr); gap: 16px; align-items: start; } -.editor textarea { - height: calc(100vh - 230px); - min-height: 360px; - font-family: "Courier Prime", ui-monospace, monospace; - font-size: 15px; - line-height: 1.45; - resize: vertical; - tab-size: 4; +.field.toggle input { accent-color: var(--accent); } +.check { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; } +.check input { width: 18px; height: 18px; margin: 0; accent-color: var(--accent); } +.notice { background: var(--hl); border-radius: 8px; padding: 8px 12px; font-size: 14px; } +button.quiet { border-color: transparent; background: transparent; color: var(--muted); } +button.quiet:hover { color: var(--accent); } + +/* login dialog */ +dialog.login .field { margin-bottom: 12px; } +.pw-field { position: relative; display: block; } +.pw-field input { padding-right: 44px; } +.pw-field input[aria-invalid] { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); } +.pw-field .eye { + position: absolute; right: 4px; top: 50%; transform: translateY(-50%); + display: grid; place-items: center; width: 36px; height: 32px; padding: 0; + border: 0; background: transparent; color: var(--muted); } -.editor-side { position: sticky; top: 12px; display: grid; gap: 14px; } -.photo-nav { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; font-size: 14px; } -.photo-nav span { flex: 1; text-align: center; color: var(--muted); } -.photo-nav button { padding: 4px 10px; font-size: 13px; } -.photo img { display: block; width: 100%; max-height: calc(100vh - 330px); object-fit: contain; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; } -.checks h2 { font-size: 16px; margin: 0 0 4px; } -.checks ul { margin: 6px 0 10px; padding-left: 18px; max-height: 220px; overflow-y: auto; font-size: 14px; } +.pw-field .eye:hover, .pw-field .eye[aria-pressed="true"] { color: var(--accent); } +dialog.login .check { margin: 2px 0 4px; font-size: 14.5px; } +dialog.login .error { margin: 10px 0 0; font-size: 14px; } +dialog.login .actions { margin-top: 16px; } + +/* editor */ +.review-bar { + display: flex; align-items: center; gap: 12px; flex-wrap: wrap; + margin: 4px 0 12px; padding: 10px 14px; border-radius: 10px; + background: var(--hl); border: 1px solid var(--hl-edge); +} +.review-bar span { flex: 1; font-weight: 600; } +details.checks { margin: 0 0 14px; font-size: 14px; } +details.checks summary { cursor: pointer; } +details.checks ul { margin: 6px 0 10px; padding-left: 18px; max-height: 220px; overflow-y: auto; } + +.editor { + display: grid; + grid-template-columns: 88px minmax(0, 1fr) minmax(0, 1.1fr); + gap: 16px; + align-items: start; +} +.editor.no-photos { grid-template-columns: 88px minmax(0, 1fr); } +.editor.busy { opacity: 0.5; pointer-events: none; } +.page-list { position: sticky; top: 12px; display: grid; gap: 8px; } +.page-list ol { + list-style: none; margin: 0; padding: 0; + display: grid; gap: 4px; max-height: calc(100vh - 140px); overflow-y: auto; +} +.page-list ol button { + position: relative; width: 100%; padding: 6px 4px; font-size: 14px; text-align: center; + display: flex; justify-content: center; align-items: center; gap: 4px; +} +.page-list ol button.current { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); color: var(--accent); } +.page-list ol button.missing { border-style: dashed; color: var(--muted); font-weight: 400; } +.page-list ol button.failed { border-color: var(--accent); } +.page-list .count { + min-width: 18px; padding: 0 5px; border-radius: 999px; font-size: 11px; line-height: 18px; + background: var(--hl); color: var(--fg); border: 1px solid var(--hl-edge); +} +.page-list .count.bad { background: var(--accent); border-color: var(--accent); color: #fff; } +.page-list-tools { display: grid; gap: 4px; } +.page-list-tools > * { padding: 6px 4px; font-size: 13px; text-align: center; } +.page-list-tools .busy { opacity: 0.6; pointer-events: none; } + +.page-photo { position: sticky; top: 12px; } +.photo-frame { + max-height: calc(100vh - 80px); overflow: auto; cursor: zoom-in; + background: var(--panel); border: 1px solid var(--line); border-radius: 8px; +} +.photo-frame img { display: block; width: 100%; height: auto; } +.photo-frame.zoomed { cursor: zoom-out; } +.photo-frame.zoomed img { width: 220%; max-width: none; } +.photo-empty { padding: 48px 16px; text-align: center; margin: 0; } +.photo-pick { display: inline-flex; align-items: center; gap: 6px; margin-top: 6px; } +.photo-pick select { width: auto; padding: 2px 6px; } + +.page-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 8px; } +.page-head .grow { flex: 1; } +.page-head > button { padding: 6px 10px; font-size: 14px; } +.page-num { display: inline-flex; align-items: center; gap: 6px; font-weight: 700; } +.page-num input { width: 5.5em; padding: 5px 8px; font-weight: 700; text-align: center; } +.page-head .check { font-size: 14px; color: var(--muted); } +.dup-note { margin-bottom: 8px; padding: 8px 12px; border-radius: 8px; background: var(--panel); border: 1px solid var(--line); font-size: 14px; } +.missing-hint { padding: 24px; border: 1px dashed var(--line); border-radius: 8px; text-align: center; } + +/* textarea over a layer that paints the {uncertain} words; both must wrap identically */ +.hl-wrap { position: relative; } +.hl-back, .hl-wrap textarea { + margin: 0; padding: 12px 14px; border: 1px solid var(--line); border-radius: 8px; + font-family: "Courier Prime", ui-monospace, monospace; font-size: 15px; line-height: 1.5; + white-space: pre-wrap; overflow-wrap: break-word; word-break: normal; tab-size: 4; letter-spacing: 0; +} +.hl-back { position: absolute; inset: 0; color: transparent; border-color: transparent; pointer-events: none; overflow: hidden; } +.hl-back mark { color: transparent; background: var(--hl); border-radius: 3px; box-shadow: 0 0 0 1px var(--hl-edge); } +.hl-wrap textarea { + position: relative; display: block; width: 100%; min-height: 320px; + background: transparent; color: var(--fg); resize: none; overflow: hidden; +} +.hl-wrap { background: var(--bg); border-radius: 8px; } .help { font-size: 14px; margin-top: 8px; } .help td { padding: 2px 10px 2px 0; vertical-align: top; } +.danger { margin-top: 32px; } .danger button { color: var(--accent); border-color: var(--accent); background: transparent; } -@media (max-width: 900px) { - .editor { grid-template-columns: minmax(0, 1fr); } - .editor-side { position: static; order: -1; } - .photo img { max-height: 60vh; } - .editor textarea { height: 70vh; } + +/* review of uncertain words */ +dialog.review { + width: min(1100px, calc(100vw - 24px)); max-height: calc(100vh - 24px); padding: 0; + border: 1px solid var(--line); border-radius: 12px; background: var(--bg); color: var(--fg); +} +.review-grid { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(300px, 1fr); min-height: min(640px, calc(100vh - 26px)); } +.review-photo { position: relative; overflow: auto; background: var(--panel); border-right: 1px solid var(--line); max-height: calc(100vh - 26px); } +.review-photo img { display: block; width: 180%; max-width: none; } +.review-band { position: absolute; left: 0; width: 180%; background: rgba(224, 180, 0, 0.18); border-block: 2px solid var(--hl-edge); pointer-events: none; } +.review-card { padding: 18px 20px; display: flex; flex-direction: column; gap: 10px; } +.review-top { display: flex; align-items: center; justify-content: space-between; } +.review-top h2 { margin: 0; font-size: 18px; } +.review-context { + font-family: "Courier Prime", ui-monospace, monospace; font-size: 15px; line-height: 1.6; + padding: 10px 12px; border-radius: 8px; background: var(--panel); overflow-wrap: anywhere; +} +.ctx-line { color: var(--muted); } +.ctx-line.main { color: var(--fg); } +.review-context mark { background: var(--hl); color: var(--fg); padding: 0 2px; border-radius: 3px; box-shadow: 0 0 0 2px var(--hl-edge); } +#review-fix { font-size: 18px; font-family: "Courier Prime", ui-monospace, monospace; } +.review-alts { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.chip { padding: 4px 10px; border-radius: 999px; font-family: "Courier Prime", ui-monospace, monospace; font-weight: 400; } +.review-card .actions { margin-top: 6px; } +#review-item, #review-done { display: flex; flex-direction: column; gap: 10px; } +#review-item[hidden], #review-done[hidden] { display: none; } + +@media (max-width: 1000px) { + .editor, .editor.no-photos { grid-template-columns: minmax(0, 1fr); } + .page-list { position: static; } + .page-list ol { display: flex; overflow-x: auto; max-height: none; padding-bottom: 4px; } + .page-list ol button { min-width: 48px; } + .page-list-tools { display: flex; } + .page-photo { position: static; } + .photo-frame { max-height: 60vh; } + .review-grid { grid-template-columns: minmax(0, 1fr); } + .review-photo { max-height: 42vh; border-right: 0; border-bottom: 1px solid var(--line); } } /* ---- PDF export (print) ---- diff --git a/public/edit.html b/public/edit.html index fad656d..aa74500 100644 --- a/public/edit.html +++ b/public/edit.html @@ -11,9 +11,9 @@
-
- - +
+ +
@@ -29,44 +29,101 @@ -
-
- + + +
+ Kontrola +
    + +
    + +
    + + +
    +
    + +

    Tato strana nemá fotku.

    +
    + +
    + +
    +
    + + + + + + + +
    + + +
    + + +
    Jak se text zapisuje - +
    =5začátek strany 5 (!7 = strana 7 chybí)
    @Lídareplika postavy Lída; další řádky jsou její text
    >(Odejde)scénická poznámka; pokračování na dalším řádku začíná >
    >  veršverš / píseň (dvě mezery za >)
    #Pokoj u Lysákůpopis scény u levého okraje
    ~O p o n ařádek na střed
    .prázdný řádek; ukončí repliku
    {slovo|slova}nejisté čtení (a jiná možnost); ve čtečce se ukáže jen první
    -

    Rozdělené slovo na konci řádku nechte se spojovníkem (nepří-), čtečka ho spojí. Pomlčku jako interpunkci na konci řádku pište jako –.

    +

    Text na začátku strany bez @Jméno pokračuje replikou z předchozí strany. Rozdělené slovo na konci řádku nechte se spojovníkem (nepří-), čtečka ho spojí. Pomlčku jako interpunkci na konci řádku pište jako –.

    - +
    + +
    +
    + + +
    +
    + Fotka strany +
    + +
    +
    +
    +

    Nejistá slova

    + +
    +
    +

    +
    + +
    +
    + + + +
    +

    Enter potvrdí, Esc zavře. Opravy se po zavření uloží.

    +
    + +
    +
    +
    diff --git a/public/edit.js b/public/edit.js index b7fb120..3e9f51f 100644 --- a/public/edit.js +++ b/public/edit.js @@ -1,98 +1,334 @@ -import { api, withLogin, getPassword, askPassword, esc, $ } from "./api.js"; -import { parsePlay, speakers, lint } from "./parse.js"; +// 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 meta; -let savedText = ""; -let img = 1; +let cfg, meta; +let pages = []; // [{ key, num, missing, body, photo }] +let cur = 0; +let saved = { text: "", photos: "" }; let leaving = false; +let nextKey = 1; -const dirty = () => $("text").value !== savedText +// ---- 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()) }; }; -function showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; } +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 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) => `
  • `).join("") - : `
  • Žádné problémy nenalezeny.
  • `; - $("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); +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 || ""; } -// Select `needle` (or the line containing `inner`) in the textarea and scroll it into view. -function jumpTo(needle, inner) { +// ---- 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 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); + 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`; } -// Drafts' photos need the password header, which 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; +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(); } -// 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]; +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 () => { - 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 } }); + 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").textContent = `Uloženo ${new Date().toLocaleTimeString("cs-CZ", { hour: "2-digit", minute: "2-digit" })}`; + $("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}`); @@ -101,8 +337,48 @@ async function save() { } } +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() { - $("text").readOnly = true; + $("editor").classList.add("busy"); $("save").disabled = true; $("progress").hidden = false; while (meta.status === "processing") { @@ -113,37 +389,99 @@ async function waitForJob() { meta = await api(`plays/${enc}`); } $("progress").hidden = true; - $("text").readOnly = false; + $("editor").classList.remove("busy"); $("save").disabled = false; - savedText = await api(`plays/${enc}/text`); - $("text").value = savedText; + 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(); } -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(); +// ---- 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", () => { clearTimeout(timer); timer = setTimeout(check, 400); }); - $("text").addEventListener("keydown", (e) => { - if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); save(); } + $("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); - $("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}`); }); + 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" })); @@ -158,8 +496,22 @@ async function main() { location.replace("./"); } catch (err) { showError(err.message); } }); - window.addEventListener("beforeunload", (e) => { if (!leaving && meta.status !== "processing" && dirty()) e.preventDefault(); }); + 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(); }