@paragraf/linebreak 0.7.0 → 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/README.md CHANGED
@@ -18,7 +18,8 @@ Build a node sequence, find breakpoints, then assemble composed lines:
18
18
  import { computeBreakpoints, traceback, composeParagraph } from '@paragraf/linebreak';
19
19
 
20
20
  const result = computeBreakpoints(paragraph);
21
- // throws if no solution; result.usedEmergency is true if emergencyStretch was needed
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)
22
23
  const breaks = traceback(result.node);
23
24
  const lines = composeParagraph(nodes, breaks, 'justified', false, lineWidth, [], getMetrics);
24
25
  ```
@@ -55,9 +56,61 @@ interface HyphenateOptions {
55
56
  fontSize: number; // required — drives minLeft/minRight derivation
56
57
  language: Language; // required
57
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;
58
64
  }
59
65
  ```
60
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
+
61
114
  ### Test utilities
62
115
 
63
116
  ```ts
package/dist/index.d.ts CHANGED
@@ -37,13 +37,35 @@ interface HyphenateOptions {
37
37
  preserveSoftHyphens?: boolean;
38
38
  minLeft?: number;
39
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
+ */
40
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;
41
56
  /** Per-document exception dictionary checked before pattern-based hyphenation. */
42
57
  exceptions?: ExceptionDictionary;
43
58
  }
44
59
  interface HyphenatedWord {
45
60
  original: string;
61
+ /** The word split at its break points; one fragment when there are none. */
46
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
+ */
47
69
  hyphenable: boolean;
48
70
  hasSoftHyphen: boolean;
49
71
  }
package/dist/index.js CHANGED
@@ -336,6 +336,13 @@ var buildHyphenPenalty = (font, measurer, penaltyValue = HYPHEN_PENALTY) => ({
336
336
  penalty: penaltyValue,
337
337
  flagged: true
338
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
+ });
339
346
  var buildTermination = () => [
340
347
  {
341
348
  type: "glue",
@@ -368,6 +375,8 @@ var buildNodeSequence = (words, measurer, firstLineIndent = 0) => {
368
375
  words.forEach((word, index) => {
369
376
  const { fragments, font, hasSoftHyphen, segments } = word;
370
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);
371
380
  if (segments) {
372
381
  segments.forEach((fragSegs, fi) => {
373
382
  fragSegs.forEach((seg) => {
@@ -377,7 +386,7 @@ var buildNodeSequence = (words, measurer, firstLineIndent = 0) => {
377
386
  });
378
387
  if (fi < segments.length - 1) {
379
388
  const lastSeg = fragSegs[fragSegs.length - 1];
380
- nodes.push(buildHyphenPenalty(lastSeg.font, measurer, penaltyValue));
389
+ nodes.push(breakPenalty(lastSeg.font));
381
390
  }
382
391
  });
383
392
  } else if (fragments.length === 1) {
@@ -386,7 +395,7 @@ var buildNodeSequence = (words, measurer, firstLineIndent = 0) => {
386
395
  fragments.forEach((fragment, fi) => {
387
396
  nodes.push(buildBox(fragment, font, measurer));
388
397
  if (fi < fragments.length - 1) {
389
- nodes.push(buildHyphenPenalty(font, measurer, penaltyValue));
398
+ nodes.push(breakPenalty(font));
390
399
  }
391
400
  });
392
401
  }
@@ -466,6 +475,9 @@ var extractLine = (nodes, from, to, ratio, flagged, alignment, isLastLine, justi
466
475
  } else if (node.type === "penalty" && node.flagged) {
467
476
  lastWasHyphenPenalty = i < to;
468
477
  lastWasBox = false;
478
+ } else if (node.type === "penalty" && lastWasBox) {
479
+ lastWasHyphenPenalty = i < to;
480
+ lastWasBox = false;
469
481
  } else {
470
482
  lastWasHyphenPenalty = false;
471
483
  lastWasBox = false;
@@ -650,13 +662,126 @@ var extractSoftHyphenFragments = (word) => {
650
662
  if (fragments.some((f) => f.length === 0)) return null;
651
663
  return fragments;
652
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;
653
776
  var shouldSkip = (word, opts, isFirstWord) => {
654
777
  const clean = word.replaceAll(INPUT_SOFT_HYPHEN, "");
655
778
  if (clean.length < opts.minWordLength) return true;
656
779
  if (/\d/.test(clean)) return true;
657
780
  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)) {
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)) {
660
785
  const isSentenceStart = opts._prevWord !== void 0 && /[.!?]['"\)\]\}]*$/.test(opts._prevWord);
661
786
  if (!isSentenceStart) return true;
662
787
  }
@@ -675,6 +800,18 @@ var enforceMinBoundaries = (fragments, minLeft, minRight) => {
675
800
  return result;
676
801
  };
677
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
+ }
678
815
  if (preserveSoftHyphens) {
679
816
  const softFragments = extractSoftHyphenFragments(word);
680
817
  if (softFragments) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@paragraf/linebreak",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "Knuth-Plass line-breaking algorithm + hyphenation. Browser-safe, zero font dependencies.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -50,7 +50,7 @@
50
50
  "postpack": "node ../scripts/publishconfig-swap.mjs restore"
51
51
  },
52
52
  "dependencies": {
53
- "@paragraf/types": "^0.7.0",
53
+ "@paragraf/types": "^0.7.1",
54
54
  "hyphen": "^1.14.1"
55
55
  },
56
56
  "devDependencies": {