@open-document/core 0.16.0 → 0.17.0

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 (56) hide show
  1. package/dist/{build-BS_CoazO.js → build-BzNZnIhF.js} +1 -1
  2. package/dist/{check-tTjyMCrU.js → check-C7kxlAFW.js} +11 -4
  3. package/dist/cli/bin.js +24 -11
  4. package/dist/{context-Cli81dhF.js → context-CFPnmNCR.js} +1 -1
  5. package/dist/{dev-n222xdoE.js → dev-BUo7OESU.js} +1 -1
  6. package/dist/{diff-DB_qruzT.js → diff-B950T0O6.js} +2 -2
  7. package/dist/{export-CCFtdscQ.js → export-CHN1CiGv.js} +3 -3
  8. package/dist/{flow-CS5apebG.d.ts → flow-DlV3t5ML.d.ts} +24 -4
  9. package/dist/{import-D7k0yYZh.js → import-CLSnIxvN.js} +11 -7
  10. package/dist/index.d.ts +26 -2
  11. package/dist/index.js +55 -1
  12. package/dist/ops/index.d.ts +138 -4
  13. package/dist/ops/index.js +3 -3
  14. package/dist/{ops-CouYBa1O.js → ops-BgbM5Irm.js} +197 -9
  15. package/dist/{preview-DV0GDIsj.js → preview-BVwVqS-I.js} +1 -1
  16. package/dist/proofread-BpR_3GZz.js +35 -0
  17. package/dist/{session-Cx7Msl_F.js → session-DmbXf3u7.js} +5135 -67
  18. package/dist/{templates-C-7VcMMV.js → templates-BsWxs7oo.js} +3 -3
  19. package/dist/translations-CW5OVM0L.js +42 -0
  20. package/dist/vite/index.js +1 -1
  21. package/package.json +1 -1
  22. package/skills/doc-authoring/references/pagination.md +1 -1
  23. package/skills/fill-form/SKILL.md +42 -0
  24. package/skills/fit-pages/SKILL.md +48 -0
  25. package/skills/import-document/SKILL.md +58 -0
  26. package/skills/proofread/SKILL.md +44 -0
  27. package/skills/refresh-report/SKILL.md +48 -0
  28. package/skills/sync-translation/SKILL.md +55 -0
  29. package/src/agent/prompt.ts +1 -1
  30. package/src/app/components/checkbox.tsx +68 -0
  31. package/src/app/components/doc-sidebar.tsx +5 -3
  32. package/src/app/components/flow-page.tsx +7 -2
  33. package/src/app/components/panel/edit-save-card.tsx +3 -0
  34. package/src/app/lib/agent-bridge.ts +37 -4
  35. package/src/app/lib/diagnostics.ts +46 -5
  36. package/src/app/lib/export-docx.ts +5 -2
  37. package/src/app/lib/export-dom.ts +13 -0
  38. package/src/app/lib/export-html.ts +6 -1
  39. package/src/app/lib/export-image.ts +9 -4
  40. package/src/app/lib/export-pdf.ts +17 -4
  41. package/src/app/lib/flow-measure.ts +9 -5
  42. package/src/app/lib/flow.ts +3 -2
  43. package/src/app/lib/i18n-ja/browser.ts +1 -0
  44. package/src/app/lib/i18n-ko/browser.ts +1 -0
  45. package/src/app/lib/i18n-zh-cn/browser.ts +1 -0
  46. package/src/app/lib/i18n-zh-tw/browser.ts +1 -0
  47. package/src/app/lib/page-budget.ts +81 -0
  48. package/src/app/lib/proofread-script.ts +61 -0
  49. package/src/app/lib/proofread.ts +399 -0
  50. package/src/app/lib/recent-docs.ts +27 -0
  51. package/src/app/lib/sdk.ts +44 -2
  52. package/src/app/lib/text-runs.ts +83 -0
  53. package/src/app/lib/use-doc-pages.ts +10 -3
  54. package/src/app/routes/doc-preview.tsx +1 -1
  55. package/src/app/routes/doc.tsx +26 -2
  56. package/src/app/routes/home.tsx +39 -5
@@ -12,7 +12,8 @@ export type LayoutRule =
12
12
  | 'oversized-block'
13
13
  | 'orphan-heading'
14
14
  | 'tiny-text'
15
- | 'broken-image';
15
+ | 'broken-image'
16
+ | 'page-budget';
16
17
 
17
18
  export type LayoutSeverity = 'error' | 'warn';
