finnbusse commited on
Commit
730a007
·
verified ·
1 Parent(s): 8bd1276

App aktualisiert

Browse files
Files changed (6) hide show
  1. config.js +1 -1
  2. index.html +45 -8
  3. js/capture/ink.js +26 -19
  4. js/generate/render.js +295 -34
  5. js/generate/view.js +147 -47
  6. styles.css +68 -21
config.js CHANGED
@@ -3,7 +3,7 @@
3
  // No account name here: the account comes from the sign-in at runtime.
4
  self.HW_CONFIG = Object.freeze({
5
  appName: 'handwriting-capture',
6
- version: '0.5.0',
7
  datasetRepo: 'handwriting-fable', // dataset <user>/handwriting-fable (private)
8
  modelRepo: 'handwriting-fable-model', // model <user>/handwriting-fable-model (private)
9
  hfBase: 'https://huggingface.co',
 
3
  // No account name here: the account comes from the sign-in at runtime.
4
  self.HW_CONFIG = Object.freeze({
5
  appName: 'handwriting-capture',
6
+ version: '0.6.0',
7
  datasetRepo: 'handwriting-fable', // dataset <user>/handwriting-fable (private)
8
  modelRepo: 'handwriting-fable-model', // model <user>/handwriting-fable-model (private)
9
  hfBase: 'https://huggingface.co',
index.html CHANGED
@@ -183,6 +183,7 @@
183
  <!-- The sheet. It is always there; without a model it says why and what to do. -->
184
  <div class="gen-stage" id="gen-stage">
185
  <div class="gen-paper" id="gen-paper">
 
186
  <canvas id="gen-canvas" aria-label="Geschriebener Text"></canvas>
187
  <p class="gen-empty" id="gen-empty">Hier erscheint deine Schrift.</p>
188
  <div class="gen-state" id="gen-model" role="status">
@@ -212,6 +213,7 @@
212
  <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>
213
  <div class="gen-menu" id="gen-save-menu" role="menu" hidden>
214
  <button type="button" role="menuitem" id="gen-png" disabled>Als Bild</button>
 
215
  <button type="button" role="menuitem" id="gen-svg" disabled>Als SVG</button>
216
  <button type="button" role="menuitem" id="gen-copy" disabled hidden>Kopieren</button>
217
  </div>
@@ -219,15 +221,50 @@
219
  </div>
220
  </div>
221
 
 
222
  <div class="gen-style" id="gen-style" hidden>
223
- <label class="gen-ctl"><span>Lesbarkeit</span><input type="range" id="gen-bias" min="0" max="1.2" step="0.05" value="0.4"></label>
224
- <label class="gen-ctl"><span>Größe</span><input type="range" id="gen-size" min="6" max="30" step="1" value="11"></label>
225
- <label class="gen-ctl"><span>Zeilenabstand</span><input type="range" id="gen-spacing" min="5" max="9" step="0.25" value="6.5"></label>
226
- <div class="gen-ctl gen-ctl-ink"><span id="gen-ink-l">Tinte</span>
227
- <div class="gen-inks" id="gen-inks" role="radiogroup" aria-labelledby="gen-ink-l">
228
- <button class="gen-ink" type="button" role="radio" aria-checked="true" data-ink="blueblack" aria-label="Blauschwarz" title="Blauschwarz"><i style="background:#1b2a49"></i></button>
229
- <button class="gen-ink" type="button" role="radio" aria-checked="false" data-ink="black" aria-label="Schwarz" title="Schwarz"><i style="background:#15171a"></i></button>
230
- <button class="gen-ink" type="button" role="radio" aria-checked="false" data-ink="blue" aria-label="Königsblau" title="Königsblau"><i style="background:#2141b8"></i></button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  </div>
232
  </div>
233
  </div>
 
183
  <!-- The sheet. It is always there; without a model it says why and what to do. -->
184
  <div class="gen-stage" id="gen-stage">
185
  <div class="gen-paper" id="gen-paper">
186
+ <canvas class="gen-lines" id="gen-lines" aria-hidden="true"></canvas>
187
  <canvas id="gen-canvas" aria-label="Geschriebener Text"></canvas>
188
  <p class="gen-empty" id="gen-empty">Hier erscheint deine Schrift.</p>
189
  <div class="gen-state" id="gen-model" role="status">
 
213
  <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>
214
  <div class="gen-menu" id="gen-save-menu" role="menu" hidden>
215
  <button type="button" role="menuitem" id="gen-png" disabled>Als Bild</button>
216
+ <button type="button" role="menuitem" id="gen-ink-png" disabled>Ohne Papier</button>
217
  <button type="button" role="menuitem" id="gen-svg" disabled>Als SVG</button>
218
  <button type="button" role="menuitem" id="gen-copy" disabled hidden>Kopieren</button>
219
  </div>
 
221
  </div>
222
  </div>
223
 
224
+ <!-- Stil: the look of the sheet (the same options as when recording), then the finer controls -->
225
  <div class="gen-style" id="gen-style" hidden>
226
+ <div class="gen-style-main">
227
+ <div class="gen-opt gen-opt-pen"><span class="gen-opt-l" id="gs-pen-l">Stift</span>
228
+ <div class="gen-choices" role="radiogroup" aria-labelledby="gs-pen-l">
229
+ <button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="pen" data-v="fineliner">Fineliner</button>
230
+ <button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="pen" data-v="fueller">Füller</button>
231
+ <button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="pen" data-v="bleistift">Bleistift</button>
232
+ </div>
233
+ </div>
234
+ <div class="gen-opt gen-opt-width"><span class="gen-opt-l" id="gs-width-l">Strichstärke</span>
235
+ <div class="gen-choices" role="radiogroup" aria-labelledby="gs-width-l">
236
+ <button class="gen-choice gen-w" type="button" role="radio" aria-checked="false" data-k="width" data-v="0.14" aria-label="Sehr fein" title="Sehr fein"><i style="height:1px"></i></button>
237
+ <button class="gen-choice gen-w" type="button" role="radio" aria-checked="false" data-k="width" data-v="0.19" aria-label="Fein" title="Fein"><i style="height:1.5px"></i></button>
238
+ <button class="gen-choice gen-w" type="button" role="radio" aria-checked="false" data-k="width" data-v="0.25" aria-label="Mittel" title="Mittel"><i style="height:2px"></i></button>
239
+ <button class="gen-choice gen-w" type="button" role="radio" aria-checked="false" data-k="width" data-v="0.32" aria-label="Kräftig" title="Kräftig"><i style="height:3px"></i></button>
240
+ <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>
241
+ </div>
242
+ </div>
243
+ <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>
244
+ <div class="gen-opt gen-opt-paper"><span class="gen-opt-l" id="gs-paper-l">Papier</span>
245
+ <div class="gen-choices" role="radiogroup" aria-labelledby="gs-paper-l">
246
+ <button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="paper" data-v="blanko">Blanko</button>
247
+ <button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="paper" data-v="liniert">Liniert</button>
248
+ <button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="paper" data-v="kariert">Kariert</button>
249
+ </div>
250
+ </div>
251
+ <div class="gen-opt gen-opt-scheme"><span class="gen-opt-l" id="gs-scheme-l">Farben</span>
252
+ <div class="gen-choices" role="radiogroup" aria-labelledby="gs-scheme-l">
253
+ <button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="scheme" data-v="dark_on_light">Dunkel auf hell</button>
254
+ <button class="gen-choice" type="button" role="radio" aria-checked="false" data-k="scheme" data-v="light_on_dark">Hell auf dunkel</button>
255
+ </div>
256
+ </div>
257
+ <div class="gen-opt gen-opt-more"><button class="gen-more-btn" id="gen-more-btn" type="button" aria-expanded="false" aria-controls="gen-more">Erweitert<i aria-hidden="true"></i></button></div>
258
+ </div>
259
+ <div class="gen-style-more" id="gen-more" hidden>
260
+ <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>
261
+ <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>
262
+ <div class="gen-opt" id="gen-ink-row"><span class="gen-opt-l" id="gen-ink-l">Tinte</span>
263
+ <div class="gen-inks" id="gen-inks" role="radiogroup" aria-labelledby="gen-ink-l">
264
+ <button class="gen-ink" type="button" role="radio" aria-checked="true" data-ink="blueblack" aria-label="Blauschwarz" title="Blauschwarz"><i></i></button>
265
+ <button class="gen-ink" type="button" role="radio" aria-checked="false" data-ink="black" aria-label="Schwarz" title="Schwarz"><i></i></button>
266
+ <button class="gen-ink" type="button" role="radio" aria-checked="false" data-ink="blue" aria-label="Königsblau" title="Königsblau"><i></i></button>
267
+ </div>
268
  </div>
269
  </div>
270
  </div>
js/capture/ink.js CHANGED
@@ -18,7 +18,7 @@ const BASELINE_FRAC = 0.64; // baseline position inside the band (unchanged
18
  const GUIDE_INSET = 32; // baseline starts/ends this far inside the band
19
  const EDGE = 6; // no paper line closer than this to the sheet edge
20
  const TAU_MS = 9; // pressure smoothing (Füller width, Bleistift tone)
21
- const TONES = 8; // Bleistift: pressure levels, one grain pattern each
22
  const GRAIN = 64; // grain tile, device px
23
 
24
  /** Any stored or half-valid object -> a complete, valid set of options. */
@@ -180,6 +180,28 @@ function makeGrain(c, colors, devScale) {
180
 
181
  const clamp01 = (v) => (v > 0 ? (v < 1 ? v : 1) : 0);
182
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  /**
184
  * A renderer for one 2D context. configure() before drawing (cheap when nothing changed);
185
  * draw(stroke, from) draws the samples from index `from` on, as the recorder delivers them.
@@ -201,26 +223,11 @@ export function createInk(c) {
201
  }
202
 
203
  /** Fold sample i into the smoothed pressure. */
204
- function advance(s, i) {
205
- const p = clamp01(s.p[i]);
206
- if (i === 0) { st.pe = p; return; }
207
- const dt = s.t[i] - s.t[i - 1];
208
- st.pe += (p - st.pe) * (1 - Math.exp(-(dt > 0 ? dt : 0) / TAU_MS));
209
- }
210
 
211
- function lineWidthNow() {
212
- if (pen !== 'fueller') return width;
213
- // Thin on light pressure, fuller on firm pressure; nominal width at pressure 0.5.
214
- const k = 0.4 + 1.2 * st.pe;
215
- return width * (k < 1.6 ? k : 1.6);
216
- }
217
 
218
- function styleNow() {
219
- if (pen !== 'bleistift') return colors.ink;
220
- let k = Math.round(st.pe * 1.25 * (TONES - 1)); // pencil pressure seldom reaches 1
221
- if (k > TONES - 1) k = TONES - 1;
222
- return grain[k];
223
- }
224
 
225
  function draw(s, from) {
226
  if (!colors) return;
 
18
  const GUIDE_INSET = 32; // baseline starts/ends this far inside the band
19
  const EDGE = 6; // no paper line closer than this to the sheet edge
20
  const TAU_MS = 9; // pressure smoothing (Füller width, Bleistift tone)
21
+ export const TONES = 8; // Bleistift: pressure levels, one grain pattern each
22
  const GRAIN = 64; // grain tile, device px
23
 
24
  /** Any stored or half-valid object -> a complete, valid set of options. */
 
180
 
181
  const clamp01 = (v) => (v > 0 ? (v < 1 ? v : 1) : 0);
182
 
183
+ // The pressure rules, shared with the Schreiben screen (its SVG export needs them without a canvas).
184
+
185
+ /** Smoothed pressure after sample i, given the smoothed value `pe` after sample i-1. */
186
+ export function smoothPressure(pe, s, i) {
187
+ const p = clamp01(s.p[i]);
188
+ if (i === 0) return p;
189
+ const dt = s.t[i] - s.t[i - 1];
190
+ return pe + (p - pe) * (1 - Math.exp(-(dt > 0 ? dt : 0) / TAU_MS));
191
+ }
192
+
193
+ /** Füller: thin on light pressure, fuller on firm pressure; nominal width at pressure 0.5. */
194
+ export function fuellerWidth(width, pe) {
195
+ const k = 0.4 + 1.2 * pe;
196
+ return width * (k < 1.6 ? k : 1.6);
197
+ }
198
+
199
+ /** Bleistift: the tone level (0 .. TONES-1) for a smoothed pressure. */
200
+ export function pencilLevel(pe) {
201
+ const k = Math.round(pe * 1.25 * (TONES - 1)); // pencil pressure seldom reaches 1
202
+ return k > TONES - 1 ? TONES - 1 : k;
203
+ }
204
+
205
  /**
206
  * A renderer for one 2D context. configure() before drawing (cheap when nothing changed);
207
  * draw(stroke, from) draws the samples from index `from` on, as the recorder delivers them.
 
223
  }
224
 
225
  /** Fold sample i into the smoothed pressure. */
226
+ function advance(s, i) { st.pe = smoothPressure(st.pe, s, i); }
 
 
 
 
 
227
 
228
+ const lineWidthNow = () => (pen === 'fueller' ? fuellerWidth(width, st.pe) : width);
 
 
 
 
 
229
 
230
+ const styleNow = () => (pen === 'bleistift' ? grain[pencilLevel(st.pe)] : colors.ink);
 
 
 
 
 
231
 
232
  function draw(s, from) {
233
  if (!colors) return;
js/generate/render.js CHANGED
@@ -1,5 +1,68 @@
1
  // Drawing and exporting handwriting. A page is what layout.js produces:
2
  // { strokes: Float32Array[] ([x, y, eos, ...] in xh units), width, height }.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  /** Split a point array into strokes: arrays of [x, y]. */
5
  export function toPolylines(points) {
@@ -13,6 +76,62 @@ export function toPolylines(points) {
13
  return out;
14
  }
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  /** Trace one stroke as a smooth curve through the midpoints of its segments. */
17
  function trace(ctx, line, scale, ox, oy) {
18
  const px = (p) => p[0] * scale + ox, py = (p) => p[1] * scale + oy;
@@ -30,58 +149,200 @@ function trace(ctx, line, scale, ox, oy) {
30
  ctx.lineTo(px(last), py(last));
31
  }
32
 
33
- /** Draw word arrays (as in page.strokes) onto a 2D context. `scale` = pixels per x-height. */
34
- export function drawStrokes(ctx, wordArrays, { scale, offsetX = 0, offsetY = 0, color = '#1b2a49', lineWidth = 0.16 } = {}) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  ctx.save();
36
- ctx.strokeStyle = color;
37
- ctx.lineWidth = Math.max(lineWidth * scale, 0.6);
38
- ctx.lineCap = 'round';
39
- ctx.lineJoin = 'round';
40
- ctx.beginPath();
41
- for (const points of wordArrays) for (const line of toPolylines(points)) trace(ctx, line, scale, offsetX, offsetY);
42
- ctx.stroke();
43
  ctx.restore();
44
  }
45
 
 
 
 
46
  /** Draw only the first `count` points of a word array (for the writing animation). */
47
- export function drawPartial(ctx, points, count, options) {
48
  const n = Math.min(count, points.length / 3);
49
  if (n <= 0) return;
50
  const part = points.slice(0, 3 * n);
51
  part[3 * (n - 1) + 2] = 1;
52
- drawStrokes(ctx, [part], options);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  }
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  const fmt = (v) => (Math.round(v * 100) / 100).toString();
56
 
57
- /** The page as a standalone SVG document (smooth paths, real vectors). */
58
- export function toSVG(page, { scale = 12, color = '#1b2a49', lineWidth = 0.16, background = null } = {}) {
59
- const w = page.width * scale, h = page.height * scale;
60
- const paths = [];
 
 
 
 
 
 
 
 
 
 
 
 
61
  for (const points of page.strokes) {
62
- let d = '';
63
- for (const line of toPolylines(points)) {
64
- const p = line.map(([x, y]) => [x * scale, y * scale]);
65
- d += `M${fmt(p[0][0])} ${fmt(p[0][1])}`;
66
- if (p.length === 1) { d += 'l0.01 0'; continue; }
67
- for (let i = 1; i < p.length - 1; i++) {
68
- d += `Q${fmt(p[i][0])} ${fmt(p[i][1])} ${fmt((p[i][0] + p[i + 1][0]) / 2)} ${fmt((p[i][1] + p[i + 1][1]) / 2)}`;
 
 
 
69
  }
70
- d += `L${fmt(p[p.length - 1][0])} ${fmt(p[p.length - 1][1])}`;
71
  }
72
- paths.push(`<path d="${d}"/>`);
73
  }
74
- const bg = background ? `<rect width="100%" height="100%" fill="${background}"/>` : '';
75
- return `<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${fmt(w)} ${fmt(h)}" width="${fmt(w)}" height="${fmt(h)}">${bg}` +
76
- `<g fill="none" stroke="${color}" stroke-width="${fmt(lineWidth * scale)}" stroke-linecap="round" stroke-linejoin="round">${paths.join('')}</g></svg>\n`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  }
78
 
79
- /** Render the page into a new canvas (for PNG export). */
80
- export function toCanvas(page, { scale = 24, color = '#1b2a49', lineWidth = 0.16, background = '#ffffff', createCanvas } = {}) {
 
 
 
 
 
81
  const make = createCanvas || ((w, h) => Object.assign(document.createElement('canvas'), { width: w, height: h }));
82
- const canvas = make(Math.ceil(page.width * scale), Math.ceil(page.height * scale));
83
- const ctx = canvas.getContext('2d');
84
- if (background) { ctx.fillStyle = background; ctx.fillRect(0, 0, canvas.width, canvas.height); }
85
- drawStrokes(ctx, page.strokes, { scale, color, lineWidth });
86
- return canvas;
 
 
 
 
 
 
 
87
  }
 
1
  // Drawing and exporting handwriting. A page is what layout.js produces:
2
  // { strokes: Float32Array[] ([x, y, eos, ...] in xh units), width, height }.
3
+ //
4
+ // The look ("Stil") is the same as on the capture sheet (capture/ink.js): pen, stroke
5
+ // width, paper, colours. Widths here are in x-heights, so they scale with the size of
6
+ // the writing. Generated strokes carry no pressure: their points are equidistant in
7
+ // time, so the speed between two points stands in for it (slow = firm), and ink.js
8
+ // smooths it exactly as it smooths a real pen's pressure. Everything below is a pure
9
+ // function of the page and the look: the same page always gives the same pixels.
10
+ import {
11
+ schemeColors, createInk, smoothPressure, fuellerWidth, pencilLevel, pencilColor, hexRgb, TONES,
12
+ } from '../capture/ink.js';
13
+
14
+ export const PENS = ['fineliner', 'fueller', 'bleistift'];
15
+ // Stroke widths in x-heights: the capture widths (0.75 .. 3 CSS px) on its writing of
16
+ // about 6 px x-height, slightly evened out. Index i matches capture/ink.js WIDTHS[i].
17
+ export const WIDTHS = [0.14, 0.19, 0.25, 0.32, 0.42];
18
+ export const PAPERS = ['blanko', 'liniert', 'kariert'];
19
+ export const SCHEMES = ['dark_on_light', 'light_on_dark'];
20
+ // Tinte per sheet scheme. 'blue' is the capture sheet's ink in both schemes.
21
+ export const INKS = {
22
+ dark_on_light: { blueblack: ['#1B2A49', 'Blauschwarz'], black: ['#15171A', 'Schwarz'], blue: ['#2141B8', 'Königsblau'] },
23
+ light_on_dark: { blueblack: ['#AEBBDD', 'Taubenblau'], black: ['#ECEEF2', 'Weiß'], blue: ['#C9D4FF', 'Hellblau'] },
24
+ };
25
+ export const DEFAULT_LOOK = Object.freeze({ pen: 'fineliner', width: 0.32, paper: 'blanko', scheme: 'dark_on_light', ink: 'blueblack' });
26
+
27
+ const STEP_MS = 4; // time between two generated points, for ink.js's pressure smoothing
28
+ const V_REF = 0.12; // median distance between two generated points, x-heights
29
+ const SUB_XH = 0.05; // longest straight piece when a curve is cut up for the pressure pens
30
+ const MIN_PX = 0.6; // thinnest line drawn, device px
31
+
32
+ /** Any stored or half-valid object -> a complete look. */
33
+ export function normalizeLook(o) {
34
+ const v = o && typeof o === 'object' ? o : {};
35
+ return {
36
+ pen: PENS.includes(v.pen) ? v.pen : DEFAULT_LOOK.pen,
37
+ width: WIDTHS.includes(v.width) ? v.width : DEFAULT_LOOK.width,
38
+ paper: PAPERS.includes(v.paper) ? v.paper : DEFAULT_LOOK.paper,
39
+ scheme: SCHEMES.includes(v.scheme) ? v.scheme : DEFAULT_LOOK.scheme,
40
+ ink: v.ink in INKS.dark_on_light ? v.ink : DEFAULT_LOOK.ink,
41
+ };
42
+ }
43
+
44
+ /** The capture sheet's options (capture/ink.js normalize()) as a Schreiben look. */
45
+ export function lookFromCapture(d, captureWidths) {
46
+ const i = captureWidths.indexOf(d.width);
47
+ return normalizeLook({
48
+ pen: d.pen, width: WIDTHS[i < 0 ? 1 : i], paper: d.paper === 'linie' ? 'liniert' : d.paper, scheme: d.scheme, ink: 'blue',
49
+ });
50
+ }
51
+
52
+ const FALLBACK = {
53
+ dark_on_light: { scheme: 'dark_on_light', dark: false, paper: '#FFFFFF', ink: '#2141B8', graphite: '#2B2E34', rule: '#9DB0CB', faint: '#DFE5EE' },
54
+ light_on_dark: { scheme: 'light_on_dark', dark: true, paper: '#1B1F26', ink: '#C9D4FF', graphite: '#E9ECF1', rule: '#52637F', faint: '#2F3746' },
55
+ };
56
+
57
+ /** Sheet colours for a look, with its ink: { paper, ink, graphite, rule, faint, dark }. */
58
+ export function lookColors(look) {
59
+ const l = normalizeLook(look);
60
+ const base = typeof document !== 'undefined' && typeof getComputedStyle === 'function' ? schemeColors(l.scheme) : FALLBACK[l.scheme];
61
+ return Object.assign({}, base, { ink: INKS[l.scheme][l.ink][0] });
62
+ }
63
+
64
+ /** The colour the strokes have (the graphite for Bleistift). */
65
+ export const strokeColor = (look, colors) => (look.pen === 'bleistift' ? colors.graphite : colors.ink);
66
 
67
  /** Split a point array into strokes: arrays of [x, y]. */
68
  export function toPolylines(points) {
 
76
  return out;
77
  }
78
 
79
+ // ---------- the pressure pens: speed -> pressure ----------
80
+
81
+ /** Pressure-like value at each point of a stroke: 0.5 at the usual speed, firmer when slower. */
82
+ function speedPressure(line) {
83
+ const n = line.length, p = new Float64Array(n);
84
+ for (let i = 1; i < n; i++) {
85
+ const v = Math.hypot(line[i][0] - line[i - 1][0], line[i][1] - line[i - 1][1]) / V_REF;
86
+ p[i] = 0.15 + 0.7 / (1 + v * Math.sqrt(v));
87
+ }
88
+ p[0] = n > 1 ? p[1] : 0.5;
89
+ return p;
90
+ }
91
+
92
+ /**
93
+ * One stroke as ink.js samples ({x, y, t, p} in xh), following the same smooth curve the
94
+ * Fineliner draws (quadratic pieces through the midpoints), cut into short straight pieces
95
+ * so that width and tone can change along it.
96
+ */
97
+ function penSamples(line) {
98
+ const pr = speedPressure(line);
99
+ const s = { x: [], y: [], t: [], p: [] };
100
+ const push = (x, y, t, p) => { s.x.push(x); s.y.push(y); s.t.push(t); s.p.push(p); };
101
+ const n = line.length;
102
+ push(line[0][0], line[0][1], 0, pr[0]);
103
+ if (n === 1) return s;
104
+ let ax = line[0][0], ay = line[0][1], at = 0, ap = pr[0];
105
+ for (let i = 1; i < n - 1; i++) {
106
+ const cx = line[i][0], cy = line[i][1], cp = pr[i], ct = i * STEP_MS;
107
+ const bx = (cx + line[i + 1][0]) / 2, by = (cy + line[i + 1][1]) / 2;
108
+ const bp = (cp + pr[i + 1]) / 2, bt = (i + 0.5) * STEP_MS;
109
+ const k = Math.max(1, Math.min(16, Math.ceil((Math.hypot(cx - ax, cy - ay) + Math.hypot(bx - cx, by - cy)) / SUB_XH)));
110
+ for (let j = 1; j <= k; j++) {
111
+ const u = j / k, a = (1 - u) * (1 - u), b = 2 * u * (1 - u), c = u * u;
112
+ push(a * ax + b * cx + c * bx, a * ay + b * cy + c * by, a * at + b * ct + c * bt, a * ap + b * cp + c * bp);
113
+ }
114
+ ax = bx; ay = by; at = bt; ap = bp;
115
+ }
116
+ const L = line[n - 1], lt = (n - 1) * STEP_MS, lp = pr[n - 1];
117
+ const k = Math.max(1, Math.min(16, Math.ceil(Math.hypot(L[0] - ax, L[1] - ay) / SUB_XH)));
118
+ for (let j = 1; j <= k; j++) {
119
+ const u = j / k;
120
+ push(ax + (L[0] - ax) * u, ay + (L[1] - ay) * u, at + (lt - at) * u, ap + (lp - ap) * u);
121
+ }
122
+ return s;
123
+ }
124
+
125
+ const sampleCache = new WeakMap();
126
+ /** ink.js samples for every stroke of a word (cached per word array: they never change). */
127
+ function wordSamples(points) {
128
+ let out = sampleCache.get(points);
129
+ if (!out) { out = toPolylines(points).map(penSamples); sampleCache.set(points, out); }
130
+ return out;
131
+ }
132
+
133
+ // ---------- drawing ----------
134
+
135
  /** Trace one stroke as a smooth curve through the midpoints of its segments. */
136
  function trace(ctx, line, scale, ox, oy) {
137
  const px = (p) => p[0] * scale + ox, py = (p) => p[1] * scale + oy;
 
149
  ctx.lineTo(px(last), py(last));
150
  }
151
 
152
+ const inks = new WeakMap(); // one ink.js renderer per 2D context (it keeps its grain patterns)
153
+
154
+ /**
155
+ * Draw one word array (an entry of page.strokes) onto a 2D context whose transform is the
156
+ * identity. o = { scale (device px per x-height), look, colors }. Each word is drawn on
157
+ * its own, so drawing word by word and drawing a whole page give the same pixels.
158
+ */
159
+ export function drawWord(ctx, points, { scale, look, colors, offsetX = 0, offsetY = 0 }) {
160
+ const l = look;
161
+ if (l.pen === 'fineliner') {
162
+ ctx.save();
163
+ ctx.globalCompositeOperation = 'source-over';
164
+ ctx.strokeStyle = colors.ink;
165
+ ctx.lineWidth = Math.max(l.width * scale, MIN_PX);
166
+ ctx.lineCap = 'round'; ctx.lineJoin = 'round';
167
+ ctx.beginPath();
168
+ for (const line of toPolylines(points)) trace(ctx, line, scale, offsetX, offsetY);
169
+ ctx.stroke();
170
+ ctx.restore();
171
+ return;
172
+ }
173
+ let ink = inks.get(ctx);
174
+ if (!ink) { ink = createInk(ctx); inks.set(ctx, ink); }
175
  ctx.save();
176
+ ctx.setTransform(scale, 0, 0, scale, offsetX, offsetY);
177
+ ink.configure({ pen: l.pen, width: Math.max(l.width, MIN_PX / scale) }, colors, scale);
178
+ for (const s of wordSamples(points)) ink.draw(s, 0);
 
 
 
 
179
  ctx.restore();
180
  }
181
 
182
+ /** Draw several word arrays, one after the other. */
183
+ export function drawWords(ctx, words, o) { for (const w of words) drawWord(ctx, w, o); }
184
+
185
  /** Draw only the first `count` points of a word array (for the writing animation). */
186
+ export function drawPartial(ctx, points, count, o) {
187
  const n = Math.min(count, points.length / 3);
188
  if (n <= 0) return;
189
  const part = points.slice(0, 3 * n);
190
  part[3 * (n - 1) + 2] = 1;
191
+ drawWord(ctx, part, o);
192
+ }
193
+
194
+ /**
195
+ * The paper's lines in xh units for a sheet `width` x `height` x-heights.
196
+ * Liniert: one line under every line of text. Kariert: squares of half a line, so the
197
+ * baselines sit on grid lines, the vertical ones starting at the left margin.
198
+ */
199
+ export function guideLines(paper, { width, height, spacing, top = 5, margin = 3 }) {
200
+ const ys = [], xs = [];
201
+ if (paper === 'blanko') return { ys, xs };
202
+ const step = paper === 'kariert' ? spacing / 2 : spacing;
203
+ for (let y = top - step * Math.floor(top / step); y <= height; y += step) ys.push(y);
204
+ if (paper === 'kariert') for (let x = margin - step * Math.floor(margin / step); x <= width; x += step) xs.push(x);
205
+ return { ys, xs };
206
  }
207
 
208
+ /**
209
+ * Paper colour and lines onto a context with the identity transform, `w` x `h` device px.
210
+ * g = { scale, spacing, top, margin, lineWidth (device px) }. Lines on whole device
211
+ * pixels when they are whole pixels wide, so they stay crisp.
212
+ */
213
+ export function drawSheet(ctx, w, h, look, colors, g) {
214
+ ctx.save();
215
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
216
+ ctx.globalCompositeOperation = 'source-over';
217
+ ctx.fillStyle = colors.paper; ctx.fillRect(0, 0, w, h);
218
+ const { ys, xs } = guideLines(look.paper, { width: w / g.scale, height: h / g.scale, spacing: g.spacing, top: g.top, margin: g.margin });
219
+ if (ys.length || xs.length) {
220
+ const lw = g.lineWidth, whole = Math.abs(lw - Math.round(lw)) < 1e-6;
221
+ const at = (v) => (whole ? Math.round(v * g.scale - lw / 2) + lw / 2 : v * g.scale);
222
+ ctx.lineWidth = lw; ctx.lineCap = 'butt';
223
+ ctx.strokeStyle = look.paper === 'liniert' ? colors.rule : colors.faint;
224
+ ctx.beginPath();
225
+ for (const y of ys) { ctx.moveTo(0, at(y)); ctx.lineTo(w, at(y)); }
226
+ for (const x of xs) { ctx.moveTo(at(x), 0); ctx.lineTo(at(x), h); }
227
+ ctx.stroke();
228
+ }
229
+ ctx.restore();
230
+ }
231
+
232
+ // ---------- export ----------
233
+
234
  const fmt = (v) => (Math.round(v * 100) / 100).toString();
235
 
236
+ /** Bézier path data of one stroke (the same curve trace() draws). */
237
+ function pathData(line, scale) {
238
+ const p = line.map(([x, y]) => [x * scale, y * scale]);
239
+ let d = `M${fmt(p[0][0])} ${fmt(p[0][1])}`;
240
+ if (p.length === 1) return `${d}l0.01 0`;
241
+ for (let i = 1; i < p.length - 1; i++) {
242
+ d += `Q${fmt(p[i][0])} ${fmt(p[i][1])} ${fmt((p[i][0] + p[i + 1][0]) / 2)} ${fmt((p[i][1] + p[i + 1][1]) / 2)}`;
243
+ }
244
+ return `${d}L${fmt(p[p.length - 1][0])} ${fmt(p[p.length - 1][1])}`;
245
+ }
246
+
247
+ /** Füller / Bleistift: the short straight pieces of every stroke, grouped by width or tone level. */
248
+ function svgPenGroups(page, look, scale) {
249
+ const groups = new Map(); // level -> path data
250
+ const add = (key, d) => groups.set(key, (groups.get(key) || '') + d);
251
+ const levels = 12; // Füller: width steps between 0.4x and 1.6x
252
  for (const points of page.strokes) {
253
+ for (const s of wordSamples(points)) {
254
+ let pe = 0, prev = null;
255
+ for (let i = 0; i < s.x.length; i++) {
256
+ pe = smoothPressure(pe, s, i);
257
+ const key = look.pen === 'fueller' ? Math.round(Math.min(1, pe) * levels) : pencilLevel(pe);
258
+ const x = fmt(s.x[i] * scale), y = fmt(s.y[i] * scale);
259
+ if (i === 0) { add(key, `M${x} ${y}l0.01 0`); prev = key; continue; }
260
+ const px = fmt(s.x[i - 1] * scale), py = fmt(s.y[i - 1] * scale);
261
+ add(key, key === prev ? `L${x} ${y}` : `M${px} ${py}L${x} ${y}`);
262
+ prev = key;
263
  }
 
264
  }
 
265
  }
266
+ // A new level always starts a new subpath; continuing "L"s join the previous point.
267
+ return [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([key, d]) => ({ key, d: d.replace(/^L/, 'M') }));
268
+ }
269
+
270
+ /**
271
+ * The page as a standalone SVG document. paper: true draws the paper and its lines as
272
+ * vectors. Fineliner is exact (one path per word, the same curves as on screen); Füller
273
+ * is the same pieces as on screen with the width in 13 steps; Bleistift is the same pieces
274
+ * in the eight graphite tones of the screen, with an SVG noise filter for the grain.
275
+ */
276
+ export function toSVG(page, { scale = 12, look = DEFAULT_LOOK, paper = false, guideWidth = 1, spacing = 6.5, top = 5, margin = 3 } = {}) {
277
+ const l = normalizeLook(look);
278
+ const colors = lookColors(l);
279
+ const w = page.width * scale, h = page.height * scale;
280
+ let out = `<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${fmt(w)} ${fmt(h)}" width="${fmt(w)}" height="${fmt(h)}">`;
281
+ if (paper) {
282
+ out += `<rect width="100%" height="100%" fill="${colors.paper}"/>`;
283
+ const { ys, xs } = guideLines(l.paper, { width: page.width, height: page.height, spacing, top, margin });
284
+ if (ys.length || xs.length) {
285
+ const d = ys.map((y) => `M0 ${fmt(y * scale)}H${fmt(w)}`).join('') + xs.map((x) => `M${fmt(x * scale)} 0V${fmt(h)}`).join('');
286
+ out += `<path d="${d}" fill="none" stroke="${l.paper === 'liniert' ? colors.rule : colors.faint}" stroke-width="${fmt(guideWidth)}"/>`;
287
+ }
288
+ }
289
+ const lw = l.width * scale;
290
+ if (l.pen === 'fineliner') {
291
+ const paths = page.strokes.map((points) => `<path d="${toPolylines(points).map((line) => pathData(line, scale)).join('')}"/>`);
292
+ out += `<g fill="none" stroke="${colors.ink}" stroke-width="${fmt(lw)}" stroke-linecap="round" stroke-linejoin="round">${paths.join('')}</g>`;
293
+ } else if (l.pen === 'fueller') {
294
+ const paths = svgPenGroups(page, l, scale).map(({ key, d }) => `<path stroke-width="${fmt(fuellerWidth(lw, key / 12))}" d="${d}"/>`);
295
+ out += `<g fill="none" stroke="${colors.ink}" stroke-linecap="round" stroke-linejoin="round">${paths.join('')}</g>`;
296
+ } else {
297
+ // Graphite: lighter tones first, so the stronger tone wins where pieces overlap.
298
+ // On a transparent background the tone is the graphite's opacity instead of a mix with the paper.
299
+ const paths = svgPenGroups(page, l, scale).map(({ key, d }) => (paper
300
+ ? `<path stroke="${pencilColor(colors, key)}" d="${d}"/>`
301
+ : `<path stroke="${colors.graphite}" stroke-opacity="${fmt(0.54 + 0.42 * (key / (TONES - 1)))}" d="${d}"/>`));
302
+ out += '<filter id="grain" x="-5%" y="-5%" width="110%" height="110%"><feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="1" seed="7" result="n"/>' +
303
+ '<feColorMatrix in="n" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1.1 0 0 0 1.45" result="m"/><feComposite in="SourceGraphic" in2="m" operator="in"/></filter>';
304
+ out += `<g fill="none" stroke-width="${fmt(lw)}" stroke-linecap="round" stroke-linejoin="round" filter="url(#grain)">${paths.join('')}</g>`;
305
+ }
306
+ return `${out}</svg>\n`;
307
+ }
308
+
309
+ /**
310
+ * Only the ink: the paper's colour is taken out again, so every pixel is the stroke colour
311
+ * with some transparency (exact for Fineliner and Füller, which have none to take out;
312
+ * for Bleistift its tone and grain become transparency).
313
+ */
314
+ function inkOnly(canvas, colors, color) {
315
+ const c = canvas.getContext('2d');
316
+ const img = c.getImageData(0, 0, canvas.width, canvas.height), d = img.data;
317
+ const p = hexRgb(colors.paper), k = hexRgb(color);
318
+ const v = [k[0] - p[0], k[1] - p[1], k[2] - p[2]], vv = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] || 1;
319
+ for (let i = 0; i < d.length; i += 4) {
320
+ if (!d[i + 3]) continue;
321
+ let t = ((d[i] - p[0]) * v[0] + (d[i + 1] - p[1]) * v[1] + (d[i + 2] - p[2]) * v[2]) / vv;
322
+ t = t > 0 ? (t < 1 ? t : 1) : 0;
323
+ d[i] = k[0]; d[i + 1] = k[1]; d[i + 2] = k[2]; d[i + 3] = Math.round(d[i + 3] * t);
324
+ }
325
+ c.putImageData(img, 0, 0);
326
  }
327
 
328
+ /**
329
+ * Render the page into a new canvas (for PNG export). paper: true = as on the sheet
330
+ * (paper, lines, ink); false = transparent background with the ink only.
331
+ */
332
+ export function toCanvas(page, { scale = 24, look = DEFAULT_LOOK, paper = true, guideWidth = 1, spacing = 6.5, top = 5, margin = 3, createCanvas } = {}) {
333
+ const l = normalizeLook(look);
334
+ const colors = lookColors(l);
335
  const make = createCanvas || ((w, h) => Object.assign(document.createElement('canvas'), { width: w, height: h }));
336
+ const W = Math.ceil(page.width * scale), H = Math.ceil(page.height * scale);
337
+ const inkCanvas = make(W, H);
338
+ drawWords(inkCanvas.getContext('2d'), page.strokes, { scale, look: l, colors });
339
+ if (!paper) {
340
+ if (l.pen === 'bleistift') inkOnly(inkCanvas, colors, colors.graphite);
341
+ return inkCanvas;
342
+ }
343
+ const out = make(W, H);
344
+ const c = out.getContext('2d');
345
+ drawSheet(c, W, H, l, colors, { scale, spacing, top, margin, lineWidth: guideWidth });
346
+ c.drawImage(inkCanvas, 0, 0);
347
+ return out;
348
  }
js/generate/view.js CHANGED
@@ -7,22 +7,26 @@
7
  // text, "Schreiben", "Nochmal schreiben", Lesbarkeit (bias) -> the network writes again
8
  // Schriftgröße, Zeilenabstand -> the finished pieces are laid out again (page-writer.relayout),
9
  // nothing is generated
10
- // Tintenfarbe, window size -> redraw only
 
 
 
 
11
  import { createNormalizer } from '../engine/engine.js';
12
  import { createPageWriter } from './page-writer.js';
13
- import { drawStrokes, drawPartial, toSVG, toCanvas } from './render.js';
14
  import { createEngine } from './engine-client.js';
15
  import { createModelStore } from './model-store.js';
 
16
 
17
- const INKS = { blueblack: '#1b2a49', black: '#15171a', blue: '#2141b8' };
18
- const LINE_WIDTH = 0.16; // pen width in x-heights (render.js default)
19
  const MIN_PAGE_WIDTH = 18; // x-heights
20
  const BASE_PPS = 260; // writing animation: points per second when nothing is waiting
21
  const CATCHUP_S = 1.0; // ... and never slower than "everything waiting within this many seconds"
22
  const MAX_PIXELS = 16e6; // canvas budget (per canvas; there are two)
23
  const RECHECK_MS = 5 * 60 * 1000; // look for a newer model at most this often
24
 
25
- const DEFAULTS = { text: '', bias: 0.4, size: 11, spacing: 6.5, ink: 'blueblack' }; // size: CSS px per x-height
26
 
27
  const mb = (bytes) => (bytes / 1e6).toFixed(1).replace('.', ',');
28
 
@@ -49,18 +53,22 @@ export function createGenerateView(deps) {
49
  note: $('gen-note'), chars: $('gen-chars'), bad: $('gen-bad'),
50
  bias: $('gen-bias'), size: $('gen-size'), spacing: $('gen-spacing'), inks: $('gen-inks'),
51
  infoText: $('gi-text'), infoBar: $('gi-bar'), infoFill: $('gi-fill'),
52
- stage: $('gen-stage'), paper: $('gen-paper'), canvas: $('gen-canvas'), empty: $('gen-empty'),
53
  info: $('gen-info'), styleBtn: $('gen-style-btn'), style: $('gen-style'),
 
54
  save: $('gen-save'), saveMenu: $('gen-save-menu'),
55
- png: $('gen-png'), svg: $('gen-svg'), copy: $('gen-copy'),
56
  };
57
  const ctx = el.canvas.getContext('2d');
 
58
  const layer = document.createElement('canvas'); // everything already written (the animation draws on top of it)
59
  const lctx = layer.getContext('2d');
60
  const motion = matchMedia('(prefers-reduced-motion: reduce)');
61
 
62
  const S = {
63
  settings: Object.assign({}, DEFAULTS),
 
 
64
  visible: false,
65
  // model
66
  engine: null, engineUser: null, sha: null, normalizer: null, writer: null, trainedOn: null,
@@ -71,7 +79,7 @@ export function createGenerateView(deps) {
71
  lastText: null, seed: null, pageWriter: null,
72
  page: null, bad: 0,
73
  // drawing
74
- settled: 0, pos: 0, total: 0, done: 0, geo: null, raf: 0, last: 0, width: 0,
75
  };
76
 
77
  // ---------- model card / info line ----------
@@ -215,41 +223,65 @@ export function createGenerateView(deps) {
215
 
216
  // ---------- drawing ----------
217
 
218
- const ink = () => INKS[S.settings.ink] || INKS.blueblack;
219
- const drawOptions = () => ({ scale: S.geo.scale, color: ink(), lineWidth: LINE_WIDTH });
220
 
221
  /** The page as shown and exported: widened when an unsplit piece sticks out past the right edge. */
222
- function framed(page) {
223
- let right = page.width;
224
- for (const w of page.words) right = Math.max(right, w.x + w.width + 3);
225
- return right > page.width ? Object.assign({}, page, { width: right }) : page;
226
- }
227
 
228
- /** Size the canvases to the page and the sheet; true when the bitmap size changed (= it is blank now). */
 
 
 
 
 
 
 
 
229
  function fit() {
230
  const page = S.page;
231
  const cssW = el.paper.clientWidth;
232
- if (!page || !cssW) return false;
233
- const cssScale = cssW / framed(page).width;
234
- const cssH = Math.max(1, Math.ceil(page.height * cssScale));
235
- let ratio = window.devicePixelRatio || 1;
236
- let pw = Math.round(cssW * ratio), ph = Math.round(cssH * ratio);
237
- if (pw * ph > MAX_PIXELS) {
238
- ratio *= Math.sqrt(MAX_PIXELS / (pw * ph));
239
- pw = Math.round(cssW * ratio); ph = Math.round(cssH * ratio);
240
- }
241
  const changed = el.canvas.width !== pw || el.canvas.height !== ph;
242
  if (changed) { el.canvas.width = pw; el.canvas.height = ph; layer.width = pw; layer.height = ph; }
243
  el.canvas.style.height = `${cssH}px`;
244
- S.geo = { scale: cssScale * ratio, cssScale };
245
  S.width = cssW;
 
246
  return changed;
247
  }
248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  function rebuildLayer() {
250
  if (!S.page || !S.geo) return;
251
  lctx.clearRect(0, 0, layer.width, layer.height);
252
- drawStrokes(lctx, S.page.strokes.slice(0, S.settled), drawOptions());
253
  }
254
 
255
  function paint() {
@@ -265,7 +297,7 @@ function framed(page) {
265
  if (!page) return;
266
  if (S.visible && S.geo) {
267
  const rest = page.strokes.slice(S.settled);
268
- if (rest.length) drawStrokes(lctx, rest, drawOptions());
269
  }
270
  S.settled = page.strokes.length; S.pos = 0; S.done = S.total;
271
  if (S.visible) paint();
@@ -294,7 +326,7 @@ function framed(page) {
294
  const w = page.strokes[S.settled];
295
  const left = w.length / 3 - S.pos;
296
  if (adv >= left) {
297
- drawStrokes(lctx, [w], drawOptions());
298
  S.settled++; S.pos = 0; S.done += left; adv -= left;
299
  } else { S.pos += adv; S.done += adv; adv = 0; }
300
  }
@@ -316,13 +348,14 @@ function framed(page) {
316
  }
317
 
318
  function redrawAll() {
319
- if (!S.visible || !S.page) return;
320
  fit(); rebuildLayer(); paint();
321
  }
322
 
323
  /** Same pieces, other width / line height: no new writing. */
324
  function relayout() {
325
- if (!S.page || !S.pageWriter || S.phase === 'writing' || !S.visible) return;
 
326
  const page = S.pageWriter.relayout({ width: pageWidth(), lineHeight: S.settings.spacing });
327
  if (!page) return;
328
  S.page = page;
@@ -348,7 +381,7 @@ function framed(page) {
348
  el.size.disabled = writing; el.spacing.disabled = writing;
349
  const canExport = !!S.page && !writing;
350
  el.save.disabled = !canExport;
351
- el.png.disabled = !canExport; el.svg.disabled = !canExport; el.copy.disabled = !canExport;
352
  if (!canExport) closeMenu();
353
  el.empty.hidden = !!S.page || writing || !el.card.hidden;
354
  }
@@ -380,6 +413,12 @@ function framed(page) {
380
  el.styleBtn.setAttribute('aria-expanded', open ? 'true' : 'false');
381
  }
382
 
 
 
 
 
 
 
383
  function badText(n) {
384
  return n === 1 ? 'Eine Stelle ist unsauber geworden. „Nochmal“ schreibt alles neu.'
385
  : `${n} Stellen sind unsauber geworden. „Nochmal“ schreibt alles neu.`;
@@ -459,10 +498,17 @@ function framed(page) {
459
 
460
  // ---------- export ----------
461
 
462
- function pngBlob() {
 
 
 
 
 
 
 
463
  const page = framed(S.page);
464
  const scale = Math.max(12, Math.min(40, 2400 / page.width, 30000 / page.height));
465
- const canvas = toCanvas(page, { scale, color: ink(), lineWidth: LINE_WIDTH, background: '#ffffff' });
466
  return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png'));
467
  }
468
 
@@ -474,15 +520,15 @@ function framed(page) {
474
  setTimeout(() => URL.revokeObjectURL(a.href), 10000);
475
  }
476
 
477
- async function savePng() {
478
  if (!S.page) return;
479
- try { download(await pngBlob(), `handschrift-${stamp()}.png`); }
480
  catch (e) { console.error(e); toast('Das Bild konnte nicht erstellt werden.'); }
481
  }
482
 
483
  function saveSvg() {
484
  if (!S.page) return;
485
- const svg = toSVG(framed(S.page), { scale: 12, color: ink(), lineWidth: LINE_WIDTH });
486
  download(new Blob([svg], { type: 'image/svg+xml' }), `handschrift-${stamp()}.svg`);
487
  }
488
 
@@ -503,8 +549,10 @@ function framed(page) {
503
  function save() {
504
  clearTimeout(saveTimer);
505
  saveTimer = setTimeout(() => {
506
- const { bias, size, spacing, ink: inkName } = S.settings;
507
- store.kvSet('generate', { text: el.text.value, bias, size, spacing, ink: inkName }).catch(() => {});
 
 
508
  }, 300);
509
  }
510
 
@@ -512,7 +560,51 @@ function framed(page) {
512
  el.bias.value = S.settings.bias;
513
  el.size.value = S.settings.size;
514
  el.spacing.value = S.settings.spacing;
515
- for (const b of el.inks.querySelectorAll('[data-ink]')) b.setAttribute('aria-checked', b.dataset.ink === S.settings.ink ? 'true' : 'false');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
516
  }
517
 
518
  let relayoutFrame = 0;
@@ -528,6 +620,12 @@ function framed(page) {
528
  // Lesbarkeit changes how the network writes, so letting go of the slider writes the text again.
529
  el.bias.addEventListener('change', () => { if (S.lastText && S.phase === 'idle') run(S.lastText); });
530
  el.styleBtn.addEventListener('click', toggleStyle);
 
 
 
 
 
 
531
  el.save.addEventListener('click', toggleMenu);
532
  el.saveMenu.addEventListener('click', (e) => { if (e.target.closest('button')) closeMenu(); });
533
  document.addEventListener('pointerdown', (e) => { if (!e.target.closest('.gen-menu-wrap')) closeMenu(); });
@@ -537,10 +635,10 @@ function framed(page) {
537
  el.spacing.addEventListener('input', () => { S.settings.spacing = Number(el.spacing.value); save(); later(); });
538
  el.inks.addEventListener('click', (e) => {
539
  const b = e.target.closest('[data-ink]');
540
- if (!b) return;
541
- S.settings.ink = b.dataset.ink; applySettings(); save(); redrawAll();
542
  });
543
- el.png.addEventListener('click', savePng);
 
544
  el.svg.addEventListener('click', saveSvg);
545
  el.copy.addEventListener('click', copyPng);
546
  el.copy.hidden = !(typeof ClipboardItem !== 'undefined' && navigator.clipboard && navigator.clipboard.write);
@@ -551,7 +649,7 @@ function framed(page) {
551
  let lastW = 0;
552
  new ResizeObserver(() => {
553
  const w = el.paper.clientWidth;
554
- if (w === lastW) return;
555
  lastW = w;
556
  redrawAll();
557
  }).observe(el.paper);
@@ -570,21 +668,23 @@ function framed(page) {
570
  bias: num(saved.bias, 0, 1.2, DEFAULTS.bias),
571
  size: num(saved.size, 6, 30, DEFAULTS.size),
572
  spacing: num(saved.spacing, 5, 9, DEFAULTS.spacing),
573
- ink: INKS[saved.ink] ? saved.ink : DEFAULTS.ink,
574
  };
 
575
  el.text.value = S.settings.text;
576
  } else if (window.innerWidth < 600) S.settings.size = 9;
577
  } catch (_) { /* no stored settings: defaults */ }
578
  applySettings();
579
  wire();
580
  syncUi();
 
581
  }
582
 
583
  function show() {
584
  S.visible = true;
585
  S.follow = true;
586
  autosize();
587
- if (S.page) redrawAll();
 
588
  const stale = S.stale || hf.userName() !== S.authUser || Date.now() - S.lastCheck > RECHECK_MS || el.card.hidden === false;
589
  if (stale && !S.syncing) refresh();
590
  }
@@ -595,6 +695,6 @@ function framed(page) {
595
  init, show, hide, refresh,
596
  info: () => ms.info(),
597
  /** For tests and the diagnostics page. */
598
- debug: () => ({ phase: S.phase, page: S.page, seed: S.seed, sha: S.sha, settings: S.settings, text: S.lastText, bad: S.bad, settled: S.settled, total: S.total, done: S.done }),
599
  };
600
  }
 
7
  // text, "Schreiben", "Nochmal schreiben", Lesbarkeit (bias) -> the network writes again
8
  // Schriftgröße, Zeilenabstand -> the finished pieces are laid out again (page-writer.relayout),
9
  // nothing is generated
10
+ // Stift, Strichstärke, Papier, Farben, Tinte, window size -> redraw only
11
+ //
12
+ // The look starts out as the current writer's capture sheet ("Stift & Papier", kv
13
+ // `displayBy`), so the page looks like what they write on. Once it is changed here,
14
+ // Schreiben keeps its own (kv `generate`.look).
15
  import { createNormalizer } from '../engine/engine.js';
16
  import { createPageWriter } from './page-writer.js';
17
+ import { drawWord, drawWords, drawPartial, drawSheet, toSVG, toCanvas, lookColors, normalizeLook, lookFromCapture, INKS, DEFAULT_LOOK } from './render.js';
18
  import { createEngine } from './engine-client.js';
19
  import { createModelStore } from './model-store.js';
20
+ import { normalize as normalizeDisplay, WIDTHS as CAPTURE_WIDTHS } from '../capture/ink.js';
21
 
22
+ const PAGE_TOP = 5, PAGE_MARGIN = 3; // layout.js: first baseline and side margin, x-heights
 
23
  const MIN_PAGE_WIDTH = 18; // x-heights
24
  const BASE_PPS = 260; // writing animation: points per second when nothing is waiting
25
  const CATCHUP_S = 1.0; // ... and never slower than "everything waiting within this many seconds"
26
  const MAX_PIXELS = 16e6; // canvas budget (per canvas; there are two)
27
  const RECHECK_MS = 5 * 60 * 1000; // look for a newer model at most this often
28
 
29
+ const DEFAULTS = { text: '', bias: 0.4, size: 11, spacing: 6.5 }; // size: CSS px per x-height
30
 
31
  const mb = (bytes) => (bytes / 1e6).toFixed(1).replace('.', ',');
32
 
 
53
  note: $('gen-note'), chars: $('gen-chars'), bad: $('gen-bad'),
54
  bias: $('gen-bias'), size: $('gen-size'), spacing: $('gen-spacing'), inks: $('gen-inks'),
55
  infoText: $('gi-text'), infoBar: $('gi-bar'), infoFill: $('gi-fill'),
56
+ stage: $('gen-stage'), paper: $('gen-paper'), canvas: $('gen-canvas'), lines: $('gen-lines'), empty: $('gen-empty'),
57
  info: $('gen-info'), styleBtn: $('gen-style-btn'), style: $('gen-style'),
58
+ moreBtn: $('gen-more-btn'), more: $('gen-more'), inkRow: $('gen-ink-row'),
59
  save: $('gen-save'), saveMenu: $('gen-save-menu'),
60
+ png: $('gen-png'), inkPng: $('gen-ink-png'), svg: $('gen-svg'), copy: $('gen-copy'),
61
  };
62
  const ctx = el.canvas.getContext('2d');
63
+ const gctx = el.lines.getContext('2d'); // the paper and its lines, under the ink
64
  const layer = document.createElement('canvas'); // everything already written (the animation draws on top of it)
65
  const lctx = layer.getContext('2d');
66
  const motion = matchMedia('(prefers-reduced-motion: reduce)');
67
 
68
  const S = {
69
  settings: Object.assign({}, DEFAULTS),
70
+ look: Object.assign({}, DEFAULT_LOOK),
71
+ ownLook: false, // changed here at least once: no longer follows the capture sheet
72
  visible: false,
73
  // model
74
  engine: null, engineUser: null, sha: null, normalizer: null, writer: null, trainedOn: null,
 
79
  lastText: null, seed: null, pageWriter: null,
80
  page: null, bad: 0,
81
  // drawing
82
+ settled: 0, pos: 0, total: 0, done: 0, geo: null, raf: 0, last: 0, width: 0, sheetKey: '',
83
  };
84
 
85
  // ---------- model card / info line ----------
 
223
 
224
  // ---------- drawing ----------
225
 
226
+ /** What every drawing call needs: the look, its colours and the current scale. */
227
+ const drawOptions = () => ({ scale: S.geo.scale, look: S.look, colors: lookColors(S.look) });
228
 
229
  /** The page as shown and exported: widened when an unsplit piece sticks out past the right edge. */
230
+ function framed(page) {
231
+ let right = page.width;
232
+ for (const w of page.words) right = Math.max(right, w.x + w.width + 3);
233
+ return right > page.width ? Object.assign({}, page, { width: right }) : page;
234
+ }
235
 
236
+ /** Device px per CSS px for a canvas of cssW x cssH, within the pixel budget. */
237
+ function ratioFor(cssW, cssH) {
238
+ const ratio = window.devicePixelRatio || 1;
239
+ const px = cssW * ratio * cssH * ratio;
240
+ return px > MAX_PIXELS ? ratio * Math.sqrt(MAX_PIXELS / px) : ratio;
241
+ }
242
+
243
+ /** Size the canvases to the page and the sheet; true when the ink bitmap size changed (= it is blank now).
244
+ * Without a page the paper is still drawn, at the scale the next page will have. */
245
  function fit() {
246
  const page = S.page;
247
  const cssW = el.paper.clientWidth;
248
+ if (!cssW) return false;
249
+ const cssScale = cssW / (page ? framed(page).width : pageWidth());
250
+ const cssH = page ? Math.max(1, Math.ceil(page.height * cssScale)) : 0;
251
+ const ratio = ratioFor(cssW, Math.max(cssH, 1));
252
+ const pw = Math.round(cssW * ratio), ph = Math.max(1, Math.round(cssH * ratio)); // never 0: getImageData must work
 
 
 
 
253
  const changed = el.canvas.width !== pw || el.canvas.height !== ph;
254
  if (changed) { el.canvas.width = pw; el.canvas.height = ph; layer.width = pw; layer.height = ph; }
255
  el.canvas.style.height = `${cssH}px`;
256
+ S.geo = { scale: cssScale * ratio, cssScale, ratio };
257
  S.width = cssW;
258
+ paintSheet();
259
  return changed;
260
  }
261
 
262
+ const sheetGeometry = (scale, lineWidth) => ({ scale, spacing: S.settings.spacing, top: PAGE_TOP, margin: PAGE_MARGIN, lineWidth });
263
+
264
+ /** The paper canvas covers the whole sheet (also below the last line); repainted only when something it shows changed. */
265
+ function paintSheet() {
266
+ if (!S.geo) return;
267
+ const cssW = el.paper.clientWidth, cssH = el.paper.clientHeight;
268
+ if (!cssW || !cssH) return;
269
+ const ratio = ratioFor(cssW, cssH);
270
+ const pw = Math.round(cssW * ratio), ph = Math.round(cssH * ratio);
271
+ const scale = S.geo.cssScale * ratio;
272
+ const key = [pw, ph, scale, S.look.paper, S.look.scheme, S.settings.spacing].join('|');
273
+ if (key === S.sheetKey) return;
274
+ S.sheetKey = key;
275
+ if (el.lines.width !== pw || el.lines.height !== ph) { el.lines.width = pw; el.lines.height = ph; }
276
+ el.lines.style.height = `${cssH}px`;
277
+ drawSheet(gctx, pw, ph, S.look, lookColors(S.look), sheetGeometry(scale, Math.max(1, Math.round(ratio))));
278
+ }
279
+
280
+ /** The settled words, drawn one by one exactly as the animation draws them. */
281
  function rebuildLayer() {
282
  if (!S.page || !S.geo) return;
283
  lctx.clearRect(0, 0, layer.width, layer.height);
284
+ drawWords(lctx, S.page.strokes.slice(0, S.settled), drawOptions());
285
  }
286
 
287
  function paint() {
 
297
  if (!page) return;
298
  if (S.visible && S.geo) {
299
  const rest = page.strokes.slice(S.settled);
300
+ if (rest.length) drawWords(lctx, rest, drawOptions());
301
  }
302
  S.settled = page.strokes.length; S.pos = 0; S.done = S.total;
303
  if (S.visible) paint();
 
326
  const w = page.strokes[S.settled];
327
  const left = w.length / 3 - S.pos;
328
  if (adv >= left) {
329
+ drawWord(lctx, w, drawOptions());
330
  S.settled++; S.pos = 0; S.done += left; adv -= left;
331
  } else { S.pos += adv; S.done += adv; adv = 0; }
332
  }
 
348
  }
349
 
350
  function redrawAll() {
351
+ if (!S.visible) return;
352
  fit(); rebuildLayer(); paint();
353
  }
354
 
355
  /** Same pieces, other width / line height: no new writing. */
356
  function relayout() {
357
+ if (!S.visible) return;
358
+ if (!S.page || !S.pageWriter || S.phase === 'writing') { fit(); return; }
359
  const page = S.pageWriter.relayout({ width: pageWidth(), lineHeight: S.settings.spacing });
360
  if (!page) return;
361
  S.page = page;
 
381
  el.size.disabled = writing; el.spacing.disabled = writing;
382
  const canExport = !!S.page && !writing;
383
  el.save.disabled = !canExport;
384
+ el.png.disabled = !canExport; el.inkPng.disabled = !canExport; el.svg.disabled = !canExport; el.copy.disabled = !canExport;
385
  if (!canExport) closeMenu();
386
  el.empty.hidden = !!S.page || writing || !el.card.hidden;
387
  }
 
413
  el.styleBtn.setAttribute('aria-expanded', open ? 'true' : 'false');
414
  }
415
 
416
+ function toggleMore() {
417
+ const open = el.more.hidden;
418
+ el.more.hidden = !open;
419
+ el.moreBtn.setAttribute('aria-expanded', open ? 'true' : 'false');
420
+ }
421
+
422
  function badText(n) {
423
  return n === 1 ? 'Eine Stelle ist unsauber geworden. „Nochmal“ schreibt alles neu.'
424
  : `${n} Stellen sind unsauber geworden. „Nochmal“ schreibt alles neu.`;
 
498
 
499
  // ---------- export ----------
500
 
501
+ /** Export geometry: the lines as wide, relative to the page, as on screen. */
502
+ function exportOptions(scale, paper) {
503
+ const cssScale = (S.geo && S.geo.cssScale) || S.settings.size;
504
+ return { scale, look: S.look, paper, guideWidth: scale / cssScale, spacing: S.settings.spacing, top: PAGE_TOP, margin: PAGE_MARGIN };
505
+ }
506
+
507
+ /** paper: true = the sheet as shown (paper, lines, pen); false = transparent, ink only. */
508
+ function pngBlob(paper = true) {
509
  const page = framed(S.page);
510
  const scale = Math.max(12, Math.min(40, 2400 / page.width, 30000 / page.height));
511
+ const canvas = toCanvas(page, exportOptions(scale, paper));
512
  return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png'));
513
  }
514
 
 
520
  setTimeout(() => URL.revokeObjectURL(a.href), 10000);
521
  }
522
 
523
+ async function savePng(paper = true) {
524
  if (!S.page) return;
525
+ try { download(await pngBlob(paper), `handschrift-${stamp()}${paper ? '' : '-ohne-papier'}.png`); }
526
  catch (e) { console.error(e); toast('Das Bild konnte nicht erstellt werden.'); }
527
  }
528
 
529
  function saveSvg() {
530
  if (!S.page) return;
531
+ const svg = toSVG(framed(S.page), exportOptions(12, true));
532
  download(new Blob([svg], { type: 'image/svg+xml' }), `handschrift-${stamp()}.svg`);
533
  }
534
 
 
549
  function save() {
550
  clearTimeout(saveTimer);
551
  saveTimer = setTimeout(() => {
552
+ const { bias, size, spacing } = S.settings;
553
+ const v = { text: el.text.value, bias, size, spacing };
554
+ if (S.ownLook) v.look = Object.assign({}, S.look);
555
+ store.kvSet('generate', v).catch(() => {});
556
  }, 300);
557
  }
558
 
 
560
  el.bias.value = S.settings.bias;
561
  el.size.value = S.settings.size;
562
  el.spacing.value = S.settings.spacing;
563
+ applyLook();
564
+ }
565
+
566
+ /** Buttons, swatches and the sheet's own colours follow the look. */
567
+ function applyLook() {
568
+ const l = S.look;
569
+ for (const b of el.style.querySelectorAll('.gen-choice')) {
570
+ const v = b.dataset.k === 'width' ? Number(b.dataset.v) : b.dataset.v;
571
+ b.setAttribute('aria-checked', l[b.dataset.k] === v ? 'true' : 'false');
572
+ }
573
+ for (const b of el.inks.querySelectorAll('[data-ink]')) {
574
+ const [color, name] = INKS[l.scheme][b.dataset.ink];
575
+ b.setAttribute('aria-checked', b.dataset.ink === l.ink ? 'true' : 'false');
576
+ b.setAttribute('aria-label', name); b.title = name;
577
+ b.firstElementChild.style.background = color;
578
+ }
579
+ el.inkRow.hidden = l.pen === 'bleistift'; // graphite has no ink to choose
580
+ el.paper.dataset.scheme = l.scheme;
581
+ }
582
+
583
+ /** Change one part of the look here: from now on Schreiben keeps its own. */
584
+ function setLook(key, value) {
585
+ const next = normalizeLook(Object.assign({}, S.look, { [key]: value }));
586
+ if (next[key] === S.look[key] && S.ownLook) return;
587
+ S.look = next; S.ownLook = true;
588
+ applyLook(); save();
589
+ S.sheetKey = '';
590
+ if (key === 'paper') paintSheet(); else redrawAll();
591
+ }
592
+
593
+ /** Until the look is changed here, it is the current writer's capture sheet (when they set one up). */
594
+ async function followCapture() {
595
+ if (S.ownLook) return;
596
+ let look = DEFAULT_LOOK;
597
+ try {
598
+ const wid = await store.kvGet('writer', null);
599
+ const by = wid ? await store.kvGet('displayBy', null) : null;
600
+ if (by && by[wid] && typeof by[wid] === 'object') look = lookFromCapture(normalizeDisplay(by[wid]), CAPTURE_WIDTHS);
601
+ } catch (_) { /* no capture look: Schreiben's own defaults */ }
602
+ if (S.ownLook) return;
603
+ const next = normalizeLook(look);
604
+ if (JSON.stringify(next) === JSON.stringify(S.look)) return;
605
+ S.look = next;
606
+ applyLook();
607
+ S.sheetKey = ''; redrawAll();
608
  }
609
 
610
  let relayoutFrame = 0;
 
620
  // Lesbarkeit changes how the network writes, so letting go of the slider writes the text again.
621
  el.bias.addEventListener('change', () => { if (S.lastText && S.phase === 'idle') run(S.lastText); });
622
  el.styleBtn.addEventListener('click', toggleStyle);
623
+ el.moreBtn.addEventListener('click', toggleMore);
624
+ el.style.addEventListener('click', (e) => {
625
+ const b = e.target.closest('.gen-choice');
626
+ if (!b) return;
627
+ setLook(b.dataset.k, b.dataset.k === 'width' ? Number(b.dataset.v) : b.dataset.v);
628
+ });
629
  el.save.addEventListener('click', toggleMenu);
630
  el.saveMenu.addEventListener('click', (e) => { if (e.target.closest('button')) closeMenu(); });
631
  document.addEventListener('pointerdown', (e) => { if (!e.target.closest('.gen-menu-wrap')) closeMenu(); });
 
635
  el.spacing.addEventListener('input', () => { S.settings.spacing = Number(el.spacing.value); save(); later(); });
636
  el.inks.addEventListener('click', (e) => {
637
  const b = e.target.closest('[data-ink]');
638
+ if (b) setLook('ink', b.dataset.ink);
 
639
  });
640
+ el.png.addEventListener('click', () => savePng(true));
641
+ el.inkPng.addEventListener('click', () => savePng(false));
642
  el.svg.addEventListener('click', saveSvg);
643
  el.copy.addEventListener('click', copyPng);
644
  el.copy.hidden = !(typeof ClipboardItem !== 'undefined' && navigator.clipboard && navigator.clipboard.write);
 
649
  let lastW = 0;
650
  new ResizeObserver(() => {
651
  const w = el.paper.clientWidth;
652
+ if (w === lastW) { if (S.visible) paintSheet(); return; } // only taller or shorter: the paper, not the ink
653
  lastW = w;
654
  redrawAll();
655
  }).observe(el.paper);
 
668
  bias: num(saved.bias, 0, 1.2, DEFAULTS.bias),
669
  size: num(saved.size, 6, 30, DEFAULTS.size),
670
  spacing: num(saved.spacing, 5, 9, DEFAULTS.spacing),
 
671
  };
672
+ if (saved.look && typeof saved.look === 'object') { S.look = normalizeLook(saved.look); S.ownLook = true; }
673
  el.text.value = S.settings.text;
674
  } else if (window.innerWidth < 600) S.settings.size = 9;
675
  } catch (_) { /* no stored settings: defaults */ }
676
  applySettings();
677
  wire();
678
  syncUi();
679
+ await followCapture();
680
  }
681
 
682
  function show() {
683
  S.visible = true;
684
  S.follow = true;
685
  autosize();
686
+ redrawAll();
687
+ followCapture();
688
  const stale = S.stale || hf.userName() !== S.authUser || Date.now() - S.lastCheck > RECHECK_MS || el.card.hidden === false;
689
  if (stale && !S.syncing) refresh();
690
  }
 
695
  init, show, hide, refresh,
696
  info: () => ms.info(),
697
  /** For tests and the diagnostics page. */
698
+ debug: () => ({ 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 }),
699
  };
700
  }
styles.css CHANGED
@@ -360,10 +360,10 @@ input[role="switch"]:checked::after { transform: translateX(24px); }
360
 
361
  /* ---------- Schreiben ----------
362
  Two things on the screen: the sheet, and below it the line where the text is
363
- typed. The sheet is paper (sharp corners, light in both themes); everything
364
- that is a tool is rounded and stays quiet. */
365
- :root { --gen-paper: #FFFFFF; --gen-paper-edge: rgba(28, 35, 48, .09); --gen-column: 880px; }
366
- @media (prefers-color-scheme: dark) { :root { --gen-paper: #EFEDE7; --gen-paper-edge: transparent; } }
367
  .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
368
 
369
  body[data-route="schreiben"] { height: 100dvh; overflow: hidden; }
@@ -376,7 +376,8 @@ body[data-route="schreiben"] { height: 100dvh; overflow: hidden; }
376
  margin: 0 -12px; padding: 4px 12px 18px; /* room for the sheet's shadow */
377
  }
378
  .gen-paper {
379
- /* whatever sits on the sheet is dark on light, in both themes */
 
380
  --ink: #1C2330; --muted: #5E6775; --line: #DDE2E8; --sheet: #FFFFFF;
381
  --accent: #2847C4; --accent-ink: #FFFFFF; --accent-soft: #E7ECFA;
382
  color-scheme: light; color: var(--ink);
@@ -384,10 +385,19 @@ body[data-route="schreiben"] { height: 100dvh; overflow: hidden; }
384
  background: var(--gen-paper); border-radius: 3px;
385
  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);
386
  }
 
 
 
 
 
 
 
387
  .gen-paper canvas { display: block; width: 100%; }
 
 
388
  .gen-empty {
389
  position: absolute; inset: 0; display: grid; place-items: center; text-align: center; padding: 24px;
390
- color: #8B93A0; pointer-events: none;
391
  }
392
  .gen-state { position: absolute; inset: 0; display: grid; place-items: center; padding: 28px; background: var(--gen-paper); border-radius: inherit; }
393
  .gen-state-in { display: grid; justify-items: center; gap: 16px; max-width: 420px; text-align: center; }
@@ -433,23 +443,60 @@ body[data-route="schreiben"] { height: 100dvh; overflow: hidden; }
433
  .gen-menu button:not(:disabled):hover, .gen-menu button:focus-visible { background: var(--accent-soft); outline: 0; }
434
  .gen-menu button:disabled { opacity: .4; cursor: default; }
435
 
436
- /* Stil: opens in place, above the text line, so the sheet stays in view while it changes */
437
- .gen-style { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)) auto; column-gap: 28px; padding: 0 4px 4px; }
438
- .gen-ctl { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; column-gap: 12px; font-size: 14px; color: var(--muted); }
439
- .gen-ctl input[type="range"] { appearance: none; width: 100%; min-width: 48px; height: 48px; margin: 0; background: transparent; cursor: pointer; }
440
- .gen-ctl input[type="range"]::-webkit-slider-runnable-track { height: 3px; border-radius: 2px; background: var(--line); }
441
- .gen-ctl input[type="range"]::-moz-range-track { height: 3px; border-radius: 2px; background: var(--line); }
442
- .gen-ctl input[type="range"]::-webkit-slider-thumb { appearance: none; width: 18px; height: 18px; margin-top: -7.5px; border-radius: 50%; background: var(--ink); border: 0; }
443
- .gen-ctl input[type="range"]::-moz-range-thumb { width: 18px; height: 18px; border-radius: 50%; background: var(--ink); border: 0; }
444
- .gen-ctl input[type="range"]:disabled { opacity: .4; cursor: default; }
445
- .gen-ctl input[type="range"]:focus-visible { outline: 0; }
446
- .gen-ctl input[type="range"]:focus-visible::-webkit-slider-thumb { box-shadow: 0 0 0 4px color-mix(in srgb, var(--accent) 45%, transparent); }
447
- .gen-inks { display: flex; margin-right: -12px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
448
  .gen-ink { appearance: none; border: 0; background: none; padding: 0; width: 48px; height: 48px; display: grid; place-items: center; cursor: pointer; touch-action: manipulation; border-radius: 12px; }
449
- .gen-ink i { width: 20px; height: 20px; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .22); }
450
  .gen-ink[aria-checked="true"] i { box-shadow: 0 0 0 2.5px var(--desk), 0 0 0 4.5px var(--ink); }
451
- @media (max-width: 860px) { .gen-style { grid-template-columns: repeat(2, minmax(0, 1fr)); } .gen-ctl-ink { grid-template-columns: auto auto; justify-content: start; } }
452
- @media (max-width: 520px) { .gen-style { grid-template-columns: minmax(0, 1fr); } .gen-ctl { grid-template-columns: 112px minmax(0, 1fr); } .gen-ctl-ink { grid-template-columns: 112px auto; } }
 
 
 
453
 
454
  /* the text line */
455
  .gen-composer {
 
360
 
361
  /* ---------- Schreiben ----------
362
  Two things on the screen: the sheet, and below it the line where the text is
363
+ typed. The sheet is paper (sharp corners, the colours of the capture sheet,
364
+ whatever the app theme); everything that is a tool is rounded and stays quiet. */
365
+ :root { --gen-paper-edge: rgba(28, 35, 48, .09); --gen-column: 880px; }
366
+ @media (prefers-color-scheme: dark) { :root { --gen-paper-edge: transparent; } }
367
  .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
368
 
369
  body[data-route="schreiben"] { height: 100dvh; overflow: hidden; }
 
376
  margin: 0 -12px; padding: 4px 12px 18px; /* room for the sheet's shadow */
377
  }
378
  .gen-paper {
379
+ /* what sits on the sheet follows the sheet's scheme ("Farben"), not the app theme */
380
+ --gen-paper: var(--paper-light-bg); --gen-hint: #8B93A0;
381
  --ink: #1C2330; --muted: #5E6775; --line: #DDE2E8; --sheet: #FFFFFF;
382
  --accent: #2847C4; --accent-ink: #FFFFFF; --accent-soft: #E7ECFA;
383
  color-scheme: light; color: var(--ink);
 
385
  background: var(--gen-paper); border-radius: 3px;
386
  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);
387
  }
388
+ .gen-paper[data-scheme="light_on_dark"] {
389
+ --gen-paper: var(--paper-dark-bg); --gen-hint: var(--paper-dark-muted);
390
+ --ink: #E6E9EE; --muted: var(--paper-dark-muted); --line: #343B47; --sheet: #232832;
391
+ --accent: #8EA4FF; --accent-ink: #0F1424; --accent-soft: #2A3352;
392
+ color-scheme: dark;
393
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, .06), 0 1px 2px rgba(20, 26, 38, .08), 0 14px 30px -14px rgba(20, 26, 38, .3);
394
+ }
395
  .gen-paper canvas { display: block; width: 100%; }
396
+ .gen-paper #gen-canvas { position: relative; } /* the ink, over the paper's lines */
397
+ .gen-paper .gen-lines { position: absolute; left: 0; top: 0; border-radius: inherit; }
398
  .gen-empty {
399
  position: absolute; inset: 0; display: grid; place-items: center; text-align: center; padding: 24px;
400
+ color: var(--gen-hint); pointer-events: none;
401
  }
402
  .gen-state { position: absolute; inset: 0; display: grid; place-items: center; padding: 28px; background: var(--gen-paper); border-radius: inherit; }
403
  .gen-state-in { display: grid; justify-items: center; gap: 16px; max-width: 420px; text-align: center; }
 
443
  .gen-menu button:not(:disabled):hover, .gen-menu button:focus-visible { background: var(--accent-soft); outline: 0; }
444
  .gen-menu button:disabled { opacity: .4; cursor: default; }
445
 
446
+ /* Stil: opens in place, above the text line, so the sheet stays in view while it changes.
447
+ Labels on the left, plain words to choose from; the choice in use is marked as quietly
448
+ as an open tool. Two columns where there is room: the pen on the left, the sheet on the right. */
449
+ .gen-style {
450
+ --gen-label: 104px;
451
+ max-height: min(46dvh, 420px); overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin;
452
+ padding: 2px 4px 6px;
453
+ }
454
+ .gen-style-main, .gen-style-more { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); column-gap: 32px; }
455
+ .gen-style-main { grid-template-rows: repeat(3, auto); grid-auto-flow: column; }
456
+ .gen-style-more { margin-top: 6px; }
457
+ .gen-opt { display: grid; grid-template-columns: var(--gen-label) minmax(0, 1fr); align-items: center; min-height: 48px; min-width: 0; }
458
+ .gen-opt[hidden] { display: none; }
459
+ .gen-opt-l { font-size: 14px; color: var(--muted); }
460
+ .gen-choices { display: flex; flex-wrap: wrap; margin-left: -10px; }
461
+ .gen-choice {
462
+ appearance: none; border: 0; background: none; font: inherit; font-size: 15px; color: var(--muted);
463
+ position: relative; isolation: isolate; display: inline-grid; place-items: center;
464
+ min-width: 48px; height: 48px; padding: 0 10px; cursor: pointer; touch-action: manipulation; white-space: nowrap;
465
+ }
466
+ .gen-choice::before { content: ""; position: absolute; inset: 8px 0; border-radius: 9px; z-index: -1; }
467
+ .gen-choice[aria-checked="true"] { color: var(--ink); }
468
+ @media (hover: hover) { .gen-choice:hover { color: var(--ink); } .gen-choice:hover:not([aria-checked="true"])::before { background: color-mix(in srgb, var(--ink) 5%, transparent); } }
469
+ .gen-choice[aria-checked="true"]::before { background: color-mix(in srgb, var(--ink) 9%, transparent); }
470
+ .gen-choice:focus-visible { outline: 0; }
471
+ .gen-choice:focus-visible::before { outline: 3px solid color-mix(in srgb, var(--accent) 55%, transparent); }
472
+ .gen-w { padding: 0; }
473
+ .gen-w i { display: block; width: 22px; border-radius: 2px; background: currentColor; }
474
+ .gen-more-btn {
475
+ appearance: none; border: 0; background: none; font: inherit; font-size: 14px; color: var(--muted);
476
+ grid-column: 1 / -1; justify-self: start; display: inline-flex; align-items: center; gap: 8px;
477
+ height: 48px; padding: 0 10px; margin-left: -10px; cursor: pointer; touch-action: manipulation; border-radius: 9px;
478
+ }
479
+ .gen-more-btn i { width: 7px; height: 7px; border: solid currentColor; border-width: 0 1.5px 1.5px 0; transform: translateY(-2px) rotate(45deg); transition: transform .15s; }
480
+ .gen-more-btn[aria-expanded="true"] i { transform: translateY(1px) rotate(-135deg); }
481
+ .gen-more-btn:hover, .gen-more-btn[aria-expanded="true"] { color: var(--ink); }
482
+ .gen-more-btn:focus-visible { outline: 3px solid color-mix(in srgb, var(--accent) 55%, transparent); outline-offset: -6px; }
483
+ .gen-opt input[type="range"] { appearance: none; width: 100%; min-width: 48px; height: 48px; margin: 0; background: transparent; cursor: pointer; }
484
+ .gen-opt input[type="range"]::-webkit-slider-runnable-track { height: 3px; border-radius: 2px; background: var(--line); }
485
+ .gen-opt input[type="range"]::-moz-range-track { height: 3px; border-radius: 2px; background: var(--line); }
486
+ .gen-opt input[type="range"]::-webkit-slider-thumb { appearance: none; width: 18px; height: 18px; margin-top: -7.5px; border-radius: 50%; background: var(--ink); border: 0; }
487
+ .gen-opt input[type="range"]::-moz-range-thumb { width: 18px; height: 18px; border-radius: 50%; background: var(--ink); border: 0; }
488
+ .gen-opt input[type="range"]:disabled { opacity: .4; cursor: default; }
489
+ .gen-opt input[type="range"]:focus-visible { outline: 0; }
490
+ .gen-opt input[type="range"]:focus-visible::-webkit-slider-thumb { box-shadow: 0 0 0 4px color-mix(in srgb, var(--accent) 45%, transparent); }
491
+ .gen-inks { display: flex; margin-left: -14px; }
492
  .gen-ink { appearance: none; border: 0; background: none; padding: 0; width: 48px; height: 48px; display: grid; place-items: center; cursor: pointer; touch-action: manipulation; border-radius: 12px; }
493
+ .gen-ink i { width: 20px; height: 20px; border-radius: 50%; box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--ink) 18%, transparent); }
494
  .gen-ink[aria-checked="true"] i { box-shadow: 0 0 0 2.5px var(--desk), 0 0 0 4.5px var(--ink); }
495
+ .gen-ink:focus-visible { outline: 3px solid color-mix(in srgb, var(--accent) 55%, transparent); outline-offset: -4px; }
496
+ @media (max-width: 760px) {
497
+ .gen-style { --gen-label: 100px; max-height: min(38dvh, 340px); }
498
+ .gen-style-main, .gen-style-more { grid-template-columns: minmax(0, 1fr); grid-template-rows: none; grid-auto-flow: row; }
499
+ }
500
 
501
  /* the text line */
502
  .gen-composer {