@mark1russell7/typeset 0.4.0 → 0.5.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.
@@ -1 +1 @@
1
- {"version":3,"file":"breaking.d.ts","names":[],"sources":["../../src/breaking/breakers.ts","../../src/breaking/measures.ts","../../src/breaking.ts"],"mappings":";;;;;UAMiB;WACN;EACT,OAAO,WAAW,WAAW;;;;;;cAOlB,QAAQ;;UAsCJ;;WAEN;;WAEA;;;;;;;;;;;;iBAaK,SAAS,UAAS,kBAAuB;;cAU5C,YAAY;;UAiER;;WAEN;;;;;;iBAOK,gBAAgB,UAAS,kBAAuB;;cAmBnD,UAAU;;cAGV,UAAU,SAAS,4CAA4C;;;;;iBC1K5D,WAAW,gBAAgB,QAAQ;;iBAWnC,OAAO,gBAAgB;;;;;;iBAgBvB,iBAAiB,WAAW,WAAW,gBAAgB,QAAQ;;;;;iBAW/D,WAAW,WAAW,WAAW,gBAAgB,QAAQ"}
1
+ {"version":3,"file":"breaking.d.ts","names":[],"sources":["../../src/breaking/breakers.ts","../../src/breaking/measures.ts","../../src/breaking.ts"],"mappings":";;;;;UAMiB;WACN;EACT,OAAO,WAAW,WAAW;;;;;;cAOlB,QAAQ;;UAsCJ;;WAEN;;WAEA;;;;;;;;;;;;iBAaK,SAAS,UAAS,kBAAuB;;cAU5C,YAAY;;UA+ER;;WAEN;;;;;;iBAOK,gBAAgB,UAAS,kBAAuB;;cAmBnD,UAAU;;cAGV,UAAU,SAAS,4CAA4C;;;;;iBCxL5D,WAAW,gBAAgB,QAAQ;;iBAWnC,OAAO,gBAAgB;;;;;;iBAgBvB,iBAAiB,WAAW,WAAW,gBAAgB,QAAQ;;;;;iBAW/D,WAAW,WAAW,WAAW,gBAAgB,QAAQ"}
@@ -195,6 +195,7 @@ function totalFitBreaks(paragraph, width, linePenalty, flaggedCost) {
195
195
  const over = new Array(nodes.length).fill(justified ? Infinity : 0);
196
196
  over[0] = 0;
197
197
  best[0] = 0;
198
+ const steady = items.every((item) => item.type !== "glue" || (item.shrink ?? 0) <= item.width);
198
199
  for (let a = 0; a < nodes.length - 1; a++) {
199
200
  if (best[a] === Infinity) continue;
200
201
  const start = a === 0 ? 0 : lineStart(items, nodes[a]);
@@ -206,7 +207,7 @@ function totalFitBreaks(paragraph, width, linePenalty, flaggedCost) {
206
207
  const fit = justified ? adjustmentRatio(items, start, end, width) : 0;
207
208
  const overflow = justified ? fit < -1 : used > width;
208
209
  if (overflow && b > a + 1) {
209
- if (items[end]?.type === "penalty") continue;
210
+ if (items[end]?.type === "penalty" && !(steady && leastWidth(items, start, end, used, justified) > width)) continue;
210
211
  break;
211
212
  }
212
213
  const penalty = items[end];
@@ -230,6 +231,16 @@ function totalFitBreaks(paragraph, width, linePenalty, flaggedCost) {
230
231
  for (let b = previous[nodes.length - 1]; b > 0; b = previous[b]) breaks.push(nodes[b]);
231
232
  return breaks.reverse();
232
233
  }
234
+ /**
235
+ * This function gives the least width of the line from `start` to `end`, without the text of the penalty at `end`. It is
236
+ * the width `used` less that text, and less the shrink of the glue for a justified edge. A later break of the line has no
237
+ * smaller least width when no glue shrinks by more than its width.
238
+ */
239
+ function leastWidth(items, start, end, used, justified) {
240
+ let least = used - items[end].width;
241
+ if (justified) for (let i = start; i < end; i++) least -= items[i].type === "glue" ? items[i].shrink ?? 0 : 0;
242
+ return least;
243
+ }
233
244
  /** This function tells if the item `index` is a flagged penalty. */
234
245
  function isFlagged(paragraph, index) {
235
246
  const item = paragraph.items[index];
@@ -1 +1 @@
1
- {"version":3,"file":"breaking.js","names":[],"sources":["../../src/breaking/paragraph.ts","../../src/breaking/breakers.ts","../../src/breaking/measures.ts","../../src/breaking.ts"],"sourcesContent":["/**\n * The paragraph model of the breakers: a list of boxes, glue and penalties, as Knuth and Plass define it. A builder makes\n * the items of a text. The breakers read only the items, so a new rule of break opportunities is a new builder.\n */\n\n/** A width function: the width of a run of text, in any unit. The breakers add the widths and compare them. */\nexport type WidthOf = (text: string) => number;\n\n/** A box: text that the breaker does not break. */\nexport interface Box {\n readonly type: \"box\";\n readonly text: string;\n readonly width: number;\n}\n\n/**\n * Glue: a space between two boxes. A line can end at glue that comes after a box. The line then does not show the glue. A\n * justified line sets each glue to its width plus a part of its stretch, or less a part of its shrink.\n */\nexport interface Glue {\n readonly type: \"glue\";\n readonly text: string;\n readonly width: number;\n /** The width that the glue can add to a justified line. The default is 0. */\n readonly stretch?: number;\n /** The width that the glue can take from a justified line, at most its width. The default is 0. */\n readonly shrink?: number;\n}\n\n/**\n * A penalty: a break opportunity with a cost. A line that ends at the penalty shows its text, for example a hyphen. A cost of\n * `Infinity` forbids the break, and a cost of `-Infinity` forces it.\n */\nexport interface Penalty {\n readonly type: \"penalty\";\n readonly text: string;\n readonly width: number;\n readonly cost: number;\n /** A flagged penalty is a hyphen. Total fit adds a cost to two flagged breaks in sequence. */\n readonly flagged: boolean;\n}\n\n/** An item of a paragraph. */\nexport type Item = Box | Glue | Penalty;\n\n/** A paragraph: the items in the order of the text. */\nexport interface Paragraph {\n readonly items: readonly Item[];\n}\n\n/** The options of `paragraphOf`. */\nexport interface ParagraphOptions {\n /** The width function of the boxes, the spaces and the hyphens. */\n readonly widthOf: WidthOf;\n /**\n * The hyphenation hook. It gives the offsets in a word where a break with a hyphen is possible. The default gives no\n * offset. The width of each part of a word comes from `widthOf`, so the kerning across an offset is not in the sum.\n */\n readonly hyphenate?: (word: string) => readonly number[];\n /**\n * The hook of the break places inside a word, for example `lineBreaks` of `./segmentation`. It gives offsets in a word where\n * a line can end with no hyphen and no cost. The default gives no offset. This hook wins at an offset that `hyphenate` also gives.\n */\n readonly breaks?: (word: string) => readonly number[];\n /** The text that a line shows at a hyphen break. The default is \"-\". */\n readonly hyphen?: string;\n /** The cost of a hyphen break. The default is 50, as in TeX. */\n readonly hyphenCost?: number;\n /** The stretch of each glue, in the unit of `widthOf`. The default is 0. TeX uses a half of a space. */\n readonly stretch?: number;\n /** The shrink of each glue, in the unit of `widthOf`. The default is 0. TeX uses a third of a space. */\n readonly shrink?: number;\n}\n\nconst whiteSpace = /\\s+/u;\n\n/**\n * This function makes the paragraph of a text with the break opportunities of CSS `white-space: normal`. Each run of white\n * space becomes one glue of the width of a space. Each word between two runs becomes a box, or boxes and hyphen penalties.\n */\nexport function paragraphOf(text: string, options: ParagraphOptions): Paragraph {\n const { widthOf } = options;\n const hyphen = options.hyphen ?? \"-\";\n const hyphenCost = options.hyphenCost ?? 50;\n const space = widthOf(\" \");\n const hyphenWidth = options.hyphenate === undefined ? 0 : widthOf(hyphen);\n const { stretch = 0, shrink = 0 } = options;\n const glue: Glue = stretch > 0 || shrink > 0 ? { type: \"glue\", text: \" \", width: space, stretch, shrink } : { type: \"glue\", text: \" \", width: space };\n const items: Item[] = [];\n for (const word of text.split(whiteSpace)) {\n if (word === \"\") continue;\n if (items.length > 0) items.push(glue);\n const free = new Set(options.breaks?.(word) ?? []);\n const offsets = [...new Set([...(options.hyphenate?.(word) ?? []), ...free])].filter((o) => o > 0 && o < word.length).sort((a, b) => a - b);\n let start = 0;\n for (const offset of offsets) {\n const part = word.slice(start, offset);\n items.push({ type: \"box\", text: part, width: widthOf(part) });\n items.push(free.has(offset) ? { type: \"penalty\", text: \"\", width: 0, cost: 0, flagged: false } : { type: \"penalty\", text: hyphen, width: hyphenWidth, cost: hyphenCost, flagged: true });\n start = offset;\n }\n const last = word.slice(start);\n items.push({ type: \"box\", text: last, width: widthOf(last) });\n }\n return { items };\n}\n\n/** A line of a broken paragraph. */\nexport interface Line {\n readonly text: string;\n /** The width of the line: its boxes, the glue between them and the text of a penalty at its end. */\n readonly width: number;\n /** The index of the first item of the line. */\n readonly start: number;\n /** The index after the last item of the line. A break at glue or at a penalty has the index of that item. */\n readonly end: number;\n}\n\n/** This function tells if a line can end at the item `index`: glue after a box, or a penalty with a cost below `Infinity`. */\nexport function isBreak(items: readonly Item[], index: number): boolean {\n const item = items[index]!;\n if (item.type === \"glue\") return index > 0 && items[index - 1]!.type === \"box\";\n return item.type === \"penalty\" && item.cost < Infinity;\n}\n\n/** This function gives the index of the first item of a line after a break at `index`. It skips the glue and the penalties. */\nexport function lineStart(items: readonly Item[], index: number): number {\n let i = index + 1;\n while (i < items.length && items[i]!.type !== \"box\") i++;\n return i;\n}\n\n/** This function gives the width of the line from the item `start` to a break at `end`, with the text of a penalty at `end`. */\nexport function lineWidth(items: readonly Item[], start: number, end: number): number {\n let width = 0;\n for (let i = start; i < end; i++) {\n const item = items[i]!;\n if (item.type !== \"penalty\") width += item.width;\n }\n const last = items[end];\n return last?.type === \"penalty\" ? width + last.width : width;\n}\n\n/**\n * This function gives the adjustment ratio of Knuth and Plass for the line from the item `start` to a break at `end`. The\n * ratio is the free width divided by the stretch of the line, or by its shrink when the line is too wide. A ratio below -1\n * needs more shrink than the line has. The ratio is infinite when the line needs stretch or shrink and has none.\n */\nexport function adjustmentRatio(items: readonly Item[], start: number, end: number, width: number): number {\n const free = width - lineWidth(items, start, end);\n if (free === 0) return 0;\n let room = 0;\n for (let i = start; i < end; i++) {\n const item = items[i]!;\n if (item.type === \"glue\") room += (free > 0 ? item.stretch : item.shrink) ?? 0;\n }\n return room > 0 ? free / room : free * Infinity;\n}\n\n/**\n * This function gives the lines of a paragraph from the indices of its breaks. Each break is the index of glue or of a penalty.\n * The last line ends at the end of the items.\n */\nexport function linesOf(paragraph: Paragraph, breaks: readonly number[]): Line[] {\n const { items } = paragraph;\n const lines: Line[] = [];\n let start = 0;\n for (const end of [...breaks, items.length]) {\n let text = \"\";\n for (let i = start; i < end; i++) {\n const item = items[i]!;\n if (item.type !== \"penalty\") text += item.text;\n }\n const last = items[end];\n if (last?.type === \"penalty\") text += last.text;\n lines.push({ text, width: lineWidth(items, start, end), start, end });\n start = lineStart(items, end);\n }\n return lines;\n}\n","import { adjustmentRatio, isBreak, lineStart, lineWidth, type Paragraph } from \"./paragraph.ts\";\n\n/**\n * A breaker: a strategy that chooses the breaks of a paragraph for the line width `width`. It gives the indices of the\n * items where the lines end, in order. A breaker reads only the items, so any width function and any builder work with it.\n */\nexport interface Breaker {\n readonly name: string;\n breaks(paragraph: Paragraph, width: number): number[];\n}\n\n/**\n * The greedy breaker: first fit, as a browser with `text-wrap: wrap`. Each line takes the items while they fit in the width.\n * A box that is wider than a line stays whole on its own line.\n */\nexport const greedy: Breaker = {\n name: \"greedy\",\n breaks: (paragraph, width) => greedyBreaks(paragraph, width),\n};\n\n/**\n * This function gives the breaks of the greedy breaker. After each break, it reads the items again from the start of the new\n * line, so that each break opportunity of the new line counts.\n */\nfunction greedyBreaks(paragraph: Paragraph, width: number): number[] {\n const { items } = paragraph;\n const breaks: number[] = [];\n let used = 0;\n let candidate = -1;\n const breakAt = (index: number): number => {\n breaks.push(index);\n used = 0;\n candidate = -1;\n return lineStart(items, index) - 1;\n };\n for (let i = 0; i < items.length; i++) {\n const item = items[i]!;\n if (item.type === \"box\") {\n used += item.width;\n if (used > width && candidate >= 0) i = breakAt(candidate);\n } else if (item.type === \"penalty\" && item.cost === -Infinity) {\n i = breakAt(i);\n } else if (item.type === \"glue\") {\n if (isBreak(items, i)) candidate = i;\n used += item.width;\n } else if (isBreak(items, i) && used + item.width <= width) {\n candidate = i;\n }\n }\n return breaks;\n}\n\n/** The options of the total fit breaker. */\nexport interface TotalFitOptions {\n /** The cost of each line, as `\\linepenalty` of TeX. A larger value gives fewer lines. The default is 10. */\n readonly linePenalty?: number;\n /** The cost of two hyphen breaks in sequence. The default is 3000, as `\\doublehyphendemerits` of TeX. */\n readonly flaggedCost?: number;\n}\n\n/**\n * This function gives the total fit breaker of Knuth and Plass. It chooses the breaks with the least sum of demerits over all\n * the lines. A paragraph with no stretch and no shrink has a ragged right edge. The demerits of a line are then\n * `(linePenalty + 100 r²)²` plus the square of the cost of its penalty. The ratio `r` is the free space divided by the width.\n * The last line has `r = 0`.\n *\n * A paragraph with glue that has stretch or shrink has a justified edge. The demerits then use `100 |r|³` with the ratio of\n * `adjustmentRatio`, and the last line does not stretch. A line that needs more shrink than it has counts first. Thus the\n * breaker keeps such a line only when each set of breaks has one.\n */\nexport function totalFit(options: TotalFitOptions = {}): Breaker {\n const linePenalty = options.linePenalty ?? 10;\n const flaggedCost = options.flaggedCost ?? 3000;\n return {\n name: \"total-fit\",\n breaks: (paragraph, width) => totalFitBreaks(paragraph, width, linePenalty, flaggedCost),\n };\n}\n\n/** The total fit breaker with the default options. */\nexport const knuthPlass: Breaker = totalFit();\n\n/** The largest badness of a justified line. An infinite ratio gets this value, so the sum of the demerits stays finite. */\nconst worstBadness = 1e8;\n\n/** This function gives the breaks of the total fit breaker, by dynamic programming over the break opportunities. */\nfunction totalFitBreaks(paragraph: Paragraph, width: number, linePenalty: number, flaggedCost: number): number[] {\n const { items } = paragraph;\n // The nodes: the start of the paragraph (-1), each break opportunity, and the end (items.length)\n const nodes = [-1];\n for (let i = 0; i < items.length; i++) if (isBreak(items, i)) nodes.push(i);\n nodes.push(items.length);\n const best = new Array<number>(nodes.length).fill(Infinity);\n const previous = new Array<number>(nodes.length).fill(-1);\n const justified = items.some((item) => item.type === \"glue\" && ((item.stretch ?? 0) > 0 || (item.shrink ?? 0) > 0));\n // The count of lines over their shrink comes before the demerits. It stays 0 for a ragged edge.\n const over = new Array<number>(nodes.length).fill(justified ? Infinity : 0);\n over[0] = 0;\n best[0] = 0;\n for (let a = 0; a < nodes.length - 1; a++) {\n if (best[a] === Infinity) continue;\n const start = a === 0 ? 0 : lineStart(items, nodes[a]!);\n const flaggedBefore = a > 0 && isFlagged(paragraph, nodes[a]!);\n for (let b = a + 1; b < nodes.length; b++) {\n const end = nodes[b]!;\n const last = b === nodes.length - 1;\n const used = lineWidth(items, start, end);\n const fit = justified ? adjustmentRatio(items, start, end, width) : 0;\n const overflow = justified ? fit < -1 : used > width;\n // A line wider than the width is possible only when no break opportunity is inside it\n if (overflow && b > a + 1) {\n if (items[end]?.type === \"penalty\") continue;\n break;\n }\n const penalty = items[end];\n const cost = penalty?.type === \"penalty\" ? penalty.cost : 0;\n const ratio = last || overflow ? 0 : (width - used) / width;\n const badness = justified ? Math.min(100 * Math.abs(last ? Math.min(fit, 0) : fit) ** 3, worstBadness) : 100 * ratio * ratio;\n let demerits = (linePenalty + badness) ** 2;\n if (cost > 0) demerits += cost * cost;\n else if (cost > -Infinity && cost < 0) demerits -= cost * cost;\n if (flaggedBefore && isFlagged(paragraph, end)) demerits += flaggedCost;\n const total = best[a]! + demerits;\n const count = over[a]! + (justified && overflow ? 1 : 0);\n if (count < over[b]! || (count === over[b]! && total < best[b]!)) {\n over[b] = count;\n best[b] = total;\n previous[b] = a;\n }\n // A forced break ends each line that comes to it\n if (cost === -Infinity) break;\n }\n }\n const breaks: number[] = [];\n for (let b = previous[nodes.length - 1]!; b > 0; b = previous[b]!) breaks.push(nodes[b]!);\n return breaks.reverse();\n}\n\n/** This function tells if the item `index` is a flagged penalty. */\nfunction isFlagged(paragraph: Paragraph, index: number): boolean {\n const item = paragraph.items[index];\n return item?.type === \"penalty\" && item.flagged;\n}\n\n/** The options of the balanced breaker. */\nexport interface BalancedOptions {\n /** The steps of the search for the width. The default is 32. */\n readonly steps?: number;\n}\n\n/**\n * This function gives the balanced breaker, as a browser with `text-wrap: balance`. It keeps the line count of the greedy\n * breaker, and it finds the least width that gives that count. Thus the lines have more equal widths.\n */\nexport function balancedBreaker(options: BalancedOptions = {}): Breaker {\n const steps = options.steps ?? 32;\n return {\n name: \"balanced\",\n breaks: (paragraph, width) => {\n const count = greedyBreaks(paragraph, width).length;\n let low = 0;\n let high = width;\n for (let step = 0; step < steps; step++) {\n const middle = (low + high) / 2;\n if (greedyBreaks(paragraph, middle).length === count) high = middle;\n else low = middle;\n }\n return greedyBreaks(paragraph, high);\n },\n };\n}\n\n/** The balanced breaker with the default options. */\nexport const balanced: Breaker = balancedBreaker();\n\n/** The breakers of the package, by name. */\nexport const breakers: Readonly<Record<\"greedy\" | \"total-fit\" | \"balanced\", Breaker>> = { greedy, \"total-fit\": knuthPlass, balanced };\n","import { adjustmentRatio, type Line, type Paragraph } from \"./paragraph.ts\";\n\n/**\n * This function gives the raggedness of the lines for the width `width`: the mean of `((width - line) / width)²` over the\n * lines before the last line. It is 0 for one line. `@mark1russell7/layout-contract/text` uses the same measure.\n */\nexport function raggedness(lines: readonly Line[], width: number): number {\n if (lines.length < 2) return 0;\n let sum = 0;\n for (let i = 0; i < lines.length - 1; i++) {\n const free = (width - lines[i]!.width) / width;\n sum += free * free;\n }\n return sum / (lines.length - 1);\n}\n\n/** This function gives the spread of the lines: the width of the widest line less the width of the narrowest line, the last line included. */\nexport function spread(lines: readonly Line[]): number {\n if (lines.length === 0) return 0;\n let widest = -Infinity;\n let narrowest = Infinity;\n for (const line of lines) {\n widest = Math.max(widest, line.width);\n narrowest = Math.min(narrowest, line.width);\n }\n return widest - narrowest;\n}\n\n/**\n * This function gives the adjustment ratio of each line for the width `width`. A renderer sets each glue of a line with a\n * ratio `r` to its width plus `r` times its stretch. When `r` is negative, the glue gets its width plus `r` times its shrink.\n * The last line does not stretch, so its ratio is not more than 0.\n */\nexport function adjustmentRatios(paragraph: Paragraph, lines: readonly Line[], width: number): number[] {\n return lines.map((line, index) => {\n const ratio = adjustmentRatio(paragraph.items, line.start, line.end, width);\n return index === lines.length - 1 ? Math.min(ratio, 0) : ratio;\n });\n}\n\n/**\n * This function gives the measure of the justified edge: the largest absolute adjustment ratio of the lines. A value of 1 or\n * less means that the glue of each line reaches the edge within its stretch and its shrink.\n */\nexport function worstRatio(paragraph: Paragraph, lines: readonly Line[], width: number): number {\n return Math.max(0, ...adjustmentRatios(paragraph, lines, width).map(Math.abs));\n}\n","export { balanced, balancedBreaker, breakers, greedy, knuthPlass, totalFit, type BalancedOptions, type Breaker, type TotalFitOptions } from \"./breaking/breakers.ts\";\nexport { adjustmentRatios, raggedness, spread, worstRatio } from \"./breaking/measures.ts\";\nexport { adjustmentRatio, isBreak, lineStart, lineWidth, linesOf, paragraphOf, type Box, type Glue, type Item, type Line, type Paragraph, type ParagraphOptions, type Penalty, type Wid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E"}
1
+ {"version":3,"file":"breaking.js","names":[],"sources":["../../src/breaking/paragraph.ts","../../src/breaking/breakers.ts","../../src/breaking/measures.ts","../../src/breaking.ts"],"sourcesContent":["/**\n * The paragraph model of the breakers: a list of boxes, glue and penalties, as Knuth and Plass define it. A builder makes\n * the items of a text. The breakers read only the items, so a new rule of break opportunities is a new builder.\n */\n\n/** A width function: the width of a run of text, in any unit. The breakers add the widths and compare them. */\nexport type WidthOf = (text: string) => number;\n\n/** A box: text that the breaker does not break. */\nexport interface Box {\n readonly type: \"box\";\n readonly text: string;\n readonly width: number;\n}\n\n/**\n * Glue: a space between two boxes. A line can end at glue that comes after a box. The line then does not show the glue. A\n * justified line sets each glue to its width plus a part of its stretch, or less a part of its shrink.\n */\nexport interface Glue {\n readonly type: \"glue\";\n readonly text: string;\n readonly width: number;\n /** The width that the glue can add to a justified line. The default is 0. */\n readonly stretch?: number;\n /** The width that the glue can take from a justified line, at most its width. The default is 0. */\n readonly shrink?: number;\n}\n\n/**\n * A penalty: a break opportunity with a cost. A line that ends at the penalty shows its text, for example a hyphen. A cost of\n * `Infinity` forbids the break, and a cost of `-Infinity` forces it.\n */\nexport interface Penalty {\n readonly type: \"penalty\";\n readonly text: string;\n readonly width: number;\n readonly cost: number;\n /** A flagged penalty is a hyphen. Total fit adds a cost to two flagged breaks in sequence. */\n readonly flagged: boolean;\n}\n\n/** An item of a paragraph. */\nexport type Item = Box | Glue | Penalty;\n\n/** A paragraph: the items in the order of the text. */\nexport interface Paragraph {\n readonly items: readonly Item[];\n}\n\n/** The options of `paragraphOf`. */\nexport interface ParagraphOptions {\n /** The width function of the boxes, the spaces and the hyphens. */\n readonly widthOf: WidthOf;\n /**\n * The hyphenation hook. It gives the offsets in a word where a break with a hyphen is possible. The default gives no\n * offset. The width of each part of a word comes from `widthOf`, so the kerning across an offset is not in the sum.\n */\n readonly hyphenate?: (word: string) => readonly number[];\n /**\n * The hook of the break places inside a word, for example `lineBreaks` of `./segmentation`. It gives offsets in a word where\n * a line can end with no hyphen and no cost. The default gives no offset. This hook wins at an offset that `hyphenate` also gives.\n */\n readonly breaks?: (word: string) => readonly number[];\n /** The text that a line shows at a hyphen break. The default is \"-\". */\n readonly hyphen?: string;\n /** The cost of a hyphen break. The default is 50, as in TeX. */\n readonly hyphenCost?: number;\n /** The stretch of each glue, in the unit of `widthOf`. The default is 0. TeX uses a half of a space. */\n readonly stretch?: number;\n /** The shrink of each glue, in the unit of `widthOf`. The default is 0. TeX uses a third of a space. */\n readonly shrink?: number;\n}\n\nconst whiteSpace = /\\s+/u;\n\n/**\n * This function makes the paragraph of a text with the break opportunities of CSS `white-space: normal`. Each run of white\n * space becomes one glue of the width of a space. Each word between two runs becomes a box, or boxes and hyphen penalties.\n */\nexport function paragraphOf(text: string, options: ParagraphOptions): Paragraph {\n const { widthOf } = options;\n const hyphen = options.hyphen ?? \"-\";\n const hyphenCost = options.hyphenCost ?? 50;\n const space = widthOf(\" \");\n const hyphenWidth = options.hyphenate === undefined ? 0 : widthOf(hyphen);\n const { stretch = 0, shrink = 0 } = options;\n const glue: Glue = stretch > 0 || shrink > 0 ? { type: \"glue\", text: \" \", width: space, stretch, shrink } : { type: \"glue\", text: \" \", width: space };\n const items: Item[] = [];\n for (const word of text.split(whiteSpace)) {\n if (word === \"\") continue;\n if (items.length > 0) items.push(glue);\n const free = new Set(options.breaks?.(word) ?? []);\n const offsets = [...new Set([...(options.hyphenate?.(word) ?? []), ...free])].filter((o) => o > 0 && o < word.length).sort((a, b) => a - b);\n let start = 0;\n for (const offset of offsets) {\n const part = word.slice(start, offset);\n items.push({ type: \"box\", text: part, width: widthOf(part) });\n items.push(free.has(offset) ? { type: \"penalty\", text: \"\", width: 0, cost: 0, flagged: false } : { type: \"penalty\", text: hyphen, width: hyphenWidth, cost: hyphenCost, flagged: true });\n start = offset;\n }\n const last = word.slice(start);\n items.push({ type: \"box\", text: last, width: widthOf(last) });\n }\n return { items };\n}\n\n/** A line of a broken paragraph. */\nexport interface Line {\n readonly text: string;\n /** The width of the line: its boxes, the glue between them and the text of a penalty at its end. */\n readonly width: number;\n /** The index of the first item of the line. */\n readonly start: number;\n /** The index after the last item of the line. A break at glue or at a penalty has the index of that item. */\n readonly end: number;\n}\n\n/** This function tells if a line can end at the item `index`: glue after a box, or a penalty with a cost below `Infinity`. */\nexport function isBreak(items: readonly Item[], index: number): boolean {\n const item = items[index]!;\n if (item.type === \"glue\") return index > 0 && items[index - 1]!.type === \"box\";\n return item.type === \"penalty\" && item.cost < Infinity;\n}\n\n/** This function gives the index of the first item of a line after a break at `index`. It skips the glue and the penalties. */\nexport function lineStart(items: readonly Item[], index: number): number {\n let i = index + 1;\n while (i < items.length && items[i]!.type !== \"box\") i++;\n return i;\n}\n\n/** This function gives the width of the line from the item `start` to a break at `end`, with the text of a penalty at `end`. */\nexport function lineWidth(items: readonly Item[], start: number, end: number): number {\n let width = 0;\n for (let i = start; i < end; i++) {\n const item = items[i]!;\n if (item.type !== \"penalty\") width += item.width;\n }\n const last = items[end];\n return last?.type === \"penalty\" ? width + last.width : width;\n}\n\n/**\n * This function gives the adjustment ratio of Knuth and Plass for the line from the item `start` to a break at `end`. The\n * ratio is the free width divided by the stretch of the line, or by its shrink when the line is too wide. A ratio below -1\n * needs more shrink than the line has. The ratio is infinite when the line needs stretch or shrink and has none.\n */\nexport function adjustmentRatio(items: readonly Item[], start: number, end: number, width: number): number {\n const free = width - lineWidth(items, start, end);\n if (free === 0) return 0;\n let room = 0;\n for (let i = start; i < end; i++) {\n const item = items[i]!;\n if (item.type === \"glue\") room += (free > 0 ? item.stretch : item.shrink) ?? 0;\n }\n return room > 0 ? free / room : free * Infinity;\n}\n\n/**\n * This function gives the lines of a paragraph from the indices of its breaks. Each break is the index of glue or of a penalty.\n * The last line ends at the end of the items.\n */\nexport function linesOf(paragraph: Paragraph, breaks: readonly number[]): Line[] {\n const { items } = paragraph;\n const lines: Line[] = [];\n let start = 0;\n for (const end of [...breaks, items.length]) {\n let text = \"\";\n for (let i = start; i < end; i++) {\n const item = items[i]!;\n if (item.type !== \"penalty\") text += item.text;\n }\n const last = items[end];\n if (last?.type === \"penalty\") text += last.text;\n lines.push({ text, width: lineWidth(items, start, end), start, end });\n start = lineStart(items, end);\n }\n return lines;\n}\n","import { adjustmentRatio, isBreak, lineStart, lineWidth, type Glue, type Item, type Paragraph } from \"./paragraph.ts\";\n\n/**\n * A breaker: a strategy that chooses the breaks of a paragraph for the line width `width`. It gives the indices of the\n * items where the lines end, in order. A breaker reads only the items, so any width function and any builder work with it.\n */\nexport interface Breaker {\n readonly name: string;\n breaks(paragraph: Paragraph, width: number): number[];\n}\n\n/**\n * The greedy breaker: first fit, as a browser with `text-wrap: wrap`. Each line takes the items while they fit in the width.\n * A box that is wider than a line stays whole on its own line.\n */\nexport const greedy: Breaker = {\n name: \"greedy\",\n breaks: (paragraph, width) => greedyBreaks(paragraph, width),\n};\n\n/**\n * This function gives the breaks of the greedy breaker. After each break, it reads the items again from the start of the new\n * line, so that each break opportunity of the new line counts.\n */\nfunction greedyBreaks(paragraph: Paragraph, width: number): number[] {\n const { items } = paragraph;\n const breaks: number[] = [];\n let used = 0;\n let candidate = -1;\n const breakAt = (index: number): number => {\n breaks.push(index);\n used = 0;\n candidate = -1;\n return lineStart(items, index) - 1;\n };\n for (let i = 0; i < items.length; i++) {\n const item = items[i]!;\n if (item.type === \"box\") {\n used += item.width;\n if (used > width && candidate >= 0) i = breakAt(candidate);\n } else if (item.type === \"penalty\" && item.cost === -Infinity) {\n i = breakAt(i);\n } else if (item.type === \"glue\") {\n if (isBreak(items, i)) candidate = i;\n used += item.width;\n } else if (isBreak(items, i) && used + item.width <= width) {\n candidate = i;\n }\n }\n return breaks;\n}\n\n/** The options of the total fit breaker. */\nexport interface TotalFitOptions {\n /** The cost of each line, as `\\linepenalty` of TeX. A larger value gives fewer lines. The default is 10. */\n readonly linePenalty?: number;\n /** The cost of two hyphen breaks in sequence. The default is 3000, as `\\doublehyphendemerits` of TeX. */\n readonly flaggedCost?: number;\n}\n\n/**\n * This function gives the total fit breaker of Knuth and Plass. It chooses the breaks with the least sum of demerits over all\n * the lines. A paragraph with no stretch and no shrink has a ragged right edge. The demerits of a line are then\n * `(linePenalty + 100 r²)²` plus the square of the cost of its penalty. The ratio `r` is the free space divided by the width.\n * The last line has `r = 0`.\n *\n * A paragraph with glue that has stretch or shrink has a justified edge. The demerits then use `100 |r|³` with the ratio of\n * `adjustmentRatio`, and the last line does not stretch. A line that needs more shrink than it has counts first. Thus the\n * breaker keeps such a line only when each set of breaks has one.\n */\nexport function totalFit(options: TotalFitOptions = {}): Breaker {\n const linePenalty = options.linePenalty ?? 10;\n const flaggedCost = options.flaggedCost ?? 3000;\n return {\n name: \"total-fit\",\n breaks: (paragraph, width) => totalFitBreaks(paragraph, width, linePenalty, flaggedCost),\n };\n}\n\n/** The total fit breaker with the default options. */\nexport const knuthPlass: Breaker = totalFit();\n\n/** The largest badness of a justified line. An infinite ratio gets this value, so the sum of the demerits stays finite. */\nconst worstBadness = 1e8;\n\n/** This function gives the breaks of the total fit breaker, by dynamic programming over the break opportunities. */\nfunction totalFitBreaks(paragraph: Paragraph, width: number, linePenalty: number, flaggedCost: number): number[] {\n const { items } = paragraph;\n // The nodes: the start of the paragraph (-1), each break opportunity, and the end (items.length)\n const nodes = [-1];\n for (let i = 0; i < items.length; i++) if (isBreak(items, i)) nodes.push(i);\n nodes.push(items.length);\n const best = new Array<number>(nodes.length).fill(Infinity);\n const previous = new Array<number>(nodes.length).fill(-1);\n const justified = items.some((item) => item.type === \"glue\" && ((item.stretch ?? 0) > 0 || (item.shrink ?? 0) > 0));\n // The count of lines over their shrink comes before the demerits. It stays 0 for a ragged edge.\n const over = new Array<number>(nodes.length).fill(justified ? Infinity : 0);\n over[0] = 0;\n best[0] = 0;\n // With no glue that shrinks by more than its width, the least width of a line grows with its end\n const steady = items.every((item) => item.type !== \"glue\" || (item.shrink ?? 0) <= item.width);\n for (let a = 0; a < nodes.length - 1; a++) {\n if (best[a] === Infinity) continue;\n const start = a === 0 ? 0 : lineStart(items, nodes[a]!);\n const flaggedBefore = a > 0 && isFlagged(paragraph, nodes[a]!);\n for (let b = a + 1; b < nodes.length; b++) {\n const end = nodes[b]!;\n const last = b === nodes.length - 1;\n const used = lineWidth(items, start, end);\n const fit = justified ? adjustmentRatio(items, start, end, width) : 0;\n const overflow = justified ? fit < -1 : used > width;\n // A line wider than the width is possible only when no break opportunity is inside it\n if (overflow && b > a + 1) {\n // Only the text of the penalty can make the line too wide. A later break has no such text, so it can fit.\n if (items[end]?.type === \"penalty\" && !(steady && leastWidth(items, start, end, used, justified) > width)) continue;\n break;\n }\n const penalty = items[end];\n const cost = penalty?.type === \"penalty\" ? penalty.cost : 0;\n const ratio = last || overflow ? 0 : (width - used) / width;\n const badness = justified ? Math.min(100 * Math.abs(last ? Math.min(fit, 0) : fit) ** 3, worstBadness) : 100 * ratio * ratio;\n let demerits = (linePenalty + badness) ** 2;\n if (cost > 0) demerits += cost * cost;\n else if (cost > -Infinity && cost < 0) demerits -= cost * cost;\n if (flaggedBefore && isFlagged(paragraph, end)) demerits += flaggedCost;\n const total = best[a]! + demerits;\n const count = over[a]! + (justified && overflow ? 1 : 0);\n if (count < over[b]! || (count === over[b]! && total < best[b]!)) {\n over[b] = count;\n best[b] = total;\n previous[b] = a;\n }\n // A forced break ends each line that comes to it\n if (cost === -Infinity) break;\n }\n }\n const breaks: number[] = [];\n for (let b = previous[nodes.length - 1]!; b > 0; b = previous[b]!) breaks.push(nodes[b]!);\n return breaks.reverse();\n}\n\n/**\n * This function gives the least width of the line from `start` to `end`, without the text of the penalty at `end`. It is\n * the width `used` less that text, and less the shrink of the glue for a justified edge. A later break of the line has no\n * smaller least width when no glue shrinks by more than its width.\n */\nfunction leastWidth(items: readonly Item[], start: number, end: number, used: number, justified: boolean): number {\n let least = used - items[end]!.width;\n if (justified) for (let i = start; i < end; i++) least -= items[i]!.type === \"glue\" ? ((items[i] as Glue).shrink ?? 0) : 0;\n return least;\n}\n\n/** This function tells if the item `index` is a flagged penalty. */\nfunction isFlagged(paragraph: Paragraph, index: number): boolean {\n const item = paragraph.items[index];\n return item?.type === \"penalty\" && item.flagged;\n}\n\n/** The options of the balanced breaker. */\nexport interface BalancedOptions {\n /** The steps of the search for the width. The default is 32. */\n readonly steps?: number;\n}\n\n/**\n * This function gives the balanced breaker, as a browser with `text-wrap: balance`. It keeps the line count of the greedy\n * breaker, and it finds the least width that gives that count. Thus the lines have more equal widths.\n */\nexport function balancedBreaker(options: BalancedOptions = {}): Breaker {\n const steps = options.steps ?? 32;\n return {\n name: \"balanced\",\n breaks: (paragraph, width) => {\n const count = greedyBreaks(paragraph, width).length;\n let low = 0;\n let high = width;\n for (let step = 0; step < steps; step++) {\n const middle = (low + high) / 2;\n if (greedyBreaks(paragraph, middle).length === count) high = middle;\n else low = middle;\n }\n return greedyBreaks(paragraph, high);\n },\n };\n}\n\n/** The balanced breaker with the default options. */\nexport const balanced: Breaker = balancedBreaker();\n\n/** The breakers of the package, by name. */\nexport const breakers: Readonly<Record<\"greedy\" | \"total-fit\" | \"balanced\", Breaker>> = { greedy, \"total-fit\": knuthPlass, balanced };\n","import { adjustmentRatio, type Line, type Paragraph } from \"./paragraph.ts\";\n\n/**\n * This function gives the raggedness of the lines for the width `width`: the mean of `((width - line) / width)²` over the\n * lines before the last line. It is 0 for one line. `@mark1russell7/layout-contract/text` uses the same measure.\n */\nexport function raggedness(lines: readonly Line[], width: number): number {\n if (lines.length < 2) return 0;\n let sum = 0;\n for (let i = 0; i < lines.length - 1; i++) {\n const free = (width - lines[i]!.width) / width;\n sum += free * free;\n }\n return sum / (lines.length - 1);\n}\n\n/** This function gives the spread of the lines: the width of the widest line less the width of the narrowest line, the last line included. */\nexport function spread(lines: readonly Line[]): number {\n if (lines.length === 0) return 0;\n let widest = -Infinity;\n let narrowest = Infinity;\n for (const line of lines) {\n widest = Math.max(widest, line.width);\n narrowest = Math.min(narrowest, line.width);\n }\n return widest - narrowest;\n}\n\n/**\n * This function gives the adjustment ratio of each line for the width `width`. A renderer sets each glue of a line with a\n * ratio `r` to its width plus `r` times its stretch. When `r` is negative, the glue gets its width plus `r` times its shrink.\n * The last line does not stretch, so its ratio is not more than 0.\n */\nexport function adjustmentRatios(paragraph: Paragraph, lines: readonly Line[], width: number): number[] {\n return lines.map((line, index) => {\n const ratio = adjustmentRatio(paragraph.items, line.start, line.end, width);\n return index === lines.length - 1 ? Math.min(ratio, 0) : ratio;\n });\n}\n\n/**\n * This function gives the measure of the justified edge: the largest absolute adjustment ratio of the lines. A value of 1 or\n * less means that the glue of each line reaches the edge within its stretch and its shrink.\n */\nexport function worstRatio(paragraph: Paragraph, lines: readonly Line[], width: number): number {\n return Math.max(0, ...adjustmentRatios(paragraph, lines, width).map(Math.abs));\n}\n","export { balanced, balancedBreaker, breakers, greedy, knuthPlass, totalFit, type BalancedOptions, type Breaker, type TotalFitOptions } from \"./breaking/breakers.ts\";\nexport { adjustmentRatios, raggedness, spread, worstRatio } from \"./breaking/measures.ts\";\nexport { adjustmentRatio, isBreak, lineStart, lineWidth, linesOf, paragraphOf, type Box, type Glue, type Item, type Line, type Paragraph, type ParagraphOptions, type Penalty, type WidthOf } from \"./breaking/paragraph.ts\";\n"],"mappings":";;AA0EA,MAAM,aAAa;;;;;AAMnB,SAAgB,YAAY,MAAc,SAAsC;CAC9E,MAAM,EAAE,YAAY;CACpB,MAAM,SAAS,QAAQ,UAAU;CACjC,MAAM,aAAa,QAAQ,cAAc;CACzC,MAAM,QAAQ,QAAQ,GAAG;CACzB,MAAM,cAAc,QAAQ,cAAc,KAAA,IAAY,IAAI,QAAQ,MAAM;CACxE,MAAM,EAAE,UAAU,GAAG,SAAS,MAAM;CACpC,MAAM,OAAa,UAAU,KAAK,SAAS,IAAI;EAAE,MAAM;EAAQ,MAAM;EAAK,OAAO;EAAO;EAAS;CAAO,IAAI;EAAE,MAAM;EAAQ,MAAM;EAAK,OAAO;CAAM;CACpJ,MAAM,QAAgB,CAAC;CAC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,UAAU,MAAM,QAAQ;IAC9B,IAAI,aAAa,WAAW,MAAM,CAAC,CAAC,WAAW,OAAO,OAAO;SACxD,MAAM;GACb;GACA,OAAO,aAAa,WAAW,IAAI;EACrC;CACF;AACF;;AAGA,MAAa,WAAoB,gBAAgB;;AAGjD,MAAa,WAA2E;CAAE;CAAQ,aAAa;CAAY;AAAS;;;;;;ACxLpI,SAAgB,WAAW,OAAwB,OAAuB;CACxE,IAAI,MAAM,SAAS,GAAG,OAAO;CAC7B,IAAI,MAAM;CACV,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,SAAS,GAAG,KAAK;EACzC,MAAM,QAAQ,QAAQ,MAAM,EAAE,CAAE,SAAS;EACzC,OAAO,OAAO;CAChB;CACA,OAAO,OAAO,MAAM,SAAS;AAC/B;;AAGA,SAAgB,OAAO,OAAgC;CACrD,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,IAAI,SAAS;CACb,IAAI,YAAY;CAChB,KAAK,MAAM,QAAQ,OAAO;EACxB,SAAS,KAAK,IAAI,QAAQ,KAAK,KAAK;EACpC,YAAY,KAAK,IAAI,WAAW,KAAK,KAAK;CAC5C;CACA,OAAO,SAAS;AAClB;;;;;;AAOA,SAAgB,iBAAiB,WAAsB,OAAwB,OAAyB;CACtG,OAAO,MAAM,KAAK,MAAM,UAAU;EAChC,MAAM,QAAQ,gBAAgB,UAAU,OAAO,KAAK,OAAO,KAAK,KAAK,KAAK;EAC1E,OAAO,UAAU,MAAM,SAAS,IAAI,KAAK,IAAI,OAAO,CAAC,IAAI;CAC3D,CAAC;AACH;;;;;AAMA,SAAgB,WAAW,WAAsB,OAAwB,OAAuB;CAC9F,OAAO,KAAK,IAAI,GAAG,GAAG,iBAAiB,WAAW,OAAO,KAAK,CAAC,CAAC,IAAI,KAAK,GAAG,CAAC;AAC/E"}
@@ -57,9 +57,10 @@ declare function parseFont(font: string): FontSpec;
57
57
  */
58
58
  declare function scriptTag(text: string): string;
59
59
  /**
60
- * This function gives the advance function of the faces of the host: the width in px of a text in a CSS font. Each run
61
- * of the text gets the first family of the font with a glyph for its first character. When no family has a glyph, the
62
- * run gets the first family that has a face. The width of a run is `measureWidth` with the size of the font, the script
60
+ * This function gives the advance function of the faces of the host: the width in px of a text in a CSS font. Each cluster
61
+ * of `fallbackClusters` gets the first family of the font that holds it, as Blink falls back. A family holds a cluster when
62
+ * it has a glyph for each code point, or for each code point of the composed form. When no family holds the cluster, the
63
+ * cluster gets the first family with its first code point, or else the font before it. The width of a run is `measureWidth` with the size of the font, the script
63
64
  * of `scriptTag` and the rules of the engine. The instance of a variable face takes the weight and the stretch as `wdth`.
64
65
  * It takes the style as `ital` or `slnt`, and the size as `opsz`, as `font-optical-sizing: auto` does.
65
66
  */
@@ -1 +1 @@
1
- {"version":3,"file":"measurer.d.ts","names":[],"sources":["../../src/measurer/advance.ts","../../src/measurer.ts"],"mappings":";;;KAaY,aAAa,cAAc;;UAGtB;;WAEN;;WAEA,MAAM;;;;;WAKN;;WAEA;;WAEA,aAAa;;;UAIP;;WAEN,gBAAgB;;WAEhB,SAAS,aAAa;;;;;WAKtB;;WAEA,WAAW;;;UAIL;WACN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;iBAuBK,UAAU,eAAe;;;;;iBAwGzB,UAAU;;;;;;;;iBAmDV,YAAY,SAAS,sBAAsB,cAAc"}
1
+ {"version":3,"file":"measurer.d.ts","names":[],"sources":["../../src/measurer/advance.ts","../../src/measurer.ts"],"mappings":";;;KAaY,aAAa,cAAc;;UAGtB;;WAEN;;WAEA,MAAM;;;;;WAKN;;WAEA;;WAEA,aAAa;;;UAIP;;WAEN,gBAAgB;;WAEhB,SAAS,aAAa;;;;;WAKtB;;WAEA,WAAW;;;UAIL;WACN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;iBAuBK,UAAU,eAAe;;;;;iBAwGzB,UAAU;;;;;;;;;iBA2FV,YAAY,SAAS,sBAAsB,cAAc"}
@@ -134,8 +134,40 @@ function scriptTag(text) {
134
134
  }
135
135
  return "DFLT";
136
136
  }
137
- /** A character that stays in the run of the character before it: a mark, a joiner, a variation selector, a tag or a skin tone. */
138
- const attached = /^[\p{M}‌‍︀-️\u{e0020}-\u{e007f}\u{e0100}-\u{e01ef}\u{1f3fb}-\u{1f3ff}]$/u;
137
+ /** The clusters of a font list: a font takes a whole cluster, as the second pass of Blink does. */
138
+ const clusters = new Intl.Segmenter("und", { granularity: "grapheme" });
139
+ /** This pattern finds a character with no ink. A font needs no glyph for it, because HarfBuzz hides it. */
140
+ const ignorable = /^\p{Default_Ignorable_Code_Point}$/u;
141
+ /** This function tells if a font has a glyph for each code point of a text that needs one. */
142
+ function covers(font, text) {
143
+ for (const character of text) if (font.glyph(character.codePointAt(0)) === 0 && !ignorable.test(character)) return false;
144
+ return true;
145
+ }
146
+ /**
147
+ * This function tells if a font holds a cluster. The normalizer of HarfBuzz composes a base and a mark when the font has the
148
+ * composed character. So a font with `â` holds `a` and U+0302.
149
+ */
150
+ function holds(font, cluster) {
151
+ return covers(font, cluster) || covers(font, cluster.normalize("NFC"));
152
+ }
153
+ /** This pattern finds a character that starts an emoji run of Blink: a character with emoji presentation, or a skin tone modifier. */
154
+ const emojiStart = /^[\p{Emoji_Presentation}\p{Emoji_Modifier}]$/u;
155
+ /**
156
+ * This function gives the clusters of a text for the font fallback. The run segmenter of Blink divides the text into script
157
+ * runs and emoji runs before the fallback. So a cluster is a grapheme cluster inside one run of `scriptRuns`. It splits
158
+ * where an emoji run starts. Thus a Devanagari mark after a Latin base keeps the base in its font. A space before a lone
159
+ * skin tone modifier also keeps its font.
160
+ */
161
+ function fallbackClusters(text) {
162
+ const out = [];
163
+ for (const run of scriptRuns(text)) for (const { segment } of clusters.segment(run)) {
164
+ const characters = [...segment];
165
+ const split = emojiStart.test(characters[0]) ? -1 : characters.findIndex((character) => emojiStart.test(character));
166
+ if (split <= 0) out.push(segment);
167
+ else out.push(characters.slice(0, split).join(""), characters.slice(split).join(""));
168
+ }
169
+ return out;
170
+ }
139
171
  const styleOrder = {
140
172
  normal: [
141
173
  "normal",
@@ -170,9 +202,10 @@ function weightRank(range, weight) {
170
202
  return above ? 1e3 + min : 3e3 - max;
171
203
  }
172
204
  /**
173
- * This function gives the advance function of the faces of the host: the width in px of a text in a CSS font. Each run
174
- * of the text gets the first family of the font with a glyph for its first character. When no family has a glyph, the
175
- * run gets the first family that has a face. The width of a run is `measureWidth` with the size of the font, the script
205
+ * This function gives the advance function of the faces of the host: the width in px of a text in a CSS font. Each cluster
206
+ * of `fallbackClusters` gets the first family of the font that holds it, as Blink falls back. A family holds a cluster when
207
+ * it has a glyph for each code point, or for each code point of the composed form. When no family holds the cluster, the
208
+ * cluster gets the first family with its first code point, or else the font before it. The width of a run is `measureWidth` with the size of the font, the script
176
209
  * of `scriptTag` and the rules of the engine. The instance of a variable face takes the weight and the stretch as `wdth`.
177
210
  * It takes the style as `ital` or `slnt`, and the size as `opsz`, as `font-optical-sizing: auto` does.
178
211
  */
@@ -284,23 +317,23 @@ function fontAdvance(options) {
284
317
  });
285
318
  };
286
319
  if (fonts.length === 1) return measure(text, fonts[0]);
287
- let width = 0;
288
- let run = "";
289
- let current;
290
- let joined = false;
291
- for (const character of text) {
292
- const code = character.codePointAt(0);
293
- const face = current !== void 0 && (joined || attached.test(character)) ? current : fonts.find((value) => value.glyph(code) !== 0) ?? fonts[0];
294
- if (face !== current && run.length > 0) {
295
- width += measure(run, current);
296
- run = "";
320
+ /** This function gives each cluster the first font that holds it, and measures each run of one font. */
321
+ const listed = (part) => {
322
+ let width = 0;
323
+ let run = "";
324
+ let current;
325
+ for (const segment of fallbackClusters(part)) {
326
+ const face = fonts.find((value) => holds(value, segment)) ?? fonts.find((value) => value.glyph(segment.codePointAt(0)) !== 0) ?? current ?? fonts[0];
327
+ if (face !== current && run.length > 0) {
328
+ width += measure(run, current);
329
+ run = "";
330
+ }
331
+ current = face;
332
+ run += segment;
297
333
  }
298
- current = face;
299
- run += character;
300
- joined = code === 8205;
301
- }
302
- if (run.length > 0) width += measure(run, current);
303
- return width;
334
+ return run.length > 0 ? width + measure(run, current) : width;
335
+ };
336
+ return listed(text);
304
337
  };
305
338
  }
306
339
  // src/measurer.ts
@@ -1 +1 @@
1
- {"version":3,"file":"measurer.js","names":[],"sources":["../../src/measurer/advance.ts","../../src/measurer.ts"],"sourcesContent":["/**\n * The advance function of the font model: the width of a text in a CSS font, as the measurer of\n * `@mark1russell7/layout-contract/text` asks for it. The host gives the font files as faces. The function finds the face\n * of each run of the text with the matching rules of CSS. It finds the script of the run, and measures the run with the\n * rules of one text engine.\n */\nimport { engines, isEngineName, type EngineName, type EngineRules } from \"../fonts/engines.ts\";\nimport { measureWidth, readFont, type Font } from \"../fonts/font.ts\";\nimport { shapingRisks } from \"../fonts/risks.ts\";\nimport type { Decompress } from \"../fonts/sfnt.ts\";\nimport { canvasWords } from \"../fonts/words.ts\";\n\n/** This function gives the width of a text in a CSS font, as `AdvanceFn` of layout-contract does. */\nexport type AdvanceFn = (text: string, font: string) => number;\n\n/** One font file of the host, with the family, the weight and the style that CSS matches. */\nexport interface FontFace {\n /** The family name, as the CSS font names it. The match ignores the case. */\n readonly family: string;\n /** The bytes of a TrueType, OpenType or WOFF2 file. */\n readonly data: Uint8Array;\n /**\n * The weight of the face: one value, or the range of a variable font. The default is the range of the `wght` axis of the\n * font, or 400 for a font with no `wght` axis.\n */\n readonly weight?: number | readonly [number, number];\n /** The style of the face. The default is `normal`. */\n readonly style?: \"normal\" | \"italic\" | \"oblique\";\n /** The Brotli decompressor of a WOFF2 file. */\n readonly decompress?: Decompress;\n}\n\n/** The options of `fontAdvance`. */\nexport interface FontAdvanceOptions {\n /** The font files of the host. The order sets the choice between two faces with the same match. */\n readonly faces: readonly FontFace[];\n /** The text engine: a row name of `engines`, or the rules of a row. The default is `freetype`, as Chromium on Linux. */\n readonly engine?: EngineName | EngineRules;\n /**\n * The shaping of `measureWidth`. The default is `canvas`, as `canvasAdvance` of layout-contract measures each segment\n * with `measureText`. Use `dom` for the widths of a text in a page.\n */\n readonly shaping?: \"dom\" | \"canvas\";\n /** The shaper of the host. Under the shaping `canvas`, it measures each word that `shapingRisks` flags. The shaping `dom` does not use it. */\n readonly fallback?: AdvanceFn;\n}\n\n/** The parts of a CSS font shorthand that change a width. */\nexport interface FontSpec {\n readonly style: \"normal\" | \"italic\" | \"oblique\";\n /** The angle of an oblique style in degrees. CSS gives 14 when the font names no angle. */\n readonly angle: number;\n /** The weight from 1 to 1000. */\n readonly weight: number;\n /** The width of the font as a percent of the normal width, from the keyword of `font-stretch`. */\n readonly stretch: number;\n /** The size in px. */\n readonly size: number;\n /** The family names in the order of the font, with no quotes. */\n readonly families: readonly string[];\n}\n\nconst stretches: Readonly<Record<string, number>> = {\n \"ultra-condensed\": 50,\n \"extra-condensed\": 62.5,\n condensed: 75,\n \"semi-condensed\": 87.5,\n \"semi-expanded\": 112.5,\n expanded: 125,\n \"extra-expanded\": 150,\n \"ultra-expanded\": 200,\n};\n\n// Each number pattern matches a text in one way only. Thus a long run of digits does not make the match slow.\nconst sizePattern = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:e[+-]?\\d+)?)(px|pt)(\\/.*)?$/i;\nconst anglePattern = /^(-?(?:\\d+(?:\\.\\d+)?|\\.\\d+))deg$/i;\nconst weightPattern = /^(?:\\d+(?:\\.\\d+)?|\\.\\d+)$/;\n\n/**\n * This function reads a CSS font shorthand, for example `italic 700 16px/1.2 \"Noto Sans\", sans-serif`. The size must be in\n * `px` or `pt`. The function refuses `small-caps`, the system font keywords and the relative sizes with a `RangeError`.\n */\nexport function parseFont(font: string): FontSpec {\n const tokens = font.trim().split(/\\s+/);\n let style: FontSpec[\"style\"] = \"normal\";\n let angle = 14;\n let weight = 400;\n let stretch = 100;\n let index = 0;\n for (; index < tokens.length; index++) {\n const token = tokens[index]!;\n const lower = token.toLowerCase();\n const size = sizePattern.exec(token);\n if (size !== null) break;\n if (lower === \"normal\") continue;\n if (lower === \"italic\") style = \"italic\";\n else if (lower === \"oblique\") {\n style = \"oblique\";\n const next = anglePattern.exec(tokens[index + 1] ?? \"\");\n if (next !== null) {\n angle = Number(next[1]);\n index++;\n }\n } else if (lower === \"bold\" || lower === \"bolder\") weight = 700;\n else if (lower === \"lighter\") weight = 100;\n else if (weightPattern.test(token) && Number(token) >= 1 && Number(token) <= 1000) weight = Number(token);\n else if (Object.hasOwn(stretches, lower)) stretch = stretches[lower]!;\n else throw new RangeError(`the font \"${font}\" has the part \"${token}\", which the measurer does not know`);\n }\n const size = sizePattern.exec(tokens[index] ?? \"\");\n if (size === null) throw new RangeError(`the font \"${font}\" has no size in px or pt`);\n let rest = tokens.slice(index + 1).join(\" \");\n // A line height after a space: \"16px / 1.2\" or \"16px /1.2\"\n if (size[3] === undefined && rest.startsWith(\"/\")) rest = rest.slice(1).trim().replace(/^\\S+\\s*/, \"\");\n // A line height after a slash and a space: \"16px/ 1.2\"\n else if (size[3] === \"/\") rest = rest.replace(/^\\S+\\s*/, \"\");\n const families = rest\n .split(\",\")\n .map((family) => family.trim().replace(/^([\"'])(.*)\\1$/, \"$2\").trim())\n .filter((family) => family.length > 0);\n if (families.length === 0) throw new RangeError(`the font \"${font}\" has no family`);\n const value = Number(size[1]);\n return { style, angle, weight, stretch, size: size[2]!.toLowerCase() === \"pt\" ? (value * 4) / 3 : value, families };\n}\n\n/** The Unicode scripts and their OpenType tags. A script that is not in the list gets `DFLT`. */\nconst scriptPatterns: readonly (readonly [RegExp, string])[] = [\n [/\\p{sc=Latin}/u, \"latn\"],\n [/\\p{sc=Greek}/u, \"grek\"],\n [/\\p{sc=Cyrillic}/u, \"cyrl\"],\n [/\\p{sc=Armenian}/u, \"armn\"],\n [/\\p{sc=Hebrew}/u, \"hebr\"],\n [/\\p{sc=Arabic}/u, \"arab\"],\n [/\\p{sc=Syriac}/u, \"syrc\"],\n [/\\p{sc=Thaana}/u, \"thaa\"],\n [/\\p{sc=Devanagari}/u, \"deva\"],\n [/\\p{sc=Bengali}/u, \"beng\"],\n [/\\p{sc=Gurmukhi}/u, \"guru\"],\n [/\\p{sc=Gujarati}/u, \"gujr\"],\n [/\\p{sc=Oriya}/u, \"orya\"],\n [/\\p{sc=Tamil}/u, \"taml\"],\n [/\\p{sc=Telugu}/u, \"telu\"],\n [/\\p{sc=Kannada}/u, \"knda\"],\n [/\\p{sc=Malayalam}/u, \"mlym\"],\n [/\\p{sc=Sinhala}/u, \"sinh\"],\n [/\\p{sc=Thai}/u, \"thai\"],\n [/\\p{sc=Lao}/u, \"lao \"],\n [/\\p{sc=Tibetan}/u, \"tibt\"],\n [/\\p{sc=Myanmar}/u, \"mymr\"],\n [/\\p{sc=Georgian}/u, \"geor\"],\n [/\\p{sc=Hangul}/u, \"hang\"],\n [/\\p{sc=Ethiopic}/u, \"ethi\"],\n [/\\p{sc=Khmer}/u, \"khmr\"],\n [/\\p{sc=Mongolian}/u, \"mong\"],\n [/[\\p{sc=Hiragana}\\p{sc=Katakana}]/u, \"kana\"],\n [/\\p{sc=Bopomofo}/u, \"bopo\"],\n [/\\p{sc=Han}/u, \"hani\"],\n];\n\nconst neutral = /[\\p{sc=Common}\\p{sc=Inherited}\\p{sc=Unknown}]/u;\n\n/** This function divides a text into parts of one script. A neutral character stays with the part before it. */\nexport function scriptRuns(text: string): string[] {\n if (/^[\\0-\\x7f]*$/.test(text)) return [text];\n const runs: string[] = [];\n let run = \"\";\n let current: string | undefined;\n for (const character of text) {\n if (!neutral.test(character)) {\n const tag = scriptTag(character).replace(/kana|bopo/, \"hani\");\n if (current !== undefined && tag !== current) {\n runs.push(run);\n run = \"\";\n }\n current = tag;\n }\n run += character;\n }\n runs.push(run);\n return runs;\n}\n\n/**\n * This function gives the OpenType script tag of a text, as HarfBuzz guesses it. The tag is the script of the first\n * character that is not of the scripts Common, Inherited or Unknown. A text of only those characters, for example emoji, gets `DFLT`.\n */\nexport function scriptTag(text: string): string {\n for (const character of text) {\n if (neutral.test(character)) continue;\n for (const [pattern, tag] of scriptPatterns) if (pattern.test(character)) return tag;\n return \"DFLT\";\n }\n return \"DFLT\";\n}\n\n/** A character that stays in the run of the character before it: a mark, a joiner, a variation selector, a tag or a skin tone. */\nconst attached = /^[\\p{M}‌‍︀-️\\u{e0020}-\\u{e007f}\\u{e0100}-\\u{e01ef}\\u{1f3fb}-\\u{1f3ff}]$/u;\n\nconst styleOrder: Readonly<Record<FontSpec[\"style\"], readonly FontSpec[\"style\"][]>> = {\n normal: [\"normal\", \"oblique\", \"italic\"],\n italic: [\"italic\", \"oblique\", \"normal\"],\n oblique: [\"oblique\", \"italic\", \"normal\"],\n};\n\n/** A face with its font, read at the first use. */\ninterface Loaded {\n readonly face: FontFace;\n readonly index: number;\n readonly font: Font;\n readonly range: readonly [number, number];\n}\n\n/**\n * This function gives the rank of a face for the weight `weight`, with the rules of CSS Fonts 4. A lower rank is a\n * better match. A face whose range holds the weight has the rank 0.\n */\nfunction weightRank(range: readonly [number, number], weight: number): number {\n const [min, max] = range;\n if (min <= weight && weight <= max) return 0;\n const above = min > weight;\n // The groups of CSS: 1 is the first choice after an exact match, 3 is the last\n if (weight >= 400 && weight <= 500) {\n if (above && min <= 500) return 1000 + min;\n if (!above) return 3000 - max;\n return 5000 + min;\n }\n if (weight < 400) return above ? 3000 + min : 1000 - max;\n return above ? 1000 + min : 3000 - max;\n}\n\n/**\n * This function gives the advance function of the faces of the host: the width in px of a text in a CSS font. Each run\n * of the text gets the first family of the font with a glyph for its first character. When no family has a glyph, the\n * run gets the first family that has a face. The width of a run is `measureWidth` with the size of the font, the script\n * of `scriptTag` and the rules of the engine. The instance of a variable face takes the weight and the stretch as `wdth`.\n * It takes the style as `ital` or `slnt`, and the size as `opsz`, as `font-optical-sizing: auto` does.\n */\nexport function fontAdvance(options: FontAdvanceOptions): (text: string, font: string) => number {\n const engine = options.engine ?? \"freetype\";\n if (typeof engine === \"string\" && !isEngineName(engine)) throw new RangeError(`the engine \"${engine}\" is not a row of engines`);\n const rules: EngineRules = typeof engine === \"string\" ? engines[engine] : engine;\n const shaping = options.shaping ?? \"canvas\";\n const fallback = shaping === \"canvas\" ? options.fallback : undefined;\n const faces = options.faces;\n const loaded = new Map<number, Loaded>();\n const specs = new Map<string, FontSpec>();\n const instances = new Map<string, Font>();\n const families = new Map<string, readonly Font[] | undefined>();\n\n const load = (index: number): Loaded => {\n let entry = loaded.get(index);\n if (entry === undefined) {\n const face = faces[index]!;\n const font = readFont(face.data, { deltas: rules.deltas, metrics: rules.metrics, ...(face.decompress === undefined ? {} : { decompress: face.decompress }) });\n const axis = font.axes.find((value) => value.tag === \"wght\");\n const declared = face.weight;\n const range: readonly [number, number] = typeof declared === \"number\" ? [declared, declared] : (declared ?? (axis === undefined ? [400, 400] : [axis.min, axis.max]));\n entry = { face, index, font, range };\n loaded.set(index, entry);\n }\n return entry;\n };\n\n /** This function gives the font of the best face of a family for the spec, or `undefined` when the family has no face. */\n const fontOf = (family: string, spec: FontSpec): Font | undefined => {\n const name = family.toLowerCase();\n const candidates: Loaded[] = [];\n for (let i = 0; i < faces.length; i++) if (faces[i]!.family.toLowerCase() === name) candidates.push(load(i));\n if (candidates.length === 0) return undefined;\n const style = styleOrder[spec.style].find((value) => candidates.some((entry) => (entry.face.style ?? \"normal\") === value))!;\n let best: Loaded | undefined;\n let bestRank = Infinity;\n for (const entry of candidates) {\n if ((entry.face.style ?? \"normal\") !== style) continue;\n const rank = weightRank(entry.range, spec.weight);\n if (rank < bestRank) {\n best = entry;\n bestRank = rank;\n }\n }\n const chosen = best!;\n const tags = new Set(chosen.font.axes.map((axis) => axis.tag));\n const instance: Record<string, number> = {};\n if (tags.has(\"wght\")) instance[\"wght\"] = Math.min(chosen.range[1], Math.max(chosen.range[0], spec.weight));\n if (tags.has(\"wdth\")) instance[\"wdth\"] = spec.stretch;\n if (tags.has(\"opsz\")) instance[\"opsz\"] = spec.size;\n if (tags.has(\"ital\")) instance[\"ital\"] = spec.style === \"italic\" ? 1 : 0;\n if (tags.has(\"slnt\")) instance[\"slnt\"] = spec.style === \"oblique\" ? -spec.angle : 0;\n const key = `${chosen.index}|${JSON.stringify(instance)}`;\n let font = instances.get(key);\n if (font === undefined) {\n font = Object.keys(instance).length === 0 ? chosen.font : chosen.font.at(instance);\n // A key holds the size for an axis opsz, so this cache has a bound, as the other caches have\n if (instances.size >= 256) instances.clear();\n instances.set(key, font);\n }\n return font;\n };\n\n const fontsOf = (font: string): { readonly spec: FontSpec; readonly fonts: readonly Font[] } => {\n let spec = specs.get(font);\n if (spec === undefined) {\n spec = parseFont(font);\n if (specs.size >= 256) specs.clear();\n specs.set(font, spec);\n }\n let fonts = families.get(font);\n if (fonts === undefined) {\n fonts = spec.families.map((family) => fontOf(family, spec)).filter((value) => value !== undefined);\n if (fonts.length === 0) throw new RangeError(`no face of the host has a family of the font \"${font}\"`);\n if (families.size >= 256) families.clear();\n families.set(font, fonts);\n }\n return { spec, fonts };\n };\n\n return (text: string, font: string): number => {\n const { spec, fonts } = fontsOf(font);\n const sum = (parts: readonly string[], width: (part: string) => number): number => parts.reduce((total, part) => total + width(part), 0);\n const measure = (run: string, face: Font): number => {\n const runs = scriptRuns(run);\n const tagged = (part: string): number => measureWidth(face, part, spec.size, { script: scriptTag(part), shaping, rounding: rules.rounding, sum: rules.sum });\n const risky = (part: string): boolean => fallback !== undefined && shapingRisks(face, part, { script: scriptTag(part), shaping }).length > 0;\n if (runs.length === 1 && !risky(run)) return tagged(run);\n if (shaping !== \"canvas\") return sum(runs, tagged);\n // The width of a word comes from the word alone. This keeps the separator law of the rope\n return sum(canvasWords(run), (word) => {\n const parts = scriptRuns(word);\n return parts.some(risky) ? fallback!(word, font) : sum(parts, tagged);\n });\n };\n if (fonts.length === 1) return measure(text, fonts[0]!);\n let width = 0;\n let run = \"\";\n let current: Font | undefined;\n let joined = false;\n for (const character of text) {\n const code = character.codePointAt(0)!;\n const stays = current !== undefined && (joined || attached.test(character));\n const face = stays ? current! : (fonts.find((value) => value.glyph(code) !== 0) ?? fonts[0]!);\n if (face !== current && run.length > 0) {\n width += measure(run, current!);\n run = \"\";\n }\n current = face;\n run += character;\n joined = code === 0x200d;\n }\n if (run.length > 0) width += measure(run, current!);\n return width;\n };\n}\n","/**\n * The subpath `./measurer`: the advance function of a layout engine, from the font model of typeset. The measurer of\n * `@mark1russell7/layout-contract/text` takes it as its `AdvanceFn`.\n */\nexport { fontAdvance, parseFont, scriptTag, type AdvanceFn, type FontAdvanceOptions, type FontFace, type FontSpec } from \"./measurer/advance.ts\";\n"],"mappings":";;;;;;;;;;AA8DA,MAAM,YAA8C;CAClD,mBAAmB;CACnB,mBAAmB;CACnB,WAAW;CACX,kBAAkB;CAClB,iBAAiB;CACjB,UAAU;CACV,kBAAkB;CAClB,kBAAkB;AACpB;AAGA,MAAM,cAAc;AACpB,MAAM,eAAe;AACrB,MAAM,gBAAgB;;;;;AAMtB,SAAgB,UAAU,MAAwB;CAChD,MAAM,SAAS,KAAK,KAAK,CAAC,CAAC,MAAM,KAAK;CACtC,IAAI,QAA2B;CAC/B,IAAI,QAAQ;CACZ,IAAI,SAAS;CACb,IAAI,UAAU;CACd,IAAI,QAAQ;CACZ,OAAO,QAAQ,OAAO,QAAQ,SAAS;EACrC,MAAM,QAAQ,OAAO;EACrB,MAAM,QAAQ,MAAM,YAAY;EAEhC,IADa,YAAY,KAAK,KACvB,MAAM,MAAM;EACnB,IAAI,UAAU,UAAU;EACxB,IAAI,UAAU,UAAU,QAAQ;OAC3B,IAAI,UAAU,WAAW;GAC5B,QAAQ;GACR,MAAM,OAAO,aAAa,KAAK,OAAO,QAAQ,MAAM,EAAE;GACtD,IAAI,SAAS,MAAM;IACjB,QAAQ,OAAO,KAAK,EAAE;IACtB;GACF;EACF,OAAO,IAAI,UAAU,UAAU,UAAU,UAAU,SAAS;OACvD,IAAI,UAAU,WAAW,SAAS;OAClC,IAAI,cAAc,KAAK,KAAK,KAAK,OAAO,KAAK,KAAK,KAAK,OAAO,KAAK,KAAK,KAAM,SAAS,OAAO,KAAK;OACnG,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W,GAAG;GAC3B,MAAM,UAAU,SAAyB,aAAa,MAAM,MAAM,KAAK,MAAM;IAAE,QAAQ,UAAU,IAAI;IAAG;IAAS,UAAU,MAAM;IAAU,KAAK,MAAM;GAAI,CAAC;GAC3J,MAAM,SAAS,SAA0B,aAAa,KAAA,KAAa,aAAa,MAAM,MAAM;IAAE,QAAQ,UAAU,IAAI;IAAG;GAAQ,CAAC,CAAC,CAAC,SAAS;GAC3I,IAAI,KAAK,WAAW,KAAK,CAAC,MAAM,GAAG,GAAG,OAAO,OAAO,GAAG;GACvD,IAAI,YAAY,UAAU,OAAO,IAAI,MAAM,MAAM;GAEjD,OAAO,IAAI,YAAY,GAAG,IAAI,SAAS;IACrC,MAAM,QAAQ,WAAW,IAAI;IAC7B,OAAO,MAAM,KAAK,KAAK,IAAI,SAAU,MAAM,IAAI,IAAI,IAAI,OAAO,MAAM;GACtE,CAAC;EACH;EACA,IAAI,MAAM,WAAW,GAAG,OAAO,QAAQ,MAAM,MAAM,EAAG;EACtD,IAAI,QAAQ;EACZ,IAAI,MAAM;EACV,IAAI;EACJ,IAAI,SAAS;EACb,KAAK,MAAM,aAAa,MAAM;GAC5B,MAAM,OAAO,UAAU,YAAY,CAAC;GAEpC,MAAM,OADQ,YAAY,KAAA,MAAc,UAAU,SAAS,KAAK,SAAS,KACpD,UAAY,MAAM,MAAM,UAAU,MAAM,MAAM,IAAI,MAAM,CAAC,KAAK,MAAM;GACzF,IAAI,SAAS,WAAW,IAAI,SAAS,GAAG;IACtC,SAAS,QAAQ,KAAK,OAAQ;IAC9B,MAAM;GACR;GACA,UAAU;GACV,OAAO;GACP,SAAS,SAAS;EACpB;EACA,IAAI,IAAI,SAAS,GAAG,SAAS,QAAQ,KAAK,OAAQ;EAClD,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"measurer.js","names":[],"sources":["../../src/measurer/advance.ts","../../src/measurer.ts"],"sourcesContent":["/**\n * The advance function of the font model: the width of a text in a CSS font, as the measurer of\n * `@mark1russell7/layout-contract/text` asks for it. The host gives the font files as faces. The function finds the face\n * of each run of the text with the matching rules of CSS. It finds the script of the run, and measures the run with the\n * rules of one text engine.\n */\nimport { engines, isEngineName, type EngineName, type EngineRules } from \"../fonts/engines.ts\";\nimport { measureWidth, readFont, type Font } from \"../fonts/font.ts\";\nimport { shapingRisks } from \"../fonts/risks.ts\";\nimport type { Decompress } from \"../fonts/sfnt.ts\";\nimport { canvasWords } from \"../fonts/words.ts\";\n\n/** This function gives the width of a text in a CSS font, as `AdvanceFn` of layout-contract does. */\nexport type AdvanceFn = (text: string, font: string) => number;\n\n/** One font file of the host, with the family, the weight and the style that CSS matches. */\nexport interface FontFace {\n /** The family name, as the CSS font names it. The match ignores the case. */\n readonly family: string;\n /** The bytes of a TrueType, OpenType or WOFF2 file. */\n readonly data: Uint8Array;\n /**\n * The weight of the face: one value, or the range of a variable font. The default is the range of the `wght` axis of the\n * font, or 400 for a font with no `wght` axis.\n */\n readonly weight?: number | readonly [number, number];\n /** The style of the face. The default is `normal`. */\n readonly style?: \"normal\" | \"italic\" | \"oblique\";\n /** The Brotli decompressor of a WOFF2 file. */\n readonly decompress?: Decompress;\n}\n\n/** The options of `fontAdvance`. */\nexport interface FontAdvanceOptions {\n /** The font files of the host. The order sets the choice between two faces with the same match. */\n readonly faces: readonly FontFace[];\n /** The text engine: a row name of `engines`, or the rules of a row. The default is `freetype`, as Chromium on Linux. */\n readonly engine?: EngineName | EngineRules;\n /**\n * The shaping of `measureWidth`. The default is `canvas`, as `canvasAdvance` of layout-contract measures each segment\n * with `measureText`. Use `dom` for the widths of a text in a page.\n */\n readonly shaping?: \"dom\" | \"canvas\";\n /** The shaper of the host. Under the shaping `canvas`, it measures each word that `shapingRisks` flags. The shaping `dom` does not use it. */\n readonly fallback?: AdvanceFn;\n}\n\n/** The parts of a CSS font shorthand that change a width. */\nexport interface FontSpec {\n readonly style: \"normal\" | \"italic\" | \"oblique\";\n /** The angle of an oblique style in degrees. CSS gives 14 when the font names no angle. */\n readonly angle: number;\n /** The weight from 1 to 1000. */\n readonly weight: number;\n /** The width of the font as a percent of the normal width, from the keyword of `font-stretch`. */\n readonly stretch: number;\n /** The size in px. */\n readonly size: number;\n /** The family names in the order of the font, with no quotes. */\n readonly families: readonly string[];\n}\n\nconst stretches: Readonly<Record<string, number>> = {\n \"ultra-condensed\": 50,\n \"extra-condensed\": 62.5,\n condensed: 75,\n \"semi-condensed\": 87.5,\n \"semi-expanded\": 112.5,\n expanded: 125,\n \"extra-expanded\": 150,\n \"ultra-expanded\": 200,\n};\n\n// Each number pattern matches a text in one way only. Thus a long run of digits does not make the match slow.\nconst sizePattern = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:e[+-]?\\d+)?)(px|pt)(\\/.*)?$/i;\nconst anglePattern = /^(-?(?:\\d+(?:\\.\\d+)?|\\.\\d+))deg$/i;\nconst weightPattern = /^(?:\\d+(?:\\.\\d+)?|\\.\\d+)$/;\n\n/**\n * This function reads a CSS font shorthand, for example `italic 700 16px/1.2 \"Noto Sans\", sans-serif`. The size must be in\n * `px` or `pt`. The function refuses `small-caps`, the system font keywords and the relative sizes with a `RangeError`.\n */\nexport function parseFont(font: string): FontSpec {\n const tokens = font.trim().split(/\\s+/);\n let style: FontSpec[\"style\"] = \"normal\";\n let angle = 14;\n let weight = 400;\n let stretch = 100;\n let index = 0;\n for (; index < tokens.length; index++) {\n const token = tokens[index]!;\n const lower = token.toLowerCase();\n const size = sizePattern.exec(token);\n if (size !== null) break;\n if (lower === \"normal\") continue;\n if (lower === \"italic\") style = \"italic\";\n else if (lower === \"oblique\") {\n style = \"oblique\";\n const next = anglePattern.exec(tokens[index + 1] ?? \"\");\n if (next !== null) {\n angle = Number(next[1]);\n index++;\n }\n } else if (lower === \"bold\" || lower === \"bolder\") weight = 700;\n else if (lower === \"lighter\") weight = 100;\n else if (weightPattern.test(token) && Number(token) >= 1 && Number(token) <= 1000) weight = Number(token);\n else if (Object.hasOwn(stretches, lower)) stretch = stretches[lower]!;\n else throw new RangeError(`the font \"${font}\" has the part \"${token}\", which the measurer does not know`);\n }\n const size = sizePattern.exec(tokens[index] ?? \"\");\n if (size === null) throw new RangeError(`the font \"${font}\" has no size in px or pt`);\n let rest = tokens.slice(index + 1).join(\" \");\n // A line height after a space: \"16px / 1.2\" or \"16px /1.2\"\n if (size[3] === undefined && rest.startsWith(\"/\")) rest = rest.slice(1).trim().replace(/^\\S+\\s*/, \"\");\n // A line height after a slash and a space: \"16px/ 1.2\"\n else if (size[3] === \"/\") rest = rest.replace(/^\\S+\\s*/, \"\");\n const families = rest\n .split(\",\")\n .map((family) => family.trim().replace(/^([\"'])(.*)\\1$/, \"$2\").trim())\n .filter((family) => family.length > 0);\n if (families.length === 0) throw new RangeError(`the font \"${font}\" has no family`);\n const value = Number(size[1]);\n return { style, angle, weight, stretch, size: size[2]!.toLowerCase() === \"pt\" ? (value * 4) / 3 : value, families };\n}\n\n/** The Unicode scripts and their OpenType tags. A script that is not in the list gets `DFLT`. */\nconst scriptPatterns: readonly (readonly [RegExp, string])[] = [\n [/\\p{sc=Latin}/u, \"latn\"],\n [/\\p{sc=Greek}/u, \"grek\"],\n [/\\p{sc=Cyrillic}/u, \"cyrl\"],\n [/\\p{sc=Armenian}/u, \"armn\"],\n [/\\p{sc=Hebrew}/u, \"hebr\"],\n [/\\p{sc=Arabic}/u, \"arab\"],\n [/\\p{sc=Syriac}/u, \"syrc\"],\n [/\\p{sc=Thaana}/u, \"thaa\"],\n [/\\p{sc=Devanagari}/u, \"deva\"],\n [/\\p{sc=Bengali}/u, \"beng\"],\n [/\\p{sc=Gurmukhi}/u, \"guru\"],\n [/\\p{sc=Gujarati}/u, \"gujr\"],\n [/\\p{sc=Oriya}/u, \"orya\"],\n [/\\p{sc=Tamil}/u, \"taml\"],\n [/\\p{sc=Telugu}/u, \"telu\"],\n [/\\p{sc=Kannada}/u, \"knda\"],\n [/\\p{sc=Malayalam}/u, \"mlym\"],\n [/\\p{sc=Sinhala}/u, \"sinh\"],\n [/\\p{sc=Thai}/u, \"thai\"],\n [/\\p{sc=Lao}/u, \"lao \"],\n [/\\p{sc=Tibetan}/u, \"tibt\"],\n [/\\p{sc=Myanmar}/u, \"mymr\"],\n [/\\p{sc=Georgian}/u, \"geor\"],\n [/\\p{sc=Hangul}/u, \"hang\"],\n [/\\p{sc=Ethiopic}/u, \"ethi\"],\n [/\\p{sc=Khmer}/u, \"khmr\"],\n [/\\p{sc=Mongolian}/u, \"mong\"],\n [/[\\p{sc=Hiragana}\\p{sc=Katakana}]/u, \"kana\"],\n [/\\p{sc=Bopomofo}/u, \"bopo\"],\n [/\\p{sc=Han}/u, \"hani\"],\n];\n\nconst neutral = /[\\p{sc=Common}\\p{sc=Inherited}\\p{sc=Unknown}]/u;\n\n/** This function divides a text into parts of one script. A neutral character stays with the part before it. */\nexport function scriptRuns(text: string): string[] {\n if (/^[\\0-\\x7f]*$/.test(text)) return [text];\n const runs: string[] = [];\n let run = \"\";\n let current: string | undefined;\n for (const character of text) {\n if (!neutral.test(character)) {\n const tag = scriptTag(character).replace(/kana|bopo/, \"hani\");\n if (current !== undefined && tag !== current) {\n runs.push(run);\n run = \"\";\n }\n current = tag;\n }\n run += character;\n }\n runs.push(run);\n return runs;\n}\n\n/**\n * This function gives the OpenType script tag of a text, as HarfBuzz guesses it. The tag is the script of the first\n * character that is not of the scripts Common, Inherited or Unknown. A text of only those characters, for example emoji, gets `DFLT`.\n */\nexport function scriptTag(text: string): string {\n for (const character of text) {\n if (neutral.test(character)) continue;\n for (const [pattern, tag] of scriptPatterns) if (pattern.test(character)) return tag;\n return \"DFLT\";\n }\n return \"DFLT\";\n}\n\n/** The clusters of a font list: a font takes a whole cluster, as the second pass of Blink does. */\nconst clusters = new Intl.Segmenter(\"und\", { granularity: \"grapheme\" });\n\n/** This pattern finds a character with no ink. A font needs no glyph for it, because HarfBuzz hides it. */\nconst ignorable = /^\\p{Default_Ignorable_Code_Point}$/u;\n\n/** This function tells if a font has a glyph for each code point of a text that needs one. */\nfunction covers(font: Font, text: string): boolean {\n for (const character of text) if (font.glyph(character.codePointAt(0)!) === 0 && !ignorable.test(character)) return false;\n return true;\n}\n\n/**\n * This function tells if a font holds a cluster. The normalizer of HarfBuzz composes a base and a mark when the font has the\n * composed character. So a font with `â` holds `a` and U+0302.\n */\nfunction holds(font: Font, cluster: string): boolean {\n return covers(font, cluster) || covers(font, cluster.normalize(\"NFC\"));\n}\n\n/** This pattern finds a character that starts an emoji run of Blink: a character with emoji presentation, or a skin tone modifier. */\nconst emojiStart = /^[\\p{Emoji_Presentation}\\p{Emoji_Modifier}]$/u;\n\n/**\n * This function gives the clusters of a text for the font fallback. The run segmenter of Blink divides the text into script\n * runs and emoji runs before the fallback. So a cluster is a grapheme cluster inside one run of `scriptRuns`. It splits\n * where an emoji run starts. Thus a Devanagari mark after a Latin base keeps the base in its font. A space before a lone\n * skin tone modifier also keeps its font.\n */\nexport function fallbackClusters(text: string): string[] {\n const out: string[] = [];\n for (const run of scriptRuns(text)) {\n for (const { segment } of clusters.segment(run)) {\n const characters = [...segment];\n const split = emojiStart.test(characters[0]!) ? -1 : characters.findIndex((character) => emojiStart.test(character));\n if (split <= 0) out.push(segment);\n else out.push(characters.slice(0, split).join(\"\"), characters.slice(split).join(\"\"));\n }\n }\n return out;\n}\n\nconst styleOrder: Readonly<Record<FontSpec[\"style\"], readonly FontSpec[\"style\"][]>> = {\n normal: [\"normal\", \"oblique\", \"italic\"],\n italic: [\"italic\", \"oblique\", \"normal\"],\n oblique: [\"oblique\", \"italic\", \"normal\"],\n};\n\n/** A face with its font, read at the first use. */\ninterface Loaded {\n readonly face: FontFace;\n readonly index: number;\n readonly font: Font;\n readonly range: readonly [number, number];\n}\n\n/**\n * This function gives the rank of a face for the weight `weight`, with the rules of CSS Fonts 4. A lower rank is a\n * better match. A face whose range holds the weight has the rank 0.\n */\nfunction weightRank(range: readonly [number, number], weight: number): number {\n const [min, max] = range;\n if (min <= weight && weight <= max) return 0;\n const above = min > weight;\n // The groups of CSS: 1 is the first choice after an exact match, 3 is the last\n if (weight >= 400 && weight <= 500) {\n if (above && min <= 500) return 1000 + min;\n if (!above) return 3000 - max;\n return 5000 + min;\n }\n if (weight < 400) return above ? 3000 + min : 1000 - max;\n return above ? 1000 + min : 3000 - max;\n}\n\n/**\n * This function gives the advance function of the faces of the host: the width in px of a text in a CSS font. Each cluster\n * of `fallbackClusters` gets the first family of the font that holds it, as Blink falls back. A family holds a cluster when\n * it has a glyph for each code point, or for each code point of the composed form. When no family holds the cluster, the\n * cluster gets the first family with its first code point, or else the font before it. The width of a run is `measureWidth` with the size of the font, the script\n * of `scriptTag` and the rules of the engine. The instance of a variable face takes the weight and the stretch as `wdth`.\n * It takes the style as `ital` or `slnt`, and the size as `opsz`, as `font-optical-sizing: auto` does.\n */\nexport function fontAdvance(options: FontAdvanceOptions): (text: string, font: string) => number {\n const engine = options.engine ?? \"freetype\";\n if (typeof engine === \"string\" && !isEngineName(engine)) throw new RangeError(`the engine \"${engine}\" is not a row of engines`);\n const rules: EngineRules = typeof engine === \"string\" ? engines[engine] : engine;\n const shaping = options.shaping ?? \"canvas\";\n const fallback = shaping === \"canvas\" ? options.fallback : undefined;\n const faces = options.faces;\n const loaded = new Map<number, Loaded>();\n const specs = new Map<string, FontSpec>();\n const instances = new Map<string, Font>();\n const families = new Map<string, readonly Font[] | undefined>();\n\n const load = (index: number): Loaded => {\n let entry = loaded.get(index);\n if (entry === undefined) {\n const face = faces[index]!;\n const font = readFont(face.data, { deltas: rules.deltas, metrics: rules.metrics, ...(face.decompress === undefined ? {} : { decompress: face.decompress }) });\n const axis = font.axes.find((value) => value.tag === \"wght\");\n const declared = face.weight;\n const range: readonly [number, number] = typeof declared === \"number\" ? [declared, declared] : (declared ?? (axis === undefined ? [400, 400] : [axis.min, axis.max]));\n entry = { face, index, font, range };\n loaded.set(index, entry);\n }\n return entry;\n };\n\n /** This function gives the font of the best face of a family for the spec, or `undefined` when the family has no face. */\n const fontOf = (family: string, spec: FontSpec): Font | undefined => {\n const name = family.toLowerCase();\n const candidates: Loaded[] = [];\n for (let i = 0; i < faces.length; i++) if (faces[i]!.family.toLowerCase() === name) candidates.push(load(i));\n if (candidates.length === 0) return undefined;\n const style = styleOrder[spec.style].find((value) => candidates.some((entry) => (entry.face.style ?? \"normal\") === value))!;\n let best: Loaded | undefined;\n let bestRank = Infinity;\n for (const entry of candidates) {\n if ((entry.face.style ?? \"normal\") !== style) continue;\n const rank = weightRank(entry.range, spec.weight);\n if (rank < bestRank) {\n best = entry;\n bestRank = rank;\n }\n }\n const chosen = best!;\n const tags = new Set(chosen.font.axes.map((axis) => axis.tag));\n const instance: Record<string, number> = {};\n if (tags.has(\"wght\")) instance[\"wght\"] = Math.min(chosen.range[1], Math.max(chosen.range[0], spec.weight));\n if (tags.has(\"wdth\")) instance[\"wdth\"] = spec.stretch;\n if (tags.has(\"opsz\")) instance[\"opsz\"] = spec.size;\n if (tags.has(\"ital\")) instance[\"ital\"] = spec.style === \"italic\" ? 1 : 0;\n if (tags.has(\"slnt\")) instance[\"slnt\"] = spec.style === \"oblique\" ? -spec.angle : 0;\n const key = `${chosen.index}|${JSON.stringify(instance)}`;\n let font = instances.get(key);\n if (font === undefined) {\n font = Object.keys(instance).length === 0 ? chosen.font : chosen.font.at(instance);\n // A key holds the size for an axis opsz, so this cache has a bound, as the other caches have\n if (instances.size >= 256) instances.clear();\n instances.set(key, font);\n }\n return font;\n };\n\n const fontsOf = (font: string): { readonly spec: FontSpec; readonly fonts: readonly Font[] } => {\n let spec = specs.get(font);\n if (spec === undefined) {\n spec = parseFont(font);\n if (specs.size >= 256) specs.clear();\n specs.set(font, spec);\n }\n let fonts = families.get(font);\n if (fonts === undefined) {\n fonts = spec.families.map((family) => fontOf(family, spec)).filter((value) => value !== undefined);\n if (fonts.length === 0) throw new RangeError(`no face of the host has a family of the font \"${font}\"`);\n if (families.size >= 256) families.clear();\n families.set(font, fonts);\n }\n return { spec, fonts };\n };\n\n return (text: string, font: string): number => {\n const { spec, fonts } = fontsOf(font);\n const sum = (parts: readonly string[], width: (part: string) => number): number => parts.reduce((total, part) => total + width(part), 0);\n const measure = (run: string, face: Font): number => {\n const runs = scriptRuns(run);\n const tagged = (part: string): number => measureWidth(face, part, spec.size, { script: scriptTag(part), shaping, rounding: rules.rounding, sum: rules.sum });\n const risky = (part: string): boolean => fallback !== undefined && shapingRisks(face, part, { script: scriptTag(part), shaping }).length > 0;\n if (runs.length === 1 && !risky(run)) return tagged(run);\n if (shaping !== \"canvas\") return sum(runs, tagged);\n // The width of a word comes from the word alone. This keeps the separator law of the rope\n return sum(canvasWords(run), (word) => {\n const parts = scriptRuns(word);\n return parts.some(risky) ? fallback!(word, font) : sum(parts, tagged);\n });\n };\n if (fonts.length === 1) return measure(text, fonts[0]!);\n /** This function gives each cluster the first font that holds it, and measures each run of one font. */\n const listed = (part: string): number => {\n let width = 0;\n let run = \"\";\n let current: Font | undefined;\n for (const segment of fallbackClusters(part)) {\n const face = fonts.find((value) => holds(value, segment)) ?? fonts.find((value) => value.glyph(segment.codePointAt(0)!) !== 0) ?? current ?? fonts[0]!;\n if (face !== current && run.length > 0) {\n width += measure(run, current!);\n run = \"\";\n }\n current = face;\n run += segment;\n }\n return run.length > 0 ? width + measure(run, current!) : width;\n };\n return listed(text);\n };\n}\n","/**\n * The subpath `./measurer`: the advance function of a layout engine, from the font model of typeset. The measurer of\n * `@mark1russell7/layout-contract/text` takes it as its `AdvanceFn`.\n */\nexport { fontAdvance, parseFont, scriptTag, type AdvanceFn, type FontAdvanceOptions, type FontFace, type FontSpec } from \"./measurer/advance.ts\";\n"],"mappings":";;;;;;;;;;AA8DA,MAAM,YAA8C;CAClD,mBAAmB;CACnB,mBAAmB;CACnB,WAAW;CACX,kBAAkB;CAClB,iBAAiB;CACjB,UAAU;CACV,kBAAkB;CAClB,kBAAkB;AACpB;AAGA,MAAM,cAAc;AACpB,MAAM,eAAe;AACrB,MAAM,gBAAgB;;;;;AAMtB,SAAgB,UAAU,MA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AAI,SAAS,GAAG;KACtC,SAAS,QAAQ,KAAK,OAAQ;KAC9B,MAAM;IACR;IACA,UAAU;IACV,OAAO;GACT;GACA,OAAO,IAAI,SAAS,IAAI,QAAQ,QAAQ,KAAK,OAAQ,IAAI;EAC3D;EACA,OAAO,OAAO,IAAI;CACpB;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/typeset",
4
- "version": "0.4.0",
4
+ "version": "0.5.1",
5
5
  "description": "Text measurement and line breaking. The subpath ./fonts reads font tables and gives widths, ./measurer gives the advance function of a layout, ./breaking has the line breakers, ./hyphen has hyphen patterns for each language, ./segmentation has the break positions of Unicode, ./bidi has the bidirectional algorithm of Unicode, and ./text has a rope.",
6
6
  "keywords": [
7
7
  "typeset",
@@ -97,6 +97,8 @@
97
97
  "@mark1russell7/layout-contract": "^0.5.3",
98
98
  "@types/node": "^26.6.5",
99
99
  "@typeset/corpus": "0.1.0",
100
+ "@vitest/coverage-v8": "^5.0.5",
101
+ "fast-check": "^4.10.2",
100
102
  "tsdown": "^0.23.1",
101
103
  "typescript": "^7.0.2",
102
104
  "vitest": "^5.0.3"
@@ -1,4 +1,4 @@
1
- import { adjustmentRatio, isBreak, lineStart, lineWidth, type Paragraph } from "./paragraph.ts";
1
+ import { adjustmentRatio, isBreak, lineStart, lineWidth, type Glue, type Item, type Paragraph } from "./paragraph.ts";
2
2
 
3
3
  /**
4
4
  * A breaker: a strategy that chooses the breaks of a paragraph for the line width `width`. It gives the indices of the
@@ -97,6 +97,8 @@ function totalFitBreaks(paragraph: Paragraph, width: number, linePenalty: number
97
97
  const over = new Array<number>(nodes.length).fill(justified ? Infinity : 0);
98
98
  over[0] = 0;
99
99
  best[0] = 0;
100
+ // With no glue that shrinks by more than its width, the least width of a line grows with its end
101
+ const steady = items.every((item) => item.type !== "glue" || (item.shrink ?? 0) <= item.width);
100
102
  for (let a = 0; a < nodes.length - 1; a++) {
101
103
  if (best[a] === Infinity) continue;
102
104
  const start = a === 0 ? 0 : lineStart(items, nodes[a]!);
@@ -109,7 +111,8 @@ function totalFitBreaks(paragraph: Paragraph, width: number, linePenalty: number
109
111
  const overflow = justified ? fit < -1 : used > width;
110
112
  // A line wider than the width is possible only when no break opportunity is inside it
111
113
  if (overflow && b > a + 1) {
112
- if (items[end]?.type === "penalty") continue;
114
+ // Only the text of the penalty can make the line too wide. A later break has no such text, so it can fit.
115
+ if (items[end]?.type === "penalty" && !(steady && leastWidth(items, start, end, used, justified) > width)) continue;
113
116
  break;
114
117
  }
115
118
  const penalty = items[end];
@@ -136,6 +139,17 @@ function totalFitBreaks(paragraph: Paragraph, width: number, linePenalty: number
136
139
  return breaks.reverse();
137
140
  }
138
141
 
142
+ /**
143
+ * This function gives the least width of the line from `start` to `end`, without the text of the penalty at `end`. It is
144
+ * the width `used` less that text, and less the shrink of the glue for a justified edge. A later break of the line has no
145
+ * smaller least width when no glue shrinks by more than its width.
146
+ */
147
+ function leastWidth(items: readonly Item[], start: number, end: number, used: number, justified: boolean): number {
148
+ let least = used - items[end]!.width;
149
+ if (justified) for (let i = start; i < end; i++) least -= items[i]!.type === "glue" ? ((items[i] as Glue).shrink ?? 0) : 0;
150
+ return least;
151
+ }
152
+
139
153
  /** This function tells if the item `index` is a flagged penalty. */
140
154
  function isFlagged(paragraph: Paragraph, index: number): boolean {
141
155
  const item = paragraph.items[index];
@@ -193,8 +193,47 @@ export function scriptTag(text: string): string {
193
193
  return "DFLT";
194
194
  }
195
195
 
196
- /** A character that stays in the run of the character before it: a mark, a joiner, a variation selector, a tag or a skin tone. */
197
- const attached = /^[\p{M}‌‍︀-️\u{e0020}-\u{e007f}\u{e0100}-\u{e01ef}\u{1f3fb}-\u{1f3ff}]$/u;
196
+ /** The clusters of a font list: a font takes a whole cluster, as the second pass of Blink does. */
197
+ const clusters = new Intl.Segmenter("und", { granularity: "grapheme" });
198
+
199
+ /** This pattern finds a character with no ink. A font needs no glyph for it, because HarfBuzz hides it. */
200
+ const ignorable = /^\p{Default_Ignorable_Code_Point}$/u;
201
+
202
+ /** This function tells if a font has a glyph for each code point of a text that needs one. */
203
+ function covers(font: Font, text: string): boolean {
204
+ for (const character of text) if (font.glyph(character.codePointAt(0)!) === 0 && !ignorable.test(character)) return false;
205
+ return true;
206
+ }
207
+
208
+ /**
209
+ * This function tells if a font holds a cluster. The normalizer of HarfBuzz composes a base and a mark when the font has the
210
+ * composed character. So a font with `â` holds `a` and U+0302.
211
+ */
212
+ function holds(font: Font, cluster: string): boolean {
213
+ return covers(font, cluster) || covers(font, cluster.normalize("NFC"));
214
+ }
215
+
216
+ /** This pattern finds a character that starts an emoji run of Blink: a character with emoji presentation, or a skin tone modifier. */
217
+ const emojiStart = /^[\p{Emoji_Presentation}\p{Emoji_Modifier}]$/u;
218
+
219
+ /**
220
+ * This function gives the clusters of a text for the font fallback. The run segmenter of Blink divides the text into script
221
+ * runs and emoji runs before the fallback. So a cluster is a grapheme cluster inside one run of `scriptRuns`. It splits
222
+ * where an emoji run starts. Thus a Devanagari mark after a Latin base keeps the base in its font. A space before a lone
223
+ * skin tone modifier also keeps its font.
224
+ */
225
+ export function fallbackClusters(text: string): string[] {
226
+ const out: string[] = [];
227
+ for (const run of scriptRuns(text)) {
228
+ for (const { segment } of clusters.segment(run)) {
229
+ const characters = [...segment];
230
+ const split = emojiStart.test(characters[0]!) ? -1 : characters.findIndex((character) => emojiStart.test(character));
231
+ if (split <= 0) out.push(segment);
232
+ else out.push(characters.slice(0, split).join(""), characters.slice(split).join(""));
233
+ }
234
+ }
235
+ return out;
236
+ }
198
237
 
199
238
  const styleOrder: Readonly<Record<FontSpec["style"], readonly FontSpec["style"][]>> = {
200
239
  normal: ["normal", "oblique", "italic"],
@@ -229,9 +268,10 @@ function weightRank(range: readonly [number, number], weight: number): number {
229
268
  }
230
269
 
231
270
  /**
232
- * This function gives the advance function of the faces of the host: the width in px of a text in a CSS font. Each run
233
- * of the text gets the first family of the font with a glyph for its first character. When no family has a glyph, the
234
- * run gets the first family that has a face. The width of a run is `measureWidth` with the size of the font, the script
271
+ * This function gives the advance function of the faces of the host: the width in px of a text in a CSS font. Each cluster
272
+ * of `fallbackClusters` gets the first family of the font that holds it, as Blink falls back. A family holds a cluster when
273
+ * it has a glyph for each code point, or for each code point of the composed form. When no family holds the cluster, the
274
+ * cluster gets the first family with its first code point, or else the font before it. The width of a run is `measureWidth` with the size of the font, the script
235
275
  * of `scriptTag` and the rules of the engine. The instance of a variable face takes the weight and the stretch as `wdth`.
236
276
  * It takes the style as `ital` or `slnt`, and the size as `opsz`, as `font-optical-sizing: auto` does.
237
277
  */
@@ -330,23 +370,22 @@ export function fontAdvance(options: FontAdvanceOptions): (text: string, font: s
330
370
  });
331
371
  };
332
372
  if (fonts.length === 1) return measure(text, fonts[0]!);
333
- let width = 0;
334
- let run = "";
335
- let current: Font | undefined;
336
- let joined = false;
337
- for (const character of text) {
338
- const code = character.codePointAt(0)!;
339
- const stays = current !== undefined && (joined || attached.test(character));
340
- const face = stays ? current! : (fonts.find((value) => value.glyph(code) !== 0) ?? fonts[0]!);
341
- if (face !== current && run.length > 0) {
342
- width += measure(run, current!);
343
- run = "";
373
+ /** This function gives each cluster the first font that holds it, and measures each run of one font. */
374
+ const listed = (part: string): number => {
375
+ let width = 0;
376
+ let run = "";
377
+ let current: Font | undefined;
378
+ for (const segment of fallbackClusters(part)) {
379
+ const face = fonts.find((value) => holds(value, segment)) ?? fonts.find((value) => value.glyph(segment.codePointAt(0)!) !== 0) ?? current ?? fonts[0]!;
380
+ if (face !== current && run.length > 0) {
381
+ width += measure(run, current!);
382
+ run = "";
383
+ }
384
+ current = face;
385
+ run += segment;
344
386
  }
345
- current = face;
346
- run += character;
347
- joined = code === 0x200d;
348
- }
349
- if (run.length > 0) width += measure(run, current!);
350
- return width;
387
+ return run.length > 0 ? width + measure(run, current!) : width;
388
+ };
389
+ return listed(text);
351
390
  };
352
391
  }