@quario/pdf 0.2.0 → 0.4.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/lib/style.js DELETED
@@ -1,106 +0,0 @@
1
- /**
2
- * The PDF target's reading of the closed style vocabulary — the counterpart of
3
- * the CSS table in the HTML target package. Declarations are lenient at
4
- * render: a value of the wrong shape contributes nothing rather than reaching
5
- * the page.
6
- *
7
- * `HEX` is restated per target on purpose: the coercion is each target's own
8
- * edge, never shared engine code. Finiteness is not one of those coercions —
9
- * `Number.isFinite` never coerces, so this target asks it directly.
10
- */
11
- import { rgb } from "pdf-lib";
12
-
13
- let HEX = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
14
-
15
- // Leading as a fraction of the font size, cell padding, the gap between a
16
- // page band and the body, and the gutter between two page-column strips.
17
- // `example/print.css` is the reference look (10pt/1.4) — body type stays a
18
- // host decision, so `@quario/html/style.css` carries no `body` rule and this
19
- // pairs with the example rather than it.
20
- //
21
- // GUTTER is this target's structural default: SCHEMA.md gives page columns no
22
- // gap knob deliberately, so the space between strips is the target's to pick
23
- // and an author never writes it. Twice the cell padding, which is the widest
24
- // space this target already puts between two columns of anything.
25
- let LEAD = 1.4;
26
- let PADX = 6;
27
- let PADY = 2;
28
- let BAND = 8;
29
- let GUTTER = 2 * PADX;
30
-
31
- let BLACK = rgb(0, 0, 0);
32
-
33
- // Horizontal placement within a given leftover width: left keeps it, right
34
- // takes all of it, center takes half. Own-key so an authored `constructor`
35
- // cannot resolve an inherited member.
36
- /** @type {Record<string, number>} */
37
- let SHIFT = { right: 1, center: 0.5 };
38
- /** @type {(align: any, extra: number) => number} */
39
- let shift = (align, extra) => (Object.hasOwn(SHIFT, align) ? SHIFT[align] : 0) * extra;
40
-
41
- // A declared colour as a pdf-lib colour, or null when the value is not one.
42
- /** @type {(value: any) => any} */
43
- let col = (value) => {
44
- let match = typeof value === "string" && HEX.exec(value);
45
- if (!match) return null;
46
- // `#abc` is `#aabbcc`.
47
- let digits = match[1].length === 3 ? match[1].replace(/./g, (d) => d + d) : match[1];
48
- let [r, g, b] = [0, 2, 4].map((i) => parseInt(digits.slice(i, i + 2), 16) / 255);
49
- return rgb(r, g, b);
50
- };
51
-
52
- /** @type {(style: any, base: number) => number} */
53
- let sizeOf = (style, base) => (Number.isFinite(style.size) && style.size > 0 ? style.size : base);
54
-
55
- // Style blocks layer outward-in: row under cell.
56
- /** @type {(under: any, over: any) => any} */
57
- let merge = (under, over) => (under ? (over ? { ...under, ...over } : under) : over || {});
58
-
59
- // The whole stack a resolved style is composed of, outermost first: the report
60
- // default the canvas carries, the enclosing block's style (a table row's, a
61
- // split's), and the node's own. This target's reading of docs/adr/0033, in one
62
- // place, so a third resolution funnel cannot quietly omit the outer layer.
63
- //
64
- // Only `family` is load-bearing in the outer layer: `settle` has already put
65
- // the report default's `size` on `canvas.base`, which `sizeOf` falls back to
66
- // for every drawn atom, so the size reaches the page whether or not it is
67
- // merged here.
68
- /** @type {(canvas: { style?: any }, under: any, own: any) => any} */
69
- let stack = (canvas, under, own) => merge(canvas.style, merge(under, own));
70
-
71
- // Band-role omakase defaults — the outermost layer of that same stack, under
72
- // the author's own style, which therefore always wins. Only the headline
73
- // roles carry one; the XLSX target carries the same two, byte-identical, in
74
- // `packages/xlsx/lib/index.js`, and they move together (SCHEMA.md states the
75
- // pair for both). A target can only import public engine helpers, so there is
76
- // nowhere to share this from and the two copies are synced by hand.
77
- //
78
- // `@quario/html` deliberately carries none of this, nor the leading, padding
79
- // and band gap below: its consumer has a stylesheet and the `q-*` classes are
80
- // the seam. The rule is docs/adr/0014-a-target-supplies-defaults-only-where-its-consumer-has-no-seam.md —
81
- // a target supplies defaults only where its consumer has no seam to supply
82
- // them. `@quario/html/style.css` and `packages/viewer/lib/style.js` are what supply
83
- // them there; keep all four in agreement.
84
- /** @type {Record<string, any>} */
85
- let ROLES = { "report-header": { bold: true, size: 14 }, "group-header": { bold: true } };
86
-
87
- // One item event wearing its role's defaults. Events reach layout as events,
88
- // so the default is folded into a copy rather than passed alongside.
89
- /** @type {(event: any) => any} */
90
- let roled = (event) =>
91
- Object.hasOwn(ROLES, event.role)
92
- ? { ...event, style: merge(ROLES[event.role], event.style) }
93
- : event;
94
-
95
- // Whether a resolved style asks for either text decoration -- one reading for
96
- // the wrapper that stamps it on a line and the canvas that draws it.
97
- /** @type {(style: any) => boolean} */
98
- let dressed = (style) => !!(style && (style.underline || style.strikethrough));
99
-
100
- // Whether a resolved style asks for capitals. This target has no
101
- // text-transform to defer to, so the reading is here beside the rest of the
102
- // vocabulary and `text.js` applies it before measuring.
103
- /** @type {(style: any) => boolean} */
104
- let upper = (style) => !!(style && style.uppercase);
105
-
106
- export { BAND, BLACK, GUTTER, LEAD, PADX, PADY, col, dressed, roled, shift, sizeOf, stack, upper };
package/lib/text.js DELETED
@@ -1,247 +0,0 @@
1
- /**
2
- * Measuring and breaking text: tokens flatten to word and space atoms carrying
3
- * their resolved typography, and a greedy breaker turns those into lines. Pure
4
- * measurement against the font registry — nothing here touches the page.
5
- */
6
- import { display } from "quario";
7
- import { ascOf, face, printable, width } from "./fonts.js";
8
- import { LEAD, col, dressed, sizeOf, upper } from "./style.js";
9
-
10
- // What measuring needs and no more: the embedded faces to measure against
11
- // and the base size a style falls back to. A `Canvas` satisfies it, so
12
- // callers pass theirs straight in — but nothing here can touch a page.
13
- /** @typedef {{ fonts: import('./fonts.js').Fonts, base: number }} Metrics */
14
-
15
- /**
16
- * @typedef {{ text: string, font: any, size: number, color: any,
17
- * space: boolean, hard: boolean }} Atom
18
- */
19
- /**
20
- * @typedef {{ pieces: { text: string, font: any, size: number, color: any,
21
- * w: number }[], w: number, h: number, size: number, asc: number,
22
- * underline?: boolean, strikethrough?: boolean }} Line
23
- */
24
-
25
- /**
26
- * @typedef {{ cur: Atom[], w: number, lines: Line[], base: number,
27
- * fonts: import('./fonts.js').Fonts }} Wrap
28
- */
29
-
30
- /** @type {(token: any) => string} */
31
- let rawOf = (token) => ("literal" in token ? token.literal : display(token.value));
32
-
33
- // This target has no text-transform to defer to, so `uppercase` is applied to
34
- // the string before it is measured -- the widths have to be the widths of what
35
- // is actually drawn. `toUpperCase` rather than `toLocaleUpperCase`: this
36
- // target's output is byte-reproducible, so the host's locale must not reach
37
- // the glyphs.
38
- /** @type {(text: string, style: any) => string} */
39
- let cased = (text, style) => (upper(style) ? text.toUpperCase() : text);
40
-
41
- /** @type {(font: any, line: string) => string[]} */
42
- let partsOf = (font, line) => printable(font, line).split(/( +)/).filter(Boolean);
43
-
44
- /** @type {(out: Atom[], font: any, size: number, color: any, line: string) => void} */
45
- let pushParts = (out, font, size, color, line) => {
46
- for (let part of partsOf(font, line))
47
- out.push({ text: part, font, size, color, space: part[0] === " ", hard: false });
48
- };
49
-
50
- /** @type {(out: Atom[], font: any, size: number, color: any, i: number, line: string) => void} */
51
- let pushLine = (out, font, size, color, i, line) => {
52
- if (i) out.push({ text: "", font, size, color, space: false, hard: true });
53
- pushParts(out, font, size, color, line);
54
- };
55
-
56
- /** @type {(metrics: Metrics, style: any) => { font: any, size: number, color: any }} */
57
- let look = (metrics, style) => {
58
- let resolved = style || {};
59
- return {
60
- font: face(metrics.fonts, resolved),
61
- size: sizeOf(resolved, metrics.base),
62
- color: col(resolved.color),
63
- };
64
- };
65
-
66
- // Flatten a cell's tokens to word/space atoms carrying the cell's resolved
67
- // typography — one face, size and colour for the whole cell.
68
- /** @type {(metrics: Metrics, tokens: any[], style: any) => Atom[]} */
69
- let atoms = (metrics, tokens, style) => {
70
- let out = /** @type {Atom[]} */ ([]);
71
- let { font, size, color } = look(metrics, style);
72
- for (let token of tokens)
73
- for (let [i, line] of cased(rawOf(token), style).split("\n").entries())
74
- pushLine(out, font, size, color, i, line);
75
- return out;
76
- };
77
-
78
- /** @type {(cur: Atom[]) => void} */
79
- let trimEnd = (cur) => {
80
- while (cur.length && cur[cur.length - 1].space) cur.pop();
81
- };
82
-
83
- /** @type {(pieces: Line['pieces'], atom: Atom, atomWidth: number) => void} */
84
- let mergeAtom = (pieces, atom, atomWidth) => {
85
- let last = pieces[pieces.length - 1];
86
- if (last) {
87
- last.text += atom.text;
88
- last.w += atomWidth;
89
- return;
90
- }
91
- pieces.push({
92
- text: atom.text,
93
- font: atom.font,
94
- size: atom.size,
95
- color: atom.color,
96
- w: atomWidth,
97
- });
98
- };
99
-
100
- /** @typedef {{ pieces: Line['pieces'], w: number, size: number, asc: number }} Run */
101
-
102
- /** @type {(run: Run, atom: Atom) => void} */
103
- let growPiece = (run, atom) => {
104
- let atomWidth = width(atom.font, atom.text, atom.size);
105
- run.w += atomWidth;
106
- if (atom.size > run.size) run.size = atom.size;
107
- let atomAsc = ascOf(atom.font, atom.size);
108
- if (atomAsc > run.asc) run.asc = atomAsc;
109
- mergeAtom(run.pieces, atom, atomWidth);
110
- };
111
-
112
- /** @type {(state: Wrap, run: Run) => void} */
113
- let finish = (state, run) => {
114
- if (!run.size) run.size = state.base;
115
- if (!run.asc) run.asc = ascOf(face(state.fonts, {}), run.size);
116
- state.lines.push({
117
- pieces: run.pieces,
118
- w: run.w,
119
- h: LEAD * run.size,
120
- size: run.size,
121
- asc: run.asc,
122
- });
123
- state.cur = [];
124
- state.w = 0;
125
- };
126
-
127
- // `force` keeps deliberately blank lines (hard breaks, an empty value);
128
- // a word-overflow close passes false so a line of pure trimmed spaces
129
- // vanishes instead of becoming a phantom line.
130
- /** @type {(state: Wrap, force?: boolean) => void} */
131
- let emit = (state, force = true) => {
132
- trimEnd(state.cur);
133
- if (!force && !state.cur.length) {
134
- state.w = 0;
135
- return;
136
- }
137
- /** @type {Run} */
138
- let run = { pieces: [], w: 0, size: 0, asc: 0 };
139
- for (let atom of state.cur) growPiece(run, atom);
140
- finish(state, run);
141
- };
142
-
143
- /** @type {(atom: Atom, rest: string[], avail: number) => number} */
144
- let fitChars = (atom, rest, avail) => {
145
- let n = 1;
146
- while (n < rest.length) {
147
- let longer = rest.slice(0, n + 1).join("");
148
- if (width(atom.font, longer, atom.size) > avail) break;
149
- n++;
150
- }
151
- return n;
152
- };
153
-
154
- /** @type {(state: Wrap, atom: Atom, rest: string[], avail: number) => string[]} */
155
- let takeChunk = (state, atom, rest, avail) => {
156
- let n = fitChars(atom, rest, avail);
157
- let take = rest.slice(0, n).join("");
158
- state.cur.push({ ...atom, text: take });
159
- state.w = width(atom.font, take, atom.size);
160
- return rest.slice(n);
161
- };
162
-
163
- // An over-wide word alone on its line breaks by character. Both callers
164
- // enter with the line empty, and `emit()` empties it again between
165
- // chunks, so each chunk appends to a bare line. The final chunk stays in
166
- // `cur` (with `w` set) instead of closing, so following atoms may join its
167
- // line. Split by code point, so an astral character is never halved.
168
- /** @type {(state: Wrap, atom: Atom, avail: number) => void} */
169
- let chunk = (state, atom, avail) => {
170
- // Slicing is per code point throughout this module — `no-misused-spread`
171
- // is warning about the grapheme clusters no base-14 face can encode.
172
- // oxlint-disable-next-line typescript/no-misused-spread
173
- let rest = [...atom.text];
174
- while (rest.length) {
175
- rest = takeChunk(state, atom, rest, avail);
176
- if (rest.length) emit(state);
177
- }
178
- };
179
-
180
- /** @type {(atom: Atom, atomWidth: number, avail: number) => boolean} */
181
- let isWide = (atom, atomWidth, avail) => {
182
- // oxlint-disable-next-line typescript/no-misused-spread
183
- return atomWidth > avail && [...atom.text].length > 1 && !atom.space;
184
- };
185
-
186
- /** @type {(state: Wrap, atom: Atom, atomWidth: number, avail: number) => boolean} */
187
- let canFit = (state, atom, atomWidth, avail) =>
188
- state.w + atomWidth <= avail || !state.cur.length || atom.space;
189
-
190
- /** @type {(state: Wrap, atom: Atom, atomWidth: number) => void} */
191
- let append = (state, atom, atomWidth) => {
192
- state.cur.push(atom);
193
- state.w += atomWidth;
194
- };
195
-
196
- /** @type {(state: Wrap, atom: Atom, atomWidth: number, avail: number, wide: boolean) => void} */
197
- let overflow = (state, atom, atomWidth, avail, wide) => {
198
- emit(state, false);
199
- if (atom.space) return;
200
- if (wide) chunk(state, atom, avail);
201
- else append(state, atom, atomWidth);
202
- };
203
-
204
- /** @type {(state: Wrap, wide: boolean) => boolean} */
205
- let startWide = (state, wide) => !state.cur.length && wide;
206
-
207
- /** @type {(state: Wrap, atom: Atom, avail: number) => void} */
208
- let placeAtom = (state, atom, avail) => {
209
- if (atom.hard) return emit(state);
210
- let atomWidth = width(atom.font, atom.text, atom.size);
211
- let wide = isWide(atom, atomWidth, avail);
212
- if (!canFit(state, atom, atomWidth, avail)) return overflow(state, atom, atomWidth, avail, wide);
213
- if (startWide(state, wide)) return chunk(state, atom, avail);
214
- append(state, atom, atomWidth);
215
- };
216
-
217
- // Greedy wrap against `avail`: spaces never start a line, an over-wide word
218
- // breaks by character, hard breaks always break. A cell's atoms share one
219
- // typography, so a line's atoms merge into a single draw piece.
220
- /** @type {(metrics: Metrics, list: Atom[], avail: number) => Line[]} */
221
- let wrap = (metrics, list, avail) => {
222
- /** @type {Wrap} */
223
- let state = { cur: [], w: 0, lines: [], base: metrics.base, fonts: metrics.fonts };
224
- for (let atom of list) placeAtom(state, atom, avail);
225
- emit(state);
226
- return state.lines;
227
- };
228
-
229
- // Stamp cell-level decorations onto every wrapped fragment. Measurement does
230
- // not need them; drawing does, and wrapping must not lose them.
231
- /** @type {(line: Line, underline: boolean, strikethrough: boolean) => void} */
232
- let stamp = (line, underline, strikethrough) => {
233
- if (underline) line.underline = true;
234
- if (strikethrough) line.strikethrough = true;
235
- };
236
-
237
- /** @type {(lines: Line[], style: any) => Line[]} */
238
- let dress = (lines, style) => {
239
- if (!dressed(style)) return lines;
240
- for (let line of lines) stamp(line, !!style.underline, !!style.strikethrough);
241
- return lines;
242
- };
243
-
244
- /** @type {(lines: Line[]) => number} */
245
- let heightOf = (lines) => lines.reduce((total, line) => total + line.h, 0);
246
-
247
- export { atoms, dress, heightOf, wrap };