@openartifactsai/export-kit 0.0.0-stage → 0.23.0-rc.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.
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Cutting a long rendered document into paper pages: where each page starts so no cut falls inside a line of text or a
3
+ * picture, headings stay with what they introduce, and a forced break starts a new page. Pure: the measures come from
4
+ * document-measure.ts.
5
+ */
6
+ export const PAPER = {
7
+ letter: { width: 816, height: 1056 },
8
+ a4: { width: 794, height: 1123 },
9
+ };
10
+ /** Most pages one Flow artboard exports to. */
11
+ export const MAX_FLOW_PAGES = 100;
12
+ /** Share of a page added at each break, below the cut and above the next page's content. */
13
+ export const BREAK_MARGIN = 0.05;
14
+ /** Pictures taller than this are cut where the page ends instead of being kept whole. */
15
+ export const MAX_UNSPLIT_PICTURE = 950;
16
+ /** The margin added at each break for a page height (0 when the page is too short for it). */
17
+ export function breakMargin(pageHeight) {
18
+ const margin = Math.round(pageHeight * BREAK_MARGIN);
19
+ return margin > 0 && pageHeight - 2 * margin > 40 ? margin : 0;
20
+ }
21
+ /**
22
+ * Spans that should not be cut so a block stays with its neighbour: a
23
+ * heading with the first band (line or picture) after it, a bottom caption
24
+ * with the band before it. A span longer than a quarter of a page is not
25
+ * kept (that much empty space costs more than the split).
26
+ */
27
+ export function keepTogetherSpans(blocks, bands, pageHeight) {
28
+ const spans = [];
29
+ if (!(pageHeight > 0))
30
+ return spans;
31
+ const limit = pageHeight / 4;
32
+ const sorted = bands.filter((band) => band[1] > band[0]).sort((a, b) => a[0] - b[0]);
33
+ /** Index of the first band starting at or after `position`. */
34
+ const firstFrom = (position) => {
35
+ let low = 0;
36
+ let high = sorted.length;
37
+ while (low < high) {
38
+ const middle = (low + high) >> 1;
39
+ if (sorted[middle][0] < position - 0.5)
40
+ low = middle + 1;
41
+ else
42
+ high = middle;
43
+ }
44
+ return low;
45
+ };
46
+ for (const block of blocks) {
47
+ if (!(block.bottom > block.top) || !(block.from <= block.top))
48
+ continue;
49
+ const start = block.prev || block.bottom - block.from > limit ? block.top : block.from;
50
+ const fits = block.bottom - start <= limit;
51
+ if (fits)
52
+ spans.push([start, block.bottom]);
53
+ // A block too tall to keep whole: its first and last lines stand in for it.
54
+ let firstInside = null;
55
+ let lastInside = null;
56
+ if (!fits) {
57
+ for (let i = firstFrom(block.top); i < sorted.length && sorted[i][0] < block.bottom - 0.5; i++) {
58
+ if (sorted[i][1] > block.bottom + 0.5)
59
+ continue;
60
+ firstInside ??= sorted[i];
61
+ lastInside = sorted[i];
62
+ }
63
+ }
64
+ if (block.next) {
65
+ const index = firstFrom(block.bottom);
66
+ const from = fits ? start : lastInside ? lastInside[0] : block.top;
67
+ if (index < sorted.length && sorted[index][0] - from <= limit)
68
+ spans.push([from, sorted[index][1]]);
69
+ }
70
+ if (block.prev && block.from < block.top) {
71
+ const to = fits ? block.bottom : firstInside ? firstInside[1] : block.bottom;
72
+ if (to - block.from <= limit)
73
+ spans.push([block.from, to]);
74
+ }
75
+ }
76
+ return spans;
77
+ }
78
+ /**
79
+ * Where each page starts, in document px (the first is 0). `intervals` are
80
+ * the spans a cut must not fall inside (text lines, pictures); a span longer
81
+ * than a page's content height is ignored (it is cut where the page ends).
82
+ */
83
+ export function paginate(intervals, contentHeight, pageHeight, options = {}) {
84
+ const maxPages = Math.max(1, options.maxPages ?? MAX_FLOW_PAGES);
85
+ const overlap = options.overlap ?? 0;
86
+ const margin = overlap > 0 && pageHeight - 2 * overlap > 40 ? overlap : 0;
87
+ if (!(pageHeight > 0))
88
+ return [0];
89
+ const keepSlack = pageHeight / 4;
90
+ const keep = options.keep ?? [];
91
+ const all = keep.length ? [...intervals, ...keep] : intervals;
92
+ const plan = (spans) => {
93
+ const tops = [0];
94
+ let top = 0;
95
+ for (;;) {
96
+ const room = pageHeight - (tops.length > 1 ? margin : 0);
97
+ if (!(top + room < contentHeight - 4))
98
+ break;
99
+ if (tops.length >= maxPages)
100
+ return { tops, short: true };
101
+ const target = top + room - margin;
102
+ /** Moves the cut up out of every span it would fall inside. */
103
+ const settle = (list) => {
104
+ let cut = target;
105
+ for (let attempt = 0; attempt < 64; attempt++) {
106
+ let next = cut;
107
+ for (const span of list) {
108
+ if (span[1] - span[0] > pageHeight - 2 * margin)
109
+ continue;
110
+ if (span[0] < cut && cut < span[1] && span[0] < next)
111
+ next = span[0];
112
+ }
113
+ if (next === cut)
114
+ return { cut, settled: true };
115
+ // Nothing fits on this page without a cut through something: cut at the page's end.
116
+ if (next <= top + 40)
117
+ return null;
118
+ cut = next;
119
+ }
120
+ return { cut, settled: false };
121
+ };
122
+ const base = settle(intervals);
123
+ let cut = base === null ? target : base.cut;
124
+ if (spans !== intervals) {
125
+ const kept = settle(spans);
126
+ if (kept !== null && kept.settled && kept.cut <= cut && cut - kept.cut <= keepSlack)
127
+ cut = kept.cut;
128
+ }
129
+ tops.push(cut);
130
+ top = cut;
131
+ }
132
+ return { tops, short: false };
133
+ };
134
+ const result = plan(all);
135
+ // Keeping things together pushed past the page limit: plan again without it.
136
+ return result.short && all !== intervals ? plan(intervals).tops : result.tops;
137
+ }
138
+ /** The pages for the tops {@link paginate} chose. The last page ends with the content (or its room, at the page limit). */
139
+ export function pageSlices(tops, contentHeight, pageHeight, overlap = 0) {
140
+ const margin = overlap > 0 && pageHeight - 2 * overlap > 40 ? overlap : 0;
141
+ return tops.map((top, index) => {
142
+ const offset = index > 0 ? margin : 0;
143
+ const room = pageHeight - offset;
144
+ const next = tops[index + 1];
145
+ const bottom = Math.min(next ?? contentHeight, top + room, Math.max(top, contentHeight));
146
+ return { top, bottom: Math.max(top, bottom), offset };
147
+ });
148
+ }
149
+ /** Everything at once: the page slices of a measured Flow document. */
150
+ export function flowPages(measured, pageHeight, maxPages = MAX_FLOW_PAGES) {
151
+ const overlap = breakMargin(pageHeight);
152
+ const intervals = measured.bands.filter((band) => band[1] > band[0]);
153
+ const keep = keepTogetherSpans(measured.blocks, intervals, pageHeight);
154
+ const tops = paginate(intervals, measured.contentHeight, pageHeight, { maxPages, overlap, keep });
155
+ return pageSlices(tops, measured.contentHeight, pageHeight, overlap);
156
+ }
157
+ /**
158
+ * The page slices of a measured document that also has forced breaks (`break-before: page`): each break starts a new
159
+ * page, and what lies between two breaks is paginated on its own ({@link flowPages}). A page a break starts keeps the
160
+ * break margin above its content, as the pages after a cut do. Breaks at or before the top, past the content, or
161
+ * within 1 px of another are ignored. At most `maxPages` slices; the rest of the document is left out.
162
+ */
163
+ export function flowPagesWithBreaks(measured, pageHeight, breaks, maxPages = MAX_FLOW_PAGES) {
164
+ const starts = [0];
165
+ for (const at of [...breaks].sort((a, b) => a - b))
166
+ if (at > starts[starts.length - 1] + 1 && at < measured.contentHeight - 1)
167
+ starts.push(at);
168
+ if (starts.length === 1)
169
+ return flowPages(measured, pageHeight, maxPages);
170
+ const margin = breakMargin(pageHeight);
171
+ const out = [];
172
+ for (const [index, start] of starts.entries()) {
173
+ const room = maxPages - out.length;
174
+ if (room <= 0)
175
+ break;
176
+ const end = starts[index + 1] ?? measured.contentHeight;
177
+ // A section is paginated as a document of its own that begins `lead` px above its content: the margin its first
178
+ // page keeps. A band or block across a forced break belongs to neither side whole.
179
+ const lead = index > 0 ? margin : 0;
180
+ const shift = lead - start;
181
+ const bands = measured.bands.filter((band) => band[0] >= start - 0.5 && band[1] <= end + 0.5).map((band) => [band[0] + shift, band[1] + shift]);
182
+ const blocks = measured.blocks
183
+ .filter((block) => block.from >= start - 0.5 && block.bottom <= end + 0.5)
184
+ .map((block) => ({ ...block, top: block.top + shift, bottom: block.bottom + shift, from: block.from + shift }));
185
+ for (const [page, slice] of flowPages({ contentHeight: end - start + lead, bands, blocks }, pageHeight, room).entries()) {
186
+ if (page === 0)
187
+ out.push({ top: start, bottom: Math.max(start, slice.bottom - shift), offset: lead });
188
+ else
189
+ out.push({ top: slice.top - shift, bottom: slice.bottom - shift, offset: slice.offset });
190
+ }
191
+ }
192
+ return out;
193
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The PDF's invisible text layer and links on one page, from words and link
3
+ * boxes measured on the rendered document (document-measure.ts) and grouped
4
+ * into lines (text-layer.ts). Pure: placing lines and links on a page is
5
+ * tested without a browser.
6
+ *
7
+ * Coordinates come in document px (from the document's top left) and leave
8
+ * in PDF points from the page's top left.
9
+ */
10
+ import type { PageSlice } from './pagination.js';
11
+ import { type LinkArea, type TextLine } from './text-layer.js';
12
+ /** A text run as the PDF writer takes it (points). */
13
+ export interface PdfRun {
14
+ text: string;
15
+ x: number;
16
+ baseline: number;
17
+ size: number;
18
+ width: number;
19
+ }
20
+ /** A link as the PDF writer takes it (points). */
21
+ export interface PdfLinkBox {
22
+ uri: string;
23
+ x: number;
24
+ y: number;
25
+ width: number;
26
+ height: number;
27
+ }
28
+ /** Lines whose middle lies on the page, moved to the page and converted to points. Lines past `width` are left out. */
29
+ export declare function pageRuns(lines: readonly TextLine[], slice: PageSlice, width: number, ptPerPx: number): PdfRun[];
30
+ /** Web links (http, https, mailto) on the page, clipped to it and converted to points. */
31
+ export declare function pageLinks(areas: readonly LinkArea[], slice: PageSlice, width: number, ptPerPx: number): PdfLinkBox[];
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The PDF's invisible text layer and links on one page, from words and link
3
+ * boxes measured on the rendered document (document-measure.ts) and grouped
4
+ * into lines (text-layer.ts). Pure: placing lines and links on a page is
5
+ * tested without a browser.
6
+ *
7
+ * Coordinates come in document px (from the document's top left) and leave
8
+ * in PDF points from the page's top left.
9
+ */
10
+ import { isWebLink } from "./text-layer.js";
11
+ /** Lines whose middle lies on the page, moved to the page and converted to points. Lines past `width` are left out. */
12
+ export function pageRuns(lines, slice, width, ptPerPx) {
13
+ const out = [];
14
+ for (const line of lines) {
15
+ const middle = (line.top + line.bottom) / 2;
16
+ if (middle < slice.top || middle >= slice.bottom)
17
+ continue;
18
+ if (line.x + line.width < 0 || line.x > width || !line.text.trim())
19
+ continue;
20
+ out.push({
21
+ text: line.text,
22
+ x: line.x * ptPerPx,
23
+ baseline: (line.baseline - slice.top + slice.offset) * ptPerPx,
24
+ size: line.size * ptPerPx,
25
+ width: Math.max(0, line.width) * ptPerPx,
26
+ });
27
+ }
28
+ return out;
29
+ }
30
+ /** Web links (http, https, mailto) on the page, clipped to it and converted to points. */
31
+ export function pageLinks(areas, slice, width, ptPerPx) {
32
+ const out = [];
33
+ for (const area of areas) {
34
+ if (!isWebLink(area.href))
35
+ continue;
36
+ const top = Math.max(area.y, slice.top);
37
+ const bottom = Math.min(area.y + area.h, slice.bottom);
38
+ const left = Math.max(0, area.x);
39
+ const right = Math.min(width, area.x + area.w);
40
+ if (bottom - top < 1 || right - left < 1)
41
+ continue;
42
+ out.push({ uri: area.href, x: left * ptPerPx, y: (top - slice.top + slice.offset) * ptPerPx, width: (right - left) * ptPerPx, height: (bottom - top) * ptPerPx });
43
+ }
44
+ return out;
45
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Pictures in the browser: reading blobs as `data:` URLs, encoding canvases,
3
+ * decoding picture files, and drawing them smaller. Exports inline pictures
4
+ * into self-contained files and uploads shrink pictures to the stored limits;
5
+ * each caller keeps its own limits and qualities and passes them in.
6
+ *
7
+ * Everything here needs a DOM (FileReader, canvas, `createImageBitmap`).
8
+ */
9
+ /** Reads a blob as a `data:` URL. `failure` makes the error a failed read rejects with (default: the reader's error, else "The file could not be read."). */
10
+ export declare function blobToDataUrl(blob: Blob, failure?: (error: DOMException | null) => Error): Promise<string>;
11
+ /** A canvas as a blob (null when empty, or when the browser refuses to read it back). */
12
+ export declare function canvasBlob(canvas: HTMLCanvasElement, type: string, quality?: number): Promise<Blob | null>;
13
+ /**
14
+ * Encodes a canvas as WebP where the browser writes it, else as the type
15
+ * `fallback` names (asked only then). Null when neither could be written.
16
+ */
17
+ export declare function encodePreferringWebp(canvas: HTMLCanvasElement, quality: number, fallback: () => string): Promise<Blob | null>;
18
+ /** Decodes a picture file (SVG through an image element, drawn at 1024 × 1024 when it has no size); null when it cannot be decoded. */
19
+ export declare function decodePicture(blob: Blob): Promise<ImageBitmap | HTMLImageElement | null>;
20
+ /** The scale that brings a picture's long edge down to `maxEdge` (1 when it already fits). */
21
+ export declare function edgeScale(width: number, height: number, maxEdge: number): number;
22
+ /** How {@link drawScaled} draws. */
23
+ export interface DrawScaledOptions {
24
+ /** The canvas's `imageSmoothingQuality` (left at the browser's default when omitted). */
25
+ smoothing?: ImageSmoothingQuality;
26
+ /** Smallest canvas side, px (default 1). */
27
+ minSide?: number;
28
+ }
29
+ /**
30
+ * Draws a picture of `width` × `height` px onto a new canvas at `scale`
31
+ * (each side rounded, at least `minSide`). Null when the browser gives no
32
+ * 2D context.
33
+ */
34
+ export declare function drawScaled(source: CanvasImageSource, width: number, height: number, scale: number, options?: DrawScaledOptions): HTMLCanvasElement | null;
35
+ /** Below this many bytes, a picture that already fits is left as it is by {@link shrinkPicture}. */
36
+ export declare const SHRINK_MIN_BYTES: number;
37
+ /**
38
+ * A raster picture redrawn so its long edge is at most `maxEdge` px and
39
+ * re-encoded (WebP where the browser writes it, else JPEG, or PNG for a PNG
40
+ * that may be transparent) at `quality`. Null when the file should stay as
41
+ * it is: not a still raster picture (SVG, GIF), already small enough (fits
42
+ * and under `minBytes`), undecodable, or when the smaller copy is not
43
+ * smaller in bytes.
44
+ */
45
+ export declare function shrinkPicture(blob: Blob, maxEdge: number, quality: number, minBytes?: number): Promise<Blob | null>;
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Pictures in the browser: reading blobs as `data:` URLs, encoding canvases,
3
+ * decoding picture files, and drawing them smaller. Exports inline pictures
4
+ * into self-contained files and uploads shrink pictures to the stored limits;
5
+ * each caller keeps its own limits and qualities and passes them in.
6
+ *
7
+ * Everything here needs a DOM (FileReader, canvas, `createImageBitmap`).
8
+ */
9
+ /** Reads a blob as a `data:` URL. `failure` makes the error a failed read rejects with (default: the reader's error, else "The file could not be read."). */
10
+ export function blobToDataUrl(blob, failure = (error) => error ?? new Error('The file could not be read.')) {
11
+ return new Promise((resolve, reject) => {
12
+ const reader = new FileReader();
13
+ reader.onload = () => resolve(String(reader.result));
14
+ reader.onerror = () => reject(failure(reader.error));
15
+ reader.readAsDataURL(blob);
16
+ });
17
+ }
18
+ /** A canvas as a blob (null when empty, or when the browser refuses to read it back). */
19
+ export function canvasBlob(canvas, type, quality) {
20
+ return new Promise((resolve) => {
21
+ try {
22
+ canvas.toBlob((blob) => resolve(blob), type, quality);
23
+ }
24
+ catch {
25
+ resolve(null);
26
+ }
27
+ });
28
+ }
29
+ /**
30
+ * Encodes a canvas as WebP where the browser writes it, else as the type
31
+ * `fallback` names (asked only then). Null when neither could be written.
32
+ */
33
+ export async function encodePreferringWebp(canvas, quality, fallback) {
34
+ const webp = await canvasBlob(canvas, 'image/webp', quality);
35
+ if (webp && webp.type === 'image/webp')
36
+ return webp;
37
+ return canvasBlob(canvas, fallback(), quality);
38
+ }
39
+ /** Decodes a picture file (SVG through an image element, drawn at 1024 × 1024 when it has no size); null when it cannot be decoded. */
40
+ export async function decodePicture(blob) {
41
+ if (blob.type !== 'image/svg+xml' && typeof createImageBitmap === 'function') {
42
+ try {
43
+ return await createImageBitmap(blob);
44
+ }
45
+ catch {
46
+ // Fall through to an image element.
47
+ }
48
+ }
49
+ const url = URL.createObjectURL(blob);
50
+ try {
51
+ const image = new Image();
52
+ image.decoding = 'async';
53
+ await new Promise((resolve, reject) => {
54
+ image.onload = () => resolve();
55
+ image.onerror = () => reject(new Error('undecodable'));
56
+ image.src = url;
57
+ });
58
+ if (!image.naturalWidth || !image.naturalHeight) {
59
+ // SVG without a size: draw it at a reasonable default.
60
+ image.width = 1024;
61
+ image.height = 1024;
62
+ }
63
+ return image;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ finally {
69
+ URL.revokeObjectURL(url);
70
+ }
71
+ }
72
+ /** The scale that brings a picture's long edge down to `maxEdge` (1 when it already fits). */
73
+ export function edgeScale(width, height, maxEdge) {
74
+ return Math.min(1, maxEdge / Math.max(width, height, 1));
75
+ }
76
+ /**
77
+ * Draws a picture of `width` × `height` px onto a new canvas at `scale`
78
+ * (each side rounded, at least `minSide`). Null when the browser gives no
79
+ * 2D context.
80
+ */
81
+ export function drawScaled(source, width, height, scale, options = {}) {
82
+ const minSide = options.minSide ?? 1;
83
+ const canvas = document.createElement('canvas');
84
+ canvas.width = Math.max(minSide, Math.round(width * scale));
85
+ canvas.height = Math.max(minSide, Math.round(height * scale));
86
+ const context = canvas.getContext('2d');
87
+ if (!context)
88
+ return null;
89
+ if (options.smoothing)
90
+ context.imageSmoothingQuality = options.smoothing;
91
+ context.drawImage(source, 0, 0, canvas.width, canvas.height);
92
+ return canvas;
93
+ }
94
+ /** Below this many bytes, a picture that already fits is left as it is by {@link shrinkPicture}. */
95
+ export const SHRINK_MIN_BYTES = 512 * 1024;
96
+ /**
97
+ * A raster picture redrawn so its long edge is at most `maxEdge` px and
98
+ * re-encoded (WebP where the browser writes it, else JPEG, or PNG for a PNG
99
+ * that may be transparent) at `quality`. Null when the file should stay as
100
+ * it is: not a still raster picture (SVG, GIF), already small enough (fits
101
+ * and under `minBytes`), undecodable, or when the smaller copy is not
102
+ * smaller in bytes.
103
+ */
104
+ export async function shrinkPicture(blob, maxEdge, quality, minBytes = SHRINK_MIN_BYTES) {
105
+ if (!/^image\/(png|jpeg|jpg|webp|avif|bmp)$/.test(blob.type))
106
+ return null;
107
+ const bitmap = await decodePicture(blob);
108
+ if (!bitmap)
109
+ return null;
110
+ try {
111
+ const { width, height } = bitmap;
112
+ const scale = edgeScale(width, height, maxEdge);
113
+ if (scale >= 1 && blob.size < minBytes)
114
+ return null;
115
+ const canvas = drawScaled(bitmap, width, height, scale, { smoothing: 'high' });
116
+ if (!canvas)
117
+ return null;
118
+ const out = await encodePreferringWebp(canvas, quality, () => (blob.type === 'image/png' ? 'image/png' : 'image/jpeg'));
119
+ return out && out.size < blob.size ? out : null;
120
+ }
121
+ finally {
122
+ if ('close' in bitmap)
123
+ bitmap.close();
124
+ }
125
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The PDF text layer, pure part: words measured on a rendered page
3
+ * (dom/measure.ts) joined into the lines they sit on. A PDF draws each line
4
+ * as an invisible, selectable run over the page's picture, so text can be
5
+ * searched and copied.
6
+ *
7
+ * Coordinates are whatever the words were measured in (slide px, document
8
+ * px); placing lines on a PDF page is up to each editor.
9
+ */
10
+ /** One word as drawn. */
11
+ export interface Word {
12
+ text: string;
13
+ left: number;
14
+ right: number;
15
+ top: number;
16
+ bottom: number;
17
+ /** Font size, px. */
18
+ size: number;
19
+ /** A space follows it in the source. */
20
+ space: boolean;
21
+ }
22
+ /** A line of words. */
23
+ export interface TextLine {
24
+ text: string;
25
+ /** Left edge. */
26
+ x: number;
27
+ /** Top of the line box (its first word's top). */
28
+ top: number;
29
+ /** Bottom of the line box (its lowest word's bottom). */
30
+ bottom: number;
31
+ /** Baseline, from the top. */
32
+ baseline: number;
33
+ /** Font size (the largest of its words). */
34
+ size: number;
35
+ /** Drawn width. */
36
+ width: number;
37
+ }
38
+ /** A link's clickable area. */
39
+ export interface LinkArea {
40
+ href: string;
41
+ x: number;
42
+ y: number;
43
+ w: number;
44
+ h: number;
45
+ }
46
+ /**
47
+ * Joins words in reading order into the lines they sit on. A word continues
48
+ * the current line when its top is within half its font size of the line's
49
+ * top and it starts at most 0.3 em before, and less than 2.5 em after, the
50
+ * line's right edge; a space goes between when the source has one or the
51
+ * gap is wider than 0.15 em. Empty words are skipped.
52
+ */
53
+ export declare function groupLines(words: Iterable<Word>): TextLine[];
54
+ /** True for a web link a PDF keeps: http, https or mailto. */
55
+ export declare function isWebLink(href: string): boolean;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The PDF text layer, pure part: words measured on a rendered page
3
+ * (dom/measure.ts) joined into the lines they sit on. A PDF draws each line
4
+ * as an invisible, selectable run over the page's picture, so text can be
5
+ * searched and copied.
6
+ *
7
+ * Coordinates are whatever the words were measured in (slide px, document
8
+ * px); placing lines on a PDF page is up to each editor.
9
+ */
10
+ /**
11
+ * Joins words in reading order into the lines they sit on. A word continues
12
+ * the current line when its top is within half its font size of the line's
13
+ * top and it starts at most 0.3 em before, and less than 2.5 em after, the
14
+ * line's right edge; a space goes between when the source has one or the
15
+ * gap is wider than 0.15 em. Empty words are skipped.
16
+ */
17
+ export function groupLines(words) {
18
+ const lines = [];
19
+ let current = null;
20
+ const flush = () => {
21
+ if (current)
22
+ lines.push({ text: current.text, x: current.x, top: current.top, bottom: current.bottom, baseline: current.baseline, size: current.size, width: current.right - current.x });
23
+ current = null;
24
+ };
25
+ for (const word of words) {
26
+ if (!word.text)
27
+ continue;
28
+ const line = current;
29
+ if (line && Math.abs(word.top - line.top) < word.size * 0.5 && word.left >= line.right - word.size * 0.3 && word.left - line.right < word.size * 2.5) {
30
+ const gap = word.left - line.right > word.size * 0.15;
31
+ line.text += (line.space || gap ? ' ' : '') + word.text;
32
+ line.right = Math.max(line.right, word.right);
33
+ line.bottom = Math.max(line.bottom, word.bottom);
34
+ line.space = word.space;
35
+ line.size = Math.max(line.size, word.size);
36
+ continue;
37
+ }
38
+ flush();
39
+ const baseline = word.bottom - (word.bottom - word.top) * 0.2;
40
+ current = { text: word.text, x: word.left, top: word.top, bottom: word.bottom, baseline, size: word.size, width: 0, right: word.right, space: word.space };
41
+ }
42
+ flush();
43
+ return lines;
44
+ }
45
+ /** True for a web link a PDF keeps: http, https or mailto. */
46
+ export function isWebLink(href) {
47
+ return /^(https?:|mailto:)/i.test(href);
48
+ }