@mark1russell7/typeset 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime.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";
2
+ import { c as joiningStages, i as shapingOf, l as indicFeatures, n as measureWidth, p as normalForms, r as readFont, u as indicForms } from "./font.js";
3
3
  import { n as isEngineName, r as shapingRisks, t as engines } from "./engines.js";
4
4
  // src/fonts/bound.ts
5
5
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"measurer.d.ts","names":[],"sources":["../../src/measurer/advance.ts","../../src/measurer.ts"],"mappings":";;;KAaY,aAAa,cAAc;;UAGtB;;WAEN;;WAEA,MAAM;;;;;WAKN;;WAEA;;WAEA,aAAa;;;UAIP;;WAEN,gBAAgB;;WAEhB,SAAS,aAAa;;;;;WAKtB;;WAEA,WAAW;;;UAIL;WACN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;iBAuBK,UAAU,eAAe;;;;;iBAsGzB,UAAU;;;;;;;;iBAmDV,YAAY,SAAS,sBAAsB,cAAc"}
1
+ {"version":3,"file":"measurer.d.ts","names":[],"sources":["../../src/measurer/advance.ts","../../src/measurer.ts"],"mappings":";;;KAaY,aAAa,cAAc;;UAGtB;;WAEN;;WAEA,MAAM;;;;;WAKN;;WAEA;;WAEA,aAAa;;;UAIP;;WAEN,gBAAgB;;WAEhB,SAAS,aAAa;;;;;WAKtB;;WAEA,WAAW;;;UAIL;WACN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;iBAuBK,UAAU,eAAe;;;;;iBAwGzB,UAAU;;;;;;;;iBAmDV,YAAY,SAAS,sBAAsB,cAAc"}
@@ -55,6 +55,7 @@ function parseFont(font) {
55
55
  if (size === null) throw new RangeError(`the font "${font}" has no size in px or pt`);
56
56
  let rest = tokens.slice(index + 1).join(" ");
57
57
  if (size[3] === void 0 && rest.startsWith("/")) rest = rest.slice(1).trim().replace(/^\S+\s*/, "");
58
+ else if (size[3] === "/") rest = rest.replace(/^\S+\s*/, "");
58
59
  const families = rest.split(",").map((family) => family.trim().replace(/^(["'])(.*)\1$/, "$2").trim()).filter((family) => family.length > 0);
59
60
  if (families.length === 0) throw new RangeError(`the font "${font}" has no family`);
60
61
  const value = Number(size[1]);
@@ -236,6 +237,7 @@ function fontAdvance(options) {
236
237
  let font = instances.get(key);
237
238
  if (font === void 0) {
238
239
  font = Object.keys(instance).length === 0 ? chosen.font : chosen.font.at(instance);
240
+ if (instances.size >= 256) instances.clear();
239
241
  instances.set(key, font);
240
242
  }
241
243
  return font;
@@ -1 +1 @@
1
- {"version":3,"file":"measurer.js","names":[],"sources":["../../src/measurer/advance.ts","../../src/measurer.ts"],"sourcesContent":["/**\n * The advance function of the font model: the width of a text in a CSS font, as the measurer of\n * `@mark1russell7/layout-contract/text` asks for it. The host gives the font files as faces. The function finds the face\n * of each run of the text with the matching rules of CSS. It finds the script of the run, and measures the run with the\n * rules of one text engine.\n */\nimport { engines, isEngineName, type EngineName, type EngineRules } from \"../fonts/engines.ts\";\nimport { measureWidth, readFont, type Font } from \"../fonts/font.ts\";\nimport { shapingRisks } from \"../fonts/risks.ts\";\nimport type { Decompress } from \"../fonts/sfnt.ts\";\nimport { canvasWords } from \"../fonts/words.ts\";\n\n/** This function gives the width of a text in a CSS font, as `AdvanceFn` of layout-contract does. */\nexport type AdvanceFn = (text: string, font: string) => number;\n\n/** One font file of the host, with the family, the weight and the style that CSS matches. */\nexport interface FontFace {\n /** The family name, as the CSS font names it. The match ignores the case. */\n readonly family: string;\n /** The bytes of a TrueType, OpenType or WOFF2 file. */\n readonly data: Uint8Array;\n /**\n * The weight of the face: one value, or the range of a variable font. The default is the range of the `wght` axis of the\n * font, or 400 for a font with no `wght` axis.\n */\n readonly weight?: number | readonly [number, number];\n /** The style of the face. The default is `normal`. */\n readonly style?: \"normal\" | \"italic\" | \"oblique\";\n /** The Brotli decompressor of a WOFF2 file. */\n readonly decompress?: Decompress;\n}\n\n/** The options of `fontAdvance`. */\nexport interface FontAdvanceOptions {\n /** The font files of the host. The order sets the choice between two faces with the same match. */\n readonly faces: readonly FontFace[];\n /** The text engine: a row name of `engines`, or the rules of a row. The default is `freetype`, as Chromium on Linux. */\n readonly engine?: EngineName | EngineRules;\n /**\n * The shaping of `measureWidth`. The default is `canvas`, as `canvasAdvance` of layout-contract measures each segment\n * with `measureText`. Use `dom` for the widths of a text in a page.\n */\n readonly shaping?: \"dom\" | \"canvas\";\n /** The shaper of the host. Under the shaping `canvas`, it measures each word that `shapingRisks` flags. The shaping `dom` does not use it. */\n readonly fallback?: AdvanceFn;\n}\n\n/** The parts of a CSS font shorthand that change a width. */\nexport interface FontSpec {\n readonly style: \"normal\" | \"italic\" | \"oblique\";\n /** The angle of an oblique style in degrees. CSS gives 14 when the font names no angle. */\n readonly angle: number;\n /** The weight from 1 to 1000. */\n readonly weight: number;\n /** The width of the font as a percent of the normal width, from the keyword of `font-stretch`. */\n readonly stretch: number;\n /** The size in px. */\n readonly size: number;\n /** The family names in the order of the font, with no quotes. */\n readonly families: readonly string[];\n}\n\nconst stretches: Readonly<Record<string, number>> = {\n \"ultra-condensed\": 50,\n \"extra-condensed\": 62.5,\n condensed: 75,\n \"semi-condensed\": 87.5,\n \"semi-expanded\": 112.5,\n expanded: 125,\n \"extra-expanded\": 150,\n \"ultra-expanded\": 200,\n};\n\n// Each number pattern matches a text in one way only. Thus a long run of digits does not make the match slow.\nconst sizePattern = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:e[+-]?\\d+)?)(px|pt)(\\/.*)?$/i;\nconst anglePattern = /^(-?(?:\\d+(?:\\.\\d+)?|\\.\\d+))deg$/i;\nconst weightPattern = /^(?:\\d+(?:\\.\\d+)?|\\.\\d+)$/;\n\n/**\n * This function reads a CSS font shorthand, for example `italic 700 16px/1.2 \"Noto Sans\", sans-serif`. The size must be in\n * `px` or `pt`. The function refuses `small-caps`, the system font keywords and the relative sizes with a `RangeError`.\n */\nexport function parseFont(font: string): FontSpec {\n const tokens = font.trim().split(/\\s+/);\n let style: FontSpec[\"style\"] = \"normal\";\n let angle = 14;\n let weight = 400;\n let stretch = 100;\n let index = 0;\n for (; index < tokens.length; index++) {\n const token = tokens[index]!;\n const lower = token.toLowerCase();\n const size = sizePattern.exec(token);\n if (size !== null) break;\n if (lower === \"normal\") continue;\n if (lower === \"italic\") style = \"italic\";\n else if (lower === \"oblique\") {\n style = \"oblique\";\n const next = anglePattern.exec(tokens[index + 1] ?? \"\");\n if (next !== null) {\n angle = Number(next[1]);\n index++;\n }\n } else if (lower === \"bold\" || lower === \"bolder\") weight = 700;\n else if (lower === \"lighter\") weight = 100;\n else if (weightPattern.test(token) && Number(token) >= 1 && Number(token) <= 1000) weight = Number(token);\n else if (Object.hasOwn(stretches, lower)) stretch = stretches[lower]!;\n else throw new RangeError(`the font \"${font}\" has the part \"${token}\", which the measurer does not know`);\n }\n const size = sizePattern.exec(tokens[index] ?? \"\");\n if (size === null) throw new RangeError(`the font \"${font}\" has no size in px or pt`);\n let rest = tokens.slice(index + 1).join(\" \");\n // A line height after a space: \"16px / 1.2\" or \"16px /1.2\"\n if (size[3] === undefined && rest.startsWith(\"/\")) rest = rest.slice(1).trim().replace(/^\\S+\\s*/, \"\");\n 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,QAAQ;OAC3B,IAAI,UAAU,WAAW;GAC5B,QAAQ;GACR,MAAM,OAAO,aAAa,KAAK,OAAO,QAAQ,MAAM,EAAE;GACtD,IAAI,SAAS,MAAM;IACjB,QAAQ,OAAO,KAAK,EA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src/measurer/advance.ts","../../src/measurer.ts"],"sourcesContent":["/**\n * The advance function of the font model: the width of a text in a CSS font, as the measurer of\n * `@mark1russell7/layout-contract/text` asks for it. The host gives the font files as faces. The function finds the face\n * of each run of the text with the matching rules of CSS. It finds the script of the run, and measures the run with the\n * rules of one text engine.\n */\nimport { engines, isEngineName, type EngineName, type EngineRules } from \"../fonts/engines.ts\";\nimport { measureWidth, readFont, type Font } from \"../fonts/font.ts\";\nimport { shapingRisks } from \"../fonts/risks.ts\";\nimport type { Decompress } from \"../fonts/sfnt.ts\";\nimport { canvasWords } from \"../fonts/words.ts\";\n\n/** This function gives the width of a text in a CSS font, as `AdvanceFn` of layout-contract does. */\nexport type AdvanceFn = (text: string, font: string) => number;\n\n/** One font file of the host, with the family, the weight and the style that CSS matches. */\nexport interface FontFace {\n /** The family name, as the CSS font names it. The match ignores the case. */\n readonly family: string;\n /** The bytes of a TrueType, OpenType or WOFF2 file. */\n readonly data: Uint8Array;\n /**\n * The weight of the face: one value, or the range of a variable font. The default is the range of the `wght` axis of the\n * font, or 400 for a font with no `wght` axis.\n */\n readonly weight?: number | readonly [number, number];\n /** The style of the face. The default is `normal`. */\n readonly style?: \"normal\" | \"italic\" | \"oblique\";\n /** The Brotli decompressor of a WOFF2 file. */\n readonly decompress?: Decompress;\n}\n\n/** The options of `fontAdvance`. */\nexport interface FontAdvanceOptions {\n /** The font files of the host. The order sets the choice between two faces with the same match. */\n readonly faces: readonly FontFace[];\n /** The text engine: a row name of `engines`, or the rules of a row. The default is `freetype`, as Chromium on Linux. */\n readonly engine?: EngineName | EngineRules;\n /**\n * The shaping of `measureWidth`. The default is `canvas`, as `canvasAdvance` of layout-contract measures each segment\n * with `measureText`. Use `dom` for the widths of a text in a page.\n */\n readonly shaping?: \"dom\" | \"canvas\";\n /** The shaper of the host. Under the shaping `canvas`, it measures each word that `shapingRisks` flags. The shaping `dom` does not use it. */\n readonly fallback?: AdvanceFn;\n}\n\n/** The parts of a CSS font shorthand that change a width. */\nexport interface FontSpec {\n readonly style: \"normal\" | \"italic\" | \"oblique\";\n /** The angle of an oblique style in degrees. CSS gives 14 when the font names no angle. */\n readonly angle: number;\n /** The weight from 1 to 1000. */\n readonly weight: number;\n /** The width of the font as a percent of the normal width, from the keyword of `font-stretch`. */\n readonly stretch: number;\n /** The size in px. */\n readonly size: number;\n /** The family names in the order of the font, with no quotes. */\n readonly families: readonly string[];\n}\n\nconst stretches: Readonly<Record<string, number>> = {\n \"ultra-condensed\": 50,\n \"extra-condensed\": 62.5,\n condensed: 75,\n \"semi-condensed\": 87.5,\n \"semi-expanded\": 112.5,\n expanded: 125,\n \"extra-expanded\": 150,\n \"ultra-expanded\": 200,\n};\n\n// Each number pattern matches a text in one way only. Thus a long run of digits does not make the match slow.\nconst sizePattern = /^((?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:e[+-]?\\d+)?)(px|pt)(\\/.*)?$/i;\nconst anglePattern = /^(-?(?:\\d+(?:\\.\\d+)?|\\.\\d+))deg$/i;\nconst weightPattern = /^(?:\\d+(?:\\.\\d+)?|\\.\\d+)$/;\n\n/**\n * This function reads a CSS font shorthand, for example `italic 700 16px/1.2 \"Noto Sans\", sans-serif`. The size must be in\n * `px` or `pt`. The function refuses `small-caps`, the system font keywords and the relative sizes with a `RangeError`.\n */\nexport function parseFont(font: string): FontSpec {\n const tokens = font.trim().split(/\\s+/);\n let style: FontSpec[\"style\"] = \"normal\";\n let angle = 14;\n let weight = 400;\n let stretch = 100;\n let index = 0;\n for (; index < tokens.length; index++) {\n const token = tokens[index]!;\n const lower = token.toLowerCase();\n const size = sizePattern.exec(token);\n if (size !== null) break;\n if (lower === \"normal\") continue;\n if (lower === \"italic\") style = \"italic\";\n else if (lower === \"oblique\") {\n style = \"oblique\";\n const next = anglePattern.exec(tokens[index + 1] ?? \"\");\n if (next !== null) {\n angle = Number(next[1]);\n index++;\n }\n } else if (lower === \"bold\" || lower === \"bolder\") weight = 700;\n else if (lower === \"lighter\") weight = 100;\n else if (weightPattern.test(token) && Number(token) >= 1 && Number(token) <= 1000) weight = Number(token);\n else if (Object.hasOwn(stretches, lower)) stretch = stretches[lower]!;\n else throw new RangeError(`the font \"${font}\" has the part \"${token}\", which the measurer does not know`);\n }\n const size = sizePattern.exec(tokens[index] ?? \"\");\n if (size === null) throw new RangeError(`the font \"${font}\" has no size in px or pt`);\n let rest = tokens.slice(index + 1).join(\" \");\n // A line height after a space: \"16px / 1.2\" or \"16px /1.2\"\n if (size[3] === undefined && rest.startsWith(\"/\")) rest = rest.slice(1).trim().replace(/^\\S+\\s*/, \"\");\n // A line height after a slash and a space: \"16px/ 1.2\"\n else if (size[3] === \"/\") rest = rest.replace(/^\\S+\\s*/, \"\");\n const families = rest\n .split(\",\")\n .map((family) => family.trim().replace(/^([\"'])(.*)\\1$/, \"$2\").trim())\n .filter((family) => family.length > 0);\n if (families.length === 0) throw new RangeError(`the font \"${font}\" has no family`);\n const value = Number(size[1]);\n return { style, angle, weight, stretch, size: size[2]!.toLowerCase() === \"pt\" ? (value * 4) / 3 : value, families };\n}\n\n/** The Unicode scripts and their OpenType tags. A script that is not in the list gets `DFLT`. */\nconst scriptPatterns: readonly (readonly [RegExp, string])[] = [\n [/\\p{sc=Latin}/u, \"latn\"],\n [/\\p{sc=Greek}/u, \"grek\"],\n [/\\p{sc=Cyrillic}/u, \"cyrl\"],\n [/\\p{sc=Armenian}/u, \"armn\"],\n [/\\p{sc=Hebrew}/u, \"hebr\"],\n [/\\p{sc=Arabic}/u, \"arab\"],\n [/\\p{sc=Syriac}/u, \"syrc\"],\n [/\\p{sc=Thaana}/u, \"thaa\"],\n [/\\p{sc=Devanagari}/u, \"deva\"],\n [/\\p{sc=Bengali}/u, \"beng\"],\n [/\\p{sc=Gurmukhi}/u, \"guru\"],\n [/\\p{sc=Gujarati}/u, \"gujr\"],\n [/\\p{sc=Oriya}/u, \"orya\"],\n [/\\p{sc=Tamil}/u, \"taml\"],\n [/\\p{sc=Telugu}/u, \"telu\"],\n [/\\p{sc=Kannada}/u, \"knda\"],\n [/\\p{sc=Malayalam}/u, \"mlym\"],\n [/\\p{sc=Sinhala}/u, \"sinh\"],\n [/\\p{sc=Thai}/u, \"thai\"],\n [/\\p{sc=Lao}/u, \"lao \"],\n [/\\p{sc=Tibetan}/u, \"tibt\"],\n [/\\p{sc=Myanmar}/u, \"mymr\"],\n [/\\p{sc=Georgian}/u, \"geor\"],\n [/\\p{sc=Hangul}/u, \"hang\"],\n [/\\p{sc=Ethiopic}/u, \"ethi\"],\n [/\\p{sc=Khmer}/u, \"khmr\"],\n [/\\p{sc=Mongolian}/u, \"mong\"],\n [/[\\p{sc=Hiragana}\\p{sc=Katakana}]/u, \"kana\"],\n [/\\p{sc=Bopomofo}/u, \"bopo\"],\n [/\\p{sc=Han}/u, \"hani\"],\n];\n\nconst neutral = /[\\p{sc=Common}\\p{sc=Inherited}\\p{sc=Unknown}]/u;\n\n/** This function divides a text into parts of one script. A neutral character stays with the part before it. */\nexport function scriptRuns(text: string): string[] {\n if (/^[\\0-\\x7f]*$/.test(text)) return [text];\n const runs: string[] = [];\n let run = \"\";\n let current: string | undefined;\n for (const character of text) {\n if (!neutral.test(character)) {\n const tag = scriptTag(character).replace(/kana|bopo/, \"hani\");\n if (current !== undefined && tag !== current) {\n runs.push(run);\n run = \"\";\n }\n current = tag;\n }\n run += character;\n }\n runs.push(run);\n return runs;\n}\n\n/**\n * This function gives the OpenType script tag of a text, as HarfBuzz guesses it. The tag is the script of the first\n * character that is not of the scripts Common, Inherited or Unknown. A text of only those characters, for example emoji, gets `DFLT`.\n */\nexport function scriptTag(text: string): string {\n for (const character of text) {\n if (neutral.test(character)) continue;\n for (const [pattern, tag] of scriptPatterns) if (pattern.test(character)) return tag;\n return \"DFLT\";\n }\n return \"DFLT\";\n}\n\n/** A character that stays in the run of the character before it: a mark, a joiner, a variation selector, a tag or a skin tone. */\nconst attached = /^[\\p{M}‌‍︀-️\\u{e0020}-\\u{e007f}\\u{e0100}-\\u{e01ef}\\u{1f3fb}-\\u{1f3ff}]$/u;\n\nconst styleOrder: Readonly<Record<FontSpec[\"style\"], readonly FontSpec[\"style\"][]>> = {\n normal: [\"normal\", \"oblique\", \"italic\"],\n italic: [\"italic\", \"oblique\", \"normal\"],\n oblique: [\"oblique\", \"italic\", \"normal\"],\n};\n\n/** A face with its font, read at the first use. */\ninterface Loaded {\n readonly face: FontFace;\n readonly index: number;\n readonly font: Font;\n readonly range: readonly [number, number];\n}\n\n/**\n * This function gives the rank of a face for the weight `weight`, with the rules of CSS Fonts 4. A lower rank is a\n * better match. A face whose range holds the weight has the rank 0.\n */\nfunction weightRank(range: readonly [number, number], weight: number): number {\n const [min, max] = range;\n if (min <= weight && weight <= max) return 0;\n const above = min > weight;\n // The groups of CSS: 1 is the first choice after an exact match, 3 is the last\n if (weight >= 400 && weight <= 500) {\n if (above && min <= 500) return 1000 + min;\n if (!above) return 3000 - max;\n return 5000 + min;\n }\n if (weight < 400) return above ? 3000 + min : 1000 - max;\n return above ? 1000 + min : 3000 - max;\n}\n\n/**\n * This function gives the advance function of the faces of the host: the width in px of a text in a CSS font. Each run\n * of the text gets the first family of the font with a glyph for its first character. When no family has a glyph, the\n * run gets the first family that has a face. The width of a run is `measureWidth` with the size of the font, the script\n * of `scriptTag` and the rules of the engine. The instance of a variable face takes the weight and the stretch as `wdth`.\n * It takes the style as `ital` or `slnt`, and the size as `opsz`, as `font-optical-sizing: auto` does.\n */\nexport function fontAdvance(options: FontAdvanceOptions): (text: string, font: string) => number {\n const engine = options.engine ?? \"freetype\";\n if (typeof engine === \"string\" && !isEngineName(engine)) throw new RangeError(`the engine \"${engine}\" is not a row of engines`);\n const rules: EngineRules = typeof engine === \"string\" ? engines[engine] : engine;\n const shaping = options.shaping ?? \"canvas\";\n const fallback = shaping === \"canvas\" ? options.fallback : undefined;\n const faces = options.faces;\n const loaded = new Map<number, Loaded>();\n const specs = new Map<string, FontSpec>();\n const instances = new Map<string, Font>();\n const families = new Map<string, readonly Font[] | undefined>();\n\n const load = (index: number): Loaded => {\n let entry = loaded.get(index);\n if (entry === undefined) {\n const face = faces[index]!;\n const font = readFont(face.data, { deltas: rules.deltas, metrics: rules.metrics, ...(face.decompress === undefined ? {} : { decompress: face.decompress }) });\n const axis = font.axes.find((value) => value.tag === \"wght\");\n const declared = face.weight;\n const range: readonly [number, number] = typeof declared === \"number\" ? [declared, declared] : (declared ?? (axis === undefined ? [400, 400] : [axis.min, axis.max]));\n entry = { face, index, font, range };\n loaded.set(index, entry);\n }\n return entry;\n };\n\n /** This function gives the font of the best face of a family for the spec, or `undefined` when the family has no face. */\n const fontOf = (family: string, spec: FontSpec): Font | undefined => {\n const name = family.toLowerCase();\n const candidates: Loaded[] = [];\n for (let i = 0; i < faces.length; i++) if (faces[i]!.family.toLowerCase() === name) candidates.push(load(i));\n if (candidates.length === 0) return undefined;\n const style = styleOrder[spec.style].find((value) => candidates.some((entry) => (entry.face.style ?? \"normal\") === value))!;\n let best: Loaded | undefined;\n let bestRank = Infinity;\n for (const entry of candidates) {\n if ((entry.face.style ?? \"normal\") !== style) continue;\n const rank = weightRank(entry.range, spec.weight);\n if (rank < bestRank) {\n best = entry;\n bestRank = rank;\n }\n }\n const chosen = best!;\n const tags = new Set(chosen.font.axes.map((axis) => axis.tag));\n const instance: Record<string, number> = {};\n if (tags.has(\"wght\")) instance[\"wght\"] = Math.min(chosen.range[1], Math.max(chosen.range[0], spec.weight));\n if (tags.has(\"wdth\")) instance[\"wdth\"] = spec.stretch;\n if (tags.has(\"opsz\")) instance[\"opsz\"] = spec.size;\n if (tags.has(\"ital\")) instance[\"ital\"] = spec.style === \"italic\" ? 1 : 0;\n if (tags.has(\"slnt\")) instance[\"slnt\"] = spec.style === \"oblique\" ? -spec.angle : 0;\n const key = `${chosen.index}|${JSON.stringify(instance)}`;\n let font = instances.get(key);\n if (font === undefined) {\n font = Object.keys(instance).length === 0 ? chosen.font : chosen.font.at(instance);\n // A key holds the size for an axis opsz, so this cache has a bound, as the other caches have\n if (instances.size >= 256) instances.clear();\n instances.set(key, font);\n }\n return font;\n };\n\n const fontsOf = (font: string): { readonly spec: FontSpec; readonly fonts: readonly Font[] } => {\n let spec = specs.get(font);\n if (spec === undefined) {\n spec = parseFont(font);\n if (specs.size >= 256) specs.clear();\n specs.set(font, spec);\n }\n let fonts = families.get(font);\n if (fonts === undefined) {\n fonts = spec.families.map((family) => fontOf(family, spec)).filter((value) => value !== undefined);\n if (fonts.length === 0) throw new RangeError(`no face of the host has a family of the font \"${font}\"`);\n if (families.size >= 256) families.clear();\n families.set(font, fonts);\n }\n return { spec, fonts };\n };\n\n return (text: string, font: string): number => {\n const { spec, fonts } = fontsOf(font);\n const sum = (parts: readonly string[], width: (part: string) => number): number => parts.reduce((total, part) => total + width(part), 0);\n const measure = (run: string, face: Font): number => {\n const runs = scriptRuns(run);\n const tagged = (part: string): number => measureWidth(face, part, spec.size, { script: scriptTag(part), shaping, rounding: rules.rounding, sum: rules.sum });\n const risky = (part: string): boolean => fallback !== undefined && shapingRisks(face, part, { script: scriptTag(part), shaping }).length > 0;\n if (runs.length === 1 && !risky(run)) return tagged(run);\n if (shaping !== \"canvas\") return sum(runs, tagged);\n // The width of a word comes from the word alone. This keeps the separator law of the rope\n return sum(canvasWords(run), (word) => {\n const parts = scriptRuns(word);\n return parts.some(risky) ? fallback!(word, font) : sum(parts, tagged);\n });\n };\n if (fonts.length === 1) return measure(text, fonts[0]!);\n let width = 0;\n let run = \"\";\n let current: Font | undefined;\n let joined = false;\n for (const character of text) {\n const code = character.codePointAt(0)!;\n const stays = current !== undefined && (joined || attached.test(character));\n const face = stays ? current! : (fonts.find((value) => value.glyph(code) !== 0) ?? fonts[0]!);\n if (face !== current && run.length > 0) {\n width += measure(run, current!);\n run = \"\";\n }\n current = face;\n run += character;\n joined = code === 0x200d;\n }\n if (run.length > 0) width += measure(run, current!);\n return width;\n };\n}\n","/**\n * The subpath `./measurer`: the advance function of a layout engine, from the font model of typeset. The measurer of\n * `@mark1russell7/layout-contract/text` takes it as its `AdvanceFn`.\n */\nexport { fontAdvance, parseFont, scriptTag, type AdvanceFn, type FontAdvanceOptions, type FontFace, type FontSpec } from \"./measurer/advance.ts\";\n"],"mappings":";;;;;;;;;;AA8DA,MAAM,YAA8C;CAClD,mBAAmB;CACnB,mBAAmB;CACnB,WAAW;CACX,kBAAkB;CAClB,iBAAiB;CACjB,UAAU;CACV,kBAAkB;CAClB,kBAAkB;AACpB;AAGA,MAAM,cAAc;AACpB,MAAM,eAAe;AACrB,MAAM,gBAAgB;;;;;AAMtB,SAAgB,UAAU,MAAwB;CAChD,MAAM,SAAS,KAAK,KAAK,CAAC,CAAC,MAAM,KAAK;CACtC,IAAI,QAA2B;CAC/B,IAAI,QAAQ;CACZ,IAAI,SAAS;CACb,IAAI,UAAU;CACd,IAAI,QAAQ;CACZ,OAAO,QAAQ,OAAO,QAAQ,SAAS;EACrC,MAAM,QAAQ,OAAO;EACrB,MAAM,QAAQ,MAAM,YAAY;EAEhC,IADa,YAAY,KAAK,KACvB,MAAM,MAAM;EACnB,IAAI,UAAU,UAAU;EACxB,IAAI,UAAU,UAAU,QAAQ;OAC3B,IAAI,UAAU,WAAW;GAC5B,QAAQ;GACR,MAAM,OAAO,aAAa,KAAK,OAAO,QAAQ,MAAM,EAAE;GACtD,IAAI,SAAS,MAAM;IACjB,QAAQ,OAAO,KAAK,EAAE;IACtB;GACF;EACF,OAAO,IAAI,UAAU,UAAU,UAAU,UAAU,SAAS;OACvD,IAAI,UAAU,WAAW,SAAS;OAClC,IAAI,cAAc,KAAK,KAAK,KAAK,OAAO,KAAK,KAAK,KAAK,OAAO,KAAK,KAAK,KAAM,SAAS,OAAO,KAAK;OACnG,IAAI,OAAO,OAAO,WAAW,KAAK,GAAG,UAAU,UAAU;OACzD,MAAM,IAAI,WAAW,aAAa,KAAK,kBAAkB,MAAM,oCAAoC;CAC1G;CACA,MAAM,OAAO,YAAY,KAAK,OAAO,UAAU,EAAE;CACjD,IAAI,SAAS,MAAM,M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a,aAAa,MAAM,MAAM;IAAE,QAAQ,UAAU,IAAI;IAAG;GAAQ,CAAC,CAAC,CAAC,SAAS;GAC3I,IAAI,KAAK,WAAW,KAAK,CAAC,MAAM,GAAG,GAAG,OAAO,OAAO,GAAG;GACvD,IAAI,YAAY,UAAU,OAAO,IAAI,MAAM,MAAM;GAEjD,OAAO,IAAI,YAAY,GAAG,IAAI,SAAS;IACrC,MAAM,QAAQ,WAAW,IAAI;IAC7B,OAAO,MAAM,KAAK,KAAK,IAAI,SAAU,MAAM,IAAI,IAAI,IAAI,OAAO,MAAM;GACtE,CAAC;EACH;EACA,IAAI,MAAM,WAAW,GAAG,OAAO,QAAQ,MAAM,MAAM,EAAG;EACtD,IAAI,QAAQ;EACZ,IAAI,MAAM;EACV,IAAI;EACJ,IAAI,SAAS;EACb,KAAK,MAAM,aAAa,MAAM;GAC5B,MAAM,OAAO,UAAU,YAAY,CAAC;GAEpC,MAAM,OADQ,YAAY,KAAA,MAAc,UAAU,SAAS,KAAK,SAAS,KACpD,UAAY,MAAM,MAAM,UAAU,MAAM,MAAM,IAAI,MAAM,CAAC,KAAK,MAAM;GACzF,IAAI,SAAS,WAAW,IAAI,SAAS,GAAG;IACtC,SAAS,QAAQ,KAAK,OAAQ;IAC9B,MAAM;GACR;GACA,UAAU;GACV,OAAO;GACP,SAAS,SAAS;EACpB;EACA,IAAI,IAAI,SAAS,GAAG,SAAS,QAAQ,KAAK,OAAQ;EAClD,OAAO;CACT;AACF"}
@@ -43,6 +43,11 @@ interface ParagraphOptions {
43
43
  * offset. The width of each part of a word comes from `widthOf`, so the kerning across an offset is not in the sum.
44
44
  */
45
45
  readonly hyphenate?: (word: string) => readonly number[];
46
+ /**
47
+ * The hook of the break places inside a word, for example `lineBreaks` of `./segmentation`. It gives offsets in a word where
48
+ * a line can end with no hyphen and no cost. The default gives no offset. This hook wins at an offset that `hyphenate` also gives.
49
+ */
50
+ readonly breaks?: (word: string) => readonly number[];
46
51
  /** The text that a line shows at a hyphen break. The default is "-". */
47
52
  readonly hyphen?: string;
48
53
  /** The cost of a hyphen break. The default is 50, as in TeX. */
@@ -1 +1 @@
1
- {"version":3,"file":"paragraph.d.ts","names":[],"sources":["../../src/breaking/paragraph.ts"],"mappings":";;;;;KAMY,WAAW;;UAGN;WACN;WACA;WACA;;;UAIM;WACN;WACA;WACA;;;;;;UAOM;WACN;WACA;WACA;WACA;;WAEA;;;KAIC,OAAO,MAAM,OAAO;;UAGf;WACN,gBAAgB;;;UAIV;;WAEN,SAAS;;;;;WAKT,aAAa;;WAEb;;WAEA;;;;;;iBASK,YAAY,cAAc,SAAS,mBAAmB;;UAyBrD;WACN;;WAEA;;WAEA;;WAEA;;;iBAIK,QAAQ,gBAAgB,QAAQ;;iBAOhC,UAAU,gBAAgB,QAAQ;;iBAOlC,UAAU,gBAAgB,QAAQ,eAAe;;;;;iBAcjD,QAAQ,WAAW,WAAW,4BAA4B"}
1
+ {"version":3,"file":"paragraph.d.ts","names":[],"sources":["../../src/breaking/paragraph.ts"],"mappings":";;;;;KAMY,WAAW;;UAGN;WACN;WACA;WACA;;;UAIM;WACN;WACA;WACA;;;;;;UAOM;WACN;WACA;WACA;WACA;;WAEA;;;KAIC,OAAO,MAAM,OAAO;;UAGf;WACN,gBAAgB;;;UAIV;;WAEN,SAAS;;;;;WAKT,aAAa;;;;;WAKb,UAAU;;WAEV;;WAEA;;;;;;iBASK,YAAY,cAAc,SAAS,mBAAmB;;UA0BrD;WACN;;WAEA;;WAEA;;WAEA;;;iBAIK,QAAQ,gBAAgB,QAAQ;;iBAOhC,UAAU,gBAAgB,QAAQ;;iBAOlC,UAAU,gBAAgB,QAAQ,eAAe;;;;;iBAcjD,QAAQ,WAAW,WAAW,4BAA4B"}
@@ -1 +1 @@
1
- {"version":3,"file":"text.d.ts","names":[],"sources":["../../src/text/rope.ts","../../src/text.ts"],"mappings":";;UAYiB;;;;;WAKN;;WAEA;;;;;;cAkLE;;UAIH;;SAMD,KAAK,cAAc,OAAO,SAAS,UAAS,cAAmB;;MAalE;;MAKA;;MAKA;;EAKJ;;EAKA;;EAKA,MAAM,eAAe,eAA4B;;EAQjD,QAAQ,eAAe;;EAKvB,OAAO,OAAO,OAAO;;EASrB,OAAO,YAAY,eAAe;;EAKlC,OAAO,eAAe,cAAc;;EAKpC,QAAQ,eAAe,aAAa,eAAe"}
1
+ {"version":3,"file":"text.d.ts","names":[],"sources":["../../src/text/rope.ts","../../src/text.ts"],"mappings":";;UAkBiB;;;;;WAKN;;WAEA;;;;;;cAwIE;;UAIH;;SAMD,KAAK,cAAc,OAAO,SAAS,UAAS,cAAmB;;MAelE;;MAKA;;MAKA;;EAKJ;;EAKA;;EAKA,MAAM,eAAe,eAA4B;;EAYjD,QAAQ,eAAe;;EAKvB,OAAO,OAAO,OAAO;;EAMrB,OAAO,YAAY,eAAe;;EAKlC,OAAO,eAAe,cAAc;;EAKpC,QAAQ,eAAe,aAAa,eAAe"}
@@ -1,62 +1,91 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime.js";
2
+ import * as Tree from "@mark1russell7/collections/summary-tree";
2
3
  // src/text/rope.ts
3
- function isSeparator(context, code) {
4
- for (let i = 0; i < context.separators.length; i++) if (context.separators.charCodeAt(i) === code) return true;
4
+ /**
5
+ * The `Text` rope: a persistent balanced tree of strings with the width and the length of each subtree. An edit makes a
6
+ * new rope. The new rope shares the subtrees that do not change. The tree is the `summary-tree` record of
7
+ * `@mark1russell7/collections`, and this module gives it the summary of a text.
8
+ *
9
+ * A width function gives the width of a run of text. The rope uses it only for the leaves and for the windows at the
10
+ * seams. Thus an edit uses it of the order of `log n` times. The rope keeps the widths of the short windows, so an edit
11
+ * measures only the windows that it changes. `Text.from` clears this memory.
12
+ *
13
+ * The seams are exact when the width function obeys the separator law. For each text `p + s + q` with a separator `s`:
14
+ * `width(p + s + q) = width(p + s) + width(s + q) - width(s)`. The model of `@mark1russell7/typeset/fonts` obeys it for a space and a
15
+ * tab. It shapes each word alone, and its kerning goes only between two adjacent glyphs.
16
+ */
17
+ /** The summary of the empty text. */
18
+ const noText = {
19
+ length: 0,
20
+ width: 0,
21
+ separated: false,
22
+ head: "",
23
+ headWidth: 0,
24
+ tail: "",
25
+ tailWidth: 0
26
+ };
27
+ /** The largest count of windows in the memory of a context. */
28
+ const windowLimit = 16384;
29
+ /** This function gives the width of a window. A window longer than a leaf stays out of the memory. */
30
+ function windowWidth(context, window) {
31
+ if (window.length > context.chunk) return context.width(window);
32
+ const known = context.windows.get(window);
33
+ if (known !== void 0) return known;
34
+ const width = context.width(window);
35
+ if (context.windows.size >= windowLimit) context.windows.clear();
36
+ context.windows.set(window, width);
37
+ return width;
38
+ }
39
+ function isSeparator(separators, code) {
40
+ for (let i = 0; i < separators.length; i++) if (separators.charCodeAt(i) === code) return true;
5
41
  return false;
6
42
  }
7
- function leafOf(context, text) {
8
- const width = context.width(text);
43
+ function summaryOfLeaf(context, text) {
44
+ const { separators } = context;
45
+ const whole = context.width(text);
9
46
  let first = -1;
10
47
  let last = -1;
11
48
  for (let i = 0; i < text.length; i++) {
12
- if (!isSeparator(context, text.charCodeAt(i))) continue;
49
+ if (!isSeparator(separators, text.charCodeAt(i))) continue;
13
50
  if (first < 0) first = i;
14
51
  last = i;
15
52
  }
16
53
  if (first < 0) return {
17
- kind: "leaf",
18
- text,
19
- height: 0,
20
54
  length: text.length,
21
- width,
55
+ width: whole,
22
56
  separated: false,
23
57
  head: text,
24
- headWidth: width,
58
+ headWidth: whole,
25
59
  tail: text,
26
- tailWidth: width
60
+ tailWidth: whole
27
61
  };
28
62
  const head = text.slice(0, first + 1);
29
63
  const tail = text.slice(last);
30
64
  return {
31
- kind: "leaf",
32
- text,
33
- height: 0,
34
65
  length: text.length,
35
- width,
66
+ width: whole,
36
67
  separated: true,
37
68
  head,
38
- headWidth: context.width(head),
69
+ headWidth: windowWidth(context, head),
39
70
  tail,
40
- tailWidth: context.width(tail)
71
+ tailWidth: windowWidth(context, tail)
41
72
  };
42
73
  }
43
74
  /**
44
- * This function makes the branch of two subtrees. It measures one window: the tail of the left side and the head of the right
45
- * side. The separator law then gives the width of all the text from the widths of the two sides.
75
+ * This function gives the summary of two runs in the order of the text. It measures one window: the tail of the left run and
76
+ * the head of the right run. The separator law then gives the width of all the text from the widths of the two runs.
46
77
  */
47
- function branchOf(context, left, right) {
78
+ function combine(context, left, right) {
79
+ if (left.length === 0) return right;
80
+ if (right.length === 0) return left;
48
81
  const seam = left.tail + right.head;
49
- const seamWidth = context.width(seam);
82
+ const seamWidth = windowWidth(context, seam);
50
83
  let width;
51
84
  if (!left.separated && !right.separated) width = seamWidth;
52
85
  else if (!left.separated) width = right.width - right.headWidth + seamWidth;
53
86
  else if (!right.separated) width = left.width - left.tailWidth + seamWidth;
54
87
  else width = left.width + right.width - left.tailWidth - right.headWidth + seamWidth;
55
88
  return {
56
- kind: "branch",
57
- left,
58
- right,
59
- height: Math.max(left.height, right.height) + 1,
60
89
  length: left.length + right.length,
61
90
  width,
62
91
  separated: left.separated || right.separated,
@@ -66,96 +95,60 @@ function branchOf(context, left, right) {
66
95
  tailWidth: right.separated ? right.tailWidth : seamWidth
67
96
  };
68
97
  }
69
- /** This function joins two trees in the order of the text and keeps the heights of the two children within 1. */
70
- function join(context, left, right) {
71
- if (left === void 0) return right;
72
- if (right === void 0) return left;
73
- if (left.kind === "leaf" && right.kind === "leaf" && left.length + right.length <= context.chunk) return leafOf(context, left.text + right.text);
74
- if (left.height > right.height + 1) {
75
- const branch = left;
76
- const joined = join(context, branch.right, right);
77
- if (joined.height <= branch.left.height + 1) return branchOf(context, branch.left, joined);
78
- return rotateLeft(context, branch.left, joined);
79
- }
80
- if (right.height > left.height + 1) {
81
- const branch = right;
82
- const joined = join(context, left, branch.left);
83
- if (joined.height <= branch.right.height + 1) return branchOf(context, joined, branch.right);
84
- return rotateRight(context, joined, branch.right);
85
- }
86
- return branchOf(context, left, right);
87
- }
88
- /** This function balances the branch of `left` and `heavy`, when `heavy` is 2 levels higher than `left`. */
89
- function rotateLeft(context, left, heavy) {
90
- if (heavy.left.height <= heavy.right.height) return branchOf(context, branchOf(context, left, heavy.left), heavy.right);
91
- const middle = heavy.left;
92
- return branchOf(context, branchOf(context, left, middle.left), branchOf(context, middle.right, heavy.right));
93
- }
94
- /** This function balances the branch of `heavy` and `right`, when `heavy` is 2 levels higher than `right`. */
95
- function rotateRight(context, heavy, right) {
96
- if (heavy.right.height <= heavy.left.height) return branchOf(context, heavy.left, branchOf(context, heavy.right, right));
97
- const middle = heavy.right;
98
- return branchOf(context, branchOf(context, heavy.left, middle.left), branchOf(context, middle.right, right));
99
- }
100
- /** This function divides a tree at the UTF-16 offset `at` into the text before and the text after. */
101
- function split(context, node, at) {
102
- if (node === void 0) return [void 0, void 0];
103
- if (at <= 0) return [void 0, node];
104
- if (at >= node.length) return [node, void 0];
105
- if (node.kind === "leaf") return [leafOf(context, node.text.slice(0, at)), leafOf(context, node.text.slice(at))];
106
- if (at === node.left.length) return [node.left, node.right];
107
- if (at < node.left.length) {
108
- const [before, after] = split(context, node.left, at);
109
- return [before, join(context, after, node.right)];
110
- }
111
- const [before, after] = split(context, node.right, at - node.left.length);
112
- return [join(context, node.left, before), after];
98
+ /** The contexts of each width function. Two ropes join only when their trees have the same spec. */
99
+ const contexts = /* @__PURE__ */ new WeakMap();
100
+ function contextOf(width, separators, chunk) {
101
+ const own = contexts.get(width) ?? /* @__PURE__ */ new Map();
102
+ contexts.set(width, own);
103
+ const key = `${chunk}/${separators}`;
104
+ const known = own.get(key);
105
+ if (known !== void 0) return known;
106
+ const context = {
107
+ width,
108
+ separators,
109
+ chunk,
110
+ spec: {
111
+ monoid: {
112
+ empty: noText,
113
+ combine: (left, right) => combine(context, left, right)
114
+ },
115
+ measure: (leaf) => summaryOfLeaf(context, leaf),
116
+ merge: (left, right) => left.length + right.length <= chunk ? left + right : void 0
117
+ },
118
+ windows: /* @__PURE__ */ new Map()
119
+ };
120
+ own.set(key, context);
121
+ return context;
113
122
  }
114
123
  /** This function gives the end of the next leaf of `text` from `start`: after a separator when it can, and not in a surrogate pair. */
115
124
  function chunkEnd(context, text, start) {
116
125
  const limit = start + context.chunk;
117
126
  if (limit >= text.length) return text.length;
118
- for (let i = limit - 1; i >= start + context.chunk / 2; i--) if (isSeparator(context, text.charCodeAt(i))) return i + 1;
127
+ for (let i = limit - 1; i >= start + context.chunk / 2; i--) if (isSeparator(context.separators, text.charCodeAt(i))) return i + 1;
119
128
  const code = text.charCodeAt(limit - 1);
120
129
  return code >= 55296 && code <= 56319 ? limit - 1 : limit;
121
130
  }
122
- /** This function makes a balanced tree of a text: leaves of at most `chunk` code units, and then a level of branches at a time. */
123
- function build(context, text) {
124
- let level = [];
131
+ /** This function divides a text into leaves of at most `chunk` code units. */
132
+ function chunksOf(context, text) {
133
+ const out = [];
125
134
  for (let start = 0; start < text.length;) {
126
135
  const end = chunkEnd(context, text, start);
127
- level.push(leafOf(context, text.slice(start, end)));
136
+ out.push(text.slice(start, end));
128
137
  start = end;
129
138
  }
130
- if (level.length === 0) return void 0;
131
- while (level.length > 1) {
132
- const next = [];
133
- for (let i = 0; i + 1 < level.length; i += 2) next.push(branchOf(context, level[i], level[i + 1]));
134
- if (level.length % 2 === 1) next.push(level[level.length - 1]);
135
- level = next;
136
- }
137
- return level[0];
138
- }
139
- function leaves(node, out) {
140
- if (node === void 0) return out;
141
- const stack = [node];
142
- while (stack.length > 0) {
143
- const top = stack.pop();
144
- if (top.kind === "leaf") out.push(top.text);
145
- else stack.push(top.right, top.left);
146
- }
147
139
  return out;
148
140
  }
141
+ const lengthOf = (summary) => summary.length;
149
142
  /**
150
143
  * A text with its width: a persistent balanced rope. Each edit gives a new `Text` and does not change this one. The offsets
151
144
  * are in UTF-16 code units, as the offsets of a JavaScript string.
152
145
  */
153
146
  var Text = class Text {
154
147
  #context;
155
- #root;
156
- constructor(context, root) {
148
+ #tree;
149
+ constructor(context, tree) {
157
150
  this.#context = context;
158
- this.#root = root;
151
+ this.#tree = tree;
159
152
  }
160
153
  /** This function makes the rope of `text` with the width function `width`. */
161
154
  static from(text, width, options = {}) {
@@ -166,39 +159,40 @@ var Text = class Text {
166
159
  const code = separators.charCodeAt(i);
167
160
  if (code >= 55296 && code <= 57343) throw new RangeError("a separator is one UTF-16 code unit, not a half of a surrogate pair");
168
161
  }
169
- const context = {
170
- width,
171
- separators,
172
- chunk
173
- };
174
- return new Text(context, build(context, text));
162
+ const context = contextOf(width, separators, chunk);
163
+ context.windows.clear();
164
+ return new Text(context, Tree.of(context.spec, chunksOf(context, text)));
175
165
  }
176
166
  /** The count of UTF-16 code units of the text. */
177
167
  get length() {
178
- return this.#root?.length ?? 0;
168
+ return Tree.summary(this.#tree).length;
179
169
  }
180
170
  /** The width of the text. It is equal to the width of the flat string when the width function obeys the separator law. */
181
171
  get width() {
182
- return this.#root?.width ?? 0;
172
+ return Tree.summary(this.#tree).width;
183
173
  }
184
174
  /** The height of the tree: 0 for a text of one leaf. The tests use it to examine the balance. */
185
175
  get height() {
186
- return this.#root?.height ?? 0;
176
+ return Math.max(0, Tree.height(this.#tree) - 1);
187
177
  }
188
178
  /** This function gives the flat string. */
189
179
  toString() {
190
- return leaves(this.#root, []).join("");
180
+ return this.chunks().join("");
191
181
  }
192
182
  /** This function gives the strings of the leaves in the order of the text. */
193
183
  chunks() {
194
- return leaves(this.#root, []);
184
+ return Tree.toArray(this.#tree);
195
185
  }
196
186
  /** This function gives the text from `start` to `end`, as a new rope. */
197
187
  slice(start, end = this.length) {
198
188
  this.#check(start, end);
199
- const [, after] = split(this.#context, this.#root, start);
200
- const [middle] = split(this.#context, after, end - start);
201
- return new Text(this.#context, middle);
189
+ if (start === end) return new Text(this.#context, Tree.slice(this.#tree, 0, 0));
190
+ const first = Tree.locate(this.#tree, lengthOf, start);
191
+ const last = Tree.locate(this.#tree, lengthOf, end - 1);
192
+ const stop = first.offset + end - start;
193
+ const middle = Tree.slice(this.#tree, first.index, last.index + 1);
194
+ if (first.index === last.index) return new Text(this.#context, Tree.set(middle, 0, first.leaf.slice(first.offset, stop)));
195
+ return new Text(this.#context, Tree.set(Tree.set(middle, -1, last.leaf.slice(0, last.offset + 1)), 0, first.leaf.slice(first.offset)));
202
196
  }
203
197
  /** This function gives the width of the text from `start` to `end`. */
204
198
  widthOf(start, end = this.length) {
@@ -206,9 +200,8 @@ var Text = class Text {
206
200
  }
207
201
  /** This function gives this text and then `other`. The two ropes must have the same width function and options. */
208
202
  concat(other) {
209
- const context = other.#context;
210
- if (context.width !== this.#context.width || context.separators !== this.#context.separators || context.chunk !== this.#context.chunk) throw new TypeError("the two ropes have different width functions or options");
211
- return new Text(this.#context, join(this.#context, this.#root, other.#root));
203
+ if (other.#context !== this.#context) throw new TypeError("the two ropes have different width functions or options");
204
+ return new Text(this.#context, Tree.concat(this.#tree, other.#tree));
212
205
  }
213
206
  /** This function puts `text` at the offset `at`. */
214
207
  insert(at, text) {
@@ -221,10 +214,24 @@ var Text = class Text {
221
214
  /** This function puts `text` in place of the text from `start` to `end`. */
222
215
  replace(start, end, text) {
223
216
  this.#check(start, end);
224
- const [before, rest] = split(this.#context, this.#root, start);
225
- const [, after] = split(this.#context, rest, end - start);
226
- const middle = build(this.#context, text);
227
- return new Text(this.#context, join(this.#context, join(this.#context, before, middle), after));
217
+ if (start === end && text.length === 0) return this;
218
+ if (Tree.size(this.#tree) === 0) return Text.from(text, this.#context.width, this.#context);
219
+ const first = Tree.locate(this.#tree, lengthOf, start) ?? this.#lastPlace();
220
+ const last = start === end ? first : Tree.locate(this.#tree, lengthOf, end - 1);
221
+ const lastEnd = start === end ? first.offset : last.offset + 1;
222
+ const fresh = first.leaf.slice(0, first.offset) + text + last.leaf.slice(lastEnd);
223
+ const leaves = chunksOf(this.#context, fresh);
224
+ if (first.index === last.index && leaves.length === 1 && leaves[0].length * 2 >= this.#context.chunk) return new Text(this.#context, Tree.set(this.#tree, first.index, leaves[0]));
225
+ return new Text(this.#context, Tree.splice(this.#tree, first.index, last.index - first.index + 1, leaves));
226
+ }
227
+ /** This function gives the place after the last code unit: the end of the last leaf. */
228
+ #lastPlace() {
229
+ const leaf = Tree.at(this.#tree, -1);
230
+ return {
231
+ index: Tree.size(this.#tree) - 1,
232
+ leaf,
233
+ offset: leaf.length
234
+ };
228
235
  }
229
236
  #check(start, end) {
230
237
  if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end > this.length) throw new RangeError(`the range ${start} to ${end} is not in the text of length ${this.length}`);
@@ -1 +1 @@
1
- {"version":3,"file":"text.js","names":[],"sources":["../../src/text/rope.ts","../../src/text.ts"],"sourcesContent":["/**\n * The `Text` rope: a persistent balanced tree of strings with the width and the length of each subtree. An edit makes a\n * new rope. The new rope shares the subtrees that do not change. A width function gives the width of a run of text. The\n * rope uses it only for the leaves and for the windows at the seams. Thus an edit uses it of the order of `log n` times.\n *\n * The seams are exact when the width function obeys the separator law. For each text `p + s + q` with a separator `s`:\n * `width(p + s + q) = width(p + s) + width(s + q) - width(s)`. The model of `@mark1russell7/typeset/fonts` obeys it for a space and a\n * tab. It shapes each word alone, and its kerning goes only between two adjacent glyphs.\n */\nimport type { WidthOf } from \"../breaking/paragraph.ts\";\n\n/** The options of a rope. */\nexport interface TextOptions {\n /**\n * The separators of the separator law: each character is one UTF-16 code unit. The default is a space and a tab. An\n * empty string makes each seam measure the full text of the two sides.\n */\n readonly separators?: string;\n /** The largest count of UTF-16 code units in a leaf. The default is 256. */\n readonly chunk?: number;\n}\n\n/** The summary of a subtree: its length, its width, and the two ends that a seam measures again. */\ninterface Summary {\n /** The count of UTF-16 code units. */\n readonly length: number;\n readonly width: number;\n /** This value is `true` when the text has a separator. */\n readonly separated: boolean;\n /** The text through the first separator, or all the text when the text has no separator. */\n readonly head: string;\n readonly headWidth: number;\n /** The text from the last separator, or all the text when the text has no separator. */\n readonly tail: string;\n readonly tailWidth: number;\n}\n\ninterface Leaf extends Summary {\n readonly kind: \"leaf\";\n readonly text: string;\n readonly height: 0;\n}\n\ninterface Branch extends Summary {\n readonly kind: \"branch\";\n readonly left: Node;\n readonly right: Node;\n readonly height: number;\n}\n\ntype Node = Leaf | Branch;\n\n/** The shared state of the ropes of one width function and one set of options. */\ninterface Context {\n readonly width: WidthOf;\n readonly separators: string;\n readonly chunk: number;\n}\n\nfunction isSeparator(context: Context, code: number): boolean {\n for (let i = 0; i < context.separators.length; i++) if (context.separators.charCodeAt(i) === code) return true;\n return false;\n}\n\nfunction leafOf(context: Context, text: string): Leaf {\n const width = context.width(text);\n let first = -1;\n let last = -1;\n for (let i = 0; i < text.length; i++) {\n if (!isSeparator(context, text.charCodeAt(i))) continue;\n if (first < 0) first = i;\n last = i;\n }\n if (first < 0) return { kind: \"leaf\", text, height: 0, length: text.length, width, separated: false, head: text, headWidth: width, tail: text, tailWidth: width };\n const head = text.slice(0, first + 1);\n const tail = text.slice(last);\n return { kind: \"leaf\", text, height: 0, length: text.length, width, separated: true, head, headWidth: context.width(head), tail, tailWidth: context.width(tail) };\n}\n\n/**\n * This function makes the branch of two subtrees. It measures one window: the tail of the left side and the head of the right\n * side. The separator law then gives the width of all the text from the widths of the two sides.\n */\nfunction branchOf(context: Context, left: Node, right: Node): Branch {\n const seam = left.tail + right.head;\n const seamWidth = context.width(seam);\n let width: number;\n if (!left.separated && !right.separated) width = seamWidth;\n else if (!left.separated) width = right.width - right.headWidth + seamWidth;\n else if (!right.separated) width = left.width - left.tailWidth + seamWidth;\n else width = left.width + right.width - left.tailWidth - right.headWidth + seamWidth;\n return {\n kind: \"branch\",\n left,\n right,\n height: Math.max(left.height, right.height) + 1,\n length: left.length + right.length,\n width,\n separated: left.separated || right.separated,\n head: left.separated ? left.head : seam,\n headWidth: left.separated ? left.headWidth : seamWidth,\n tail: right.separated ? right.tail : seam,\n tailWidth: right.separated ? right.tailWidth : seamWidth,\n };\n}\n\n/** This function joins two trees in the order of the text and keeps the heights of the two children within 1. */\nfunction join(context: Context, left: Node | undefined, right: Node | undefined): Node | undefined {\n if (left === undefined) return right;\n if (right === undefined) return left;\n if (left.kind === \"leaf\" && right.kind === \"leaf\" && left.length + right.length <= context.chunk) return leafOf(context, left.text + right.text);\n if (left.height > right.height + 1) {\n const branch = left as Branch;\n const joined = join(context, branch.right, right)!;\n if (joined.height <= branch.left.height + 1) return branchOf(context, branch.left, joined);\n return rotateLeft(context, branch.left, joined as Branch);\n }\n if (right.height > left.height + 1) {\n const branch = right as Branch;\n const joined = join(context, left, branch.left)!;\n if (joined.height <= branch.right.height + 1) return branchOf(context, joined, branch.right);\n return rotateRight(context, joined as Branch, branch.right);\n }\n return branchOf(context, left, right);\n}\n\n/** This function balances the branch of `left` and `heavy`, when `heavy` is 2 levels higher than `left`. */\nfunction rotateLeft(context: Context, left: Node, heavy: Branch): Branch {\n if (heavy.left.height <= heavy.right.height) return branchOf(context, branchOf(context, left, heavy.left), heavy.right);\n const middle = heavy.left as Branch;\n return branchOf(context, branchOf(context, left, middle.left), branchOf(context, middle.right, heavy.right));\n}\n\n/** This function balances the branch of `heavy` and `right`, when `heavy` is 2 levels higher than `right`. */\nfunction rotateRight(context: Context, heavy: Branch, right: Node): Branch {\n if (heavy.right.height <= heavy.left.height) return branchOf(context, heavy.left, branchOf(context, heavy.right, right));\n const middle = heavy.right as Branch;\n return branchOf(context, branchOf(context, heavy.left, middle.left), branchOf(context, middle.right, right));\n}\n\n/** This function divides a tree at the UTF-16 offset `at` into the text before and the text after. */\nfunction split(context: Context, node: Node | undefined, at: number): [Node | undefined, Node | undefined] {\n if (node === undefined) return [undefined, undefined];\n if (at <= 0) return [undefined, node];\n if (at >= node.length) return [node, undefined];\n if (node.kind === \"leaf\") return [leafOf(context, node.text.slice(0, at)), leafOf(context, node.text.slice(at))];\n if (at === node.left.length) return [node.left, node.right];\n if (at < node.left.length) {\n const [before, after] = split(context, node.left, at);\n return [before, join(context, after, node.right)];\n }\n const [before, after] = split(context, node.right, at - node.left.length);\n return [join(context, node.left, before), after];\n}\n\n/** This function gives the end of the next leaf of `text` from `start`: after a separator when it can, and not in a surrogate pair. */\nfunction chunkEnd(context: Context, text: string, start: number): number {\n const limit = start + context.chunk;\n if (limit >= text.length) return text.length;\n for (let i = limit - 1; i >= start + context.chunk / 2; i--) if (isSeparator(context, text.charCodeAt(i))) return i + 1;\n const code = text.charCodeAt(limit - 1);\n return code >= 0xd800 && code <= 0xdbff ? limit - 1 : limit;\n}\n\n/** This function makes a balanced tree of a text: leaves of at most `chunk` code units, and then a level of branches at a time. */\nfunction build(context: Context, text: string): Node | undefined {\n let level: Node[] = [];\n for (let start = 0; start < text.length; ) {\n const end = chunkEnd(context, text, start);\n level.push(leafOf(context, text.slice(start, end)));\n start = end;\n }\n if (level.length === 0) return undefined;\n while (level.length > 1) {\n const next: Node[] = [];\n for (let i = 0; i + 1 < level.length; i += 2) next.push(branchOf(context, level[i]!, level[i + 1]!));\n if (level.length % 2 === 1) next.push(level[level.length - 1]!);\n level = next;\n }\n return level[0];\n}\n\nfunction leaves(node: Node | undefined, out: string[]): string[] {\n if (node === undefined) return out;\n const stack: Node[] = [node];\n while (stack.length > 0) {\n const top = stack.pop()!;\n if (top.kind === \"leaf\") out.push(top.text);\n else stack.push(top.right, top.left);\n }\n return out;\n}\n\n/**\n * A text with its width: a persistent balanced rope. Each edit gives a new `Text` and does not change this one. The offsets\n * are in UTF-16 code units, as the offsets of a JavaScript string.\n */\nexport class Text {\n readonly #context: Context;\n readonly #root: Node | undefined;\n\n private constructor(context: Context, root: Node | undefined) {\n this.#context = context;\n this.#root = root;\n }\n\n /** This function makes the rope of `text` with the width function `width`. */\n static from(text: string, width: WidthOf, options: TextOptions = {}): Text {\n const separators = options.separators ?? \" \\t\";\n const chunk = options.chunk ?? 256;\n if (!Number.isInteger(chunk) || chunk < 2) throw new RangeError(`the chunk is ${chunk}, not an integer of 2 or more`);\n for (let i = 0; i < separators.length; i++) {\n const code = separators.charCodeAt(i);\n if (code >= 0xd800 && code <= 0xdfff) throw new RangeError(\"a separator is one UTF-16 code unit, not a half of a surrogate pair\");\n }\n const context: Context = { width, separators, chunk };\n return new Text(context, build(context, text));\n }\n\n /** The count of UTF-16 code units of the text. */\n get length(): number {\n return this.#root?.length ?? 0;\n }\n\n /** The width of the text. It is equal to the width of the flat string when the width function obeys the separator law. */\n get width(): number {\n return this.#root?.width ?? 0;\n }\n\n /** The height of the tree: 0 for a text of one leaf. The tests use it to examine the balance. */\n get height(): number {\n return this.#root?.height ?? 0;\n }\n\n /** This function gives the flat string. */\n toString(): string {\n return leaves(this.#root, []).join(\"\");\n }\n\n /** This function gives the strings of the leaves in the order of the text. */\n chunks(): string[] {\n return leaves(this.#root, []);\n }\n\n /** This function gives the text from `start` to `end`, as a new rope. */\n slice(start: number, end: number = this.length): Text {\n this.#check(start, end);\n const [, after] = split(this.#context, this.#root, start);\n const [middle] = split(this.#context, after, end - start);\n return new Text(this.#context, middle);\n }\n\n /** This function gives the width of the text from `start` to `end`. */\n widthOf(start: number, end: number = this.length): number {\n return this.slice(start, end).width;\n }\n\n /** This function gives this text and then `other`. The two ropes must have the same width function and options. */\n concat(other: Text): Text {\n const context = other.#context;\n if (context.width !== this.#context.width || context.separators !== this.#context.separators || context.chunk !== this.#context.chunk) {\n throw new TypeError(\"the two ropes have different width functions or options\");\n }\n return new Text(this.#context, join(this.#context, this.#root, other.#root));\n }\n\n /** This function puts `text` at the offset `at`. */\n insert(at: number, text: string): Text {\n return this.replace(at, at, text);\n }\n\n /** This function removes the text from `start` to `end`. */\n remove(start: number, end: number): Text {\n return this.replace(start, end, \"\");\n }\n\n /** This function puts `text` in place of the text from `start` to `end`. */\n replace(start: number, end: number, text: string): Text {\n this.#check(start, end);\n const [before, rest] = split(this.#context, this.#root, start);\n const [, after] = split(this.#context, rest, end - start);\n const middle = build(this.#context, text);\n return new Text(this.#context, join(this.#context, join(this.#context, before, middle), after));\n }\n\n #check(start: number, end: number): void {\n if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end > this.length) {\n throw new RangeError(`the range ${start} to ${end} is not in the text of length ${this.length}`);\n }\n }\n}\n","export { Text, type TextOpt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EACxB,MAAM,UAAU,MAAM;EACtB,IAAI,QAAQ,UAAU,KAAK,SAAS,SAAS,QAAQ,eAAe,KAAK,SAAS,cAAc,QAAQ,UAAU,KAAK,SAAS,OAC9H,MAAM,IAAI,UAAU,yDAAyD;EAE/E,OAAO,IAAI,KAAK,KAAK,UAAU,KAAK,KAAK,UAAU,KAAK,OAAO,MAAM,KAAK,CAAC;CAC7E;;CAGA,OAAO,IAAY,MAAoB;EACrC,OAAO,KAAK,QAAQ,IAAI,IAAI,IAAI;CAClC;;CAGA,OAAO,OAAe,KAAmB;EACvC,OAAO,KAAK,QAAQ,OAAO,KAAK,EAAE;CACpC;;CAGA,QAAQ,OAAe,KAAa,MAAoB;EACtD,KAAK,OAAO,OAAO,GAAG;EACtB,MAAM,CAAC,QAAQ,QAAQ,MAAM,KAAK,UAAU,KAAK,OAAO,KAAK;EAC7D,MAAM,GAAG,SAAS,MAAM,KAAK,UAAU,MAAM,MAAM,KAAK;EACxD,MAAM,SAAS,MAAM,KAAK,UAAU,IAAI;EACxC,OAAO,IAAI,KAAK,KAAK,UAAU,KAAK,KAAK,UAAU,KAAK,KAAK,UAAU,QAAQ,MAAM,GAAG,KAAK,CAAC;CAChG;CAEA,OAAO,OAAe,KAAmB;EACvC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,CAAC,OAAO,UAAU,GAAG,KAAK,QAAQ,KAAK,MAAM,SAAS,MAAM,KAAK,QAC/F,MAAM,IAAI,WAAW,aAAa,MAAM,MAAM,IAAI,gCAAgC,KAAK,QAAQ;CAEnG;AACF"}
1
+ {"version":3,"file":"text.js","names":[],"sources":["../../src/text/rope.ts","../../src/text.ts"],"sourcesContent":["/**\n * The `Text` rope: a persistent balanced tree of strings with the width and the length of each subtree. An edit makes a\n * new rope. The new rope shares the subtrees that do not change. The tree is the `summary-tree` record of\n * `@mark1russell7/collections`, and this module gives it the summary of a text.\n *\n * A width function gives the width of a run of text. The rope uses it only for the leaves and for the windows at the\n * seams. Thus an edit uses it of the order of `log n` times. The rope keeps the widths of the short windows, so an edit\n * measures only the windows that it changes. `Text.from` clears this memory.\n *\n * The seams are exact when the width function obeys the separator law. For each text `p + s + q` with a separator `s`:\n * `width(p + s + q) = width(p + s) + width(s + q) - width(s)`. The model of `@mark1russell7/typeset/fonts` obeys it for a space and a\n * tab. It shapes each word alone, and its kerning goes only between two adjacent glyphs.\n */\nimport * as Tree from \"@mark1russell7/collections/summary-tree\";\nimport type { SummarySpec, SummaryTreeRecord } from \"@mark1russell7/collections/summary-tree\";\nimport type { WidthOf } from \"../breaking/paragraph.ts\";\n\n/** The options of a rope. */\nexport interface TextOptions {\n /**\n * The separators of the separator law: each character is one UTF-16 code unit. The default is a space and a tab. An\n * empty string makes each seam measure the full text of the two sides.\n */\n readonly separators?: string;\n /** The largest count of UTF-16 code units in a leaf. The default is 256. */\n readonly chunk?: number;\n}\n\n/** The summary of a run of text: its length, its width, and the two ends that a seam measures again. */\ninterface Summary {\n /** The count of UTF-16 code units. */\n readonly length: number;\n readonly width: number;\n /** This value is `true` when the text has a separator. */\n readonly separated: boolean;\n /** The text through the first separator, or all the text when the text has no separator. */\n readonly head: string;\n readonly headWidth: number;\n /** The text from the last separator, or all the text when the text has no separator. */\n readonly tail: string;\n readonly tailWidth: number;\n}\n\n/** The summary of the empty text. */\nconst noText: Summary = { length: 0, width: 0, separated: false, head: \"\", headWidth: 0, tail: \"\", tailWidth: 0 };\n\n/** The shared state of the ropes of one width function and one set of options. */\ninterface Context {\n readonly width: WidthOf;\n readonly separators: string;\n readonly chunk: number;\n readonly spec: SummarySpec<string, Summary>;\n /** The widths of the short windows. An edit gives the tree new paths, and most windows on these paths do not change. */\n readonly windows: Map<string, number>;\n}\n\n/** The largest count of windows in the memory of a context. */\nconst windowLimit = 16_384;\n\n/** This function gives the width of a window. A window longer than a leaf stays out of the memory. */\nfunction windowWidth(context: Context, window: string): number {\n if (window.length > context.chunk) return context.width(window);\n const known = context.windows.get(window);\n if (known !== undefined) return known;\n const width = context.width(window);\n if (context.windows.size >= windowLimit) context.windows.clear();\n context.windows.set(window, width);\n return width;\n}\n\nfunction isSeparator(separators: string, code: number): boolean {\n for (let i = 0; i < separators.length; i++) if (separators.charCodeAt(i) === code) return true;\n return false;\n}\n\nfunction summaryOfLeaf(context: Context, text: string): Summary {\n const { separators } = context;\n const whole = context.width(text);\n let first = -1;\n let last = -1;\n for (let i = 0; i < text.length; i++) {\n if (!isSeparator(separators, text.charCodeAt(i))) continue;\n if (first < 0) first = i;\n last = i;\n }\n if (first < 0) return { length: text.length, width: whole, separated: false, head: text, headWidth: whole, tail: text, tailWidth: whole };\n const head = text.slice(0, first + 1);\n const tail = text.slice(last);\n return { length: text.length, width: whole, separated: true, head, headWidth: windowWidth(context, head), tail, tailWidth: windowWidth(context, tail) };\n}\n\n/**\n * This function gives the summary of two runs in the order of the text. It measures one window: the tail of the left run and\n * the head of the right run. The separator law then gives the width of all the text from the widths of the two runs.\n */\nfunction combine(context: Context, left: Summary, right: Summary): Summary {\n if (left.length === 0) return right;\n if (right.length === 0) return left;\n const seam = left.tail + right.head;\n const seamWidth = windowWidth(context, seam);\n let width: number;\n if (!left.separated && !right.separated) width = seamWidth;\n else if (!left.separated) width = right.width - right.headWidth + seamWidth;\n else if (!right.separated) width = left.width - left.tailWidth + seamWidth;\n else width = left.width + right.width - left.tailWidth - right.headWidth + seamWidth;\n return {\n length: left.length + right.length,\n width,\n separated: left.separated || right.separated,\n head: left.separated ? left.head : seam,\n headWidth: left.separated ? left.headWidth : seamWidth,\n tail: right.separated ? right.tail : seam,\n tailWidth: right.separated ? right.tailWidth : seamWidth,\n };\n}\n\n/** The contexts of each width function. Two ropes join only when their trees have the same spec. */\nconst contexts = new WeakMap<WidthOf, Map<string, Context>>();\n\nfunction contextOf(width: WidthOf, separators: string, chunk: number): Context {\n const own = contexts.get(width) ?? new Map<string, Context>();\n contexts.set(width, own);\n const key = `${chunk}/${separators}`;\n const known = own.get(key);\n if (known !== undefined) return known;\n const spec: SummarySpec<string, Summary> = {\n monoid: { empty: noText, combine: (left, right) => combine(context, left, right) },\n measure: (leaf) => summaryOfLeaf(context, leaf),\n merge: (left, right) => (left.length + right.length <= chunk ? left + right : undefined),\n };\n const context: Context = { width, separators, chunk, spec, windows: new Map() };\n own.set(key, context);\n return context;\n}\n\n/** This function gives the end of the next leaf of `text` from `start`: after a separator when it can, and not in a surrogate pair. */\nfunction chunkEnd(context: Context, text: string, start: number): number {\n const limit = start + context.chunk;\n if (limit >= text.length) return text.length;\n for (let i = limit - 1; i >= start + context.chunk / 2; i--) if (isSeparator(context.separators, text.charCodeAt(i))) return i + 1;\n const code = text.charCodeAt(limit - 1);\n return code >= 0xd800 && code <= 0xdbff ? limit - 1 : limit;\n}\n\n/** This function divides a text into leaves of at most `chunk` code units. */\nfunction chunksOf(context: Context, text: string): string[] {\n const out: string[] = [];\n for (let start = 0; start < text.length; ) {\n const end = chunkEnd(context, text, start);\n out.push(text.slice(start, end));\n start = end;\n }\n return out;\n}\n\nconst lengthOf = (summary: Summary): number => summary.length;\n\n/**\n * A text with its width: a persistent balanced rope. Each edit gives a new `Text` and does not change this one. The offsets\n * are in UTF-16 code units, as the offsets of a JavaScript string.\n */\nexport class Text {\n readonly #context: Context;\n readonly #tree: SummaryTreeRecord<string, Summary>;\n\n private constructor(context: Context, tree: SummaryTreeRecord<string, Summary>) {\n this.#context = context;\n this.#tree = tree;\n }\n\n /** This function makes the rope of `text` with the width function `width`. */\n static from(text: string, width: WidthOf, options: TextOptions = {}): Text {\n const separators = options.separators ?? \" \\t\";\n const chunk = options.chunk ?? 256;\n if (!Number.isInteger(chunk) || chunk < 2) throw new RangeError(`the chunk is ${chunk}, not an integer of 2 or more`);\n for (let i = 0; i < separators.length; i++) {\n const code = separators.charCodeAt(i);\n if (code >= 0xd800 && code <= 0xdfff) throw new RangeError(\"a separator is one UTF-16 code unit, not a half of a surrogate pair\");\n }\n const context = contextOf(width, separators, chunk);\n // A new rope measures again: the width function can change its result when a font loads\n context.windows.clear();\n return new Text(context, Tree.of(context.spec, chunksOf(context, text)));\n }\n\n /** The count of UTF-16 code units of the text. */\n get length(): number {\n return Tree.summary(this.#tree).length;\n }\n\n /** The width of the text. It is equal to the width of the flat string when the width function obeys the separator law. */\n get width(): number {\n return Tree.summary(this.#tree).width;\n }\n\n /** The height of the tree: 0 for a text of one leaf. The tests use it to examine the balance. */\n get height(): number {\n return Math.max(0, Tree.height(this.#tree) - 1);\n }\n\n /** This function gives the flat string. */\n toString(): string {\n return this.chunks().join(\"\");\n }\n\n /** This function gives the strings of the leaves in the order of the text. */\n chunks(): string[] {\n return Tree.toArray(this.#tree);\n }\n\n /** This function gives the text from `start` to `end`, as a new rope. */\n slice(start: number, end: number = this.length): Text {\n this.#check(start, end);\n if (start === end) return new Text(this.#context, Tree.slice(this.#tree, 0, 0));\n const first = Tree.locate(this.#tree, lengthOf, start)!;\n const last = Tree.locate(this.#tree, lengthOf, end - 1)!;\n const stop = first.offset + end - start;\n const middle = Tree.slice(this.#tree, first.index, last.index + 1);\n if (first.index === last.index) return new Text(this.#context, Tree.set(middle, 0, first.leaf.slice(first.offset, stop)));\n return new Text(this.#context, Tree.set(Tree.set(middle, -1, last.leaf.slice(0, last.offset + 1)), 0, first.leaf.slice(first.offset)));\n }\n\n /** This function gives the width of the text from `start` to `end`. */\n widthOf(start: number, end: number = this.length): number {\n return this.slice(start, end).width;\n }\n\n /** This function gives this text and then `other`. The two ropes must have the same width function and options. */\n concat(other: Text): Text {\n if (other.#context !== this.#context) throw new TypeError(\"the two ropes have different width functions or options\");\n return new Text(this.#context, Tree.concat(this.#tree, other.#tree));\n }\n\n /** This function puts `text` at the offset `at`. */\n insert(at: number, text: string): Text {\n return this.replace(at, at, text);\n }\n\n /** This function removes the text from `start` to `end`. */\n remove(start: number, end: number): Text {\n return this.replace(start, end, \"\");\n }\n\n /** This function puts `text` in place of the text from `start` to `end`. */\n replace(start: number, end: number, text: string): Text {\n this.#check(start, end);\n if (start === end && text.length === 0) return this;\n const size = Tree.size(this.#tree);\n if (size === 0) return Text.from(text, this.#context.width, this.#context);\n const first = Tree.locate(this.#tree, lengthOf, start) ?? this.#lastPlace();\n const last = start === end ? first : Tree.locate(this.#tree, lengthOf, end - 1)!;\n const lastEnd = start === end ? first.offset : last.offset + 1;\n const fresh = first.leaf.slice(0, first.offset) + text + last.leaf.slice(lastEnd);\n const leaves = chunksOf(this.#context, fresh);\n // One long leaf in place of one leaf changes only a path. A short leaf goes through the seams, so that it can merge\n if (first.index === last.index && leaves.length === 1 && leaves[0]!.length * 2 >= this.#context.chunk) {\n return new Text(this.#context, Tree.set(this.#tree, first.index, leaves[0]!));\n }\n return new Text(this.#context, Tree.splice(this.#tree, first.index, last.index - first.index + 1, leaves));\n }\n\n /** This function gives the place after the last code unit: the end of the last leaf. */\n #lastPlace(): { index: number; leaf: string; offset: number } {\n const leaf = Tree.at(this.#tree, -1)!;\n return { index: Tree.size(this.#tree) - 1, leaf, offset: leaf.length };\n }\n\n #check(start: number, end: number): void {\n if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end > this.length) {\n throw new RangeError(`the range ${start} to ${end} is not in the text of length ${this.length}`);\n }\n }\n}\n","export { Text, type TextOptions } from \"./text/rope.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;AA4CA,MAAM,SAAkB;CAAE,QAAQ;CAAG,OAAO;CAAG,WAAW;CAAO,MAAM;CAAI,WAAW;CAAG,MAAM;CAAI,WAAW;AAAE;;AAahH,MAAM,cAAc;;AAGpB,SAAS,YAAY,SAAkB,QAAwB;CAC7D,IAAI,OAAO,SAAS,QAAQ,OAAO,OAAO,QAAQ,MAAM,MAAM;CAC9D,MAAM,QAAQ,QAAQ,QAAQ,IAAI,MAAM;CACxC,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,MAAM,QAAQ,QAAQ,MAAM,MAAM;CAClC,IAAI,QAAQ,QAAQ,QAAQ,aAAa,QAAQ,QAAQ,MAAM;CAC/D,QAAQ,QAAQ,I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