18
19
 
@@ -59,7 +60,7 @@ function snippet(el: Element): string {
59
60
  return `${tag}: ${text.length > SNIPPET_MAX ? `${text.slice(0, SNIPPET_MAX)}…` : text}`;
60
61
  }
61
62
 
62
- function locOf(el: Element): string | undefined {
63
+ export function locOf(el: Element): string | undefined {
63
64
  return el.closest('[data-od-loc]')?.getAttribute('data-od-loc') ?? undefined;
64
65
  }
65
66
 
@@ -81,7 +82,7 @@ function leafmost(elements: Element[]): Element[] {
81
82
  return elements.filter((el) => !elements.some((other) => other !== el && el.contains(other)));
82
83
  }
83
84
 
84
- function pageNumberOf(frame: Element, fallbackIndex: number): number {
85
+ export function pageNumberOf(frame: Element, fallbackIndex: number): number {
85
86
  const declared = Number(frame.getAttribute(PAGE_INDEX_ATTR));
86
87
  return (Number.isFinite(declared) ? declared : fallbackIndex) + 1;
87
88
  }
@@ -151,8 +152,9 @@ export function diagnosePages(
151
152
  const rawText = (frame.textContent ?? '').trim();
152
153
  const text = watermarkText && rawText === watermarkText ? '' : rawText;
153
154
  // A page shell always paints — background, borders. What makes a sheet
154
- // blank is that it carries neither words nor a picture.
155
- if (text === '' && !hasMedia) {
155
+ // blank is that it carries neither words nor a picture; an empty ruled
156
+ // table is a form to fill in, not a blank sheet.
157
+ if (text === '' && !hasMedia && !frame.querySelector('td, th')) {
156
158
  findings.push({
157
159
  page,
158
160
  rule: 'blank-page',
@@ -322,6 +324,45 @@ function danglingHeadings(
322
324
  return out;
323
325
  }
324
326
 
327
+ /**
328
+ * How far down each sheet the body reaches, as a share of the space above the
329
+ * footer band — 0 for an empty sheet, about 1 for a full one. The running
330
+ * footer is left out, or every sheet would read as full.
331
+ */
332
+ export function pageFills(root: ParentNode, geometry: PageGeometry): number[] {
333
+ const frames = Array.from(root.querySelectorAll<HTMLElement>(`[${PAGE_ATTR}]`));
334
+ return frames.map((frame) => {
335
+ const frameRect = frame.getBoundingClientRect();
336
+ const footerTop = frameRect.bottom - geometry.height * FOOTER_ZONE_RATIO;
337
+ let reach = frameRect.top;
338
+ for (const el of Array.from(frame.querySelectorAll<HTMLElement>('*'))) {
339
+ if (el.closest('[data-od-watermark]')) continue;
340
+ if (!hasOwnText(el) && !MEDIA_TAGS.has(el.tagName)) continue;
341
+ const rect = el.getBoundingClientRect();
342
+ if (!isPainted(el, rect) || rect.top >= footerTop) continue;
343
+ reach = Math.max(reach, Math.min(rect.bottom, footerTop));
344
+ }
345
+ const room = footerTop - frameRect.top;
346
+ return room > 0 ? Math.round(((reach - frameRect.top) / room) * 100) / 100 : 0;
347
+ });
348
+ }
349
+
350
+ /** Where each heading with an id sits down its sheet, on the same 0–1 scale as `pageFills`. */
351
+ export function headingOffsets(root: ParentNode, geometry: PageGeometry): Record<string, number> {
352
+ const out: Record<string, number> = {};
353
+ for (const frame of Array.from(root.querySelectorAll<HTMLElement>(`[${PAGE_ATTR}]`))) {
354
+ const frameRect = frame.getBoundingClientRect();
355
+ const room = frameRect.height - geometry.height * FOOTER_ZONE_RATIO;
356
+ if (room <= 0) continue;
357
+ for (const heading of Array.from(frame.querySelectorAll<HTMLElement>(HEADING_SELECTOR))) {
358
+ if (!heading.id || heading.id in out) continue;
359
+ const top = heading.getBoundingClientRect().top - frameRect.top;
360
+ out[heading.id] = Math.round(Math.min(Math.max(top / room, 0), 1) * 100) / 100;
361
+ }
362
+ }
363
+ return out;
364
+ }
365
+
325
366
  export function summarize(findings: LayoutFinding[]): {
326
367
  errors: number;
327
368
  warnings: number;
@@ -24,7 +24,7 @@ import {
24
24
  PX_TO_TWIPS,
25
25
  type StyleId,
26
26
  } from './docx/ooxml';
27
- import { downloadBlob, withRenderedPages } from './export-dom';
27
+ import { downloadBlob, downloadName, withRenderedPages } from './export-dom';
28
28
  import { elementToPng } from './export-image';
29
29
  import { type DocEntry, type FlowSection, isFlowSection } from './flow';
30
30
  import { DocPageProvider } from './page-context';
@@ -257,5 +257,8 @@ export async function exportDocAsDocx(
257
257
  ): Promise<void> {
258
258
  const bundle = await buildDocDocx(doc, docId, pages);
259
259
  if (!bundle) return;
260
- downloadBlob(new Blob([bundle.bytes as BlobPart], { type: bundle.mimeType }), bundle.filename);
260
+ downloadBlob(
261
+ new Blob([bundle.bytes as BlobPart], { type: bundle.mimeType }),
262
+ `${downloadName(doc, docId)}.docx`,
263
+ );
261
264
  }
@@ -203,6 +203,19 @@ export function shortHash(input: string): string {
203
203
  }
204
204
  return (h >>> 0).toString(36).slice(0, 6);
205
205
  }
206
+ /** The name a browser download is saved under: the document's title, made safe for every OS. */
207
+ export function downloadName(doc: DocModule, docId: string): string {
208
+ const name = (doc.meta?.title ?? '')
209
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it removes
210
+ .replace(/[\\/:*?"<>|\u0000-\u001f]/g, ' ')
211
+ .replace(/\s+/g, ' ')
212
+ .trim()
213
+ .replace(/[. ]+$/, '')
214
+ .slice(0, 120)
215
+ .trim();
216
+ return name || docId;
217
+ }
218
+
206
219
  export function downloadBlob(blob: Blob, filename: string): void {
207
220
  const url = URL.createObjectURL(blob);
208
221
  const a = document.createElement('a');
@@ -3,6 +3,7 @@ import {
3
3
  collectCss,
4
4
  collectExternalStylesheetLinks,
5
5
  downloadBlob,
6
+ downloadName,
6
7
  escapeAttr,
7
8
  escapeHtml,
8
9
  findCssAssetUrls,
@@ -96,7 +97,11 @@ export async function exportDocAsHtml(
96
97
  ): Promise<void> {
97
98
  const bundle = await buildDocHtmlBundle(doc, docId, pages);
98
99
  if (!bundle) return;
99
- downloadBlob(new Blob([bundle.bytes as BlobPart], { type: bundle.mimeType }), bundle.filename);
100
+ const extension = bundle.filename.slice(bundle.filename.lastIndexOf('.'));
101
+ downloadBlob(
102
+ new Blob([bundle.bytes as BlobPart], { type: bundle.mimeType }),
103
+ `${downloadName(doc, docId)}${extension}`,
104
+ );
100
105
  }
101
106
 
102
107
  function rewriteUrls(
@@ -14,6 +14,7 @@
14
14
  import { designToCssVars } from './design';
15
15
  import {
16
16
  downloadBlob,
17
+ downloadName,
17
18
  findCssAssetUrls,
18
19
  findHtmlAssetUrls,
19
20
  renderPagesToHtml,
@@ -59,10 +60,11 @@ export async function exportDocAsImages(
59
60
  report('embedding', 0, 20);
60
61
  const { css, html } = await embedAssets(pagesHtml, doc);
61
62
 
63
+ const baseName = downloadName(doc, docId);
62
64
  const files: { name: string; blob: Blob }[] = [];
63
65
  for (let i = 0; i < html.length; i++) {
64
66
  const svg = buildSvg(html[i] ?? '', css, geometry, doc);
65
- const name = `${docId}-${String(i + 1).padStart(2, '0')}`;
67
+ const name = `${baseName}-${String(i + 1).padStart(2, '0')}`;
66
68
  if (format === 'svg') {
67
69
  files.push({ name: `${name}.svg`, blob: new Blob([svg], { type: 'image/svg+xml' }) });
68
70
  } else {
@@ -72,12 +74,12 @@ export async function exportDocAsImages(
72
74
  }
73
75
 
74
76
  report('done', total, 100);
75
- await deliver(files, docId, format);
77
+ await deliver(files, baseName, format);
76
78
  }
77
79
 
78
80
  async function deliver(
79
81
  files: { name: string; blob: Blob }[],
80
- docId: string,
82
+ baseName: string,
81
83
  format: ImageFormat,
82
84
  ): Promise<void> {
83
85
  const only = files[0];
@@ -89,7 +91,10 @@ async function deliver(
89
91
  const tree: Record<string, Uint8Array> = {};
90
92
  for (const file of files) tree[file.name] = new Uint8Array(await file.blob.arrayBuffer());
91
93
  const zip = zipSync(tree as Parameters<typeof zipSync>[0]);
92
- downloadBlob(new Blob([zip as BlobPart], { type: 'application/zip' }), `${docId}-${format}.zip`);
94
+ downloadBlob(
95
+ new Blob([zip as BlobPart], { type: 'application/zip' }),
96
+ `${baseName}-${format}.zip`,
97
+ );
93
98
  }
94
99
 
95
100
  async function embedAssets(
@@ -3,21 +3,27 @@ import { createRoot, type Root } from 'react-dom/client';
3
3
  import { PageErrorBoundary } from '../components/page-error-boundary';
4
4
  import { SheetWatermark } from '../components/page-frame';
5
5
  import { designToCssVars } from './design';
6
+ import { downloadName } from './export-dom';
6
7
  import { PAGE_ATTR, PAGE_INDEX_ATTR } from './outline';
7
8
  import { DocPageProvider } from './page-context';
8
9
  import { nextFrame, sleep, waitForDataWaitfor, waitForFonts, waitForImages } from './print-ready';
9
10
  import { captureScan, restoreScan, scanDocument } from './scan';
10
- import { type DocModule, resolvePageGeometry } from './sdk';
11
+ import { type DocModule, resolvePageGeometry, turnGeometry } from './sdk';
11
12
  import { scopeSvgIds } from './svg-ids';
12
13
  import type { ExpandedPage } from './use-doc-pages';
13
14
 
14
15
  export const PRINT_ROOT_ID = 'od-print-root';
15
16
  export const PRINT_PAGE_CLASS = 'od-print-page';
16
17
  const PRINT_STYLE_ID = 'od-print-style';
18
+ /** On a print page whose sheet is turned from the document's. */
19
+ export const TURNED_ATTR = 'data-od-turned';
17
20
 
18
21
  function printStyles(geometry: { width: number; height: number; css: string }): string {
22
+ const turned = turnGeometry(geometry);
19
23
  return `
20
24
  @page { size: ${geometry.css}; margin: 0; }
25
+ /* A landscape section's sheets inside a portrait document, or the reverse. */
26
+ @page od-turned { size: ${turned.css}; margin: 0; }
21
27
 
22
28
  @media screen {
23
29
  #${PRINT_ROOT_ID} {
@@ -55,6 +61,11 @@ function printStyles(geometry: { width: number; height: number; css: string }):
55
61
  -webkit-print-color-adjust: exact;
56
62
  print-color-adjust: exact;
57
63
  }
64
+ #${PRINT_ROOT_ID} .${PRINT_PAGE_CLASS}[${TURNED_ATTR}] {
65
+ width: ${turned.width}px !important;
66
+ height: ${turned.height}px !important;
67
+ page: od-turned;
68
+ }
58
69
  #${PRINT_ROOT_ID} .${PRINT_PAGE_CLASS}:last-child {
59
70
  page-break-after: auto;
60
71
  break-after: auto;
@@ -117,8 +128,10 @@ export async function mountPrintCopy(
117
128
  host.className = PRINT_PAGE_CLASS;
118
129
  host.setAttribute(PAGE_ATTR, '');
119
130
  host.setAttribute(PAGE_INDEX_ATTR, String(i));
120
- host.style.width = `${geometry.width}px`;
121
- host.style.height = `${geometry.height}px`;
131
+ const sheet = page.geometry ?? geometry;
132
+ host.style.width = `${sheet.width}px`;
133
+ host.style.height = `${sheet.height}px`;
134
+ if (page.geometry) host.setAttribute(TURNED_ATTR, '');
122
135
  if (designVars) {
123
136
  for (const [k, v] of Object.entries(designVars)) host.style.setProperty(k, v);
124
137
  host.style.background = 'var(--od-bg)';
@@ -145,7 +158,7 @@ export async function mountPrintCopy(
145
158
 
146
159
  const previousTitle = document.title;
147
160
  const previousScan = captureScan();
148
- document.title = doc.meta?.title ?? docId;
161
+ document.title = downloadName(doc, docId);
149
162
 
150
163
  const dispose = () => {
151
164
  document.title = previousTitle;
@@ -7,7 +7,7 @@ import { type DesignSystem, designToCssVars } from './design';
7
7
  import type { BlockMetrics } from './flow';
8
8
  import type { ExtractedNote } from './footnotes';
9
9
  import { nextFrame, waitForFonts } from './print-ready';
10
- import type { PageGeometry } from './sdk';
10
+ import { type FlowPadding, type PageGeometry, paddingSides } from './sdk';
11
11
 
12
12
  const HEADING_TAGS = new Set(['H1', 'H2', 'H3', 'H4']);
13
13
 
@@ -16,7 +16,9 @@ export type MeasurableSection = {
16
16
  blocks: ReactNode[];
17
17
  /** Index-aligned with `blocks`. */
18
18
  notesByBlock: ExtractedNote[][];
19
- padding?: number;
19
+ padding?: FlowPadding;
20
+ /** This section's own sheet, when it is turned from the document's. */
21
+ geometry?: PageGeometry;
20
22
  columns?: 1 | 2 | 3;
21
23
  columnGap?: number;
22
24
  };
@@ -127,7 +129,8 @@ export async function measureFlowSections(
127
129
  const blockContainers: HTMLElement[] = [];
128
130
  const noteContainers: Array<HTMLElement | null> = [];
129
131
 
130
- const paddingOf = (section: MeasurableSection) => section.padding ?? opts.design?.margin ?? 76;
132
+ const paddingOf = (section: MeasurableSection) =>
133
+ paddingSides(section.padding, opts.design?.margin ?? 76);
131
134
 
132
135
  const makeContainer = (width: number): HTMLElement => {
133
136
  const container = document.createElement('div');
@@ -146,7 +149,8 @@ export async function measureFlowSections(
146
149
  // Out of the effect that called us, so `flushSync` below may commit.
147
150
  await Promise.resolve();
148
151
  for (const section of sections) {
149
- const fullWidth = opts.geometry.width - paddingOf(section) * 2;
152
+ const sides = paddingOf(section);
153
+ const fullWidth = (section.geometry ?? opts.geometry).width - sides.left - sides.right;
150
154
  const cols = section.columns && section.columns > 1 ? section.columns : 1;
151
155
  const gap = section.columnGap ?? 24;
152
156
  const blockWidth = cols > 1 ? (fullWidth - gap * (cols - 1)) / cols : fullWidth;
@@ -224,7 +228,7 @@ export async function measureFlowSections(
224
228
 
225
229
  return {
226
230
  metrics,
227
- available: opts.geometry.height - padding * 2,
231
+ available: (section.geometry ?? opts.geometry).height - padding.top - padding.bottom,
228
232
  footnoteOverhead,
229
233
  };
230
234
  });
@@ -1,5 +1,5 @@
1
1
  import { Children, type ComponentType, Fragment, isValidElement, type ReactNode } from 'react';
2
- import type { DocEntry, FlowSection } from './sdk';
2
+ import type { DocEntry, FlowPadding, FlowSection, Orientation } from './sdk';
3
3
 
4
4
  export type { DocEntry, FlowSection };
5
5
 
@@ -30,7 +30,8 @@ export function flow(
30
30
  opts: {
31
31
  header?: ComponentType;
32
32
  footer?: ComponentType;
33
- padding?: number;
33
+ padding?: FlowPadding;
34
+ orientation?: Orientation;
34
35
  columns?: 1 | 2 | 3;
35
36
  columnGap?: number;
36
37
  } = {},
@@ -80,6 +80,7 @@ export const BROWSER: Record<string, string> = {
80
80
  Navigate: '移動',
81
81
  Open: '開く',
82
82
  'Go to': '移動先',
83
+ 'Recently opened': '最近開いたドキュメント',
83
84
  'All documents': 'すべてのドキュメント',
84
85
  Appearance: '外観',
85
86
  'Light theme': 'ライトテーマ',
@@ -79,6 +79,7 @@ export const BROWSER: Record<string, string> = {
79
79
  Navigate: '이동',
80
80
  Open: '열기',
81
81
  'Go to': '바로 가기',
82
+ 'Recently opened': '최근 연 문서',
82
83
  'All documents': '모든 문서',
83
84
  Appearance: '화면 모드',
84
85
  'Light theme': '라이트 테마',
@@ -76,6 +76,7 @@ export const BROWSER: Record<string, string> = {
76
76
  Navigate: '导航',
77
77
  Open: '打开',
78
78
  'Go to': '转到',
79
+ 'Recently opened': '最近打开',
79
80
  'All documents': '所有文档',
80
81
  Appearance: '外观',
81
82
  'Light theme': '浅色主题',
@@ -76,6 +76,7 @@ export const BROWSER: Record<string, string> = {
76
76
  Navigate: '移動',
77
77
  Open: '開啟',
78
78
  'Go to': '前往',
79
+ 'Recently opened': '最近開啟',
79
80
  'All documents': '所有文件',
80
81
  Appearance: '外觀',
81
82
  'Light theme': '淺色主題',
@@ -0,0 +1,81 @@
1
+ import type { OutlineEntry } from './outline';
2
+
3
+ export type BudgetSection = {
4
+ title: string;
5
+ level: number;
6
+ /** 1-based sheet the section's heading is on. */
7
+ startPage: number;
8
+ /** Last sheet it reaches. */
9
+ endPage: number;
10
+ /** Sheets it fills, from its heading to the next section's (or to the end of the last sheet's content). */
11
+ pages: number;
12
+ };
13
+
14
+ export type PageBudget = {
15
+ maxPages: number;
16
+ pageCount: number;
17
+ /** Sheets past the budget; 0 when it fits. */
18
+ over: number;
19
+ /** How full the last sheet is, 0–1. A nearly empty last sheet is the cheapest one to lose. */
20
+ lastPageFill: number;
21
+ /** Roughly how many sheets of body must go: `over`, less the last sheet's slack. */
22
+ toCut: number;
23
+ /** Top-rank sections in document order. */
24
+ sections: BudgetSection[];
25
+ };
26
+
27
+ const round = (n: number) => Math.round(n * 100) / 100;
28
+
29
+ /**
30
+ * What it takes to bring a document down to `maxPages` sheets, and where its
31
+ * length is. Sections are the outline's top rank; content before the first
32
+ * heading (a cover, a contents page) is its own `(front matter)` entry.
33
+ */
34
+ export function pageBudget(
35
+ maxPages: number,
36
+ pageCount: number,
37
+ fills: number[],
38
+ outline: OutlineEntry[],
39
+ offsets: Record<string, number> = {},
40
+ ): PageBudget {
41
+ const fillOf = (page: number) => fills[page - 1] ?? 1;
42
+ const lastPageFill = pageCount > 0 ? fillOf(pageCount) : 0;
43
+ const over = Math.max(0, pageCount - maxPages);
44
+
45
+ const top = outline.length > 0 ? Math.min(...outline.map((entry) => entry.level)) : 0;
46
+ const heads = outline.filter((entry) => entry.level === top);
47
+ // A position in sheets from the top of the document: page 3, halfway down, is 2.5.
48
+ const at = (head: OutlineEntry) => head.page - 1 + (offsets[head.id] ?? 0);
49
+ const end = pageCount - 1 + lastPageFill;
50
+ const sections: BudgetSection[] = [];
51
+
52
+ if (heads.length > 0 && at(heads[0]) > 0) {
53
+ sections.push({
54
+ title: '(front matter)',
55
+ level: 0,
56
+ startPage: 1,
57
+ endPage: heads[0].page - (offsets[heads[0].id] ? 0 : 1) || 1,
58
+ pages: round(at(heads[0])),
59
+ });
60
+ }
61
+ heads.forEach((head, i) => {
62
+ const next = heads[i + 1];
63
+ const until = next ? at(next) : end;
64
+ sections.push({
65
+ title: head.text,
66
+ level: head.level,
67
+ startPage: head.page,
68
+ endPage: next ? Math.max(head.page, Math.ceil(until)) : pageCount,
69
+ pages: round(Math.max(until - at(head), 0)),
70
+ });
71
+ });
72
+
73
+ return {
74
+ maxPages,
75
+ pageCount,
76
+ over,
77
+ lastPageFill,
78
+ toCut: over === 0 ? 0 : round(Math.max(over - 1 + lastPageFill, 0)),
79
+ sections,
80
+ };
81
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Simplified → Traditional pairs where each side is used by one script only.
3
+ * A character either script writes (后, 里, 干, 只, 台, 面, 系, 着, 于, 价…)
4
+ * never goes in here: flagging it would be wrong in one of them. Variant
5
+ * shapes that Hong Kong or Taiwan also print (决/決, 别/別, 没/沒) are left
6
+ * out for the same reason.
7
+ */
8
+ const PAIRS = `
9
+ 们們 这這 个個 说說 时時 会會 发發 经經 动動 实實 现現 进進 应應 关關 开開 问問 题題 学學
10
+ 国國 过過 还還 来來 对對 为為 东東 两兩 样樣 点點 长長 门門 间間 见見 觉覺 让讓 认認 识識
11
+ 话話 语語 请請 谢謝 读讀 写寫 书書 电電 脑腦 网網 络絡 页頁 图圖 画畫 报報 纸紙 级級 组組
12
+ 织織 结結 给給 统統 线線 细細 终終 绍紹 红紅 绿綠 蓝藍 买買 卖賣 车車 军軍 运運 连連 边邊
13
+ 远遠 递遞 选選 迟遲 违違 销銷 钱錢 铁鐵 银銀 错錯 镜鏡 锁鎖 键鍵 链鏈 闭閉 闻聞 阅閱 队隊
14
+ 阳陽 阴陰 际際 陆陸 随隨 险險 难難 鸡雞 鸟鳥 鱼魚 马馬 驾駕 验驗 骑騎 饭飯 馆館 饮飲 头頭
15
+ 颜顏 顺順 须須 预預 领領 频頻 颗顆 风風 飞飛 养養 岁歲 业業 丽麗 严嚴 乐樂 习習 乡鄉 乱亂
16
+ 亏虧 产產 亲親 亿億 仅僅 仓倉 众眾 优優 传傳 伤傷 伦倫 侠俠 侣侶 侧側 侦偵 债債 倾傾 偿償
17
+ 储儲 兴興 农農 刘劉 则則 刚剛 创創 剧劇 务務 劳勞 势勢 区區 华華 单單 卫衛 厂廠 厅廳 压壓
18
+ 厌厭 县縣 参參 双雙 变變 叹嘆 吗嗎 呜嗚 响響 哑啞 园園 围圍 圆圓 场場 块塊 坚堅 处處 备備
19
+ 夹夾 夺奪 奋奮 奖獎 妇婦 妈媽 娱娛 孙孫 宝寶 审審 宪憲 寻尋 导導 层層 屿嶼 岛島 帅帥 师師
20
+ 帐帳 带帶 帮幫 广廣 庆慶 库庫 废廢 张張 弹彈 归歸 当當 录錄 彻徹 径徑 忆憶 怀懷 态態 总總
21
+ 恋戀 恶惡 惊驚 惯慣 忧憂 战戰 扩擴 扫掃 抢搶 护護 拥擁 择擇 挡擋 挥揮 损損 换換 摄攝 摆擺
22
+ 击擊 敌敵 数數 断斷 旧舊 显顯 晓曉 暂暫 杀殺 权權 条條 杨楊 枪槍 标標 栏欄 树樹 桥橋 检檢
23
+ 楼樓 欢歡 欧歐 毕畢 汉漢 沟溝 浅淺 测測 济濟 浏瀏 浓濃 涨漲 渐漸 湾灣 满滿 灭滅 灵靈 烦煩
24
+ 热熱 爱愛 爷爺 状狀 犹猶 独獨 狮獅 猎獵 环環 畅暢 疗療 盘盤 码碼 础礎 祸禍 离離 积積 称稱
25
+ 稳穩 穷窮 竞競 笔筆 签簽 简簡 类類 紧緊 纪紀 约約 纯純 纳納 纵縱 练練 绑綁 续續 维維 编編
26
+ 缩縮 罗羅 罚罰 职職 联聯 肃肅 肤膚 腾騰 舰艦 艺藝 节節 荣榮 药藥 莱萊 营營 萝蘿 虑慮 虽雖
27
+ 虾蝦 蚁蟻 补補 衬襯 袭襲 装裝 观觀 规規 视視 览覽 计計 订訂 讨討 训訓 议議 讯訊 记記 讲講
28
+ 许許 论論 设設 访訪 证證 评評 诉訴 词詞 译譯 试試 诗詩 诚誠 询詢 该該 详詳 误誤 诸諸 课課
29
+ 谁誰 调調 谈談 谋謀 谓謂 谱譜 贝貝 负負 财財 责責 败敗 货貨 质質 购購 贴貼 贵貴 费費 贸貿
30
+ 资資 赏賞 赔賠 赛賽 赵趙 趋趨 跃躍 践踐 轨軌 转轉 轮輪 软軟 轻輕 载載 较較 辅輔 辆輛 输輸
31
+ 辑輯 辽遼 邮郵 邻鄰 郑鄭 酱醬 释釋 针針 钓釣 钢鋼 钥鑰 钮鈕 铃鈴 铅鉛 锅鍋 锐銳 镇鎮 闪閃
32
+ 闷悶 闹鬧 阔闊 阶階 陈陳 隐隱 雾霧 韩韓 顶頂 项項 顾顧 顿頓 额額 飘飄 饰飾 饱飽 饼餅 馈饋
33
+ 驱驅 驶駛 骂罵 骗騙 鲁魯 鲜鮮 鸭鴨 齐齊 龙龍 龟龜 帧幀 档檔 缓緩 举舉 义義 乌烏 丛叢 丝絲
34
+ 专專 丧喪 临臨 亚亞 仪儀 伞傘 伟偉 侨僑 俩倆 俭儉 兰蘭 兽獸 凤鳳 凭憑 剑劍 剂劑 办辦 劝勸
35
+ 励勵 劲勁 勋勳 协協 卢盧 卧臥 厉厲 厕廁 吓嚇 哗嘩 唤喚 喷噴 嘱囑 团團 坝壩 坟墳 坠墜 垄壟
36
+ 垒壘 墙牆 壮壯 声聲 壳殼 壶壺 妆妝 娄婁 娇嬌 婴嬰 宠寵 宽寬 宾賓 寿壽 将將 尘塵 尝嘗 属屬
37
+ 岂豈 岗崗 峡峽 币幣 帜幟 弯彎 忏懺 恳懇 恼惱 悬懸 惧懼 惨慘 惩懲 愤憤 懒懶 戏戲 执執 扬揚
38
+ 扰擾 抚撫 拟擬 拢攏 拣揀 拦攔 挚摯 挤擠 捞撈 捣搗 掷擲 斋齋 斩斬 旷曠 昼晝 晒曬 晕暈 杂雜
39
+ 栈棧 栋棟 桩樁 梦夢 椭橢 歼殲 残殘 毙斃 氢氫 汤湯 沪滬 泽澤 涛濤 渊淵 渔漁 湿濕 滞滯 滤濾
40
+ 炉爐 烂爛 烛燭 烧燒 焕煥 牵牽 狱獄 狭狹 献獻 玛瑪 琐瑣 疯瘋 盏盞 盐鹽 监監 矫矯 砖磚 窃竊
41
+ 笼籠 纠糾 纷紛 纹紋 纺紡 绕繞 绘繪 绝絕 继繼 绩績 绪緒 缅緬 缆纜 罢罷 聪聰 肠腸 肾腎 肿腫
42
+ 胀脹 胁脅 脸臉 舆輿 舱艙 艰艱 苍蒼 荡蕩 莲蓮 萨薩 蚀蝕 蛮蠻 裤褲 触觸 誉譽 诈詐 诊診 诱誘
43
+ 诺諾 谅諒 谊誼 谎謊 谜謎 谣謠 谦謙 谨謹 贞貞 贡貢 贤賢 贩販 贪貪 贫貧 贯貫 贷貸 贺賀 赋賦
44
+ 赌賭 赖賴 赚賺 赠贈 赢贏 轰轟 轴軸 辈輩 辉輝 钉釘 钞鈔 钻鑽 铜銅 锡錫 锦錦 闯闖 闸閘 阀閥
45
+ 阐闡 顽頑 颁頒 颇頗 颠顛 饲飼 馒饅 驰馳 驳駁 驻駐 骄驕 骚騷 骤驟 鸣鳴 鹅鵝 鹰鷹 齿齒 龄齡
46
+ 讽諷 儿兒
47
+ `;
48
+
49
+ function build(): { toTraditional: Map<string, string>; toSimplified: Map<string, string> } {
50
+ const toTraditional = new Map<string, string>();
51
+ const toSimplified = new Map<string, string>();
52
+ for (const pair of PAIRS.split(/\s+/)) {
53
+ const [simplified, traditional] = Array.from(pair);
54
+ if (!simplified || !traditional) continue;
55
+ toTraditional.set(simplified, traditional);
56
+ toSimplified.set(traditional, simplified);
57
+ }
58
+ return { toTraditional, toSimplified };
59
+ }
60
+
61
+ export const { toTraditional: SIMPLIFIED_ONLY, toSimplified: TRADITIONAL_ONLY } = build();