Spaces:
Running
Running
App aktualisiert
Browse filesFiles changed (11)
- config.js+1-1
- index.html+46-9
- js/generate/document.jsAdded+436
- js/generate/engine-client.js+87-1
- js/generate/page-view.jsAdded+517
- js/generate/pdf.jsAdded+216
- js/generate/render.js+96-14
- js/generate/view.js+81-14
- js/training/state.js+1-1
- styles.css+55
- sw.js+1
2 unmodified lines34567892 unmodified lines// No account name here: the account comes from the sign-in at runtime.self.HW_CONFIG = Object.freeze({appName: 'handwriting-capture',version: '0.12.2',datasetRepo: 'handwriting-fable', // dataset <user>/handwriting-fable (private)modelRepo: 'handwriting-fable-model', // model <user>/handwriting-fable-model (private)hfBase: 'https://huggingface.co',2 unmodified lines34567892 unmodified lines// No account name here: the account comes from the sign-in at runtime.self.HW_CONFIG = Object.freeze({appName: 'handwriting-capture',version: '0.13.0',datasetRepo: 'handwriting-fable', // dataset <user>/handwriting-fable (private)modelRepo: 'handwriting-fable-model', // model <user>/handwriting-fable-model (private)hfBase: 'https://huggingface.co',
37 unmodified lines383940414243149 unmodified lines19319419519619719819915 unmodified lines2152162172182192202212222232242252262272282292302 unmodified lines23323423523623723816 unmodified lines25525625725825926026113 unmodified lines2752762772782792802811 unmodified line28328428528628728828929029129229329429529629729829930037 unmodified lines<symbol id="i-nib" viewBox="0 0 24 24"><path d="M12 3.5 17.5 10 12 20.5 6.5 10z"/><path d="M12 13.2v7.3"/><circle cx="12" cy="11.6" r="1.4"/></symbol><symbol id="i-expand" viewBox="0 0 24 24"><path d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5"/></symbol><symbol id="i-more" viewBox="0 0 24 24"><circle cx="5.5" cy="12" r="1.3"/><circle cx="12" cy="12" r="1.3"/><circle cx="18.5" cy="12" r="1.3"/></symbol><symbol id="i-shrink" viewBox="0 0 24 24"><path d="M9 4v5H4M15 4v5h5M20 15h-5v5M4 15h5v5"/></symbol></defs></svg>149 unmodified lines<!-- Generate: text in, handwriting out --><section class="view view-write" id="v-schreiben" hidden><div class="gen" id="gen"><!-- The sheet. It is always there; without a model it says why and what to do. --><div class="gen-stage" id="gen-stage">15 unmodified lines</div></div><div class="gen-dock" id="gen-work" hidden><div class="gen-row"><div class="gen-status"><span class="gen-busy" id="gen-busy" hidden><span class="pen-dot" aria-hidden="true"></span><span id="gen-busy-text" role="status">schreibt …</span></span><span class="gen-info" id="gen-info"><span id="gi-text" role="status"></span><span class="pbar" id="gi-bar" hidden><span id="gi-fill"></span></span></span></div><div class="gen-tools"><button class="gen-tool" id="gen-again" type="button" title="Denselben Text noch einmal schreiben" disabled><svg class="ic" aria-hidden="true"><use href="#i-again"/></svg><span>Nochmal</span></button><button class="gen-tool" id="gen-style-btn" type="button" aria-expanded="false" aria-controls="gen-style"><svg class="ic" aria-hidden="true"><use href="#i-nib"/></svg><span>Stil</span></button><div class="gen-menu-wrap"><button class="gen-tool" id="gen-save" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="gen-save-menu" disabled><svg class="ic" aria-hidden="true"><use href="#i-down"/></svg><span>Speichern</span></button><div class="gen-menu" id="gen-save-menu" role="menu" hidden><button type="button" role="menuitem" id="gen-png" disabled>Als Bild</button>2 unmodified lines<button type="button" role="menuitem" id="gen-copy" disabled hidden>Kopieren</button></div></div></div></div>16 unmodified lines<button class="gen-choice gen-w" type="button" role="radio" aria-checked="false" data-k="width" data-v="0.42" aria-label="Dick" title="Dick"><i style="height:4px"></i></button></div></div><label class="gen-opt"><span class="gen-opt-l">Größe</span><input type="range" id="gen-size" min="6" max="30" step="1" value="11"></label><div class="gen-opt gen-opt-paper"><span class="gen-opt-l" id="gs-paper-l">Papier</span><div class="gen-choices" role="radiogroup" aria-labelledby="gs-paper-l"><button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="paper" data-v="blanko">Blanko</button>13 unmodified lines<label class="gen-opt gen-opt-model" id="gen-model-row" hidden><span class="gen-opt-l">Modell</span><select class="gen-select" id="gen-model-pick"><option value="newest">Neuestes</option></select></label><label class="gen-opt"><span class="gen-opt-l">Lesbarkeit</span><input type="range" id="gen-bias" min="0" max="1.2" step="0.05" value="0.4"></label><label class="gen-opt"><span class="gen-opt-l">Zeilenabstand</span><input type="range" id="gen-spacing" min="5" max="9" step="0.25" value="6.5"></label><div class="gen-opt" id="gen-ink-row"><span class="gen-opt-l" id="gen-ink-l">Tinte</span><div class="gen-inks" id="gen-inks" role="radiogroup" aria-labelledby="gen-ink-l"><button class="gen-ink" type="button" role="radio" aria-checked="true" data-ink="blueblack" aria-label="Blauschwarz" title="Blauschwarz"><i></i></button>1 unmodified line<button class="gen-ink" type="button" role="radio" aria-checked="false" data-ink="blue" aria-label="Königsblau" title="Königsblau"><i></i></button></div></div></div></div><div class="gen-composer"><label class="sr-only" for="gen-text">Text</label><textarea id="gen-text" rows="1" maxlength="4000" placeholder="Was soll ich schreiben?" autocomplete="off" spellcheck="true" enterkeyhint="enter"></textarea><button class="gen-go" id="gen-write" type="button" title="Strg + Eingabe">Schreiben</button><button class="gen-go stop" id="gen-cancel" type="button" hidden><i aria-hidden="true"></i>Abbrechen</button></div><p class="gen-note" id="gen-note" role="status" hidden></p><p class="gen-note" id="gen-chars" hidden></p><p class="gen-note" id="gen-bad" hidden></p></div></div></section>37 unmodified lines38394041424344149 unmodified lines19419519619719819920020120220320420520615 unmodified lines2222232242252262272282292302312322332342352362372382392402412422432442452462472 unmodified lines25025125225325425525625716 unmodified lines27427527627727827928028128228328428528628713 unmodified lines3013023033043053063071 unmodified line30931031131231331431531631731831932032132232332432532632732832933033133233333433533633737 unmodified lines<symbol id="i-nib" viewBox="0 0 24 24"><path d="M12 3.5 17.5 10 12 20.5 6.5 10z"/><path d="M12 13.2v7.3"/><circle cx="12" cy="11.6" r="1.4"/></symbol><symbol id="i-expand" viewBox="0 0 24 24"><path d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5"/></symbol><symbol id="i-more" viewBox="0 0 24 24"><circle cx="5.5" cy="12" r="1.3"/><circle cx="12" cy="12" r="1.3"/><circle cx="18.5" cy="12" r="1.3"/></symbol><symbol id="i-share" viewBox="0 0 24 24"><path d="M12 15V4"/><path d="M7.5 8.5 12 4l4.5 4.5"/><path d="M5 12v6.5A1.5 1.5 0 0 0 6.5 20h11a1.5 1.5 0 0 0 1.5-1.5V12"/></symbol><symbol id="i-shrink" viewBox="0 0 24 24"><path d="M9 4v5H4M15 4v5h5M20 15h-5v5M4 15h5v5"/></symbol></defs></svg>149 unmodified lines<!-- Generate: text in, handwriting out --><section class="view view-write" id="v-schreiben" hidden><div class="gen" id="gen" data-mode="zettel"><!-- Zettel: a short text on a sheet of its own size; Seite: A4 pages and a PDF (page-view.js) --><div class="gen-modes" role="radiogroup" aria-label="Art"><button class="gen-choice" type="button" role="radio" aria-checked="true" data-mode="zettel">Zettel</button><button class="gen-choice" type="button" role="radio" aria-checked="false" data-mode="seite">Seite</button></div><!-- The sheet. It is always there; without a model it says why and what to do. --><div class="gen-stage" id="gen-stage">15 unmodified lines</div></div><!-- Seite: the A4 pages, one canvas each; a tap on a word marks its piece for rewriting --><div class="pg-stage" id="pg-stage" data-only="seite" hidden><div class="pg-pages" id="pg-pages"><p class="pg-empty" id="pg-empty">Hier erscheinen deine Seiten.</p><div class="pg-pick" id="pg-pick" hidden><button class="pg-redo" id="pg-redo" type="button"><svg class="ic" aria-hidden="true"><use href="#i-again"/></svg><span>Neu schreiben</span></button></div></div></div><div class="gen-dock" id="gen-work" hidden><div class="gen-row"><div class="gen-status"><span class="gen-busy" id="gen-busy" hidden><span class="pen-dot" aria-hidden="true"></span><span id="gen-busy-text" role="status">schreibt …</span></span><span class="gen-busy" id="pg-busy" data-only="seite" hidden><span class="pen-dot" aria-hidden="true"></span><span id="pg-busy-text" role="status"></span><span class="pbar" id="pg-bar" hidden><span id="pg-fill"></span></span></span><span class="gen-info pg-info" id="pg-info" data-only="seite" role="status" hidden></span><span class="gen-info" id="gen-info"><span id="gi-text" role="status"></span><span class="pbar" id="gi-bar" hidden><span id="gi-fill"></span></span></span></div><div class="gen-tools"><button class="gen-tool" id="gen-again" data-only="zettel" type="button" title="Denselben Text noch einmal schreiben" disabled><svg class="ic" aria-hidden="true"><use href="#i-again"/></svg><span>Nochmal</span></button><button class="gen-tool" id="gen-style-btn" type="button" aria-expanded="false" aria-controls="gen-style"><svg class="ic" aria-hidden="true"><use href="#i-nib"/></svg><span>Stil</span></button><div class="gen-menu-wrap" data-only="zettel"><button class="gen-tool" id="gen-save" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="gen-save-menu" disabled><svg class="ic" aria-hidden="true"><use href="#i-down"/></svg><span>Speichern</span></button><div class="gen-menu" id="gen-save-menu" role="menu" hidden><button type="button" role="menuitem" id="gen-png" disabled>Als Bild</button>2 unmodified lines<button type="button" role="menuitem" id="gen-copy" disabled hidden>Kopieren</button></div></div><button class="gen-tool" id="pg-share" data-only="seite" type="button" aria-label="Teilen" disabled hidden><svg class="ic" aria-hidden="true"><use href="#i-share"/></svg><span class="pg-long">Teilen</span></button><button class="gen-tool" id="pg-pdf" data-only="seite" type="button" disabled><svg class="ic" aria-hidden="true"><use href="#i-down"/></svg><span class="pg-long">PDF herunterladen</span><span class="pg-short">PDF</span></button></div></div>16 unmodified lines<button class="gen-choice gen-w" type="button" role="radio" aria-checked="false" data-k="width" data-v="0.42" aria-label="Dick" title="Dick"><i style="height:4px"></i></button></div></div><label class="gen-opt" data-only="zettel"><span class="gen-opt-l">Größe</span><input type="range" id="gen-size" min="6" max="30" step="1" value="11"></label><div class="gen-opt" data-only="seite"><span class="gen-opt-l" id="gs-docsize-l">Schrift</span><div class="gen-choices" role="radiogroup" aria-labelledby="gs-docsize-l"><button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="docsize" data-v="klein">Klein</button><button class="gen-choice" type="button" role="radio" aria-checked="true" data-k="docsize" data-v="mittel">Mittel</button><button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="docsize" data-v="gross">Groß</button></div></div><div class="gen-opt gen-opt-paper"><span class="gen-opt-l" id="gs-paper-l">Papier</span><div class="gen-choices" role="radiogroup" aria-labelledby="gs-paper-l"><button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="paper" data-v="blanko">Blanko</button>13 unmodified lines<label class="gen-opt gen-opt-model" id="gen-model-row" hidden><span class="gen-opt-l">Modell</span><select class="gen-select" id="gen-model-pick"><option value="newest">Neuestes</option></select></label><label class="gen-opt"><span class="gen-opt-l">Lesbarkeit</span><input type="range" id="gen-bias" min="0" max="1.2" step="0.05" value="0.4"></label><label class="gen-opt" data-only="zettel"><span class="gen-opt-l">Zeilenabstand</span><input type="range" id="gen-spacing" min="5" max="9" step="0.25" value="6.5"></label><div class="gen-opt" id="gen-ink-row"><span class="gen-opt-l" id="gen-ink-l">Tinte</span><div class="gen-inks" id="gen-inks" role="radiogroup" aria-labelledby="gen-ink-l"><button class="gen-ink" type="button" role="radio" aria-checked="true" data-ink="blueblack" aria-label="Blauschwarz" title="Blauschwarz"><i></i></button>1 unmodified line<button class="gen-ink" type="button" role="radio" aria-checked="false" data-ink="blue" aria-label="Königsblau" title="Königsblau"><i></i></button></div></div><div class="gen-opt" data-only="seite"><span class="gen-opt-l">PDF</span><label class="pg-switch"><input type="checkbox" role="switch" id="pg-textlayer" checked><span>Text durchsuchbar</span></label></div></div></div><div class="gen-composer" data-only="zettel"><label class="sr-only" for="gen-text">Text</label><textarea id="gen-text" rows="1" maxlength="4000" placeholder="Was soll ich schreiben?" autocomplete="off" spellcheck="true" enterkeyhint="enter"></textarea><button class="gen-go" id="gen-write" type="button" title="Strg + Eingabe">Schreiben</button><button class="gen-go stop" id="gen-cancel" type="button" hidden><i aria-hidden="true"></i>Abbrechen</button></div><div class="gen-composer pg-composer" data-only="seite"><label class="sr-only" for="pg-text">Text für die Seiten</label><textarea id="pg-text" rows="2" maxlength="40000" placeholder="Text tippen oder einfügen" autocomplete="off" spellcheck="true" enterkeyhint="enter"></textarea><button class="gen-go" id="pg-write" type="button" title="Strg + Eingabe">Schreiben</button><button class="gen-go stop" id="pg-cancel" type="button" hidden><i aria-hidden="true"></i>Abbrechen</button></div><p class="gen-note" id="gen-note" data-only="zettel" role="status" hidden></p><p class="gen-note" id="gen-chars" data-only="zettel" hidden></p><p class="gen-note" id="gen-bad" data-only="zettel" hidden></p><p class="gen-note" id="pg-note" data-only="seite" role="status" hidden></p><p class="gen-note" id="pg-chars" data-only="seite" hidden></p></div></div></section>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436// The page mode ("Seite"): a typed text written onto A4 pages. No DOM in here.//// const plan = planDocument(text, model.normalize);// for every piece i: result = await engine.writePiece({ text: plan.pieces[i].text, bias, seed: pieceSeed(seed, i) })// written[i] = preparePiece(result, xhModel)// const doc = layoutDocument(plan, written, settings, { gapXh, sizeByBias }); // also while pieces are missing// render.js drawDocumentPage() and pdf.js documentToPDF() both read `doc`.//// Everything in a document is in millimetres, y pointing down, (0, 0) the top// left corner of the page. Ink arrives in xh units (layout.js) and is scaled here.import { makeRandom } from '../engine/engine.js';import { splitPieces, straighten, toXh, levelledWords, wordLevel, strokeRanges, strokeSize, sizeScale, MAX_PIECE_CHARS, LEVEL_KEEP } from './layout.js';
// ---------- paper ----------
export const PAGE = Object.freeze({ width: 210, height: 297 }); // A4 portrait, mmexport const MARGIN = Object.freeze({ left: 20, right: 15 });export const DOC_PAPERS = ['liniert', 'kariert', 'blanko'];// Rulings as in a notebook app. Liniert / Blanko: a baseline every 8 mm from 24 mm// on, the last one at least 12 mm above the bottom edge (33 lines). Kariert: a 5 mm// grid centred on the page, the writing on every second grid line (26 lines).export const LINE_PITCH = 8, FIRST_LINE = 24, BOTTOM_ROOM = 12, GRID = 5;// x-height / baseline distance, chosen by looking at written pages and counting// neighbouring lines whose ink touches. Within a piece this hand's highest point// is a median 3.5 xh above the baseline, its deepest 1.5 xh below: 0.30 (the// first guess) ran lines into each other; on one lined page of prose 0.25 touched// on 16 of 36 line pairs, 0.21 on 12 of 31, 0.18 on 4 of 28.export const SIZES = Object.freeze({ klein: 0.16, mittel: 0.18, gross: 0.21 });export const DOC_SIZES = Object.keys(SIZES);export const RULE_WIDTH = 0.16; // mm: a hairline that still prints
/** Where the writing goes on a page of this paper: baselines (mm from the top), * the x-height, and the ruling to draw ({ ys, xs, tone: 'rule' | 'faint' }). */export function paperGeometry(paper, size = 'mittel') { const kind = DOC_PAPERS.includes(paper) ? paper : 'liniert'; const share = SIZES[size] ?? SIZES.mittel; const last = PAGE.height - BOTTOM_ROOM; const baselines = [], ys = [], xs = []; let pitch = LINE_PITCH; if (kind === 'kariert') { pitch = 2 * GRID; const y0 = (PAGE.height - GRID * Math.floor(PAGE.height / GRID)) / 2; // 1 mm: the grid sits centred for (let y = y0; y <= PAGE.height + 1e-9; y += GRID) ys.push(round3(y)); for (let x = 0; x <= PAGE.width + 1e-9; x += GRID) xs.push(round3(x)); const first = ys.find((y) => y >= FIRST_LINE - 1e-9); for (let y = first; y <= last + 1e-9; y += pitch) baselines.push(round3(y)); } else { for (let y = FIRST_LINE; y <= last + 1e-9; y += pitch) baselines.push(y); if (kind === 'liniert') ys.push(...baselines); } return { paper: kind, size: share === SIZES[size] ? size : 'mittel', pitch, xh: round3(share * pitch), baselines, left: MARGIN.left, right: PAGE.width - MARGIN.right, ruling: { ys, xs, tone: kind === 'kariert' ? 'faint' : 'rule', width: RULE_WIDTH }, };}const round3 = (v) => Math.round(v * 1000) / 1000;
// ---------- text -> pieces, seeds ----------
/** Deterministic 32-bit seed of piece `index` of a document, independent of how * many workers write and in which order; `version` counts the rewrites. */export function pieceSeed(docSeed, index, version = 0) { let h = (docSeed >>> 0) ^ Math.imul(index + 1, 0x9E3779B1) ^ Math.imul(version + 1, 0x7FEB352D); h ^= h >>> 16; h = Math.imul(h, 0x85EBCA6B); h ^= h >>> 13; h = Math.imul(h, 0xC2B2AE35); h ^= h >>> 16; return h >>> 0;}const LAYOUT_SALT = 0x5BD1E995; // the layout's own random numbers, apart from the network's
/** Text -> { paragraphs: [[pieceIndex, ...], ...], pieces: [{ index, text, para, typed }] }. * One newline (\n, \r\n or a lone \r) starts a new line, an empty line stays one * empty line (an empty paragraph). `normalize` is the model's (model.normalize / * createNormalizer); typed[] holds the piece's words as typed, for the PDF's text * layer ("„Süße“" stays that, the network writes '"Süße"'). */export function planDocument(text, normalize = (t) => t) { // Word by word, so that every written word keeps its typed form. const lines = String(text).replace(/\r\n?/g, '\n').split('\n').map((line) => { const words = []; for (const typed of line.split(/\s+/u).filter(Boolean)) { const parts = normalize(typed).split(' ').filter(Boolean); for (const w of parts) words.push([w, parts.length === 1 ? typed : w]); } return words; }); const pieces = [], paragraphs = []; splitPieces(lines.map((words) => words.map(([w]) => w).join(' ')).join('\n'), MAX_PIECE_CHARS).forEach((para, k) => { let at = 0; paragraphs.push(para.map((t) => { const n = t.split(' ').length; pieces.push({ index: pieces.length, text: t, para: k, typed: lines[k].slice(at, at + n).map(([, typed]) => typed) }); at += n; return pieces.length - 1; })); }); // Trailing empty lines write nothing and would only add blank lines. while (paragraphs.length && !paragraphs[paragraphs.length - 1].length) paragraphs.pop(); return { paragraphs, pieces };}
// ---------- letter size of a written piece ----------
// Expected pen-down ink length per character (xh), fitted on the writer's real// lines and words (ridge towards the class means, cross-validated by line).const INK_PER_CHAR = (() => { const t = {}; const s = '!6.3"4.3#6.9%7.7&8.5\'2.2(4.3)4.6*7.1+4.1,5.5-2.0.1.8/3.4' + '06.912.924.935.144.654.465.173.786.296.6' + ':4.6;9.3=5.1?3.9@10.3A7.0B9.5C7.6D12.9E6.3F7.6G10.4H9.5I5.7J8.2K8.2L3.3M9.2N10.2O8.8P9.5Q11.0R9.8S5.8T8.7' + 'U5.8V6.4W9.1X8.1Y12.3Z4.8[6.3]6.3_5.1a4.7b6.6c2.2d7.6e4.1f7.2g6.1h6.1i1.3j6.0k5.0l2.3m5.6n3.4o3.9p6.3q3.8' + 'r1.8s1.8t4.0u4.3v1.8w3.3x5.4y7.3z2.9Ä9.7Ö15.1Ü8.4ß7.4ä4.3ö4.8ü3.7€6.0'; for (const m of s.matchAll(/(.)(\d+\.\d)/gu)) t[m[1]] = Number(m[2]); return t;})();const classLength = (c) => (/\d/u.test(c) ? 5.0 : /\p{Lu}/u.test(c) ? 8.1 : /\p{L}/u.test(c) ? 3.8 : 4.3);// log(stroke size) explained by the text: constant, shares of ascender letters,// capitals, descender letters, capital umlauts, digits, punctuation.const HEIGHT_W = [1.008, 0.684, 1.73, 1.028, -0.009, 0.476, -0.357];// Weight of the ink-length measure against the height measure. Recovering a known// factor (0.7-1.4) on 322 real pieces of 8-22 characters, 4-fold by line, sd of// the log error: stroke size 0.220, stroke size over its text 0.183, ink length// 0.140, this mix 0.136.const INK_WEIGHT = 0.85;export const SIZE_ERROR = 0.136;
/** Estimated log letter size of a straightened piece (xh units), up to a constant * that is the same for every piece; NaN when the piece has too few characters. */export function sizeEstimate(points, text) { const chars = [...text].filter((c) => c !== ' '); if (chars.length < 3 || points.length < 9) return NaN; let ink = 0; for (let i = 3; i < points.length; i += 3) if (points[i - 1] <= 0.5) ink += Math.hypot(points[i] - points[i - 3], points[i + 1] - points[i - 2]); let expect = 0; for (const c of chars) expect += INK_PER_CHAR[c] ?? classLength(c); const n = chars.length, share = (re) => chars.filter((c) => re.test(c)).length / n; const f = [1, share(/[bdfhklt]/u), share(/\p{Lu}/u), share(/[gjpqyß]/u), share(/[ÄÖÜ]/u), share(/\d/u), share(/[,.;:!?-]/u)]; const height = Math.log(strokeSize(points)) - f.reduce((s, v, i) => s + v * HEIGHT_W[i], 0); return ink > 0 ? INK_WEIGHT * Math.log(ink / expect) + (1 - INK_WEIGHT) * height : NaN;}
// How far a piece is pulled towards the page's typical size: the share of the// estimate's spread that is real, cov(estimate, x-height fit) / var(estimate) with// an independent height measure (hw/prep.py: fit_xheight). 117 pieces of the// test model (bias 0.4) spread by sd 0.088 and give 0.68; the same 14 texts// written with 6 seeds each give 0.99 +- 0.15 within a text. (The error 0.136// on real lines mostly is the lines' own size: two pieces of one line differ by// an error of only 0.085.)export const SIZE_PULL = 0.7;export const SIZE_CLAMP = [0.8, 1.25];
/** The correction factor for a piece of estimated log size `est` on a page whose * typical estimate is `typical`. */export function sizeCorrection(est, typical, pull = SIZE_PULL) { if (!Number.isFinite(est) || !Number.isFinite(typical) || !pull) return 1; return Math.min(SIZE_CLAMP[1], Math.max(SIZE_CLAMP[0], Math.exp(-pull * (est - typical))));}
// Words inside a piece differ in size too ("Nachricht!" twice as tall as its// neighbours). Words of 4 or more characters, measured against their own piece,// on the 117 test pieces: sd 0.100, cov with the x-height fit / var = 0.46 (229 words).export const WORD_PULL = 0.46, WORD_MIN_CHARS = 4;export const WORD_CLAMP = [0.85, 1.18];
/** The correction of a word whose estimate is `rel` above its piece's. */export function wordCorrection(rel) { if (!Number.isFinite(rel)) return 1; return Math.min(WORD_CLAMP[1], Math.max(WORD_CLAMP[0], Math.exp(-WORD_PULL * rel)));}
// The page's typical size is the median of the first pieces of the text only: once// they are written it stays put, so what is shown never moves while the rest of the// text arrives, whatever order the workers finish in. Twelve pieces put the median// within about 0.03 of the whole document's (sd of the estimate 0.088).export const TYPICAL_PIECES = 12;
/** The typical estimate: the median of the first `count` written pieces' estimates. */export function typicalSize(written, count = TYPICAL_PIECES) { const v = written.slice(0, count).filter((p) => p && Number.isFinite(p.estimate)).map((p) => p.estimate).sort((a, b) => a - b); if (!v.length) return NaN; const m = (v.length - 1) / 2; return (v[Math.floor(m)] + v[Math.ceil(m)]) / 2;}
// A cut whose words fit their texts this badly is wrong (hw/dataset.py: WORD_FIT_MAX).const WORD_FIT_MAX = 1.2, LOOSE_MIN_GAP = 0.35;
/** levelledWords, and for a piece whose word gaps are unclear (3 of 113 test * pieces) a looser cut: the largest gaps even when the next one is nearly as * large, kept only if every word's width fits its number of characters * (hw/dataset.py: split_words with ambiguous=True). A piece left whole cannot * wrap and leaves a short line before it. */function pieceParts(piece) { const parts = levelledWords(piece); const texts = piece.text.split(/\s+/u).filter(Boolean); if (parts.length === texts.length || texts.length < 2) return parts; const p = piece.points, ranges = strokeRanges(p); const ext = ([s, e]) => { let lo = Infinity, hi = -Infinity; for (let i = s; i < e; i++) { lo = Math.min(lo, p[3 * i]); hi = Math.max(hi, p[3 * i]); } return [lo, hi]; }; let reach = ext(ranges[0])[1]; const jumps = []; for (let k = 1; k < ranges.length; k++) { const [lo, hi] = ext(ranges[k]); jumps.push([lo - reach, k]); reach = Math.max(reach, hi); } const cuts = [...jumps].sort((u, v) => v[0] - u[0]).slice(0, texts.length - 1); if (cuts.length < texts.length - 1 || cuts.some(([g]) => g < LOOSE_MIN_GAP)) return parts; const bounds = [0, ...cuts.map(([, k]) => ranges[k][0]).sort((a, b) => a - b), p.length / 3]; const words = texts.map((text, i) => ({ text, ok: piece.ok, points: p.subarray(3 * bounds[i], 3 * bounds[i + 1]) })); const widths = words.map((w) => { let lo = Infinity, hi = -Infinity; for (let i = 0; i < w.points.length; i += 3) { lo = Math.min(lo, w.points[i]); hi = Math.max(hi, w.points[i]); } return Math.max(hi - lo, 1e-3); }); const perChar = widths.map((wd, i) => wd / [...texts[i]].length).sort((a, b) => a - b); const med = (perChar[(perChar.length - 1) >> 1] + perChar[perChar.length >> 1]) / 2; if (widths.some((wd, i) => Math.abs(Math.log(wd / (med * [...texts[i]].length))) > WORD_FIT_MAX)) return parts; const size = strokeSize(p); return words.map((word) => ({ word, level: wordLevel(word.points, word.text, size) }));}
/** The line a word sits on (xh, positive = below the piece's line), from the * bottoms of its letters: the largest group of stroke bottoms within 0.3 xh of * each other, the highest group on a tie (descenders only go down); NaN without * any. Unlike wordLevel it also answers for words of 1-2 characters. */export function sitLine(p, size) { const ys = []; for (const [s, e] of strokeRanges(p)) { if (e - s < 3) continue; let len = 0; for (let i = s + 1; i < e; i++) len += Math.hypot(p[3 * i] - p[3 * i - 3], p[3 * i + 1] - p[3 * i - 2]); if (len < 0.3 * size) continue; // dots and short dashes // local lowest points, wiggles under 0.08 x the stroke size ignored (as layout.js) const delta = 0.08 * size; let hi = s, down = true; for (let i = s + 1; i < e; i++) { const y = p[3 * i + 1]; if (down) { if (y > p[3 * hi + 1]) hi = i; else if (p[3 * hi + 1] - y > delta) { ys.push(p[3 * hi + 1]); down = false; hi = i; } } else if (y < p[3 * hi + 1]) hi = i; else if (y - p[3 * hi + 1] > delta) { down = true; hi = i; } } if (down) ys.push(p[3 * hi + 1]); } if (!ys.length) return NaN; ys.sort((a, b) => a - b); let best = null; for (let i = 0; i < ys.length; i++) { let j = i; while (j + 1 < ys.length && ys[j + 1] - ys[i] <= 0.3) j++; if (!best || j - i + 1 > best[1] - best[0] + 1) best = [i, j]; } const g = ys.slice(best[0], best[1] + 1); return g[(g.length - 1) >> 1] / 2 + g[g.length >> 1] / 2;}
// wordLevel leaves words of 1-2 characters, and words whose bottoms it finds more// than 1.5 xh off, where the network put them: on test pages 'es' and 'zu' sat// 0.8-1.7 mm above the rule, a whole word 2.1 mm. Such a word is moved onto the// line by its own letter bottoms instead, up to SIT_MAX. A word still more than// SIT_OFF from the line afterwards marks the piece (it is written once more).export const SIT_MAX = 2.5, SIT_OFF = 0.5;// A word reaching higher than this (xh) is broken (a capital drawn twice the// size): capitals reach 3, capital umlaut dots 4 (on 814 test words: p99 4.2, the// two above 5.0 broken). A long stroke (over RAISED_LENGTH xh of path) whose// lowest point stays more than RAISED_HEIGHT above the line is letters written a// line too high ('bes' over 'nbasen'): on 259 test pieces only that piece has one.export const TOP_MAX = 5, RAISED_HEIGHT = 1, RAISED_LENGTH = 2.5;
/** What the layout needs of a written piece (engine result in model units -> * straightened, cut into levelled words, with its size estimate). Done once per * piece; the result goes into written[i]. `flags` lists what the page mode sees * wrong with the piece (a word off the line, a word far too tall); the page mode * writes such a piece once more. */export function preparePiece(result, xhModel) { const piece = straighten(toXh(result, xhModel)); const estimate = sizeEstimate(piece.points, piece.text); const parts = pieceParts(piece); const size = strokeSize(piece.points); const flags = []; const words = parts.map(({ word, level }) => { const p = word.points; let x0 = Infinity, x1 = -Infinity, top = Infinity; for (let i = 0; i < p.length; i += 3) { if (p[i] < x0) x0 = p[i]; if (p[i] > x1) x1 = p[i]; if (p[i + 1] < top) top = p[i + 1]; } const sit = /[\p{L}\p{N}]/u.test(word.text) ? sitLine(p, size) : NaN; if (level === 0 && Number.isFinite(sit) && Math.abs(sit) > LEVEL_KEEP && Math.abs(sit) <= SIT_MAX) { level = sit - Math.min(LEVEL_KEEP, Math.max(-LEVEL_KEEP, sit)); } if (Number.isFinite(sit) && Math.abs(sit - level) > SIT_OFF) flags.push(`neben der Linie: ${word.text}`); if (level - top > TOP_MAX) flags.push(`zu hoch: ${word.text}`); else if (strokeRanges(p).some(([a, e]) => { let len = 0, low = -Infinity; for (let i = a; i < e; i++) { if (i > a) len += Math.hypot(p[3 * i] - p[3 * i - 3], p[3 * i + 1] - p[3 * i - 2]); if (p[3 * i + 1] > low) low = p[3 * i + 1]; } return len > RAISED_LENGTH && level - low > RAISED_HEIGHT; })) flags.push(`über der Linie: ${word.text}`); const long = parts.length > 1 && [...word.text].length >= WORD_MIN_CHARS; return { text: word.text, points: new Float32Array(p), level, x0, x1, size: long ? wordCorrection(sizeEstimate(p, word.text) - estimate) : 1 }; }); return { text: piece.text, ok: piece.ok !== false, problems: result.problems || [], flags, words, estimate };}
// ---------- layout ----------
export const DEFAULT_SETTINGS = Object.freeze({ paper: 'liniert', size: 'mittel', bias: 0.4, seed: 1, textLayer: true });const JITTER = 0.2, JITTER_MAX = 0.5; // mm: line starts vary a little, as by hand
/** Any half-valid settings -> complete ones. `look` (render.js) rides along for * the renderers; it never changes the layout. */export function normalizeSettings(o) { const v = o && typeof o === 'object' ? o : {}; return { paper: DOC_PAPERS.includes(v.paper) ? v.paper : DEFAULT_SETTINGS.paper, size: DOC_SIZES.includes(v.size) ? v.size : DEFAULT_SETTINGS.size, bias: Number.isFinite(v.bias) ? v.bias : DEFAULT_SETTINGS.bias, seed: Number.isFinite(v.seed) ? v.seed >>> 0 : DEFAULT_SETTINGS.seed, textLayer: v.textLayer !== false, look: v.look && typeof v.look === 'object' ? { ...v.look } : null, };}
/** * Lay out the written pieces of `plan` on A4 pages. written[i] is preparePiece()'s * result for piece i or missing; the layout stops at the first missing piece (the * page fills in from the start of the text while the rest is written). * * o.gapXh: the writer's word gap [mean, sd] in xh (model.json gap_xh); * o.sizeByBias: model.json size_by_bias; o.typical: the typical size estimate to * even towards, default typicalSize(written). Keep doc.typical when a piece is * rewritten (relayoutDocument), so that nothing before it moves. * * Returns { settings, page: { width, height }, geometry, typical, total, placed, complete, pages: [{ strokes, words }], pieces }: * strokes = one Float32Array [x, y, penUp, ...] in mm per word; words = { text, typed, piece, * word, line, x, width, baseline, box: [x0, y0, x1, y1], ok }; pieces[i] = { page, * line, scale } for the pieces laid out. */export function layoutDocument(plan, written, settings, { gapXh = [2.9, 0.8], sizeByBias = null, typical } = {}) { const s = normalizeSettings(settings); const g = paperGeometry(s.paper, s.size); const typ = typical !== undefined && typical !== null ? typical : typicalSize(written); const unit = g.xh * sizeScale(sizeByBias, s.bias); // mm per xh of the ink const gapMm = (z) => g.xh * Math.min(1.6 * gapXh[0], Math.max(0.6 * gapXh[0], gapXh[0] + gapXh[1] * z)); const width = g.right - g.left; const pages = [], pieces = []; let page = null, line = 0, right = null, fresh = true, placed = 0, stop = false;
const newPage = () => { page = { strokes: [], words: [] }; pages.push(page); line = 0; }; const advance = () => { // the next line; an empty one never opens a page right = null; if (fresh) return; line++; if (line >= g.baselines.length) { page = null; fresh = true; } }; const lineStart = (index, k) => { const z = makeRandom(pieceSeed(s.seed ^ LAYOUT_SALT, index, k + 1)).normal(); return g.left + Math.max(-JITTER_MAX, Math.min(JITTER_MAX, JITTER * z)); };
for (let k = 0; k < plan.paragraphs.length && !stop; k++) { if (k > 0) advance(); for (const index of plan.paragraphs[k]) { const pc = written[index]; if (!pc) { stop = true; break; } const z = makeRandom(pieceSeed(s.seed ^ LAYOUT_SALT, index, 0)).normal(); const even = sizeCorrection(pc.estimate, typ); const scale = unit * even; let prevEnd = null, first = null; const typed = plan.pieces[index] && plan.pieces[index].typed; const typedOf = (w, wi) => (!typed ? w.text : typed.length === pc.words.length ? typed[wi] : pc.words.length === 1 ? typed.join(' ') : w.text); pc.words.forEach((w, wi) => { const gap = prevEnd === null ? gapMm(z) : g.xh * even * Math.min(1.8 * gapXh[0], Math.max(0.5 * gapXh[0], w.x0 - prevEnd)); prevEnd = w.x1; let f = scale * w.size, wide = (w.x1 - w.x0) * f; if (wide > width) { f *= width / wide; wide = width; } // a word longer than a line: smaller, on a line of its own let start = right === null ? null : right + gap; if (start !== null && start + wide > g.right) { advance(); start = null; } if (!page) newPage(); if (start === null) start = Math.min(lineStart(index, wi), g.right - wide); fresh = false; const y = g.baselines[line]; const p = w.points, q = new Float32Array(p.length); let y0 = Infinity, y1 = -Infinity; for (let i = 0; i < p.length; i += 3) { q[i] = (p[i] - w.x0) * f + start; q[i + 1] = (p[i + 1] - w.level) * f + y; q[i + 2] = p[i + 2]; if (q[i + 1] < y0) y0 = q[i + 1]; if (q[i + 1] > y1) y1 = q[i + 1]; } if (q.length) q[q.length - 1] = 1; page.strokes.push(q); page.words.push({ text: w.text, typed: typedOf(w, wi), piece: index, word: wi, line, x: start, width: wide, baseline: y, box: [start, y0, start + wide, y1], ok: pc.ok }); if (!first) first = { page: pages.length - 1, line }; right = start + wide; }); pieces[index] = { page: first ? first.page : pages.length - 1, line: first ? first.line : line, scale: even }; placed++; } } return { settings: s, page: { ...PAGE }, geometry: g, typical: typ, total: plan.pieces.length, placed, complete: placed === plan.pieces.length, pages, pieces };}
/** The document again after written[index] was replaced (a rewrite): the same * typical size, so the pieces before it stay exactly where they were. */export function relayoutDocument(doc, plan, written, o = {}) { return layoutDocument(plan, written, doc.settings, { ...o, typical: doc.typical });}
/** The word under a point (mm) of page `pageIndex`: { word, piece, index } or null. * `reach` (mm) widens every word's box, for a finger. */export function wordAt(doc, pageIndex, x, y, reach = 2.5) { const page = doc.pages[pageIndex]; if (!page) return null; let best = null, bestD = Infinity; page.words.forEach((w, i) => { const [x0, y0, x1, y1] = w.box; const top = Math.min(y0, w.baseline - doc.geometry.xh), bottom = Math.max(y1, w.baseline); const dx = x < x0 ? x0 - x : x > x1 ? x - x1 : 0, dy = y < top ? top - y : y > bottom ? y - bottom : 0; const d = Math.hypot(dx, dy); if (d <= reach && d < bestD) { best = { word: w, piece: w.piece, index: i }; bestD = d; } }); return best;}
/** The boxes (mm) of the words of piece `index` on each page: [{ page, box }], for * marking it. */export function pieceBoxes(doc, index) { const out = []; doc.pages.forEach((page, p) => { for (const w of page.words) { if (w.piece !== index) continue; const last = out[out.length - 1]; const top = Math.min(w.box[1], w.baseline - doc.geometry.xh); if (last && last.page === p && last.line === w.line) { last.box = [Math.min(last.box[0], w.box[0]), Math.min(last.box[1], top), Math.max(last.box[2], w.box[2]), Math.max(last.box[3], w.box[3])]; } else out.push({ page: p, line: w.line, box: [w.box[0], top, w.box[2], w.box[3]] }); } }); return out;}
/** The text of the document as laid out (for the PDF's text layer): per page, the * lines with their words. */export function pageLines(page) { const lines = new Map(); for (const w of page.words) { if (!lines.has(w.line)) lines.set(w.line, []); lines.get(w.line).push(w); } return [...lines.entries()].sort((a, b) => a[0] - b[0]).map(([, ws]) => ws);}35 unmodified lines363738394041427 unmodified lines50515253545513 unmodified lines69707135 unmodified lines} else if (m.type === 'error') {const error = new Error(m.message || 'engine error');if (m.id !== undefined && pending.has(m.id)) { const p = pending.get(m.id); pending.delete(m.id); p.reject(error); }else { readyHandlers.reject(error); failAll(error); }}};worker.onerror = (event) => {7 unmodified linesreturn {ready,set onProgress(fn) { onProgress = fn; },writePiece({ text, bias, seed, tries }) {if (dead) return Promise.reject(dead);13 unmodified lines},};}35 unmodified lines363738394041427 unmodified lines505152535455565713 unmodified lines717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615735 unmodified lines} else if (m.type === 'error') {const error = new Error(m.message || 'engine error');if (m.id !== undefined && pending.has(m.id)) { const p = pending.get(m.id); pending.delete(m.id); p.reject(error); }else { dead = error; readyHandlers.reject(error); failAll(error); } // the model did not load: this engine is no use}};worker.onerror = (event) => {7 unmodified linesreturn {ready,/** The worker crashed or could not load the model; every writePiece() fails. */get failed() { return !!dead; },set onProgress(fn) { onProgress = fn; },writePiece({ text, bias, seed, tries }) {if (dead) return Promise.reject(dead);13 unmodified lines},};}/** How many engines a device can spare for writing pages: one core stays with the* page, at most 4 (a piece is about 600 steps at ~200 steps/s per core), and fewer* where memory is small (every engine holds its own copy of the model). */export function poolSize(nav = typeof navigator !== 'undefined' ? navigator : {}) {let n = Math.min(4, Math.max(1, (nav.hardwareConcurrency || 2) - 1));const mem = nav.deviceMemory;if (mem && mem <= 2) n = 1;else if (mem && mem <= 4) n = Math.min(n, 2);return n;}/*** Several engines writing pieces side by side. Same interface as one engine, plus* `size`; writePiece({ ..., first: true }) goes ahead of everything queued (a piece* the writer asked to rewrite). Pieces are handed out in the order they are asked* for, so the start of a text is written first.** A piece that fails is tried once more, on another engine if there is one. An* engine whose worker died (crash, out of memory, model not loaded) is replaced by* a fresh one; after `size` replacements a dead engine is dropped instead, and only* when none is left do the pieces fail. Without this a dead engine, which fails at* once, would take most of the queue and fail the whole text.*/export function createEnginePool(manifest, buffer, size = poolSize(), o = {}) {const make = o.createEngine || createEngine;const engines = Array.from({ length: Math.max(1, size) }, () => make(manifest, buffer, o));const busy = new Set();let queue = []; // { job, resolve, reject, tried }let renewals = 0;const ready = Promise.any(engines.map((e) => e.ready));ready.catch(() => {});const replace = (e) => {const k = engines.indexOf(e);if (k < 0) return;e.terminate();if (renewals < engines.length + 1) { renewals++; engines[k] = make(manifest, buffer, o); engines[k].ready.catch(() => {}); }else engines.splice(k, 1);};const pump = () => {if (!engines.length) {const q = queue; queue = [];for (const it of q) it.reject(new Error('no engine left'));return;}for (const e of [...engines]) {if (!queue.length) return;if (busy.has(e)) continue;const item = queue.shift();busy.add(e);e.writePiece(item.job).then(item.resolve, (error) => {if (error && error.cancelled) { item.reject(error); return; }if (e.failed) replace(e);if (item.tried) item.reject(error);else { item.tried = true; queue.unshift(item); }}).finally(() => { busy.delete(e); pump(); });}};return {ready,get size() { return engines.length; },writePiece(job) {return new Promise((resolve, reject) => {const { first, ...rest } = job;const item = { job: rest, resolve, reject, tried: false };if (first) queue.unshift(item); else queue.push(item);pump();});},/** Pending and running pieces reject with .cancelled = true. */cancel() {const q = queue; queue = [];for (const it of q) it.reject(cancelled());for (const e of busy) e.cancel();},terminate() {this.cancel();for (const e of engines) e.terminate();},};}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517// The page mode of Schreiben ("Seite", SPEC 2.5.2): a typed text written onto A4// pages by several engines at once, shown page by page while it is written, a tap// on a word writes its piece again, and the pages download as one PDF.//// document.js lays out, render.js draws, pdf.js writes the file; all three read the// same document object, so the pages on the screen are the pages in the PDF.// view.js owns the model and the shared controls (Stil, Lesbarkeit) and hands them in.import { planDocument, pieceSeed, preparePiece, layoutDocument, wordAt, pieceBoxes, typicalSize, PAGE, DOC_PAPERS, DOC_SIZES, TYPICAL_PIECES,} from './document.js';import { drawDocumentPage, lookColors } from './render.js';import { documentToPDF, pdfFileName } from './pdf.js';import { createEnginePool, poolSize } from './engine-client.js';
export const PAGE_DEFAULTS = Object.freeze({ text: '', paper: 'liniert', size: 'mittel', textLayer: true });const MAX_PIXELS = 8e6; // per page canvas; only the pages near the viewport keep theirsconst TAP_MOVE = 10; // CSS px a tap may move and still count as a tapconst REACH = { touch: 3, pen: 2, mouse: 1.5 }; // mm around a word that still hits it (a finger is wide)
/** * deps: { store, model() -> { entry, info, normalizer } | null, look() -> render.js look, * bias() -> number, onIdle() (called when nothing is being written any more) } */export function createPageView(deps) { const { store, model, look, bias } = deps; const $ = (id) => document.getElementById(id); const el = { stage: $('pg-stage'), pages: $('pg-pages'), empty: $('pg-empty'), pick: $('pg-pick'), redo: $('pg-redo'), text: $('pg-text'), write: $('pg-write'), cancel: $('pg-cancel'), busy: $('pg-busy'), busyText: $('pg-busy-text'), info: $('pg-info'), bar: $('pg-bar'), fill: $('pg-fill'), pdf: $('pg-pdf'), share: $('pg-share'), note: $('pg-note'), chars: $('pg-chars'), textLayer: $('pg-textlayer'), }; const P = { settings: { ...PAGE_DEFAULTS }, visible: false, active: false, pool: null, poolSha: null, run: null, // { token, text, seed, bias, plan, written, version, typical, info, sizeByBias, start, done, cancelled } doc: null, phase: 'idle', rewriting: new Set(), pick: null, follow: true, frames: [], // per page: { wrap, canvas, sig } near: new Set(), raf: 0, lastStatus: '', }; let token = 0;
// ---------- engines ----------
function ensurePool(m) { const sha = m.entry.manifest.sha256; if (P.pool && P.poolSha === sha) return P.pool; if (P.pool) P.pool.terminate(); P.pool = createEnginePool(m.entry.manifest, m.entry.buffer, poolSize()); P.poolSha = sha; return P.pool; }
/** A newer model: the engines go; written pages stay as they are. */ function modelChanged() { if (P.phase === 'writing' || P.rewriting.size) return; if (P.pool) { P.pool.terminate(); P.pool = null; P.poolSha = null; } }
const busy = () => P.phase === 'writing' || P.rewriting.size > 0;
// A piece the layout flags (a word off the line or far too tall, document.js: // preparePiece) gets one more attempt, with a seed derived from its own, and the // one with fewer flags is kept. About 1.5 % of pieces (3 of ~200 test pieces). const RETRY_SALT = 0x2545F491; async function writeChecked(pool, r, i, seed, first) { const job = { text: r.plan.pieces[i].text, bias: r.bias }; const w = preparePiece(await pool.writePiece({ ...job, first, seed }), r.info.xhModel); if (!w.flags.length) return w; r.retried = (r.retried || 0) + 1; try { const again = preparePiece(await pool.writePiece({ ...job, first: true, seed: (seed ^ RETRY_SALT) >>> 0 }), r.info.xhModel); return again.flags.length < w.flags.length ? again : w; } catch (_) { return w; } // cancelled or failed: the first attempt stands }
// ---------- layout ----------
const docSettings = () => ({ paper: P.settings.paper, size: P.settings.size, textLayer: P.settings.textLayer, bias: P.run ? P.run.bias : bias(), seed: P.run ? P.run.seed : 1, });
/** The pieces written so far laid out with the current paper and size (no writing). */ function relayout() { const r = P.run; if (!r) { P.doc = layoutDocument({ paragraphs: [], pieces: [] }, [], docSettings()); return; } // The typical size is fixed as soon as the first pieces are there: from then on // nothing shown moves while the rest arrives, and a rewrite moves nothing before it. if (r.typical === undefined) { const need = Math.min(TYPICAL_PIECES, r.plan.pieces.length); let have = 0; for (let i = 0; i < need; i++) if (r.written[i]) have++; if (have === need) r.typical = typicalSize(r.written); } P.doc = layoutDocument(r.plan, r.written, docSettings(), { gapXh: r.info.gapXh, sizeByBias: r.sizeByBias, typical: r.typical }); }
// ---------- drawing ----------
const dpr = () => window.devicePixelRatio || 1; const cssWidth = () => el.pages.clientWidth; const cssPerMm = () => cssWidth() / PAGE.width; const lookKey = (l) => [l.pen, l.width, l.scheme, l.ink].join('|');
/** Cheap fingerprint of what a page shows: changes whenever a word is added or moves. */ function pageSig(page) { if (!page) return 'blank'; let s = 0; for (const w of page.words) s = (s * 31 + Math.round(w.x * 100) * 7 + Math.round(w.box[1] * 100) + Math.round(w.box[3] * 100) * 3 + w.piece) % 2147483647; return `${page.words.length}:${s}`; }
const io = typeof IntersectionObserver === 'function' ? new IntersectionObserver((entries) => { for (const e of entries) { const i = P.frames.findIndex((f) => f.wrap === e.target); if (i < 0) continue; if (e.isIntersecting) P.near.add(i); else P.near.delete(i); } schedule(); }, { root: el.stage, rootMargin: '100% 0px' }) : null;
function frames(n) { while (P.frames.length < n) { const wrap = document.createElement('div'); wrap.className = 'pg-page'; const canvas = document.createElement('canvas'); canvas.setAttribute('aria-hidden', 'true'); wrap.append(canvas); el.pages.insertBefore(wrap, el.pick); const f = { wrap, canvas, sig: '' }; P.frames.push(f); if (io) io.observe(wrap); else P.near.add(P.frames.length - 1); } while (P.frames.length > n) { const f = P.frames.pop(); if (io) io.unobserve(f.wrap); f.wrap.remove(); P.near.delete(P.frames.length); } P.frames.forEach((f, i) => f.wrap.setAttribute('aria-label', `Seite ${i + 1} von ${n}`)); if (el.empty.parentNode !== P.frames[0].wrap) P.frames[0].wrap.append(el.empty); // the hint sits in the first page's top margin }
function schedule() { if (P.raf || !P.visible) return; P.raf = requestAnimationFrame(() => { P.raf = 0; paint(); }); }
const markColor = (l) => (l.scheme === 'light_on_dark' ? '#34406A' : '#DCE3F7');
function paint() { if (!P.visible || !P.active) return; if (!P.doc) relayout(); const doc = P.doc; const n = Math.max(1, doc.pages.length); frames(n); const w = cssWidth(); if (!w) return; const l = look(); const colors = lookColors(l); const marks = P.pick ? pieceBoxes(doc, P.pick.piece) : []; const ratio = Math.min(dpr(), Math.sqrt(MAX_PIXELS / (w * w * (PAGE.height / PAGE.width)))); const pw = Math.round(w * ratio), ph = Math.round(pw * PAGE.height / PAGE.width); P.frames.forEach((f, i) => { if (!P.near.has(i)) { // far away: give the memory back if (f.canvas.width) { f.canvas.width = 0; f.canvas.height = 0; f.sig = ''; } return; } const mark = marks.filter((b) => b.page === i).map((b) => b.box); const sig = [pw, lookKey(l), doc.settings.paper, doc.settings.size, JSON.stringify(mark), pageSig(doc.pages[i])].join('#'); if (sig === f.sig) return; if (f.canvas.width !== pw || f.canvas.height !== ph) { f.canvas.width = pw; f.canvas.height = ph; } drawDocumentPage(f.canvas.getContext('2d'), doc, i, { scale: pw / PAGE.width, look: l, colors, mark, markColor: markColor(l) }); f.sig = sig; }); el.empty.hidden = !!(P.run && doc.placed) || P.phase === 'writing'; placePick(); follow(); }
/** Redraw everything (look, width or theme changed). */ function redraw() { for (const f of P.frames) f.sig = ''; schedule(); }
/** Keep the line being written in view while writing, until the writer scrolls. */ function follow() { if (!P.follow || P.phase !== 'writing' || !P.doc || !P.doc.pages.length) return; const pi = P.doc.pages.length - 1, page = P.doc.pages[pi]; const last = page.words[page.words.length - 1]; if (!last) return; const f = P.frames[pi]; const y = f.wrap.offsetTop + last.baseline * cssPerMm(); const room = 3 * P.doc.geometry.pitch * cssPerMm(); const top = el.stage.scrollTop, bottom = top + el.stage.clientHeight; if (y + room > bottom) el.stage.scrollTo({ top: y + room - el.stage.clientHeight, behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' }); }
// ---------- tap to rewrite ----------
/** The "Neu schreiben" bar sits next to the marked piece, under or over it, where * it hides the least of the other words (the margins are often free). */ function placePick() { const pick = P.pick && P.doc ? pieceBoxes(P.doc, P.pick.piece) : []; if (!pick.length) { el.pick.hidden = true; return; } const b = pick[pick.length - 1]; const f = P.frames[b.page]; if (!f) { el.pick.hidden = true; return; } const k = cssPerMm(); el.pick.hidden = false; const writing = P.rewriting.has(P.pick.piece); el.redo.disabled = writing; el.redo.querySelector('span').textContent = writing ? 'schreibt …' : 'Neu schreiben'; el.redo.classList.toggle('writing', writing); const bw = el.pick.offsetWidth / k, bh = el.pick.offsetHeight / k; // mm const pad = 0.12 * P.doc.geometry.pitch, gap = 1.5; const others = P.doc.pages[b.page].words.filter((w) => w.piece !== P.pick.piece).map((w) => w.box); const clampX = (x) => Math.max(1, Math.min(PAGE.width - bw - 1, x)); const xs = [clampX((b.box[0] + b.box[2]) / 2 - bw / 2), clampX(b.box[0]), clampX(b.box[2] - bw), 1, PAGE.width - bw - 1]; const ys = [b.box[3] + pad + gap, b.box[1] - pad - gap - bh].filter((y) => y >= 1 && y + bh <= PAGE.height - 1); let best = null; for (const y of ys.length ? ys : [b.box[3] + pad + gap]) { for (const x of xs) { let hidden = 0; for (const o of others) hidden += Math.max(0, Math.min(x + bw, o[2]) - Math.max(x, o[0])) * Math.max(0, Math.min(y + bh, o[3]) - Math.max(y, o[1])); const away = Math.abs(x + bw / 2 - (b.box[0] + b.box[2]) / 2) / PAGE.width; // nearer the piece wins a tie if (!best || hidden + away < best.score) best = { x, y, score: hidden + away }; } } el.pick.style.transform = `translate(${Math.round(best.x * k)}px, ${Math.round(f.wrap.offsetTop + best.y * k)}px)`; }
function choose(piece) { P.pick = piece === null || (P.pick && P.pick.piece === piece) ? null : { piece }; schedule(); }
function onTap(e, f) { if (!P.doc || !P.run) return; const i = P.frames.indexOf(f); const r = f.wrap.getBoundingClientRect(); const k = r.width / PAGE.width; const hit = wordAt(P.doc, i, (e.clientX - r.left) / k, (e.clientY - r.top) / k, REACH[e.pointerType] || REACH.mouse); choose(hit ? hit.piece : null); }
async function rewrite() { const r = P.run; if (!P.pick || !r) return; const i = P.pick.piece; if (P.rewriting.has(i)) return; const m = model(); if (!m) return; // A piece of another model would not match its neighbours (size, xh unit). if (m.entry.manifest.sha256 !== r.sha) { note('Inzwischen ist ein anderes Modell geladen. Bitte schreib den Text neu.'); return; } const pool = ensurePool(m); const ver = (r.version[i] || 0) + 1; r.version[i] = ver; P.rewriting.add(i); sync(); try { const w = await writeChecked(pool, r, i, pieceSeed(r.seed, i, ver), true); if (r === P.run && r.version[i] === ver) { r.written[i] = w; r.done = r.written.filter(Boolean).length; relayout(); } } catch (e) { if (!e || !e.cancelled) { console.error(e); note('Das Neuschreiben hat nicht geklappt. Bitte versuch es noch einmal.'); } if (r.version[i] === ver) r.version[i] = ver - 1; } P.rewriting.delete(i); sync(); schedule(); idleCheck(); }
// ---------- writing ----------
const note = (text) => { el.note.textContent = text || ''; el.note.hidden = !text; }; const charsNote = (list) => { const set = [...new Set(list)]; el.chars.textContent = set.length ? `Diese Zeichen kann ich nicht schreiben und lasse sie weg: ${set.slice(0, 8).map((c) => `„${c}“`).join(', ')}${set.length > 8 ? ' …' : ''}` : ''; el.chars.hidden = !set.length; };
async function write() { const m = model(); if (!m || P.phase === 'writing') return; const text = String(el.text.value || '').replace(/\r\n?/g, '\n'); note(''); charsNote(m.normalizer.unsupported(text)); const plan = planDocument(text, m.normalizer.normalize); if (!plan.pieces.length) { note(text.trim() ? 'In diesem Text steht nichts, was ich schreiben kann.' : 'Bitte tippe oder füge zuerst einen Text ein.'); if (!text.trim()) el.text.focus(); return; } const mine = ++token; const pool = ensurePool(m); if (matchMedia('(pointer: coarse)').matches) el.text.blur(); // the keyboard away: the pages are the thing to watch P.pick = null; P.rewriting.clear(); P.run = { token: mine, sha: m.entry.manifest.sha256, text, seed: (Math.random() * 2 ** 32) >>> 0, bias: bias(), plan, written: [], version: [], typical: undefined, info: m.info, sizeByBias: m.entry.manifest.size_by_bias || null, start: performance.now(), done: 0, cancelled: false, workers: pool.size, }; const r = P.run; P.phase = 'writing'; P.follow = true; el.stage.scrollTop = 0; relayout(); sync(); schedule(); const jobs = plan.pieces.map((p, i) => writeChecked(pool, r, i, pieceSeed(r.seed, i, 0), false).then((w) => { if (r !== P.run || r.version[i]) return; // replaced meanwhile by a rewrite r.written[i] = w; r.done = r.written.filter(Boolean).length; relayout(); sync(); schedule(); })); const outcome = await Promise.allSettled(jobs); if (mine !== token) return; const failed = outcome.find((o) => o.status === 'rejected' && !(o.reason && o.reason.cancelled)); if (failed) { // A piece failed twice (the pool already retried it and replaced dead engines): // stop, and start the next run with fresh engines. console.error(failed.reason); pool.terminate(); if (P.pool === pool) { P.pool = null; P.poolSha = null; } note('Beim Schreiben ist etwas schiefgegangen. Was bis dahin geschrieben ist, bleibt stehen.'); } else if (r.cancelled) { const kept = P.doc && P.doc.placed ? ' Was schon geschrieben ist, bleibt stehen.' : ''; note(`${r.dropped ? 'Abgebrochen, auch das Neuschreiben.' : 'Abgebrochen.'}${kept}`); } r.ms = performance.now() - r.start; P.phase = 'idle'; relayout(); sync(); schedule(); save(); idleCheck(); }
function cancel() { if (!busy()) return; if (P.run) { P.run.cancelled = true; if (P.rewriting.size) P.run.dropped = true; } if (P.pool) P.pool.cancel(); }
function idleCheck() { if (!busy() && deps.onIdle) deps.onIdle(); }
// ---------- status ----------
function sync() { const writing = P.phase === 'writing'; const r = P.run, doc = P.doc; el.write.hidden = writing; el.cancel.hidden = !writing; el.write.disabled = writing || !model(); const pages = doc ? doc.pages.length : 0; const canSave = !writing && pages > 0 && !!r && doc.placed > 0; el.pdf.disabled = !canSave; el.share.disabled = !canSave; el.busy.hidden = !writing; el.bar.hidden = !writing; let info = ''; if (writing) { const total = r.plan.pieces.length; // [text, shown on a phone too]: the narrow form keeps to one line beside the tools const parts = [['schreibt … ', false], [`${r.done} von ${total}`, true]]; if (pages > 1) parts.push([` · Seite ${pages}`, false]); // the rate is measured: only once every engine has finished a piece does it mean anything if (r.done >= Math.min(total, r.workers) && r.done < total) { const s = ((performance.now() - r.start) / r.done) * (total - r.done) / 1000; if (s < 50) parts.push([' · noch unter 1 Min.', true]); else parts.push([' · noch ', true], ['etwa ', false], [`${Math.max(1, Math.round(s / 60))} Min.`, true]); } el.busyText.replaceChildren(...parts.map(([t, short]) => { const e = document.createElement('span'); e.textContent = t; if (!short) e.className = 'pg-long'; return e; })); el.fill.style.width = `${(100 * r.done) / total}%`; } else if (r && doc && doc.placed) { info = `${pages === 1 ? '1 Seite' : `${pages} Seiten`} · Ein Wort antippen, um es neu schreiben zu lassen.`; } el.info.textContent = info; el.info.hidden = !info; if (deps.onStatus) deps.onStatus(writing || !!info); placePick(); }
// ---------- PDF ----------
function title() { const line = ((P.run && P.run.text) || '').split('\n').map((s) => s.trim()).find(Boolean) || 'Handschrift'; const chars = [...line]; // by characters: never half an emoji return chars.length > 60 ? `${chars.slice(0, 59).join('')}…` : line; }
async function pdfFile() { const date = new Date(); const blob = await documentToPDF(P.doc, { look: look(), title: title(), date, textLayer: P.settings.textLayer }); return { blob, name: pdfFileName(date) }; }
async function downloadPdf() { if (!P.doc || !P.doc.placed || P.phase === 'writing') return; try { const { blob, name } = await pdfFile(); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 10000); } catch (e) { console.error(e); if (deps.toast) deps.toast('Das PDF konnte nicht erstellt werden.'); } }
async function sharePdf() { if (!P.doc || !P.doc.placed || P.phase === 'writing') return; try { const { blob, name } = await pdfFile(); await navigator.share({ files: [new File([blob], name, { type: 'application/pdf' })], title: title() }); } catch (e) { if (e && e.name !== 'AbortError') { console.error(e); if (deps.toast) deps.toast('Teilen hat nicht geklappt. Herunterladen geht immer.'); } } }
const canShareFiles = () => { try { return !!(navigator.canShare && navigator.share && navigator.canShare({ files: [new File(['%PDF'], 'x.pdf', { type: 'application/pdf' })] })); } catch (_) { return false; } };
// ---------- settings ----------
let saveTimer = null; function save() { clearTimeout(saveTimer); saveTimer = setTimeout(() => { const { paper, size, textLayer } = P.settings; store.kvSet('page', { text: el.text.value, paper, size, textLayer }).catch(() => {}); }, 300); }
/** paper / size: the written pieces are laid out again, nothing is written. */ function set(key, value) { if (key === 'paper' && DOC_PAPERS.includes(value)) P.settings.paper = value; else if (key === 'size' && DOC_SIZES.includes(value)) P.settings.size = value; else return; save(); relayout(); sync(); schedule(); }
function autosize() { if (!P.visible || !P.active) return; el.text.style.height = 'auto'; el.text.style.height = `${el.text.scrollHeight + 2}px`; }
async function init() { try { const v = await store.kvGet('page', null); if (v && typeof v === 'object') { if (typeof v.text === 'string') el.text.value = v.text; if (DOC_PAPERS.includes(v.paper)) P.settings.paper = v.paper; if (DOC_SIZES.includes(v.size)) P.settings.size = v.size; P.settings.textLayer = v.textLayer !== false; } } catch (_) { /* defaults */ } el.textLayer.checked = P.settings.textLayer; el.share.hidden = !canShareFiles(); el.write.addEventListener('click', write); el.cancel.addEventListener('click', cancel); el.text.addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); write(); } }); // maxlength cuts a long paste without a word: say so el.text.addEventListener('input', () => { note(el.text.maxLength > 0 && el.text.value.length >= el.text.maxLength ? `Der Text ist auf ${el.text.maxLength.toLocaleString('de-DE')} Zeichen gekürzt.` : ''); autosize(); save(); }); // Away from the keyboard the field shows two lines: from the start, not a line cut in half. el.text.addEventListener('blur', () => { el.text.scrollTop = 0; }); el.pdf.addEventListener('click', downloadPdf); el.share.addEventListener('click', sharePdf); el.redo.addEventListener('click', rewrite); el.textLayer.addEventListener('change', () => { P.settings.textLayer = el.textLayer.checked; save(); }); // A tap is a short press that hardly moves (a scroll with the finger is not a tap). let down = null; el.pages.addEventListener('pointerdown', (e) => { const f = P.frames.find((x) => x.wrap.contains(e.target)); down = f && e.isPrimary ? { f, x: e.clientX, y: e.clientY } : null; }); el.pages.addEventListener('pointerup', (e) => { if (!down || Math.hypot(e.clientX - down.x, e.clientY - down.y) > TAP_MOVE) { down = null; return; } const f = down.f; down = null; onTap(e, f); }); el.pages.addEventListener('pointercancel', () => { down = null; }); document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && P.pick && P.active) choose(null); }); for (const type of ['wheel', 'touchmove']) el.stage.addEventListener(type, () => { P.follow = false; }, { passive: true }); let lastW = 0; new ResizeObserver(() => { const w = cssWidth(); if (w !== lastW) { lastW = w; redraw(); } }).observe(el.pages); sync(); }
return { init, set, redraw, modelChanged, busy, cancel, autosize, sync, /** Drop the mark and its "Neu schreiben" bar (Stil opened over the page). */ unpick() { if (P.pick) choose(null); }, get settings() { return { ...P.settings }; }, /** The page mode is the one in use (shown when the tab is shown). */ activate(on) { P.active = on; if (on) { autosize(); redraw(); } }, show() { P.visible = true; P.follow = true; autosize(); redraw(); }, hide() { P.visible = false; }, debug: () => { const r = P.run, d = P.doc; return { phase: P.phase, rewriting: [...P.rewriting], pick: P.pick ? P.pick.piece : null, seed: r ? r.seed : null, total: r ? r.plan.pieces.length : 0, done: r ? r.done : 0, workers: r ? r.workers : 0, ms: r ? r.ms : null, retried: r ? r.retried || 0 : 0, versions: r ? r.plan.pieces.map((_, i) => r.version[i] || 0) : [], settings: { ...P.settings }, pages: d ? d.pages.length : 0, placed: d ? d.placed : 0, words: d ? d.pages.flatMap((p, pi) => p.words.map((w) => ({ page: pi, text: w.text, piece: w.piece, line: w.line, x: w.x, baseline: w.baseline, box: w.box }))) : [], ink: r ? r.written.map((w) => (w ? w.words.map((x) => Array.from(x.points.slice(0, 12)).map((v) => Math.round(v * 1000))) : null)) : [], drawn: P.frames.map((f) => f.canvas.width > 0), }; }, };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216// A document (document.js) as a vector PDF, written by hand: one A4 page per// document page, the paper colour, the ruling, the ink as stroked paths in the// look of the screen (render.js: the same curves, width steps and tones), and an// invisible text layer so that the PDF can be searched and copied.//// const blob = await documentToPDF(doc, { look, title, date }); // Blob in the browser, Uint8Array in Nodeimport { normalizeLook, lookColors, toPolylines, penGroups, docWordXh, rulingColor, FUELLER_LEVELS } from './render.js';import { fuellerWidth, pencilTone, hexRgb, TONES } from '../capture/ink.js';import { pageLines } from './document.js';
const PT = 72 / 25.4; // points per mmconst f2 = (v) => { const r = Math.round(v * 100) / 100; return Object.is(r, -0) ? '0' : String(r); }; // 0.01 ptconst rgb = (hex) => hexRgb(hex).map((v) => f2(v / 255)).join(' ');
// Helvetica advance widths (1/1000 em), WinAnsi codes 32..255; 0 = not in the font.const HELV = (() => { const w = new Array(256).fill(0); const ascii = [278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584]; ascii.forEach((v, i) => { w[32 + i] = v; }); const hi = { 0x80: 556, 0x82: 222, 0x84: 333, 0x85: 1000, 0x8B: 333, 0x91: 222, 0x92: 222, 0x93: 333, 0x94: 333, 0x95: 350, 0x96: 556, 0x97: 1000, 0x9B: 333 }; Object.entries(hi).forEach(([k, v]) => { w[k] = v; }); for (let c = 0xA0; c <= 0xFF; c++) { const ch = String.fromCharCode(c); const base = ch.normalize('NFD')[0]; w[c] = base !== ch && base.charCodeAt(0) < 128 ? w[base.charCodeAt(0)] : 556; } w[0xA0] = 278; w[0xDF] = 611; w[0xB0] = 400; w[0xB7] = 278; w[0xAB] = 556; w[0xBB] = 556; w[0xD7] = 584; w[0xF7] = 584; return w;})();// The WinAnsi codes outside Latin-1 that a German text may use.const WIN = { '€': 0x80, '‚': 0x82, '„': 0x84, '…': 0x85, '‹': 0x8B, '‘': 0x91, '’': 0x92, '“': 0x93, '”': 0x94, '•': 0x95, '–': 0x96, '—': 0x97, '›': 0x9B };
/** A word as WinAnsi bytes (characters the encoding lacks become '?'). */export function winAnsi(text) { const out = []; for (const ch of text) { const c = ch.codePointAt(0); if (WIN[ch] !== undefined) out.push(WIN[ch]); else if ((c >= 32 && c < 127) || (c >= 0xA0 && c <= 0xFF)) out.push(c); else out.push(63); } return out;}const pdfString = (bytes) => `(${bytes.map((b) => (b === 40 || b === 41 || b === 92 ? `\\${String.fromCharCode(b)}` : b < 32 || b > 126 ? `\\${b.toString(8).padStart(3, '0')}` : String.fromCharCode(b))).join('')})`;
/** Content stream text of one page. */function pageContent(doc, pageIndex, l, colors, textLayer, gstates) { const H = doc.page.height * PT, W = doc.page.width * PT; const X = (mm) => f2(mm * PT), Y = (mm) => f2(H - mm * PT); const g = doc.geometry, page = doc.pages[pageIndex]; const out = []; if (colors.paper.toUpperCase() !== '#FFFFFF') out.push(`${rgb(colors.paper)} rg 0 0 ${f2(W)} ${f2(H)} re f`); const { ys, xs } = g.ruling; if (ys.length || xs.length) { out.push(`${rgb(rulingColor(doc, colors))} RG ${f2(g.ruling.width * PT)} w 0 J`); for (const y of ys) out.push(`0 ${Y(y)} m ${f2(W)} ${Y(y)} l`); for (const x of xs) out.push(`${X(x)} 0 m ${X(x)} ${f2(H)} l`); out.push('S'); } // Ink: word arrays in the page's x-heights (as the screen draws them), xh -> mm -> pt. const xh = g.xh, P = (v) => v * xh; const words = page.strokes.map((q) => docWordXh(q, xh)); const lw = l.width * xh; // mm out.push(`1 J 1 j ${rgb(l.pen === 'bleistift' ? colors.graphite : colors.ink)} RG`); if (l.pen === 'fineliner') { out.push(`${f2(lw * PT)} w`); for (const points of words) { const path = []; for (const line of toPolylines(points)) { const p = line.map(([x, y]) => [P(x), P(y)]); path.push(`${X(p[0][0])} ${Y(p[0][1])} m`); if (p.length === 1) { path.push(`${X(p[0][0] + 0.004)} ${Y(p[0][1])} l`); continue; } // The screen's curve: quadratic pieces through the midpoints, as cubics. let ax = p[0][0], ay = p[0][1]; for (let i = 1; i < p.length - 1; i++) { const [cx, cy] = p[i], bx = (cx + p[i + 1][0]) / 2, by = (cy + p[i + 1][1]) / 2; path.push(`${X(ax + (2 / 3) * (cx - ax))} ${Y(ay + (2 / 3) * (cy - ay))} ${X(bx + (2 / 3) * (cx - bx))} ${Y(by + (2 / 3) * (cy - by))} ${X(bx)} ${Y(by)} c`); ax = bx; ay = by; } const last = p[p.length - 1]; path.push(`${X(last[0])} ${Y(last[1])} l`); } if (path.length) out.push(path.join('\n'), 'S'); } } else { for (const { key, runs } of penGroups(words, l)) { if (l.pen === 'fueller') out.push(`${f2(fuellerWidth(lw, key / FUELLER_LEVELS) * PT)} w`); else { out.push(`${f2(lw * PT)} w /${gstates(key)} gs`); } const path = []; for (const { dot, pts } of runs) { path.push(`${X(P(pts[0][0]))} ${Y(P(pts[0][1]))} m`); if (dot) path.push(`${X(P(pts[0][0]) + 0.004)} ${Y(P(pts[0][1]))} l`); for (let i = 1; i < pts.length; i++) path.push(`${X(P(pts[i][0]))} ${Y(P(pts[i][1]))} l`); } out.push(path.join('\n'), 'S'); } if (l.pen === 'bleistift') out.push('/GN gs'); } // Text layer: every word invisible (render mode 3) on its baseline, stretched to its // width. Its space is widened (word spacing) to reach the next word: text tools read a // gap of 2 em without a glyph as a column break and would put every word on a line. if (textLayer && page.words.length) { // The font size that fits the median word without stretching: the handwriting is // 2-3x as wide as Helvetica at its x-height, and words stretched that much differ // too much in size for text tools to see them as one line. const em = (w) => winAnsi(w.typed ?? w.text).reduce((s, b) => s + (HELV[b] || 556), 0) / 1000; const fits = page.words.filter((w) => em(w) > 0).map((w) => (w.width * PT) / em(w)).sort((a, b) => a - b); const size = fits.length ? fits[fits.length >> 1] : xh * PT / 0.523; const space = (HELV[32] / 1000) * size; out.push(`BT 3 Tr /F1 ${f2(size)} Tf`); for (const line of pageLines(page)) { line.forEach((w, i) => { const bytes = winAnsi(w.typed ?? w.text), adv = em(w) * size; const sx = adv > 0 ? (w.width * PT) / adv : 1; const next = line[i + 1]; const tw = next ? Math.max(0, (next.x - w.x - w.width) * PT) / sx - space : 0; out.push(`${f2(sx)} 0 0 1 ${X(w.x)} ${Y(w.baseline)} Tm ${f2(tw)} Tw ${pdfString(next ? [...bytes, 32] : bytes)} Tj`); }); } out.push('ET'); } return out.join('\n');}
const enc = new TextEncoder();
async function deflate(bytes) { if (typeof CompressionStream === 'undefined') return null; const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream('deflate')); return new Uint8Array(await new Response(stream).arrayBuffer());}
/** PDF date string D:YYYYMMDDHHmmSS+hh'mm' in local time. */export function pdfDate(d) { const p = (v) => String(v).padStart(2, '0'), off = -d.getTimezoneOffset(); return `D:${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}` + `${off >= 0 ? '+' : '-'}${p(Math.floor(Math.abs(off) / 60))}'${p(Math.abs(off) % 60)}'`;}const utf16Hex = (s) => `<FEFF${[...s].map((ch) => { const c = ch.codePointAt(0); return c > 0xFFFF ? '003F' : c.toString(16).toUpperCase().padStart(4, '0'); }).join('')}>`;
/** * The PDF bytes. o = { look (default the document's), title, date (Date), textLayer * (default the document's setting), compress (default true where the browser can) }. */export async function pdfBytes(doc, { look, title = 'Handschrift', date = new Date(), textLayer, compress = true } = {}) { const l = normalizeLook(look || doc.settings.look); const colors = lookColors(l); const text = textLayer ?? doc.settings.textLayer !== false; const objects = []; // index + 1 = object number; each a Uint8Array const add = (body) => { objects.push(body); return objects.length; }; const reserve = () => add(null); const catalog = reserve(), pages = reserve(), font = reserve(), info = reserve(); // Bleistift tones: graphite with the tone as opacity; Darken (Lighten on dark paper) // so overlapping pieces do not pile up, as on the screen. const used = new Set(); const gstate = (key) => { used.add(key); return `G${key}`; }; const blend = colors.dark ? '/Lighten' : '/Darken'; const kids = []; const streamObj = async (content) => { const raw = enc.encode(content); const packed = compress ? await deflate(raw) : null; const data = packed || raw; const head = enc.encode(`<< /Length ${data.length}${packed ? ' /Filter /FlateDecode' : ''} >>\nstream\n`); return concat([head, data, enc.encode('\nendstream')]); }; const pageCount = Math.max(doc.pages.length, 1); const contents = []; for (let i = 0; i < pageCount; i++) contents.push(doc.pages[i] ? pageContent(doc, i, l, colors, text, gstate) : ''); const gsDict = [...used].sort((a, b) => a - b).map((k) => `/G${k} << /CA ${f2(pencilTone(Math.min(k, TONES - 1)))} /BM ${blend} >>`).join(' '); const resources = `<< /Font << /F1 ${font} 0 R >> /ExtGState << ${gsDict} /GN << /CA 1 /BM /Normal >> >> >>`; const mediaBox = `[0 0 ${f2(doc.page.width * PT)} ${f2(doc.page.height * PT)}]`; for (const content of contents) { const c = add(await streamObj(content)); kids.push(add(enc.encode(`<< /Type /Page /Parent ${pages} 0 R /MediaBox ${mediaBox} /Resources ${resources} /Contents ${c} 0 R >>`))); } objects[catalog - 1] = enc.encode(`<< /Type /Catalog /Pages ${pages} 0 R >>`); objects[pages - 1] = enc.encode(`<< /Type /Pages /Kids [${kids.map((k) => `${k} 0 R`).join(' ')}] /Count ${kids.length} >>`); objects[font - 1] = enc.encode('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>'); objects[info - 1] = enc.encode(`<< /Title ${utf16Hex(title)} /Creator (Handschrift) /CreationDate (${pdfDate(date)}) >>`);
// The second line is a comment of bytes above 127: it tells transfer tools the file is binary. const parts = [enc.encode('%PDF-1.4\n'), new Uint8Array([0x25, 0xE2, 0xE3, 0xCF, 0xD3, 0x0A])]; let offset = parts[0].length + parts[1].length; const offsets = []; objects.forEach((body, i) => { offsets.push(offset); const chunk = concat([enc.encode(`${i + 1} 0 obj\n`), body, enc.encode('\nendobj\n')]); parts.push(chunk); offset += chunk.length; }); const xref = [`xref\n0 ${objects.length + 1}\n`, '0000000000 65535 f \n', ...offsets.map((o) => `${String(o).padStart(10, '0')} 00000 n \n`)].join(''); parts.push(enc.encode(`${xref}trailer\n<< /Size ${objects.length + 1} /Root ${catalog} 0 R /Info ${info} 0 R >>\nstartxref\n${offset}\n%%EOF\n`)); return concat(parts);}
function concat(chunks) { const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0)); let at = 0; for (const c of chunks) { out.set(c, at); at += c.length; } return out;}
/** The document as a PDF: a Blob in the browser, a Uint8Array elsewhere. */export async function documentToPDF(doc, o = {}) { const bytes = await pdfBytes(doc, o); return typeof document !== 'undefined' ? new Blob([bytes], { type: 'application/pdf' }) : bytes;}
/** A file name with the date: handschrift-2026-11-26.pdf */export function pdfFileName(date = new Date()) { const p = (v) => String(v).padStart(2, '0'); return `handschrift-${date.getFullYear()}-${p(date.getMonth() + 1)}-${p(date.getDate())}.pdf`;}243 unmodified lines24424524624724824925025125225325425525625725825926026126226326426526626726826927075 unmodified lines346347348243 unmodified linesreturn `${d}L${fmt(p[p.length - 1][0])} ${fmt(p[p.length - 1][1])}`;}/** Füller / Bleistift: the short straight pieces of every stroke, grouped by width or tone level. */function svgPenGroups(page, look, scale) {const groups = new Map(); // level -> path dataconst add = (key, d) => groups.set(key, (groups.get(key) || '') + d);const levels = 12; // Füller: width steps between 0.4x and 1.6xfor (const points of page.strokes) {for (const s of wordSamples(points)) {let pe = 0, prev = null;for (let i = 0; i < s.x.length; i++) {pe = smoothPressure(pe, s, i);const key = look.pen === 'fueller' ? Math.round(Math.min(1, pe) * levels) : pencilLevel(pe);const x = fmt(s.x[i] * scale), y = fmt(s.y[i] * scale);if (i === 0) { add(key, `M${x} ${y}l0.01 0`); prev = key; continue; }const px = fmt(s.x[i - 1] * scale), py = fmt(s.y[i - 1] * scale);add(key, key === prev ? `L${x} ${y}` : `M${px} ${py}L${x} ${y}`);prev = key;}}}// A new level always starts a new subpath; continuing "L"s join the previous point.return [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([key, d]) => ({ key, d: d.replace(/^L/, 'M') }));}/**75 unmodified linesc.drawImage(inkCanvas, 0, 0);return out;}243 unmodified lines24424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228375 unmodified lines359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430243 unmodified linesreturn `${d}L${fmt(p[p.length - 1][0])} ${fmt(p[p.length - 1][1])}`;}export const FUELLER_LEVELS = 12; // Füller: width steps between 0.4x and 1.6x/*** Füller / Bleistift: the short straight pieces of every stroke (word arrays in xh* units), grouped by width or tone level: [{ key, runs: [{ dot, pts: [[x, y], ...] }] }],* keys ascending. A run with `dot` starts a stroke (exporters mark it with a tiny* segment so that a one-point stroke still shows). SVG and PDF export share this.*/export function penGroups(strokes, look) {const groups = new Map(); // level -> runsfor (const points of strokes) {for (const s of wordSamples(points)) {let pe = 0, prev = null, run = null;for (let i = 0; i < s.x.length; i++) {pe = smoothPressure(pe, s, i);const key = look.pen === 'fueller' ? Math.round(Math.min(1, pe) * FUELLER_LEVELS) : pencilLevel(pe);if (!groups.has(key)) groups.set(key, []);if (i === 0) { run = { dot: true, pts: [[s.x[0], s.y[0]]] }; groups.get(key).push(run); }else if (key === prev) run.pts.push([s.x[i], s.y[i]]);else { run = { dot: false, pts: [[s.x[i - 1], s.y[i - 1]], [s.x[i], s.y[i]]] }; groups.get(key).push(run); }prev = key;}}}return [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([key, runs]) => ({ key, runs }));}/** Füller / Bleistift as SVG path data per level. */function svgPenGroups(page, look, scale) {return penGroups(page.strokes, look).map(({ key, runs }) => ({key,d: runs.map(({ dot, pts }) => `M${fmt(pts[0][0] * scale)} ${fmt(pts[0][1] * scale)}${dot ? 'l0.01 0' : ''}` +pts.slice(1).map(([x, y]) => `L${fmt(x * scale)} ${fmt(y * scale)}`).join('')).join(''),}));}/**75 unmodified linesc.drawImage(inkCanvas, 0, 0);return out;}// ---------- document pages (document.js), in millimetres ----------const nominal = new WeakMap();/** A document word array (mm) in the x-heights of the page (mm / xh), so that the* pens' speed and width rules see the same units as on the quick sheet (cached). */export function docWordXh(points, xh) {let out = nominal.get(points);if (!out || out.xh !== xh) {const q = new Float32Array(points.length);for (let i = 0; i < q.length; i += 3) { q[i] = points[i] / xh; q[i + 1] = points[i + 1] / xh; q[i + 2] = points[i + 2]; }out = { xh, q };nominal.set(points, out);}return out.q;}/** The colour of a document page's ruling. */export const rulingColor = (doc, colors) => (doc.geometry.ruling.tone === 'faint' ? colors.faint : colors.rule);/*** Draw page `pageIndex` of a document onto a 2D context with the identity transform:* paper, ruling, ink. o = { scale (device px per mm), look (default the document's),* colors, offsetX, offsetY, mark: [[x0, y0, x1, y1], ...] boxes in mm to underlay* (a piece picked for rewriting), markColor }. The page is drawn from the same* object the PDF is written from, with the same pens.*/export function drawDocumentPage(ctx, doc, pageIndex, { scale, look, colors, offsetX = 0, offsetY = 0, mark = null, markColor = null, ink = true } = {}) {const l = normalizeLook(look || doc.settings.look);const c = colors || lookColors(l);const { width: W, height: H } = doc.page;const g = doc.geometry;ctx.save();ctx.setTransform(1, 0, 0, 1, 0, 0);ctx.globalCompositeOperation = 'source-over';ctx.globalAlpha = 1;ctx.fillStyle = c.paper;ctx.fillRect(offsetX, offsetY, W * scale, H * scale);const { ys, xs } = g.ruling;if (ys.length || xs.length) {const lw = Math.max(1, g.ruling.width * scale);const whole = Math.abs(lw - Math.round(lw)) < 1e-6;const at = (v, o) => (whole ? Math.round(v * scale + o - lw / 2) + lw / 2 : v * scale + o);ctx.lineWidth = lw; ctx.lineCap = 'butt';ctx.strokeStyle = rulingColor(doc, c);ctx.beginPath();for (const y of ys) { ctx.moveTo(offsetX, at(y, offsetY)); ctx.lineTo(offsetX + W * scale, at(y, offsetY)); }for (const x of xs) { ctx.moveTo(at(x, offsetX), offsetY); ctx.lineTo(at(x, offsetX), offsetY + H * scale); }ctx.stroke();}if (mark && mark.length) {ctx.fillStyle = markColor || c.faint;const pad = 0.12 * g.pitch;for (const [x0, y0, x1, y1] of mark) ctx.fillRect(offsetX + (x0 - pad) * scale, offsetY + (y0 - pad) * scale, (x1 - x0 + 2 * pad) * scale, (y1 - y0 + 2 * pad) * scale);}ctx.restore();const page = doc.pages[pageIndex];if (!ink || !page) return;const o = { scale: scale * g.xh, look: l, colors: c, offsetX, offsetY };for (const points of page.strokes) drawWord(ctx, docWordXh(points, g.xh), o);}/** One document page in a new canvas, `scale` device px per mm (PNG export). */export function documentPageCanvas(doc, pageIndex, { scale = 8, look, createCanvas } = {}) {const make = createCanvas || ((w, h) => Object.assign(document.createElement('canvas'), { width: w, height: h }));const canvas = make(Math.round(doc.page.width * scale), Math.round(doc.page.height * scale));drawDocumentPage(canvas.getContext('2d'), doc, pageIndex, { scale, look });return canvas;}
123412 unmodified lines17181920212252 unmodified lines7576777879805 unmodified lines8687888990919232 unmodified lines12512612712812913013113213313413525 unmodified lines1611621631641651661679 unmodified lines1771781791801811821836 unmodified lines190191192193194195196197198199200254 unmodified lines45545645745845946046127 unmodified lines48949049149249349457 unmodified lines55255355455555655755855956056180 unmodified lines6426436446456466476486496506516526533 unmodified lines65765865966066166266366466566666766866967067167210 unmodified lines6836846856866876886897 unmodified lines69769869970070170270329 unmodified lines73373473573673773873917 unmodified lines7577587597607617627637641 unmodified line7667677687697707711 unmodified line773774775776777778779780781782783// The Schreiben screen: text in, handwriting out (SPEC 2.5).//// Pieces: model-store.js (download, check, cache), engine-client.js (network in a// worker), page-writer.js (text -> page, piece by piece), render.js (drawing, export).12 unmodified linesimport { drawWord, drawWords, drawPartial, drawSheet, toSVG, toCanvas, lookColors, normalizeLook, lookFromCapture, INKS, DEFAULT_LOOK } from './render.js';import { createEngine } from './engine-client.js';import { createModelStore } from './model-store.js';import { normalize as normalizeDisplay, WIDTHS as CAPTURE_WIDTHS } from '../capture/ink.js';const PAGE_TOP = 6.5, PAGE_MARGIN = 3; // first baseline and side margin, x-heights (ascenders of enlarged words need about 3.5)52 unmodified linesmodelRow: $('gen-model-row'), modelPick: $('gen-model-pick'),save: $('gen-save'), saveMenu: $('gen-save-menu'),png: $('gen-png'), inkPng: $('gen-ink-png'), svg: $('gen-svg'), copy: $('gen-copy'),};const ctx = el.canvas.getContext('2d');const gctx = el.lines.getContext('2d'); // the paper and its lines, under the ink5 unmodified linessettings: Object.assign({}, DEFAULTS),look: Object.assign({}, DEFAULT_LOOK),ownLook: false, // changed here at least once: no longer follows the capture sheetvisible: false,// modelengine: null, engineUser: null, sha: null, normalizer: null, writer: null, trainedOn: null,version: null, index: null, choice: 'newest', switching: false, again: false,32 unmodified linesel.card.hidden = false;el.work.hidden = true;el.empty.hidden = true;}function showWork() {el.card.hidden = true;el.work.hidden = false;renderInfo();syncUi();autosize();25 unmodified lines};async function useModel(entry, trainedOn, { updated = false, info = null } = {}) {if (S.phase === 'writing') { // never swap the network under a running textS.pendingModel = { entry, trainedOn, updated, info };S.info = { kind: 'waiting' }; renderInfo();return;9 unmodified lines}const old = S.engine;const normalizer = createNormalizer(ready.charset);S.engine = engine; S.engineUser = entry.user; S.sha = entry.manifest.sha256;S.normalizer = normalizer; S.trainedOn = trainedOn || null; S.version = entry.version || null;S.writer = createPageWriter({normalize: normalizer.normalize, xhModel: ready.xhModel, gapXh: ready.gapXh,6 unmodified linesrenderPicker();showWork();syncUi();}function onSyncError(e) {const have = ownEngine();if (!have && S.engine) { S.engine.terminate(); S.engine = null; S.writer = null; } // some other account's modelswitch (e.kind) {case 'cancelled': return;case 'signin': if (!have) showCard('signin'); return;254 unmodified linesel.write.disabled = writing || !S.engine;el.write.hidden = writing; el.cancel.hidden = !writing; // one place, two meaningsel.again.disabled = writing || !S.engine || !S.lastText;el.busy.hidden = !writing; el.info.hidden = writing;el.size.disabled = writing; el.spacing.disabled = writing;const canExport = !!S.page && !writing;el.save.disabled = !canExport;27 unmodified linesconst open = el.style.hidden;el.style.hidden = !open;el.styleBtn.setAttribute('aria-expanded', open ? 'true' : 'false');}function toggleMore() {57 unmodified linesif (S.cancelled) { settleAll(); setNote(el.note, S.page ? 'Abgebrochen. Was schon geschrieben ist, bleibt stehen.' : 'Abgebrochen.'); }setNote(el.bad, S.bad ? badText(S.bad) : '');syncUi();if (S.pendingModel) { const p = S.pendingModel; S.pendingModel = null; await useModel(p.entry, p.trainedOn, { updated: p.updated, info: p.info }); }save();}function onPiece({ page, fresh, problems }) {S.page = page;S.total += wordPoints(fresh);80 unmodified linesapplyLook();}/** Buttons, swatches and the sheet's own colours follow the look. */function applyLook() {const l = S.look;for (const b of el.style.querySelectorAll('.gen-choice')) {const v = b.dataset.k === 'width' ? Number(b.dataset.v) : b.dataset.v;b.setAttribute('aria-checked', l[b.dataset.k] === v ? 'true' : 'false');}for (const b of el.inks.querySelectorAll('[data-ink]')) {const [color, name] = INKS[l.scheme][b.dataset.ink];3 unmodified lines}el.inkRow.hidden = l.pen === 'bleistift'; // graphite has no ink to chooseel.paper.dataset.scheme = l.scheme;}/** Change one part of the look here: from now on Schreiben keeps its own. */function setLook(key, value) {const next = normalizeLook(Object.assign({}, S.look, { [key]: value }));if (next[key] === S.look[key] && S.ownLook) return;S.look = next; S.ownLook = true;applyLook(); save();S.sheetKey = '';if (key === 'paper') paintSheet(); else redrawAll();}/** Until the look is changed here, it is the current writer's capture sheet (when they set one up). */10 unmodified linesif (JSON.stringify(next) === JSON.stringify(S.look)) return;S.look = next;applyLook();S.sheetKey = ''; redrawAll();}let relayoutFrame = 0;7 unmodified linesel.text.addEventListener('input', () => { setNote(el.note, ''); autosize(); save(); });el.bias.addEventListener('input', () => { S.settings.bias = Number(el.bias.value); save(); });// Lesbarkeit changes how the network writes, so letting go of the slider writes the text again.el.bias.addEventListener('change', () => { if (S.lastText && S.phase === 'idle') run(S.lastText); });el.styleBtn.addEventListener('click', toggleStyle);el.moreBtn.addEventListener('click', toggleMore);el.modelPick.addEventListener('change', () => choose(el.modelPick.value));29 unmodified lineslastW = w;redrawAll();}).observe(el.paper);window.addEventListener('resize', () => { redrawAll(); autosize(); });window.addEventListener('hw-auth', () => { S.stale = true; if (S.visible) refresh(); });window.addEventListener('online', () => { if (S.visible && !S.syncing) refresh(); });};17 unmodified linesconst c = await store.kvGet('modelChoice', null);if (c && typeof c.id === 'string' && c.user === hf.userName()) S.choice = c.id;} catch (_) { /* "Neuestes" */ }applySettings();wire();syncUi();await followCapture();}1 unmodified linefunction show() {S.visible = true;S.follow = true;autosize();redrawAll();followCapture();1 unmodified lineif (stale && !S.syncing) refresh();}function hide() { S.visible = false; }return {init, show, hide, refresh,info: () => ms.info(),/** For tests and the diagnostics page. */debug: () => ({ choice: S.choice, version: S.version ? S.version.id : null, models: ((S.index && S.index.models) || []).map((m) => m.id), phase: S.phase, page: S.page, seed: S.seed, sha: S.sha, settings: S.settings, look: Object.assign({}, S.look), ownLook: S.ownLook, runs: S.runId, scale: S.geo ? S.geo.scale : 0, text: S.lastText, bad: S.bad, settled: S.settled, total: S.total, done: S.done }),};12345612 unmodified lines1920212223242552 unmodified lines787980818283845 unmodified lines909192939495969732 unmodified lines13013113213313413513613713813914014114225 unmodified lines1681691701711721731749 unmodified lines1841851861871881891901916 unmodified lines198199200201202203204205206207208209254 unmodified lines46446546646746846947047127 unmodified lines49950050150250350450557 unmodified lines56356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961080 unmodified lines6916926936946956966976986997007017027037047057063 unmodified lines71071171271371471571671771871972072172272372472572672772872973073110 unmodified lines7427437447457467477487 unmodified lines75675775875976076176276329 unmodified lines79379479579679779879917 unmodified lines8178188198208218228238248258268271 unmodified line8298308318328338348358361 unmodified line838839840841842843844845846847848849850// The Schreiben screen: text in, handwriting out (SPEC 2.5). Two modes: "Zettel"// (this file: a short text on a sheet of its own size) and "Seite" (page-view.js:// A4 pages and a PDF); the model, Stil and Lesbarkeit are shared.//// Pieces: model-store.js (download, check, cache), engine-client.js (network in a// worker), page-writer.js (text -> page, piece by piece), render.js (drawing, export).12 unmodified linesimport { drawWord, drawWords, drawPartial, drawSheet, toSVG, toCanvas, lookColors, normalizeLook, lookFromCapture, INKS, DEFAULT_LOOK } from './render.js';import { createEngine } from './engine-client.js';import { createModelStore } from './model-store.js';import { createPageView } from './page-view.js';import { normalize as normalizeDisplay, WIDTHS as CAPTURE_WIDTHS } from '../capture/ink.js';const PAGE_TOP = 6.5, PAGE_MARGIN = 3; // first baseline and side margin, x-heights (ascenders of enlarged words need about 3.5)52 unmodified linesmodelRow: $('gen-model-row'), modelPick: $('gen-model-pick'),save: $('gen-save'), saveMenu: $('gen-save-menu'),png: $('gen-png'), inkPng: $('gen-ink-png'), svg: $('gen-svg'), copy: $('gen-copy'),gen: $('gen'), modes: document.querySelector('#gen .gen-modes'), pgStage: $('pg-stage'), pgPages: $('pg-pages'),};const ctx = el.canvas.getContext('2d');const gctx = el.lines.getContext('2d'); // the paper and its lines, under the ink5 unmodified linessettings: Object.assign({}, DEFAULTS),look: Object.assign({}, DEFAULT_LOOK),ownLook: false, // changed here at least once: no longer follows the capture sheetvisible: false, mode: 'zettel', pageStatus: false,entry: null, ready: null, // the model in use, for the page mode's engines// modelengine: null, engineUser: null, sha: null, normalizer: null, writer: null, trainedOn: null,version: null, index: null, choice: 'newest', switching: false, again: false,32 unmodified linesel.card.hidden = false;el.work.hidden = true;el.empty.hidden = true;applyMode();}function showWork() {el.card.hidden = true;el.work.hidden = false;applyMode();renderInfo();syncUi();autosize();25 unmodified lines};async function useModel(entry, trainedOn, { updated = false, info = null } = {}) {if (S.phase === 'writing' || pageView.busy()) { // never swap the network under a running textS.pendingModel = { entry, trainedOn, updated, info };S.info = { kind: 'waiting' }; renderInfo();return;9 unmodified lines}const old = S.engine;const normalizer = createNormalizer(ready.charset);S.engine = engine; S.engineUser = entry.user; S.sha = entry.manifest.sha256; S.entry = entry; S.ready = ready;pageView.modelChanged();S.normalizer = normalizer; S.trainedOn = trainedOn || null; S.version = entry.version || null;S.writer = createPageWriter({normalize: normalizer.normalize, xhModel: ready.xhModel, gapXh: ready.gapXh,6 unmodified linesrenderPicker();showWork();syncUi();pageView.sync();}function onSyncError(e) {const have = ownEngine();if (!have && S.engine) { S.engine.terminate(); S.engine = null; S.writer = null; S.entry = null; pageView.modelChanged(); } // some other account's modelswitch (e.kind) {case 'cancelled': return;case 'signin': if (!have) showCard('signin'); return;254 unmodified linesel.write.disabled = writing || !S.engine;el.write.hidden = writing; el.cancel.hidden = !writing; // one place, two meaningsel.again.disabled = writing || !S.engine || !S.lastText;const seite = S.mode === 'seite';el.busy.hidden = !writing || seite; el.info.hidden = seite ? S.pageStatus : writing;el.size.disabled = writing; el.spacing.disabled = writing;const canExport = !!S.page && !writing;el.save.disabled = !canExport;27 unmodified linesconst open = el.style.hidden;el.style.hidden = !open;el.styleBtn.setAttribute('aria-expanded', open ? 'true' : 'false');if (open) pageView.unpick();}function toggleMore() {57 unmodified linesif (S.cancelled) { settleAll(); setNote(el.note, S.page ? 'Abgebrochen. Was schon geschrieben ist, bleibt stehen.' : 'Abgebrochen.'); }setNote(el.bad, S.bad ? badText(S.bad) : '');syncUi();await takePendingModel();save();}async function takePendingModel() {if (!S.pendingModel || S.phase === 'writing' || pageView.busy()) return;const p = S.pendingModel; S.pendingModel = null;await useModel(p.entry, p.trainedOn, { updated: p.updated, info: p.info });}// ---------- Zettel / Seite ----------const pageView = createPageView({store, toast,model: () => (S.engine && S.entry && S.ready ? { entry: S.entry, info: S.ready, normalizer: S.normalizer } : null),look: () => S.look,bias: () => S.settings.bias,onIdle: () => { takePendingModel(); },onStatus: (shown) => { S.pageStatus = shown; syncUi(); },});/** Which mode's sheet, tools and text field are shown (the model card replaces both sheets). */function applyMode() {const seite = S.mode === 'seite';el.gen.dataset.mode = S.mode;for (const b of el.modes.querySelectorAll('[data-mode]')) b.setAttribute('aria-checked', b.dataset.mode === S.mode ? 'true' : 'false');el.stage.hidden = seite && el.card.hidden;el.pgStage.hidden = !seite || !el.card.hidden;pageView.activate(seite && el.card.hidden && S.visible);}function setMode(mode) {if (mode === S.mode || !['zettel', 'seite'].includes(mode)) return;S.mode = mode;closeMenu();applyMode();applyLook();syncUi();store.kvSet('generateMode', mode).catch(() => {});if (mode === 'zettel' && S.visible) { autosize(); redrawAll(); }}function onPiece({ page, fresh, problems }) {S.page = page;S.total += wordPoints(fresh);80 unmodified linesapplyLook();}/** Buttons, swatches and the sheet's own colours follow the look (paper and letter* size of the page mode are its own). */function applyLook() {const l = S.look;const ps = pageView.settings;// Letter size belongs to the page mode only: in Zettel none of its (hidden) choices is on.const value = (k) => (k === 'docsize' ? (S.mode === 'seite' ? ps.size : null) : k === 'paper' && S.mode === 'seite' ? ps.paper : l[k]);for (const b of el.style.querySelectorAll('.gen-choice')) {const v = b.dataset.k === 'width' ? Number(b.dataset.v) : b.dataset.v;b.setAttribute('aria-checked', value(b.dataset.k) === v ? 'true' : 'false');}for (const b of el.inks.querySelectorAll('[data-ink]')) {const [color, name] = INKS[l.scheme][b.dataset.ink];3 unmodified lines}el.inkRow.hidden = l.pen === 'bleistift'; // graphite has no ink to chooseel.paper.dataset.scheme = l.scheme;el.pgPages.dataset.scheme = l.scheme;}/** Change one part of the look here: from now on Schreiben keeps its own. */function setLook(key, value) {if (key === 'docsize' || (key === 'paper' && S.mode === 'seite')) {pageView.set(key === 'docsize' ? 'size' : 'paper', value);applyLook();return;}const next = normalizeLook(Object.assign({}, S.look, { [key]: value }));if (next[key] === S.look[key] && S.ownLook) return;S.look = next; S.ownLook = true;applyLook(); save();S.sheetKey = '';if (key === 'paper') paintSheet(); else { redrawAll(); pageView.redraw(); }}/** Until the look is changed here, it is the current writer's capture sheet (when they set one up). */10 unmodified linesif (JSON.stringify(next) === JSON.stringify(S.look)) return;S.look = next;applyLook();S.sheetKey = ''; redrawAll(); pageView.redraw();}let relayoutFrame = 0;7 unmodified linesel.text.addEventListener('input', () => { setNote(el.note, ''); autosize(); save(); });el.bias.addEventListener('input', () => { S.settings.bias = Number(el.bias.value); save(); });// Lesbarkeit changes how the network writes, so letting go of the slider writes the text again.el.bias.addEventListener('change', () => { if (S.mode === 'zettel' && S.lastText && S.phase === 'idle') run(S.lastText); });el.modes.addEventListener('click', (e) => { const b = e.target.closest('[data-mode]'); if (b) setMode(b.dataset.mode); });el.styleBtn.addEventListener('click', toggleStyle);el.moreBtn.addEventListener('click', toggleMore);el.modelPick.addEventListener('change', () => choose(el.modelPick.value));29 unmodified lineslastW = w;redrawAll();}).observe(el.paper);window.addEventListener('resize', () => { redrawAll(); autosize(); pageView.autosize(); });window.addEventListener('hw-auth', () => { S.stale = true; if (S.visible) refresh(); });window.addEventListener('online', () => { if (S.visible && !S.syncing) refresh(); });};17 unmodified linesconst c = await store.kvGet('modelChoice', null);if (c && typeof c.id === 'string' && c.user === hf.userName()) S.choice = c.id;} catch (_) { /* "Neuestes" */ }try { const m = await store.kvGet('generateMode', null); if (m === 'seite') S.mode = 'seite'; } catch (_) { /* Zettel */ }await pageView.init();applySettings();wire();applyMode();syncUi();await followCapture();}1 unmodified linefunction show() {S.visible = true;S.follow = true;pageView.show();applyMode();autosize();redrawAll();followCapture();1 unmodified lineif (stale && !S.syncing) refresh();}function hide() { S.visible = false; pageView.hide(); }return {init, show, hide, refresh,info: () => ms.info(),/** For tests: the page mode's state. */pageDebug: () => Object.assign(pageView.debug(), { mode: S.mode }),/** For tests and the diagnostics page. */debug: () => ({ choice: S.choice, version: S.version ? S.version.id : null, models: ((S.index && S.index.models) || []).map((m) => m.id), phase: S.phase, page: S.page, seed: S.seed, sha: S.sha, settings: S.settings, look: Object.assign({}, S.look), ownLook: S.ownLook, runs: S.runId, scale: S.geo ? S.geo.scale : 0, text: S.lastText, bad: S.bad, settled: S.settled, total: S.total, done: S.done }),};
3 unmodified lines456789103 unmodified linesexport const MIN_LINES = 20;/** The driver's defaults (EPOCHS, LINES_ONLY, SAMPLE_EVERY in scripts/retrain.py). */export const DEFAULTS = { epochs: 12, lines_only: false, sample_every: 1 };/** From the start on GitHub to the first status.json: queue, checkout, installing. */export const START_MINUTES = 2;3 unmodified lines456789103 unmodified linesexport const MIN_LINES = 20;/** The driver's defaults (EPOCHS, LINES_ONLY, SAMPLE_EVERY in scripts/retrain.py). */export const DEFAULTS = { epochs: 20, lines_only: false, sample_every: 1 };/** From the start on GitHub to the first status.json: queue, checkout, installing. */export const START_MINUTES = 2;
570 unmodified lines571572573570 unmodified lines.gen-go.stop i { width: 10px; height: 10px; border-radius: 2px; background: currentColor; }.gen-note { font-size: 14px; color: var(--muted); padding: 4px 4px 0; }#gen-note { color: var(--ink); }570 unmodified lines571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628570 unmodified lines.gen-go.stop i { width: 10px; height: 10px; border-radius: 2px; background: currentColor; }.gen-note { font-size: 14px; color: var(--muted); padding: 4px 4px 0; }#gen-note { color: var(--ink); }/* ---------- Schreiben: Zettel / Seite ----------One switch above the sheet. Seite shows A4 pages fitted to the column, one underthe other, each the paper of its own scheme; the dock below is the same as Zettel's. */.gen[data-mode="seite"] [data-only="zettel"], .gen[data-mode="zettel"] [data-only="seite"] { display: none !important; }.gen-modes { flex: none; display: flex; margin: 0 0 2px -10px; }.gen-modes .gen-choice { font-weight: 500; }.pg-stage {flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin;margin: 0 -12px; padding: 4px 12px 18px;}.pg-pages { position: relative; display: grid; gap: 20px; --pg-hint: #8B93A0; }.pg-pages[data-scheme="light_on_dark"] { --pg-hint: var(--paper-dark-muted); }.pg-page {position: relative; aspect-ratio: 210 / 297; background: var(--paper-light-bg); border-radius: 3px;box-shadow: 0 0 0 1px var(--gen-paper-edge), 0 1px 2px rgba(20, 26, 38, .06), 0 14px 30px -14px rgba(20, 26, 38, .22);touch-action: pan-y; cursor: pointer;}.pg-pages[data-scheme="light_on_dark"] .pg-page { background: var(--paper-dark-bg); box-shadow: 0 0 0 1px rgba(255, 255, 255, .06), 0 14px 30px -14px rgba(20, 26, 38, .3); }.pg-page canvas { display: block; width: 100%; height: 100%; border-radius: inherit; }.pg-empty { position: absolute; left: 0; right: 0; top: 2.6%; z-index: 1; text-align: center; padding: 0 24px; color: var(--pg-hint); pointer-events: none; }.pg-pick {position: absolute; left: 0; top: 0; z-index: 3; padding: 4px;background: var(--sheet); border: 1px solid var(--line); border-radius: 14px; box-shadow: 0 10px 28px rgba(20, 26, 38, .18);}.pg-redo {appearance: none; border: 0; background: none; font: inherit; font-size: 16px; font-weight: 600; color: var(--accent);display: inline-flex; align-items: center; gap: 8px; height: 48px; padding: 0 16px; border-radius: 10px;cursor: pointer; touch-action: manipulation; white-space: nowrap;}.pg-redo .ic { width: 18px; height: 18px; stroke-width: 1.9; }.pg-redo:not(:disabled):hover { background: var(--accent-soft); }.pg-redo:disabled { color: var(--muted); cursor: default; }.pg-redo:focus-visible { outline: 3px solid color-mix(in srgb, var(--accent) 55%, transparent); outline-offset: -3px; }.gen-busy .pbar { flex: none; width: 72px; margin: 0; }.gen-dock { grid-template-columns: minmax(0, 1fr); } /* a long status line never widens the column */#pg-busy-text { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }#pg-text {flex: 1; min-width: 0; font: inherit; font-size: 17px; line-height: 25px; color: var(--ink);background: none; border: 0; outline: 0; resize: none; padding: 11px 0; margin: 0;max-height: min(30vh, 220px); overflow-y: auto; scrollbar-width: thin;}#pg-text::placeholder { color: var(--muted); }/* Away from the keyboard the text steps back to two lines: the pages are the thing to look at. *//* (25 px lines: 11 + 2 x 25 shows exactly two; the bottom padding moves out of the box so no third line peeks in) */.pg-composer:not(:focus-within) #pg-text { max-height: 61px; padding-bottom: 0; margin-bottom: 11px; }.pg-switch { display: inline-flex; align-items: center; gap: 12px; min-height: 48px; font-size: 15px; color: var(--ink); cursor: pointer; justify-self: start; }.pg-short { display: none; }@media (max-width: 560px) {.pg-long { display: none; } .pg-short { display: inline; } .pg-pages { gap: 14px; } #pg-bar { display: none; }/* On a phone the open Stil bar needs the height; nobody switches modes while choosing a pen. */.gen:has(> .gen-dock #gen-style:not([hidden])) .gen-modes { display: none; }/* the short progress fits beside the tools; the longer hint when done may take two lines */.gen-status:has(> #pg-busy:not([hidden])) { flex-basis: 110px; }}
11 unmodified lines12131415161711 unmodified lines'js/engine/engine.js', 'js/engine/worker.js','js/generate/layout.js', 'js/generate/page-writer.js', 'js/generate/render.js','js/generate/model-store.js', 'js/generate/engine-client.js', 'js/generate/view.js','js/capture/ink.js', 'js/capture/look.js','js/library.js', 'library.css','training.css', 'js/training/view.js', 'js/training/state.js', 'js/training/github.js', 'js/training/github-settings.js', 'js/training/curve.js',11 unmodified lines1213141516171811 unmodified lines'js/engine/engine.js', 'js/engine/worker.js','js/generate/layout.js', 'js/generate/page-writer.js', 'js/generate/render.js','js/generate/model-store.js', 'js/generate/engine-client.js', 'js/generate/view.js','js/generate/document.js', 'js/generate/pdf.js', 'js/generate/page-view.js','js/capture/ink.js', 'js/capture/look.js','js/library.js', 'library.css','training.css', 'js/training/view.js', 'js/training/state.js', 'js/training/github.js', 'js/training/github-settings.js', 'js/training/curve.js',
config.js+1-1
index.html+46-9
js/generate/document.jsAdded+436
js/generate/engine-client.js+87-1
js/generate/page-view.jsAdded+517
js/generate/pdf.jsAdded+216
js/generate/render.js+96-14
js/generate/view.js+81-14
js/training/state.js+1-1
styles.css+55
sw.js+1