bidi-kit 0.0.0-stage → 0.1.0

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,78 @@
1
+ /**
2
+ * Font stacks per script.
3
+ *
4
+ * Two failures produce the "broken Arabic" look people blame on bidi:
5
+ *
6
+ * 1. the Latin face has no Arabic glyphs, so the browser falls back per glyph —
7
+ * the word changes shape halfway through and the diacritics sit too low;
8
+ * 2. the Arabic face is a *naskh* text face rendered at a Latin line-height,
9
+ * and the kasra, the hamza below and the tail of a final yeh are clipped.
10
+ *
11
+ * The stacks below put a known-good Arabic face first, keep a Latin face that
12
+ * does not interfere, and end in `sans-serif` rather than in nothing.
13
+ */
14
+ export const FONT_STACKS = {
15
+ arabic: [
16
+ '"Noto Naskh Arabic"',
17
+ '"Noto Sans Arabic"',
18
+ '"Amiri"',
19
+ '"Scheherazade New"',
20
+ '"Geeza Pro"',
21
+ '"Segoe UI"',
22
+ '"Noto Sans"',
23
+ "sans-serif",
24
+ ].join(", "),
25
+ hebrew: ['"Noto Sans Hebrew"', '"Arial Hebrew"', '"Gisha"', '"David CLM"', "sans-serif"].join(", "),
26
+ latin: ['"Noto Sans"', "system-ui", "-apple-system", '"Segoe UI"', "Roboto", "sans-serif"].join(", "),
27
+ };
28
+ /** The stack to use for a locale tag; anything not RTL gets the Latin stack. */
29
+ export function fontStack(locale) {
30
+ if (!locale)
31
+ return FONT_STACKS.latin;
32
+ const language = locale.toLowerCase().split(/[-_]/)[0] ?? "";
33
+ if (language === "ar" || language === "fa" || language === "ur" || language === "ps") {
34
+ return FONT_STACKS.arabic;
35
+ }
36
+ if (language === "he" || language === "yi")
37
+ return FONT_STACKS.hebrew;
38
+ return FONT_STACKS.latin;
39
+ }
40
+ /** The `font-feature-settings` that keep Arabic words from looking two-tone. */
41
+ export const ARABIC_FEATURES = '"kern" 1, "liga" 1, "calt" 1, "rlig" 1, "init" 1, "medi" 1, "fina" 1';
42
+ /**
43
+ * The `unicode-range` for a script, so a downloaded face is only fetched for
44
+ * the characters it actually covers. Without it, a page with one Arabic
45
+ * headline downloads the Arabic font for every reader.
46
+ */
47
+ export const UNICODE_RANGES = {
48
+ arabic: "U+0600-06FF, U+0750-077F, U+0870-088E, U+08A0-08FF, U+FB50-FDFF, U+FE70-FEFF, U+1EE00-1EEFF",
49
+ hebrew: "U+0590-05FF, U+FB1D-FB4F",
50
+ latin: "U+0000-00FF, U+0131, U+0152-0153, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193",
51
+ };
52
+ /**
53
+ * Builds an `@font-face` rule.
54
+ *
55
+ * It is deliberately a string and not a file: the package ships no fonts, so a
56
+ * consumer decides where the bytes come from — a local install, a CDN, or a
57
+ * self-hosted file — and this only removes the chance of getting the
58
+ * `unicode-range` and the metrics wrong while doing it.
59
+ */
60
+ export function fontFace(options) {
61
+ const script = options.script ?? "arabic";
62
+ const sources = Array.isArray(options.src) ? options.src : [options.src];
63
+ const lines = [
64
+ ` font-family: "${options.family}";`,
65
+ ` src: ${sources.join(", ")};`,
66
+ ` font-weight: ${options.weight ?? "400"};`,
67
+ ` font-style: ${options.style ?? "normal"};`,
68
+ ` font-display: ${options.display ?? "swap"};`,
69
+ ` unicode-range: ${options.unicodeRange ?? UNICODE_RANGES[script]};`,
70
+ ];
71
+ if (options.sizeAdjust)
72
+ lines.push(` size-adjust: ${options.sizeAdjust};`);
73
+ return `@font-face {\n${lines.join("\n")}\n}`;
74
+ }
75
+ /** A `font-family` declaration that pairs an Arabic face with a Latin one. */
76
+ export function fontFamilyRule(selector, script = "arabic") {
77
+ return `${selector} {\n font-family: ${FONT_STACKS[script]};\n}`;
78
+ }
@@ -0,0 +1,32 @@
1
+ import type { AttributeDirection, DirectionalElement, HtmlOptions, ParagraphOptions, Part } from "./types.js";
2
+ /** Escapes text for use as element content or in a quoted attribute value. */
3
+ export declare function escapeHtml(text: string): string;
4
+ /**
5
+ * A `<bdi>` element wrapping `text`.
6
+ *
7
+ * `<bdi>` is the one HTML element whose whole job is this problem: it isolates
8
+ * its content from the surrounding paragraph, so neither the reader's text nor
9
+ * the browser's bidi algorithm can drag a neighbouring word into the wrong
10
+ * place. Reach for it before reaching for a mark you cannot see.
11
+ */
12
+ export declare function bdi(text: string, options?: HtmlOptions): string;
13
+ /** A `<span dir>` that isolates by style instead of by element. */
14
+ export declare function inline(text: string, options?: HtmlOptions): string;
15
+ /**
16
+ * Builds one paragraph out of mixed parts.
17
+ *
18
+ * Named parts get an explicit direction and, if you pass one, a font: that is
19
+ * how an Arabic sentence in a French paragraph ends up in a face that actually
20
+ * has the glyphs, instead of a fallback the operating system picked without
21
+ * asking. Strings are treated as plain text and escaped unless `html` is set.
22
+ */
23
+ export declare function paragraph(parts: readonly Part[], options?: ParagraphOptions): string;
24
+ /**
25
+ * Sets element text and direction in one call. The container decides the
26
+ * paragraph's base direction; each run inside it is left to the bidi
27
+ * algorithm, which is what makes an English sentence with an Arabic name look
28
+ * like an English sentence.
29
+ */
30
+ export declare function apply(element: DirectionalElement, text: string, options?: {
31
+ dir?: AttributeDirection;
32
+ }): DirectionalElement;
@@ -0,0 +1,89 @@
1
+ import { resolveDirection } from "./segment.js";
2
+ const ESCAPES = {
3
+ "&": "&amp;",
4
+ "<": "&lt;",
5
+ ">": "&gt;",
6
+ '"': "&quot;",
7
+ "'": "&#39;",
8
+ };
9
+ /** Escapes text for use as element content or in a quoted attribute value. */
10
+ export function escapeHtml(text) {
11
+ return text.replace(/[&<>"']/g, (char) => ESCAPES[char] ?? char);
12
+ }
13
+ function attribute(name, value) {
14
+ return value === undefined || value === "" ? "" : ` ${name}="${escapeHtml(value)}"`;
15
+ }
16
+ function styleValue(font) {
17
+ return font ? `font-family: ${font}` : undefined;
18
+ }
19
+ /**
20
+ * A `<bdi>` element wrapping `text`.
21
+ *
22
+ * `<bdi>` is the one HTML element whose whole job is this problem: it isolates
23
+ * its content from the surrounding paragraph, so neither the reader's text nor
24
+ * the browser's bidi algorithm can drag a neighbouring word into the wrong
25
+ * place. Reach for it before reaching for a mark you cannot see.
26
+ */
27
+ export function bdi(text, options = {}) {
28
+ return inline(text, { ...options, element: options.element ?? "bdi" });
29
+ }
30
+ /** A `<span dir>` that isolates by style instead of by element. */
31
+ export function inline(text, options = {}) {
32
+ const element = options.element ?? "span";
33
+ const dir = options.dir ?? "auto";
34
+ const attributes = [
35
+ dir === "auto" && element === "bdi" ? "" : attribute("dir", dir),
36
+ attribute("lang", options.lang),
37
+ attribute("class", options.class),
38
+ attribute("style", styleValue(options.font)),
39
+ ].join("");
40
+ return `<${element}${attributes}>${escapeHtml(text)}</${element}>`;
41
+ }
42
+ /**
43
+ * Builds one paragraph out of mixed parts.
44
+ *
45
+ * Named parts get an explicit direction and, if you pass one, a font: that is
46
+ * how an Arabic sentence in a French paragraph ends up in a face that actually
47
+ * has the glyphs, instead of a fallback the operating system picked without
48
+ * asking. Strings are treated as plain text and escaped unless `html` is set.
49
+ */
50
+ export function paragraph(parts, options = {}) {
51
+ const plain = parts
52
+ .map((part) => {
53
+ const text = typeof part === "string" ? part : part.text;
54
+ // The direction of a paragraph comes from its words, not from its tags.
55
+ return options.html ? text.replace(/<[^>]*>/g, " ") : text;
56
+ })
57
+ .join("");
58
+ const dir = options.dir === undefined || options.dir === "auto" ? resolveDirection(plain) : options.dir;
59
+ const body = parts
60
+ .map((part) => {
61
+ if (typeof part === "string")
62
+ return options.html ? part : escapeHtml(part);
63
+ const attributes = [
64
+ attribute("dir", part.dir ?? "auto"),
65
+ attribute("lang", part.lang),
66
+ attribute("style", styleValue(part.font)),
67
+ ].join("");
68
+ const inner = options.html ? part.text : escapeHtml(part.text);
69
+ return `<bdi${attributes}>${inner}</bdi>`;
70
+ })
71
+ .join("");
72
+ const attributes = [
73
+ attribute("dir", dir),
74
+ attribute("lang", options.lang),
75
+ attribute("class", options.class),
76
+ ].join("");
77
+ return `<p${attributes}>${body}</p>`;
78
+ }
79
+ /**
80
+ * Sets element text and direction in one call. The container decides the
81
+ * paragraph's base direction; each run inside it is left to the bidi
82
+ * algorithm, which is what makes an English sentence with an Arabic name look
83
+ * like an English sentence.
84
+ */
85
+ export function apply(element, text, options = {}) {
86
+ element.textContent = text;
87
+ element.setAttribute?.("dir", options.dir ?? resolveDirection(text));
88
+ return element;
89
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * bidi-kit — mixed-direction text that behaves.
3
+ *
4
+ * The browser already implements the Unicode bidi algorithm correctly. What it
5
+ * cannot know is where the author meant a boundary to be, which face has the
6
+ * glyphs, or that a paragraph is Arabic until it has read the first character.
7
+ * This package supplies those answers, and nothing else: no runtime
8
+ * dependencies, no fonts, no framework.
9
+ */
10
+ export { segments, detectDirection, resolveDirection, hasRtl, hasArabic, isRtlCodePoint } from "./segment.js";
11
+ export { isolate, isolateRunsText, hasBidiControls, stripBidiControls, BIDI_CONTROL_CHARACTERS, LRI, RLI, FSI, PDI, } from "./isolate.js";
12
+ export { bdi, inline, paragraph, escapeHtml, apply } from "./html.js";
13
+ export { FONT_STACKS, ARABIC_FEATURES, UNICODE_RANGES, fontStack, fontFace, fontFamilyRule, } from "./fonts.js";
14
+ export { CSS, ROOT_CSS, inlineStyle } from "./css.js";
15
+ export { audit, formatAudit } from "./audit.js";
16
+ export type { Direction, AttributeDirection, Segment, IsolateOptions, HtmlOptions, ParagraphOptions, Part, Script, FontFaceOptions, AuditRule, AuditIssue, DirectionalElement, } from "./types.js";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * bidi-kit — mixed-direction text that behaves.
3
+ *
4
+ * The browser already implements the Unicode bidi algorithm correctly. What it
5
+ * cannot know is where the author meant a boundary to be, which face has the
6
+ * glyphs, or that a paragraph is Arabic until it has read the first character.
7
+ * This package supplies those answers, and nothing else: no runtime
8
+ * dependencies, no fonts, no framework.
9
+ */
10
+ export { segments, detectDirection, resolveDirection, hasRtl, hasArabic, isRtlCodePoint } from "./segment.js";
11
+ export { isolate, isolateRunsText, hasBidiControls, stripBidiControls, BIDI_CONTROL_CHARACTERS, LRI, RLI, FSI, PDI, } from "./isolate.js";
12
+ export { bdi, inline, paragraph, escapeHtml, apply } from "./html.js";
13
+ export { FONT_STACKS, ARABIC_FEATURES, UNICODE_RANGES, fontStack, fontFace, fontFamilyRule, } from "./fonts.js";
14
+ export { CSS, ROOT_CSS, inlineStyle } from "./css.js";
15
+ export { audit, formatAudit } from "./audit.js";
@@ -0,0 +1,43 @@
1
+ import type { AttributeDirection } from "./types.js";
2
+ /** Left-to-right isolate. */
3
+ export declare const LRI = "\u2066";
4
+ /** Right-to-left isolate. */
5
+ export declare const RLI = "\u2067";
6
+ /** First-strong isolate: the reader's bidi algorithm picks the direction. */
7
+ export declare const FSI = "\u2068";
8
+ /** Pop directional isolate. */
9
+ export declare const PDI = "\u2069";
10
+ /**
11
+ * Wraps text in an isolate, for plain-text contexts where an element is not an
12
+ * option: an `aria-label`, a canvas, a terminal, a spreadsheet cell, a JSON
13
+ * field that something else will render.
14
+ *
15
+ * In HTML, prefer {@link bdi} — an element is inspectable, stylable and cannot
16
+ * leak a stray `PDI` when a string is concatenated badly.
17
+ */
18
+ export declare function isolate(text: string, options?: IsolateOptions): string;
19
+ /** Options for {@link isolate}. */
20
+ export interface IsolateOptions {
21
+ dir?: AttributeDirection;
22
+ }
23
+ /** True when the string carries invisible bidi control characters. */
24
+ export declare function hasBidiControls(text: string): boolean;
25
+ /**
26
+ * Removes every invisible bidi control character.
27
+ *
28
+ * Use this on anything a stranger wrote. Overrides and isolates are the raw
29
+ * material of display-spoofing bugs — the class of attack that turned source
30
+ * code review into a guessing game — and a text field that passes them through
31
+ * to a terminal, a diff or a filename is a bug, not a feature.
32
+ */
33
+ export declare function stripBidiControls(text: string): string;
34
+ /**
35
+ * Rewrites text so each run is explicitly isolated, for plain-text output.
36
+ *
37
+ * Unlike {@link isolate}, which wraps the whole string, this keeps an English
38
+ * sentence readable by a terminal that only understands the bidi algorithm: the
39
+ * Arabic run gets an RLI/PDI pair and everything else is left alone.
40
+ */
41
+ export declare function isolateRunsText(text: string): string;
42
+ /** The invisible characters, exported so a UI can explain what it stripped. */
43
+ export declare const BIDI_CONTROL_CHARACTERS: readonly ["؜", "‎", "‏", "‪", "‫", "‬", "‭", "‮", "⁦", "⁧", "⁨", "⁩"];
@@ -0,0 +1,77 @@
1
+ import { segments } from "./segment.js";
2
+ /** Left-to-right isolate. */
3
+ export const LRI = "\u2066";
4
+ /** Right-to-left isolate. */
5
+ export const RLI = "\u2067";
6
+ /** First-strong isolate: the reader's bidi algorithm picks the direction. */
7
+ export const FSI = "\u2068";
8
+ /** Pop directional isolate. */
9
+ export const PDI = "\u2069";
10
+ /** Every character that can change the visual order without being visible. */
11
+ const BIDI_CONTROLS = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g;
12
+ /**
13
+ * Wraps text in an isolate, for plain-text contexts where an element is not an
14
+ * option: an `aria-label`, a canvas, a terminal, a spreadsheet cell, a JSON
15
+ * field that something else will render.
16
+ *
17
+ * In HTML, prefer {@link bdi} — an element is inspectable, stylable and cannot
18
+ * leak a stray `PDI` when a string is concatenated badly.
19
+ */
20
+ export function isolate(text, options = {}) {
21
+ if (text === "")
22
+ return "";
23
+ const dir = options.dir ?? "auto";
24
+ if (dir === "rtl")
25
+ return RLI + text + PDI;
26
+ if (dir === "ltr")
27
+ return LRI + text + PDI;
28
+ return FSI + text + PDI;
29
+ }
30
+ /** True when the string carries invisible bidi control characters. */
31
+ export function hasBidiControls(text) {
32
+ return /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/u.test(text);
33
+ }
34
+ /**
35
+ * Removes every invisible bidi control character.
36
+ *
37
+ * Use this on anything a stranger wrote. Overrides and isolates are the raw
38
+ * material of display-spoofing bugs — the class of attack that turned source
39
+ * code review into a guessing game — and a text field that passes them through
40
+ * to a terminal, a diff or a filename is a bug, not a feature.
41
+ */
42
+ export function stripBidiControls(text) {
43
+ return text.replace(BIDI_CONTROLS, "");
44
+ }
45
+ /**
46
+ * Rewrites text so each run is explicitly isolated, for plain-text output.
47
+ *
48
+ * Unlike {@link isolate}, which wraps the whole string, this keeps an English
49
+ * sentence readable by a terminal that only understands the bidi algorithm: the
50
+ * Arabic run gets an RLI/PDI pair and everything else is left alone.
51
+ */
52
+ export function isolateRunsText(text) {
53
+ return segments(text)
54
+ .map((segment) => {
55
+ if (segment.dir === "rtl")
56
+ return RLI + segment.text + PDI;
57
+ if (segment.dir === "ltr")
58
+ return LRI + segment.text + PDI;
59
+ return segment.text;
60
+ })
61
+ .join("");
62
+ }
63
+ /** The invisible characters, exported so a UI can explain what it stripped. */
64
+ export const BIDI_CONTROL_CHARACTERS = [
65
+ "\u061C",
66
+ "\u200E",
67
+ "\u200F",
68
+ "\u202A",
69
+ "\u202B",
70
+ "\u202C",
71
+ "\u202D",
72
+ "\u202E",
73
+ "\u2066",
74
+ "\u2067",
75
+ "\u2068",
76
+ "\u2069",
77
+ ];
@@ -0,0 +1,40 @@
1
+ import type { Direction, Segment } from "./types.js";
2
+ /** True when the code point belongs to a script written right to left. */
3
+ export declare function isRtlCodePoint(codePoint: number): boolean;
4
+ /** True when the string contains at least one right-to-left character. */
5
+ export declare function hasRtl(text: string): boolean;
6
+ /** True when the string contains Arabic letters, as opposed to just Arabic digits. */
7
+ export declare function hasArabic(text: string): boolean;
8
+ /**
9
+ * Splits text into runs that each have one direction.
10
+ *
11
+ * The browser implements the Unicode bidi algorithm correctly; what it cannot
12
+ * know is where the author meant a boundary to be. This answers that question,
13
+ * and nothing else:
14
+ *
15
+ * - a strong character starts a run and decides its direction;
16
+ * - Arabic digits and Arabic punctuation stay inside an Arabic run, so `مرحبا،`
17
+ * does not break in half;
18
+ * - Latin digits read left to right even inside Arabic, so `123.45%` stays one
19
+ * piece;
20
+ * - brackets, quotes and symbols are neutral: they take the direction of the
21
+ * runs on both sides when those agree, and otherwise the base direction — so
22
+ * an English full stop after an Arabic name ends the English sentence instead
23
+ * of moving to the wrong side of the name.
24
+ *
25
+ * Pass `base` when you know the paragraph direction — say, because the column
26
+ * is Arabic and this is one row of it. By default the base is the direction of
27
+ * the first strong character, which is what the browser would assume anyway.
28
+ */
29
+ export declare function segments(text: string, base?: "ltr" | "rtl"): Segment[];
30
+ /**
31
+ * The direction of the first strong character, which is what `dir="auto"`
32
+ * resolves to. `neutral` means the text has no strong character at all.
33
+ */
34
+ export declare function detectDirection(text: string): Direction;
35
+ /**
36
+ * Like {@link detectDirection}, but resolves `neutral` to `ltr` — the same
37
+ * fallback HTML uses for `dir="auto"`, so this is always safe to write to an
38
+ * attribute.
39
+ */
40
+ export declare function resolveDirection(text: string): "ltr" | "rtl";
@@ -0,0 +1,209 @@
1
+ const RTL_RANGES = [
2
+ [0x0590, 0x05ff], // Hebrew
3
+ [0x0600, 0x06ff], // Arabic
4
+ [0x0700, 0x074f], // Syriac
5
+ [0x0750, 0x077f], // Arabic Supplement
6
+ [0x0780, 0x07bf], // Thaana
7
+ [0x07c0, 0x07ff], // NKo
8
+ [0x0800, 0x083f], // Samaritan
9
+ [0x0840, 0x085f], // Mandaic
10
+ [0x0860, 0x086f], // Syriac Supplement
11
+ [0x0870, 0x08ff], // Arabic Extended-B and -A
12
+ [0xfb1d, 0xfb4f], // Hebrew presentation forms
13
+ [0xfb50, 0xfdff], // Arabic presentation forms A
14
+ [0xfe70, 0xfeff], // Arabic presentation forms B
15
+ [0x1e800, 0x1e8df], // Mende Kikakui
16
+ [0x1e900, 0x1e95f], // Adlam
17
+ [0x1ee00, 0x1eeff], // Arabic mathematical alphabetic symbols
18
+ ];
19
+ /** Arabic comma, semicolon, question mark, percent and the rest of the set. */
20
+ const ARABIC_PUNCTUATION = /[\u060C\u061B\u061F\u066A-\u066D\u06D4]/u;
21
+ const ARABIC_DIGITS = /[\u0660-\u0669\u06F0-\u06F9]/u;
22
+ const ANY_DIGIT = /\p{Nd}/u;
23
+ const MARK = /\p{M}/u;
24
+ const WHITESPACE_OR_FORMAT = /[\s\p{Z}\p{M}\p{Cf}]/u;
25
+ /** A neutral that joins a number when it sits between two digits: `1,000.5%`. */
26
+ const NUMERIC_JOINER = /[.,:+\-\u066B\u066C]/u;
27
+ /** A percent sign is part of the number it follows, not a sentence of its own. */
28
+ const NUMERIC_SUFFIX = /[%\u2030\u066A]/u;
29
+ /** True when the code point belongs to a script written right to left. */
30
+ export function isRtlCodePoint(codePoint) {
31
+ for (const [start, end] of RTL_RANGES) {
32
+ if (codePoint >= start && codePoint <= end)
33
+ return true;
34
+ }
35
+ return false;
36
+ }
37
+ /** True when the string contains at least one right-to-left character. */
38
+ export function hasRtl(text) {
39
+ for (const char of text) {
40
+ if (isRtlCodePoint(char.codePointAt(0) ?? 0))
41
+ return true;
42
+ }
43
+ return false;
44
+ }
45
+ /** True when the string contains Arabic letters, as opposed to just Arabic digits. */
46
+ export function hasArabic(text) {
47
+ for (const char of text) {
48
+ const codePoint = char.codePointAt(0) ?? 0;
49
+ const inArabicScript = (codePoint >= 0x0600 && codePoint <= 0x06ff) ||
50
+ (codePoint >= 0x0750 && codePoint <= 0x077f) ||
51
+ (codePoint >= 0xfb50 && codePoint <= 0xfdff) ||
52
+ (codePoint >= 0xfe70 && codePoint <= 0xfeff);
53
+ if (inArabicScript && /\p{L}/u.test(char))
54
+ return true;
55
+ }
56
+ return false;
57
+ }
58
+ function baseClass(char) {
59
+ if (char === "\u200f")
60
+ return "rtl";
61
+ if (char === "\u200e")
62
+ return "ltr";
63
+ if (ARABIC_DIGITS.test(char))
64
+ return "rtlWeak";
65
+ if (ANY_DIGIT.test(char))
66
+ return "ltrWeak";
67
+ if (MARK.test(char))
68
+ return "join";
69
+ if (WHITESPACE_OR_FORMAT.test(char))
70
+ return "join";
71
+ if (ARABIC_PUNCTUATION.test(char))
72
+ return "rtlWeak";
73
+ if (isRtlCodePoint(char.codePointAt(0) ?? 0))
74
+ return "rtl";
75
+ // Letters are what is left: a symbol or a bracket is neutral, a letter is not.
76
+ return /\p{L}/u.test(char) ? "ltr" : "neutral";
77
+ }
78
+ function classAt(chars, index) {
79
+ const char = chars[index];
80
+ const cls = baseClass(char);
81
+ if (cls !== "neutral")
82
+ return cls;
83
+ const previous = chars[index - 1];
84
+ const next = chars[index + 1];
85
+ const numeric = (digit) => digit === undefined || !ANY_DIGIT.test(digit)
86
+ ? null
87
+ : ARABIC_DIGITS.test(digit)
88
+ ? "rtlWeak"
89
+ : "ltrWeak";
90
+ const beforeIsDigit = numeric(previous);
91
+ if (beforeIsDigit === null)
92
+ return cls;
93
+ if (NUMERIC_SUFFIX.test(char))
94
+ return beforeIsDigit;
95
+ if (!NUMERIC_JOINER.test(char))
96
+ return cls;
97
+ return numeric(next) === null ? cls : beforeIsDigit;
98
+ }
99
+ /**
100
+ * Splits text into runs that each have one direction.
101
+ *
102
+ * The browser implements the Unicode bidi algorithm correctly; what it cannot
103
+ * know is where the author meant a boundary to be. This answers that question,
104
+ * and nothing else:
105
+ *
106
+ * - a strong character starts a run and decides its direction;
107
+ * - Arabic digits and Arabic punctuation stay inside an Arabic run, so `مرحبا،`
108
+ * does not break in half;
109
+ * - Latin digits read left to right even inside Arabic, so `123.45%` stays one
110
+ * piece;
111
+ * - brackets, quotes and symbols are neutral: they take the direction of the
112
+ * runs on both sides when those agree, and otherwise the base direction — so
113
+ * an English full stop after an Arabic name ends the English sentence instead
114
+ * of moving to the wrong side of the name.
115
+ *
116
+ * Pass `base` when you know the paragraph direction — say, because the column
117
+ * is Arabic and this is one row of it. By default the base is the direction of
118
+ * the first strong character, which is what the browser would assume anyway.
119
+ */
120
+ export function segments(text, base) {
121
+ const fallback = base ?? (detectDirection(text) === "rtl" ? "rtl" : "ltr");
122
+ const chars = Array.from(text);
123
+ const drafts = [];
124
+ let current = null;
125
+ let offset = 0;
126
+ for (let index = 0; index < chars.length; index += 1) {
127
+ const char = chars[index];
128
+ const start = offset;
129
+ const end = offset + char.length;
130
+ offset = end;
131
+ const cls = classAt(chars, index);
132
+ const dir = cls === "rtl" || cls === "rtlWeak" ? "rtl" : cls === "ltr" || cls === "ltrWeak" ? "ltr" : cls === "join" ? (current ? current.dir : "neutral") : "neutral";
133
+ if (current && current.dir === dir) {
134
+ current.text += char;
135
+ current.end = end;
136
+ continue;
137
+ }
138
+ if (current)
139
+ drafts.push(current);
140
+ current = { text: char, dir, start, end };
141
+ }
142
+ if (current)
143
+ drafts.push(current);
144
+ const resolved = resolveNeutrals(drafts, fallback);
145
+ return merge(resolved);
146
+ }
147
+ /** N1/N2 in miniature: a neutral takes the direction of agreeing neighbours, else the base. */
148
+ function resolveNeutrals(drafts, base) {
149
+ return drafts.map((draft, index) => {
150
+ if (draft.dir !== "neutral")
151
+ return draft;
152
+ const before = previousDirection(drafts, index);
153
+ const after = nextDirection(drafts, index);
154
+ const fallback = before !== "neutral" && before === after ? before : base;
155
+ return { ...draft, dir: fallback };
156
+ });
157
+ }
158
+ function previousDirection(drafts, index) {
159
+ for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
160
+ const draft = drafts[cursor];
161
+ if (draft && draft.dir !== "neutral")
162
+ return draft.dir;
163
+ }
164
+ return "neutral";
165
+ }
166
+ function nextDirection(drafts, index) {
167
+ for (let cursor = index + 1; cursor < drafts.length; cursor += 1) {
168
+ const draft = drafts[cursor];
169
+ if (draft && draft.dir !== "neutral")
170
+ return draft.dir;
171
+ }
172
+ return "neutral";
173
+ }
174
+ function merge(drafts) {
175
+ const merged = [];
176
+ for (const draft of drafts) {
177
+ const last = merged[merged.length - 1];
178
+ if (last && last.dir === draft.dir) {
179
+ last.text += draft.text;
180
+ last.end = draft.end;
181
+ continue;
182
+ }
183
+ merged.push({ text: draft.text, dir: draft.dir, start: draft.start, end: draft.end });
184
+ }
185
+ return merged;
186
+ }
187
+ /**
188
+ * The direction of the first strong character, which is what `dir="auto"`
189
+ * resolves to. `neutral` means the text has no strong character at all.
190
+ */
191
+ export function detectDirection(text) {
192
+ const chars = Array.from(text);
193
+ for (let index = 0; index < chars.length; index += 1) {
194
+ const cls = baseClass(chars[index]);
195
+ if (cls === "rtl" || cls === "rtlWeak")
196
+ return "rtl";
197
+ if (cls === "ltr" || cls === "ltrWeak")
198
+ return "ltr";
199
+ }
200
+ return "neutral";
201
+ }
202
+ /**
203
+ * Like {@link detectDirection}, but resolves `neutral` to `ltr` — the same
204
+ * fallback HTML uses for `dir="auto"`, so this is always safe to write to an
205
+ * attribute.
206
+ */
207
+ export function resolveDirection(text) {
208
+ return detectDirection(text) === "rtl" ? "rtl" : "ltr";
209
+ }