@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.
@@ -24,8 +24,18 @@ interface WidthBound {
24
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
+ /** The kinds of risk. */
28
+ type ShapingRiskCode = "missing-glyph" | "unshaped-script" | "emoji-zwj" | "variation-selector" | "keycap" | "flag" | "tag" | "positioning";
29
+ /** One part of a text that the model does not shape as HarfBuzz does, in UTF-16 units. */
30
+ interface ShapingRisk {
31
+ readonly code: ShapingRiskCode;
32
+ readonly index: number;
33
+ readonly length: number;
34
+ }
35
+ /** This function gives the risks of a text in text order. An empty list is not a proof of a correct width. */
36
+ declare function shapingRisks(font: Font, text: string, options?: MeasureOptions): ShapingRisk[];
27
37
  declare namespace fonts_d_exports {
28
- export { Axis, Decompress, EngineName, EngineRules, Font, Instance, MeasureOptions, ReadOptions, WidthBound, engines, isEngineName, measureWidth, readFont, widthBound };
38
+ export { Axis, Decompress, EngineName, EngineRules, Font, Instance, MeasureOptions, ReadOptions, ShapingRisk, ShapingRiskCode, WidthBound, engines, isEngineName, measureWidth, readFont, shapingRisks, widthBound };
29
39
  }
30
- export { WidthBound as n, widthBound as r, fonts_d_exports as t };
40
+ export { WidthBound as a, shapingRisks as i, ShapingRisk as n, widthBound as o, ShapingRiskCode as r, fonts_d_exports as t };
31
41
  //# sourceMappingURL=fonts.d.ts.map
@@ -1 +1 @@
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
+ {"version":3,"file":"fonts.d.ts","names":[],"sources":["../../src/fonts/bound.ts","../../src/fonts/risks.ts","../../src/fonts.ts"],"mappings":";;;;UAOiB;;WAEN;;WAEA;;WAEA;;;;;EAKT,MAAM,gBAAgB;;;;;;;;;;iBA6FR,WAAW,MAAM,MAAM,oBAAoB,UAAS,iBAAsB;;KCzG9E;;UAGK;WACN,MAAM;WACN;WACA;;;iBAYK,aAAa,MAAM,MAAM,cAAc,UAAS,iBAAsB"}
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime.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
- import { n as isEngineName, t as engines } from "./engines.js";
2
+ import { c as joiningStages, f as normalForms, i as shapingOf, l as indicFeatures, n as measureWidth, r as readFont, u as indicForms } from "./font.js";
3
+ import { n as isEngineName, r as shapingRisks, t as engines } from "./engines.js";
4
4
  // src/fonts/bound.ts
5
5
  /**
6
6
  * The largest count of passes over the lookups of a shaper with stages. A pass covers one stage, and no shaper has more stages:
@@ -144,6 +144,7 @@ var fonts_exports = /* @__PURE__ */ __exportAll({
144
144
  isEngineName: () => isEngineName,
145
145
  measureWidth: () => measureWidth,
146
146
  readFont: () => readFont,
147
+ shapingRisks: () => shapingRisks,
147
148
  widthBound: () => widthBound
148
149
  });
149
150
  export { widthBound as n, fonts_exports as t };
@@ -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 { 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,EA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AAgB,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 { shapingRisks, type ShapingRisk, type ShapingRiskCode } from \"./fonts/risks.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;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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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"}
@@ -1,5 +1,7 @@
1
1
  import { n as EngineRules, t as EngineName } from "./engines.js";
2
2
  import { t as Decompress } from "./sfnt.js";
3
+ /** This function gives the width of a text in a CSS font, as `AdvanceFn` of layout-contract does. */
4
+ type AdvanceFn = (text: string, font: string) => number;
3
5
  /** One font file of the host, with the family, the weight and the style that CSS matches. */
4
6
  interface FontFace {
5
7
  /** The family name, as the CSS font names it. The match ignores the case. */
@@ -27,6 +29,8 @@ interface FontAdvanceOptions {
27
29
  * with `measureText`. Use `dom` for the widths of a text in a page.
28
30
  */
29
31
  readonly shaping?: "dom" | "canvas";
32
+ /** The shaper of the host. Under the shaping `canvas`, it measures each word that `shapingRisks` flags. The shaping `dom` does not use it. */
33
+ readonly fallback?: AdvanceFn;
30
34
  }
31
35
  /** The parts of a CSS font shorthand that change a width. */
32
36
  interface FontSpec {
@@ -61,7 +65,7 @@ declare function scriptTag(text: string): string;
61
65
  */
62
66
  declare function fontAdvance(options: FontAdvanceOptions): (text: string, font: string) => number;
63
67
  declare namespace measurer_d_exports {
64
- export { FontAdvanceOptions, FontFace, FontSpec, fontAdvance, parseFont, scriptTag };
68
+ export { AdvanceFn, FontAdvanceOptions, FontFace, FontSpec, fontAdvance, parseFont, scriptTag };
65
69
  }
66
- export { fontAdvance as a, FontSpec as i, FontAdvanceOptions as n, parseFont as o, FontFace as r, scriptTag as s, measurer_d_exports as t };
70
+ export { FontSpec as a, scriptTag as c, FontFace as i, AdvanceFn as n, fontAdvance as o, FontAdvanceOptions as r, parseFont as s, measurer_d_exports as t };
67
71
  //# sourceMappingURL=measurer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"measurer.d.ts","names":[],"sources":["../../src/measurer/advance.ts","../../src/measurer.ts"],"mappings":";;;UAWiB;;WAEN;;WAEA,MAAM;;;;;WAKN;;WAEA;;WAEA,aAAa;;;UAIP;;WAEN,gBAAgB;;WAEhB,SAAS,aAAa;;;;;WAKtB;;;UAIM;WACN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;iBAuBK,UAAU,eAAe;;;;;iBAiFzB,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;;;;;iBAsGzB,UAAU;;;;;;;;iBAmDV,YAAY,SAAS,sBAAsB,cAAc"}
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime.js";
2
- import { n as isEngineName, t as engines } from "./engines.js";
3
- import { n as measureWidth, r as readFont } from "./font.js";
2
+ import { n as isEngineName, r as shapingRisks, t as engines } from "./engines.js";
3
+ import { n as measureWidth, r as readFont, s as canvasWords } from "./font.js";
4
4
  // src/measurer/advance.ts
5
5
  /**
6
6
  * The advance function of the font model: the width of a text in a CSS font, as the measurer of
@@ -101,6 +101,26 @@ const scriptPatterns = [
101
101
  [/\p{sc=Han}/u, "hani"]
102
102
  ];
103
103
  const neutral = /[\p{sc=Common}\p{sc=Inherited}\p{sc=Unknown}]/u;
104
+ /** This function divides a text into parts of one script. A neutral character stays with the part before it. */
105
+ function scriptRuns(text) {
106
+ if (/^[\0-\x7f]*$/.test(text)) return [text];
107
+ const runs = [];
108
+ let run = "";
109
+ let current;
110
+ for (const character of text) {
111
+ if (!neutral.test(character)) {
112
+ const tag = scriptTag(character).replace(/kana|bopo/, "hani");
113
+ if (current !== void 0 && tag !== current) {
114
+ runs.push(run);
115
+ run = "";
116
+ }
117
+ current = tag;
118
+ }
119
+ run += character;
120
+ }
121
+ runs.push(run);
122
+ return runs;
123
+ }
104
124
  /**
105
125
  * This function gives the OpenType script tag of a text, as HarfBuzz guesses it. The tag is the script of the first
106
126
  * character that is not of the scripts Common, Inherited or Unknown. A text of only those characters, for example emoji, gets `DFLT`.
@@ -160,6 +180,7 @@ function fontAdvance(options) {
160
180
  if (typeof engine === "string" && !isEngineName(engine)) throw new RangeError(`the engine "${engine}" is not a row of engines`);
161
181
  const rules = typeof engine === "string" ? engines[engine] : engine;
162
182
  const shaping = options.shaping ?? "canvas";
183
+ const fallback = shaping === "canvas" ? options.fallback : void 0;
163
184
  const faces = options.faces;
164
185
  const loaded = /* @__PURE__ */ new Map();
165
186
  const specs = /* @__PURE__ */ new Map();
@@ -240,12 +261,26 @@ function fontAdvance(options) {
240
261
  };
241
262
  return (text, font) => {
242
263
  const { spec, fonts } = fontsOf(font);
243
- const measure = (run, face) => measureWidth(face, run, spec.size, {
244
- script: scriptTag(run),
245
- shaping,
246
- rounding: rules.rounding,
247
- sum: rules.sum
248
- });
264
+ const sum = (parts, width) => parts.reduce((total, part) => total + width(part), 0);
265
+ const measure = (run, face) => {
266
+ const runs = scriptRuns(run);
267
+ const tagged = (part) => measureWidth(face, part, spec.size, {
268
+ script: scriptTag(part),
269
+ shaping,
270
+ rounding: rules.rounding,
271
+ sum: rules.sum
272
+ });
273
+ const risky = (part) => fallback !== void 0 && shapingRisks(face, part, {
274
+ script: scriptTag(part),
275
+ shaping
276
+ }).length > 0;
277
+ if (runs.length === 1 && !risky(run)) return tagged(run);
278
+ if (shaping !== "canvas") return sum(runs, tagged);
279
+ return sum(canvasWords(run), (word) => {
280
+ const parts = scriptRuns(word);
281
+ return parts.some(risky) ? fallback(word, font) : sum(parts, tagged);
282
+ });
283
+ };
249
284
  if (fonts.length === 1) return measure(text, fonts[0]);
250
285
  let width = 0;
251
286
  let run = "";
@@ -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 type { Decompress } from \"../fonts/sfnt.ts\";\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}\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 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/**\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 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 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 measure = (run: string, face: Font): number => measureWidth(face, run, spec.size, { script: scriptTag(run), shaping, rounding: rules.rounding, sum: rules.sum });\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 FontAdvanceOptions, type FontFace, type FontSpec } from \"./measurer/advance.ts\";\n"],"mappings":";;;;;;;;;;AAuDA,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,MAAw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AK,KAAK,MAAM;GAAE,QAAQ,UAAU,GAAG;GAAG;GAAS,UAAU,MAAM;GAAU,KAAK,MAAM;EAAI,CAAC;EACrK,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 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 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,QAA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ACV,OAAO;GACP,SAAS,SAAS;EACpB;EACA,IAAI,IAAI,SAAS,GAAG,SAAS,QAAQ,KAAK,OAAQ;EAClD,OAAO;CACT;AACF"}
@@ -1 +1 @@
1
- export { o as canvasSegments, s as canvasWords, f as defaultFeatures, t as glyphAdvances, p as readTables, a as shapingWords } from "./chunks/font.js";
1
+ export { o as canvasSegments, s as canvasWords, h as defaultFeatures, t as glyphAdvances, m as readTables, a as shapingWords } from "./chunks/font.js";
package/build/fonts.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as Decompress } from "./chunks/sfnt.js";
2
2
  import { a as measureWidth, c as Axis, l as Instance, n as MeasureOptions, o as readFont, r as ReadOptions, t as Font } from "./chunks/font.js";
3
- import { n as WidthBound, r as widthBound } from "./chunks/fonts.js";
3
+ import { a as WidthBound, i as shapingRisks, n as ShapingRisk, o as widthBound, r as ShapingRiskCode } from "./chunks/fonts.js";
4
4
  import { i as isEngineName, n as EngineRules, r as engines, t as EngineName } from "./chunks/engines.js";
5
- export { type Axis, type Decompress, type EngineName, type EngineRules, type Font, type Instance, type MeasureOptions, type ReadOptions, type WidthBound, engines, isEngineName, measureWidth, readFont, widthBound };
5
+ export { type Axis, type Decompress, type EngineName, type EngineRules, type Font, type Instance, type MeasureOptions, type ReadOptions, type ShapingRisk, type ShapingRiskCode, type WidthBound, engines, isEngineName, measureWidth, readFont, shapingRisks, widthBound };
package/build/fonts.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { n as measureWidth, r as readFont } from "./chunks/font.js";
2
2
  import { n as widthBound } from "./chunks/fonts.js";
3
- import { n as isEngineName, t as engines } from "./chunks/engines.js";
4
- export { engines, isEngineName, measureWidth, readFont, widthBound };
3
+ import { n as isEngineName, r as shapingRisks, t as engines } from "./chunks/engines.js";
4
+ export { engines, isEngineName, measureWidth, readFont, shapingRisks, widthBound };
@@ -1,2 +1,2 @@
1
- import { a as fontAdvance, i as FontSpec, n as FontAdvanceOptions, o as parseFont, r as FontFace, s as scriptTag } from "./chunks/measurer.js";
2
- export { type FontAdvanceOptions, type FontFace, type FontSpec, fontAdvance, parseFont, scriptTag };
1
+ import { a as FontSpec, c as scriptTag, i as FontFace, n as AdvanceFn, o as fontAdvance, r as FontAdvanceOptions, s as parseFont } from "./chunks/measurer.js";
2
+ export { type AdvanceFn, type FontAdvanceOptions, type FontFace, type FontSpec, fontAdvance, parseFont, scriptTag };
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.4",
4
+ "version": "0.1.5",
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",
@@ -0,0 +1,48 @@
1
+ /** The GPOS lookups of `kern` and `dist` outside PairPos. The model only detects them. */
2
+ import type { Reader } from "./binary.ts";
3
+ import { lookupSkip, pairLookupIndices, subtablesOf } from "./kerning.ts";
4
+ import { chainRecords, contextRecords, type GlyphFilter } from "./substitution.ts";
5
+ import { coverageIndex } from "./tables.ts";
6
+
7
+ /**
8
+ * This function gives a test for each such lookup that can change an advance. A chained rule of format 3 must match.
9
+ * Another rule needs only its coverage. With `zeroesMarks`, HarfBuzz zeroes a mark after GPOS, so a value on a mark changes no width.
10
+ */
11
+ export function readContextKerning(gpos: Reader, script: string, filter: GlyphFilter, zeroesMarks: boolean): ((glyphs: readonly number[]) => boolean)[] {
12
+ const lookups = gpos.part(gpos.u16(8));
13
+ const lookupAt = (index: number): Reader => lookups.part(lookups.u16(2 + index * 2));
14
+ const changes = (type: number, t: Reader, depth: number): boolean => {
15
+ if (type === 7 || type === 8) return depth < 8 && (type === 7 ? contextRecords(t) : chainRecords(t)).some((record) => subtablesOf(lookupAt(record.lookupIndex), 9).some(([nested, table]) => changes(nested, table, depth + 1)));
16
+ // The bits 0x44 are XAdvance and its device table
17
+ return type === 3 || ((type === 1 || type === 2) && ((t.u16(4) | (type === 2 ? t.u16(6) : 0)) & 0x44) !== 0);
18
+ };
19
+ const applies = (index: number, glyphs: readonly number[], at: number, depth: number): boolean => {
20
+ const lookup = lookupAt(index);
21
+ const skip = lookupSkip(lookup, lookup.u16(2), filter);
22
+ return !skip(glyphs[at]!) && subtablesOf(lookup, 9).some(([type, t]) => {
23
+ if ((depth === 0 && type === 2) || !changes(type, t, depth) || (type < 7 && zeroesMarks && filter.glyphClass(glyphs[at]!) === 3)) return false;
24
+ const covers = (offset: number, glyph: number): boolean => coverageIndex(t.part(t.u16(offset)), glyph) >= 0;
25
+ if (type !== 8 || t.u16(0) !== 3) return covers(type === 7 && t.u16(0) === 3 ? 6 : 2, glyphs[at]!);
26
+ const walk = (from: number, step: number, offset: number, count: number, seen: number[] = []): number => {
27
+ let i = from;
28
+ for (let k = 0; k < count; k++) {
29
+ do i += step;
30
+ while (i >= 0 && i < glyphs.length && skip(glyphs[i]!));
31
+ if (i < 0 || i >= glyphs.length || !covers(offset + k * 2, glyphs[i]!)) return -1;
32
+ seen.push(i);
33
+ }
34
+ return i;
35
+ };
36
+ const inputAt = 4 + t.u16(2) * 2;
37
+ const aheadAt = inputAt + 2 + t.u16(inputAt) * 2;
38
+ const positions = [at];
39
+ if (!covers(inputAt + 2, glyphs[at]!) || walk(at, -1, 4, t.u16(2)) < 0) return false;
40
+ const last = walk(at, 1, inputAt + 4, t.u16(inputAt) - 1, positions);
41
+ if (last < 0 || walk(last, 1, aheadAt + 2, t.u16(aheadAt)) < 0) return false;
42
+ return chainRecords(t).some((record) => record.sequenceIndex < positions.length && applies(record.lookupIndex, glyphs, positions[record.sequenceIndex]!, depth + 1));
43
+ });
44
+ };
45
+ return pairLookupIndices(gpos, script)
46
+ .filter((index) => subtablesOf(lookupAt(index), 9).some(([type, t]) => type !== 2 && changes(type, t, 0)))
47
+ .map((index) => (glyphs: readonly number[]) => glyphs.some((_, at) => applies(index, glyphs, at, 0)));
48
+ }
package/src/fonts/font.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { fnv1a32 } from "@mark1russell7/rigor-generators";
2
2
  import type { Reader } from "./binary.ts";
3
+ import { readContextKerning } from "./context.ts";
3
4
  import { readGposKerning, readKernTable, IGNORE_BASE, IGNORE_LIGATURES, IGNORE_MARKS, type PairLookup } from "./kerning.ts";
4
5
  import { readTables, type Decompress, type TableMap } from "./sfnt.ts";
5
6
  import { defaultFeatures, readGlyphFilter, readSubstitutions, type GlyphFilter, type SubstitutionLookup } from "./substitution.ts";
@@ -8,7 +9,7 @@ import { gvarAdvanceDeltas, readPointCounts, readTransformedPointCounts, type Gl
8
9
  import { instanceAdvances, normalize, readAxes, readVariationStore, type Axis, type Instance } from "./variations.ts";
9
10
  import { indicScripts, indicShaper } from "./indic.ts";
10
11
  import { joiningFeatures, joiningForms, joiningScripts, joiningStages } from "./joining.ts";
11
- import { hasMark, normalizeCodePoints } from "./normalize.ts";
12
+ import { hasDefaultIgnorable, hasMark, isHidden, normalizeCodePoints, zeroedMarks } from "./normalize.ts";
12
13
  import { canvasSegments, canvasWords } from "./words.ts";
13
14
 
14
15
  /** The options of `readFont`. */
@@ -57,6 +58,10 @@ export interface Font {
57
58
  /** The source of the advances of this instance. The default instance and a font that is not variable use `hmtx`. */
58
59
  readonly advanceSource: AdvanceSource;
59
60
  readonly numGlyphs: number;
61
+ /** This value tells if the font has a GPOS table. */
62
+ readonly hasPositioning?: boolean;
63
+ /** This value tells if GDEF has glyph classes. */
64
+ readonly hasGlyphClasses?: boolean;
60
65
  /** This function gives the glyph of a code point, or 0 when the font has no glyph for it. */
61
66
  glyph(codePoint: number): number;
62
67
  /** This function gives the advance of a glyph in font units, as the shaper uses it. A mark has the advance 0. */
@@ -65,6 +70,8 @@ export interface Font {
65
70
  glyphClass(glyph: number): number;
66
71
  /** This function gives the pair lookups of the kerning for an OpenType script tag, for example `latn`. */
67
72
  kerning(script: string): readonly PairLookup[];
73
+ /** This function gives a test for each lookup of `kern` and `dist` that the model does not apply. */
74
+ contextKerning?(script: string): readonly ((glyphs: readonly number[]) => boolean)[];
68
75
  /** This function gives the GSUB lookups of a list of feature tags for an OpenType script tag, in the order of the lookup list. */
69
76
  substitutions(script: string, features: readonly string[]): readonly SubstitutionLookup[];
70
77
  /** This function gives the same font at another instance. It uses the tables that are already read. */
@@ -160,12 +167,15 @@ function build(parsed: Parsed, requested: Instance, modes: Modes): Font {
160
167
  const kern = tables.get("kern");
161
168
  const gsub = tables.get("GSUB");
162
169
  const lookups = new Map<string, readonly PairLookup[]>();
170
+ const contexts = new Map<string, ReturnType<NonNullable<Font["contextKerning"]>>>();
163
171
  const substitutions = new Map<string, readonly SubstitutionLookup[]>();
164
172
  const hashed = [tables.get("cmap"), gdef, gpos, kern, tables.get("fvar"), tables.get("avar"), tables.get("HVAR"), gsub];
165
173
  return {
166
174
  epoch: `${header.revision.toString(16).padStart(8, "0")}-${widthHash(header.unitsPerEm, coordinates, advances, hashed)}${deltas === "exact" ? "-exact" : ""}${advanceSource === "gvar" && hvar !== undefined ? "-gvar" : ""}${metrics !== undefined ? "-metrics" : ""}`,
167
175
  unitsPerEm: header.unitsPerEm,
168
176
  numGlyphs: header.numGlyphs,
177
+ hasPositioning: gpos !== undefined,
178
+ hasGlyphClasses: gdef !== undefined && gdef.u16(4) !== 0,
169
179
  axes,
170
180
  instance,
171
181
  coordinates,
@@ -182,11 +192,17 @@ function build(parsed: Parsed, requested: Instance, modes: Modes): Font {
182
192
  }
183
193
  return found;
184
194
  },
195
+ contextKerning(script) {
196
+ if (!contexts.has(script)) contexts.set(script, gpos === undefined ? [] : readContextKerning(gpos, script, parsed.filter, !noMarkZero.includes(script)));
197
+ return contexts.get(script)!;
198
+ },
185
199
  substitutions(script, features) {
186
200
  const key = `${script} ${features.join(",")}`;
187
201
  let found = substitutions.get(key);
188
202
  if (found === undefined) {
189
- found = gsub === undefined ? [] : readSubstitutions(gsub, script, features, parsed.filter);
203
+ // The Indic shaper of HarfBuzz keeps the joiners visible, so only the other shapers skip them
204
+ const joiners = script === "deva" ? [] : [characters.get(0x200c) ?? 0, characters.get(0x200d) ?? 0].filter((glyph) => glyph !== 0);
205
+ found = gsub === undefined ? [] : readSubstitutions(gsub, script, features, { ...parsed.filter, joiners });
190
206
  substitutions.set(key, found);
191
207
  }
192
208
  return found;
@@ -312,10 +328,22 @@ export function shapingOf(font: Font, options: MeasureOptions): Shaping {
312
328
  return { script, features, shaper: options.joining !== false && joiningScripts.includes(script) ? "joining" : "plain", kerning };
313
329
  }
314
330
 
331
+ /** The bits of a mask: all the glyphs, a default ignorable, a mark with no advance. */
332
+ const GLOBAL_MASK = 0x80;
333
+ const IGNORABLE_MASK = 0x100;
334
+ const ZEROED_MASK = 0x200;
335
+
336
+ /** The scripts whose shaper in HarfBuzz has no fallback mark position. */
337
+ const noFallbackPosition: readonly string[] = ["thai", "lao ", "khmr", "mymr", "mym2", ...indicScripts];
338
+ /** The scripts whose shaper in HarfBuzz does not zero the marks. */
339
+ const noMarkZero: readonly string[] = ["hang", "khmr", ...indicScripts];
340
+
315
341
  /** The GSUB pass of one set of options: a function that gives the glyphs of one word, and the kerning lookups. */
316
342
  function shaperOf(font: Font, options: MeasureOptions): { substitute: (word: string) => number[]; kerning: readonly PairLookup[] } {
317
343
  const { script, features, shaper, kerning } = shapingOf(font, options);
318
344
  if (shaper === "indic") return { substitute: indicShaper(font, script, features), kerning };
345
+ const classes = font.hasGlyphClasses === false && !noMarkZero.includes(script);
346
+ const fallback = font.hasPositioning === false && !noFallbackPosition.includes(script);
319
347
  const joins = shaper === "joining";
320
348
  const lookups = joins ? [] : font.substitutions(script, features);
321
349
  const stages = joins ? joiningStages(features, features.includes("rclt") && font.substitutions(script, ["rclt"]).length > 0).map((stage) => ({ stage, lookups: font.substitutions(script, stage.features) })) : [];
@@ -329,16 +357,21 @@ function shaperOf(font: Font, options: MeasureOptions): { substitute: (word: str
329
357
  codePoints = normalizeCodePoints(codePoints, rules);
330
358
  wordGlyphs = codePoints.map((codePoint) => font.glyph(codePoint));
331
359
  }
332
- for (const lookup of lookups) lookup.apply(wordGlyphs);
333
- if (joins) {
334
- // Each glyph has the bit of its joining form, and the bit 7 for the features of all the glyphs
335
- const masks = joiningForms(codePoints).map((form) => 0x80 | (form === undefined ? 0 : 1 << joiningFeatures.indexOf(form)));
336
- for (const { stage, lookups: stageLookups } of stages) {
337
- const mask = stage.form === undefined ? 0x80 : 1 << joiningFeatures.indexOf(stage.form);
338
- for (const lookup of stageLookups) lookup.apply(wordGlyphs, masks, mask);
339
- }
360
+ const hides = hasDefaultIgnorable(word);
361
+ const zeroed = (classes || fallback) && hasMark(word) ? zeroedMarks(codePoints, classes, fallback) : [];
362
+ const forms = joins ? joiningForms(codePoints) : [];
363
+ const masks = joins || hides || zeroed.length > 0 ? codePoints.map((codePoint, i) => GLOBAL_MASK | (forms[i] === undefined ? 0 : 1 << joiningFeatures.indexOf(forms[i])) | (hides && isHidden(codePoint) ? IGNORABLE_MASK : 0) | (zeroed[i] === true ? ZEROED_MASK : 0)) : undefined;
364
+ const before = hides ? [...wordGlyphs] : [];
365
+ for (const lookup of lookups) lookup.apply(wordGlyphs, masks, GLOBAL_MASK);
366
+ for (const { stage, lookups: stageLookups } of stages) {
367
+ const mask = stage.form === undefined ? GLOBAL_MASK : 1 << joiningFeatures.indexOf(stage.form);
368
+ for (const lookup of stageLookups) lookup.apply(wordGlyphs, masks, mask);
340
369
  }
341
- return wordGlyphs;
370
+ // A new glyph has the mask of its source: a default ignorable with a new id is not hidden
371
+ return masks === undefined ? wordGlyphs : wordGlyphs.map((glyph, i) => {
372
+ const mask = masks[i] ?? 0;
373
+ return (mask & ZEROED_MASK) !== 0 || ((mask & IGNORABLE_MASK) !== 0 && before.includes(glyph)) ? ~glyph : glyph;
374
+ });
342
375
  };
343
376
  return { substitute, kerning };
344
377
  }
@@ -350,6 +383,12 @@ function shaperOf(font: Font, options: MeasureOptions): { substitute: (word: str
350
383
  * the joining forms of each word, in the stages of `joiningStages`. A script of `indicScripts` uses `indicShaper`.
351
384
  */
352
385
  export function glyphAdvances(font: Font, text: string, options: MeasureOptions = {}): { glyphs: number[]; advances: number[] } {
386
+ const { glyphs, advances } = shapedAdvances(font, text, options);
387
+ return { glyphs: glyphs.map((glyph) => (glyph < 0 ? ~glyph : glyph)), advances };
388
+ }
389
+
390
+ /** This function is `glyphAdvances`, with `~glyph` for a hidden glyph. It has no advance, and the kerning skips it. */
391
+ function shapedAdvances(font: Font, text: string, options: MeasureOptions): { glyphs: number[]; advances: number[] } {
353
392
  const { substitute, kerning } = shaperOf(font, options);
354
393
  const canvas = options.shaping === "canvas";
355
394
  const glyphs: number[] = [];
@@ -397,7 +436,7 @@ function kerningPosition(value: number, delta: number, scale: PositionScale): nu
397
436
  function kern(font: Font, lookups: readonly PairLookup[], glyphs: readonly number[], advances: number[], positions?: number[], scale?: PositionScale): void {
398
437
  for (const lookup of lookups) {
399
438
  const next = (from: number): number => {
400
- for (let j = from; j < glyphs.length; j++) if (!(lookup.skip?.(glyphs[j]!) ?? skips(lookup.flags, font.glyphClass(glyphs[j]!)))) return j;
439
+ for (let j = from; j < glyphs.length; j++) if (glyphs[j]! >= 0 && !(lookup.skip?.(glyphs[j]!) ?? skips(lookup.flags, font.glyphClass(glyphs[j]!)))) return j;
401
440
  return -1;
402
441
  };
403
442
  let i = next(0);
@@ -449,7 +488,7 @@ function float32Width(font: Font, text: string, size: number, options: MeasureOp
449
488
  */
450
489
  export function measureWidth(font: Font, text: string, size: number, options: MeasureOptions = {}): number {
451
490
  if (options.sum === "float32" && options.rounding !== "pixel") return float32Width(font, text, size, options);
452
- const { glyphs, advances } = glyphAdvances(font, text, options);
491
+ const { glyphs, advances } = shapedAdvances(font, text, options);
453
492
  if (options.rounding === "pixel") {
454
493
  const scale = size / font.unitsPerEm;
455
494
  let px = 0;
@@ -1,5 +1,6 @@
1
1
  export { readFont, measureWidth, glyphAdvances, shapingWords, type AdvanceSource, type Font, type ReadOptions, type MeasureOptions } from "./font.ts";
2
2
  export { widthBound, type WidthBound } from "./bound.ts";
3
+ export { shapingRisks, type ShapingRisk, type ShapingRiskCode } from "./risks.ts";
3
4
  export { canvasSegments, canvasWords, isCjkIdeographOrSymbol } from "./words.ts";
4
5
  export { bidiLevels, visualOrder } from "./bidi.ts";
5
6
  export { indicScripts, indicShaper, indicSyllables, type IndicSyllableType } from "./indic.ts";
@@ -6,6 +6,7 @@
6
6
  import type { Font } from "./font.ts";
7
7
  import { normalForms, normalizeCodePoints, type NormalForms } from "./normalize.ts";
8
8
  import { LIGATED, MULTIPLIED, SUBSTITUTED, type GlyphInfo } from "./substitution.ts";
9
+ import { isHidden } from "./normalize.ts";
9
10
 
10
11
  /** The OpenType script tags that use the Indic shaper in this model. */
11
12
  export const indicScripts: readonly string[] = ["deva"];
@@ -524,6 +525,6 @@ export function indicShaper(font: Font, script: string, features: readonly strin
524
525
  for (const { lookups, mask } of basic) for (const lookup of lookups) lookup.applyInfos(run.glyphs, run.infos, mask, true);
525
526
  for (const [start, end] of syllables(run.infos)) finalReordering(run, start, end);
526
527
  for (const { lookup, mask, perSyllable } of last) lookup.applyInfos(run.glyphs, run.infos, mask, perSyllable);
527
- return run.glyphs;
528
+ return run.glyphs.map((glyph, i) => ((run.infos[i]!.props & SUBSTITUTED) === 0 && isHidden(run.infos[i]!.codePoint) ? ~glyph : glyph));
528
529
  };
529
530
  }