bidi-kit 0.0.0-stage → 0.1.1

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,68 @@
1
+ const RULES = [
2
+ {
3
+ id: "bidi-control-character",
4
+ severity: "error",
5
+ pattern: /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu,
6
+ message: "Invisible bidi control character. It reorders text without showing why; strip it from anything a stranger wrote.",
7
+ },
8
+ {
9
+ id: "inline-direction-without-isolation",
10
+ severity: "warning",
11
+ pattern: /<span[^>]*\bdir=/giu,
12
+ message: "<span dir=...> does not isolate. Use <bdi>, or add unicode-bidi: isolate to the rule.",
13
+ },
14
+ {
15
+ id: "physical-text-align",
16
+ severity: "warning",
17
+ pattern: /text-align\s*:\s*(left|right)\b/giu,
18
+ message: "text-align: left/right is physical. Use start/end so Arabic paragraphs align correctly.",
19
+ },
20
+ {
21
+ id: "physical-css-property",
22
+ severity: "warning",
23
+ pattern: /\b(padding|margin|border)-(left|right)\b/giu,
24
+ message: "Logical properties (padding-inline-start, margin-inline-end, border-inline-start) mirror with direction.",
25
+ },
26
+ {
27
+ id: "document-without-lang",
28
+ severity: "warning",
29
+ pattern: /<html(?![^>]*\blang=)[^>]*>/giu,
30
+ message: "<html> has no lang. Screen readers pick a voice from it, and Arabic is unreadable in an English voice.",
31
+ },
32
+ ];
33
+ /**
34
+ * Reports the markers that predict a bidi bug, for a string of HTML or CSS.
35
+ *
36
+ * This is a lint, not a proof: it finds patterns that are almost always wrong
37
+ * and never claims a document that passes is correct. It is meant for a CI step
38
+ * on content, and for the moment a translator asks why their paragraph is
39
+ * backwards.
40
+ */
41
+ export function audit(source) {
42
+ const issues = [];
43
+ for (const rule of RULES) {
44
+ rule.pattern.lastIndex = 0;
45
+ for (const match of source.matchAll(rule.pattern)) {
46
+ const index = match.index ?? 0;
47
+ issues.push({
48
+ rule: rule.id,
49
+ severity: rule.severity,
50
+ message: rule.message,
51
+ index,
52
+ snippet: source.slice(index, index + 40),
53
+ });
54
+ }
55
+ }
56
+ return issues.sort((a, b) => a.index - b.index);
57
+ }
58
+ /** Formats {@link audit} output as one line per finding, for a terminal. */
59
+ export function formatAudit(issues, file) {
60
+ if (issues.length === 0)
61
+ return "no bidi issues found";
62
+ return issues
63
+ .map((issue) => {
64
+ const where = file ? `${file}: ` : "";
65
+ return `${where}[${issue.severity}] ${issue.rule} at ${issue.index}: ${issue.message}`;
66
+ })
67
+ .join("\n");
68
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The rules that keep mixed-script text from breaking, as a string you can
3
+ * drop in a `<style>` tag or a stylesheet.
4
+ *
5
+ * Every line here fixes a specific, reproducible glitch:
6
+ *
7
+ * - `unicode-bidi: isolate` stops an inline element's direction from leaking
8
+ * into its neighbours;
9
+ * - `text-align: start` makes alignment follow the text instead of the page —
10
+ * `left` is a bug the moment one paragraph is Arabic;
11
+ * - the line-height on Arabic blocks is not aesthetics: naskh faces put marks
12
+ * above and below the baseline, and a 1.2 line-height cuts them off;
13
+ * - `white-space: normal` (and no `text-overflow: ellipsis` on RTL) keeps a
14
+ * wrapped Arabic sentence from being reordered across lines.
15
+ */
16
+ export declare const CSS: string;
17
+ /**
18
+ * Rules to add once, on `html` or `body`, when a page mixes scripts and wants
19
+ * the browser to stop guessing.
20
+ */
21
+ export declare const ROOT_CSS = "html { unicode-bidi: plaintext; }\nbody { text-align: start; }\n:lang(ar) { font-variant-numeric: normal; }\n";
22
+ /** A single declaration block for one element, for inline-style applications. */
23
+ export declare function inlineStyle(options?: {
24
+ dir?: "ltr" | "rtl" | "auto";
25
+ script?: "arabic" | "hebrew" | "latin";
26
+ }): string;
@@ -0,0 +1,55 @@
1
+ import { ARABIC_FEATURES, FONT_STACKS } from "./fonts.js";
2
+ /**
3
+ * The rules that keep mixed-script text from breaking, as a string you can
4
+ * drop in a `<style>` tag or a stylesheet.
5
+ *
6
+ * Every line here fixes a specific, reproducible glitch:
7
+ *
8
+ * - `unicode-bidi: isolate` stops an inline element's direction from leaking
9
+ * into its neighbours;
10
+ * - `text-align: start` makes alignment follow the text instead of the page —
11
+ * `left` is a bug the moment one paragraph is Arabic;
12
+ * - the line-height on Arabic blocks is not aesthetics: naskh faces put marks
13
+ * above and below the baseline, and a 1.2 line-height cuts them off;
14
+ * - `white-space: normal` (and no `text-overflow: ellipsis` on RTL) keeps a
15
+ * wrapped Arabic sentence from being reordered across lines.
16
+ */
17
+ export const CSS = `:where([dir], [lang]):not(html, body) { unicode-bidi: isolate; }
18
+ [dir="rtl"] { text-align: right; direction: rtl; }
19
+ [dir="ltr"] { text-align: left; direction: ltr; }
20
+ [dir="auto"] { text-align: start; }
21
+ :where([lang^="ar"], [lang^="fa"], [lang^="ur"], [lang^="ps"], .script-arabic) {
22
+ font-family: ${FONT_STACKS.arabic};
23
+ font-feature-settings: ${ARABIC_FEATURES};
24
+ line-height: 1.9;
25
+ }
26
+ :where([lang^="he"], [lang^="yi"], .script-hebrew) {
27
+ font-family: ${FONT_STACKS.hebrew};
28
+ line-height: 1.7;
29
+ }
30
+ :where(bdi, [dir="auto"]) { unicode-bidi: isolate; }
31
+ `;
32
+ /**
33
+ * Rules to add once, on `html` or `body`, when a page mixes scripts and wants
34
+ * the browser to stop guessing.
35
+ */
36
+ export const ROOT_CSS = `html { unicode-bidi: plaintext; }
37
+ body { text-align: start; }
38
+ :lang(ar) { font-variant-numeric: normal; }
39
+ `;
40
+ /** A single declaration block for one element, for inline-style applications. */
41
+ export function inlineStyle(options = {}) {
42
+ const declarations = [];
43
+ if (options.dir) {
44
+ declarations.push(`direction: ${options.dir === "auto" ? "inherit" : options.dir}`);
45
+ declarations.push("unicode-bidi: isolate");
46
+ }
47
+ if (options.script) {
48
+ declarations.push(`font-family: ${FONT_STACKS[options.script]}`);
49
+ if (options.script === "arabic") {
50
+ declarations.push(`font-feature-settings: ${ARABIC_FEATURES}`);
51
+ declarations.push("line-height: 1.9");
52
+ }
53
+ }
54
+ return declarations.join("; ");
55
+ }
@@ -0,0 +1,36 @@
1
+ import type { FontFaceOptions, Script } from "./types.js";
2
+ /**
3
+ * Font stacks per script.
4
+ *
5
+ * Two failures produce the "broken Arabic" look people blame on bidi:
6
+ *
7
+ * 1. the Latin face has no Arabic glyphs, so the browser falls back per glyph —
8
+ * the word changes shape halfway through and the diacritics sit too low;
9
+ * 2. the Arabic face is a *naskh* text face rendered at a Latin line-height,
10
+ * and the kasra, the hamza below and the tail of a final yeh are clipped.
11
+ *
12
+ * The stacks below put a known-good Arabic face first, keep a Latin face that
13
+ * does not interfere, and end in `sans-serif` rather than in nothing.
14
+ */
15
+ export declare const FONT_STACKS: Readonly<Record<Script, string>>;
16
+ /** The stack to use for a locale tag; anything not RTL gets the Latin stack. */
17
+ export declare function fontStack(locale?: string): string;
18
+ /** The `font-feature-settings` that keep Arabic words from looking two-tone. */
19
+ export declare const ARABIC_FEATURES = "\"kern\" 1, \"liga\" 1, \"calt\" 1, \"rlig\" 1, \"init\" 1, \"medi\" 1, \"fina\" 1";
20
+ /**
21
+ * The `unicode-range` for a script, so a downloaded face is only fetched for
22
+ * the characters it actually covers. Without it, a page with one Arabic
23
+ * headline downloads the Arabic font for every reader.
24
+ */
25
+ export declare const UNICODE_RANGES: Readonly<Record<Script, string>>;
26
+ /**
27
+ * Builds an `@font-face` rule.
28
+ *
29
+ * It is deliberately a string and not a file: the package ships no fonts, so a
30
+ * consumer decides where the bytes come from — a local install, a CDN, or a
31
+ * self-hosted file — and this only removes the chance of getting the
32
+ * `unicode-range` and the metrics wrong while doing it.
33
+ */
34
+ export declare function fontFace(options: FontFaceOptions): string;
35
+ /** A `font-family` declaration that pairs an Arabic face with a Latin one. */
36
+ export declare function fontFamilyRule(selector: string, script?: Script): string;
@@ -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";