@open-document/core 0.2.0 → 0.3.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.
- package/dist/{build-U81g9Hnk.js → build-C3pMGxJN.js} +1 -1
- package/dist/check-Dtwb1wvU.js +42 -0
- package/dist/cli/bin.js +24 -3
- package/dist/config-Dg1AMP0r.js +2461 -0
- package/dist/context-FoX0afRf.js +26 -0
- package/dist/{dev-DwwFT6uX.js → dev-Cdd7NZRQ.js} +1 -1
- package/dist/diagram-xlVDekYk.js +763 -0
- package/dist/export-ClJ4T1uU.js +36 -0
- package/dist/import-D7Psi8WK.js +25 -0
- package/dist/index.d.ts +235 -90
- package/dist/index.js +515 -49
- package/dist/ops/index.d.ts +96 -1
- package/dist/ops/index.js +3 -199
- package/dist/ops-Ci5Xw6QG.js +1270 -0
- package/dist/{preview-C_jbySle.js → preview-BhbCiAKC.js} +1 -1
- package/dist/sdk-CWMsH9Ms.d.ts +123 -0
- package/dist/vite/index.d.ts +6 -0
- package/dist/vite/index.js +1 -2
- package/env.d.ts +33 -1
- package/package.json +10 -1
- package/skills/create-doc/SKILL.md +6 -2
- package/skills/doc-authoring/SKILL.md +79 -0
- package/skills/doc-authoring/references/long-form.md +131 -0
- package/src/app/components/data-table.tsx +196 -0
- package/src/app/components/diagram.tsx +76 -0
- package/src/app/components/flow-page.tsx +20 -3
- package/src/app/components/footnote.tsx +196 -0
- package/src/app/components/numbering.tsx +208 -0
- package/src/app/lib/agent-bridge.ts +128 -0
- package/src/app/lib/diagnostics.ts +282 -0
- package/src/app/lib/export-html.ts +35 -11
- package/src/app/lib/export-pdf.ts +54 -19
- package/src/app/lib/flow-measure.ts +100 -31
- package/src/app/lib/flow.test.ts +46 -0
- package/src/app/lib/flow.ts +28 -3
- package/src/app/lib/footnotes.test.tsx +102 -0
- package/src/app/lib/footnotes.ts +94 -0
- package/src/app/lib/labels.ts +175 -0
- package/src/app/lib/page-context.tsx +6 -1
- package/src/app/lib/scan.ts +26 -0
- package/src/app/lib/sdk.ts +3 -0
- package/src/app/lib/use-doc-pages.ts +50 -15
- package/src/app/routes/doc.tsx +7 -4
- package/dist/config-8zkUElGq.js +0 -1169
- package/dist/design-IyRSwCtK.js +0 -52
- package/dist/edit-ops-D2W2plpc.js +0 -1190
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { type CSSProperties, type ReactNode, useId } from 'react';
|
|
2
|
+
import {
|
|
3
|
+
formatOnPage,
|
|
4
|
+
LABEL_ATTR,
|
|
5
|
+
LABEL_ID_ATTR,
|
|
6
|
+
LABEL_TEXT_ATTR,
|
|
7
|
+
type LabelKind,
|
|
8
|
+
useDocLabel,
|
|
9
|
+
useDocLabels,
|
|
10
|
+
useLabelVocabulary,
|
|
11
|
+
} from '../lib/labels';
|
|
12
|
+
import { useDocPageNumber } from '../lib/page-context';
|
|
13
|
+
|
|
14
|
+
function nameFor(kind: LabelKind, vocabulary: { figure: string; table: string }): string {
|
|
15
|
+
return kind === 'table' ? vocabulary.table : vocabulary.figure;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type FigureProps = {
|
|
19
|
+
/** Stable id, so `<Ref to>` can point at it. Generated when omitted. */
|
|
20
|
+
id?: string;
|
|
21
|
+
/** What the caption says after the number. */
|
|
22
|
+
caption?: ReactNode;
|
|
23
|
+
/** `figure` numbers with figures, `table` with tables. Defaults to `figure`. */
|
|
24
|
+
kind?: LabelKind;
|
|
25
|
+
/** Tables conventionally caption above, figures below. */
|
|
26
|
+
captionPosition?: 'above' | 'below';
|
|
27
|
+
/** Plain-text caption for the list of figures, when `caption` carries markup. */
|
|
28
|
+
captionText?: string;
|
|
29
|
+
style?: CSSProperties;
|
|
30
|
+
captionStyle?: CSSProperties;
|
|
31
|
+
className?: string;
|
|
32
|
+
children?: ReactNode;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A numbered figure or table. The number comes from a scan of the rendered
|
|
37
|
+
* pages, not from a counter in the source, so inserting a figure halfway
|
|
38
|
+
* through a document renumbers everything after it — including the references
|
|
39
|
+
* to it — without anyone editing a number.
|
|
40
|
+
*
|
|
41
|
+
* Caption and content are one block, so a `flow()` section never separates them.
|
|
42
|
+
*/
|
|
43
|
+
export function Figure({
|
|
44
|
+
id,
|
|
45
|
+
caption,
|
|
46
|
+
kind = 'figure',
|
|
47
|
+
captionPosition,
|
|
48
|
+
captionText,
|
|
49
|
+
style,
|
|
50
|
+
captionStyle,
|
|
51
|
+
className,
|
|
52
|
+
children,
|
|
53
|
+
}: FigureProps) {
|
|
54
|
+
const generated = useId();
|
|
55
|
+
const labelId = id ?? generated;
|
|
56
|
+
const entry = useDocLabel(labelId);
|
|
57
|
+
const vocabulary = useLabelVocabulary();
|
|
58
|
+
const position = captionPosition ?? (kind === 'table' ? 'above' : 'below');
|
|
59
|
+
|
|
60
|
+
const text =
|
|
61
|
+
captionText ??
|
|
62
|
+
(typeof caption === 'string' || typeof caption === 'number' ? String(caption) : '');
|
|
63
|
+
|
|
64
|
+
const captionNode = caption ? (
|
|
65
|
+
<figcaption
|
|
66
|
+
style={{
|
|
67
|
+
fontSize: 'var(--od-size-caption)',
|
|
68
|
+
color: 'var(--od-muted)',
|
|
69
|
+
lineHeight: 1.4,
|
|
70
|
+
margin: position === 'above' ? '0 0 6px' : '6px 0 0',
|
|
71
|
+
...captionStyle,
|
|
72
|
+
}}
|
|
73
|
+
>
|
|
74
|
+
<span style={{ fontWeight: 600, color: 'var(--od-text)' }}>
|
|
75
|
+
{nameFor(kind, vocabulary)} {entry?.number ?? ''}
|
|
76
|
+
</span>
|
|
77
|
+
{caption ? <span> — {caption}</span> : null}
|
|
78
|
+
</figcaption>
|
|
79
|
+
) : null;
|
|
80
|
+
|
|
81
|
+
return (
|
|
82
|
+
<figure
|
|
83
|
+
{...{
|
|
84
|
+
[LABEL_ATTR]: kind,
|
|
85
|
+
[LABEL_ID_ATTR]: labelId,
|
|
86
|
+
[LABEL_TEXT_ATTR]: text,
|
|
87
|
+
}}
|
|
88
|
+
className={className}
|
|
89
|
+
style={{ margin: '0 0 16px', ...style }}
|
|
90
|
+
>
|
|
91
|
+
{position === 'above' && captionNode}
|
|
92
|
+
{children}
|
|
93
|
+
{position === 'below' && captionNode}
|
|
94
|
+
</figure>
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export type RefProps = {
|
|
99
|
+
/** The `id` of a `<Figure>` or `<Footnote>`. */
|
|
100
|
+
to: string;
|
|
101
|
+
/**
|
|
102
|
+
* Append the page. `auto` (the default) adds it only when the target sits on
|
|
103
|
+
* another sheet, which is the only time a reader needs it.
|
|
104
|
+
*/
|
|
105
|
+
showPage?: boolean | 'auto';
|
|
106
|
+
style?: CSSProperties;
|
|
107
|
+
className?: string;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* A cross-reference that resolves after layout: "Figure 3", plus the page when
|
|
112
|
+
* the target is elsewhere. Never write "see Figure 3 on page 12" by hand — both
|
|
113
|
+
* numbers move.
|
|
114
|
+
*/
|
|
115
|
+
export function Ref({ to, showPage = 'auto', style, className }: RefProps) {
|
|
116
|
+
const entry = useDocLabel(to);
|
|
117
|
+
const vocabulary = useLabelVocabulary();
|
|
118
|
+
const here = useDocPageNumber();
|
|
119
|
+
|
|
120
|
+
if (!entry) {
|
|
121
|
+
// Visible on the page and reported by `open-doc check`: a reference that
|
|
122
|
+
// resolves to nothing is a broken document, not a blank space.
|
|
123
|
+
return (
|
|
124
|
+
<span
|
|
125
|
+
data-od-ref-unresolved={to}
|
|
126
|
+
className={className}
|
|
127
|
+
style={{ color: 'var(--od-accent)', ...style }}
|
|
128
|
+
>
|
|
129
|
+
[?{to}]
|
|
130
|
+
</span>
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const name = entry.kind === 'footnote' ? '' : `${nameFor(entry.kind, vocabulary)} `;
|
|
135
|
+
const withPage = showPage === 'auto' ? entry.page !== here : showPage;
|
|
136
|
+
|
|
137
|
+
return (
|
|
138
|
+
<span data-od-ref={to} className={className} style={style}>
|
|
139
|
+
{name}
|
|
140
|
+
{entry.number}
|
|
141
|
+
{withPage ? formatOnPage(vocabulary, entry.page) : ''}
|
|
142
|
+
</span>
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export type ListOfProps = {
|
|
147
|
+
kind?: LabelKind;
|
|
148
|
+
/** Show the page number column with dot leaders. Defaults to true. */
|
|
149
|
+
showPageNumbers?: boolean;
|
|
150
|
+
style?: CSSProperties;
|
|
151
|
+
className?: string;
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The document's figures or tables as a contents list. Same lifecycle as
|
|
156
|
+
* `<TableOfContents>`: empty on the first render pass, filled once the scan has
|
|
157
|
+
* run — including before an export serializes.
|
|
158
|
+
*/
|
|
159
|
+
export function ListOf({ kind = 'figure', showPageNumbers = true, style, className }: ListOfProps) {
|
|
160
|
+
const entries = useDocLabels(kind);
|
|
161
|
+
const vocabulary = useLabelVocabulary();
|
|
162
|
+
|
|
163
|
+
return (
|
|
164
|
+
<div
|
|
165
|
+
data-od-list-of={kind}
|
|
166
|
+
className={className}
|
|
167
|
+
style={{
|
|
168
|
+
fontFamily: 'var(--od-font-body)',
|
|
169
|
+
fontSize: 'var(--od-size-body)',
|
|
170
|
+
color: 'var(--od-text)',
|
|
171
|
+
...style,
|
|
172
|
+
}}
|
|
173
|
+
>
|
|
174
|
+
{entries.map((entry) => (
|
|
175
|
+
<div
|
|
176
|
+
key={entry.id}
|
|
177
|
+
style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}
|
|
178
|
+
>
|
|
179
|
+
<span style={{ flex: 'none', color: 'var(--od-muted)' }}>
|
|
180
|
+
{nameFor(kind, vocabulary)} {entry.number}
|
|
181
|
+
</span>
|
|
182
|
+
<span>{entry.text}</span>
|
|
183
|
+
{showPageNumbers && (
|
|
184
|
+
<>
|
|
185
|
+
<span
|
|
186
|
+
aria-hidden
|
|
187
|
+
style={{
|
|
188
|
+
flex: 1,
|
|
189
|
+
borderBottom: '1px dotted var(--od-rule)',
|
|
190
|
+
transform: 'translateY(-3px)',
|
|
191
|
+
}}
|
|
192
|
+
/>
|
|
193
|
+
<span style={{ fontVariantNumeric: 'tabular-nums' }}>{entry.page}</span>
|
|
194
|
+
</>
|
|
195
|
+
)}
|
|
196
|
+
</div>
|
|
197
|
+
))}
|
|
198
|
+
</div>
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function ListOfFigures(props: Omit<ListOfProps, 'kind'>) {
|
|
203
|
+
return <ListOf {...props} kind="figure" />;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function ListOfTables(props: Omit<ListOfProps, 'kind'>) {
|
|
207
|
+
return <ListOf {...props} kind="table" />;
|
|
208
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { useEffect, useRef } from 'react';
|
|
2
|
+
import { diagnosePages, type LayoutFinding } from './diagnostics';
|
|
3
|
+
import { buildDocHtmlBundle } from './export-html';
|
|
4
|
+
import { mountPrintCopy } from './export-pdf';
|
|
5
|
+
import type { DocModule, PageGeometry } from './sdk';
|
|
6
|
+
import type { ExpandedPage } from './use-doc-pages';
|
|
7
|
+
|
|
8
|
+
export const BRIDGE_KEY = '__openDoc';
|
|
9
|
+
|
|
10
|
+
export type BridgeStatus = {
|
|
11
|
+
docId: string;
|
|
12
|
+
title: string;
|
|
13
|
+
/** False while the flow packer is still measuring — page count is not final yet. */
|
|
14
|
+
ready: boolean;
|
|
15
|
+
pageCount: number;
|
|
16
|
+
geometry: PageGeometry;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export type BridgeReport = BridgeStatus & { findings: LayoutFinding[] };
|
|
20
|
+
|
|
21
|
+
export type BridgeBundle = { filename: string; mimeType: string; base64: string };
|
|
22
|
+
|
|
23
|
+
export type OpenDocBridge = {
|
|
24
|
+
version: 1;
|
|
25
|
+
status(): BridgeStatus;
|
|
26
|
+
/** Mounts the print copy and reads the layout back from it. */
|
|
27
|
+
diagnose(): Promise<BridgeReport>;
|
|
28
|
+
/** Mounts the print copy and leaves it up, for `page.pdf()` or a screenshot. */
|
|
29
|
+
preparePrint(): Promise<{ pageCount: number }>;
|
|
30
|
+
releasePrint(): void;
|
|
31
|
+
htmlBundle(): Promise<BridgeBundle | null>;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
type BridgeInput = {
|
|
35
|
+
docId: string;
|
|
36
|
+
doc: DocModule | null;
|
|
37
|
+
pages: ExpandedPage[];
|
|
38
|
+
geometry: PageGeometry;
|
|
39
|
+
measuring: boolean;
|
|
40
|
+
oversized: Array<{ section: number; block: number }>;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
type GlobalWithBridge = typeof globalThis & { [BRIDGE_KEY]?: OpenDocBridge };
|
|
44
|
+
|
|
45
|
+
function toBase64(bytes: Uint8Array): string {
|
|
46
|
+
let binary = '';
|
|
47
|
+
const CHUNK = 0x8000;
|
|
48
|
+
for (let i = 0; i < bytes.length; i += CHUNK) {
|
|
49
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
|
|
50
|
+
}
|
|
51
|
+
return btoa(binary);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Publishes the rendered document to whoever is driving the page from outside —
|
|
56
|
+
* `open-doc export`, `check_layout`, `render_page`. The viewer already owns the
|
|
57
|
+
* measured page list and the print pipeline; the bridge just hands them to a
|
|
58
|
+
* headless caller instead of to a Download button, so an agent sees exactly the
|
|
59
|
+
* sheets a person would.
|
|
60
|
+
*/
|
|
61
|
+
export function useAgentBridge(input: BridgeInput): void {
|
|
62
|
+
const latest = useRef(input);
|
|
63
|
+
latest.current = input;
|
|
64
|
+
|
|
65
|
+
useEffect(() => {
|
|
66
|
+
const g = globalThis as GlobalWithBridge;
|
|
67
|
+
let held: { dispose: () => void } | null = null;
|
|
68
|
+
|
|
69
|
+
const status = (): BridgeStatus => {
|
|
70
|
+
const { docId, doc, pages, geometry, measuring } = latest.current;
|
|
71
|
+
return {
|
|
72
|
+
docId,
|
|
73
|
+
title: doc?.meta?.title ?? docId,
|
|
74
|
+
ready: doc !== null && !measuring && pages.length > 0,
|
|
75
|
+
pageCount: pages.length,
|
|
76
|
+
geometry,
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const release = () => {
|
|
81
|
+
held?.dispose();
|
|
82
|
+
held = null;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
g[BRIDGE_KEY] = {
|
|
86
|
+
version: 1,
|
|
87
|
+
status,
|
|
88
|
+
async diagnose() {
|
|
89
|
+
const { docId, doc, pages, geometry, oversized } = latest.current;
|
|
90
|
+
const snapshot = status();
|
|
91
|
+
if (!doc || pages.length === 0) return { ...snapshot, findings: [] };
|
|
92
|
+
const copy = await mountPrintCopy(doc, docId, pages);
|
|
93
|
+
try {
|
|
94
|
+
return {
|
|
95
|
+
...snapshot,
|
|
96
|
+
findings: diagnosePages(copy.root, geometry, { oversized }),
|
|
97
|
+
};
|
|
98
|
+
} finally {
|
|
99
|
+
copy.dispose();
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
async preparePrint() {
|
|
103
|
+
release();
|
|
104
|
+
const { docId, doc, pages } = latest.current;
|
|
105
|
+
if (!doc || pages.length === 0) return { pageCount: 0 };
|
|
106
|
+
held = await mountPrintCopy(doc, docId, pages);
|
|
107
|
+
return { pageCount: pages.length };
|
|
108
|
+
},
|
|
109
|
+
releasePrint: release,
|
|
110
|
+
async htmlBundle() {
|
|
111
|
+
const { docId, doc, pages } = latest.current;
|
|
112
|
+
if (!doc || pages.length === 0) return null;
|
|
113
|
+
const bundle = await buildDocHtmlBundle(doc, docId, pages);
|
|
114
|
+
if (!bundle) return null;
|
|
115
|
+
return {
|
|
116
|
+
filename: bundle.filename,
|
|
117
|
+
mimeType: bundle.mimeType,
|
|
118
|
+
base64: toBase64(bundle.bytes),
|
|
119
|
+
};
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
return () => {
|
|
124
|
+
release();
|
|
125
|
+
delete g[BRIDGE_KEY];
|
|
126
|
+
};
|
|
127
|
+
}, []);
|
|
128
|
+
}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { PAGE_ATTR, PAGE_INDEX_ATTR } from './outline';
|
|
2
|
+
import type { PageGeometry } from './sdk';
|
|
3
|
+
|
|
4
|
+
export type LayoutRule =
|
|
5
|
+
| 'unresolved-ref'
|
|
6
|
+
| 'page-overflow'
|
|
7
|
+
| 'off-page'
|
|
8
|
+
| 'blank-page'
|
|
9
|
+
| 'oversized-block'
|
|
10
|
+
| 'orphan-heading'
|
|
11
|
+
| 'tiny-text'
|
|
12
|
+
| 'broken-image';
|
|
13
|
+
|
|
14
|
+
export type LayoutSeverity = 'error' | 'warn';
|
|
15
|
+
|
|
16
|
+
export type LayoutFinding = {
|
|
17
|
+
/** 1-based sheet the problem is on. */
|
|
18
|
+
page: number;
|
|
19
|
+
rule: LayoutRule;
|
|
20
|
+
severity: LayoutSeverity;
|
|
21
|
+
message: string;
|
|
22
|
+
/** Tag plus a text snippet, so the caller can recognise the element. */
|
|
23
|
+
element?: string;
|
|
24
|
+
/** `line:column` in the document source, from the inspector's `data-od-loc`. */
|
|
25
|
+
loc?: string;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export type DiagnoseOptions = {
|
|
29
|
+
/** Flow blocks the packer reported as taller than one page. */
|
|
30
|
+
oversized?: Array<{ section: number; block: number }>;
|
|
31
|
+
/** Slack before a bounds violation counts, in CSS px. Subpixel layout needs some. */
|
|
32
|
+
tolerance?: number;
|
|
33
|
+
/** Smallest computed font size that still reads on paper. */
|
|
34
|
+
minFontSize?: number;
|
|
35
|
+
/** Findings kept per rule per page, so one broken page can't drown the report. */
|
|
36
|
+
perPageLimit?: number;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const DEFAULTS = { tolerance: 1, minFontSize: 7, perPageLimit: 3 } as const;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The band at the bottom of a sheet where a running footer lives. A heading
|
|
43
|
+
* followed only by content down here is still a dangling heading — the body it
|
|
44
|
+
* introduces went to the next page.
|
|
45
|
+
*/
|
|
46
|
+
const FOOTER_ZONE_RATIO = 0.12;
|
|
47
|
+
|
|
48
|
+
const HEADING_SELECTOR = 'h1, h2, h3, h4, [data-od-heading]';
|
|
49
|
+
const MEDIA_TAGS = new Set(['IMG', 'SVG', 'CANVAS', 'VIDEO', 'PICTURE', 'IFRAME', 'OBJECT']);
|
|
50
|
+
const SNIPPET_MAX = 60;
|
|
51
|
+
|
|
52
|
+
function snippet(el: Element): string {
|
|
53
|
+
const text = (el.textContent ?? '').replace(/\s+/g, ' ').trim();
|
|
54
|
+
const tag = el.tagName.toLowerCase();
|
|
55
|
+
if (!text) return tag;
|
|
56
|
+
return `${tag}: ${text.length > SNIPPET_MAX ? `${text.slice(0, SNIPPET_MAX)}…` : text}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function locOf(el: Element): string | undefined {
|
|
60
|
+
return el.closest('[data-od-loc]')?.getAttribute('data-od-loc') ?? undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function hasOwnText(el: Element): boolean {
|
|
64
|
+
for (const node of Array.from(el.childNodes)) {
|
|
65
|
+
if (node.nodeType === Node.TEXT_NODE && (node.textContent ?? '').trim() !== '') return true;
|
|
66
|
+
}
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function isPainted(el: Element, rect: DOMRect): boolean {
|
|
71
|
+
if (rect.width <= 0 || rect.height <= 0) return false;
|
|
72
|
+
const style = getComputedStyle(el);
|
|
73
|
+
return style.visibility !== 'hidden' && style.display !== 'none' && style.opacity !== '0';
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Keeps the innermost offender: a wrapper that only overflows because its child does is noise. */
|
|
77
|
+
function leafmost(elements: Element[]): Element[] {
|
|
78
|
+
return elements.filter((el) => !elements.some((other) => other !== el && el.contains(other)));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function pageNumberOf(frame: Element, fallbackIndex: number): number {
|
|
82
|
+
const declared = Number(frame.getAttribute(PAGE_INDEX_ATTR));
|
|
83
|
+
return (Number.isFinite(declared) ? declared : fallbackIndex) + 1;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Reads rendered sheets and reports what a person would call a layout mistake:
|
|
88
|
+
* content past the paper edge, an empty sheet, a heading stranded at the foot
|
|
89
|
+
* of a page, type too small to print, an image that never loaded.
|
|
90
|
+
*
|
|
91
|
+
* It runs against the print copy — pages at their true pixel size — so the
|
|
92
|
+
* numbers describe the PDF, not the zoomed-down viewer.
|
|
93
|
+
*/
|
|
94
|
+
export function diagnosePages(
|
|
95
|
+
root: ParentNode,
|
|
96
|
+
geometry: PageGeometry,
|
|
97
|
+
opts: DiagnoseOptions = {},
|
|
98
|
+
): LayoutFinding[] {
|
|
99
|
+
const tolerance = opts.tolerance ?? DEFAULTS.tolerance;
|
|
100
|
+
const minFontSize = opts.minFontSize ?? DEFAULTS.minFontSize;
|
|
101
|
+
const perPageLimit = opts.perPageLimit ?? DEFAULTS.perPageLimit;
|
|
102
|
+
|
|
103
|
+
const findings: LayoutFinding[] = [];
|
|
104
|
+
const frames = Array.from(root.querySelectorAll<HTMLElement>(`[${PAGE_ATTR}]`));
|
|
105
|
+
|
|
106
|
+
frames.forEach((frame, index) => {
|
|
107
|
+
const page = pageNumberOf(frame, index);
|
|
108
|
+
const frameRect = frame.getBoundingClientRect();
|
|
109
|
+
const descendants = Array.from(frame.querySelectorAll<HTMLElement>('*'));
|
|
110
|
+
|
|
111
|
+
const below: Element[] = [];
|
|
112
|
+
const sideways: Element[] = [];
|
|
113
|
+
const tiny: Element[] = [];
|
|
114
|
+
const broken: Element[] = [];
|
|
115
|
+
let hasMedia = false;
|
|
116
|
+
|
|
117
|
+
for (const el of descendants) {
|
|
118
|
+
const rect = el.getBoundingClientRect();
|
|
119
|
+
if (!isPainted(el, rect)) continue;
|
|
120
|
+
if (MEDIA_TAGS.has(el.tagName)) hasMedia = true;
|
|
121
|
+
|
|
122
|
+
if (rect.bottom > frameRect.bottom + tolerance) below.push(el);
|
|
123
|
+
if (rect.right > frameRect.right + tolerance || rect.left < frameRect.left - tolerance) {
|
|
124
|
+
sideways.push(el);
|
|
125
|
+
}
|
|
126
|
+
if (hasOwnText(el) && Number.parseFloat(getComputedStyle(el).fontSize) < minFontSize) {
|
|
127
|
+
tiny.push(el);
|
|
128
|
+
}
|
|
129
|
+
if (el instanceof HTMLImageElement && el.complete && el.naturalWidth === 0) broken.push(el);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const text = (frame.textContent ?? '').trim();
|
|
133
|
+
// A page shell always paints — background, borders. What makes a sheet
|
|
134
|
+
// blank is that it carries neither words nor a picture.
|
|
135
|
+
if (text === '' && !hasMedia) {
|
|
136
|
+
findings.push({
|
|
137
|
+
page,
|
|
138
|
+
rule: 'blank-page',
|
|
139
|
+
severity: 'error',
|
|
140
|
+
message: 'The sheet renders nothing — an empty page will still print.',
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
for (const el of leafmost(below).slice(0, perPageLimit)) {
|
|
145
|
+
const overshoot = Math.round(el.getBoundingClientRect().bottom - frameRect.bottom);
|
|
146
|
+
findings.push({
|
|
147
|
+
page,
|
|
148
|
+
rule: 'page-overflow',
|
|
149
|
+
severity: 'error',
|
|
150
|
+
message: `Content runs ${overshoot}px past the bottom of the sheet and is clipped in the PDF.`,
|
|
151
|
+
element: snippet(el),
|
|
152
|
+
loc: locOf(el),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
for (const el of leafmost(sideways).slice(0, perPageLimit)) {
|
|
157
|
+
const rect = el.getBoundingClientRect();
|
|
158
|
+
const side = rect.right > frameRect.right + tolerance ? 'right' : 'left';
|
|
159
|
+
const overshoot = Math.round(
|
|
160
|
+
side === 'right' ? rect.right - frameRect.right : frameRect.left - rect.left,
|
|
161
|
+
);
|
|
162
|
+
findings.push({
|
|
163
|
+
page,
|
|
164
|
+
rule: 'off-page',
|
|
165
|
+
severity: 'error',
|
|
166
|
+
message: `Content runs ${overshoot}px past the ${side} edge of the sheet.`,
|
|
167
|
+
element: snippet(el),
|
|
168
|
+
loc: locOf(el),
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
for (const el of leafmost(tiny).slice(0, perPageLimit)) {
|
|
173
|
+
const size = Math.round(Number.parseFloat(getComputedStyle(el).fontSize) * 10) / 10;
|
|
174
|
+
findings.push({
|
|
175
|
+
page,
|
|
176
|
+
rule: 'tiny-text',
|
|
177
|
+
severity: 'warn',
|
|
178
|
+
message: `Type is ${size}px — under ${minFontSize}px it stops being readable on paper.`,
|
|
179
|
+
element: snippet(el),
|
|
180
|
+
loc: locOf(el),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
for (const el of broken.slice(0, perPageLimit)) {
|
|
185
|
+
findings.push({
|
|
186
|
+
page,
|
|
187
|
+
rule: 'broken-image',
|
|
188
|
+
severity: 'error',
|
|
189
|
+
message: `Image failed to load: ${(el as HTMLImageElement).getAttribute('src') ?? 'no src'}`,
|
|
190
|
+
element: snippet(el),
|
|
191
|
+
loc: locOf(el),
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
for (const el of Array.from(
|
|
196
|
+
frame.querySelectorAll<HTMLElement>('[data-od-ref-unresolved]'),
|
|
197
|
+
).slice(0, perPageLimit)) {
|
|
198
|
+
findings.push({
|
|
199
|
+
page,
|
|
200
|
+
rule: 'unresolved-ref',
|
|
201
|
+
severity: 'error',
|
|
202
|
+
message: `Cross-reference points at "${el.getAttribute('data-od-ref-unresolved')}", which no figure, table, or footnote declares.`,
|
|
203
|
+
element: snippet(el),
|
|
204
|
+
loc: locOf(el),
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
findings.push(...danglingHeadings(frame, frameRect, geometry, page).slice(0, perPageLimit));
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
for (const { section, block } of opts.oversized ?? []) {
|
|
212
|
+
findings.push({
|
|
213
|
+
page: 0,
|
|
214
|
+
rule: 'oversized-block',
|
|
215
|
+
severity: 'error',
|
|
216
|
+
message: `Flow section ${section + 1}, block ${block + 1} is taller than one page. Blocks are never split — break it into smaller siblings.`,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return findings.sort((a, b) => a.page - b.page || rank(b.severity) - rank(a.severity));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function rank(severity: LayoutSeverity): number {
|
|
224
|
+
return severity === 'error' ? 1 : 0;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function danglingHeadings(
|
|
228
|
+
frame: HTMLElement,
|
|
229
|
+
frameRect: DOMRect,
|
|
230
|
+
geometry: PageGeometry,
|
|
231
|
+
page: number,
|
|
232
|
+
): LayoutFinding[] {
|
|
233
|
+
const footerTop = frameRect.bottom - geometry.height * FOOTER_ZONE_RATIO;
|
|
234
|
+
const bodyText = Array.from(frame.querySelectorAll<HTMLElement>('*')).filter(
|
|
235
|
+
(el) => hasOwnText(el) && isPainted(el, el.getBoundingClientRect()),
|
|
236
|
+
);
|
|
237
|
+
|
|
238
|
+
const out: LayoutFinding[] = [];
|
|
239
|
+
for (const heading of Array.from(frame.querySelectorAll<HTMLElement>(HEADING_SELECTOR))) {
|
|
240
|
+
// A heading kept out of the outline is decoration — a cover title, a stat
|
|
241
|
+
// label — and is supposed to end its page.
|
|
242
|
+
if (heading.getAttribute('data-od-outline') === 'skip') continue;
|
|
243
|
+
const rect = heading.getBoundingClientRect();
|
|
244
|
+
if (!isPainted(heading, rect)) continue;
|
|
245
|
+
|
|
246
|
+
const follows = bodyText.filter(
|
|
247
|
+
(el) =>
|
|
248
|
+
!heading.contains(el) &&
|
|
249
|
+
!el.contains(heading) &&
|
|
250
|
+
el.getBoundingClientRect().top >= rect.bottom - 1,
|
|
251
|
+
);
|
|
252
|
+
// Nothing after it, or nothing except whatever sits in the footer band.
|
|
253
|
+
const hasBody = follows.some((el) => el.getBoundingClientRect().top < footerTop);
|
|
254
|
+
if (hasBody) continue;
|
|
255
|
+
|
|
256
|
+
out.push({
|
|
257
|
+
page,
|
|
258
|
+
rule: 'orphan-heading',
|
|
259
|
+
severity: 'warn',
|
|
260
|
+
message: 'Heading ends the page — the section it opens starts on the next sheet.',
|
|
261
|
+
element: snippet(heading),
|
|
262
|
+
loc: locOf(heading),
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function summarize(findings: LayoutFinding[]): {
|
|
269
|
+
errors: number;
|
|
270
|
+
warnings: number;
|
|
271
|
+
byRule: Record<string, number>;
|
|
272
|
+
} {
|
|
273
|
+
const byRule: Record<string, number> = {};
|
|
274
|
+
let errors = 0;
|
|
275
|
+
let warnings = 0;
|
|
276
|
+
for (const finding of findings) {
|
|
277
|
+
byRule[finding.rule] = (byRule[finding.rule] ?? 0) + 1;
|
|
278
|
+
if (finding.severity === 'error') errors++;
|
|
279
|
+
else warnings++;
|
|
280
|
+
}
|
|
281
|
+
return { errors, warnings, byRule };
|
|
282
|
+
}
|