@mark1russell7/typeset 0.1.4 → 0.1.5

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.
@@ -44,8 +44,8 @@ const joiningTable: readonly number[] = [
44
44
  0x855, 0x855, D, 0x856, 0x858, R, 0x860, 0x860, D, 0x861, 0x861, U, 0x862, 0x865, D, 0x866, 0x866, U, 0x867, 0x867, R,
45
45
  0x868, 0x868, D, 0x869, 0x86a, R, 0x870, 0x882, R, 0x883, 0x885, D, 0x886, 0x886, D, 0x887, 0x888, U, 0x889, 0x88d, D,
46
46
  0x88e, 0x88e, R, 0x88f, 0x88f, D, 0x890, 0x891, U, 0x8a0, 0x8a9, D, 0x8aa, 0x8ac, R, 0x8ad, 0x8ad, U, 0x8ae, 0x8ae, R,
47
- 0x8af, 0x8b0, D, 0x8b1, 0x8b2, R, 0x8b3, 0x8b8, D, 0x8b9, 0x8b9, R, 0x8ba, 0x8c8, D, 0x8e2, 0x8e2, U, 0x200c, 0x200c, U,
48
- 0x200d, 0x200d, D,
47
+ 0x8af, 0x8b0, D, 0x8b1, 0x8b2, R, 0x8b3, 0x8b8, D, 0x8b9, 0x8b9, R, 0x8ba, 0x8c8, D, 0x8e2, 0x8e2, U, 0x180e, 0x180e, U, 0x200c, 0x200c, U,
48
+ 0x200d, 0x200d, D, 0x2066, 0x2069, U,
49
49
  ];
50
50
 
51
51
  const transparent = /[\p{Mn}\p{Me}\p{Cf}]/u;
@@ -171,25 +171,46 @@ const pairFeatures = new Set(["kern", "dist"]);
171
171
  /** The lookup flag that selects a mark filtering set of GDEF. */
172
172
  const USE_MARK_FILTERING_SET = 0x10;
173
173
 
