@mark1russell7/layout-contract 0.5.5 → 0.6.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/src/text.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { breakers, linesOf, type Box, type Item, type Penalty } from "@mark1russell7/typeset/breaking";
2
+ import { graphemes, lineBreaks } from "@mark1russell7/typeset/segmentation";
3
+ import { partsOfWords } from "./word-parts.ts";
2
4
  import type { MeasureSpec } from "./measures.ts";
3
5
 
4
6
  /**
@@ -101,32 +103,34 @@ export function canvasAdvance(context: CanvasTextContext): AdvanceFn {
101
103
  };
102
104
  }
103
105
 
104
- /** A word of a text: its segments, which the measurer measures and caches one by one. */
106
+ /**
107
+ * A word of a text: the text from one break place of UAX #14 to the next, with no white space at its end.
108
+ * Its parts are its word segments (UAX #29), which the measurer measures and caches one by one.
109
+ */
105
110
  interface Word {
106
111
  readonly text: string;
107
112
  readonly parts: readonly string[];
113
+ /** This value is `true` when white space follows the word in the text. Then one space comes after the word. Else the gap has no width. */
114
+ readonly spaced: boolean;
108
115
  }
109
116
 
110
- const SPACE = /^\s+$/u;
111
-
112
- /** The segmenters of the module. A new `Intl.Segmenter` loads the data of the locale, so the module makes each granularity only once. */
113
- const segmenters = /* @__PURE__ */ new Map<"word" | "grapheme", Intl.Segmenter | null>();
117
+ /**
118
+ * A run of the white space that collapses: the white space of CSS (space, tab, line feed, form feed, carriage return) and the other mandatory breaks of UAX #14.
119
+ * A no-break space or an ideographic space stays in its word, as in CSS.
120
+ */
121
+ const SPACES = /[ \t\n\v\f\r\u0085\u2028\u2029]+/gu;
114
122
 
115
- /** This function gives the segmenter of a granularity, or `null` without `Intl.Segmenter`. */
116
- function segmenterOf(granularity: "word" | "grapheme"): Intl.Segmenter | null {
117
- let s = segmenters.get(granularity);
118
- if (s === undefined) {
119
- s = typeof Intl !== "undefined" && typeof Intl.Segmenter === "function" ? new Intl.Segmenter(undefined, { granularity }) : null;
120
- segmenters.set(granularity, s);
121
- }
122
- return s;
123
- }
123
+ /** The white space of `SPACES` at the end of a text. */
124
+ const TRAILING_SPACE = /[ \t\n\v\f\r\u0085\u2028\u2029]+$/u;
124
125
 
125
126
  /** The largest count of texts in the memo of `wordsOf`. A page often asks for the same labels many times. */
126
127
  const WORDS_MEMO = 4096;
127
128
  const wordsMemo = /* @__PURE__ */ new Map<string, readonly Word[]>();
128
129
 
