@mark1russell7/typeset 0.1.3 → 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.
@@ -0,0 +1,48 @@
1
+ /** The risks of shaping: the text that the model cannot measure with trust. */
2
+ import { glyphAdvances, shapingOf, type Font, type MeasureOptions } from "./font.ts";
3
+ import { hasDefaultIgnorable, normalizeCodePoints } from "./normalize.ts";
4
+ import { canvasWords } from "./words.ts";
5
+
6
+ /** The kinds of risk. */
7
+ export type ShapingRiskCode = "missing-glyph" | "unshaped-script" | "emoji-zwj" | "variation-selector" | "keycap" | "flag" | "tag" | "positioning";
8
+
9
+ /** One part of a text that the model does not shape as HarfBuzz does, in UTF-16 units. */
10
+ export interface ShapingRisk {
11
+ readonly code: ShapingRiskCode;
12
+ readonly index: number;
13
+ readonly length: number;
14
+ }
15
+
16
+ const unshaped = /[\p{sc=Beng}\p{sc=Guru}\p{sc=Gujr}\p{sc=Orya}\p{sc=Taml}\p{sc=Telu}\p{sc=Knda}\p{sc=Mlym}\p{sc=Sinh}\p{sc=Khmr}\p{sc=Mymr}\p{sc=Tibt}\p{sc=Mong}\p{sc=Nkoo}\p{sc=Mand}]+/gu;
17
+ const pictograph = String.raw`\p{ExtPict}(?:\uFE0F|[\u{1F3FB}-\u{1F3FF}])?`;
18
+ // The longest forms come first
19
+ const sequences = new RegExp(String.raw`(\p{ExtPict}[\u{E0020}-\u{E007E}]+\u{E007F})|(${pictograph}(?:\u200D${pictograph})+)|([0-9#*]\uFE0F?\u20E3)|(\p{RI}\p{RI})|([\uFE00-\uFE0F\u{E0100}-\u{E01EF}])`, "gu");
20
+ const sequenceCodes: readonly ShapingRiskCode[] = ["tag", "emoji-zwj", "keycap", "flag", "variation-selector"];
21
+ const clusters = /\P{M}\p{M}*|\p{M}+/gu;
22
+ const control = /\p{Cc}/u;
23
+
24
+ /** This function gives the risks of a text in text order. An empty list is not a proof of a correct width. */
25
+ export function shapingRisks(font: Font, text: string, options: MeasureOptions = {}): ShapingRisk[] {
26
+ const risks: ShapingRisk[] = [];
27
+ const add = (code: ShapingRiskCode, index: number, { length }: string): number => risks.push({ code, index, length });
28
+ const absent = (codePoint: number): boolean => {
29
+ const character = String.fromCodePoint(codePoint);
30
+ return font.glyph(codePoint) === 0 && !control.test(character) && !hasDefaultIgnorable(character);
31
+ };
32
+ const hasGlyph = (codePoint: number): boolean => font.glyph(codePoint) !== 0;
33
+ for (const { 0: cluster, index } of text.matchAll(clusters)) {
34
+ if (normalizeCodePoints(Array.from(cluster, (character) => character.codePointAt(0)!), { hasGlyph, shortCircuit: true }).some(absent)) add("missing-glyph", index, cluster);
35
+ }
36
+ for (const { 0: part, index } of text.matchAll(unshaped)) add("unshaped-script", index, part);
37
+ for (const match of text.matchAll(sequences)) add(sequenceCodes[match.slice(1).findIndex(Boolean)]!, match.index, match[0]);
38
+ const tests = options.kerning === false ? [] : font.contextKerning?.(shapingOf(font, options).script) ?? [];
39
+ if (tests.length > 0) {
40
+ let index = 0;
41
+ for (const word of options.shaping === "canvas" ? canvasWords(text) : [text]) {
42
+ const { glyphs } = glyphAdvances(font, word, options);
43
+ if (tests.some((test) => test(glyphs))) add("positioning", index, word);
44
+ index += word.length;
45
+ }
46
+ }
47
+ return risks.sort((a, b) => a.index - b.index);
48
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Reader } from "./binary.ts";
2
- import { IGNORE_BASE, IGNORE_LIGATURES, IGNORE_MARKS, scriptTags } from "./kerning.ts";
2
+ import { languageSystem, lookupSkip, subtablesOf } from "./kerning.ts";
3
3
  import { classOf, coverageGlyphs, coverageIndex } from "./tables.ts";
4
4
 
