@paragraf/linebreak 0.0.0-stage → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 paragraf contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,130 @@
1
- # Temporary Holding Version
1
+ # @paragraf/linebreak
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Knuth-Plass optimum line-breaking algorithm with hyphenation. No font dependencies, no WASM — pure TypeScript, browser-safe.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @paragraf/linebreak @paragraf/types
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### `computeBreakpoints` + `traceback` + `composeParagraph`
14
+
15
+ Build a node sequence, find breakpoints, then assemble composed lines:
16
+
17
+ ```ts
18
+ import { computeBreakpoints, traceback, composeParagraph } from '@paragraf/linebreak';
19
+
20
+ const result = computeBreakpoints(paragraph);
21
+ // result.usedEmergency is true if emergencyStretch was needed; result.usedFallback is true
22
+ // if the paragraph could not be set within tolerance (pass onInfeasible: 'throw' to throw instead)
23
+ const breaks = traceback(result.node);
24
+ const lines = composeParagraph(nodes, breaks, 'justified', false, lineWidth, [], getMetrics);
25
+ ```
26
+
27
+ ### Node building: `buildNodeSequence`
28
+
29
+ Converts hyphenated words + fonts into the node sequence the algorithm expects.
30
+
31
+ ```ts
32
+ import { buildNodeSequence } from '@paragraf/linebreak';
33
+
34
+ const nodes = buildNodeSequence(hyphenatedWords, measurer);
35
+ ```
36
+
37
+ ### Hyphenation
38
+
39
+ ```ts
40
+ import { loadHyphenator, hyphenateWord, hyphenateParagraph, loadLanguages } from '@paragraf/linebreak';
41
+
42
+ // Load patterns for a language (must call before hyphenating)
43
+ await loadHyphenator('en-us');
44
+ // patterns loaded — use hyphenateWord / hyphenateParagraph from this point on
45
+ const words = hyphenateParagraph(text, { language: 'en-us', minWordLength: 5, fontSize: 12 });
46
+
47
+ // Batch-load multiple languages
48
+ await loadLanguages(['en-us', 'de', 'fr']);
49
+ ```
50
+
51
+ #### `HyphenateOptions`
52
+
53
+ ```ts
54
+ interface HyphenateOptions {
55
+ minWordLength: number; // required — skip words shorter than this
56
+ fontSize: number; // required — drives minLeft/minRight derivation
57
+ language: Language; // required
58
+ preserveSoftHyphens?: boolean; // default true
59
+ minLeft?: number; // override the font-size-derived minimum left fragment
60
+ minRight?: number; // override the font-size-derived minimum right fragment
61
+ processCapitalized?: boolean; // default: true for 'de', false for every other language
62
+ breakUrls?: boolean; // default true (since v0.7.1)
63
+ exceptions?: ExceptionDictionary;
64
+ }
65
+ ```
66
+
67
+ **Capitalised words.** A capitalised word that does not start a sentence is
68
+ taken for a proper noun and left whole. German (`de`) is the exception: every
69
+ noun is capitalised there, so capitalised words are hyphenated by default
70
+ (since v0.7.1), proper names included. An explicit `processCapitalized` always
71
+ wins here; `compose()` and `compile()` in the higher packages do not pass it.
72
+ Never hyphenated: a word in capitals (no lower-case letter and at least two
73
+ upper-case letters, in any script, with or without punctuation: `NATO`,
74
+ `(NATO)`, `GRÖSSE`), a word that contains a digit, and an e-mail address (an
75
+ `@` between letters or digits).
76
+
77
+ **URLs** (since v0.7.1). A URL is never hyphenated. It gets break points that
78
+ take no hyphen instead:
79
+
80
+ - after `/`, `?`, `&`, `=`, `#`, `_`, `-` (the last one of a run);
81
+ - before a `.` that is followed by a letter or digit;
82
+ - never inside `://`, and never leaving fewer than two characters on a side.
83
+
84
+ Detected as a URL: `http://…`, `https://…`, `ftp://…`, `www.name.tld…`, and a
85
+ bare host followed by a slash (`example.com/docs`). A bare host must be in
86
+ lower case and its top-level domain must be one of
87
+ `com org net edu gov info io dev app eu de uk fr es nl ch ca au jp se dk fi cz br cn`.
88
+ Domains that are also common file extensions or abbreviations are left out so
89
+ that `Node.js/Express` or `README.md/CHANGELOG.md` are not taken for URLs; write
90
+ the scheme or `www.` for other domains. Not detected: a bare host without a
91
+ slash, e-mail addresses, file paths. Surrounding punctuation, as in
92
+ `(https://example.com/a).`, stays attached and gets no break.
93
+
94
+ ```ts
95
+ hyphenateWord('https://example.com/docs/index.html', opts);
96
+ // { fragments: ['https://', 'example', '.com/', 'docs/', 'index', '.html'],
97
+ // hyphenable: false, hasSoftHyphen: false, … }
98
+ ```
99
+
100
+ `hyphenable: false` with more than one fragment means "break here, add no
101
+ hyphen". `buildNodeSequence` then puts a zero-width, unflagged penalty of 200
102
+ between the fragments (a hyphenation point is a flagged penalty of 50 with the
103
+ width of a hyphen), and `composeParagraph` keeps the fragments in one word.
104
+ `composeParagraph` applies that to any unflagged penalty directly after a box,
105
+ whatever its value: when the line does not break there, the next box continues
106
+ the same word. A `HyphenatedWord` built by hand with several fragments needs
107
+ `hyphenable: true` to get hyphens.
108
+
109
+ Fragments are measured one by one. Letter-spacing is not added between two
110
+ fragments and kerning is not applied across them; this holds for hyphenation
111
+ points and URL break points alike.
112
+ `breakUrls: false` returns a URL as a single fragment, as before v0.7.1.
113
+
114
+ ### Test utilities
115
+
116
+ ```ts
117
+ import { mockMeasure, mockSpace, mockMetrics } from '@paragraf/linebreak';
118
+
119
+ const measurer = {
120
+ measure: mockMeasure,
121
+ space: mockSpace,
122
+ metrics: mockMetrics,
123
+ registry: new Map(),
124
+ };
125
+ ```
126
+
127
+ ## Browser safety
128
+
129
+ This package has zero Node.js dependencies. It can be imported in
130
+ any bundler or browser environment without polyfills.
@@ -0,0 +1,92 @@
1
+ import { BreakpointNode, Paragraph, Language, Font, SpanSegment, Measurer, Node, AlignmentMode, GetFontMetrics, ComposedParagraph, MeasureText, GlueSpaceFn } from '@paragraf/types';
2
+
3
+ interface BreakpointResult {
4
+ node: BreakpointNode;
5
+ usedEmergency: boolean;
6
+ /**
7
+ * True when the paragraph could not be set within tolerance and the
8
+ * fallback pass produced the breaks. Lines may then be looser than the
9
+ * tolerance allows, and some may be marked `overfull`.
10
+ * @since v0.7
11
+ */
12
+ usedFallback: boolean;
13
+ }
14
+ declare const computeBreakpoints: (paragraph: Paragraph) => BreakpointResult;
15
+
16
+ interface LineBreak {
17
+ position: number;
18
+ ratio: number;
19
+ flagged: boolean;
20
+ line: number;
21
+ /** Present (and true) only when the line cannot fit the measure. @since v0.7 */
22
+ overfull?: boolean;
23
+ }
24
+ declare const traceback: (finalNode: BreakpointNode) => LineBreak[];
25
+
26
+ /** Per-document hyphenation override dictionary (mirrors TeX `\hyphenation{…}`).
27
+ * Keys are words (case-insensitive). Values:
28
+ * - `string[]` — explicit break fragments (e.g. `{ 'present': ['pre', 'sent'] }`).
29
+ * `minLeft`/`minRight` boundaries are still enforced.
30
+ * - `false` — never hyphenate this word, overriding any pattern output.
31
+ */
32
+ type ExceptionDictionary = Record<string, string[] | false>;
33
+ interface HyphenateOptions {
34
+ minWordLength: number;
35
+ fontSize: number;
36
+ language: Language;
37
+ preserveSoftHyphens?: boolean;
38
+ minLeft?: number;
39
+ minRight?: number;
40
+ /**
41
+ * Whether capitalised words that do not start a sentence are hyphenated.
42
+ * - `false` — skip them (proper-noun heuristic). Default for every language
43
+ * except German.
44
+ * - `true` — hyphenate all words regardless of capitalisation. Default for
45
+ * German (`de`), where every noun is capitalised.
46
+ * An explicit value always wins over the language default.
47
+ */
48
+ processCapitalized?: boolean;
49
+ /**
50
+ * Whether a URL-like token gets break points (default `true`). The breaks
51
+ * insert no hyphen: after `/ ? & = # _ -` and before `.`, never inside
52
+ * `://`. Set `false` to keep a URL in one piece, as before v0.7.1.
53
+ * @since v0.7.1
54
+ */
55
+ breakUrls?: boolean;
56
+ /** Per-document exception dictionary checked before pattern-based hyphenation. */
57
+ exceptions?: ExceptionDictionary;
58
+ }
59
+ interface HyphenatedWord {
60
+ original: string;
61
+ /** The word split at its break points; one fragment when there are none. */
62
+ fragments: string[];
63
+ /**
64
+ * True when a hyphen is added at a break between fragments. False with more
65
+ * than one fragment means the breaks take no hyphen: that is how a URL is
66
+ * returned (since v0.7.1), and `buildNodeSequence` then puts a plain
67
+ * zero-width penalty between the fragments instead of a hyphen penalty.
68
+ */
69
+ hyphenable: boolean;
70
+ hasSoftHyphen: boolean;
71
+ }
72
+ declare const DEFAULT_HYPHENATE_OPTIONS: HyphenateOptions;
73
+ declare const deriveMinLeft: (fontSize: number) => number;
74
+ declare const deriveMinRight: (fontSize: number) => number;
75
+ declare const loadHyphenator: (language: Language) => Promise<void>;
76
+ declare const loadLanguages: (languages: Language[]) => Promise<void>;
77
+ declare const hyphenateWord: (word: string, opts?: HyphenateOptions, isFirstWord?: boolean, preserveSoftHyphens?: boolean) => HyphenatedWord;
78
+ declare const hyphenateParagraph: (text: string, opts?: HyphenateOptions) => HyphenatedWord[];
79
+
80
+ interface HyphenatedWordWithFont extends HyphenatedWord {
81
+ font: Font;
82
+ segments?: SpanSegment[][];
83
+ }
84
+ declare const buildNodeSequence: (words: HyphenatedWordWithFont[], measurer: Measurer, firstLineIndent?: number) => Node[];
85
+
86
+ declare const composeParagraph: (nodes: Node[], breaks: LineBreak[], alignment?: AlignmentMode, justifyLastLine?: boolean, lineWidth?: number, lineWidths?: number[], getMetrics?: GetFontMetrics, direction?: "ltr" | "rtl", leftSkip?: number, rightSkip?: number, kashida?: boolean, maxGlyphExpansion?: number) => ComposedParagraph;
87
+
88
+ declare const mockMeasure: MeasureText;
89
+ declare const mockSpace: GlueSpaceFn;
90
+ declare const mockMetrics: GetFontMetrics;
91
+
92
+ export { type BreakpointResult, DEFAULT_HYPHENATE_OPTIONS, type ExceptionDictionary, type HyphenateOptions, type HyphenatedWord, type HyphenatedWordWithFont, type LineBreak, buildNodeSequence, composeParagraph, computeBreakpoints, deriveMinLeft, deriveMinRight, hyphenateParagraph, hyphenateWord, loadHyphenator, loadLanguages, mockMeasure, mockMetrics, mockSpace, traceback };
package/dist/index.js ADDED
@@ -0,0 +1,923 @@
1
+ // src/linebreak.ts
2
+ import {
3
+ DOUBLE_HYPHEN_PENALTY,
4
+ isForced,
5
+ isProhibited
6
+ } from "@paragraf/types";
7
+ var buildPrefixSums = (nodes) => {
8
+ const len = nodes.length + 1;
9
+ const widths = new Array(len).fill(0);
10
+ const stretches = new Array(len).fill(0);
11
+ const shrinks = new Array(len).fill(0);
12
+ for (let i = 0; i < nodes.length; i++) {
13
+ const node = nodes[i];
14
+ widths[i + 1] = widths[i];
15
+ stretches[i + 1] = stretches[i];
16
+ shrinks[i + 1] = shrinks[i];
17
+ if (node.type === "box") {
18
+ widths[i + 1] += node.width;
19
+ } else if (node.type === "glue") {
20
+ widths[i + 1] += node.width;
21
+ stretches[i + 1] += node.stretch;
22
+ shrinks[i + 1] += node.shrink;
23
+ }
24
+ }
25
+ return { widths, stretches, shrinks };
26
+ };
27
+ var isFeasible = (ratio, tolerance) => ratio >= -1 && ratio <= tolerance;
28
+ var computeBadness = (ratio) => Math.min(1e4, Math.round(100 * Math.pow(Math.abs(ratio), 3)));
29
+ var fitnessClassOf = (ratio) => {
30
+ if (ratio < -0.5) return 0;
31
+ if (ratio <= 0.5) return 1;
32
+ if (ratio <= 1) return 2;
33
+ return 3;
34
+ };
35
+ var computeDemerits = (badness, penalty, prevFlagged, currFlagged) => {
36
+ let demerits;
37
+ if (penalty >= 0) {
38
+ demerits = Math.pow(1 + badness + penalty, 2);
39
+ } else if (!isForced(penalty)) {
40
+ demerits = Math.pow(1 + badness, 2) - Math.pow(penalty, 2);
41
+ } else {
42
+ demerits = Math.pow(1 + badness, 2);
43
+ }
44
+ if (prevFlagged && currFlagged) demerits += DOUBLE_HYPHEN_PENALTY;
45
+ return demerits;
46
+ };
47
+ var isValidBreak = (nodes, index) => {
48
+ const node = nodes[index];
49
+ if (node.type === "penalty") return !isProhibited(node.penalty);
50
+ if (node.type === "glue") {
51
+ if (index > 0 && nodes[index - 1].type === "box") return true;
52
+ }
53
+ return false;
54
+ };
55
+ var computeRatio = (lineWidth, penaltyWidth, sumWidth, sumStretch, sumShrink, emergencyStretch = 0) => {
56
+ const target = lineWidth - sumWidth - penaltyWidth;
57
+ if (target > 0) {
58
+ const totalStretch = sumStretch + emergencyStretch;
59
+ return totalStretch > 0 ? target / totalStretch : Infinity;
60
+ }
61
+ if (target < 0) return sumShrink > 0 ? target / sumShrink : -Infinity;
62
+ return 0;
63
+ };
64
+ var lineStartAfter = (nodes, breakPosition, to) => {
65
+ if (breakPosition === 0) return 0;
66
+ let start = breakPosition + 1;
67
+ while (start < to) {
68
+ const node = nodes[start];
69
+ if (node.type === "box") break;
70
+ if (node.type === "penalty" && isForced(node.penalty)) break;
71
+ start++;
72
+ }
73
+ return Math.min(start, to);
74
+ };
75
+ var buildLineStarts = (nodes) => {
76
+ const starts = new Array(nodes.length + 1);
77
+ let next = nodes.length;
78
+ starts[nodes.length] = next;
79
+ for (let i = nodes.length - 1; i >= 0; i--) {
80
+ starts[i] = next;
81
+ const node = nodes[i];
82
+ if (node.type === "box" || node.type === "penalty" && isForced(node.penalty)) {
83
+ next = i;
84
+ }
85
+ }
86
+ starts[0] = 0;
87
+ return starts;
88
+ };
89
+ var countContentBoxes = (nodes, from, to) => {
90
+ let count = 0;
91
+ const start = lineStartAfter(nodes, from, to);
92
+ for (let i = start; i <= to; i++) {
93
+ const node = nodes[i];
94
+ if (node.type === "box" && node.content !== "") count++;
95
+ }
96
+ return count;
97
+ };
98
+ var forwardPass = (nodes, lineWidth, tolerance, sums, lineStarts, emergencyStretch = 0, consecutiveHyphenLimit = 0, runtPenalty = 0, singleLinePenalty = 0, lineWidths = [], adjDemerits = 0, fallback = false) => {
99
+ const startNode = {
100
+ position: 0,
101
+ line: 0,
102
+ totalDemerits: 0,
103
+ ratio: 0,
104
+ previous: null,
105
+ flagged: false,
106
+ consecutiveHyphens: 0,
107
+ fitnessClass: 1
108
+ // initial node is treated as normal (ratio 0)
109
+ };
110
+ let active = [startNode];
111
+ for (let i = 0; i < nodes.length; i++) {
112
+ const node = nodes[i];
113
+ if (!isValidBreak(nodes, i)) continue;
114
+ const penaltyWidth = node.type === "penalty" ? node.width : 0;
115
+ const penaltyValue = node.type === "penalty" ? node.penalty : 0;
116
+ const isFlagged = node.type === "penalty" ? node.flagged : false;
117
+ const isForcedBreak = isForced(penaltyValue);
118
+ const nextActive = [];
119
+ const bestAtI = /* @__PURE__ */ new Map();
120
+ for (const a of active) {
121
+ const effectiveLineWidth = lineWidths[a.line] ?? lineWidth;
122
+ const start = Math.min(lineStarts[a.position], i);
123
+ const sumWidth = sums.widths[i] - sums.widths[start];
124
+ const sumStretch = sums.stretches[i] - sums.stretches[start];
125
+ const sumShrink = sums.shrinks[i] - sums.shrinks[start];
126
+ const ratio = computeRatio(
127
+ effectiveLineWidth,
128
+ penaltyWidth,
129
+ sumWidth,
130
+ sumStretch,
131
+ sumShrink,
132
+ emergencyStretch
133
+ );
134
+ if (ratio >= -1 && !isForcedBreak) nextActive.push(a);
135
+ if (fallback ? ratio >= -1 : isFeasible(ratio, tolerance)) {
136
+ const consecutiveHyphens = isFlagged ? a.consecutiveHyphens + 1 : 0;
137
+ if (!fallback && consecutiveHyphenLimit > 0 && consecutiveHyphens > consecutiveHyphenLimit) {
138
+ continue;
139
+ }
140
+ const badness = computeBadness(ratio);
141
+ let demerits = computeDemerits(
142
+ badness,
143
+ penaltyValue,
144
+ a.flagged,
145
+ isFlagged
146
+ );
147
+ if (adjDemerits > 0) {
148
+ const fc = fitnessClassOf(ratio);
149
+ if (Math.abs(fc - a.fitnessClass) > 1) demerits += adjDemerits;
150
+ }
151
+ if (isForcedBreak && runtPenalty > 0) {
152
+ const lastLineBoxes = countContentBoxes(nodes, a.position, i);
153
+ if (lastLineBoxes === 1) demerits += runtPenalty;
154
+ }
155
+ if (isForcedBreak && singleLinePenalty > 0 && a.previous === null) {
156
+ demerits += singleLinePenalty;
157
+ }
158
+ const candidate = {
159
+ position: i,
160
+ line: a.line + 1,
161
+ totalDemerits: a.totalDemerits + demerits,
162
+ // A line with nothing to stretch has an infinite ratio; it is set
163
+ // at its natural width, so record 0 (only reachable in fallback).
164
+ ratio: Number.isFinite(ratio) ? ratio : 0,
165
+ previous: a,
166
+ flagged: isFlagged,
167
+ consecutiveHyphens,
168
+ fitnessClass: fitnessClassOf(ratio)
169
+ };
170
+ const lineAndClass = adjDemerits > 0 ? candidate.line * 4 + candidate.fitnessClass : candidate.line * 4;
171
+ const key = consecutiveHyphenLimit > 0 ? lineAndClass * (consecutiveHyphenLimit + 1) + Math.min(consecutiveHyphens, consecutiveHyphenLimit) : lineAndClass;
172
+ const existing = bestAtI.get(key);
173
+ if (!existing || candidate.totalDemerits < existing.totalDemerits) {
174
+ bestAtI.set(key, candidate);
175
+ }
176
+ }
177
+ }
178
+ for (const key of [...bestAtI.keys()].sort((x, y) => x - y)) {
179
+ nextActive.push(bestAtI.get(key));
180
+ }
181
+ if (fallback && nextActive.length === 0 && active.length > 0) {
182
+ let a = active[0];
183
+ for (const c of active) {
184
+ if (c.position > a.position || c.position === a.position && c.totalDemerits < a.totalDemerits) {
185
+ a = c;
186
+ }
187
+ }
188
+ nextActive.push({
189
+ position: i,
190
+ line: a.line + 1,
191
+ totalDemerits: a.totalDemerits + computeDemerits(1e4, penaltyValue, a.flagged, isFlagged),
192
+ ratio: -1,
193
+ previous: a,
194
+ flagged: isFlagged,
195
+ consecutiveHyphens: isFlagged ? a.consecutiveHyphens + 1 : 0,
196
+ fitnessClass: 0,
197
+ overfull: true
198
+ });
199
+ }
200
+ active = nextActive;
201
+ }
202
+ return active;
203
+ };
204
+ var computeBreakpoints = (paragraph) => {
205
+ const {
206
+ nodes,
207
+ lineWidth,
208
+ lineWidths = [],
209
+ tolerance,
210
+ emergencyStretch = 0,
211
+ consecutiveHyphenLimit = 0,
212
+ looseness = 0
213
+ } = paragraph;
214
+ const runtPenalty = paragraph.runtPenalty ?? 0;
215
+ const singleLinePenalty = paragraph.singleLinePenalty ?? 0;
216
+ const adjDemerits = paragraph.adjDemerits ?? 0;
217
+ const onInfeasible = paragraph.onInfeasible ?? "overfull";
218
+ const sums = buildPrefixSums(nodes);
219
+ const lineStarts = buildLineStarts(nodes);
220
+ let active = forwardPass(
221
+ nodes,
222
+ lineWidth,
223
+ tolerance,
224
+ sums,
225
+ lineStarts,
226
+ 0,
227
+ consecutiveHyphenLimit,
228
+ runtPenalty,
229
+ singleLinePenalty,
230
+ lineWidths,
231
+ adjDemerits
232
+ );
233
+ let usedEmergency = false;
234
+ let usedFallback = false;
235
+ if (active.length === 0) {
236
+ if (emergencyStretch > 0) {
237
+ active = forwardPass(
238
+ nodes,
239
+ lineWidth,
240
+ tolerance,
241
+ sums,
242
+ lineStarts,
243
+ emergencyStretch,
244
+ consecutiveHyphenLimit,
245
+ runtPenalty,
246
+ singleLinePenalty,
247
+ lineWidths,
248
+ adjDemerits
249
+ );
250
+ usedEmergency = true;
251
+ }
252
+ if (active.length === 0) {
253
+ if (onInfeasible === "throw") {
254
+ throw new Error(
255
+ "Paragraph could not be set within tolerance. Consider increasing tolerance or adding emergencyStretch."
256
+ );
257
+ }
258
+ active = forwardPass(
259
+ nodes,
260
+ lineWidth,
261
+ tolerance,
262
+ sums,
263
+ lineStarts,
264
+ emergencyStretch,
265
+ consecutiveHyphenLimit,
266
+ runtPenalty,
267
+ singleLinePenalty,
268
+ lineWidths,
269
+ adjDemerits,
270
+ true
271
+ );
272
+ usedFallback = true;
273
+ }
274
+ }
275
+ const optimal = active.reduce(
276
+ (prev, curr) => curr.totalDemerits < prev.totalDemerits ? curr : prev
277
+ );
278
+ if (looseness === 0 || usedFallback) {
279
+ return { node: optimal, usedEmergency, usedFallback };
280
+ }
281
+ const targetLine = optimal.line + looseness;
282
+ const candidates = active.filter((n) => n.line === targetLine);
283
+ if (candidates.length === 0) return { node: optimal, usedEmergency, usedFallback };
284
+ return {
285
+ node: candidates.reduce(
286
+ (prev, curr) => curr.totalDemerits < prev.totalDemerits ? curr : prev
287
+ ),
288
+ usedEmergency,
289
+ usedFallback
290
+ };
291
+ };
292
+
293
+ // src/traceback.ts
294
+ var traceback = (finalNode) => {
295
+ const breaks = [];
296
+ let current = finalNode;
297
+ while (current !== null && current.previous !== null) {
298
+ breaks.push({
299
+ position: current.position,
300
+ ratio: current.ratio,
301
+ flagged: current.flagged,
302
+ line: current.line,
303
+ ...current.overfull ? { overfull: true } : {}
304
+ });
305
+ current = current.previous;
306
+ }
307
+ return breaks.reverse();
308
+ };
309
+
310
+ // src/nodes.ts
311
+ import {
312
+ FORCED_BREAK,
313
+ HYPHEN_PENALTY,
314
+ SOFT_HYPHEN_PENALTY
315
+ } from "@paragraf/types";
316
+ var buildBox = (content, font, measurer, verticalOffset) => ({
317
+ type: "box",
318
+ content,
319
+ font,
320
+ width: measurer.measure(content, font),
321
+ verticalOffset
322
+ });
323
+ var buildIndentBox = (width, font) => ({
324
+ type: "box",
325
+ content: "",
326
+ font,
327
+ width
328
+ });
329
+ var buildGlue = (font, measurer) => {
330
+ const { width, stretch, shrink } = measurer.space(font);
331
+ return { type: "glue", kind: "word", width, stretch, shrink, font };
332
+ };
333
+ var buildHyphenPenalty = (font, measurer, penaltyValue = HYPHEN_PENALTY) => ({
334
+ type: "penalty",
335
+ width: measurer.measure("-", font),
336
+ penalty: penaltyValue,
337
+ flagged: true
338
+ });
339
+ var URL_BREAK_PENALTY = 200;
340
+ var buildPlainBreakPenalty = () => ({
341
+ type: "penalty",
342
+ width: 0,
343
+ penalty: URL_BREAK_PENALTY,
344
+ flagged: false
345
+ });
346
+ var buildTermination = () => [
347
+ {
348
+ type: "glue",
349
+ kind: "termination",
350
+ // explicit
351
+ width: 0,
352
+ stretch: Infinity,
353
+ shrink: 0
354
+ },
355
+ {
356
+ type: "penalty",
357
+ width: 0,
358
+ penalty: FORCED_BREAK,
359
+ flagged: false
360
+ }
361
+ ];
362
+ var glueFont = (word) => {
363
+ if (word.segments && word.segments.length > 0) {
364
+ const lastFrag = word.segments[word.segments.length - 1];
365
+ if (lastFrag.length > 0) return lastFrag[lastFrag.length - 1].font;
366
+ }
367
+ return word.font;
368
+ };
369
+ var buildNodeSequence = (words, measurer, firstLineIndent = 0) => {
370
+ const nodes = [];
371
+ if (firstLineIndent > 0) {
372
+ const firstFont = words[0]?.font;
373
+ if (firstFont) nodes.push(buildIndentBox(firstLineIndent, firstFont));
374
+ }
375
+ words.forEach((word, index) => {
376
+ const { fragments, font, hasSoftHyphen, segments } = word;
377
+ const penaltyValue = hasSoftHyphen ? SOFT_HYPHEN_PENALTY : HYPHEN_PENALTY;
378
+ const plainBreaks = !word.hyphenable && !hasSoftHyphen;
379
+ const breakPenalty = (penaltyFont) => plainBreaks ? buildPlainBreakPenalty() : buildHyphenPenalty(penaltyFont, measurer, penaltyValue);
380
+ if (segments) {
381
+ segments.forEach((fragSegs, fi) => {
382
+ fragSegs.forEach((seg) => {
383
+ nodes.push(
384
+ buildBox(seg.text, seg.font, measurer, seg.verticalOffset)
385
+ );
386
+ });
387
+ if (fi < segments.length - 1) {
388
+ const lastSeg = fragSegs[fragSegs.length - 1];
389
+ nodes.push(breakPenalty(lastSeg.font));
390
+ }
391
+ });
392
+ } else if (fragments.length === 1) {
393
+ nodes.push(buildBox(fragments[0], font, measurer));
394
+ } else {
395
+ fragments.forEach((fragment, fi) => {
396
+ nodes.push(buildBox(fragment, font, measurer));
397
+ if (fi < fragments.length - 1) {
398
+ nodes.push(breakPenalty(font));
399
+ }
400
+ });
401
+ }
402
+ if (index < words.length - 1) {
403
+ nodes.push(buildGlue(glueFont(word), measurer));
404
+ }
405
+ });
406
+ nodes.push(...buildTermination());
407
+ return nodes;
408
+ };
409
+
410
+ // src/compose.ts
411
+ var resolveGlueWidth = (glue, ratio, alignment) => {
412
+ if (alignment !== "justified") return glue.width;
413
+ if (ratio >= 0) return glue.width + ratio * glue.stretch;
414
+ return glue.width + ratio * glue.shrink;
415
+ };
416
+ var computeLastLineRatio = (nodes, from, to, lineWidth) => {
417
+ let contentWidth = 0;
418
+ let totalStretch = 0;
419
+ let totalShrink = 0;
420
+ let glueCount = 0;
421
+ const start = lineStartAfter(nodes, from, to);
422
+ for (let i = start; i <= to; i++) {
423
+ const node = nodes[i];
424
+ if (node.type === "box") {
425
+ contentWidth += node.width;
426
+ } else if (node.type === "glue" && node.kind === "word") {
427
+ contentWidth += node.width;
428
+ totalStretch += node.stretch;
429
+ totalShrink += node.shrink;
430
+ glueCount++;
431
+ }
432
+ }
433
+ if (glueCount === 0) return 0;
434
+ const remaining = lineWidth - contentWidth;
435
+ if (remaining > 0) return totalStretch > 0 ? remaining / totalStretch : 0;
436
+ if (remaining < 0) return totalShrink > 0 ? remaining / totalShrink : 0;
437
+ return 0;
438
+ };
439
+ var extractLine = (nodes, from, to, ratio, flagged, alignment, isLastLine, justifyLastLine, lineWidth, getMetrics, overfull = false) => {
440
+ const words = [];
441
+ const fonts = [];
442
+ const wordRuns = [];
443
+ let wordSpacing = 0;
444
+ let spacingResolved = false;
445
+ let lastWasHyphenPenalty = false;
446
+ let lastWasBox = false;
447
+ const effectiveRatio = isLastLine && justifyLastLine && !overfull ? computeLastLineRatio(nodes, from, to, lineWidth) : ratio;
448
+ const start = lineStartAfter(nodes, from, to);
449
+ let boxWidthSum = 0;
450
+ let wordGlueCount = 0;
451
+ for (let i = start; i <= to; i++) {
452
+ const node = nodes[i];
453
+ if (node.type === "box") {
454
+ boxWidthSum += node.width;
455
+ if ((lastWasHyphenPenalty || lastWasBox) && words.length > 0) {
456
+ words[words.length - 1] += node.content;
457
+ wordRuns[wordRuns.length - 1].push({
458
+ text: node.content,
459
+ font: node.font,
460
+ verticalOffset: node.verticalOffset
461
+ });
462
+ } else {
463
+ words.push(node.content);
464
+ fonts.push(node.font);
465
+ wordRuns.push([
466
+ {
467
+ text: node.content,
468
+ font: node.font,
469
+ verticalOffset: node.verticalOffset
470
+ }
471
+ ]);
472
+ }
473
+ lastWasHyphenPenalty = false;
474
+ lastWasBox = true;
475
+ } else if (node.type === "penalty" && node.flagged) {
476
+ lastWasHyphenPenalty = i < to;
477
+ lastWasBox = false;
478
+ } else if (node.type === "penalty" && lastWasBox) {
479
+ lastWasHyphenPenalty = i < to;
480
+ lastWasBox = false;
481
+ } else {
482
+ lastWasHyphenPenalty = false;
483
+ lastWasBox = false;
484
+ }
485
+ if (node.type === "glue" && node.kind === "word") {
486
+ wordGlueCount++;
487
+ if (!spacingResolved) {
488
+ wordSpacing = resolveGlueWidth(node, effectiveRatio, alignment);
489
+ spacingResolved = true;
490
+ }
491
+ }
492
+ }
493
+ if (flagged && words.length > 0) {
494
+ words[words.length - 1] += "-";
495
+ const lastRuns = wordRuns[wordRuns.length - 1];
496
+ if (lastRuns.length > 0) {
497
+ const last = lastRuns[lastRuns.length - 1];
498
+ lastRuns[lastRuns.length - 1] = { ...last, text: last.text + "-" };
499
+ }
500
+ }
501
+ const breakNode = nodes[to];
502
+ const breakIsWordGlue = breakNode?.type === "glue" && breakNode.kind === "word";
503
+ const visibleGlues = wordGlueCount - (breakIsWordGlue ? 1 : 0);
504
+ const penaltyWidth = breakNode?.type === "penalty" && breakNode.flagged ? breakNode.width : 0;
505
+ if (alignment === "justified" && (!isLastLine || justifyLastLine) && !overfull) {
506
+ if (visibleGlues > 0) {
507
+ wordSpacing = Math.max(
508
+ 0,
509
+ (lineWidth - boxWidthSum - penaltyWidth) / visibleGlues
510
+ );
511
+ }
512
+ }
513
+ let lineHeight = 0;
514
+ let baseline = 0;
515
+ if (getMetrics) {
516
+ const seen = /* @__PURE__ */ new Set();
517
+ for (const runs of wordRuns) {
518
+ for (const seg of runs) {
519
+ if (!seen.has(seg.font)) {
520
+ seen.add(seg.font);
521
+ const m = getMetrics(seg.font);
522
+ if (m) {
523
+ const lh = m.ascender - m.descender + m.lineGap;
524
+ if (lh > lineHeight) lineHeight = lh;
525
+ if (m.ascender > baseline) baseline = m.ascender;
526
+ }
527
+ }
528
+ }
529
+ }
530
+ }
531
+ return {
532
+ words,
533
+ fonts,
534
+ wordRuns,
535
+ wordSpacing,
536
+ hyphenated: flagged,
537
+ ratio: alignment === "justified" ? effectiveRatio : 0,
538
+ alignment,
539
+ isWidow: false,
540
+ // @deprecated — use isRunt
541
+ isRunt: false,
542
+ // set by composeParagraph post-pass
543
+ lineWidth,
544
+ lineHeight,
545
+ baseline,
546
+ ...overfull ? {
547
+ overfull: true,
548
+ overflow: Math.max(
549
+ 0,
550
+ boxWidthSum + penaltyWidth + visibleGlues * wordSpacing - lineWidth
551
+ )
552
+ } : {}
553
+ };
554
+ };
555
+ var composeParagraph = (nodes, breaks, alignment = "justified", justifyLastLine = false, lineWidth = 0, lineWidths = [], getMetrics, direction = "ltr", leftSkip = 0, rightSkip = 0, kashida = false, maxGlyphExpansion = 0) => {
556
+ if (justifyLastLine && lineWidth === 0) {
557
+ throw new Error(
558
+ "lineWidth must be provided when justifyLastLine=true. Pass the same lineWidth used for composition."
559
+ );
560
+ }
561
+ const lines = [];
562
+ let previousPosition = 0;
563
+ for (let bi = 0; bi < breaks.length; bi++) {
564
+ const lineBreak = breaks[bi];
565
+ const isLastLine = bi === breaks.length - 1;
566
+ const effectiveWidth = lineWidths[bi] ?? lineWidth;
567
+ const line = extractLine(
568
+ nodes,
569
+ previousPosition,
570
+ lineBreak.position,
571
+ lineBreak.ratio,
572
+ lineBreak.flagged,
573
+ alignment,
574
+ isLastLine,
575
+ justifyLastLine,
576
+ effectiveWidth,
577
+ getMetrics,
578
+ lineBreak.overfull === true
579
+ );
580
+ if (line.words.length > 0) {
581
+ const useKashida = kashida && direction === "rtl" && line.alignment === "justified" && !isLastLine;
582
+ const glyphExpansion = maxGlyphExpansion > 0 ? Math.max(
583
+ -maxGlyphExpansion,
584
+ Math.min(maxGlyphExpansion, lineBreak.ratio * maxGlyphExpansion)
585
+ ) : 0;
586
+ lines.push({
587
+ ...line,
588
+ direction,
589
+ leftSkip,
590
+ rightSkip,
591
+ kashidaSpacing: useKashida ? line.wordSpacing : 0,
592
+ wordSpacing: useKashida ? 0 : line.wordSpacing,
593
+ glyphExpansion
594
+ });
595
+ }
596
+ previousPosition = lineBreak.position;
597
+ }
598
+ if (lines.length > 1) {
599
+ const last = lines[lines.length - 1];
600
+ const contentWords = last.words.filter((w) => w !== "");
601
+ if (contentWords.length === 1) {
602
+ lines[lines.length - 1] = { ...last, isWidow: true, isRunt: true };
603
+ }
604
+ }
605
+ return lines;
606
+ };
607
+
608
+ // src/hyphenate.ts
609
+ import createHyphenator from "hyphen";
610
+ var DEFAULT_HYPHENATE_OPTIONS = {
611
+ minWordLength: 5,
612
+ fontSize: 12,
613
+ language: "en-us",
614
+ preserveSoftHyphens: true
615
+ };
616
+ var deriveMinLeft = (fontSize) => Math.max(2, Math.round(fontSize / 6));
617
+ var deriveMinRight = (fontSize) => Math.max(3, Math.round(fontSize / 6) + 1);
618
+ var PATTERN_LOADERS = {
619
+ "en-us": () => import("hyphen/patterns/en-us.js"),
620
+ "en-gb": () => import("hyphen/patterns/en-gb.js"),
621
+ // de-1996: reformed German orthography (post-1996 spelling reform)
622
+ de: () => import("hyphen/patterns/de-1996.js"),
623
+ fr: () => import("hyphen/patterns/fr.js"),
624
+ tr: () => import("hyphen/patterns/tr.js"),
625
+ nl: () => import("hyphen/patterns/nl.js"),
626
+ pl: () => import("hyphen/patterns/pl.js"),
627
+ it: () => import("hyphen/patterns/it.js"),
628
+ es: () => import("hyphen/patterns/es.js"),
629
+ sv: () => import("hyphen/patterns/sv.js"),
630
+ // no: Bokmål + Nynorsk combined patterns (covers both official written standards)
631
+ no: () => import("hyphen/patterns/no.js"),
632
+ da: () => import("hyphen/patterns/da.js"),
633
+ fi: () => import("hyphen/patterns/fi.js"),
634
+ hu: () => import("hyphen/patterns/hu.js"),
635
+ cs: () => import("hyphen/patterns/cs.js"),
636
+ sk: () => import("hyphen/patterns/sk.js"),
637
+ ro: () => import("hyphen/patterns/ro.js"),
638
+ hr: () => import("hyphen/patterns/hr.js"),
639
+ sl: () => import("hyphen/patterns/sl.js"),
640
+ lt: () => import("hyphen/patterns/lt.js"),
641
+ lv: () => import("hyphen/patterns/lv.js"),
642
+ et: () => import("hyphen/patterns/et.js")
643
+ };
644
+ var hyphenatorCache = /* @__PURE__ */ new Map();
645
+ var loadHyphenator = async (language) => {
646
+ if (hyphenatorCache.has(language)) return;
647
+ const loader = PATTERN_LOADERS[language];
648
+ if (!loader) throw new Error(`Unsupported language: ${language}`);
649
+ const patterns = await loader();
650
+ const hyphenator = createHyphenator(patterns.default ?? patterns, {
651
+ async: false
652
+ });
653
+ hyphenatorCache.set(language, hyphenator);
654
+ };
655
+ var loadLanguages = async (languages) => {
656
+ await Promise.all(languages.map(loadHyphenator));
657
+ };
658
+ var INPUT_SOFT_HYPHEN = "\xAD";
659
+ var extractSoftHyphenFragments = (word) => {
660
+ if (!word.includes(INPUT_SOFT_HYPHEN)) return null;
661
+ const fragments = word.split(INPUT_SOFT_HYPHEN);
662
+ if (fragments.some((f) => f.length === 0)) return null;
663
+ return fragments;
664
+ };
665
+ var capitalisesAllNouns = (language) => language === "de" || language.startsWith("de-");
666
+ var URL_LEADING = /^[(\[{<"'“‘«„]+/;
667
+ var URL_TRAILING_CHARS = new Set(`)]}>"'\u201D\u2019\xBB.,;:!?`);
668
+ var trailingPunctuationLength = (text) => {
669
+ let end = text.length;
670
+ while (end > 0 && URL_TRAILING_CHARS.has(text[end - 1])) end--;
671
+ return text.length - end;
672
+ };
673
+ var URL_WITH_SCHEME = /^(?:https?|ftp):\/\/\S/i;
674
+ var URL_WWW = /^www\.[^\s./]+\.\S/i;
675
+ var BARE_HOST_TLDS = /* @__PURE__ */ new Set([
676
+ "com",
677
+ "org",
678
+ "net",
679
+ "edu",
680
+ "gov",
681
+ "info",
682
+ "io",
683
+ "dev",
684
+ "app",
685
+ "eu",
686
+ "de",
687
+ "uk",
688
+ "fr",
689
+ "es",
690
+ "nl",
691
+ "ch",
692
+ "ca",
693
+ "au",
694
+ "jp",
695
+ "se",
696
+ "dk",
697
+ "fi",
698
+ "cz",
699
+ "br",
700
+ "cn"
701
+ ]);
702
+ var isHostLabel = (label) => {
703
+ if (label.length === 0 || label.length > 63) return false;
704
+ if (label.startsWith("-") || label.endsWith("-")) return false;
705
+ for (let i = 0; i < label.length; i++) {
706
+ const c = label.charCodeAt(i);
707
+ const lower = c >= 97 && c <= 122;
708
+ const digit = c >= 48 && c <= 57;
709
+ if (!lower && !digit && c !== 45) return false;
710
+ }
711
+ return true;
712
+ };
713
+ var isDigits = (text) => {
714
+ if (text.length === 0) return false;
715
+ for (let i = 0; i < text.length; i++) {
716
+ const c = text.charCodeAt(i);
717
+ if (c < 48 || c > 57) return false;
718
+ }
719
+ return true;
720
+ };
721
+ var isBareHostUrl = (text) => {
722
+ const slash = text.indexOf("/");
723
+ if (slash < 4 || slash > 260) return false;
724
+ let host = text.slice(0, slash);
725
+ const colon = host.indexOf(":");
726
+ if (colon >= 0) {
727
+ if (!isDigits(host.slice(colon + 1))) return false;
728
+ host = host.slice(0, colon);
729
+ }
730
+ const labels = host.split(".");
731
+ if (labels.length < 2) return false;
732
+ if (!labels.every(isHostLabel)) return false;
733
+ return BARE_HOST_TLDS.has(labels[labels.length - 1]);
734
+ };
735
+ var isUrlLike = (text) => URL_WITH_SCHEME.test(text) || URL_WWW.test(text) || isBareHostUrl(text);
736
+ var URL_BREAK_AFTER = /* @__PURE__ */ new Set(["/", "?", "&", "=", "#", "_", "-"]);
737
+ var URL_BREAK_BEFORE = ".";
738
+ var URL_MIN_SIDE = 2;
739
+ var isAsciiAlnum = (ch) => ch !== void 0 && /[A-Za-z0-9]/.test(ch);
740
+ var splitUrl = (word) => {
741
+ const lead = word.match(URL_LEADING)?.[0] ?? "";
742
+ const rest = word.slice(lead.length);
743
+ if (!isUrlLike(rest)) return null;
744
+ const trailLength = trailingPunctuationLength(rest);
745
+ const trail = rest.slice(rest.length - trailLength);
746
+ const core = rest.slice(0, rest.length - trailLength);
747
+ if (!isUrlLike(core)) return null;
748
+ const schemeEnd = core.indexOf("://");
749
+ const firstAllowed = Math.max(
750
+ URL_MIN_SIDE,
751
+ schemeEnd >= 0 ? schemeEnd + 3 : 0
752
+ );
753
+ const fragments = [];
754
+ let start = 0;
755
+ for (let p = firstAllowed; p <= core.length - URL_MIN_SIDE; p++) {
756
+ const prev = core[p - 1];
757
+ const next = core[p];
758
+ const afterSeparator = URL_BREAK_AFTER.has(prev) && !URL_BREAK_AFTER.has(next);
759
+ const beforeDot = next === URL_BREAK_BEFORE && prev !== URL_BREAK_BEFORE && isAsciiAlnum(core[p + 1]);
760
+ if (afterSeparator || beforeDot) {
761
+ fragments.push(core.slice(start, p));
762
+ start = p;
763
+ }
764
+ }
765
+ fragments.push(core.slice(start));
766
+ fragments[0] = lead + fragments[0];
767
+ fragments[fragments.length - 1] += trail;
768
+ return fragments;
769
+ };
770
+ var isInCapitals = (word) => {
771
+ if (/\p{Ll}/u.test(word)) return false;
772
+ const upper = word.match(/\p{Lu}/gu);
773
+ return upper !== null && upper.length >= 2;
774
+ };
775
+ var EMAIL_ADDRESS = /[\p{L}\p{N}]@[\p{L}\p{N}]/u;
776
+ var shouldSkip = (word, opts, isFirstWord) => {
777
+ const clean = word.replaceAll(INPUT_SOFT_HYPHEN, "");
778
+ if (clean.length < opts.minWordLength) return true;
779
+ if (/\d/.test(clean)) return true;
780
+ if (/^https?:\/\//.test(clean)) return true;
781
+ if (isInCapitals(clean)) return true;
782
+ if (EMAIL_ADDRESS.test(clean)) return true;
783
+ const processCapitalized = opts.processCapitalized ?? capitalisesAllNouns(opts.language);
784
+ if (!processCapitalized && !isFirstWord && /^[A-Z]/.test(clean)) {
785
+ const isSentenceStart = opts._prevWord !== void 0 && /[.!?]['"\)\]\}]*$/.test(opts._prevWord);
786
+ if (!isSentenceStart) return true;
787
+ }
788
+ return false;
789
+ };
790
+ var enforceMinBoundaries = (fragments, minLeft, minRight) => {
791
+ if (fragments.length <= 1) return fragments;
792
+ const result = [...fragments];
793
+ while (result.length > 1 && result[0].length < minLeft) {
794
+ result.splice(0, 2, result[0] + result[1]);
795
+ }
796
+ while (result.length > 1 && result[result.length - 1].length < minRight) {
797
+ const last = result.pop();
798
+ result[result.length - 1] = result[result.length - 1] + last;
799
+ }
800
+ return result;
801
+ };
802
+ var hyphenateWord = (word, opts = DEFAULT_HYPHENATE_OPTIONS, isFirstWord = false, preserveSoftHyphens = opts.preserveSoftHyphens ?? true) => {
803
+ if (opts.breakUrls !== false) {
804
+ const stripped = word.replaceAll(INPUT_SOFT_HYPHEN, "");
805
+ const urlFragments = splitUrl(stripped);
806
+ if (urlFragments) {
807
+ return {
808
+ original: stripped,
809
+ fragments: urlFragments,
810
+ hyphenable: false,
811
+ hasSoftHyphen: false
812
+ };
813
+ }
814
+ }
815
+ if (preserveSoftHyphens) {
816
+ const softFragments = extractSoftHyphenFragments(word);
817
+ if (softFragments) {
818
+ return {
819
+ original: word.replaceAll(INPUT_SOFT_HYPHEN, ""),
820
+ fragments: softFragments,
821
+ hyphenable: softFragments.length > 1,
822
+ hasSoftHyphen: true
823
+ };
824
+ }
825
+ }
826
+ const clean = word.replaceAll(INPUT_SOFT_HYPHEN, "");
827
+ if (shouldSkip(clean, opts, isFirstWord)) {
828
+ return {
829
+ original: clean,
830
+ fragments: [clean],
831
+ hyphenable: false,
832
+ hasSoftHyphen: false
833
+ };
834
+ }
835
+ const hyphenator = hyphenatorCache.get(opts.language);
836
+ if (!hyphenator) {
837
+ throw new Error(
838
+ `Hyphenator for "${opts.language}" not loaded. Call loadHyphenator("${opts.language}") before hyphenating.`
839
+ );
840
+ }
841
+ const minLeft = opts.minLeft ?? deriveMinLeft(opts.fontSize);
842
+ const minRight = opts.minRight ?? deriveMinRight(opts.fontSize);
843
+ if (opts.exceptions) {
844
+ const key = clean.toLowerCase();
845
+ const override = opts.exceptions[key];
846
+ if (override === false) {
847
+ return {
848
+ original: clean,
849
+ fragments: [clean],
850
+ hyphenable: false,
851
+ hasSoftHyphen: false
852
+ };
853
+ }
854
+ if (Array.isArray(override) && override.length > 1) {
855
+ const frags = enforceMinBoundaries(override, minLeft, minRight);
856
+ return {
857
+ original: clean,
858
+ fragments: frags,
859
+ hyphenable: frags.length > 1,
860
+ hasSoftHyphen: false
861
+ };
862
+ }
863
+ }
864
+ const hyphenated = hyphenator(clean);
865
+ const all = hyphenated.split(INPUT_SOFT_HYPHEN);
866
+ const fragments = enforceMinBoundaries(all, minLeft, minRight);
867
+ return {
868
+ original: clean,
869
+ fragments,
870
+ hyphenable: fragments.length > 1,
871
+ hasSoftHyphen: false
872
+ };
873
+ };
874
+ var hyphenateParagraph = (text, opts = DEFAULT_HYPHENATE_OPTIONS) => {
875
+ const words = text.trim().split(/\s+/);
876
+ return words.map((word, index) => {
877
+ const optsWithPrev = index > 0 ? { ...opts, _prevWord: words[index - 1] } : opts;
878
+ return hyphenateWord(
879
+ word,
880
+ optsWithPrev,
881
+ index === 0,
882
+ opts.preserveSoftHyphens ?? true
883
+ );
884
+ });
885
+ };
886
+
887
+ // src/testing.ts
888
+ var mockMeasure = (content, font) => {
889
+ const base = content.length * font.size * 0.6;
890
+ const spacing = (font.letterSpacing ?? 0) * Math.max(0, content.length - 1);
891
+ return base + spacing;
892
+ };
893
+ var mockSpace = (font) => {
894
+ const width = font.size * 0.25;
895
+ const stretch = width * 0.5;
896
+ const shrink = width * 0.3;
897
+ return { width, stretch, shrink };
898
+ };
899
+ var mockMetrics = (font) => ({
900
+ unitsPerEm: 1e3,
901
+ ascender: font.size * 0.8,
902
+ descender: -font.size * 0.2,
903
+ xHeight: font.size * 0.5,
904
+ capHeight: font.size * 0.7,
905
+ lineGap: 0,
906
+ baselineShift: font.variant === "superscript" ? font.size * 0.35 : font.variant === "subscript" ? -font.size * 0.15 : 0
907
+ });
908
+ export {
909
+ DEFAULT_HYPHENATE_OPTIONS,
910
+ buildNodeSequence,
911
+ composeParagraph,
912
+ computeBreakpoints,
913
+ deriveMinLeft,
914
+ deriveMinRight,
915
+ hyphenateParagraph,
916
+ hyphenateWord,
917
+ loadHyphenator,
918
+ loadLanguages,
919
+ mockMeasure,
920
+ mockMetrics,
921
+ mockSpace,
922
+ traceback
923
+ };
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@paragraf/linebreak",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.1",
4
+ "description": "Knuth-Plass line-breaking algorithm + hyphenation. Browser-safe, zero font dependencies.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/kadetr/paragraf.git",
9
+ "directory": "1a-linebreak"
10
+ },
11
+ "homepage": "https://github.com/kadetr/paragraf/tree/main/1a-linebreak#readme",
12
+ "keywords": [
13
+ "typography",
14
+ "typesetting",
15
+ "knuth-plass",
16
+ "line-breaking",
17
+ "hyphenation",
18
+ "paragraf"
19
+ ],
20
+ "type": "module",
21
+ "engines": {
22
+ "node": ">=22"
23
+ },
24
+ "files": [
25
+ "dist/",
26
+ "README.md"
27
+ ],
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ }
33
+ },
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "exports": {
37
+ ".": {
38
+ "types": "./dist/index.d.ts",
39
+ "default": "./dist/index.js"
40
+ }
41
+ }
42
+ },
43
+ "scripts": {
44
+ "build": "tsup",
45
+ "prepublishOnly": "npm run build",
46
+ "test": "vitest run --passWithNoTests",
47
+ "test:watch": "vitest",
48
+ "typecheck": "tsc --noEmit",
49
+ "prepack": "node ../scripts/publishconfig-swap.mjs apply",
50
+ "postpack": "node ../scripts/publishconfig-swap.mjs restore"
51
+ },
52
+ "dependencies": {
53
+ "@paragraf/types": "^0.7.1",
54
+ "hyphen": "^1.14.1"
55
+ },
56
+ "devDependencies": {
57
+ "@types/fontkit": "^2.0.9",
58
+ "@types/node": "^22.19.15",
59
+ "fontkit": "^2.0.4",
60
+ "tsx": "^4.21.0",
61
+ "typescript": "^5.4.0",
62
+ "vitest": "^3.2.4"
63
+ }
64
+ }