@mark1russell7/layout-contract 0.3.0 → 0.3.2

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.
@@ -350,6 +350,15 @@ interface LayoutInput {
350
350
  */
351
351
  readonly invalidated?: readonly string[];
352
352
  }
353
+ /**
354
+ * A link between two items of a packer input. A graph order of the packer reads the links.
355
+ * `a` and `b` are indexes into `PackInput.items`. The weight is 1 when it has no value.
356
+ */
357
+ interface PackLink {
358
+ readonly a: number;
359
+ readonly b: number;
360
+ readonly weight?: number;
361
+ }
353
362
  /** The input of a packer: a `layout-input/1` file without the edges. */
354
363
  interface PackInput {
355
364
  readonly container: LayoutContainer;
@@ -357,9 +366,26 @@ interface PackInput {
357
366
  readonly obstacles?: readonly Obstacle[];
358
367
  readonly gap?: number;
359
368
  readonly pairGaps?: readonly PairGap[];
369
+ /** The links between the items. An input without `links` has no graph, and the links have no effect on an order that does not read them. */
370
+ readonly links?: readonly PackLink[];
371
+ }
372
+ /** The options of `toPackInput`. */
373
+ interface PackInputOptions {
374
+ /** With `true`, the packer input gets the links of `packLinks`. The default is `false`, so the input has no `links`. */
375
+ readonly links?: boolean;
360
376
  }
361
- /** This function gives the packer input of a file. An input without a container gets `{ fixed: "none" }`, so the packer picks the size. */
362
- declare function toPackInput(input: LayoutInput): PackInput;
377
+ /**
378
+ * This function gives the packer input of a file. An input without a container gets `{ fixed: "none" }`, so the packer picks the size.
379
+ * The edges are not in the packer input. With the option `links`, their links are in it.
380
+ */
381
+ declare function toPackInput(input: LayoutInput, options?: PackInputOptions): PackInput;
382
+ /**
383
+ * This function gives the links of the edges of a file, with indexes into `input.boxes`.
384
+ * - Each link has `a` below `b`. The list is sorted by `a` and then by `b`.
385
+ * - The edges of one pair of boxes make one link. Its weight is the count of the edges, and a link of one edge has no weight.
386
+ * - The function does not use an edge to a box that is not in `input.boxes`, or an edge from a box to the same box.
387
+ */
388
+ declare function packLinks(input: LayoutInput): PackLink[];
363
389
  /**
364
390
  * This function gives the canonical form of an input. `documentHash` uses it for each `layout-input/1` document.
365
391
  * Each pair of `pairGaps` gets `a` before `b`, and the list is sorted by `a` and then by `b`.
@@ -556,5 +582,5 @@ declare function minEffectOf(spec: Pick<MeasureSpec, "minEffect">, a?: number, b
556
582
  * Two equal values are a tie, also two infinite values. A value `NaN` is an error.
557
583
  */
558
584
  declare function compareMeasure(candidate: number, baseline: number, spec: Pick<MeasureSpec, "direction" | "minEffect">): Verdict;
559
- export { SPLIT_SCHEMA as $, shapesOf as A, PairGap as B, itemShapeOf as C, translate as Ct, shapeKindsOf as D, shapeKindProblem as E, LayoutEdge as F, ClaimBreak as G, canonicalInput as H, LayoutGenerator as I, DeclaredClaim as J, CorpusEntry as K, LayoutInput as L, LayoutBox as M, LayoutCell as N, shapeLevel as O, LayoutContainer as P, FamilyCell as Q, Obstacle as R, isShapeKind as S, regionArea as St, shapeKindOf as T, portPoint as U, Port as V, toPackInput as W, FAMILY_ANY_KIND as X, Declares as Y, FamilyBy as Z, ShapeKindSpec as _, Sides as _t, MeasureSpec as a, declaredClaimOf as at, boxArea as b, marginSides as bt, minEffectOf as c, leaveOneSeedOut as ct, SHAPE_KINDS as d, Margin as dt, SplitCorpus as et, SHAPE_KIND_IDS as f, Point as ft, ShapeKind as g, Side as gt, ShapeGeometry as h, SIDES as ht, JointMeasureId as i, corpusHashOf as it, Item as j, shapeSupportProblems as k, DEFAULT_SHAPES as l, splitFileName as lt, ShapeCheck as m, Region as mt, JOINT_MEASURES as n, checkDeclared as nt, Verdict as o, declaredCounts as ot, ShapeBound as p, Rect as pt, CorpusSplit as q, JOINT_MOVED_MIN as r, checkSplit as rt, compareMeasure as s, familyOf as st, Direction as t, SplitFold as tt, RuleLevel as u, splitFolds as ut, ShapeLevel as v, boundsOf as vt, ruleLevel as w, checkShapes as x, overlapOf as xt, ShapeSupport as y, grow as yt, PackInput as z };
560
- //# sourceMappingURL=measures-CQAuu3T5.d.ts.map
585
+ export { FAMILY_ANY_KIND as $, shapesOf as A, PackInputOptions as B, itemShapeOf as C, marginSides as Ct, shapeKindsOf as D, shapeKindProblem as E, translate as Et, LayoutEdge as F, packLinks as G, PairGap as H, LayoutGenerator as I, ClaimBreak as J, portPoint as K, LayoutInput as L, LayoutBox as M, LayoutCell as N, shapeLevel as O, LayoutContainer as P, Declares as Q, Obstacle as R, isShapeKind as S, grow as St, shapeKindOf as T, regionArea as Tt, Port as U, PackLink as V, canonicalInput as W, CorpusSplit as X, CorpusEntry as Y, DeclaredClaim as Z, ShapeKindSpec as _, Region as _t, MeasureSpec as a, checkDeclared as at, boxArea as b, Sides as bt, minEffectOf as c, declaredClaimOf as ct, SHAPE_KINDS as d, leaveOneSeedOut as dt, FamilyBy as et, SHAPE_KIND_IDS as f, splitFileName as ft, ShapeKind as g, Rect as gt, ShapeGeometry as h, Point as ht, JointMeasureId as i, SplitFold as it, Item as j, shapeSupportProblems as k, DEFAULT_SHAPES as l, declaredCounts as lt, ShapeCheck as m, Margin as mt, JOINT_MEASURES as n, SPLIT_SCHEMA as nt, Verdict as o, checkSplit as ot, ShapeBound as p, splitFolds as pt, toPackInput as q, JOINT_MOVED_MIN as r, SplitCorpus as rt, compareMeasure as s, corpusHashOf as st, Direction as t, FamilyCell as tt, RuleLevel as u, familyOf as ut, ShapeLevel as v, SIDES as vt, ruleLevel as w, overlapOf as wt, checkShapes as x, boundsOf as xt, ShapeSupport as y, Side as yt, PackInput as z };
586
+ //# sourceMappingURL=measures-BLoTbQwB.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"measures-CQAuu3T5.d.ts","names":[],"sources":["../src/geometry.ts","../src/corpus.ts","../src/input.ts","../src/shapes.ts","../src/measures.ts"],"mappings":";KACY;;cAGC,gBAAgB;UAEZ;WACN;WACA;;;UAIM;WACN;WACA;WACA;WACA;;;UAIM;WACN;WACA;WACA;WACA;;;;;;KAOC;WACG;WAAuB;WAAoB;WAAoB;WAAoB;;WAEnF;WACA;WACA;;WAEA;WAAyB;W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AkB;;KC5NpH;;;;;;UAOK,YAAY;WAClB,IAAI;WACJ;WACA,WAAW;;WAEX;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;aAAgC;;;WAEhC;;WAEA,kBAAkB;;;;;WAKlB,QAAQ;;;KAIP;;;;;cAoBC,yBAAyB,YAAY;;cAarC;;KAGD;;;;;;iBAOI,YAAY,MAAM,KAAK,2BAA2B,YAAO;;;;;;;iBAezD,eAAe,mBAAmB,kBAAkB,MAAM,KAAK,0CAA0C"}
package/build/text.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as MeasureSpec } from "./measures-CQAuu3T5.js";
1
+ import { a as MeasureSpec } from "./measures-BLoTbQwB.js";
2
2
  /**
3
3
  * The advance function of a host: the width of a run of text in a font, in pixels.
4
4
  * A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.
@@ -69,6 +69,11 @@ export interface TextLayoutOptions {
69
69
  * `anywhere` breaks it between two grapheme clusters, as the CSS `overflow-wrap: anywhere`.
70
70
  */