129
- /** This function splits the text into words at white space. Each word holds its word segments (`Intl.Segmenter`), so words that share segments share the cache. */
130
+ /**
131
+ * This function splits the text into words at the break places of UAX #14 (`lineBreaks` of `@mark1russell7/typeset`).
132
+ * Each word holds its word segments, so words that share segments share the cache.
133
+ */
130
134
  function wordsOf(text: string): readonly Word[] {
131
135
  const known = wordsMemo.get(text);
132
136
  if (known !== undefined) return known;
@@ -137,35 +141,49 @@ function wordsOf(text: string): readonly Word[] {
137
141
  return words;
138
142
  }
139
143
 
140
- /** This function gives the words of `wordsOf` with no memo. */
144
+ /**
145
+ * This function gives the words of `wordsOf` with no memo.
146
+ * A break place of UAX #14 comes after a run of white space, so the white space of a piece is at its end. That white space goes, and the word records it.
147
+ * White space inside a piece, for example before a closing bracket, collapses to one space, as `white-space: normal` in CSS.
148
+ * A mandatory break inside the text, for example at a line feed, is white space as in CSS. Only the end of the text ends the last line.
149
+ */
141
150
  function splitWords(text: string): Word[] {
142
- const words: Word[] = [];
143
- let parts: string[] = [];
144
- const flush = (): void => {
145
- if (parts.length > 0) words.push({ text: parts.join(""), parts });
146
- parts = [];
147
- };
148
- const segmenter = segmenterOf("word");
149
- if (segmenter !== null) {
150
- for (const s of segmenter.segment(text)) {
151
- if (SPACE.test(s.segment)) flush();
152
- else parts.push(s.segment);
153
- }
154
- } else {
155
- for (const s of text.split(/(\s+)/u)) {
156
- if (s === "" || SPACE.test(s)) flush();
157
- else parts.push(s);
151
+ const words: { text: string; spaced: boolean }[] = [];
152
+ let start = 0;
153
+ for (const place of lineBreaks(text)) {
154
+ const piece = text.slice(start, place.offset);
155
+ start = place.offset;
156
+ const body = piece.replace(TRAILING_SPACE, "").replace(SPACES, " ");
157
+ const spaced = body.length < piece.length;
158
+ // White space at the start of a piece, for example after a line feed, is the gap after the word before it. A piece of only white space adds no word.
159
+ const word = body.startsWith(" ") ? body.slice(1) : body;
160
+ if (word.length < body.length || body === "") {
161
+ const last = words[words.length - 1];
162
+ if (last !== undefined) last.spaced = true;
158
163
  }
164
+ if (word === "") continue;
165
+ words.push({ text: word, spaced });
159
166
  }
160
- flush();
161
- return words;
167
+ // One call of `wordBreaks` gives the segments of all the words of the text.
168
+ const parts = partsOfWords(words.map((w) => w.text));
169
+ return words.map((w, i) => ({ text: w.text, parts: parts[i]!, spaced: w.spaced }));
162
170
  }
163
171
 
164
- /** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */
172
+ /** This function gives the grapheme clusters of a text by UAX #29 (`graphemes` of `@mark1russell7/typeset`), with no locale. */
165
173
  export function graphemesOf(text: string): string[] {
166
- const segmenter = segmenterOf("grapheme");
167
- if (segmenter !== null) return Array.from(segmenter.segment(text), (s) => s.segment);
168
- return Array.from(text);
174
+ return [...graphemes(text)];
175
+ }
176
+
177
+ /** This function gives the count of the gaps of one space between the words: one after each spaced word but the last. */
178
+ function spacesOf(words: readonly Word[]): number {
179
+ let count = 0;
180
+ for (let i = 0; i < words.length - 1; i++) if (words[i]!.spaced) count++;
181
+ return count;
182
+ }
183
+
184
+ /** This function joins the words with their gaps: one space after a spaced word, and nothing after another word. */
185
+ function joinWords(words: readonly Word[]): string {
186
+ return words.map((w, i) => (i < words.length - 1 && w.spaced ? `${w.text} ` : w.text)).join("");
169
187
  }
170
188
 
171
189
  /** The digits, as a value for `createTextCharset`. */
@@ -317,6 +335,9 @@ export interface TextLayout {
317
335
  /** A forced break: a penalty with no text, no width and the cost `-Infinity`. */
318
336
  const FORCED: Penalty = { type: "penalty", text: "", width: 0, cost: -Infinity, flagged: false };
319
337
 
338
+ /** The glue between two words with no white space between them, for example after a hyphen or between two CJK characters. A line can end there. */
339
+ const NO_GAP: Item = { type: "glue", text: "", width: 0 };
340
+
320
341
  /** This function gives the box of a part of a word. */
321
342
  /** This function gives the units of a segment: the bound for one character times the length, or a measure when there is no bound. */
322
343
  function advanceOf(segment: string, font: string, measurer: TextMeasurer, bound: number | undefined): number {
@@ -370,7 +391,7 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
370
391
  const words = wordsOf(source);
371
392
  const maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);
372
393
  const oneLine = (natural: number, bounded: boolean): TextLayout => {
373
- const one = words.map((w) => w.text).join(" ");
394
+ const one = joinWords(words);
374
395
  const px = natural / TEXT_UNITS;
375
396
  const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));
376
397
  const layout: TextLayout = { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };
@@ -380,7 +401,7 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
380
401
  // The raw text, not its words: the check sees a tab or a line break before they collapse.
381
402
  const unit = charset?.covers(source) === true ? charset.unit(font, measurer) : undefined;
382
403
  if (sizing === "bound-first" && unit !== undefined) {
383
- const natural = words.reduce((s, w) => s + w.text.length, Math.max(0, words.length - 1)) * unit;
404
+ const natural = words.reduce((s, w) => s + w.text.length, spacesOf(words)) * unit;
384
405
  if (options.wrapWidth === undefined || natural / TEXT_UNITS + padding <= maxWidth) return oneLine(natural, true);
385
406
  }
386
407
  const bound = sizing === "bound" ? unit : undefined;
@@ -388,16 +409,16 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
388
409
  const width = (w: Word): number => w.parts.reduce((s, p) => s + advanceOf(p, font, measurer, bound), 0);
389
410
  const lineUnits = (line: string): number => {
390
411
  const ws = wordsOf(line);
391
- return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);
412
+ return ws.reduce((s, w) => s + width(w), 0) + space * spacesOf(ws);
392
413
  };
393
414
  const widths = words.map(width);
394
- const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);
415
+ const natural = widths.reduce((s, w) => s + w, 0) + space * spacesOf(words);
395
416
 
396
417
  const fits = natural / TEXT_UNITS + padding <= maxWidth;
397
418
  if (options.wrapWidth === undefined || fits) return oneLine(natural, bound !== undefined);
398
419
 
399
420
  const limit = Math.round(options.wrapWidth * TEXT_UNITS);
400
- // The items of the breaker: a box for each word, and glue of one space between two words.
421
+ // The items of the breaker: a box for each word, and glue between two words. The glue is one space after a spaced word, else it has no width.
401
422
  const items: Item[] = [];
402
423
  /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. Each forced penalty ends a line. */
403
424
  const split = (word: Word): void => {
@@ -421,7 +442,7 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
421
442
  const w = widths[i]!;
422
443
  if (w > limit && !keep) split(word);
423
444
  else {
424
- if (items.length > 0) items.push({ type: "glue", text: " ", width: space });
445
+ if (items.length > 0) items.push(words[i - 1]!.spaced ? { type: "glue", text: " ", width: space } : NO_GAP);
425
446
  items.push({ type: "box", text: word.text, width: w });
426
447
  }
427
448
  });
