@open-document/core 0.16.0 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/{build-BS_CoazO.js → build-C7nHUUXO.js} +1 -1
  2. package/dist/{check-tTjyMCrU.js → check--Cbkdqw3.js} +11 -4
  3. package/dist/cli/bin.js +25 -12
  4. package/dist/{context-Cli81dhF.js → context-DRXgt6Je.js} +2 -2
  5. package/dist/{deploy-gcp-BUiSuqz7.js → deploy-gcp-bbxQT0gf.js} +1 -1
  6. package/dist/{dev-n222xdoE.js → dev-D_j2ykSa.js} +1 -1
  7. package/dist/{diff-DB_qruzT.js → diff-C1RDK_I5.js} +2 -2
  8. package/dist/{export-CCFtdscQ.js → export-BFxKPa0W.js} +3 -3
  9. package/dist/{flow-CS5apebG.d.ts → flow-DlV3t5ML.d.ts} +24 -4
  10. package/dist/{import-D7k0yYZh.js → import-TLuMXkou.js} +11 -7
  11. package/dist/index.d.ts +26 -2
  12. package/dist/index.js +55 -1
  13. package/dist/{open-doc-plugin-DnX5usgI.js → open-doc-plugin-DE1sJXK_.js} +3 -2
  14. package/dist/ops/index.d.ts +138 -4
  15. package/dist/ops/index.js +3 -3
  16. package/dist/{ops-CouYBa1O.js → ops-BG9hfBwQ.js} +197 -9
  17. package/dist/{preview-DV0GDIsj.js → preview-rlMPuRZV.js} +1 -1
  18. package/dist/proofread-Dtj9OlWX.js +35 -0
  19. package/dist/{session-Cx7Msl_F.js → session-CPFLe6BT.js} +5148 -69
  20. package/dist/{templates-C-7VcMMV.js → templates-BmSuBmj3.js} +3 -3
  21. package/dist/translations-BmTXOhx9.js +42 -0
  22. package/dist/vite/index.d.ts +2 -0
  23. package/dist/vite/index.js +2 -2
  24. package/package.json +1 -1
  25. package/skills/doc-authoring/references/pagination.md +1 -1
  26. package/skills/fill-form/SKILL.md +42 -0
  27. package/skills/fit-pages/SKILL.md +48 -0
  28. package/skills/import-document/SKILL.md +58 -0
  29. package/skills/proofread/SKILL.md +44 -0
  30. package/skills/refresh-report/SKILL.md +48 -0
  31. package/skills/sync-translation/SKILL.md +55 -0
  32. package/src/agent/prompt.ts +1 -1
  33. package/src/app/components/agent/agent-dock.tsx +1 -1
  34. package/src/app/components/browser/browser-ui.tsx +8 -2
  35. package/src/app/components/checkbox.tsx +68 -0
  36. package/src/app/components/doc-sidebar.tsx +5 -3
  37. package/src/app/components/flow-page.tsx +7 -2
  38. package/src/app/components/panel/edit-save-card.tsx +3 -0
  39. package/src/app/components/panel/panel-shell.tsx +3 -1
  40. package/src/app/components/sidebar/sidebar.tsx +2 -1
  41. package/src/app/lib/agent-bridge.ts +37 -4
  42. package/src/app/lib/diagnostics.ts +46 -5
  43. package/src/app/lib/export-docx.ts +5 -2
  44. package/src/app/lib/export-dom.ts +13 -0
  45. package/src/app/lib/export-html.ts +6 -1
  46. package/src/app/lib/export-image.ts +9 -4
  47. package/src/app/lib/export-pdf.ts +17 -4
  48. package/src/app/lib/flow-measure.ts +9 -5
  49. package/src/app/lib/flow.ts +3 -2
  50. package/src/app/lib/i18n-ja/browser.ts +1 -0
  51. package/src/app/lib/i18n-ja/doc.ts +1 -0
  52. package/src/app/lib/i18n-ko/browser.ts +1 -0
  53. package/src/app/lib/i18n-ko/doc.ts +1 -0
  54. package/src/app/lib/i18n-zh-cn/browser.ts +1 -0
  55. package/src/app/lib/i18n-zh-cn/doc.ts +1 -0
  56. package/src/app/lib/i18n-zh-tw/browser.ts +1 -0
  57. package/src/app/lib/i18n-zh-tw/doc.ts +1 -0
  58. package/src/app/lib/page-budget.ts +81 -0
  59. package/src/app/lib/proofread-script.ts +61 -0
  60. package/src/app/lib/proofread.ts +399 -0
  61. package/src/app/lib/recent-docs.ts +27 -0
  62. package/src/app/lib/sdk.ts +44 -2
  63. package/src/app/lib/text-runs.ts +83 -0
  64. package/src/app/lib/use-doc-pages.ts +10 -3
  65. package/src/app/routes/doc-preview.tsx +1 -1
  66. package/src/app/routes/doc.tsx +190 -54
  67. package/src/app/routes/home.tsx +50 -12
  68. package/src/app/virtual.d.ts +1 -1