5
5
  /**
@@ -8,8 +8,6 @@ import { classOf, coverageGlyphs, coverageIndex } from "./tables.ts";
8
8
  */
9
9
  export const defaultFeatures: readonly string[] = ["ccmp", "locl", "rlig", "liga", "clig", "calt", "rclt"];
10
10
 
11
- /** The lookup flag that selects a mark filtering set of GDEF. */
12
- const USE_MARK_FILTERING_SET = 0x10;
13
11
  /** The largest depth of nested lookups, as in HarfBuzz. */
14
12
  const MAX_NESTING = 64;
15
13
 
@@ -21,6 +19,8 @@ export interface GlyphFilter {
21
19
  markAttachClass(glyph: number): number;
22
20
  /** This function tells if a glyph is in the mark filtering set `set`. */
23
21
  inMarkSet(set: number, glyph: number): boolean;
22
+ /** The glyphs of the joiners that the backtrack and the lookahead of a context rule skip. */
23
+ readonly joiners?: readonly number[];
24
24
  }
25
25
 
26
26
  /** This function reads the glyph classes, the mark attachment classes and the mark filtering sets of GDEF. */
@@ -142,14 +142,14 @@ function ruleTables(t: Reader, at: number): Reader[] {
142
142
  }
143
143
 
144
144
  /** This function gives the records of each rule of a context subtable (lookup type 5). */
