@paragraf/linebreak 0.0.0-stage → 0.7.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/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,77 @@
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
+ // throws if no solution; result.usedEmergency is true if emergencyStretch was needed
22
+ const breaks = traceback(result.node);
23
+ const lines = composeParagraph(nodes, breaks, 'justified', false, lineWidth, [], getMetrics);
24
+ ```
25
+
26
+ ### Node building: `buildNodeSequence`
27
+
28
+ Converts hyphenated words + fonts into the node sequence the algorithm expects.
29
+
30
+ ```ts
31
+ import { buildNodeSequence } from '@paragraf/linebreak';
32
+
33
+ const nodes = buildNodeSequence(hyphenatedWords, measurer);
34
+ ```
35
+
36
+ ### Hyphenation
37
+
38
+ ```ts
39
+ import { loadHyphenator, hyphenateWord, hyphenateParagraph, loadLanguages } from '@paragraf/linebreak';
40
+
41
+ // Load patterns for a language (must call before hyphenating)
42
+ await loadHyphenator('en-us');
43
+ // patterns loaded — use hyphenateWord / hyphenateParagraph from this point on
44
+ const words = hyphenateParagraph(text, { language: 'en-us', minWordLength: 5, fontSize: 12 });
45
+
46
+ // Batch-load multiple languages
47
+ await loadLanguages(['en-us', 'de', 'fr']);
48
+ ```
49
+
50
+ #### `HyphenateOptions`
51
+
52
+ ```ts
53
+ interface HyphenateOptions {
54
+ minWordLength: number; // required — skip words shorter than this
55
+ fontSize: number; // required — drives minLeft/minRight derivation
56
+ language: Language; // required
57
+ preserveSoftHyphens?: boolean; // default true
58
+ }
59
+ ```
60
+
61
+ ### Test utilities
62
+
63
+ ```ts
64
+ import { mockMeasure, mockSpace, mockMetrics } from '@paragraf/linebreak';
65
+
66
+ const measurer = {
67
+ measure: mockMeasure,
68
+ space: mockSpace,
69
+ metrics: mockMetrics,
70
+ registry: new Map(),
71
+ };
72
+ ```
73
+
74
+ ## Browser safety
75
+
76
+ This package has zero Node.js dependencies. It can be imported in
77
+ any bundler or browser environment without polyfills.
@@ -0,0 +1,70 @@
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
+ processCapitalized?: boolean;
41
+ /** Per-document exception dictionary checked before pattern-based hyphenation. */
42
+ exceptions?: ExceptionDictionary;
43
+ }
44
+ interface HyphenatedWord {
45
+ original: string;
46
+ fragments: string[];
47
+ hyphenable: boolean;
48
+ hasSoftHyphen: boolean;
49
+ }
50
+ declare const DEFAULT_HYPHENATE_OPTIONS: HyphenateOptions;
51
+ declare const deriveMinLeft: (fontSize: number) => number;
52
+ declare const deriveMinRight: (fontSize: number) => number;
53
+ declare const loadHyphenator: (language: Language) => Promise<void>;
54
+ declare const loadLanguages: (languages: Language[]) => Promise<void>;
55
+ declare const hyphenateWord: (word: string, opts?: HyphenateOptions, isFirstWord?: boolean, preserveSoftHyphens?: boolean) => HyphenatedWord;
56
+ declare const hyphenateParagraph: (text: string, opts?: HyphenateOptions) => HyphenatedWord[];
57
+
58
+ interface HyphenatedWordWithFont extends HyphenatedWord {
59
+ font: Font;
60
+ segments?: SpanSegment[][];
61
+ }
62
+ declare const buildNodeSequence: (words: HyphenatedWordWithFont[], measurer: Measurer, firstLineIndent?: number) => Node[];
63
+
64
+ 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;
65
+
66
+ declare const mockMeasure: MeasureText;
67
+ declare const mockSpace: GlueSpaceFn;
68
+ declare const mockMetrics: GetFontMetrics;
69
+
70
+ 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,786 @@
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 buildTermination = () => [
340
+ {
341
+ type: "glue",
342
+ kind: "termination",
343
+ // explicit
344
+ width: 0,
345
+ stretch: Infinity,
346
+ shrink: 0
347
+ },
348
+ {
349
+ type: "penalty",
350
+ width: 0,
351
+ penalty: FORCED_BREAK,
352
+ flagged: false
353
+ }
354
+ ];
355
+ var glueFont = (word) => {
356
+ if (word.segments && word.segments.length > 0) {
357
+ const lastFrag = word.segments[word.segments.length - 1];
358
+ if (lastFrag.length > 0) return lastFrag[lastFrag.length - 1].font;
359
+ }
360
+ return word.font;
361
+ };
362
+ var buildNodeSequence = (words, measurer, firstLineIndent = 0) => {
363
+ const nodes = [];
364
+ if (firstLineIndent > 0) {
365
+ const firstFont = words[0]?.font;
366
+ if (firstFont) nodes.push(buildIndentBox(firstLineIndent, firstFont));
367
+ }
368
+ words.forEach((word, index) => {
369
+ const { fragments, font, hasSoftHyphen, segments } = word;
370
+ const penaltyValue = hasSoftHyphen ? SOFT_HYPHEN_PENALTY : HYPHEN_PENALTY;
371
+ if (segments) {
372
+ segments.forEach((fragSegs, fi) => {
373
+ fragSegs.forEach((seg) => {
374
+ nodes.push(
375
+ buildBox(seg.text, seg.font, measurer, seg.verticalOffset)
376
+ );
377
+ });
378
+ if (fi < segments.length - 1) {
379
+ const lastSeg = fragSegs[fragSegs.length - 1];
380
+ nodes.push(buildHyphenPenalty(lastSeg.font, measurer, penaltyValue));
381
+ }
382
+ });
383
+ } else if (fragments.length === 1) {
384
+ nodes.push(buildBox(fragments[0], font, measurer));
385
+ } else {
386
+ fragments.forEach((fragment, fi) => {
387
+ nodes.push(buildBox(fragment, font, measurer));
388
+ if (fi < fragments.length - 1) {
389
+ nodes.push(buildHyphenPenalty(font, measurer, penaltyValue));
390
+ }
391
+ });
392
+ }
393
+ if (index < words.length - 1) {
394
+ nodes.push(buildGlue(glueFont(word), measurer));
395
+ }
396
+ });
397
+ nodes.push(...buildTermination());
398
+ return nodes;
399
+ };
400
+
401
+ // src/compose.ts
402
+ var resolveGlueWidth = (glue, ratio, alignment) => {
403
+ if (alignment !== "justified") return glue.width;
404
+ if (ratio >= 0) return glue.width + ratio * glue.stretch;
405
+ return glue.width + ratio * glue.shrink;
406
+ };
407
+ var computeLastLineRatio = (nodes, from, to, lineWidth) => {
408
+ let contentWidth = 0;
409
+ let totalStretch = 0;
410
+ let totalShrink = 0;
411
+ let glueCount = 0;
412
+ const start = lineStartAfter(nodes, from, to);
413
+ for (let i = start; i <= to; i++) {
414
+ const node = nodes[i];
415
+ if (node.type === "box") {
416
+ contentWidth += node.width;
417
+ } else if (node.type === "glue" && node.kind === "word") {
418
+ contentWidth += node.width;
419
+ totalStretch += node.stretch;
420
+ totalShrink += node.shrink;
421
+ glueCount++;
422
+ }
423
+ }
424
+ if (glueCount === 0) return 0;
425
+ const remaining = lineWidth - contentWidth;
426
+ if (remaining > 0) return totalStretch > 0 ? remaining / totalStretch : 0;
427
+ if (remaining < 0) return totalShrink > 0 ? remaining / totalShrink : 0;
428
+ return 0;
429
+ };
430
+ var extractLine = (nodes, from, to, ratio, flagged, alignment, isLastLine, justifyLastLine, lineWidth, getMetrics, overfull = false) => {
431
+ const words = [];
432
+ const fonts = [];
433
+ const wordRuns = [];
434
+ let wordSpacing = 0;
435
+ let spacingResolved = false;
436
+ let lastWasHyphenPenalty = false;
437
+ let lastWasBox = false;
438
+ const effectiveRatio = isLastLine && justifyLastLine && !overfull ? computeLastLineRatio(nodes, from, to, lineWidth) : ratio;
439
+ const start = lineStartAfter(nodes, from, to);
440
+ let boxWidthSum = 0;
441
+ let wordGlueCount = 0;
442
+ for (let i = start; i <= to; i++) {
443
+ const node = nodes[i];
444
+ if (node.type === "box") {
445
+ boxWidthSum += node.width;
446
+ if ((lastWasHyphenPenalty || lastWasBox) && words.length > 0) {
447
+ words[words.length - 1] += node.content;
448
+ wordRuns[wordRuns.length - 1].push({
449
+ text: node.content,
450
+ font: node.font,
451
+ verticalOffset: node.verticalOffset
452
+ });
453
+ } else {
454
+ words.push(node.content);
455
+ fonts.push(node.font);
456
+ wordRuns.push([
457
+ {
458
+ text: node.content,
459
+ font: node.font,
460
+ verticalOffset: node.verticalOffset
461
+ }
462
+ ]);
463
+ }
464
+ lastWasHyphenPenalty = false;
465
+ lastWasBox = true;
466
+ } else if (node.type === "penalty" && node.flagged) {
467
+ lastWasHyphenPenalty = i < to;
468
+ lastWasBox = false;
469
+ } else {
470
+ lastWasHyphenPenalty = false;
471
+ lastWasBox = false;
472
+ }
473
+ if (node.type === "glue" && node.kind === "word") {
474
+ wordGlueCount++;
475
+ if (!spacingResolved) {
476
+ wordSpacing = resolveGlueWidth(node, effectiveRatio, alignment);
477
+ spacingResolved = true;
478
+ }
479
+ }
480
+ }
481
+ if (flagged && words.length > 0) {
482
+ words[words.length - 1] += "-";
483
+ const lastRuns = wordRuns[wordRuns.length - 1];
484
+ if (lastRuns.length > 0) {
485
+ const last = lastRuns[lastRuns.length - 1];
486
+ lastRuns[lastRuns.length - 1] = { ...last, text: last.text + "-" };
487
+ }
488
+ }
489
+ const breakNode = nodes[to];
490
+ const breakIsWordGlue = breakNode?.type === "glue" && breakNode.kind === "word";
491
+ const visibleGlues = wordGlueCount - (breakIsWordGlue ? 1 : 0);
492
+ const penaltyWidth = breakNode?.type === "penalty" && breakNode.flagged ? breakNode.width : 0;
493
+ if (alignment === "justified" && (!isLastLine || justifyLastLine) && !overfull) {
494
+ if (visibleGlues > 0) {
495
+ wordSpacing = Math.max(
496
+ 0,
497
+ (lineWidth - boxWidthSum - penaltyWidth) / visibleGlues
498
+ );
499
+ }
500
+ }
501
+ let lineHeight = 0;
502
+ let baseline = 0;
503
+ if (getMetrics) {
504
+ const seen = /* @__PURE__ */ new Set();
505
+ for (const runs of wordRuns) {
506
+ for (const seg of runs) {
507
+ if (!seen.has(seg.font)) {
508
+ seen.add(seg.font);
509
+ const m = getMetrics(seg.font);
510
+ if (m) {
511
+ const lh = m.ascender - m.descender + m.lineGap;
512
+ if (lh > lineHeight) lineHeight = lh;
513
+ if (m.ascender > baseline) baseline = m.ascender;
514
+ }
515
+ }
516
+ }
517
+ }
518
+ }
519
+ return {
520
+ words,
521
+ fonts,
522
+ wordRuns,
523
+ wordSpacing,
524
+ hyphenated: flagged,
525
+ ratio: alignment === "justified" ? effectiveRatio : 0,
526
+ alignment,
527
+ isWidow: false,
528
+ // @deprecated — use isRunt
529
+ isRunt: false,
530
+ // set by composeParagraph post-pass
531
+ lineWidth,
532
+ lineHeight,
533
+ baseline,
534
+ ...overfull ? {
535
+ overfull: true,
536
+ overflow: Math.max(
537
+ 0,
538
+ boxWidthSum + penaltyWidth + visibleGlues * wordSpacing - lineWidth
539
+ )
540
+ } : {}
541
+ };
542
+ };
543
+ var composeParagraph = (nodes, breaks, alignment = "justified", justifyLastLine = false, lineWidth = 0, lineWidths = [], getMetrics, direction = "ltr", leftSkip = 0, rightSkip = 0, kashida = false, maxGlyphExpansion = 0) => {
544
+ if (justifyLastLine && lineWidth === 0) {
545
+ throw new Error(
546
+ "lineWidth must be provided when justifyLastLine=true. Pass the same lineWidth used for composition."
547
+ );
548
+ }
549
+ const lines = [];
550
+ let previousPosition = 0;
551
+ for (let bi = 0; bi < breaks.length; bi++) {
552
+ const lineBreak = breaks[bi];
553
+ const isLastLine = bi === breaks.length - 1;
554
+ const effectiveWidth = lineWidths[bi] ?? lineWidth;
555
+ const line = extractLine(
556
+ nodes,
557
+ previousPosition,
558
+ lineBreak.position,
559
+ lineBreak.ratio,
560
+ lineBreak.flagged,
561
+ alignment,
562
+ isLastLine,
563
+ justifyLastLine,
564
+ effectiveWidth,
565
+ getMetrics,
566
+ lineBreak.overfull === true
567
+ );
568
+ if (line.words.length > 0) {
569
+ const useKashida = kashida && direction === "rtl" && line.alignment === "justified" && !isLastLine;
570
+ const glyphExpansion = maxGlyphExpansion > 0 ? Math.max(
571
+ -maxGlyphExpansion,
572
+ Math.min(maxGlyphExpansion, lineBreak.ratio * maxGlyphExpansion)
573
+ ) : 0;
574
+ lines.push({
575
+ ...line,
576
+ direction,
577
+ leftSkip,
578
+ rightSkip,
579
+ kashidaSpacing: useKashida ? line.wordSpacing : 0,
580
+ wordSpacing: useKashida ? 0 : line.wordSpacing,
581
+ glyphExpansion
582
+ });
583
+ }
584
+ previousPosition = lineBreak.position;
585
+ }
586
+ if (lines.length > 1) {
587
+ const last = lines[lines.length - 1];
588
+ const contentWords = last.words.filter((w) => w !== "");
589
+ if (contentWords.length === 1) {
590
+ lines[lines.length - 1] = { ...last, isWidow: true, isRunt: true };
591
+ }
592
+ }
593
+ return lines;
594
+ };
595
+
596
+ // src/hyphenate.ts
597
+ import createHyphenator from "hyphen";
598
+ var DEFAULT_HYPHENATE_OPTIONS = {
599
+ minWordLength: 5,
600
+ fontSize: 12,
601
+ language: "en-us",
602
+ preserveSoftHyphens: true
603
+ };
604
+ var deriveMinLeft = (fontSize) => Math.max(2, Math.round(fontSize / 6));
605
+ var deriveMinRight = (fontSize) => Math.max(3, Math.round(fontSize / 6) + 1);
606
+ var PATTERN_LOADERS = {
607
+ "en-us": () => import("hyphen/patterns/en-us.js"),
608
+ "en-gb": () => import("hyphen/patterns/en-gb.js"),
609
+ // de-1996: reformed German orthography (post-1996 spelling reform)
610
+ de: () => import("hyphen/patterns/de-1996.js"),
611
+ fr: () => import("hyphen/patterns/fr.js"),
612
+ tr: () => import("hyphen/patterns/tr.js"),
613
+ nl: () => import("hyphen/patterns/nl.js"),
614
+ pl: () => import("hyphen/patterns/pl.js"),
615
+ it: () => import("hyphen/patterns/it.js"),
616
+ es: () => import("hyphen/patterns/es.js"),
617
+ sv: () => import("hyphen/patterns/sv.js"),
618
+ // no: Bokmål + Nynorsk combined patterns (covers both official written standards)
619
+ no: () => import("hyphen/patterns/no.js"),
620
+ da: () => import("hyphen/patterns/da.js"),
621
+ fi: () => import("hyphen/patterns/fi.js"),
622
+ hu: () => import("hyphen/patterns/hu.js"),
623
+ cs: () => import("hyphen/patterns/cs.js"),
624
+ sk: () => import("hyphen/patterns/sk.js"),
625
+ ro: () => import("hyphen/patterns/ro.js"),
626
+ hr: () => import("hyphen/patterns/hr.js"),
627
+ sl: () => import("hyphen/patterns/sl.js"),
628
+ lt: () => import("hyphen/patterns/lt.js"),
629
+ lv: () => import("hyphen/patterns/lv.js"),
630
+ et: () => import("hyphen/patterns/et.js")
631
+ };
632
+ var hyphenatorCache = /* @__PURE__ */ new Map();
633
+ var loadHyphenator = async (language) => {
634
+ if (hyphenatorCache.has(language)) return;
635
+ const loader = PATTERN_LOADERS[language];
636
+ if (!loader) throw new Error(`Unsupported language: ${language}`);
637
+ const patterns = await loader();
638
+ const hyphenator = createHyphenator(patterns.default ?? patterns, {
639
+ async: false
640
+ });
641
+ hyphenatorCache.set(language, hyphenator);
642
+ };
643
+ var loadLanguages = async (languages) => {
644
+ await Promise.all(languages.map(loadHyphenator));
645
+ };
646
+ var INPUT_SOFT_HYPHEN = "\xAD";
647
+ var extractSoftHyphenFragments = (word) => {
648
+ if (!word.includes(INPUT_SOFT_HYPHEN)) return null;
649
+ const fragments = word.split(INPUT_SOFT_HYPHEN);
650
+ if (fragments.some((f) => f.length === 0)) return null;
651
+ return fragments;
652
+ };
653
+ var shouldSkip = (word, opts, isFirstWord) => {
654
+ const clean = word.replaceAll(INPUT_SOFT_HYPHEN, "");
655
+ if (clean.length < opts.minWordLength) return true;
656
+ if (/\d/.test(clean)) return true;
657
+ if (/^https?:\/\//.test(clean)) return true;
658
+ if (/^[A-Z][A-Z]+$/.test(clean)) return true;
659
+ if (!opts.processCapitalized && !isFirstWord && /^[A-Z]/.test(clean)) {
660
+ const isSentenceStart = opts._prevWord !== void 0 && /[.!?]['"\)\]\}]*$/.test(opts._prevWord);
661
+ if (!isSentenceStart) return true;
662
+ }
663
+ return false;
664
+ };
665
+ var enforceMinBoundaries = (fragments, minLeft, minRight) => {
666
+ if (fragments.length <= 1) return fragments;
667
+ const result = [...fragments];
668
+ while (result.length > 1 && result[0].length < minLeft) {
669
+ result.splice(0, 2, result[0] + result[1]);
670
+ }
671
+ while (result.length > 1 && result[result.length - 1].length < minRight) {
672
+ const last = result.pop();
673
+ result[result.length - 1] = result[result.length - 1] + last;
674
+ }
675
+ return result;
676
+ };
677
+ var hyphenateWord = (word, opts = DEFAULT_HYPHENATE_OPTIONS, isFirstWord = false, preserveSoftHyphens = opts.preserveSoftHyphens ?? true) => {
678
+ if (preserveSoftHyphens) {
679
+ const softFragments = extractSoftHyphenFragments(word);
680
+ if (softFragments) {
681
+ return {
682
+ original: word.replaceAll(INPUT_SOFT_HYPHEN, ""),
683
+ fragments: softFragments,
684
+ hyphenable: softFragments.length > 1,
685
+ hasSoftHyphen: true
686
+ };
687
+ }
688
+ }
689
+ const clean = word.replaceAll(INPUT_SOFT_HYPHEN, "");
690
+ if (shouldSkip(clean, opts, isFirstWord)) {
691
+ return {
692
+ original: clean,
693
+ fragments: [clean],
694
+ hyphenable: false,
695
+ hasSoftHyphen: false
696
+ };
697
+ }
698
+ const hyphenator = hyphenatorCache.get(opts.language);
699
+ if (!hyphenator) {
700
+ throw new Error(
701
+ `Hyphenator for "${opts.language}" not loaded. Call loadHyphenator("${opts.language}") before hyphenating.`
702
+ );
703
+ }
704
+ const minLeft = opts.minLeft ?? deriveMinLeft(opts.fontSize);
705
+ const minRight = opts.minRight ?? deriveMinRight(opts.fontSize);
706
+ if (opts.exceptions) {
707
+ const key = clean.toLowerCase();
708
+ const override = opts.exceptions[key];
709
+ if (override === false) {
710
+ return {
711
+ original: clean,
712
+ fragments: [clean],
713
+ hyphenable: false,
714
+ hasSoftHyphen: false
715
+ };
716
+ }
717
+ if (Array.isArray(override) && override.length > 1) {
718
+ const frags = enforceMinBoundaries(override, minLeft, minRight);
719
+ return {
720
+ original: clean,
721
+ fragments: frags,
722
+ hyphenable: frags.length > 1,
723
+ hasSoftHyphen: false
724
+ };
725
+ }
726
+ }
727
+ const hyphenated = hyphenator(clean);
728
+ const all = hyphenated.split(INPUT_SOFT_HYPHEN);
729
+ const fragments = enforceMinBoundaries(all, minLeft, minRight);
730
+ return {
731
+ original: clean,
732
+ fragments,
733
+ hyphenable: fragments.length > 1,
734
+ hasSoftHyphen: false
735
+ };
736
+ };
737
+ var hyphenateParagraph = (text, opts = DEFAULT_HYPHENATE_OPTIONS) => {
738
+ const words = text.trim().split(/\s+/);
739
+ return words.map((word, index) => {
740
+ const optsWithPrev = index > 0 ? { ...opts, _prevWord: words[index - 1] } : opts;
741
+ return hyphenateWord(
742
+ word,
743
+ optsWithPrev,
744
+ index === 0,
745
+ opts.preserveSoftHyphens ?? true
746
+ );
747
+ });
748
+ };
749
+
750
+ // src/testing.ts
751
+ var mockMeasure = (content, font) => {
752
+ const base = content.length * font.size * 0.6;
753
+ const spacing = (font.letterSpacing ?? 0) * Math.max(0, content.length - 1);
754
+ return base + spacing;
755
+ };
756
+ var mockSpace = (font) => {
757
+ const width = font.size * 0.25;
758
+ const stretch = width * 0.5;
759
+ const shrink = width * 0.3;
760
+ return { width, stretch, shrink };
761
+ };
762
+ var mockMetrics = (font) => ({
763
+ unitsPerEm: 1e3,
764
+ ascender: font.size * 0.8,
765
+ descender: -font.size * 0.2,
766
+ xHeight: font.size * 0.5,
767
+ capHeight: font.size * 0.7,
768
+ lineGap: 0,
769
+ baselineShift: font.variant === "superscript" ? font.size * 0.35 : font.variant === "subscript" ? -font.size * 0.15 : 0
770
+ });
771
+ export {
772
+ DEFAULT_HYPHENATE_OPTIONS,
773
+ buildNodeSequence,
774
+ composeParagraph,
775
+ computeBreakpoints,
776
+ deriveMinLeft,
777
+ deriveMinRight,
778
+ hyphenateParagraph,
779
+ hyphenateWord,
780
+ loadHyphenator,
781
+ loadLanguages,
782
+ mockMeasure,
783
+ mockMetrics,
784
+ mockSpace,
785
+ traceback
786
+ };
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.0",
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.0",
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
+ }