@@ -0,0 +1,399 @@
1
+ import { SIMPLIFIED_ONLY, TRADITIONAL_ONLY } from './proofread-script';
2
+
3
+ export type ProofreadRule =
4
+ | 'fullwidth-alnum'
5
+ | 'punctuation-width'
6
+ | 'script-mix'
7
+ | 'repeated-word'
8
+ | 'term-casing';
9
+
10
+ export type ProofreadFinding = {
11
+ /** 1-based sheet the text is on. */
12
+ page: number;
13
+ rule: ProofreadRule;
14
+ severity: 'warn';
15
+ message: string;
16
+ /** The words around the problem, as printed. */
17
+ snippet: string;
18
+ /** `line:column` in the document source, from the inspector's `data-od-loc`. */
19
+ loc?: string;
20
+ };
21
+
22
+ /**
23
+ * One stretch of printed text inside a single block, in reading order. Code
24
+ * and block boundaries end a run, so two runs never read as adjacent text.
25
+ */
26
+ export type TextRun = {
27
+ text: string;
28
+ page: number;
29
+ loc?: string;
30
+ /** A `lang` set inside the sheet; the document's language otherwise. */
31
+ lang?: string;
32
+ };
33
+
34
+ export type ProofreadOptions = {
35
+ /** Findings kept per rule per page, so one bad page can't drown the report. */
36
+ perPageLimit?: number;
37
+ /** Findings kept per rule across the document. */
38
+ perRuleLimit?: number;
39
+ };
40
+
41
+ export type ProofreadResult = { findings: ProofreadFinding[]; omitted: number };
42
+
43
+ const DEFAULTS = { perPageLimit: 3, perRuleLimit: 20 } as const;
44
+ const CONTEXT = 16;
45
+ const MASK = '';
46
+
47
+ const CJK_RE =
48
+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}々〆〇ー -〿＀-/:-@[-`{-・]/u;
49
+ const LATIN_RE = /[\p{Script=Latin}0-9]/u;
50
+ const DIGIT_RE = /[0-9]/;
51
+
52
+ const isCjk = (ch: string | undefined) => ch !== undefined && CJK_RE.test(ch);
53
+ const isLatin = (ch: string | undefined) => ch !== undefined && LATIN_RE.test(ch);
54
+ const isDigit = (ch: string | undefined) => ch !== undefined && DIGIT_RE.test(ch);
55
+
56
+ function isCjkLang(lang: string): boolean {
57
+ return /^(zh|ja)(-|$)/i.test(lang);
58
+ }
59
+
60
+ function chineseScript(lang: string): 'hant' | 'hans' | null {
61
+ if (/^zh-(hant|tw|hk|mo)(-|$)/i.test(lang)) return 'hant';
62
+ if (/^zh-(hans|cn|sg|my)(-|$)/i.test(lang)) return 'hans';
63
+ return null;
64
+ }
65
+
66
+ const MASKS = [
67
+ /(?:[a-z][a-z\d+.-]*:\/\/|www\.)[^\s\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana} -〿＀-￯"'<>]+/giu,
68
+ /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,
69
+ /(?<![\p{Script=Latin}\p{N}])[:;=][-^']?[()DPpO3|\\/\][*]+(?![\p{Script=Latin}\p{N}])/gu,
70
+ // Kaomoji: a bracketed face is drawn with these, never written as prose.
71
+ /[((][^()()\s\p{Script=Han}\p{Script=Latin}]{0,10}[´`^∀ω・_;*°゚▽◕‿≧≦⊙•ー^﹏∇ε><Д][^()()\s\p{Script=Han}\p{Script=Latin}]{0,10}[))]/gu,
72
+ ];
73
+
74
+ /** Same length as the text, with URLs, addresses and emoticons blanked out. */
75
+ function masked(text: string): string {
76
+ let out = text;
77
+ for (const re of MASKS) {
78
+ out = out.replace(re, (m) => MASK.repeat(m.length));
79
+ }
80
+ return out;
81
+ }
82
+
83
+ function snippetAt(text: string, start: number, end: number): string {
84
+ const from = Math.max(0, start - CONTEXT);
85
+ const to = Math.min(text.length, end + CONTEXT);
86
+ const body = text.slice(from, to).replace(/\s+/g, ' ').trim();
87
+ return `${from > 0 ? '…' : ''}${body}${to < text.length ? '…' : ''}`;
88
+ }
89
+
90
+ function times(n: number): string {
91
+ return n > 1 ? ` (${n} in this block)` : '';
92
+ }
93
+
94
+ type Hit = { start: number; end: number };
95
+
96
+ function finding(run: TextRun, rule: ProofreadRule, message: string, hit: Hit): ProofreadFinding {
97
+ return {
98
+ page: run.page,
99
+ rule,
100
+ severity: 'warn',
101
+ message,
102
+ snippet: snippetAt(run.text, hit.start, hit.end),
103
+ ...(run.loc ? { loc: run.loc } : {}),
104
+ };
105
+ }
106
+
107
+ const FULLWIDTH_ALNUM_RE = /[A-Za-z0-9]+/g;
108
+
109
+ function toHalfWidth(s: string): string {
110
+ return s.replace(/[A-Za-z0-9]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0xfee0));
111
+ }
112
+
113
+ function fullwidthAlnum(run: TextRun, text: string): ProofreadFinding[] {
114
+ const hits = Array.from(text.matchAll(FULLWIDTH_ALNUM_RE));
115
+ const first = hits[0];
116
+ if (!first) return [];
117
+ const word = first[0];
118
+ return [
119
+ finding(
120
+ run,
121
+ 'fullwidth-alnum',
122
+ `Full-width "${word}" — write "${toHalfWidth(word)}"${times(hits.length)}.`,
123
+ { start: first.index, end: first.index + word.length },
124
+ ),
125
+ ];
126
+ }
127
+
128
+ const TO_FULL: Record<string, string> = {
129
+ ',': ',',
130
+ ';': ';',
131
+ ':': ':',
132
+ '?': '?',
133
+ '!': '!',
134
+ '(': '(',
135
+ ')': ')',
136
+ };
137
+ const TO_HALF: Record<string, string> = Object.fromEntries(
138
+ Object.entries(TO_FULL).map(([half, full]) => [full, half]),
139
+ );
140
+ TO_HALF['。'] = '.';
141
+
142
+ function halfWidthInCjk(text: string): Hit[] {
143
+ const hits: Hit[] = [];
144
+ for (let i = 0; i < text.length; i++) {
145
+ const ch = text[i] as string;
146
+ if (!(ch in TO_FULL)) continue;
147
+ const prev = text[i - 1];
148
+ const next = text[i + 1];
149
+ let wrong: boolean;
150
+ // A bracket belongs to what it holds: `中文 (English)` is fine, `(中文)` is not.
151
+ if (ch === '(') wrong = isCjk(next);
152
+ else if (ch === ')') wrong = isCjk(prev);
153
+ else if ((ch === ',' || ch === ':') && isDigit(prev) && isDigit(next)) wrong = false;
154
+ else wrong = isCjk(prev) || isCjk(next);
155
+ if (wrong) hits.push({ start: i, end: i + 1 });
156
+ }
157
+ return hits;
158
+ }
159
+
160
+ function neighbour(text: string, from: number, step: 1 | -1): string | undefined {
161
+ let i = from + step;
162
+ while (text[i] === ' ') i += step;
163
+ return text[i];
164
+ }
165
+
166
+ function fullWidthInLatin(text: string): Hit[] {
167
+ const hits: Hit[] = [];
168
+ for (let i = 0; i < text.length; i++) {
169
+ const ch = text[i] as string;
170
+ // The opening bracket speaks for the pair; `中文(Chinese)means` closes
171
+ // a bracket opened after CJK text.
172
+ if (!(ch in TO_HALF) || ch === ')') continue;
173
+ if (isLatin(neighbour(text, i, -1)) && isLatin(neighbour(text, i, 1))) {
174
+ hits.push({ start: i, end: i + 1 });
175
+ }
176
+ }
177
+ return hits;
178
+ }
179
+
180
+ function punctuationWidth(run: TextRun, text: string, lang: string): ProofreadFinding[] {
181
+ const cjk = isCjkLang(lang);
182
+ const hits = cjk ? halfWidthInCjk(text) : fullWidthInLatin(text);
183
+ const first = hits[0];
184
+ if (!first) return [];
185
+ const ch = text[first.start] as string;
186
+ const message = cjk
187
+ ? `Half-width "${ch}" next to CJK text — use "${TO_FULL[ch]}"${times(hits.length)}.`
188
+ : `Full-width "${ch}" between Latin text — use "${TO_HALF[ch]}"${times(hits.length)}.`;
189
+ return [finding(run, 'punctuation-width', message, first)];
190
+ }
191
+
192
+ const SIMPLIFIED_NAMES = /简体中文|中文简体|简体|简中/g;
193
+ const TRADITIONAL_NAMES = /日本語|繁體中文|中文繁體|正體中文|繁體|正體|繁中/g;
194
+
195
+ function scriptMix(run: TextRun, source: string, lang: string): ProofreadFinding[] {
196
+ const script = chineseScript(lang);
197
+ if (!script) return [];
198
+ const table = script === 'hant' ? SIMPLIFIED_ONLY : TRADITIONAL_ONLY;
199
+ // A language picker writes each script's name in that script.
200
+ const own = script === 'hant' ? SIMPLIFIED_NAMES : TRADITIONAL_NAMES;
201
+ const text = source.replace(own, (m) => MASK.repeat(m.length));
202
+ const found = new Map<string, string>();
203
+ let start = -1;
204
+ for (let i = 0; i < text.length; i++) {
205
+ const ch = text[i] as string;
206
+ const other = table.get(ch);
207
+ if (!other) continue;
208
+ if (start < 0) start = i;
209
+ found.set(ch, other);
210
+ }
211
+ if (start < 0) return [];
212
+ const pairs = Array.from(found, ([from, to]) => `${from}→${to}`).join(', ');
213
+ const message =
214
+ script === 'hant'
215
+ ? `Simplified characters in a Traditional Chinese document: ${pairs}.`
216
+ : `Traditional characters in a Simplified Chinese document: ${pairs}.`;
217
+ return [finding(run, 'script-mix', message, { start, end: start + 1 })];
218
+ }
219
+
220
+ /** Doubled on purpose often enough that flagging them would be noise. */
221
+ const LEGIT_DOUBLES = new Set([
222
+ 'that',
223
+ 'had',
224
+ 'is',
225
+ 'was',
226
+ 'bye',
227
+ 'ha',
228
+ 'no',
229
+ 'so',
230
+ 'very',
231
+ 'la',
232
+ 'knock',
233
+ 'can',
234
+ 'do',
235
+ 'yes',
236
+ 'oh',
237
+ 'ho',
238
+ 'hey',
239
+ 'now',
240
+ 'well',
241
+ 'go',
242
+ 'tut',
243
+ 'wait',
244
+ ]);
245
+
246
+ const LATIN_DOUBLE_RE = /(?<![\p{L}\p{N}'’-])(\p{Script=Latin}+)\s+(\1)(?![\p{L}\p{N}'’-])/giu;
247
+
248
+ /**
249
+ * Doubled function characters that are typing slips, each with the contexts
250
+ * where the pair is a real word: 的的確確, 是是非非, 在在皆是, 小時了了.
251
+ */
252
+ const CJK_DOUBLES: Record<string, { before?: string; after?: string }> = {
253
+ 的: { after: '確确' },
254
+ 是: { after: '非' },
255
+ 在: { after: '皆都顯显說说表證证' },
256
+ 了: { before: '時时小', after: '分無无可一心這这此卻却結结' },
257
+ };
258
+
259
+ function repeatedWord(run: TextRun, text: string): ProofreadFinding[] {
260
+ const out: ProofreadFinding[] = [];
261
+ for (const m of text.matchAll(LATIN_DOUBLE_RE)) {
262
+ const [whole, word = '', second = ''] = m;
263
+ if (LEGIT_DOUBLES.has(word.toLowerCase())) continue;
264
+ // `Bora Bora`, `Walla Walla`: a capital on the second copy is a name.
265
+ if (second[0] !== second[0]?.toLowerCase()) continue;
266
+ out.push(
267
+ finding(run, 'repeated-word', `"${word} ${second}" — the word is doubled.`, {
268
+ start: m.index,
269
+ end: m.index + whole.length,
270
+ }),
271
+ );
272
+ }
273
+ for (let i = 0; i + 1 < text.length; i++) {
274
+ const ch = text[i] as string;
275
+ const rule = CJK_DOUBLES[ch];
276
+ if (!rule || text[i + 1] !== ch) continue;
277
+ const prev = text[i - 1] ?? '';
278
+ const next = text[i + 2] ?? '';
279
+ if (prev === ch || next === ch) continue;
280
+ if (rule.before && prev && rule.before.includes(prev)) continue;
281
+ if (rule.after && next && rule.after.includes(next)) continue;
282
+ out.push(
283
+ finding(run, 'repeated-word', `"${ch}${ch}" — the character is doubled.`, {
284
+ start: i,
285
+ end: i + 2,
286
+ }),
287
+ );
288
+ i++;
289
+ }
290
+ return out;
291
+ }
292
+
293
+ const WORD_RE =
294
+ /(?<![\p{Script=Latin}\p{N}])\p{Script=Latin}[\p{Script=Latin}\p{N}]+(?![\p{Script=Latin}\p{N}])/gu;
295
+
296
+ type Occurrence = { run: TextRun; start: number; end: number; form: string };
297
+
298
+ /**
299
+ * Compares how one term is capitalised across the whole document. A capital
300
+ * only on the first letter is a sentence start and ALL CAPS is a heading
301
+ * style, so neither counts as a different spelling.
302
+ */
303
+ function termCasing(runs: Array<{ run: TextRun; text: string }>): ProofreadFinding[] {
304
+ const terms = new Map<string, Map<string, Occurrence[]>>();
305
+ for (const { run, text } of runs) {
306
+ for (const m of text.matchAll(WORD_RE)) {
307
+ const form = m[0];
308
+ if (form === form.toUpperCase()) continue;
309
+ const variant = (form[0] as string).toLowerCase() + form.slice(1);
310
+ const key = form.toLowerCase();
311
+ let variants = terms.get(key);
312
+ if (!variants) {
313
+ variants = new Map();
314
+ terms.set(key, variants);
315
+ }
316
+ const list = variants.get(variant) ?? [];
317
+ list.push({ run, start: m.index, end: m.index + form.length, form });
318
+ variants.set(variant, list);
319
+ }
320
+ }
321
+
322
+ const out: ProofreadFinding[] = [];
323
+ for (const variants of terms.values()) {
324
+ if (variants.size < 2) continue;
325
+ // Most used first; on a tie the spelling met first is the one kept.
326
+ const ranked = Array.from(variants.values()).sort((a, b) => b.length - a.length);
327
+ const minority = ranked[ranked.length - 1] as Occurrence[];
328
+ const first = minority[0] as Occurrence;
329
+ const listed = ranked.map((list) => `"${commonForm(list)}" ×${list.length}`).join(', ');
330
+ out.push(
331
+ finding(
332
+ first.run,
333
+ 'term-casing',
334
+ `One term, several spellings: ${listed} — pick one.`,
335
+ first,
336
+ ),
337
+ );
338
+ }
339
+ return out;
340
+ }
341
+
342
+ function commonForm(list: Occurrence[]): string {
343
+ const counts = new Map<string, number>();
344
+ for (const { form } of list) counts.set(form, (counts.get(form) ?? 0) + 1);
345
+ return Array.from(counts).sort((a, b) => b[1] - a[1])[0]?.[0] ?? '';
346
+ }
347
+
348
+ /**
349
+ * Reads the printed text of a document and reports consistency slips a
350
+ * proofreader would mark: full-width letters, punctuation of the wrong width
351
+ * for the language, Simplified characters in a Traditional document (or the
352
+ * reverse), a doubled word, a term capitalised two ways.
353
+ *
354
+ * Advice only: every finding is a warning.
355
+ */
356
+ export function proofreadRuns(
357
+ runs: TextRun[],
358
+ docLang: string,
359
+ opts: ProofreadOptions = {},
360
+ ): ProofreadResult {
361
+ const perPageLimit = opts.perPageLimit ?? DEFAULTS.perPageLimit;
362
+ const perRuleLimit = opts.perRuleLimit ?? DEFAULTS.perRuleLimit;
363
+
364
+ const prepared = runs.map((run) => ({ run, text: masked(run.text) }));
365
+ const raw: ProofreadFinding[] = [];
366
+ for (const { run, text } of prepared) {
367
+ const lang = run.lang || docLang;
368
+ raw.push(
369
+ ...fullwidthAlnum(run, text),
370
+ ...punctuationWidth(run, text, lang),
371
+ ...scriptMix(run, text, lang),
372
+ ...repeatedWord(run, text),
373
+ );
374
+ }
375
+ raw.push(...termCasing(prepared));
376
+
377
+ const seen = new Set<string>();
378
+ const perPage = new Map<string, number>();
379
+ const perRule = new Map<string, number>();
380
+ const findings: ProofreadFinding[] = [];
381
+ let omitted = 0;
382
+ for (const f of raw.sort((a, b) => a.page - b.page)) {
383
+ // A running header prints the same words from one source line on every sheet.
384
+ const key = `${f.rule}\0${f.loc ?? ''}\0${f.message}\0${f.snippet}`;
385
+ if (seen.has(key)) continue;
386
+ seen.add(key);
387
+ const pageKey = `${f.rule}\0${f.page}`;
388
+ const onPage = perPage.get(pageKey) ?? 0;
389
+ const inRule = perRule.get(f.rule) ?? 0;
390
+ if (onPage >= perPageLimit || inRule >= perRuleLimit) {
391
+ omitted++;
392
+ continue;
393
+ }
394
+ perPage.set(pageKey, onPage + 1);
395
+ perRule.set(f.rule, inRule + 1);
396
+ findings.push(f);
397
+ }
398
+ return { findings, omitted };
399
+ }
@@ -0,0 +1,27 @@
1
+ const STORAGE = 'open-doc:recent';
2
+ const KEEP = 8;
3
+
4
+ export function pushRecent(list: readonly string[], docId: string): string[] {
5
+ return [docId, ...list.filter((id) => id !== docId)].slice(0, KEEP);
6
+ }
7
+
8
+ /** Ids no longer in the workspace — deleted, or renamed by the agent — are dropped. */
9
+ export function recentAmong(list: readonly string[], known: readonly string[], limit: number) {
10
+ const present = new Set(known);
11
+ return list.filter((id) => present.has(id)).slice(0, limit);
12
+ }
13
+
14
+ export function readRecentDocs(): string[] {
15
+ try {
16
+ const parsed: unknown = JSON.parse(localStorage.getItem(STORAGE) ?? '[]');
17
+ return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : [];
18
+ } catch {
19
+ return [];
20
+ }
21
+ }
22
+
23
+ export function markDocOpened(docId: string): void {
24
+ try {
25
+ localStorage.setItem(STORAGE, JSON.stringify(pushRecent(readRecentDocs(), docId)));
26
+ } catch {}
27
+ }
@@ -47,12 +47,41 @@ export type PageGeometry = {
47
47
  css: string;
48
48
  };