145
- function contextRecords(t: Reader): SequenceRecord[] {
145
+ export function contextRecords(t: Reader): SequenceRecord[] {
146
146
  const format = t.u16(0);
147
147
  if (format === 3) return records(t, 6 + t.u16(2) * 2, t.u16(4));
148
148
  return ruleTables(t, format === 2 ? 6 : 4).flatMap((rule) => records(rule, 4 + (rule.u16(0) - 1) * 2, rule.u16(2)));
149
149
  }
150
150
 
151
151
  /** This function gives the records of each rule of a chained context subtable (lookup type 6). */
152
- function chainRecords(t: Reader): SequenceRecord[] {
152
+ export function chainRecords(t: Reader): SequenceRecord[] {
153
153
  const format = t.u16(0);
154
154
  if (format === 3) {
155
155
  const inputAt = 4 + t.u16(2) * 2;
@@ -210,30 +210,11 @@ class Gsub {
210
210
  let found = this.cache.get(index);
211
211
  if (found === undefined) {
212
212
  const table = this.lookups.part(this.lookups.u16(2 + index * 2));
213
- const type = table.u16(0);
214
213
  const flags = table.u16(2);
215
- const count = table.u16(4);
216
- const markSet = (flags & USE_MARK_FILTERING_SET) !== 0 ? table.u16(6 + count * 2) : -1;
217
- const subtables: Reader[] = [];
218
- let subtype = type;
219
- for (let s = 0; s < count; s++) {
220
- const subtable = table.part(table.u16(6 + s * 2));
221
- if (type === 7) {
222
- subtype = subtable.u16(2);
223
- subtables.push(subtable.part(subtable.u32(4)));
224
- } else subtables.push(subtable);
225
- }
226
- const { glyphClass, markAttachClass, inMarkSet } = this.filter;
227
- const skip = (glyph: number): boolean => {
228
- const kind = glyphClass(glyph);
229
- if ((flags & IGNORE_BASE) !== 0 && kind === 1) return true;
230
- if ((flags & IGNORE_LIGATURES) !== 0 && kind === 2) return true;
231
- if (kind !== 3) return false;
232
- if ((flags & IGNORE_MARKS) !== 0) return true;
233
- if (markSet >= 0) return !inMarkSet(markSet, glyph);
234
- const attach = flags >> 8;
235
- return attach !== 0 && markAttachClass(glyph) !== attach;
236
- };
214
+ const parts = subtablesOf(table, 7);
215
+ const subtables = parts.map((part) => part[1]);
216
+ const subtype = parts.at(-1)?.[0] ?? table.u16(0);
217
+ const skip = lookupSkip(table, flags, this.filter);
237
218
  found = { type: subtype, flags, subtables, skip };
238
219
  this.cache.set(index, found);
239
220
  }
@@ -349,8 +330,9 @@ class Gsub {
349
330
  return -1;
350
331
  }
351
332
 
352
- private previousOf(lookup: Lookup, glyphs: readonly number[], from: number): number {
353
- for (let j = from; j >= 0; j--) if (!lookup.skip(glyphs[j]!)) return j;
333
+ /** This function finds the next glyph of a backtrack or a lookahead. As in HarfBuzz, a joiner does not stop the context. */
334
+ private contextOf(lookup: Lookup, glyphs: readonly number[], from: number, step: 1 | -1): number {
335
+ for (let j = from; j >= 0 && j < glyphs.length; j += step) if (!lookup.skip(glyphs[j]!) && !this.filter.joiners?.includes(glyphs[j]!)) return j;
354
336
  return -1;
355
337
  }
356
338
 
@@ -372,7 +354,7 @@ class Gsub {
372
354
  private matchBacktrack(lookup: Lookup, glyphs: readonly number[], i: number, count: number, test: (k: number, glyph: number) => boolean): boolean {
373
355
  let at = i;
374
356
  for (let k = 0; k < count; k++) {
375
- at = this.previousOf(lookup, glyphs, at - 1);
357
+ at = this.contextOf(lookup, glyphs, at - 1, -1);
376
358
  if (at < 0 || !this.admits(at, i, false) || !test(k, glyphs[at]!)) return false;
377
359
  }
378
360
  return true;
@@ -381,7 +363,7 @@ class Gsub {
381
363
  private matchLookahead(lookup: Lookup, glyphs: readonly number[], first: number, last: number, count: number, test: (k: number, glyph: number) => boolean): boolean {
382
364
  let at = last;
383
365
  for (let k = 0; k < count; k++) {
384
- at = this.nextOf(lookup, glyphs, at + 1);
366
+ at = this.contextOf(lookup, glyphs, at + 1, 1);
385
367
  if (at < 0 || !this.admits(at, first, false) || !test(k, glyphs[at]!)) return false;
386
368
  }
387
369
  return true;
@@ -634,19 +616,8 @@ class Gsub {
634
616
  * HarfBuzz applies them. The lookups include the lookups of the necessary feature of the language system.
635
617
  */
636
618
  export function readSubstitutions(gsub: Reader, script: string, features: readonly string[], filter: GlyphFilter): SubstitutionLookup[] {
637
- const scripts = gsub.part(gsub.u16(4));
638
619
  const featureList = gsub.part(gsub.u16(6));
639
- const scriptCount = scripts.u16(0);
640
- let langSys: Reader | undefined;
641
- for (const wanted of scriptTags(script)) {
642
- for (let i = 0; i < scriptCount && langSys === undefined; i++) {
643
- if (scripts.tag(2 + i * 6) !== wanted) continue;
644
- const table = scripts.part(scripts.u16(2 + i * 6 + 4));
645
- const fallback = table.u16(0);
646
- if (fallback !== 0) langSys = table.part(fallback);
647
- }
648
- if (langSys !== undefined) break;
649
- }
620
+ const langSys = languageSystem(gsub, script);
650
621
  if (langSys === undefined || features.length === 0) return [];
651
622
  const wanted = new Set(features);
652
623
  const indices = new Map<number, string[]>();
@@ -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";
package/src/fonts.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  */
5
5
  export { measureWidth, readFont, type Font, type MeasureOptions, type ReadOptions } from "./fonts/font.ts";
6
6
  export { widthBound, type WidthBound } from "./fonts/bound.ts";
7
+ export { shapingRisks, type ShapingRisk, type ShapingRiskCode } from "./fonts/risks.ts";
7
8
  export { engines, isEngineName, type EngineName, type EngineRules } from "./fonts/engines.ts";
8
9
  export type { Decompress } from "./fonts/sfnt.ts";
9
10
  export type { Axis, Instance } from "./fonts/variations.ts";
@@ -6,7 +6,12 @@
6
6
  */
7
7
  import { engines, isEngineName, type EngineName, type EngineRules } from "../fonts/engines.ts";
8
8
  import { measureWidth, readFont, type Font } from "../fonts/font.ts";
9
+ import { shapingRisks } from "../fonts/risks.ts";
9
10
  import type { Decompress } from "../fonts/sfnt.ts";
11
+ import { canvasWords } from "../fonts/words.ts";
12
+
13
+ /** This function gives the width of a text in a CSS font, as `AdvanceFn` of layout-contract does. */
14
+ export type AdvanceFn = (text: string, font: string) => number;
10
15
 
11
16
  /** One font file of the host, with the family, the weight and the style that CSS matches. */
12
17
  export interface FontFace {
@@ -36,6 +41,8 @@ export interface FontAdvanceOptions {
36
41
  * with `measureText`. Use `dom` for the widths of a text in a page.
37
42
  */
38
43
  readonly shaping?: "dom" | "canvas";
44
+ /** The shaper of the host. Under the shaping `canvas`, it measures each word that `shapingRisks` flags. The shaping `dom` does not use it. */
45
+ readonly fallback?: AdvanceFn;
39
46
  }
40
47
 
41
48
  /** The parts of a CSS font shorthand that change a width. */
@@ -150,6 +157,27 @@ const scriptPatterns: readonly (readonly [RegExp, string])[] = [
150
157
 
151
158
  const neutral = /[\p{sc=Common}\p{sc=Inherited}\p{sc=Unknown}]/u;
152
159
 
160
+ /** This function divides a text into parts of one script. A neutral character stays with the part before it. */
161
+ export function scriptRuns(text: string): string[] {
162
+ if (/^[\0-\x7f]*$/.test(text)) return [text];
163
+ const runs: string[] = [];
164
+ let run = "";
165
+ let current: string | undefined;
166
+ for (const character of text) {
167
+ if (!neutral.test(character)) {
168
+ const tag = scriptTag(character).replace(/kana|bopo/, "hani");
169
+ if (current !== undefined && tag !== current) {
170
+ runs.push(run);
171
+ run = "";
172
+ }
173
+ current = tag;
174
+ }
175
+ run += character;
176
+ }
177
+ runs.push(run);
178
+ return runs;
179
+ }
180
+
153
181
  /**
154
182
  * This function gives the OpenType script tag of a text, as HarfBuzz guesses it. The tag is the script of the first
155
183
  * character that is not of the scripts Common, Inherited or Unknown. A text of only those characters, for example emoji, gets `DFLT`.
@@ -210,6 +238,7 @@ export function fontAdvance(options: FontAdvanceOptions): (text: string, font: s
210
238
  if (typeof engine === "string" && !isEngineName(engine)) throw new RangeError(`the engine "${engine}" is not a row of engines`);
211
239
  const rules: EngineRules = typeof engine === "string" ? engines[engine] : engine;
212
240
  const shaping = options.shaping ?? "canvas";
241
+ const fallback = shaping === "canvas" ? options.fallback : undefined;
213
242
  const faces = options.faces;
214
243
  const loaded = new Map<number, Loaded>();
215
244
  const specs = new Map<string, FontSpec>();
@@ -283,7 +312,19 @@ export function fontAdvance(options: FontAdvanceOptions): (text: string, font: s
283
312
 
284
313
  return (text: string, font: string): number => {
285
314
  const { spec, fonts } = fontsOf(font);
286
- const measure = (run: string, face: Font): number => measureWidth(face, run, spec.size, { script: scriptTag(run), shaping, rounding: rules.rounding, sum: rules.sum });
315
+ const sum = (parts: readonly string[], width: (part: string) => number): number => parts.reduce((total, part) => total + width(part), 0);
316
+ const measure = (run: string, face: Font): number => {
317
+ const runs = scriptRuns(run);
318
+ const tagged = (part: string): number => measureWidth(face, part, spec.size, { script: scriptTag(part), shaping, rounding: rules.rounding, sum: rules.sum });
319
+ const risky = (part: string): boolean => fallback !== undefined && shapingRisks(face, part, { script: scriptTag(part), shaping }).length > 0;
320
+ if (runs.length === 1 && !risky(run)) return tagged(run);
321
+ if (shaping !== "canvas") return sum(runs, tagged);
322
+ // The width of a word comes from the word alone. This keeps the separator law of the rope
323
+ return sum(canvasWords(run), (word) => {
324
+ const parts = scriptRuns(word);
325
+ return parts.some(risky) ? fallback!(word, font) : sum(parts, tagged);
326
+ });
327
+ };
287
328
  if (fonts.length === 1) return measure(text, fonts[0]!);
288
329
  let width = 0;
289
330
  let run = "";
package/src/measurer.ts CHANGED
@@ -2,4 +2,4 @@
2
2
  * The subpath `./measurer`: the advance function of a layout engine, from the font model of typeset. The measurer of
3
3
  * `@mark1russell7/layout-contract/text` takes it as its `AdvanceFn`.
4
4
  */
5
- export { fontAdvance, parseFont, scriptTag, type FontAdvanceOptions, type FontFace, type FontSpec } from "./measurer/advance.ts";
5
+ export { fontAdvance, parseFont, scriptTag, type AdvanceFn, type FontAdvanceOptions, type FontFace, type FontSpec } from "./measurer/advance.ts";