174
- /**
175
- * This function gives the pair lookups of the features `kern` and `dist` of GPOS for a script, in the order of the lookup
176
- * list. The store gives the deltas of a variable font at its instance. The filter gives the mark filtering sets of GDEF.
177
- */
178
- export function readGposKerning(gpos: Reader, script: string, store?: VariationStore, filter?: GlyphFilter): PairLookup[] {
179
- const scripts = gpos.part(gpos.u16(4));
180
- const features = gpos.part(gpos.u16(6));
181
- const lookups = gpos.part(gpos.u16(8));
182
- const scriptCount = scripts.u16(0);
183
- let langSys: Reader | undefined;
174
+ /** This function gives the test of the glyphs that a lookup skips. */
175
+ export function lookupSkip(lookup: Reader, flags: number, filter: GlyphFilter): (glyph: number) => boolean {
176
+ const markSet = (flags & USE_MARK_FILTERING_SET) !== 0 ? lookup.u16(6 + lookup.u16(4) * 2) : -1;
177
+ return (glyph) => {
178
+ const kind = filter.glyphClass(glyph);
179
+ if ((flags & IGNORE_BASE) !== 0 && kind === 1) return true;
180
+ if ((flags & IGNORE_LIGATURES) !== 0 && kind === 2) return true;
181
+ if (kind !== 3) return false;
182
+ if ((flags & IGNORE_MARKS) !== 0) return true;
183
+ if (markSet >= 0) return !filter.inMarkSet(markSet, glyph);
184
+ const attach = flags >> 8;
185
+ return attach !== 0 && filter.markAttachClass(glyph) !== attach;
186
+ };
187
+ }
188
+
189
+ /** This function gives the subtables of a lookup with their types, after each extension of the type `extension`. */
190
+ export function subtablesOf(lookup: Reader, extension: number): (readonly [number, Reader])[] {
191
+ return Array.from({ length: lookup.u16(4) }, (_, s) => {
192
+ const subtable = lookup.part(lookup.u16(6 + s * 2));
193
+ return lookup.u16(0) === extension ? [subtable.u16(2), subtable.part(subtable.u32(4))] : [lookup.u16(0), subtable];
194
+ });
195
+ }
196
+
197
+ /** This function gives the default language system of a table for a script. */
198
+ export function languageSystem(table: Reader, script: string): Reader | undefined {
199
+ const scripts = table.part(table.u16(4));
184
200
  for (const wanted of scriptTags(script)) {
185
- for (let i = 0; i < scriptCount && langSys === undefined; i++) {
201
+ for (let i = 0; i < scripts.u16(0); i++) {
186
202
  if (scripts.tag(2 + i * 6) !== wanted) continue;
187
- const table = scripts.part(scripts.u16(2 + i * 6 + 4));
188
- const fallback = table.u16(0);
189
- if (fallback !== 0) langSys = table.part(fallback);
203
+ const entry = scripts.part(scripts.u16(2 + i * 6 + 4));
204
+ if (entry.u16(0) !== 0) return entry.part(entry.u16(0));
190
205
  }
191
- if (langSys !== undefined) break;
192
206
  }
207
+ return undefined;
208
+ }
209
+
210
+ /** This function gives the indices of the lookups of `kern` and `dist` for a script, in the order of the lookup list. */
211
+ export function pairLookupIndices(gpos: Reader, script: string): number[] {
212
+ const features = gpos.part(gpos.u16(6));
213
+ const langSys = languageSystem(gpos, script);
193
214
  if (langSys === undefined) return [];
194
215
  const indices = new Set<number>();
195
216
  const featureCount = langSys.u16(4);
@@ -199,29 +220,22 @@ export function readGposKerning(gpos: Reader, script: string, store?: VariationS
199
220
  const feature = features.part(features.u16(record + 4));
200
221
  for (let k = 0; k < feature.u16(2); k++) indices.add(feature.u16(4 + k * 2));
201
222
  }
202
- return [...indices].sort((a, b) => a - b).flatMap((index) => {
223
+ return [...indices].sort((a, b) => a - b);
224
+ }
225
+
226
+ /**
227
+ * This function gives the pair lookups of the features `kern` and `dist` of GPOS for a script, in the order of the lookup
228
+ * list. The store gives the deltas of a variable font at its instance. The filter gives the mark filtering sets of GDEF.
229
+ */
230
+ export function readGposKerning(gpos: Reader, script: string, store?: VariationStore, filter?: GlyphFilter): PairLookup[] {
231
+ const lookups = gpos.part(gpos.u16(8));
232
+ return pairLookupIndices(gpos, script).flatMap((index) => {
203
233
  const lookup = lookups.part(lookups.u16(2 + index * 2));
204
234
  const subtables: PairSubtable[] = [];
205
- const type = lookup.u16(0);
206
- for (let s = 0; s < lookup.u16(4); s++) {
207
- let subtable = lookup.part(lookup.u16(6 + s * 2));
208
- let subtype = type;
209
- if (type === 9) {
210
- subtype = subtable.u16(2);
211
- subtable = subtable.part(subtable.u32(4));
212
- }
213
- if (subtype === 2) subtables.push(pairSubtable(subtable, store));
214
- }
235
+ for (const [subtype, subtable] of subtablesOf(lookup, 9)) if (subtype === 2) subtables.push(pairSubtable(subtable, store));
215
236
  if (subtables.length === 0) return [];
216
237
  const flags = lookup.u16(2);
217
- const markSet = (flags & USE_MARK_FILTERING_SET) !== 0 && filter !== undefined ? lookup.u16(6 + lookup.u16(4) * 2) : -1;
218
- const skip = markSet < 0 ? undefined : (glyph: number): boolean => {
219
- const kind = filter!.glyphClass(glyph);
220
- if ((flags & IGNORE_BASE) !== 0 && kind === 1) return true;
221
- if ((flags & IGNORE_LIGATURES) !== 0 && kind === 2) return true;
222
- if (kind !== 3) return false;
223
- return (flags & IGNORE_MARKS) !== 0 || !filter!.inMarkSet(markSet, glyph);
224
- };
238
+ const skip = (flags & USE_MARK_FILTERING_SET) !== 0 && filter !== undefined ? lookupSkip(lookup, flags, filter) : undefined;
225
239
  return [{
226
240
  flags,
227
241
  ...(skip === undefined ? {} : { skip }),
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  const unicodeMark = /\p{M}/u;
7
+ const nonspacingMark = /\p{Mn}/u;
7
8
 
8
9
  /**
9
10
  * The classes of HarfBuzz for the marks of Hebrew and Arabic, from `hb-unicode.hh`. Their order is not the canonical order:
@@ -16,6 +17,19 @@ const sortClasses: ReadonlyMap<number, number> = new Map([
16
17
  [0x651, 27], [0x652, 34], [0x670, 35], [0x8f0, 28], [0x8f1, 29], [0x8f2, 30],
17
18
  ]);
18
19
 
20
+ /** The default ignorables of `hb-unicode.hh`. This set is not the Unicode property: it does not have the Hangul fillers. */
21
+ const defaultIgnorable = /[\u00ad\u034f\u061c\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u202a-\u202e\u2060-\u206f\ufe00-\ufe0f\ufeff\ufff0-\ufff8\u{1d173}-\u{1d17a}\u{e0000}-\u{e0fff}]/u;
22
+
23
+ /** This function tells if a text has a default ignorable. */
24
+ export function hasDefaultIgnorable(text: string): boolean {
25
+ return defaultIgnorable.test(text);
26
+ }
27
+
28
+ /** This function tells if the model hides a code point. A hidden code point takes no advance, and the kerning skips it. */
29
+ export function isHidden(codePoint: number): boolean {
30
+ return hasDefaultIgnorable(String.fromCodePoint(codePoint));
31
+ }
32
+
19
33
  /** This function tells if a code point is a mark of Unicode. The first mark of Unicode is U+0300. */
20
34
  function isMark(codePoint: number): boolean {
21
35
  return codePoint >= 0x300 && unicodeMark.test(String.fromCodePoint(codePoint));
@@ -26,6 +40,19 @@ export function hasMark(text: string): boolean {
26
40
  return unicodeMark.test(text);
27
41
  }
28
42
 
43
+ /** This function tells which code points take no advance: nonspacing marks with `classes`, marks with a class after a base with `fallback`. */
44
+ export function zeroedMarks(codePoints: readonly number[], classes: boolean, fallback: boolean): boolean[] {
45
+ let base = false;
46
+ return codePoints.map((codePoint) => {
47
+ const character = String.fromCodePoint(codePoint);
48
+ if (!isMark(codePoint)) {
49
+ base = true;
50
+ return false;
51
+ }
52
+ return (classes && nonspacingMark.test(character) && !hasDefaultIgnorable(character)) || (fallback && base && !isStarter(codePoint));
53
+ });
54
+ }
55
+
29
56
  function decomposed(codePoint: number): string {
30
57
  return String.fromCodePoint(codePoint).normalize("NFD");
31
58
  }
@@ -0,0 +1,48 @@
1
+ /** The risks of shaping: the text that the model cannot measure with trust. */
2
+ import { glyphAdvances, shapingOf, type Font, type MeasureOptions } from "./font.ts";
3
+ import { hasDefaultIgnorable, normalizeCodePoints } from "./normalize.ts";
4
+ import { canvasWords } from "./words.ts";
5
+
6
+ /** The kinds of risk. */
7
+ export type ShapingRiskCode = "missing-glyph" | "unshaped-script" | "emoji-zwj" | "variation-selector" | "keycap" | "flag" | "tag" | "positioning";
8
+
9
+ /** One part of a text that the model does not shape as HarfBuzz does, in UTF-16 units. */
10
+ export interface ShapingRisk {
11
+ readonly code: ShapingRiskCode;
12
+ readonly index: number;
13
+ readonly length: number;
14
+ }
15
+
16
+ const unshaped = /[\p{sc=Beng}\p{sc=Guru}\p{sc=Gujr}\p{sc=Orya}\p{sc=Taml}\p{sc=Telu}\p{sc=Knda}\p{sc=Mlym}\p{sc=Sinh}\p{sc=Khmr}\p{sc=Mymr}\p{sc=Tibt}\p{sc=Mong}\p{sc=Nkoo}\p{sc=Mand}]+/gu;
17
+ const pictograph = String.raw`\p{ExtPict}(?:\uFE0F|[\u{1F3FB}-\u{1F3FF}])?`;
18
+ // The longest forms come first
19
+ const sequences = new RegExp(String.raw`(\p{ExtPict}[\u{E0020}-\u{E007E}]+\u{E007F})|(${pictograph}(?:\u200D${pictograph})+)|([0-9#*]\uFE0F?\u20E3)|(\p{RI}\p{RI})|([\uFE00-\uFE0F\u{E0100}-\u{E01EF}])`, "gu");
20
+ const sequenceCodes: readonly ShapingRiskCode[] = ["tag", "emoji-zwj", "keycap", "flag", "variation-selector"];
21
+ const clusters = /\P{M}\p{M}*|\p{M}+/gu;
22
+ const control = /\p{Cc}/u;
23
+
24
+ /** This function gives the risks of a text in text order. An empty list is not a proof of a correct width. */
25
+ export function shapingRisks(font: Font, text: string, options: MeasureOptions = {}): ShapingRisk[] {
26
+ const risks: ShapingRisk[] = [];
27
+ const add = (code: ShapingRiskCode, index: number, { length }: string): number => risks.push({ code, index, length });
28
+ const absent = (codePoint: number): boolean => {
29
+ const character = String.fromCodePoint(codePoint);
30
+ return font.glyph(codePoint) === 0 && !control.test(character) && !hasDefaultIgnorable(character);
31
+ };
32
+ const hasGlyph = (codePoint: number): boolean => font.glyph(codePoint) !== 0;
33
+ for (const { 0: cluster, index } of text.matchAll(clusters)) {
34
+ if (normalizeCodePoints(Array.from(cluster, (character) => character.codePointAt(0)!), { hasGlyph, shortCircuit: true }).some(absent)) add("missing-glyph", index, cluster);
35
+ }
36
+ for (const { 0: part, index } of text.matchAll(unshaped)) add("unshaped-script", index, part);
37
+ for (const match of text.matchAll(sequences)) add(sequenceCodes[match.slice(1).findIndex(Boolean)]!, match.index, match[0]);
38
+ const tests = options.kerning === false ? [] : font.contextKerning?.(shapingOf(font, options).script) ?? [];
39
+ if (tests.length > 0) {
40
+ let index = 0;
41
+ for (const word of options.shaping === "canvas" ? canvasWords(text) : [text]) {
42
+ const { glyphs } = glyphAdvances(font, word, options);
43
+ if (tests.some((test) => test(glyphs))) add("positioning", index, word);
44
+ index += word.length;
45
+ }
46
+ }
47
+ return risks.sort((a, b) => a.index - b.index);
48
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Reader } from "./binary.ts";
2
- import { IGNORE_BASE, IGNORE_LIGATURES, IGNORE_MARKS, scriptTags } from "./kerning.ts";
2
+ import { languageSystem, lookupSkip, subtablesOf } from "./kerning.ts";
3
3
  import { classOf, coverageGlyphs, coverageIndex } from "./tables.ts";
4
4
 
5
5
  /**
@@ -8,8 +8,6 @@ import { classOf, coverageGlyphs, coverageIndex } from "./tables.ts";
8
8
  */
9
9
  export const defaultFeatures: readonly string[] = ["ccmp", "locl", "rlig", "liga", "clig", "calt", "rclt"];
10
10
 
11
- /** The lookup flag that selects a mark filtering set of GDEF. */
12
- const USE_MARK_FILTERING_SET = 0x10;
13
11
  /** The largest depth of nested lookups, as in HarfBuzz. */
14
12
  const MAX_NESTING = 64;
15
13
 
@@ -21,6 +19,8 @@ export interface GlyphFilter {
21
19
  markAttachClass(glyph: number): number;
22
20
  /** This function tells if a glyph is in the mark filtering set `set`. */
23
21
  inMarkSet(set: number, glyph: number): boolean;
22
+ /** The glyphs of the joiners that the backtrack and the lookahead of a context rule skip. */
23
+ readonly joiners?: readonly number[];
24
24
  }
25
25
 
26
26
  /** This function reads the glyph classes, the mark attachment classes and the mark filtering sets of GDEF. */
@@ -142,14 +142,14 @@ function ruleTables(t: Reader, at: number): Reader[] {
142
142
  }
143
143
 
144
144
  /** This function gives the records of each rule of a context subtable (lookup type 5). */
145
- function contextRecords(t: Reader): SequenceRecord[] {
145
+ export function contextRecords(t: Reader): SequenceRecord[] {
146
146
  const format = t.u16(0);
147
147
  if (format === 3) return records(t, 6 + t.u16(2) * 2, t.u16(4));
148
148
  return ruleTables(t, format === 2 ? 6 : 4).flatMap((rule) => records(rule, 4 + (rule.u16(0) - 1) * 2, rule.u16(2)));
149
149
  }
150
150
 
151
151
  /** This function gives the records of each rule of a chained context subtable (lookup type 6). */
152
- function chainRecords(t: Reader): SequenceRecord[] {
152
+ export function chainRecords(t: Reader): SequenceRecord[] {
153
153
  const format = t.u16(0);
154
154
  if (format === 3) {
155
155
  const inputAt = 4 + t.u16(2) * 2;
@@ -210,30 +210,11 @@ class Gsub {
210
210
  let found = this.cache.get(index);
211
211
  if (found === undefined) {
212
212
  const table = this.lookups.part(this.lookups.u16(2 + index * 2));
213
- const type = table.u16(0);
214
213
  const flags = table.u16(2);
215
- const count = table.u16(4);
216
- const markSet = (flags & USE_MARK_FILTERING_SET) !== 0 ? table.u16(6 + count * 2) : -1;
217
- const subtables: Reader[] = [];
218
- let subtype = type;
219
- for (let s = 0; s < count; s++) {
220
- const subtable = table.part(table.u16(6 + s * 2));
221
- if (type === 7) {
222
- subtype = subtable.u16(2);
223
- subtables.push(subtable.part(subtable.u32(4)));
224
- } else subtables.push(subtable);
225
- }
226
- const { glyphClass, markAttachClass, inMarkSet } = this.filter;
227
- const skip = (glyph: number): boolean => {
228
- const kind = glyphClass(glyph);
229
- if ((flags & IGNORE_BASE) !== 0 && kind === 1) return true;
230
- if ((flags & IGNORE_LIGATURES) !== 0 && kind === 2) return true;
231
- if (kind !== 3) return false;
232
- if ((flags & IGNORE_MARKS) !== 0) return true;
233
- if (markSet >= 0) return !inMarkSet(markSet, glyph);
234
- const attach = flags >> 8;
235
- return attach !== 0 && markAttachClass(glyph) !== attach;
236
- };
214
+ const parts = subtablesOf(table, 7);
215
+ const subtables = parts.map((part) => part[1]);
216
+ const subtype = parts.at(-1)?.[0] ?? table.u16(0);
217
+ const skip = lookupSkip(table, flags, this.filter);
237
218
  found = { type: subtype, flags, subtables, skip };
238
219
  this.cache.set(index, found);
239
220
  }
@@ -349,8 +330,9 @@ class Gsub {
349
330
  return -1;
350
331
  }
351
332
 
352
- private previousOf(lookup: Lookup, glyphs: readonly number[], from: number): number {
353
- for (let j = from; j >= 0; j--) if (!lookup.skip(glyphs[j]!)) return j;
333
+ /** This function finds the next glyph of a backtrack or a lookahead. As in HarfBuzz, a joiner does not stop the context. */
334
+ private contextOf(lookup: Lookup, glyphs: readonly number[], from: number, step: 1 | -1): number {
335
+ for (let j = from; j >= 0 && j < glyphs.length; j += step) if (!lookup.skip(glyphs[j]!) && !this.filter.joiners?.includes(glyphs[j]!)) return j;
354
336
  return -1;
355
337
  }
356
338
 
@@ -372,7 +354,7 @@ class Gsub {
372
354
  private matchBacktrack(lookup: Lookup, glyphs: readonly number[], i: number, count: number, test: (k: number, glyph: number) => boolean): boolean {
373
355
  let at = i;
374
356
  for (let k = 0; k < count; k++) {
375
- at = this.previousOf(lookup, glyphs, at - 1);
357
+ at = this.contextOf(lookup, glyphs, at - 1, -1);
376
358
  if (at < 0 || !this.admits(at, i, false) || !test(k, glyphs[at]!)) return false;
377
359
  }
378
360
  return true;
@@ -381,7 +363,7 @@ class Gsub {
381
363
  private matchLookahead(lookup: Lookup, glyphs: readonly number[], first: number, last: number, count: number, test: (k: number, glyph: number) => boolean): boolean {
382
364
  let at = last;
383
365
  for (let k = 0; k < count; k++) {
384
- at = this.nextOf(lookup, glyphs, at + 1);
366
+ at = this.contextOf(lookup, glyphs, at + 1, 1);
385
367
  if (at < 0 || !this.admits(at, first, false) || !test(k, glyphs[at]!)) return false;
386
368
  }
387
369
  return true;
@@ -634,19 +616,8 @@ class Gsub {
634
616
  * HarfBuzz applies them. The lookups include the lookups of the necessary feature of the language system.
635
617
  */
636
618
  export function readSubstitutions(gsub: Reader, script: string, features: readonly string[], filter: GlyphFilter): SubstitutionLookup[] {
637
- const scripts = gsub.part(gsub.u16(4));
638
619
  const featureList = gsub.part(gsub.u16(6));
639
- const scriptCount = scripts.u16(0);
640
- let langSys: Reader | undefined;
641
- for (const wanted of scriptTags(script)) {
642
- for (let i = 0; i < scriptCount && langSys === undefined; i++) {
643
- if (scripts.tag(2 + i * 6) !== wanted) continue;
644
- const table = scripts.part(scripts.u16(2 + i * 6 + 4));
645
- const fallback = table.u16(0);
646
- if (fallback !== 0) langSys = table.part(fallback);
647
- }
648
- if (langSys !== undefined) break;
649
- }
620
+ const langSys = languageSystem(gsub, script);
650
621
  if (langSys === undefined || features.length === 0) return [];
651
622
  const wanted = new Set(features);
652
623
  const indices = new Map<number, string[]>();
package/src/fonts.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  */
5
5
  export { measureWidth, readFont, type Font, type MeasureOptions, type ReadOptions } from "./fonts/font.ts";
6
6
  export { widthBound, type WidthBound } from "./fonts/bound.ts";
7
+ export { shapingRisks, type ShapingRisk, type ShapingRiskCode } from "./fonts/risks.ts";
7
8
  export { engines, isEngineName, type EngineName, type EngineRules } from "./fonts/engines.ts";
8
9
  export type { Decompress } from "./fonts/sfnt.ts";
9
10
  export type { Axis, Instance } from "./fonts/variations.ts";
@@ -6,7 +6,12 @@
6
6
  */
7
7
  import { engines, isEngineName, type EngineName, type EngineRules } from "../fonts/engines.ts";
8
8
  import { measureWidth, readFont, type Font } from "../fonts/font.ts";
9
+ import { shapingRisks } from "../fonts/risks.ts";
9
10
  import type { Decompress } from "../fonts/sfnt.ts";
11
+ import { canvasWords } from "../fonts/words.ts";
12
+
13
+ /** This function gives the width of a text in a CSS font, as `AdvanceFn` of layout-contract does. */
14
+ export type AdvanceFn = (text: string, font: string) => number;
10
15
 
11
16
  /** One font file of the host, with the family, the weight and the style that CSS matches. */
12
17
  export interface FontFace {
@@ -36,6 +41,8 @@ export interface FontAdvanceOptions {
36
41
  * with `measureText`. Use `dom` for the widths of a text in a page.
37
42
  */
38
43
  readonly shaping?: "dom" | "canvas";
44
+ /** The shaper of the host. Under the shaping `canvas`, it measures each word that `shapingRisks` flags. The shaping `dom` does not use it. */
45
+ readonly fallback?: AdvanceFn;
39
46
  }
40
47
 
41
48
  /** The parts of a CSS font shorthand that change a width. */
@@ -150,6 +157,27 @@ const scriptPatterns: readonly (readonly [RegExp, string])[] = [
150
157
 
151
158
  const neutral = /[\p{sc=Common}\p{sc=Inherited}\p{sc=Unknown}]/u;
152
159
 
160
+ /** This function divides a text into parts of one script. A neutral character stays with the part before it. */
161
+ export function scriptRuns(text: string): string[] {
162
+ if (/^[\0-\x7f]*$/.test(text)) return [text];
163
+ const runs: string[] = [];
164
+ let run = "";
165
+ let current: string | undefined;
166
+ for (const character of text) {
167
+ if (!neutral.test(character)) {
168
+ const tag = scriptTag(character).replace(/kana|bopo/, "hani");
169
+ if (current !== undefined && tag !== current) {
170
+ runs.push(run);
171
+ run = "";
172
+ }
173
+ current = tag;
174
+ }
175
+ run += character;
176
+ }
177
+ runs.push(run);
178
+ return runs;
179
+ }
180
+
153
181
  /**
154
182
  * This function gives the OpenType script tag of a text, as HarfBuzz guesses it. The tag is the script of the first
155
183
  * character that is not of the scripts Common, Inherited or Unknown. A text of only those characters, for example emoji, gets `DFLT`.
@@ -210,6 +238,7 @@ export function fontAdvance(options: FontAdvanceOptions): (text: string, font: s
210
238
  if (typeof engine === "string" && !isEngineName(engine)) throw new RangeError(`the engine "${engine}" is not a row of engines`);
211
239
  const rules: EngineRules = typeof engine === "string" ? engines[engine] : engine;
212
240
  const shaping = options.shaping ?? "canvas";
241
+ const fallback = shaping === "canvas" ? options.fallback : undefined;
213
242
  const faces = options.faces;
214
243
  const loaded = new Map<number, Loaded>();
215
244
  const specs = new Map<string, FontSpec>();
@@ -283,7 +312,19 @@ export function fontAdvance(options: FontAdvanceOptions): (text: string, font: s
283
312
 
284
313
  return (text: string, font: string): number => {
285
314
  const { spec, fonts } = fontsOf(font);
286
- const measure = (run: string, face: Font): number => measureWidth(face, run, spec.size, { script: scriptTag(run), shaping, rounding: rules.rounding, sum: rules.sum });
315
+ const sum = (parts: readonly string[], width: (part: string) => number): number => parts.reduce((total, part) => total + width(part), 0);
316
+ const measure = (run: string, face: Font): number => {
317
+ const runs = scriptRuns(run);
318
+ const tagged = (part: string): number => measureWidth(face, part, spec.size, { script: scriptTag(part), shaping, rounding: rules.rounding, sum: rules.sum });
319
+ const risky = (part: string): boolean => fallback !== undefined && shapingRisks(face, part, { script: scriptTag(part), shaping }).length > 0;
320
+ if (runs.length === 1 && !risky(run)) return tagged(run);
321
+ if (shaping !== "canvas") return sum(runs, tagged);
322
+ // The width of a word comes from the word alone. This keeps the separator law of the rope
323
+ return sum(canvasWords(run), (word) => {
324
+ const parts = scriptRuns(word);
325
+ return parts.some(risky) ? fallback!(word, font) : sum(parts, tagged);
326
+ });
327
+ };
287
328
  if (fonts.length === 1) return measure(text, fonts[0]!);
288
329
  let width = 0;
289
330
  let run = "";
package/src/measurer.ts CHANGED
@@ -2,4 +2,4 @@
2
2
  * The subpath `./measurer`: the advance function of a layout engine, from the font model of typeset. The measurer of
3
3
  * `@mark1russell7/layout-contract/text` takes it as its `AdvanceFn`.
4
4
  */
5
- export { fontAdvance, parseFont, scriptTag, type FontAdvanceOptions, type FontFace, type FontSpec } from "./measurer/advance.ts";
5
+ export { fontAdvance, parseFont, scriptTag, type AdvanceFn, type FontAdvanceOptions, type FontFace, type FontSpec } from "./measurer/advance.ts";