49
49
 
50
+ /** The same paper turned a quarter: a landscape section in a portrait document, or back. */
51
+ export function turnGeometry(geometry: PageGeometry): PageGeometry {
52
+ const [across, down] = geometry.css.split(/\s+/);
53
+ return { width: geometry.height, height: geometry.width, css: `${down} ${across}` };
54
+ }
55
+
56
+ /** A flow section's sheet: the document's, turned when the section sets the other orientation. */
57
+ export function sectionGeometry(
58
+ geometry: PageGeometry,
59
+ orientation: Orientation | undefined,
60
+ ): PageGeometry {
61
+ if (!orientation) return geometry;
62
+ const landscape = geometry.width > geometry.height;
63
+ return (orientation === 'landscape') === landscape ? geometry : turnGeometry(geometry);
64
+ }
65
+
50
66
  export type DocPage = ComponentType;
51
67
 
52
68
  /**
53
69
  * A run of continuous content the framework paginates itself. Build one with
54
70
  * `flow(...)` and put it in the page array alongside fixed pages.
55
71
  */
72
+ export type FlowPadding = number | { top: number; right: number; bottom: number; left: number };
73
+
74
+ /** A flow section's padding, side by side. */
75
+ export function paddingSides(
76
+ padding: FlowPadding | undefined,
77
+ fallback: number,
78
+ ): { top: number; right: number; bottom: number; left: number } {
79
+ const value = padding ?? fallback;
80
+ return typeof value === 'number'
81
+ ? { top: value, right: value, bottom: value, left: value }
82
+ : value;
83
+ }
84
+
56
85
  export type FlowSection = {
57
86
  readonly __odFlow: true;
58
87
  blocks: ReactNode[];
@@ -60,8 +89,17 @@ export type FlowSection = {
60
89
  header?: ComponentType;
61
90
  /** Rendered on every page the section expands into. */
62
91
  footer?: ComponentType;
63
- /** Page padding override in px; defaults to the design's `margin`. */
64
- padding?: number;
92
+ /**
93
+ * Page padding override in px — one number for all four sides, or each side
94
+ * on its own (a Word page's top and bottom margins rarely match its sides).
95
+ * Defaults to the design's `margin`.
96
+ */
97
+ padding?: FlowPadding;
98
+ /**
99
+ * Turns this section's sheets — a wide table's landscape pages inside a
100
+ * portrait document. Defaults to the document's orientation.
101
+ */
102
+ orientation?: Orientation;
65
103
  /** Number of columns for body content inside each page of this flow section. */
66
104
  columns?: 1 | 2 | 3;
67
105
  /** Gap in px between columns when `columns > 1`; defaults to 24. */
@@ -107,6 +145,10 @@ export type DocMeta = {
107
145
  recordLabel?: string;
108
146
  /** Diagonal watermark text stamped across every sheet (e.g. 'CONFIDENTIAL', 'DRAFT'). */
109
147
  watermark?: string;
148
+ /** Id of the document this one translates. `open-doc translations` reports when it falls behind. */
149
+ translationOf?: string;
150
+ /** The source's commit this translation matches. Written by `open-doc translations --mark`. */
151
+ translatedAt?: string;
110
152
  };
111
153
 
112
154
  /**
@@ -0,0 +1,83 @@
1
+ import { locOf, pageNumberOf } from './diagnostics';
2
+ import { PAGE_ATTR } from './outline';
3
+ import type { TextRun } from './proofread';
4
+
5
+ /** Text a proofreader leaves alone: code, and furigana that sits above a word rather than in it. */
6
+ const SKIP = new Set([
7
+ 'code',
8
+ 'pre',
9
+ 'kbd',
10
+ 'samp',
11
+ 'var',
12
+ 'script',
13
+ 'style',
14
+ 'noscript',
15
+ 'template',
16
+ 'textarea',
17
+ 'rt',
18
+ 'rp',
19
+ ]);
20
+
21
+ function isInline(el: Element): boolean {
22
+ if (el instanceof SVGElement) return el.tagName === 'tspan' || el.tagName === 'a';
23
+ const display = getComputedStyle(el).display;
24
+ return display === 'inline' || display === 'contents';
25
+ }
26
+
27
+ /**
28
+ * Splits each rendered sheet into runs of text that read as one line of
29
+ * prose: text inside one block, joined across inline marks, cut at every
30
+ * block, line break of a block, and piece of code.
31
+ */
32
+ export function collectTextRuns(root: ParentNode): TextRun[] {
33
+ const runs: TextRun[] = [];
34
+ const frames = Array.from(root.querySelectorAll<HTMLElement>(`[${PAGE_ATTR}]`));
35
+
36
+ frames.forEach((frame, index) => {
37
+ const page = pageNumberOf(frame, index);
38
+ let text = '';
39
+ let block: Element = frame;
40
+
41
+ const flush = () => {
42
+ if (text.trim()) {
43
+ const holder = block.closest('[lang]');
44
+ const lang = holder && frame.contains(holder) ? holder.getAttribute('lang') : null;
45
+ const loc = locOf(block);
46
+ runs.push({ text, page, ...(loc ? { loc } : {}), ...(lang ? { lang } : {}) });
47
+ }
48
+ text = '';
49
+ };
50
+
51
+ const walk = (node: Node, container: Element) => {
52
+ for (const child of Array.from(node.childNodes)) {
53
+ if (child.nodeType === Node.TEXT_NODE) {
54
+ if (!text) block = container;
55
+ text += (child as Text).data;
56
+ continue;
57
+ }
58
+ if (!(child instanceof Element)) continue;
59
+ if (SKIP.has(child.tagName.toLowerCase()) || child.hasAttribute('data-od-watermark')) {
60
+ flush();
61
+ continue;
62
+ }
63
+ if (child.tagName === 'BR') {
64
+ text += '\n';
65
+ continue;
66
+ }
67
+ if (!(child instanceof SVGElement) && getComputedStyle(child).display === 'none') continue;
68
+ if (isInline(child)) {
69
+ walk(child, container);
70
+ continue;
71
+ }
72
+ flush();
73
+ walk(child, child);
74
+ flush();
75
+ }
76
+ };
77
+
78
+ walk(frame, frame);
79
+ flush();
80
+ });
81
+
82
+ return runs;
83
+ }
@@ -11,11 +11,13 @@ import {
11
11
  import { type MeasurableSection, measureFlowSections } from './flow-measure';
12
12
  import { extractSectionFootnotes, notesForPage, type PreparedSection } from './footnotes';
13
13
  import { useRecordIndex } from './records';
14
- import { type DocModule, type PageGeometry, pageLang } from './sdk';
14
+ import { type DocModule, type PageGeometry, pageLang, sectionGeometry } from './sdk';
15
15
 
16
16
  export type ExpandedPage = {
17
17
  key: string;
18
18
  content: ReactNode;
19
+ /** Set when this sheet is turned from the document's: a landscape section's page. */
20
+ geometry?: PageGeometry;
19
21
  };
20
22
 
21
23
  type Plan = {
@@ -65,10 +67,13 @@ export function useDocPages(
65
67
  blocks: prepared[index].blocks,
66
68
  notesByBlock: prepared[index].notesByBlock,
67
69
  ...(section.padding !== undefined ? { padding: section.padding } : {}),
70
+ ...(sectionGeometry(geometry, section.orientation) !== geometry
71
+ ? { geometry: sectionGeometry(geometry, section.orientation) }
72
+ : {}),
68
73
  ...(section.columns !== undefined ? { columns: section.columns } : {}),
69
74
  ...(section.columnGap !== undefined ? { columnGap: section.columnGap } : {}),
70
75
  })),
71
- [sections, prepared],
76
+ [sections, prepared, geometry],
72
77
  );
73
78
 
74
79
  const [state, setState] = useState<Measured>(NOT_MEASURED);
@@ -129,6 +134,7 @@ export function useDocPages(
129
134
  const chunks: BlockSlice[][] = plan.bySection[sectionIndex] ?? [
130
135
  blocks.map((_, index) => ({ index })),
131
136
  ];
137
+ const turned = sectionGeometry(geometry, section.orientation);
132
138
  chunks.forEach((blockSlices, pageIndex) => {
133
139
  const blockIndices = blockSlices.map((s) => s.index);
134
140
  const noteIndices = blockSlices
@@ -136,6 +142,7 @@ export function useDocPages(
136
142
  .map((s) => s.index);
137
143
  out.push({
138
144
  key: `f${entryIndex}-${pageIndex}`,
145
+ ...(turned !== geometry ? { geometry: turned } : {}),
139
146
  content: createElement(FlowPage, {
140
147
  section,
141
148
  design,
@@ -149,7 +156,7 @@ export function useDocPages(
149
156
  });
150
157
 
151
158
  return out;
152
- }, [entries, plan, prepared, design]);
159
+ }, [entries, plan, prepared, design, geometry]);
153
160
 
154
161
  return { pages, measuring, overflowing: plan.overflowing };
155
162
  }
@@ -86,7 +86,7 @@ export function DocPreview() {
86
86
  <PageFrame
87
87
  index={index}
88
88
  total={pages.length}
89
- geometry={geometry}
89
+ geometry={entry.geometry ?? geometry}
90
90
  scale={1}
91
91
  design={doc.design}
92
92
  lang={pageLang(doc.meta)}