71
71
  readonly wordBreak?: "keep" | "anywhere";
72
+ /**
73
+ * The line breaker of `@mark1russell7/typeset`. `greedy` (the default) fills each line, as a browser. `total-fit` (Knuth and Plass)
74
+ * makes the lines more equal. `balanced` keeps the greedy line count with the least width.
75
+ */
76
+ readonly breaker?: "greedy" | "total-fit" | "balanced";
72
77
  }
73
78
  /** The layout of a text: its lines and its box. */
74
79
  export interface TextLayout {
@@ -87,7 +92,8 @@ export interface TextLayout {
87
92
  /**
88
93
  * This function lays out a text. It cuts the text to `maxChars`. It keeps the text on one line when it fits in `maxWidth`. Else it breaks the text into lines of `wrapWidth`.
89
94
  *
90
- * The breaker is greedy, as a browser with `white-space: normal`. It collapses each run of white space to one space, and a line does not count its last space.
95
+ * The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.
96
+ * It collapses each run of white space to one space, and a line does not count its last space.
91
97
  * The width of a word is the sum of the advances of its segments. `docs/TEXT.md` gives the rules and the error of this sum.
92
98
  */
93
99
  export declare function layoutText(text: string, options: TextLayoutOptions): TextLayout;
@@ -1 +1 @@
1
- {"version":3,"file":"text.d.ts","names":[],"sources":["../src/text.ts"],"mappings":";;;;;YAMY,aAAa,cAAc;;qBAG1B;;iBAGI;WACN;WACA;WACA;;;iBAIM;;EAEf,QAAQ,iBAAiB;;EAEzB,SAAS;;EAET;;;iBAIe;;WAEN;;;wBAIK,QAAQ;;;;;wBAQR,eAAe,SAAS,WAAW,UAAS,kBAAuB;;iBAqClE;EACf;EACA,YAAY;aAA0B;;;;wBAIxB,cAAc,SAAS,oBAAoB;;wBAwE3C,YAAY;;iBAOX;WACN;WACA,UAAU;;WAEV;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;;;iBAIM;WACN;;WAEA;WACA;;WAEA;WACA;;WAEA;;WAEA;;;;;;;;wBAeK,WAAW,cAAc,SAAS,oBAAoB;;YA+F1D;;qBAGC,wBAAwB,YAAY;;;;;;wBAajC,aAAa,QAAQ,YAAY,QAAQ,gBAAgB,QAAQ,OAAO"}
1
+ {"version":3,"file":"text.d.ts","names":[],"sources":["../src/text.ts"],"mappings":";;;;;YAOY,aAAa,cAAc;;qBAG1B;;iBAGI;WACN;WACA;WACA;;;iBAIM;;EAEf,QAAQ,iBAAiB;;EAEzB,SAAS;;EAET;;;iBAIe;;WAEN;;;wBAIK,QAAQ;;;;;wBAQR,eAAe,SAAS,WAAW,UAAS,kBAAuB;;iBAqClE;EACf;EACA,YAAY;aAA0B;;;;wBAIxB,cAAc,SAAS,oBAAoB;;wBAwE3C,YAAY;;iBAOX;WACN;WACA,UAAU;;WAEV;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;;;;;WAKA;;;iBAIM;WACN;;WAEA;WACA;;WAEA;WACA;;WAEA;;WAEA;;;;;;;;;wBAwBK,WAAW,cAAc,SAAS,oBAAoB;;YAkG1D;;qBAGC,wBAAwB,YAAY;;;;;;wBAajC,aAAa,QAAQ,YAAY,QAAQ,gBAAgB,QAAQ,OAAO"}
package/build/text.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { breakers, linesOf } from "@mark1russell7/typeset/breaking";
1
2
  // src/text.ts
2
3
  /** The count of the units in one pixel. Each advance is a whole number of units, so each sum is exact and each port gets the same pixels. */
3
4
  const TEXT_UNITS = 64;
@@ -108,10 +109,27 @@ function graphemesOf(text) {
108
109
  if (segmenter !== null) return Array.from(segmenter.segment(text), (s) => s.segment);
109
110
  return Array.from(text);
110
111
  }
112
+ /** A forced break: a penalty with no text, no width and the cost `-Infinity`. */
113
+ const FORCED = {
114
+ type: "penalty",
115
+ text: "",
116
+ width: 0,
117
+ cost: -Infinity,
118
+ flagged: false
119
+ };
120
+ /** This function gives the box of a part of a word. */
121
+ function boxOf(part) {
122
+ return {
123
+ type: "box",
124
+ text: part.text,
125
+ width: part.width
126
+ };
127
+ }
111
128
  /**
112
129
  * This function lays out a text. It cuts the text to `maxChars`. It keeps the text on one line when it fits in `maxWidth`. Else it breaks the text into lines of `wrapWidth`.
113
130
  *
114
- * The breaker is greedy, as a browser with `white-space: normal`. It collapses each run of white space to one space, and a line does not count its last space.
131
+ * The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.
132
+ * It collapses each run of white space to one space, and a line does not count its last space.
115
133
  * The width of a word is the sum of the advances of its segments. `docs/TEXT.md` gives the rules and the error of this sum.
116
134
  */
117
135
  function layoutText(text, options) {
@@ -120,6 +138,9 @@ function layoutText(text, options) {
120
138
  const ellipsis = options.ellipsis ?? "…";
121
139
  const padding = options.padding ?? 0;
122
140
  const keep = (options.wordBreak ?? "keep") === "keep";
141
+ const name = options.breaker ?? "greedy";
142
+ if (!Object.hasOwn(breakers, name)) throw new RangeError(`layoutText: breaker is "greedy", "total-fit" or "balanced", not ${String(name)}.`);
143
+ const breaker = breakers[name];
123
144
  let truncated = false;
124
145
  let source = text;
125
146
  if (options.maxChars !== void 0) {
@@ -155,42 +176,49 @@ function layoutText(text, options) {
155
176
  };
156
177
  }
157
178
  const limit = Math.round(options.wrapWidth * 64);
158
- const lines = [];
159
- let cur;
160
- const push = () => {
161
- if (cur !== void 0) lines.push(cur);
162
- cur = void 0;
163
- };
164
- /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. */
179
+ const items = [];
180
+ /** 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. */
165
181
  const split = (word) => {
182
+ if (items.length > 0) items.push(FORCED);
183
+ let cur;
166
184
  for (const g of graphemesOf(word.text)) {
167
185
  const w = measurer.advance(g, font);
168
- if (cur !== void 0 && cur.units + w > limit) push();
186
+ if (cur !== void 0 && cur.width + w > limit) {
187
+ items.push(boxOf(cur), FORCED);
188
+ cur = void 0;
189
+ }
169
190
  if (cur === void 0) cur = {
170
191
  text: g,
171
- units: w
192
+ width: w
172
193
  };
173
194
  else {
174
195
  cur.text += g;
175
- cur.units += w;
196
+ cur.width += w;
176
197
  }
177
198
  }
199
+ if (cur !== void 0) items.push(boxOf(cur));
178
200
  };
179
201
  words.forEach((word, i) => {
180
202
  const w = widths[i];
181
- if (cur !== void 0 && cur.units + space + w <= limit) {
182
- cur.text += ` ${word.text}`;
183
- cur.units += space + w;
184
- return;
185
- }
186
- push();
187
203
  if (w > limit && !keep) split(word);
188
- else cur = {
189
- text: word.text,
190
- units: w
191
- };
204
+ else {
205
+ if (items.length > 0) items.push({
206
+ type: "glue",
207
+ text: " ",
208
+ width: space
209
+ });
210
+ items.push({
211
+ type: "box",
212
+ text: word.text,
213
+ width: w
214
+ });
215
+ }
192
216
  });
193
- push();
217
+ const paragraph = { items };
218
+ const lines = linesOf(paragraph, breaker.breaks(paragraph, limit)).map((l) => ({
219
+ text: l.text,
220
+ units: l.width
221
+ }));
194
222
  if (lines.length === 0) lines.push({
195
223
  text: "",
196
224
  units: 0
package/build/text.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"text.js","names":[],"sources":["../src/text.ts"],"sourcesContent":["import type { MeasureSpec } from \"./measures.ts\";\n\n/**\n * The advance function of a host: the width of a run of text in a font, in pixels.\n * A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.\n */\nexport type AdvanceFn = (text: string, font: string) => number;\n\n/** The count of the units in one pixel. Each advance is a whole number of units, so each sum is exact and each port gets the same pixels. */\nexport const TEXT_UNITS = 64;\n\n/** The counts of a measurer: the requests, the cache hits and the calls of the advance function. */\nexport interface MeasurerStats {\n readonly requests: number;\n readonly hits: number;\n readonly calls: number;\n}\n\n/** A measurer: the advance of a segment in a font, in whole units of 1/`TEXT_UNITS` pixel, with a cache. */\nexport interface TextMeasurer {\n /** This function gives the advance of the segment in the font, in units. */\n advance(segment: string, font: string): number;\n /** This function gives the counts since the start or since the last `reset`. */\n stats(): MeasurerStats;\n /** This function clears the cache and the counts. */\n reset(): void;\n}\n\n/** The options of `createMeasurer`. */\nexport interface MeasurerOptions {\n /** The count of the cache entries. The default is 10000. With 0, the measurer has no cache. */\n readonly maxEntries?: number;\n}\n\n/** This function gives the key of a font: the font string with its white space collapsed and trimmed. */\nexport function fontKey(font: string): string {\n return font.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * This function gives a measurer with a cache keyed by the font and the segment.\n * The cache removes its oldest entry when it is full. The advance function rounds each width to whole units.\n */\nexport function createMeasurer(measure: AdvanceFn, options: MeasurerOptions = {}): TextMeasurer {\n const max = options.maxEntries ?? 10000;\n if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createMeasurer: maxEntries is an integer of 0 or more, not ${max}.`);\n const cache = new Map<string, number>();\n let requests = 0;\n let hits = 0;\n let calls = 0;\n return {\n advance(segment, font) {\n requests++;\n const key = `${fontKey(font)}\\u0000${segment}`;\n const known = cache.get(key);\n if (known !== undefined) {\n hits++;\n return known;\n }\n calls++;\n const px = measure(segment, font);\n if (!Number.isFinite(px) || px < 0) throw new RangeError(`The advance of \"${segment}\" in \"${font}\" is ${px}, not a finite number of 0 or more.`);\n const units = Math.round(px * TEXT_UNITS);\n if (max > 0) {\n if (cache.size >= max) cache.delete(cache.keys().next().value!);\n cache.set(key, units);\n }\n return units;\n },\n stats: () => ({ requests, hits, calls }),\n reset() {\n cache.clear();\n requests = 0;\n hits = 0;\n calls = 0;\n },\n };\n}\n\n/** The part of a canvas context that `canvasAdvance` uses. */\nexport interface CanvasTextContext {\n font: string;\n measureText(text: string): { readonly width: number };\n}\n\n/** This function gives the advance function of a canvas context. It sets `font` only when the font changes, because a browser parses each new font string. */\nexport function canvasAdvance(context: CanvasTextContext): AdvanceFn {\n let current: string | undefined;\n return (text, font) => {\n if (font !== current) {\n context.font = font;\n current = font;\n }\n return context.measureText(text).width;\n };\n}\n\n/** A word of a text: its segments, which the measurer measures and caches one by one. */\ninterface Word {\n readonly text: string;\n readonly parts: readonly string[];\n}\n\nconst SPACE = /^\\s+$/u;\n\n/** The segmenters of the module. A new `Intl.Segmenter` loads the data of the locale, so the module makes each granularity only once. */\nconst segmenters = new Map<\"word\" | \"grapheme\", Intl.Segmenter | null>();\n\n/** This function gives the segmenter of a granularity, or `null` without `Intl.Segmenter`. */\nfunction segmenterOf(granularity: \"word\" | \"grapheme\"): Intl.Segmenter | null {\n let s = segmenters.get(granularity);\n if (s === undefined) {\n s = typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\" ? new Intl.Segmenter(undefined, { granularity }) : null;\n segmenters.set(granularity, s);\n }\n return s;\n}\n\n/** The largest count of texts in the memo of `wordsOf`. A page often asks for the same labels many times. */\nconst WORDS_MEMO = 4096;\nconst wordsMemo = new Map<string, readonly Word[]>();\n\n/** 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. */\nfunction wordsOf(text: string): readonly Word[] {\n const known = wordsMemo.get(text);\n if (known !== undefined) return known;\n const words = splitWords(text);\n // The memo forgets its oldest text when it is full.\n if (wordsMemo.size >= WORDS_MEMO) wordsMemo.delete(wordsMemo.keys().next().value!);\n wordsMemo.set(text, words);\n return words;\n}\n\n/** This function gives the words of `wordsOf` with no memo. */\nfunction splitWords(text: string): Word[] {\n const words: Word[] = [];\n let parts: string[] = [];\n const flush = (): void => {\n if (parts.length > 0) words.push({ text: parts.join(\"\"), parts });\n parts = [];\n };\n const segmenter = segmenterOf(\"word\");\n if (segmenter !== null) {\n for (const s of segmenter.segment(text)) {\n if (SPACE.test(s.segment)) flush();\n else parts.push(s.segment);\n }\n } else {\n for (const s of text.split(/(\\s+)/u)) {\n if (s === \"\" || SPACE.test(s)) flush();\n else parts.push(s);\n }\n }\n flush();\n return words;\n}\n\n/** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */\nexport function graphemesOf(text: string): string[] {\n const segmenter = segmenterOf(\"grapheme\");\n if (segmenter !== null) return Array.from(segmenter.segment(text), (s) => s.segment);\n return Array.from(text);\n}\n\n/** The options of `layoutText`. All lengths are in pixels. */\nexport interface TextLayoutOptions {\n readonly font: string;\n readonly measurer: TextMeasurer;\n /** The line height. A finite number above 0. */\n readonly lineHeight: number;\n /** The width of the lines of a text that does not fit on one line. Without it, the text stays on one line. */\n readonly wrapWidth?: number;\n /** The count of the lines. The last line that stays gets the ellipsis. The default is no limit. */\n readonly maxLines?: number;\n /** The count of the grapheme clusters. A longer text keeps `maxChars` clusters with the ellipsis at the end. The default is no limit. */\n readonly maxChars?: number;\n /** The text at the end of a cut text. The default is \"…\". */\n readonly ellipsis?: string;\n /** The space that the box adds to the width of the text. The default is 0. */\n readonly padding?: number;\n /** The smallest width of a box with one line. The default is 0. */\n readonly minWidth?: number;\n /** The largest width of a box with one line. A text that does not fit wraps at `wrapWidth`. The default is `wrapWidth` plus the padding, or no limit without `wrapWidth`. */\n readonly maxWidth?: number;\n /**\n * The break of a word that is wider than a line. `keep` (the default) keeps the word whole, and the line overflows.\n * `anywhere` breaks it between two grapheme clusters, as the CSS `overflow-wrap: anywhere`.\n */\n readonly wordBreak?: \"keep\" | \"anywhere\";\n}\n\n/** The layout of a text: its lines and its box. */\nexport interface TextLayout {\n readonly lines: readonly string[];\n /** The width of each line, in pixels. Each width is a whole number of units of 1/`TEXT_UNITS` pixel. */\n readonly widths: readonly number[];\n readonly lineCount: number;\n /** The width of the box: the text and the padding. */\n readonly width: number;\n readonly height: number;\n /** The width of the lines, or `undefined` for a text on one line. */\n readonly wrapWidth?: number;\n /** `true` when `maxChars` or `maxLines` cut the text. */\n readonly truncated: boolean;\n}\n\n/** A line of a layout, with its width in units. */\ninterface Line {\n text: string;\n units: number;\n}\n\n/**\n * This function lays out a text. It cuts the text to `maxChars`. It keeps the text on one line when it fits in `maxWidth`. Else it breaks the text into lines of `wrapWidth`.\n *\n * The breaker is greedy, as a browser with `white-space: normal`. It collapses each run of white space to one space, and a line does not count its last space.\n * The width of a word is the sum of the advances of its segments. `docs/TEXT.md` gives the rules and the error of this sum.\n */\nexport function layoutText(text: string, options: TextLayoutOptions): TextLayout {\n const { font, measurer, lineHeight } = options;\n if (!(Number.isFinite(lineHeight) && lineHeight > 0)) throw new RangeError(`layoutText: lineHeight is a finite number above 0, not ${lineHeight}.`);\n const ellipsis = options.ellipsis ?? \"…\";\n const padding = options.padding ?? 0;\n const keep = (options.wordBreak ?? \"keep\") === \"keep\";\n let truncated = false;\n\n let source = text;\n if (options.maxChars !== undefined) {\n const clusters = graphemesOf(source);\n if (clusters.length > options.maxChars) {\n const room = Math.max(0, options.maxChars - graphemesOf(ellipsis).length);\n source = clusters.slice(0, room).join(\"\") + ellipsis;\n truncated = true;\n }\n }\n\n const words = wordsOf(source);\n const space = measurer.advance(\" \", font);\n const width = (w: Word): number => w.parts.reduce((s, p) => s + measurer.advance(p, font), 0);\n const lineUnits = (line: string): number => {\n const ws = wordsOf(line);\n return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);\n };\n const widths = words.map(width);\n const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);\n\n const maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);\n const fits = natural / TEXT_UNITS + padding <= maxWidth;\n if (options.wrapWidth === undefined || fits) {\n const one = words.map((w) => w.text).join(\" \");\n const px = natural / TEXT_UNITS;\n const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));\n return { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };\n }\n\n const limit = Math.round(options.wrapWidth * TEXT_UNITS);\n const lines: Line[] = [];\n let cur: Line | undefined;\n const push = (): void => {\n if (cur !== undefined) lines.push(cur);\n cur = undefined;\n };\n /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. */\n const split = (word: Word): void => {\n for (const g of graphemesOf(word.text)) {\n const w = measurer.advance(g, font);\n if (cur !== undefined && cur.units + w > limit) push();\n if (cur === undefined) cur = { text: g, units: w };\n else {\n cur.text += g;\n cur.units += w;\n }\n }\n };\n words.forEach((word, i) => {\n const w = widths[i]!;\n if (cur !== undefined && cur.units + space + w <= limit) {\n cur.text += ` ${word.text}`;\n cur.units += space + w;\n return;\n }\n push();\n if (w > limit && !keep) split(word);\n else cur = { text: word.text, units: w };\n });\n push();\n if (lines.length === 0) lines.push({ text: \"\", units: 0 });\n\n const maxLines = options.maxLines ?? Infinity;\n if (lines.length > maxLines) {\n lines.length = Math.max(1, maxLines);\n const last = lines[lines.length - 1]!;\n const tail = measurer.advance(ellipsis, font);\n const clusters = graphemesOf(last.text);\n while (clusters.length > 0 && lineUnits(clusters.join(\"\")) + tail > limit) clusters.pop();\n const kept = clusters.join(\"\").replace(/\\s+$/u, \"\");\n last.text = kept + ellipsis;\n last.units = lineUnits(kept) + tail;\n truncated = true;\n }\n\n return {\n lines: lines.map((l) => l.text),\n widths: lines.map((l) => l.units / TEXT_UNITS),\n lineCount: lines.length,\n width: options.wrapWidth + padding,\n height: lines.length * lineHeight,\n wrapWidth: options.wrapWidth,\n truncated,\n };\n}\n\n/** The id of a text measure. `docs/TEXT.md` gives the definitions. */\nexport type TextMeasureId = \"text.lines\" | \"text.raggedness\" | \"text.overflow\" | \"text.cacheHit\" | \"text.ms\";\n\n/** The specs of the text measures. */\nexport const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[] = Object.freeze([\n { id: \"text.lines\", unit: \"count\", direction: \"lower\", min: 1, max: Infinity, minEffect: 0, family: \"text\" },\n { id: \"text.raggedness\", unit: \"0 to 1\", direction: \"lower\", min: 0, max: 1, minEffect: 0.005, family: \"text\" },\n { id: \"text.overflow\", unit: \"share of the wrap width\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0, minEffect: 0, family: \"text\", role: \"guard\" },\n { id: \"text.cacheHit\", unit: \"0 to 1\", direction: \"higher\", min: 0, max: 1, family: \"text\", role: \"diagnostic\" },\n { id: \"text.ms\", unit: \"milliseconds\", direction: \"lower\", min: 0, max: Infinity, family: \"text\", role: \"time\" },\n] as const);\n\n/**\n * This function gives the measures of a layout. `text.raggedness` is the mean of `((wrapWidth - width) / wrapWidth)^2` over the lines before the last line.\n * `text.overflow` is the largest excess of a line over `wrapWidth`, as a share of `wrapWidth`. A text on one line gives 0 for the two values.\n * With `stats`, the measures also hold `text.cacheHit`: the hits divided by the requests.\n */\nexport function textMeasures(layout: TextLayout, stats?: MeasurerStats): Partial<Record<TextMeasureId, number>> {\n const w = layout.wrapWidth;\n const body = layout.widths.slice(0, -1);\n const raggedness = w === undefined || body.length === 0 ? 0 : body.reduce((s, x) => s + (Math.max(0, w - x) / w) ** 2, 0) / body.length;\n const overflow = w === undefined ? 0 : Math.max(0, ...layout.widths.map((x) => (x - w) / w));\n return {\n \"text.lines\": layout.lineCount,\n \"text.raggedness\": raggedness,\n \"text.overflow\": overflow,\n ...(stats === undefined ? {} : { \"text.cacheHit\": stats.requests === 0 ? 0 : stats.hits / stats.requests }),\n };\n}\n"],"mappings":";;AASA,MAAa,aAAa;;AA0B1B,SAAgB,QAAQ,MAAsB;CAC5C,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,GAAG;AACxC;;;;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a,QAAoB,OAA+D;CAC9G,MAAM,IAAI,OAAO;CACjB,MAAM,OAAO,OAAO,OAAO,MAAM,GAAG,EAAE;CACtC,MAAM,aAAa,MAAM,KAAA,KAAa,KAAK,WAAW,IAAI,IAAI,KAAK,QAAQ,GAAG,MAAM,KAAK,KAAK,IAAI,GAAG,IAAI,CAAC,IAAI,MAAM,GAAG,CAAC,IAAI,KAAK;CACjI,MAAM,WAAW,MAAM,KAAA,IAAY,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO,OAAO,KAAK,OAAO,IAAI,KAAK,CAAC,CAAC;CAC3F,OAAO;EACL,cAAc,OAAO;EACrB,mBAAmB;EACnB,iBAAiB;EACjB,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,MAAM,aAAa,IAAI,IAAI,MAAM,OAAO,MAAM,SAAS;CAC3G;AACF"}
1
+ {"version":3,"file":"text.js","names":[],"sources":["../src/text.ts"],"sourcesContent":["import { breakers, linesOf, type Box, type Item, type Penalty } from \"@mark1russell7/typeset/breaking\";\nimport type { MeasureSpec } from \"./measures.ts\";\n\n/**\n * The advance function of a host: the width of a run of text in a font, in pixels.\n * A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.\n */\nexport type AdvanceFn = (text: string, font: string) => number;\n\n/** The count of the units in one pixel. Each advance is a whole number of units, so each sum is exact and each port gets the same pixels. */\nexport const TEXT_UNITS = 64;\n\n/** The counts of a measurer: the requests, the cache hits and the calls of the advance function. */\nexport interface MeasurerStats {\n readonly requests: number;\n readonly hits: number;\n readonly calls: number;\n}\n\n/** A measurer: the advance of a segment in a font, in whole units of 1/`TEXT_UNITS` pixel, with a cache. */\nexport interface TextMeasurer {\n /** This function gives the advance of the segment in the font, in units. */\n advance(segment: string, font: string): number;\n /** This function gives the counts since the start or since the last `reset`. */\n stats(): MeasurerStats;\n /** This function clears the cache and the counts. */\n reset(): void;\n}\n\n/** The options of `createMeasurer`. */\nexport interface MeasurerOptions {\n /** The count of the cache entries. The default is 10000. With 0, the measurer has no cache. */\n readonly maxEntries?: number;\n}\n\n/** This function gives the key of a font: the font string with its white space collapsed and trimmed. */\nexport function fontKey(font: string): string {\n return font.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * This function gives a measurer with a cache keyed by the font and the segment.\n * The cache removes its oldest entry when it is full. The advance function rounds each width to whole units.\n */\nexport function createMeasurer(measure: AdvanceFn, options: MeasurerOptions = {}): TextMeasurer {\n const max = options.maxEntries ?? 10000;\n if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createMeasurer: maxEntries is an integer of 0 or more, not ${max}.`);\n const cache = new Map<string, number>();\n let requests = 0;\n let hits = 0;\n let calls = 0;\n return {\n advance(segment, font) {\n requests++;\n const key = `${fontKey(font)}\\u0000${segment}`;\n const known = cache.get(key);\n if (known !== undefined) {\n hits++;\n return known;\n }\n calls++;\n const px = measure(segment, font);\n if (!Number.isFinite(px) || px < 0) throw new RangeError(`The advance of \"${segment}\" in \"${font}\" is ${px}, not a finite number of 0 or more.`);\n const units = Math.round(px * TEXT_UNITS);\n if (max > 0) {\n if (cache.size >= max) cache.delete(cache.keys().next().value!);\n cache.set(key, units);\n }\n return units;\n },\n stats: () => ({ requests, hits, calls }),\n reset() {\n cache.clear();\n requests = 0;\n hits = 0;\n calls = 0;\n },\n };\n}\n\n/** The part of a canvas context that `canvasAdvance` uses. */\nexport interface CanvasTextContext {\n font: string;\n measureText(text: string): { readonly width: number };\n}\n\n/** This function gives the advance function of a canvas context. It sets `font` only when the font changes, because a browser parses each new font string. */\nexport function canvasAdvance(context: CanvasTextContext): AdvanceFn {\n let current: string | undefined;\n return (text, font) => {\n if (font !== current) {\n context.font = font;\n current = font;\n }\n return context.measureText(text).width;\n };\n}\n\n/** A word of a text: its segments, which the measurer measures and caches one by one. */\ninterface Word {\n readonly text: string;\n readonly parts: readonly string[];\n}\n\nconst SPACE = /^\\s+$/u;\n\n/** The segmenters of the module. A new `Intl.Segmenter` loads the data of the locale, so the module makes each granularity only once. */\nconst segmenters = new Map<\"word\" | \"grapheme\", Intl.Segmenter | null>();\n\n/** This function gives the segmenter of a granularity, or `null` without `Intl.Segmenter`. */\nfunction segmenterOf(granularity: \"word\" | \"grapheme\"): Intl.Segmenter | null {\n let s = segmenters.get(granularity);\n if (s === undefined) {\n s = typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\" ? new Intl.Segmenter(undefined, { granularity }) : null;\n segmenters.set(granularity, s);\n }\n return s;\n}\n\n/** The largest count of texts in the memo of `wordsOf`. A page often asks for the same labels many times. */\nconst WORDS_MEMO = 4096;\nconst wordsMemo = new Map<string, readonly Word[]>();\n\n/** 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. */\nfunction wordsOf(text: string): readonly Word[] {\n const known = wordsMemo.get(text);\n if (known !== undefined) return known;\n const words = splitWords(text);\n // The memo forgets its oldest text when it is full.\n if (wordsMemo.size >= WORDS_MEMO) wordsMemo.delete(wordsMemo.keys().next().value!);\n wordsMemo.set(text, words);\n return words;\n}\n\n/** This function gives the words of `wordsOf` with no memo. */\nfunction splitWords(text: string): Word[] {\n const words: Word[] = [];\n let parts: string[] = [];\n const flush = (): void => {\n if (parts.length > 0) words.push({ text: parts.join(\"\"), parts });\n parts = [];\n };\n const segmenter = segmenterOf(\"word\");\n if (segmenter !== null) {\n for (const s of segmenter.segment(text)) {\n if (SPACE.test(s.segment)) flush();\n else parts.push(s.segment);\n }\n } else {\n for (const s of text.split(/(\\s+)/u)) {\n if (s === \"\" || SPACE.test(s)) flush();\n else parts.push(s);\n }\n }\n flush();\n return words;\n}\n\n/** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */\nexport function graphemesOf(text: string): string[] {\n const segmenter = segmenterOf(\"grapheme\");\n if (segmenter !== null) return Array.from(segmenter.segment(text), (s) => s.segment);\n return Array.from(text);\n}\n\n/** The options of `layoutText`. All lengths are in pixels. */\nexport interface TextLayoutOptions {\n readonly font: string;\n readonly measurer: TextMeasurer;\n /** The line height. A finite number above 0. */\n readonly lineHeight: number;\n /** The width of the lines of a text that does not fit on one line. Without it, the text stays on one line. */\n readonly wrapWidth?: number;\n /** The count of the lines. The last line that stays gets the ellipsis. The default is no limit. */\n readonly maxLines?: number;\n /** The count of the grapheme clusters. A longer text keeps `maxChars` clusters with the ellipsis at the end. The default is no limit. */\n readonly maxChars?: number;\n /** The text at the end of a cut text. The default is \"…\". */\n readonly ellipsis?: string;\n /** The space that the box adds to the width of the text. The default is 0. */\n readonly padding?: number;\n /** The smallest width of a box with one line. The default is 0. */\n readonly minWidth?: number;\n /** The largest width of a box with one line. A text that does not fit wraps at `wrapWidth`. The default is `wrapWidth` plus the padding, or no limit without `wrapWidth`. */\n readonly maxWidth?: number;\n /**\n * The break of a word that is wider than a line. `keep` (the default) keeps the word whole, and the line overflows.\n * `anywhere` breaks it between two grapheme clusters, as the CSS `overflow-wrap: anywhere`.\n */\n readonly wordBreak?: \"keep\" | \"anywhere\";\n /**\n * The line breaker of `@mark1russell7/typeset`. `greedy` (the default) fills each line, as a browser. `total-fit` (Knuth and Plass)\n * makes the lines more equal. `balanced` keeps the greedy line count with the least width.\n */\n readonly breaker?: \"greedy\" | \"total-fit\" | \"balanced\";\n}\n\n/** The layout of a text: its lines and its box. */\nexport interface TextLayout {\n readonly lines: readonly string[];\n /** The width of each line, in pixels. Each width is a whole number of units of 1/`TEXT_UNITS` pixel. */\n readonly widths: readonly number[];\n readonly lineCount: number;\n /** The width of the box: the text and the padding. */\n readonly width: number;\n readonly height: number;\n /** The width of the lines, or `undefined` for a text on one line. */\n readonly wrapWidth?: number;\n /** `true` when `maxChars` or `maxLines` cut the text. */\n readonly truncated: boolean;\n}\n\n/** A forced break: a penalty with no text, no width and the cost `-Infinity`. */\nconst FORCED: Penalty = { type: \"penalty\", text: \"\", width: 0, cost: -Infinity, flagged: false };\n\n/** This function gives the box of a part of a word. */\nfunction boxOf(part: { readonly text: string; readonly width: number }): Box {\n return { type: \"box\", text: part.text, width: part.width };\n}\n\n/** A line of a layout, with its width in units. */\ninterface Line {\n text: string;\n units: number;\n}\n\n/**\n * This function lays out a text. It cuts the text to `maxChars`. It keeps the text on one line when it fits in `maxWidth`. Else it breaks the text into lines of `wrapWidth`.\n *\n * The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.\n * It collapses each run of white space to one space, and a line does not count its last space.\n * The width of a word is the sum of the advances of its segments. `docs/TEXT.md` gives the rules and the error of this sum.\n */\nexport function layoutText(text: string, options: TextLayoutOptions): TextLayout {\n const { font, measurer, lineHeight } = options;\n if (!(Number.isFinite(lineHeight) && lineHeight > 0)) throw new RangeError(`layoutText: lineHeight is a finite number above 0, not ${lineHeight}.`);\n const ellipsis = options.ellipsis ?? \"…\";\n const padding = options.padding ?? 0;\n const keep = (options.wordBreak ?? \"keep\") === \"keep\";\n const name = options.breaker ?? \"greedy\";\n if (!Object.hasOwn(breakers, name)) throw new RangeError(`layoutText: breaker is \"greedy\", \"total-fit\" or \"balanced\", not ${String(name)}.`);\n const breaker = breakers[name];\n let truncated = false;\n\n let source = text;\n if (options.maxChars !== undefined) {\n const clusters = graphemesOf(source);\n if (clusters.length > options.maxChars) {\n const room = Math.max(0, options.maxChars - graphemesOf(ellipsis).length);\n source = clusters.slice(0, room).join(\"\") + ellipsis;\n truncated = true;\n }\n }\n\n const words = wordsOf(source);\n const space = measurer.advance(\" \", font);\n const width = (w: Word): number => w.parts.reduce((s, p) => s + measurer.advance(p, font), 0);\n const lineUnits = (line: string): number => {\n const ws = wordsOf(line);\n return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);\n };\n const widths = words.map(width);\n const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);\n\n const maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);\n const fits = natural / TEXT_UNITS + padding <= maxWidth;\n if (options.wrapWidth === undefined || fits) {\n const one = words.map((w) => w.text).join(\" \");\n const px = natural / TEXT_UNITS;\n const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));\n return { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };\n }\n\n const limit = Math.round(options.wrapWidth * TEXT_UNITS);\n // The items of the breaker: a box for each word, and glue of one space between two words.\n const items: Item[] = [];\n /** 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. */\n const split = (word: Word): void => {\n if (items.length > 0) items.push(FORCED);\n let cur: { text: string; width: number } | undefined;\n for (const g of graphemesOf(word.text)) {\n const w = measurer.advance(g, font);\n if (cur !== undefined && cur.width + w > limit) {\n items.push(boxOf(cur), FORCED);\n cur = undefined;\n }\n if (cur === undefined) cur = { text: g, width: w };\n else {\n cur.text += g;\n cur.width += w;\n }\n }\n if (cur !== undefined) items.push(boxOf(cur));\n };\n words.forEach((word, i) => {\n const w = widths[i]!;\n if (w > limit && !keep) split(word);\n else {\n if (items.length > 0) items.push({ type: \"glue\", text: \" \", width: space });\n items.push({ type: \"box\", text: word.text, width: w });\n }\n });\n const paragraph = { items };\n const lines: Line[] = linesOf(paragraph, breaker.breaks(paragraph, limit)).map((l) => ({ text: l.text, units: l.width }));\n if (lines.length === 0) lines.push({ text: \"\", units: 0 });\n\n const maxLines = options.maxLines ?? Infinity;\n if (lines.length > maxLines) {\n lines.length = Math.max(1, maxLines);\n const last = lines[lines.length - 1]!;\n const tail = measurer.advance(ellipsis, font);\n const clusters = graphemesOf(last.text);\n while (clusters.length > 0 && lineUnits(clusters.join(\"\")) + tail > limit) clusters.pop();\n const kept = clusters.join(\"\").replace(/\\s+$/u, \"\");\n last.text = kept + ellipsis;\n last.units = lineUnits(kept) + tail;\n truncated = true;\n }\n\n return {\n lines: lines.map((l) => l.text),\n widths: lines.map((l) => l.units / TEXT_UNITS),\n lineCount: lines.length,\n width: options.wrapWidth + padding,\n height: lines.length * lineHeight,\n wrapWidth: options.wrapWidth,\n truncated,\n };\n}\n\n/** The id of a text measure. `docs/TEXT.md` gives the definitions. */\nexport type TextMeasureId = \"text.lines\" | \"text.raggedness\" | \"text.overflow\" | \"text.cacheHit\" | \"text.ms\";\n\n/** The specs of the text measures. */\nexport const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[] = Object.freeze([\n { id: \"text.lines\", unit: \"count\", direction: \"lower\", min: 1, max: Infinity, minEffect: 0, family: \"text\" },\n { id: \"text.raggedness\", unit: \"0 to 1\", direction: \"lower\", min: 0, max: 1, minEffect: 0.005, family: \"text\" },\n { id: \"text.overflow\", unit: \"share of the wrap width\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0, minEffect: 0, family: \"text\", role: \"guard\" },\n { id: \"text.cacheHit\", unit: \"0 to 1\", direction: \"higher\", min: 0, max: 1, family: \"text\", role: \"diagnostic\" },\n { id: \"text.ms\", unit: \"milliseconds\", direction: \"lower\", min: 0, max: Infinity, family: \"text\", role: \"time\" },\n] as const);\n\n/**\n * This function gives the measures of a layout. `text.raggedness` is the mean of `((wrapWidth - width) / wrapWidth)^2` over the lines before the last line.\n * `text.overflow` is the largest excess of a line over `wrapWidth`, as a share of `wrapWidth`. A text on one line gives 0 for the two values.\n * With `stats`, the measures also hold `text.cacheHit`: the hits divided by the requests.\n */\nexport function textMeasures(layout: TextLayout, stats?: MeasurerStats): Partial<Record<TextMeasureId, number>> {\n const w = layout.wrapWidth;\n const body = layout.widths.slice(0, -1);\n const raggedness = w === undefined || body.length === 0 ? 0 : body.reduce((s, x) => s + (Math.max(0, w - x) / w) ** 2, 0) / body.length;\n const overflow = w === undefined ? 0 : Math.max(0, ...layout.widths.map((x) => (x - w) / w));\n return {\n \"text.lines\": layout.lineCount,\n \"text.raggedness\": raggedness,\n \"text.overflow\": overflow,\n ...(stats === undefined ? {} : { \"text.cacheHit\": stats.requests === 0 ? 0 : stats.hits / stats.requests }),\n };\n}\n"],"mappings":";;;AAUA,MAAa,aAAa;;AA0B1B,SAAgB,QAAQ,MAAsB;CAC5C,OAA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/package",
3
3
  "name": "@mark1russell7/layout-contract",
4
- "version": "0.3.0",
4
+ "version": "0.3.2",
5
5
  "description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
6
6
  "keywords": [
7
7
  "layout",
@@ -53,7 +53,12 @@
53
53
  "@types/node": "^26.6.4",
54
54
  "typescript": "^7.0.2",
55
55
  "vitest": "^5.0.3",
56
- "tsdown": "^0.23.1"
56
+ "tsdown": "^0.23.1",
57
+ "layout-contract-0221": "npm:@mark1russell7/layout-contract@0.2.21"
58
+ },
59
+ "dependencies": {
60
+ "@mark1russell7/rigor-generators": "^0.1.0",
61
+ "@mark1russell7/typeset": "^0.1.0"
57
62
  },
58
63
  "scripts": {
59
64
  "build": "tsdown",
package/src/input.ts CHANGED
@@ -182,6 +182,16 @@ export interface LayoutInput {
182
182
  readonly invalidated?: readonly string[];
183
183
  }
184
184
 
185
+ /**
186
+ * A link between two items of a packer input. A graph order of the packer reads the links.
187
+ * `a` and `b` are indexes into `PackInput.items`. The weight is 1 when it has no value.
188
+ */
189
+ export interface PackLink {
190
+ readonly a: number;
191
+ readonly b: number;
192
+ readonly weight?: number;
193
+ }
194
+
185
195
  /** The input of a packer: a `layout-input/1` file without the edges. */
186
196
  export interface PackInput {
187
197
  readonly container: LayoutContainer;
@@ -189,19 +199,57 @@ export interface PackInput {
189
199
  readonly obstacles?: readonly Obstacle[];
190
200
  readonly gap?: number;
191
201
  readonly pairGaps?: readonly PairGap[];
202
+ /** The links between the items. An input without `links` has no graph, and the links have no effect on an order that does not read them. */
203
+ readonly links?: readonly PackLink[];
192
204
  }
193
205
 
194
- /** This function gives the packer input of a file. An input without a container gets `{ fixed: "none" }`, so the packer picks the size. */
195
- export function toPackInput(input: LayoutInput): PackInput {
206
+ /** The options of `toPackInput`. */
207
+ export interface PackInputOptions {
208
+ /** With `true`, the packer input gets the links of `packLinks`. The default is `false`, so the input has no `links`. */
209
+ readonly links?: boolean;
210
+ }
211
+
212
+ /**
213
+ * This function gives the packer input of a file. An input without a container gets `{ fixed: "none" }`, so the packer picks the size.
214
+ * The edges are not in the packer input. With the option `links`, their links are in it.
215
+ */
216
+ export function toPackInput(input: LayoutInput, options: PackInputOptions = {}): PackInput {
196
217
  return {
197
218
  container: input.container ?? { fixed: "none" },
198
219
  items: input.boxes,
199
220
  ...(input.obstacles === undefined ? {} : { obstacles: input.obstacles }),
200
221
  ...(input.gap === undefined ? {} : { gap: input.gap }),
201
222
  ...(input.pairGaps === undefined ? {} : { pairGaps: input.pairGaps }),
223
+ ...(options.links === true ? { links: packLinks(input) } : {}),
202
224
  };
203
225
  }
204
226
 
227
+ /**
228
+ * This function gives the links of the edges of a file, with indexes into `input.boxes`.
229
+ * - Each link has `a` below `b`. The list is sorted by `a` and then by `b`.
230
+ * - The edges of one pair of boxes make one link. Its weight is the count of the edges, and a link of one edge has no weight.
231
+ * - The function does not use an edge to a box that is not in `input.boxes`, or an edge from a box to the same box.
232
+ */
233
+ export function packLinks(input: LayoutInput): PackLink[] {
234
+ const index = new Map<string, number>();
235
+ input.boxes.forEach((box, i) => {
236
+ if (!index.has(box.id)) index.set(box.id, i);
237
+ });
238
+ const count = new Map<string, { a: number; b: number; n: number }>();
239
+ for (const edge of input.edges ?? []) {
240
+ const s = index.get(edge.source);
241
+ const t = index.get(edge.target);
242
+ if (s === undefined || t === undefined || s === t) continue;
243
+ const a = Math.min(s, t);
244
+ const b = Math.max(s, t);
245
+ const key = `${a} ${b}`;
246
+ const c = count.get(key);
247
+ if (c === undefined) count.set(key, { a, b, n: 1 });
248
+ else c.n += 1;
249
+ }
250
+ return [...count.values()].sort((x, y) => x.a - y.a || x.b - y.b).map(({ a, b, n }) => (n === 1 ? { a, b } : { a, b, weight: n }));
251
+ }
252
+
205
253
  /** This function compares two strings by their UTF-16 code units, as `Array.prototype.sort` does without a compare function. */
206
254
  const byCode = (x: string, y: string): number => (x < y ? -1 : x > y ? 1 : 0);
207
255
 
package/src/random.ts CHANGED
@@ -1,17 +1,18 @@
1
+ import { mulberry32 as homeMulberry32 } from "@mark1russell7/rigor-generators";
1
2
  import { utf8 } from "./utf8.ts";
2
3
 
3
- /** This function gives a generator of random numbers in [0, 1). It is `mulberry32`, as in `docs/FORMAT.md` of `packing`. */
4
+ /**
5
+ * This function gives a generator of random numbers in [0, 1). It is `mulberry32`, as in `docs/FORMAT.md` of `packing`.
6
+ * Its home is `@mark1russell7/rigor-generators`. This function keeps the name and the signature of the API.
7
+ */
4
8
  export function mulberry32(seed: number): () => number {
5
- let s = seed >>> 0;
6
- return () => {
7
- s = (s + 0x6d2b79f5) | 0;
8
- let t = Math.imul(s ^ (s >>> 15), 1 | s);
9
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
10
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
11
- };
9
+ return homeMulberry32(seed);
12
10
  }
13
11
 
14
- /** This function gives the FNV-1a hash of 32 bits of the UTF-8 bytes of a string. */
12
+ /**
13
+ * This function gives the FNV-1a hash of 32 bits of the UTF-8 bytes of a string.
14
+ * It stays here because `fnv1a32` of `@mark1russell7/rigor-generators` encodes a lone surrogate as U+FFFD. This function encodes the 3 bytes of its code.
15
+ */
15
16
  export function fnv1a32(text: string): number {
16
17
  let h = 0x811c9dc5;
17
18
  for (const b of utf8(text)) h = Math.imul(h ^ b, 0x01000193) >>> 0;
package/src/text.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { breakers, linesOf, type Box, type Item, type Penalty } from "@mark1russell7/typeset/breaking";
1
2
  import type { MeasureSpec } from "./measures.ts";
2
3
 
3
4
  /**
@@ -187,6 +188,11 @@ export interface TextLayoutOptions {
187
188
  * `anywhere` breaks it between two grapheme clusters, as the CSS `overflow-wrap: anywhere`.
188
189
  */
189
190
  readonly wordBreak?: "keep" | "anywhere";
191
+ /**
192
+ * The line breaker of `@mark1russell7/typeset`. `greedy` (the default) fills each line, as a browser. `total-fit` (Knuth and Plass)
193
+ * makes the lines more equal. `balanced` keeps the greedy line count with the least width.
194
+ */
195
+ readonly breaker?: "greedy" | "total-fit" | "balanced";
190
196
  }
191
197
 
192
198
  /** The layout of a text: its lines and its box. */
@@ -204,6 +210,14 @@ export interface TextLayout {
204
210
  readonly truncated: boolean;
205
211
  }
206
212
 
213
+ /** A forced break: a penalty with no text, no width and the cost `-Infinity`. */
214
+ const FORCED: Penalty = { type: "penalty", text: "", width: 0, cost: -Infinity, flagged: false };
215
+
216
+ /** This function gives the box of a part of a word. */
217
+ function boxOf(part: { readonly text: string; readonly width: number }): Box {
218
+ return { type: "box", text: part.text, width: part.width };
219
+ }
220
+
207
221
  /** A line of a layout, with its width in units. */
208
222
  interface Line {
209
223
  text: string;
@@ -213,7 +227,8 @@ interface Line {
213
227
  /**
214
228
  * This function lays out a text. It cuts the text to `maxChars`. It keeps the text on one line when it fits in `maxWidth`. Else it breaks the text into lines of `wrapWidth`.
215
229
  *
216
- * The breaker is greedy, as a browser with `white-space: normal`. It collapses each run of white space to one space, and a line does not count its last space.
230
+ * The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.
231
+ * It collapses each run of white space to one space, and a line does not count its last space.
217
232
  * The width of a word is the sum of the advances of its segments. `docs/TEXT.md` gives the rules and the error of this sum.
218
233
  */
219
234
  export function layoutText(text: string, options: TextLayoutOptions): TextLayout {
@@ -222,6 +237,9 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
222
237
  const ellipsis = options.ellipsis ?? "…";
223
238
  const padding = options.padding ?? 0;
224
239
  const keep = (options.wordBreak ?? "keep") === "keep";
240
+ const name = options.breaker ?? "greedy";
241
+ if (!Object.hasOwn(breakers, name)) throw new RangeError(`layoutText: breaker is "greedy", "total-fit" or "balanced", not ${String(name)}.`);
242
+ const breaker = breakers[name];
225
243
  let truncated = false;
226
244
 
227
245
  let source = text;
@@ -254,36 +272,36 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
254
272
  }
255
273
 
256
274
  const limit = Math.round(options.wrapWidth * TEXT_UNITS);
257
- const lines: Line[] = [];
258
- let cur: Line | undefined;
259
- const push = (): void => {
260
- if (cur !== undefined) lines.push(cur);
261
- cur = undefined;
262
- };
263
- /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. */
275
+ // The items of the breaker: a box for each word, and glue of one space between two words.
276
+ const items: Item[] = [];
277
+ /** 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. */
264
278
  const split = (word: Word): void => {
279
+ if (items.length > 0) items.push(FORCED);
280
+ let cur: { text: string; width: number } | undefined;
265
281
  for (const g of graphemesOf(word.text)) {
266
282
  const w = measurer.advance(g, font);
267
- if (cur !== undefined && cur.units + w > limit) push();
268
- if (cur === undefined) cur = { text: g, units: w };
283
+ if (cur !== undefined && cur.width + w > limit) {
284
+ items.push(boxOf(cur), FORCED);
285
+ cur = undefined;
286
+ }
287
+ if (cur === undefined) cur = { text: g, width: w };
269
288
  else {
270
289
  cur.text += g;
271
- cur.units += w;
290
+ cur.width += w;
272
291
  }
273
292
  }
293
+ if (cur !== undefined) items.push(boxOf(cur));
274
294
  };
275
295
  words.forEach((word, i) => {
276
296
  const w = widths[i]!;
277
- if (cur !== undefined && cur.units + space + w <= limit) {
278
- cur.text += ` ${word.text}`;
279
- cur.units += space + w;
280
- return;
281
- }
282
- push();
283
297
  if (w > limit && !keep) split(word);
284
- else cur = { text: word.text, units: w };
298
+ else {
299
+ if (items.length > 0) items.push({ type: "glue", text: " ", width: space });
300
+ items.push({ type: "box", text: word.text, width: w });
301
+ }
285
302
  });
286
- push();
303
+ const paragraph = { items };
304
+ const lines: Line[] = linesOf(paragraph, breaker.breaks(paragraph, limit)).map((l) => ({ text: l.text, units: l.width }));
287
305
  if (lines.length === 0) lines.push({ text: "", units: 0 });
288
306
 
289
307
  const maxLines = options.maxLines ?? Infinity;
package/src/utf8.ts CHANGED
@@ -43,7 +43,7 @@ export function utf8Write(text: string, out?: Uint8Array, at = 0): number {
43
43
  return n;
44
44
  }
45
45
 
46
- /** This function gives the UTF-8 bytes of a string. The package has no runtime dependencies, thus it does not use `TextEncoder`. */
46
+ /** This function gives the UTF-8 bytes of a string. It does not use `TextEncoder`, because `TextEncoder` encodes a lone surrogate as U+FFFD. */
47
47
  export function utf8(text: string): Uint8Array {
48
48
  const bytes = new Uint8Array(utf8Write(text));
49
49
  utf8Write(text, bytes);