@mark1russell7/typeset 0.1.3 → 0.1.4

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.
@@ -21,7 +21,7 @@ interface WidthBound {
21
21
  * A text with another character has no limit from this function.
22
22
  *
23
23
  * The limit is sound, not tight. It follows the widest character of the set. It includes each glyph of the GSUB closure, each
24
- * dotted circle, each part or composite of the Indic normalization, and the largest positive kerning.
24
+ * dotted circle, each part or composite of the normalization, and the largest positive kerning.
25
25
  */
26
26
  declare function widthBound(font: Font, characters: string, options?: MeasureOptions): WidthBound;
27
27
  declare namespace fonts_d_exports {
@@ -1 +1 @@
1
- {"version":3,"file":"fonts.d.ts","names":[],"sources":["../../src/fonts/bound.ts","../../src/fonts.ts"],"mappings":";;;;UAMiB;;WAEN;;WAEA;;WAEA;;;;;EAKT,MAAM,gBAAgB;;;;;;;;;;iBA6FR,WAAW,MAAM,MAAM,oBAAoB,UAAS,iBAAsB"}
1
+ {"version":3,"file":"fonts.d.ts","names":[],"sources":["../../src/fonts/bound.ts","../../src/fonts.ts"],"mappings":";;;;UAOiB;;WAEN;;WAEA;;WAEA;;;;;EAKT,MAAM,gBAAgB;;;;;;;;;;iBA6FR,WAAW,MAAM,MAAM,oBAAoB,UAAS,iBAAsB"}
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime.js";
2
- import { c as indicFeatures, i as shapingOf, l as indicForms, n as measureWidth, r as readFont, s as joiningStages } from "./font.js";
2
+ import { c as joiningStages, d as normalForms, i as shapingOf, l as indicFeatures, n as measureWidth, r as readFont, u as indicForms } from "./font.js";
3
3
  import { n as isEngineName, t as engines } from "./engines.js";
4
4
  // src/fonts/bound.ts
5
5
  /**
@@ -89,32 +89,33 @@ function expansionsOf(font, reached, lookups, rounds) {
89
89
  * A text with another character has no limit from this function.
90
90
  *
91
91
  * The limit is sound, not tight. It follows the widest character of the set. It includes each glyph of the GSUB closure, each
92
- * dotted circle, each part or composite of the Indic normalization, and the largest positive kerning.
92
+ * dotted circle, each part or composite of the normalization, and the largest positive kerning.
93
93
  */
94
94
  function widthBound(font, characters, options = {}) {
95
95
  const { script, features, shaper, kerning: pairLookups } = shapingOf(font, options);
96
96
  const set = new Set(Array.from(characters, (character) => character.codePointAt(0)));
97
- const indic = shaper === "indic" ? indicForms(set, (codePoint) => font.glyph(codePoint) !== 0) : void 0;
98
- const reached = new Set([...indic?.codePoints ?? set].map((codePoint) => font.glyph(codePoint)));
97
+ const hasGlyph = (codePoint) => font.glyph(codePoint) !== 0;
98
+ const forms = shaper === "indic" ? indicForms(set, hasGlyph) : normalForms(set, hasGlyph);
99
+ const reached = new Set([...forms.codePoints].map((codePoint) => font.glyph(codePoint)));
99
100
  const tags = shaper === "indic" ? indicFeatures(features) : shaper === "joining" ? joiningStages(features, true).flatMap((stage) => stage.features) : features;
100
101
  const lookups = font.substitutions(script, tags).map((lookup) => lookup.rules());
101
102
  reach(reached, lookups.flat(2));
102
103
  const expansions = expansionsOf(font, reached, lookups, shaper === "plain" ? 1 : ROUNDS);
103
- const form = (codePoint) => (indic?.composites.get(codePoint) ?? []).reduce((best, composite) => larger(best, form(composite)), expansions.get(font.glyph(codePoint)));
104
- const inserted = indic === void 0 ? {
104
+ const form = (codePoint) => (forms.composites.get(codePoint) ?? []).reduce((best, composite) => larger(best, form(composite)), expansions.get(font.glyph(codePoint)));
105
+ const inserted = shaper === "indic" ? expansions.get(font.glyph(9676)) : {
105
106
  advance: 0,
106
107
  glyphs: 0
107
- } : expansions.get(font.glyph(9676));
108
+ };
108
109
  let largest = {
109
110
  advance: 0,
110
111
  glyphs: 0
111
112
  };
112
113
  for (const codePoint of set) {
113
- const parts = indic?.parts.get(codePoint) ?? [codePoint];
114
- largest = larger(largest, parts.reduce((total, part) => sum(total, sum(form(part), inserted)), {
114
+ const decomposed = forms.parts.get(codePoint).reduce((total, part) => sum(total, sum(form(part), inserted)), {
115
115
  advance: 0,
116
116
  glyphs: 0
117
- }));
117
+ });
118
+ largest = larger(largest, larger(decomposed, sum(form(codePoint), inserted)));
118
119
  }
119
120
  let kerning = 0;
120
121
  for (const lookup of pairLookups) {
@@ -1 +1 @@
1
- {"version":3,"file":"fonts.js","names":[],"sources":["../../src/fonts/bound.ts","../../src/fonts.ts"],"sourcesContent":["import { shapingOf, type Font, type MeasureOptions } from \"./font.ts\";\nimport { indicFeatures, indicForms } from \"./indic.ts\";\nimport { joiningStages } from \"./joining.ts\";\nimport type { SubstitutionRule } from \"./substitution.ts\";\n\n/** The limit of `widthBound` for the width of a text over a declared set of characters. It needs no measurement. */\nexport interface WidthBound {\n /** The largest total advance of one character with all its expansions, in font units. */\n readonly advance: number;\n /** The largest positive kerning of one glyph, in font units. */\n readonly kerning: number;\n /** The largest count of glyphs of one character. */\n readonly glyphs: number;\n /**\n * This function gives the limit in px for a text of `length` UTF-16 units at the size `size`. It takes the length of a\n * string, so it does not read the text. The limit is for a text with only the characters of the set.\n */\n width(length: number, size: number): number;\n}\n\n/**\n * The largest count of passes over the lookups of a shaper with stages. A pass covers one stage, and no shaper has more stages:\n * the Indic shaper has 13 and the joining has 11. A rule that expands its own glyph has no fixed point, so it stops at this count.\n */\nconst ROUNDS = 16;\n/** The relative error of one rounding to single precision. */\nconst FLOAT32 = 2 ** -24;\n/** The relative error of one rounding to double precision. */\nconst FLOAT64 = 2 ** -53;\n/** The largest size of a kerning value of a `ValueRecord`, and of its variation delta, in font units: the range of `int16`. */\nconst KERNING_RANGE = 2 ** 15;\n\n/** The largest expansion of a glyph: the sum of its advances, and the count of its glyphs. */\ninterface Expansion {\n readonly advance: number;\n readonly glyphs: number;\n}\n\nfunction larger(a: Expansion, b: Expansion): Expansion {\n return { advance: Math.max(a.advance, b.advance), glyphs: Math.max(a.glyphs, b.glyphs) };\n}\n\nfunction sum(a: Expansion, b: Expansion): Expansion {\n return { advance: a.advance + b.advance, glyphs: a.glyphs + b.glyphs };\n}\n\n/** This function tells if a rule can apply to the glyphs `reached`. A ligature needs its first glyph and all its components. */\nfunction applies(rule: SubstitutionRule, reached: ReadonlySet<number>): boolean {\n return reached.has(rule.from) && (rule.components ?? []).every((glyph) => reached.has(glyph));\n}\n\n/** This function adds the glyphs that the rules can give to `reached`. */\nfunction reach(reached: Set<number>, rules: readonly SubstitutionRule[]): void {\n for (let size = -1; size !== reached.size; ) {\n size = reached.size;\n for (const rule of rules) if (applies(rule, reached)) for (const glyph of rule.to) reached.add(glyph);\n }\n}\n\n/**\n * This function applies one list of rules to the expansions. Each rule uses the values from before the list. A lookup applies\n * once at a position, so its output does not go back into it. The function tells if a value changed.\n */\nfunction relax(rules: readonly SubstitutionRule[], expansions: Map<number, Expansion>): boolean {\n const changes: (readonly [number, Expansion])[] = [];\n for (const { from, to } of rules) {\n const before = expansions.get(from)!;\n const after = to.reduce((total, glyph) => sum(total, expansions.get(glyph)!), { advance: 0, glyphs: 0 });\n if (after.advance > before.advance || after.glyphs > before.glyphs) changes.push([from, after]);\n }\n for (const [from, after] of changes) expansions.set(from, larger(expansions.get(from)!, after));\n return changes.length > 0;\n}\n\n/**\n * This function gives the largest expansion of each glyph of `reached`. Each ligature charges its first glyph, so each output\n * glyph comes from one input glyph. Each pass goes backward over the lookups: a glyph then gets the expansions of the lookups\n * after the lookup that makes it. A shaper with stages goes over the list again for each stage, so the passes repeat.\n *\n * One context rule can apply its nested lookups in any order. So the lists of a lookup with nested lookups repeat until no\n * value changes, with the same limit. A value that stops changing holds for each order.\n */\nfunction expansionsOf(font: Font, reached: ReadonlySet<number>, lookups: readonly (readonly (readonly SubstitutionRule[])[])[], rounds: number): Map<number, Expansion> {\n const expansions = new Map<number, Expansion>();\n for (const glyph of reached) expansions.set(glyph, { advance: Math.max(0, font.advance(glyph)), glyphs: 1 });\n const active = lookups.map((lists) => lists.map((rules) => rules.filter((rule) => applies(rule, reached))));\n for (let round = 0; round < rounds; round++) {\n let changed = false;\n for (let i = active.length - 1; i >= 0; i--) {\n const lists = active[i]!;\n for (let step = 0; step < (lists.length > 1 ? ROUNDS : 1); step++) {\n let moved = false;\n for (const rules of lists) moved = relax(rules, expansions) || moved;\n if (!moved) break;\n changed = true;\n }\n }\n if (!changed) break;\n }\n return expansions;\n}\n\n/**\n * This function gives a limit for the width of each text over the characters `characters`, with no measurement. For each such\n * text, `measureWidth(font, text, size, options)` is at most `width(text.length, size)` of the result. Give the same `options`.\n * A text with another character has no limit from this function.\n *\n * The limit is sound, not tight. It follows the widest character of the set. It includes each glyph of the GSUB closure, each\n * dotted circle, each part or composite of the Indic normalization, and the largest positive kerning.\n */\nexport function widthBound(font: Font, characters: string, options: MeasureOptions = {}): WidthBound {\n const { script, features, shaper, kerning: pairLookups } = shapingOf(font, options);\n const set = new Set(Array.from(characters, (character) => character.codePointAt(0)!));\n const indic = shaper === \"indic\" ? indicForms(set, (codePoint) => font.glyph(codePoint) !== 0) : undefined;\n\n // The roots: the glyph of each code point that the shaper can see. A character with no glyph gives the glyph 0\n const reached = new Set([...(indic?.codePoints ?? set)].map((codePoint) => font.glyph(codePoint)));\n // A union of the features gives the same lookups as the union of the stages. Each stage then counts, in the rounds\n const tags = shaper === \"indic\" ? indicFeatures(features) : shaper === \"joining\" ? joiningStages(features, true).flatMap((stage) => stage.features) : features;\n const lookups = font.substitutions(script, tags).map((lookup) => lookup.rules());\n reach(reached, lookups.flat(2));\n // The plain shaper is one stage: it applies each lookup once, in the order of the list\n const expansions = expansionsOf(font, reached, lookups, shaper === \"plain\" ? 1 : ROUNDS);\n\n const form = (codePoint: number): Expansion => (indic?.composites.get(codePoint) ?? []).reduce((best, composite) => larger(best, form(composite)), expansions.get(font.glyph(codePoint))!);\n // The Indic shaper can insert a dotted circle before each code point. Without a glyph, the code point U+25CC gives the glyph 0.\n // One code point gets at most one: a circle of the vowel constraints takes the next matra, so that syllable is not broken\n const inserted = indic === undefined ? { advance: 0, glyphs: 0 } : expansions.get(font.glyph(0x25cc))!;\n let largest: Expansion = { advance: 0, glyphs: 0 };\n for (const codePoint of set) {\n const parts = indic?.parts.get(codePoint) ?? [codePoint];\n largest = larger(largest, parts.reduce((total, part) => sum(total, sum(form(part), inserted)), { advance: 0, glyphs: 0 }));\n }\n\n // One glyph gets at most one first value and one second value from each lookup, and each subtable of a lookup is an alternative\n let kerning = 0;\n for (const lookup of pairLookups) {\n const { first, second } = lookup.largest(reached);\n kerning += first + second;\n }\n\n const { advance, glyphs } = largest;\n const pixel = options.rounding === \"pixel\";\n const float32 = options.sum === \"float32\" && !pixel;\n // Pixel: an advance gets at most 1/128 px from the grid of 26.6, and then 0.5 px. A kerning sum gets at most 0.5 px\n const pixelMargin = pixel ? 0.5 + 1 / 128 + (kerning > 0 ? 0.5 : 0) : 0;\n // Float32: each lookup gives a glyph two positions, in units of 1/65536 px. A negative value gets no help from the relative\n // factor below, so it has its own margin. The floor of a value and the round of a delta give 1 unit, the floor of the\n // multiplier gives 0.5 units, and the cut of the scale gives KERNING_RANGE / unitsPerEm units to each of the two parts.\n // The single precision gives FLOAT32 to the value and 4 FLOAT32 to the delta\n const positions = pairLookups.length * 2;\n const positionMargin = float32 ? (positions * (1.5 + (2 * KERNING_RANGE) / font.unitsPerEm)) / 65536 : 0;\n const kerningMargin = float32 ? positions * 5 * FLOAT32 * KERNING_RANGE : 0;\n return {\n advance,\n kerning,\n glyphs,\n width(length: number, size: number): number {\n const total = length * ((advance + glyphs * (kerning + kerningMargin)) * (size / font.unitsPerEm) + glyphs * (pixelMargin + positionMargin));\n // Float32: the fround of a glyph or 4 steps of a positive delta, the fround of a segment, and one step of the sum for\n // each segment. A text has at most one segment for each UTF-16 unit\n const single = float32 ? (1 + FLOAT32) ** (length + 6) : 1;\n // The double precision: the scale and a few products, and one rounding for each step of a sum of fractions\n return total * single * (1 + (2 ** 13 + length) * FLOAT64);\n },\n };\n}\n","/**\n * The subpath `./fonts`: the font model of typeset. It reads the tables of a TrueType, OpenType or WOFF2 file. It gives\n * the width of a text as the text engine of a browser gives it. The host gives the bytes of the font files.\n */\nexport { measureWidth, readFont, type Font, type MeasureOptions, type ReadOptions } from \"./fonts/font.ts\";\nexport { widthBound, type WidthBound } from \"./fonts/bound.ts\";\nexport { engines, isEngineName, type EngineName, type EngineRules } from \"./fonts/engines.ts\";\nexport type { Decompress } from \"./fonts/sfnt.ts\";\nexport type { Axis, Instance } from \"./fonts/variations.ts\";\n"],"mappings":";;;;;;;;AAwBA,MAAM,SAAS;;AAEf,MAAM,UAAU,KAAK;;AAErB,MAAM,UAAU,KAAK;;AAErB,MAAM,gBAAgB,KAAK;AAQ3B,SAAS,OAAO,GAAc,GAAyB;CACrD,OAAO;EAAE,SAAS,KAAK,IAAI,EAAE,SAAS,EAAE,OAAO;EAAG,QAAQ,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM;CAAE;AACzF;AAEA,SAAS,IAAI,GAAc,GAAyB;CAClD,OAAO;EAAE,SAAS,EAAE,UAAU,EAAE;EAAS,QAAQ,EAAE,SAAS,EAAE;CAAO;AACvE;;AAGA,SAAS,QAAQ,MAAwB,SAAuC;CAC9E,OAAO,QAAQ,IAAI,KAAK,IAAI,MAAM,KAAK,cAAc,CAAC,EAAA,CAAG,OAAO,UAAU,QAAQ,IAAI,KAAK,CAAC;AAC9F;;AAGA,SAAS,MAAM,SAAsB,OAA0C;CAC7E,KAAK,IAAI,OAAO,IAAI,SAAS,QAAQ,OAAQ;EAC3C,OAAO,QAAQ;EACf,KAAK,MAAM,QAAQ,OAAO,IAAI,QAAQ,MAAM,OAAO,GAAG,KAAK,MAAM,SAAS,KAAK,IAAI,QAAQ,IAAI,KAAK;CACtG;AACF;;;;;AAMA,SAAS,MAAM,OAAoC,YAA6C;CAC9F,MAAM,UAA4C,CAAC;CACnD,KAAK,MAAM,EAAE,MAAM,QAAQ,OAAO;EAChC,MAAM,SAAS,WAAW,IAAI,IAAI;EAClC,MAAM,QAAQ,GAAG,QAAQ,OAAO,UAAU,IAAI,OAAO,WAAW,IAAI,KAAK,CAAE,GAAG;GAAE,SAAS;GAAG,QAAQ;EAAE,CAAC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MAAM,QAAQ,QAAQ,aAAa;CACnC,MAAM,UAAU,QAAQ,QAAQ,aAAa,CAAC;CAE9C,MAAM,cAAc,QAAQ,YAAiB,UAAU,IAAI,KAAM,KAAK;CAKtE,MAAM,YAAY,YAAY,SAAS;CACvC,MAAM,iBAAiB,UAAW,aAAa,MAAO,IAAI,gBAAiB,KAAK,cAAe,QAAQ;CACvG,MAAM,gBAAgB,UAAU,YAAY,IAAI,UAAU,gBAAgB;CAC1E,OAAO;EACL;EACA;EACA;EACA,MAAM,QAAgB,MAAsB;GAM1C,OALc,WAAW,UAAU,UAAU,UAAU,mBAAmB,OAAO,KAAK,cAAc,UAAU,cAAc,oBAG7G,WAAW,IAAI,aAAa,SAAS,KAAK,MAEhC,KAAK,OAAU,UAAU;EACpD;CACF;AACF"}
1
+ {"version":3,"file":"fonts.js","names":[],"sources":["../../src/fonts/bound.ts","../../src/fonts.ts"],"sourcesContent":["import { shapingOf, type Font, type MeasureOptions } from \"./font.ts\";\nimport { indicFeatures, indicForms } from \"./indic.ts\";\nimport { joiningStages } from \"./joining.ts\";\nimport { normalForms } from \"./normalize.ts\";\nimport type { SubstitutionRule } from \"./substitution.ts\";\n\n/** The limit of `widthBound` for the width of a text over a declared set of characters. It needs no measurement. */\nexport interface WidthBound {\n /** The largest total advance of one character with all its expansions, in font units. */\n readonly advance: number;\n /** The largest positive kerning of one glyph, in font units. */\n readonly kerning: number;\n /** The largest count of glyphs of one character. */\n readonly glyphs: number;\n /**\n * This function gives the limit in px for a text of `length` UTF-16 units at the size `size`. It takes the length of a\n * string, so it does not read the text. The limit is for a text with only the characters of the set.\n */\n width(length: number, size: number): number;\n}\n\n/**\n * The largest count of passes over the lookups of a shaper with stages. A pass covers one stage, and no shaper has more stages:\n * the Indic shaper has 13 and the joining has 11. A rule that expands its own glyph has no fixed point, so it stops at this count.\n */\nconst ROUNDS = 16;\n/** The relative error of one rounding to single precision. */\nconst FLOAT32 = 2 ** -24;\n/** The relative error of one rounding to double precision. */\nconst FLOAT64 = 2 ** -53;\n/** The largest size of a kerning value of a `ValueRecord`, and of its variation delta, in font units: the range of `int16`. */\nconst KERNING_RANGE = 2 ** 15;\n\n/** The largest expansion of a glyph: the sum of its advances, and the count of its glyphs. */\ninterface Expansion {\n readonly advance: number;\n readonly glyphs: number;\n}\n\nfunction larger(a: Expansion, b: Expansion): Expansion {\n return { advance: Math.max(a.advance, b.advance), glyphs: Math.max(a.glyphs, b.glyphs) };\n}\n\nfunction sum(a: Expansion, b: Expansion): Expansion {\n return { advance: a.advance + b.advance, glyphs: a.glyphs + b.glyphs };\n}\n\n/** This function tells if a rule can apply to the glyphs `reached`. A ligature needs its first glyph and all its components. */\nfunction applies(rule: SubstitutionRule, reached: ReadonlySet<number>): boolean {\n return reached.has(rule.from) && (rule.components ?? []).every((glyph) => reached.has(glyph));\n}\n\n/** This function adds the glyphs that the rules can give to `reached`. */\nfunction reach(reached: Set<number>, rules: readonly SubstitutionRule[]): void {\n for (let size = -1; size !== reached.size; ) {\n size = reached.size;\n for (const rule of rules) if (applies(rule, reached)) for (const glyph of rule.to) reached.add(glyph);\n }\n}\n\n/**\n * This function applies one list of rules to the expansions. Each rule uses the values from before the list. A lookup applies\n * once at a position, so its output does not go back into it. The function tells if a value changed.\n */\nfunction relax(rules: readonly SubstitutionRule[], expansions: Map<number, Expansion>): boolean {\n const changes: (readonly [number, Expansion])[] = [];\n for (const { from, to } of rules) {\n const before = expansions.get(from)!;\n const after = to.reduce((total, glyph) => sum(total, expansions.get(glyph)!), { advance: 0, glyphs: 0 });\n if (after.advance > before.advance || after.glyphs > before.glyphs) changes.push([from, after]);\n }\n for (const [from, after] of changes) expansions.set(from, larger(expansions.get(from)!, after));\n return changes.length > 0;\n}\n\n/**\n * This function gives the largest expansion of each glyph of `reached`. Each ligature charges its first glyph, so each output\n * glyph comes from one input glyph. Each pass goes backward over the lookups: a glyph then gets the expansions of the lookups\n * after the lookup that makes it. A shaper with stages goes over the list again for each stage, so the passes repeat.\n *\n * One context rule can apply its nested lookups in any order. So the lists of a lookup with nested lookups repeat until no\n * value changes, with the same limit. A value that stops changing holds for each order.\n */\nfunction expansionsOf(font: Font, reached: ReadonlySet<number>, lookups: readonly (readonly (readonly SubstitutionRule[])[])[], rounds: number): Map<number, Expansion> {\n const expansions = new Map<number, Expansion>();\n for (const glyph of reached) expansions.set(glyph, { advance: Math.max(0, font.advance(glyph)), glyphs: 1 });\n const active = lookups.map((lists) => lists.map((rules) => rules.filter((rule) => applies(rule, reached))));\n for (let round = 0; round < rounds; round++) {\n let changed = false;\n for (let i = active.length - 1; i >= 0; i--) {\n const lists = active[i]!;\n for (let step = 0; step < (lists.length > 1 ? ROUNDS : 1); step++) {\n let moved = false;\n for (const rules of lists) moved = relax(rules, expansions) || moved;\n if (!moved) break;\n changed = true;\n }\n }\n if (!changed) break;\n }\n return expansions;\n}\n\n/**\n * This function gives a limit for the width of each text over the characters `characters`, with no measurement. For each such\n * text, `measureWidth(font, text, size, options)` is at most `width(text.length, size)` of the result. Give the same `options`.\n * A text with another character has no limit from this function.\n *\n * The limit is sound, not tight. It follows the widest character of the set. It includes each glyph of the GSUB closure, each\n * dotted circle, each part or composite of the normalization, and the largest positive kerning.\n */\nexport function widthBound(font: Font, characters: string, options: MeasureOptions = {}): WidthBound {\n const { script, features, shaper, kerning: pairLookups } = shapingOf(font, options);\n const set = new Set(Array.from(characters, (character) => character.codePointAt(0)!));\n const hasGlyph = (codePoint: number): boolean => font.glyph(codePoint) !== 0;\n const forms = shaper === \"indic\" ? indicForms(set, hasGlyph) : normalForms(set, hasGlyph);\n\n // The roots: the glyph of each code point that the shaper can see. A character with no glyph gives the glyph 0\n const reached = new Set([...forms.codePoints].map((codePoint) => font.glyph(codePoint)));\n // A union of the features gives the same lookups as the union of the stages. Each stage then counts, in the rounds\n const tags = shaper === \"indic\" ? indicFeatures(features) : shaper === \"joining\" ? joiningStages(features, true).flatMap((stage) => stage.features) : features;\n const lookups = font.substitutions(script, tags).map((lookup) => lookup.rules());\n reach(reached, lookups.flat(2));\n // The plain shaper is one stage: it applies each lookup once, in the order of the list\n const expansions = expansionsOf(font, reached, lookups, shaper === \"plain\" ? 1 : ROUNDS);\n\n const form = (codePoint: number): Expansion => (forms.composites.get(codePoint) ?? []).reduce((best, composite) => larger(best, form(composite)), expansions.get(font.glyph(codePoint))!);\n // The Indic shaper can insert a dotted circle before each code point. Without a glyph, the code point U+25CC gives the glyph 0.\n // One code point gets at most one: a circle of the vowel constraints takes the next matra, so that syllable is not broken\n const inserted = shaper === \"indic\" ? expansions.get(font.glyph(0x25cc))! : { advance: 0, glyphs: 0 };\n let largest: Expansion = { advance: 0, glyphs: 0 };\n for (const codePoint of set) {\n // A character with a mark decomposes, and a character with no mark near it keeps its form. So the larger of the two counts\n const decomposed = forms.parts.get(codePoint)!.reduce((total, part) => sum(total, sum(form(part), inserted)), { advance: 0, glyphs: 0 });\n largest = larger(largest, larger(decomposed, sum(form(codePoint), inserted)));\n }\n\n // One glyph gets at most one first value and one second value from each lookup, and each subtable of a lookup is an alternative\n let kerning = 0;\n for (const lookup of pairLookups) {\n const { first, second } = lookup.largest(reached);\n kerning += first + second;\n }\n\n const { advance, glyphs } = largest;\n const pixel = options.rounding === \"pixel\";\n const float32 = options.sum === \"float32\" && !pixel;\n // Pixel: an advance gets at most 1/128 px from the grid of 26.6, and then 0.5 px. A kerning sum gets at most 0.5 px\n const pixelMargin = pixel ? 0.5 + 1 / 128 + (kerning > 0 ? 0.5 : 0) : 0;\n // Float32: each lookup gives a glyph two positions, in units of 1/65536 px. A negative value gets no help from the relative\n // factor below, so it has its own margin. The floor of a value and the round of a delta give 1 unit, the floor of the\n // multiplier gives 0.5 units, and the cut of the scale gives KERNING_RANGE / unitsPerEm units to each of the two parts.\n // The single precision gives FLOAT32 to the value and 4 FLOAT32 to the delta\n const positions = pairLookups.length * 2;\n const positionMargin = float32 ? (positions * (1.5 + (2 * KERNING_RANGE) / font.unitsPerEm)) / 65536 : 0;\n const kerningMargin = float32 ? positions * 5 * FLOAT32 * KERNING_RANGE : 0;\n return {\n advance,\n kerning,\n glyphs,\n width(length: number, size: number): number {\n const total = length * ((advance + glyphs * (kerning + kerningMargin)) * (size / font.unitsPerEm) + glyphs * (pixelMargin + positionMargin));\n // Float32: the fround of a glyph or 4 steps of a positive delta, the fround of a segment, and one step of the sum for\n // each segment. A text has at most one segment for each UTF-16 unit\n const single = float32 ? (1 + FLOAT32) ** (length + 6) : 1;\n // The double precision: the scale and a few products, and one rounding for each step of a sum of fractions\n return total * single * (1 + (2 ** 13 + length) * FLOAT64);\n },\n };\n}\n","/**\n * The subpath `./fonts`: the font model of typeset. It reads the tables of a TrueType, OpenType or WOFF2 file. It gives\n * the width of a text as the text engine of a browser gives it. The host gives the bytes of the font files.\n */\nexport { measureWidth, readFont, type Font, type MeasureOptions, type ReadOptions } from \"./fonts/font.ts\";\nexport { widthBound, type WidthBound } from \"./fonts/bound.ts\";\nexport { engines, isEngineName, type EngineName, type EngineRules } from \"./fonts/engines.ts\";\nexport type { Decompress } from \"./fonts/sfnt.ts\";\nexport type { Axis, Instance } from \"./fonts/variations.ts\";\n"],"mappings":";;;;;;;;AAyBA,MAAM,SAAS;;AAEf,MAAM,UAAU,KAAK;;AAErB,MAAM,UAAU,KAAK;;AAErB,MAAM,gBAAgB,KAAK;AAQ3B,SAAS,OAAO,GAAc,GAAyB;CACrD,OAAO;EAAE,SAAS,KAAK,IAAI,EAAE,SAAS,EAAE,OAAO;EAAG,QAAQ,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM;CAAE;AACzF;AAEA,SAAS,IAAI,GAAc,GAAyB;CAClD,OAAO;EAAE,SAAS,EAAE,UAAU,EAAE;EAAS,QAAQ,EAAE,SAAS,EAAE;CAAO;AACvE;;AAGA,SAAS,QAAQ,MAAwB,SAAuC;CAC9E,OAAO,QAAQ,IAAI,KAAK,IAAI,MAAM,KAAK,cAAc,CAAC,EAAA,CAAG,OAAO,UAAU,QAAQ,IAAI,KAAK,CAAC;AA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I,KAAK,MAAM,IAAM,CAAC,IAAK;EAAE,SAAS;EAAG,QAAQ;CAAE;CACpG,IAAI,UAAqB;EAAE,SAAS;EAAG,QAAQ;CAAE;CACjD,KAAK,MAAM,aAAa,KAAK;EAE3B,MAAM,aAAa,MAAM,MAAM,IAAI,SAAS,CAAC,CAAE,QAAQ,OAAO,SAAS,IAAI,OAAO,IAAI,KAAK,IAAI,GAAG,QAAQ,CAAC,GAAG;GAAE,SAAS;GAAG,QAAQ;EAAE,CAAC;EACvI,UAAU,OAAO,SAAS,OAAO,YAAY,IAAI,KAAK,SAAS,GAAG,QAAQ,CAAC,CAAC;CAC9E;CAGA,IAAI,UAAU;CACd,KAAK,MAAM,UAAU,aAAa;EAChC,MAAM,EAAE,OAAO,WAAW,OAAO,QAAQ,OAAO;EAChD,WAAW,QAAQ;CACrB;CAEA,MAAM,EAAE,SAAS,WAAW;CAC5B,MAAM,QAAQ,QAAQ,aAAa;CACnC,MAAM,UAAU,QAAQ,QAAQ,aAAa,CAAC;CAE9C,MAAM,cAAc,QAAQ,YAAiB,UAAU,IAAI,KAAM,KAAK;CAKtE,MAAM,YAAY,YAAY,SAAS;CACvC,MAAM,iBAAiB,UAAW,aAAa,MAAO,IAAI,gBAAiB,KAAK,cAAe,QAAQ;CACvG,MAAM,gBAAgB,UAAU,YAAY,IAAI,UAAU,gBAAgB;CAC1E,OAAO;EACL;EACA;EACA;EACA,MAAM,QAAgB,MAAsB;GAM1C,OALc,WAAW,UAAU,UAAU,UAAU,mBAAmB,OAAO,KAAK,cAAc,UAAU,cAAc,oBAG7G,WAAW,IAAI,aAAa,SAAS,KAAK,MAEhC,KAAK,OAAU,UAAU;EACpD;CACF;AACF"}
@@ -6,5 +6,10 @@ import { n as readTables } from "./chunks/sfnt.js";
6
6
  * Common after it.
7
7
  */
8
8
  export declare function canvasWords(text: string): string[];
9
+ /**
10
+ * This function gives the segments of the text of a canvas in the visual order. A segment is a word of `canvasWords`, or a
11
+ * part of a word where the bidi level changes. Blink shapes each bidi run alone and adds the widths of the words in this order.
12
+ */
13
+ export declare function canvasSegments(text: string): string[];
9
14
  export { defaultFeatures, glyphAdvances, readTables, shapingWords };
10
15
  //# sourceMappingURL=fonts-inspect.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fonts-inspect.d.ts","names":[],"sources":["../src/fonts/words.ts"],"mappings":";;;;;;;wBAwDgB,YAAY"}
1
+ {"version":3,"file":"fonts-inspect.d.ts","names":[],"sources":["../src/fonts/words.ts"],"mappings":";;;;;;;wBAwDgB,YAAY;;;;;wBAgBZ,eAAe"}
@@ -1 +1 @@
1
- export { o as canvasWords, u as defaultFeatures, t as glyphAdvances, d as readTables, a as shapingWords } from "./chunks/font.js";
1
+ export { o as canvasSegments, s as canvasWords, f as defaultFeatures, t as glyphAdvances, p as readTables, a as shapingWords } from "./chunks/font.js";
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.1.3",
4
+ "version": "0.1.4",
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, and ./text has a rope.",
6
6
  "keywords": [
7
7
  "typeset",
@@ -1,6 +1,7 @@
1
1
  import { shapingOf, type Font, type MeasureOptions } from "./font.ts";
2
2
  import { indicFeatures, indicForms } from "./indic.ts";
3
3
  import { joiningStages } from "./joining.ts";
4
+ import { normalForms } from "./normalize.ts";
4
5
  import type { SubstitutionRule } from "./substitution.ts";
5
6
 
6
7
  /** The limit of `widthBound` for the width of a text over a declared set of characters. It needs no measurement. */
@@ -106,15 +107,16 @@ function expansionsOf(font: Font, reached: ReadonlySet<number>, lookups: readonl
106
107
  * A text with another character has no limit from this function.
107
108
  *
108
109
  * The limit is sound, not tight. It follows the widest character of the set. It includes each glyph of the GSUB closure, each
109
- * dotted circle, each part or composite of the Indic normalization, and the largest positive kerning.
110
+ * dotted circle, each part or composite of the normalization, and the largest positive kerning.
110
111
  */
111
112
  export function widthBound(font: Font, characters: string, options: MeasureOptions = {}): WidthBound {
112
113
  const { script, features, shaper, kerning: pairLookups } = shapingOf(font, options);
113
114
  const set = new Set(Array.from(characters, (character) => character.codePointAt(0)!));
114
- const indic = shaper === "indic" ? indicForms(set, (codePoint) => font.glyph(codePoint) !== 0) : undefined;
115
+ const hasGlyph = (codePoint: number): boolean => font.glyph(codePoint) !== 0;
116
+ const forms = shaper === "indic" ? indicForms(set, hasGlyph) : normalForms(set, hasGlyph);
115
117
 
116
118
  // The roots: the glyph of each code point that the shaper can see. A character with no glyph gives the glyph 0
117
- const reached = new Set([...(indic?.codePoints ?? set)].map((codePoint) => font.glyph(codePoint)));
119
+ const reached = new Set([...forms.codePoints].map((codePoint) => font.glyph(codePoint)));
118
120
  // A union of the features gives the same lookups as the union of the stages. Each stage then counts, in the rounds
119
121
  const tags = shaper === "indic" ? indicFeatures(features) : shaper === "joining" ? joiningStages(features, true).flatMap((stage) => stage.features) : features;
120
122
  const lookups = font.substitutions(script, tags).map((lookup) => lookup.rules());
@@ -122,14 +124,15 @@ export function widthBound(font: Font, characters: string, options: MeasureOptio
122
124
  // The plain shaper is one stage: it applies each lookup once, in the order of the list
123
125
  const expansions = expansionsOf(font, reached, lookups, shaper === "plain" ? 1 : ROUNDS);
124
126
 
125
- const form = (codePoint: number): Expansion => (indic?.composites.get(codePoint) ?? []).reduce((best, composite) => larger(best, form(composite)), expansions.get(font.glyph(codePoint))!);
127
+ const form = (codePoint: number): Expansion => (forms.composites.get(codePoint) ?? []).reduce((best, composite) => larger(best, form(composite)), expansions.get(font.glyph(codePoint))!);
126
128
  // The Indic shaper can insert a dotted circle before each code point. Without a glyph, the code point U+25CC gives the glyph 0.
127
129
  // One code point gets at most one: a circle of the vowel constraints takes the next matra, so that syllable is not broken
128
- const inserted = indic === undefined ? { advance: 0, glyphs: 0 } : expansions.get(font.glyph(0x25cc))!;
130
+ const inserted = shaper === "indic" ? expansions.get(font.glyph(0x25cc))! : { advance: 0, glyphs: 0 };
129
131
  let largest: Expansion = { advance: 0, glyphs: 0 };
130
132
  for (const codePoint of set) {
131
- const parts = indic?.parts.get(codePoint) ?? [codePoint];
132
- largest = larger(largest, parts.reduce((total, part) => sum(total, sum(form(part), inserted)), { advance: 0, glyphs: 0 }));
133
+ // A character with a mark decomposes, and a character with no mark near it keeps its form. So the larger of the two counts
134
+ const decomposed = forms.parts.get(codePoint)!.reduce((total, part) => sum(total, sum(form(part), inserted)), { advance: 0, glyphs: 0 });
135
+ largest = larger(largest, larger(decomposed, sum(form(codePoint), inserted)));
133
136
  }
134
137
 
135
138
  // One glyph gets at most one first value and one second value from each lookup, and each subtable of a lookup is an alternative
package/src/fonts/font.ts CHANGED
@@ -8,6 +8,7 @@ import { gvarAdvanceDeltas, readPointCounts, readTransformedPointCounts, type Gl
8
8
  import { instanceAdvances, normalize, readAxes, readVariationStore, type Axis, type Instance } from "./variations.ts";
9
9
  import { indicScripts, indicShaper } from "./indic.ts";
10
10
  import { joiningFeatures, joiningForms, joiningScripts, joiningStages } from "./joining.ts";
11
+ import { hasMark, normalizeCodePoints } from "./normalize.ts";
11
12
  import { canvasSegments, canvasWords } from "./words.ts";
12
13
 
13
14
  /** The options of `readFont`. */
@@ -318,9 +319,16 @@ function shaperOf(font: Font, options: MeasureOptions): { substitute: (word: str
318
319
  const joins = shaper === "joining";
319
320
  const lookups = joins ? [] : font.substitutions(script, features);
320
321
  const stages = joins ? joiningStages(features, features.includes("rclt") && font.substitutions(script, ["rclt"]).length > 0).map((stage) => ({ stage, lookups: font.substitutions(script, stage.features) })) : [];
322
+ // The shaper of Hangul has its own normalization in HarfBuzz: the mode `NONE` keeps each character with a glyph
323
+ const normalizes = script !== "hang";
324
+ const rules = { hasGlyph: (codePoint: number) => font.glyph(codePoint) !== 0, shortCircuit: true };
321
325
  const substitute = (word: string): number[] => {
322
- const codePoints = [...word].map((character) => character.codePointAt(0)!);
323
- const wordGlyphs = codePoints.map((codePoint) => font.glyph(codePoint));
326
+ let codePoints = [...word].map((character) => character.codePointAt(0)!);
327
+ let wordGlyphs = codePoints.map((codePoint) => font.glyph(codePoint));
328
+ if (normalizes && (hasMark(word) || wordGlyphs.includes(0))) {
329
+ codePoints = normalizeCodePoints(codePoints, rules);
330
+ wordGlyphs = codePoints.map((codePoint) => font.glyph(codePoint));
331
+ }
324
332
  for (const lookup of lookups) lookup.apply(wordGlyphs);
325
333
  if (joins) {
326
334
  // Each glyph has the bit of its joining form, and the bit 7 for the features of all the glyphs
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * The Indic shaper of HarfBuzz for the script Devanagari. This module follows `hb-ot-shaper-indic.cc`, the syllable machine
3
3
  * of `hb-ot-shaper-indic-machine.rl`, the dotted circles of `hb-ot-shaper-syllabic.cc` and `hb-ot-shaper-vowel-constraints.cc`,
4
- * and the normalization of `hb-ot-shape-normalize.cc`. The table of the categories comes from `hb-ot-shaper-indic-table.cc`.
4
+ * and the rules of the mode `COMPOSED_DIACRITICS_NO_SHORT_CIRCUIT`. The table of the categories comes from `hb-ot-shaper-indic-table.cc`.
5
5
  */
6
6
  import type { Font } from "./font.ts";
7
+ import { normalForms, normalizeCodePoints, type NormalForms } from "./normalize.ts";
7
8
  import { LIGATED, MULTIPLIED, SUBSTITUTED, type GlyphInfo } from "./substitution.ts";
8
9
 
9
10
  /** The OpenType script tags that use the Indic shaper in this model. */
@@ -85,29 +86,9 @@ function indicProperties(codePoint: number): [number, number] {
85
86
  return [X, END];
86
87
  }
87
88
 
88
- /**
89
- * The canonical combining classes of the marks of the Devanagari blocks that are not 0. The normalization uses them to
90
- * sort the marks and to block a composition. A mark of another block has the class 0 in this model.
91
- */
92
- const combiningClasses: readonly number[] = [
93
- 0x93c, 0x93c, 7, 0x94d, 0x94d, 9, 0x951, 0x951, 230, 0x952, 0x952, 220, 0x953, 0x954, 230, 0x1cd0, 0x1cd2, 230,
94
- 0x1cd4, 0x1cd4, 1, 0x1cd5, 0x1cd9, 220, 0x1cda, 0x1cdb, 230, 0x1cdc, 0x1cdf, 220, 0x1ce0, 0x1ce0, 230, 0x1ce2, 0x1ce8, 1,
95
- 0x1ced, 0x1ced, 220, 0x1cf4, 0x1cf4, 230, 0x1cf8, 0x1cf9, 230, 0xa8e0, 0xa8f1, 230,
96
- ];
97
-
98
- function combiningClass(codePoint: number): number {
99
- for (let i = 0; i < combiningClasses.length; i += 3) if (codePoint >= combiningClasses[i]! && codePoint <= combiningClasses[i + 1]!) return combiningClasses[i + 2]!;
100
- return 0;
101
- }
102
-
103
- const unicodeMark = /\p{M}/u;
104
89
  /** The general categories from `FORMAT` to `NON_SPACING_MARK` of HarfBuzz: a letter, a mark, or a format or other code point. */
105
90
  const letterOrMark = /[\p{L}\p{M}\p{Cf}\p{Cn}\p{Co}\p{Cs}]/u;
106
91
 
107
- function isMark(codePoint: number): boolean {
108
- return unicodeMark.test(String.fromCodePoint(codePoint));
109
- }
110
-
111
92
  /**
112
93
  * This function inserts a dotted circle in each vowel sequence of Devanagari that looks like another vowel, as
113
94
  * `_hb_preprocess_text_vowel_constraints` does.
@@ -134,90 +115,12 @@ function vowelConstraints(codePoints: readonly number[]): number[] {
134
115
  return out;
135
116
  }
136
117
 
137
- /**
138
- * This function normalizes the code points as HarfBuzz does in the mode `COMPOSED_DIACRITICS_NO_SHORT_CIRCUIT`. It
139
- * decomposes each character that has a canonical decomposition when the font has the glyphs of its parts. The letter
140
- * U+0931 does not decompose. A text with a mark after its first character then gets more steps. The function sorts the
141
- * marks, and composes each mark with its starter again when the font has the glyph of the composite.
142
- */
143
- function normalize(codePoints: readonly number[], hasGlyph: (codePoint: number) => boolean): number[] {
144
- const allSimple = !codePoints.some((codePoint, i) => i > 0 && isMark(codePoint));
145
- const decomposed = codePoints.flatMap((codePoint) => decomposition(codePoint, hasGlyph));
146
- if (allSimple) return decomposed;
147
- // A stable sort of each run of marks with a class that is not 0
148
- for (let i = 1; i < decomposed.length; i++) {
149
- for (let j = i; j > 0; j--) {
150
- const before = combiningClass(decomposed[j - 1]!);
151
- const after = combiningClass(decomposed[j]!);
152
- if (after === 0 || before <= after) break;
153
- [decomposed[j - 1], decomposed[j]] = [decomposed[j]!, decomposed[j - 1]!];
154
- }
155
- }
156
- const out: number[] = decomposed.slice(0, 1);
157
- let starter = 0;
158
- for (let i = 1; i < decomposed.length; i++) {
159
- const codePoint = decomposed[i]!;
160
- if (isMark(codePoint) && (starter === out.length - 1 || combiningClass(out[out.length - 1]!) < combiningClass(codePoint))) {
161
- const composed = compose(out[starter]!, codePoint);
162
- if (composed !== undefined && hasGlyph(composed)) {
163
- out[starter] = composed;
164
- continue;
165
- }
166
- }
167
- out.push(codePoint);
168
- if (combiningClass(codePoint) === 0) starter = out.length - 1;
169
- }
170
- return out;
171
- }
172
-
173
- /** This function gives the code points of a character after the decomposition of `normalize`. */
174
- function decomposition(codePoint: number, hasGlyph: (codePoint: number) => boolean): number[] {
175
- const parts = codePoint === 0x931 ? [codePoint] : [...String.fromCodePoint(codePoint).normalize("NFD")].map((part) => part.codePointAt(0)!);
176
- return (parts.length > 1 || parts[0] !== codePoint) && parts.every(hasGlyph) ? parts : [codePoint];
177
- }
178
-
179
- /** The code points that `normalize` and `vowelConstraints` can give for a set of characters. */
180
- export interface IndicForms {
181
- /** The parts of each character of the set after the decomposition. A character with no decomposition is its one part. */
182
- readonly parts: ReadonlyMap<number, readonly number[]>;
183
- /** The composites of each code point: the code points that it becomes when a mark composes with it. */
184
- readonly composites: ReadonlyMap<number, readonly number[]>;
185
- /** All the code points that the shaper can see: the set, its parts, the dotted circle and each composite. */
186
- readonly codePoints: ReadonlySet<number>;
187
- }
188
-
189
- /**
190
- * This function gives the code points that the normalization can give for the characters `characters`. A composite is
191
- * not always in the set: a nukta that follows U+0928 gives U+0929. The function repeats until no new composite appears.
192
- */
193
- export function indicForms(characters: ReadonlySet<number>, hasGlyph: (codePoint: number) => boolean): IndicForms {
194
- const parts = new Map([...characters].map((codePoint) => [codePoint, decomposition(codePoint, hasGlyph)]));
195
- const codePoints = new Set([...parts.values()].flat());
196
- for (const codePoint of characters) codePoints.add(codePoint);
197
- codePoints.add(0x25cc);
198
- const composites = new Map<number, number[]>();
199
- for (let size = 0; size !== codePoints.size; ) {
200
- size = codePoints.size;
201
- const marks = [...codePoints].filter(isMark);
202
- for (const starter of codePoints) {
203
- for (const mark of marks) {
204
- const composed = compose(starter, mark);
205
- if (composed === undefined || !hasGlyph(composed)) continue;
206
- const known = composites.get(starter) ?? [];
207
- if (!known.includes(composed)) composites.set(starter, [...known, composed]);
208
- codePoints.add(composed);
209
- }
210
- }
211
- }
212
- return { parts, composites, codePoints };
213
- }
118
+ /** The code points of Devanagari that do not decompose. */
119
+ const kept: ReadonlySet<number> = new Set([0x931]);
214
120
 
215
- /** This function gives the canonical composite of two code points, or `undefined`. A mark does not compose with a mark. */
216
- function compose(first: number, second: number): number | undefined {
217
- if (isMark(first)) return undefined;
218
- const composed = [(String.fromCodePoint(first) + String.fromCodePoint(second)).normalize("NFC")];
219
- const [single, ...rest] = [...composed[0]!];
220
- return rest.length === 0 && single !== undefined ? single.codePointAt(0) : undefined;
121
+ /** This function gives the code points that `normalizeCodePoints` and `vowelConstraints` can give for a set of characters. */
122
+ export function indicForms(characters: ReadonlySet<number>, hasGlyph: (codePoint: number) => boolean): NormalForms {
123
+ return normalForms(new Set([...characters, 0x25cc]), hasGlyph, kept);
221
124
  }
222
125
 
223
126
  // The syllable machine, with one letter for each category
@@ -596,7 +499,7 @@ export function indicShaper(font: Font, script: string, features: readonly strin
596
499
  };
597
500
 
598
501
  return (word: string): number[] => {
599
- const codePoints = normalize(vowelConstraints([...word].map((character) => character.codePointAt(0)!)), (codePoint) => font.glyph(codePoint) !== 0);
502
+ const codePoints = normalizeCodePoints(vowelConstraints([...word].map((character) => character.codePointAt(0)!)), { hasGlyph: (codePoint) => font.glyph(codePoint) !== 0, shortCircuit: false, kept });
600
503
  const run: Run = { glyphs: codePoints.map((codePoint) => font.glyph(codePoint)), infos: [] };
601
504
  for (const codePoint of codePoints) {
602
505
  const [category, position] = indicProperties(codePoint);
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The Unicode normalization of HarfBuzz, from `hb-ot-shape-normalize.cc`. HarfBuzz decomposes each cluster of a base and its marks.
3
+ * It then sorts the marks, and composes each mark with its base when the font has the glyph of the composite.
4
+ */
5
+
6
+ const unicodeMark = /\p{M}/u;
7
+
8
+ /**
9
+ * The classes of HarfBuzz for the marks of Hebrew and Arabic, from `hb-unicode.hh`. Their order is not the canonical order:
10
+ * for example the shadda comes first. Each other pair of marks uses the canonical order.
11
+ */
12
+ const sortClasses: ReadonlyMap<number, number> = new Map([
13
+ [0x5b0, 22], [0x5b1, 15], [0x5b2, 16], [0x5b3, 17], [0x5b4, 23], [0x5b5, 18], [0x5b6, 19], [0x5b7, 20], [0x5b8, 21], [0x5b9, 14],
14
+ [0x5ba, 14], [0x5bb, 24], [0x5bc, 12], [0x5bd, 25], [0x5bf, 13], [0x5c1, 10], [0x5c2, 11], [0x5c7, 21], [0xfb1e, 26],
15
+ [0x618, 31], [0x619, 32], [0x61a, 33], [0x64b, 28], [0x64c, 29], [0x64d, 30], [0x64e, 31], [0x64f, 32], [0x650, 33],
16
+ [0x651, 27], [0x652, 34], [0x670, 35], [0x8f0, 28], [0x8f1, 29], [0x8f2, 30],
17
+ ]);
18
+
19
+ /** This function tells if a code point is a mark of Unicode. The first mark of Unicode is U+0300. */
20
+ function isMark(codePoint: number): boolean {
21
+ return codePoint >= 0x300 && unicodeMark.test(String.fromCodePoint(codePoint));
22
+ }
23
+
24
+ /** This function tells if a text has a mark of Unicode. */
25
+ export function hasMark(text: string): boolean {
26
+ return unicodeMark.test(text);
27
+ }
28
+
29
+ function decomposed(codePoint: number): string {
30
+ return String.fromCodePoint(codePoint).normalize("NFD");
31
+ }
32
+
33
+ /**
34
+ * This function tells if the mark `second` sorts before the mark `first`. That is true when the class of `first` is larger
35
+ * than the class of `second`, and neither class is 0. The form NFD of JavaScript gives the canonical order, so no table is needed.
36
+ */
37
+ function reorders(first: number, second: number): boolean {
38
+ const firstClass = sortClasses.get(first);
39
+ const secondClass = sortClasses.get(second);
40
+ if (firstClass !== undefined && secondClass !== undefined) return firstClass > secondClass;
41
+ const text = decomposed(first) + decomposed(second);
42
+ return text.normalize("NFD") !== text;
43
+ }
44
+
45
+ /** This function tells if a code point has the combining class 0. U+0345 has the largest class of Unicode. */
46
+ function isStarter(codePoint: number): boolean {
47
+ return !isMark(codePoint) || (codePoint !== 0x345 && !reorders(0x345, codePoint));
48
+ }
49
+
50
+ /** This function gives the canonical composite of two code points, or `undefined`. A mark does not compose with a mark. */
51
+ function compose(first: number, second: number): number | undefined {
52
+ if (isMark(first)) return undefined;
53
+ const [single, ...rest] = [...String.fromCodePoint(first, second).normalize("NFC")];
54
+ return rest.length === 0 && single !== undefined ? single.codePointAt(0) : undefined;
55
+ }
56
+
57
+ /**
58
+ * This function gives the code points of a character after the decomposition. A character keeps its form when the font has
59
+ * no glyph for one of its parts, or when the set `kept` has the character.
60
+ */
61
+ function decomposition(codePoint: number, hasGlyph: (codePoint: number) => boolean, kept: ReadonlySet<number>): number[] {
62
+ const parts = kept.has(codePoint) ? [codePoint] : Array.from(decomposed(codePoint), (part) => part.codePointAt(0)!);
63
+ return (parts.length > 1 || parts[0] !== codePoint) && parts.every(hasGlyph) ? parts : [codePoint];
64
+ }
65
+
66
+ /** The rules of one shaper for `normalizeCodePoints`. */
67
+ export interface NormalizeRules {
68
+ /** This function tells if the font has a glyph for a code point. */
69
+ readonly hasGlyph: (codePoint: number) => boolean;
70
+ /**
71
+ * When this is `true`, a character with a glyph and with no mark near it keeps its form, as the mode `COMPOSED_DIACRITICS`
72
+ * of HarfBuzz does. When this is `false`, each character decomposes, as `COMPOSED_DIACRITICS_NO_SHORT_CIRCUIT` does.
73
+ */
74
+ readonly shortCircuit: boolean;
75
+ /** The code points that do not decompose. */
76
+ readonly kept?: ReadonlySet<number>;
77
+ }
78
+
79
+ /**
80
+ * This function normalizes code points as HarfBuzz does. It decomposes the characters by `rules`. A text with a mark after
81
+ * its first character then gets more steps. The function sorts the marks, and composes each mark with its starter again
82
+ * when the font has the glyph of the composite. A mark between them with the same class or a larger class blocks this.
83
+ */
84
+ export function normalizeCodePoints(codePoints: readonly number[], rules: NormalizeRules): number[] {
85
+ const { hasGlyph, shortCircuit, kept = new Set<number>() } = rules;
86
+ const marked = codePoints.map(isMark);
87
+ const parts = codePoints.flatMap((codePoint, i) => {
88
+ const simple = marked[i + 1] !== true && !(i > 0 && marked[i]!);
89
+ return shortCircuit && simple && hasGlyph(codePoint) ? [codePoint] : decomposition(codePoint, hasGlyph, kept);
90
+ });
91
+ if (!marked.slice(1).includes(true)) return parts;
92
+ // A stable sort of each run of marks with a class that is not 0
93
+ for (let i = 1; i < parts.length; i++) {
94
+ for (let j = i; j > 0 && isMark(parts[j - 1]!) && isMark(parts[j]!) && reorders(parts[j - 1]!, parts[j]!); j--) {
95
+ [parts[j - 1], parts[j]] = [parts[j]!, parts[j - 1]!];
96
+ }
97
+ }
98
+ const out: number[] = parts.slice(0, 1);
99
+ let starter = 0;
100
+ for (let i = 1; i < parts.length; i++) {
101
+ const codePoint = parts[i]!;
102
+ if (isMark(codePoint) && (starter === out.length - 1 || reorders(codePoint, out[out.length - 1]!))) {
103
+ const composed = compose(out[starter]!, codePoint);
104
+ if (composed !== undefined && hasGlyph(composed)) {
105
+ out[starter] = composed;
106
+ continue;
107
+ }
108
+ }
109
+ out.push(codePoint);
110
+ if (isStarter(codePoint)) starter = out.length - 1;
111
+ }
112
+ return out;
113
+ }
114
+
115
+ /** The code points that `normalizeCodePoints` can give for a set of characters. */
116
+ export interface NormalForms {
117
+ /** The parts of each character of the set after the decomposition. A character with no decomposition is its one part. */
118
+ readonly parts: ReadonlyMap<number, readonly number[]>;
119
+ /** The composites of each code point: the code points that it becomes when a mark composes with it. */
120
+ readonly composites: ReadonlyMap<number, readonly number[]>;
121
+ /** All the code points that the shaper can see: the set, its parts and each composite. */
122
+ readonly codePoints: ReadonlySet<number>;
123
+ }
124
+
125
+ /** This function gives the forms of a set of characters. It repeats the compositions until the set of code points is stable. */
126
+ export function normalForms(characters: ReadonlySet<number>, hasGlyph: (codePoint: number) => boolean, kept: ReadonlySet<number> = new Set()): NormalForms {
127
+ const parts = new Map([...characters].map((codePoint) => [codePoint, decomposition(codePoint, hasGlyph, kept)]));
128
+ const codePoints = new Set([...characters, ...[...parts.values()].flat()]);
129
+ const composites = new Map<number, number[]>();
130
+ for (let size = 0; size !== codePoints.size; ) {
131
+ size = codePoints.size;
132
+ const marks = [...codePoints].filter(isMark);
133
+ for (const starter of codePoints) {
134
+ for (const mark of marks) {
135
+ const composed = compose(starter, mark);
136
+ if (composed === undefined || !hasGlyph(composed)) continue;
137
+ const known = composites.get(starter) ?? [];
138
+ if (!known.includes(composed)) composites.set(starter, [...known, composed]);
139
+ codePoints.add(composed);
140
+ }
141
+ }
142
+ }
143
+ return { parts, composites, codePoints };
144
+ }
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * The subpath `./fonts/inspect`: the parts of the font model that a tool uses to examine a width. They give the glyphs,
3
- * the shaping words, the default features and the tables of a font file.
3
+ * the shaping words, the segments of a canvas, the default features and the tables of a font file.
4
4
  */
5
5
  export { glyphAdvances, shapingWords } from "./fonts/font.ts";
6
- export { canvasWords } from "./fonts/words.ts";
6
+ export { canvasSegments, canvasWords } from "./fonts/words.ts";
7
7
  export { defaultFeatures } from "./fonts/substitution.ts";
8
8
  export { readTables } from "./fonts/sfnt.ts";