@@ -0,0 +1,46 @@
1
+ // The word segments (UAX #29) of the words of a text, with one call of `wordBreaks` for all the words.
2
+ // This module is internal: the package root and `./text` do not export it.
3
+ import { wordBreaks } from "@mark1russell7/typeset/segmentation";
4
+
5
+ /** This function gives the word segments of one word, with one call of `wordBreaks`. */
6
+ export function partsOfWord(word: string): string[] {
7
+ const parts: string[] = [];
8
+ let from = 0;
9
+ for (const end of wordBreaks(word)) {
10
+ parts.push(word.slice(from, end));
11
+ from = end;
12
+ }
13
+ return parts;
14
+ }
15
+
16
+ /**
17
+ * This function gives the word segments of each word, with one call of `wordBreaks` on the words joined by line feeds.
18
+ * UAX #29 puts a break before and after a line feed (WB3a, WB3b), and no rule looks across it.
19
+ * So each word gets the segments of a call on the word alone.
20
+ * A word that ends with a carriage return has no break before the next line feed (WB3).
21
+ * When a break of a line feed is absent, the function gives the segments of one call for each word.
22
+ */
23
+ export function partsOfWords(words: readonly string[]): string[][] {
24
+ if (words.length === 0) return [];
25
+ if (words.length === 1) return [partsOfWord(words[0]!)];
26
+ const parts: string[][] = words.map(() => []);
27
+ const joined = words.join("\n");
28
+ let w = 0;
29
+ let from = 0;
30
+ let end = words[0]!.length;
31
+ for (const offset of wordBreaks(joined)) {
32
+ if (from === end) {
33
+ // The segment from `end` is the line feed after word `w`.
34
+ if (offset !== end + 1 || w + 1 >= words.length) return words.map(partsOfWord);
35
+ w += 1;
36
+ from = offset;
37
+ end = offset + words[w]!.length;
38
+ continue;
39
+ }
40
+ if (offset > end) return words.map(partsOfWord);
41
+ parts[w]!.push(joined.slice(from, offset));
42
+ from = offset;
43
+ }
44
+ if (w !== words.length - 1 || from !== end) return words.map(partsOfWord);
45
+ return parts;
46
+ }