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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nour Yahyaoui
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,289 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # bidi-kit
2
+
3
+ Arabic words inside English sentences, French sentences inside Arabic paragraphs — with the
4
+ punctuation, numbers, quotation marks and fonts that go with them.
5
+
6
+ ```ts
7
+ import { paragraph } from "bidi-kit";
8
+
9
+ const html = paragraph(
10
+ ["The greeting is ", { text: "مرحبا", dir: "rtl", lang: "ar" }, "."],
11
+ { lang: "en" },
12
+ );
13
+ // <p dir="ltr" lang="en">The greeting is <bdi dir="rtl" lang="ar">مرحبا</bdi>.</p>
14
+ ```
15
+
16
+ Zero dependencies. No fonts bundled. TypeScript types, ESM and CommonJS. Runs in the browser,
17
+ in Node, in an edge worker; nothing in `dist` imports `node:`.
18
+
19
+ ## What it fixes
20
+
21
+ | Symptom | Cause | What bidi-kit does |
22
+ | --- | --- | --- |
23
+ | The full stop after an Arabic name renders on the wrong side | The stop is neutral, so it is absorbed into the Arabic run | `paragraph()` ends the run at the stop and isolates the Arabic |
24
+ | `+216 71 123 456` gets split and reordered inside Arabic | Digits are weak characters with no direction of their own | `segments()` keeps a number with its own punctuation as one left-to-right run |
25
+ | A French quotation inside an Arabic paragraph reads backwards | The quotation inherits the paragraph's direction | The run is isolated with `dir="ltr"`, or wrapped in `<bdi>` |
26
+ | Diacritics are clipped, or one word is rendered in two different faces | The Latin face has no Arabic glyphs, and the line-height is set for Latin | A system Arabic stack with raised line-height, from `FONT_STACKS` and `CSS` |
27
+ | `dir="auto"` guesses wrong on a number-led string | First-strong detection is a heuristic | `detectDirection()` is explicit, and testable |
28
+ | An invisible `U+202E` renames a file or a field | Bidi control characters are invisible by design | `stripBidiControls()` removes them; `audit()` reports them as errors |
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ npm install bidi-kit
34
+ ```
35
+
36
+ Node 18 or newer for the CLI; the library itself has no engine requirement beyond ES2022.
37
+
38
+ ## The four things you will actually call
39
+
40
+ ### 1. `paragraph(parts, options)` — a paragraph built out of mixed runs
41
+
42
+ ```ts
43
+ import { paragraph, FONT_STACKS } from "bidi-kit";
44
+
45
+ const html = paragraph(
46
+ [
47
+ { text: "قال المدير:", dir: "rtl", lang: "ar" },
48
+ " ",
49
+ { text: "« Bonjour à tous »", dir: "ltr", lang: "fr", font: FONT_STACKS.latin },
50
+ " ",
51
+ { text: "ثم غادر.", dir: "rtl", lang: "ar", font: FONT_STACKS.arabic },
52
+ ],
53
+ { lang: "ar" },
54
+ );
55
+ ```
56
+
57
+ Each named part becomes a `<bdi>` with its own `dir`, `lang` and, if you pass one, font. Strings
58
+ are escaped; pass `{ html: true }` only for markup you have already sanitised.
59
+
60
+ ### 2. `segments(text, base?)` — where the runs are
61
+
62
+ ```ts
63
+ import { segments } from "bidi-kit";
64
+
65
+ segments("Write to أحمد.");
66
+ // [ { text: "Write to ", dir: "ltr", start: 0, end: 9 },
67
+ // { text: "أحمد", dir: "rtl", start: 9, end: 13 },
68
+ // { text: ".", dir: "ltr", start: 13, end: 14 } ]
69
+ ```
70
+
71
+ `base` is the paragraph direction. Omit it and the first strong character decides, which is what
72
+ the browser would assume anyway.
73
+
74
+ ### 3. `bdi(text, options)` and `apply(el, text)` — the small ones
75
+
76
+ ```ts
77
+ import { bdi, apply } from "bidi-kit";
78
+
79
+ bdi("أحمد", { lang: "ar" }); // <bdi lang="ar">أحمد</bdi>
80
+ apply(document.querySelector("#name"), "أحمد"); // textContent + dir="rtl"
81
+ ```
82
+
83
+ ### 4. `CSS` and `ROOT_CSS` — the rules that stop it happening again
84
+
85
+ ```ts
86
+ import { CSS, ROOT_CSS, ARABIC_FEATURES } from "bidi-kit";
87
+
88
+ const style = document.createElement("style");
89
+ style.textContent = CSS + ROOT_CSS;
90
+ document.head.append(style);
91
+ ```
92
+
93
+ `CSS` isolates every `[dir]`/`[lang]` element, aligns by direction rather than by side, gives
94
+ Arabic blocks a line-height that leaves room for the marks, and switches `[lang^="ar"]` to a face
95
+ that has the glyphs. `ROOT_CSS` puts `unicode-bidi: plaintext` on `html`, so a page that forgets
96
+ `dir` on one container still behaves.
97
+
98
+ ## API
99
+
100
+ ### Direction
101
+
102
+ | Function | Returns | Notes |
103
+ | --- | --- | --- |
104
+ | `detectDirection(text)` | `"ltr" \| "rtl" \| "neutral"` | First strong character, exactly what `dir="auto"` means |
105
+ | `resolveDirection(text)` | `"ltr" \| "rtl"` | Never neutral; safe to write to an attribute |
106
+ | `hasRtl(text)` | `boolean` | Any character of an RTL script |
107
+ | `hasArabic(text)` | `boolean` | Arabic *letters*; Arabic-Indic digits do not count |
108
+ | `isRtlCodePoint(cp)` | `boolean` | Script table, `U+0590`–`U+08FF` and the presentational blocks |
109
+
110
+ ### Runs
111
+
112
+ `segments(text, base?)` returns `{ text, dir, start, end }[]`, with `start`/`end` as UTF-16
113
+ indices into the original string.
114
+
115
+ The rules, in one place:
116
+
117
+ - a strong character starts a run and decides its direction;
118
+ - Arabic-Indic digits and Arabic punctuation (`,`, `;`, `?`, `%`) stay inside an Arabic run, so
119
+ `مرحبا،` does not break in half;
120
+ - Latin digits read left to right even inside Arabic, and `.` `,` `+` `-` `%` travel with the
121
+ number they belong to, so `1,248.50%` stays one run;
122
+ - brackets, quotes and symbols are neutral: they take the direction of the runs on both sides
123
+ when those agree, and otherwise the base direction — which is why an English full stop after
124
+ an Arabic name stays in the English sentence;
125
+ - combining marks and invisible controls never split a run.
126
+
127
+ ### Plain text
128
+
129
+ | Function | Use |
130
+ | --- | --- |
131
+ | `isolate(text, { dir })` | `FSI…PDI` (or `RLI`/`LRI`) around the whole string, for `aria-label`, canvas, terminals, CSV |
132
+ | `isolateRunsText(text)` | Every run isolated individually, for plain-text output |
133
+ | `stripBidiControls(text)` | Removes `U+061C`, `U+200E`, `U+200F`, `U+202A`–`U+202E`, `U+2066`–`U+2069` |
134
+ | `hasBidiControls(text)` | True when any of the above is present |
135
+ | `LRI`, `RLI`, `FSI`, `PDI`, `BIDI_CONTROL_CHARACTERS` | The constants, exported |
136
+
137
+ ### HTML
138
+
139
+ | Function | Emits |
140
+ | --- | --- |
141
+ | `bdi(text, opts)` | `<bdi>` with optional `dir`, `lang`, `class`, inline `font-family` |
142
+ | `inline(text, opts)` | `<span dir="auto">`; pass `element: "bdi"` for the other one |
143
+ | `paragraph(parts, opts)` | `<p>` with a resolved `dir`, `lang`, and one `<bdi>` per named part |
144
+ | `escapeHtml(text)` | Escapes `& < > " '` |
145
+ | `apply(el, text, opts)` | Sets `textContent` and `dir` on an element-shaped object |
146
+
147
+ `inline` and `bdi` never trust their input; `paragraph` escapes strings unless `{ html: true }`.
148
+
149
+ ### Fonts
150
+
151
+ | Export | What it is |
152
+ | --- | --- |
153
+ | `FONT_STACKS` | `arabic`, `hebrew`, `latin` stacks made of system faces |
154
+ | `fontStack(locale)` | Stack for a BCP-47 tag; `ar`, `fa`, `ur`, `ps` get Arabic |
155
+ | `ARABIC_FEATURES` | `"kern" 1, "liga" 1, "calt" 1, "rlig" 1, "init" 1, "medi" 1, "fina" 1` |
156
+ | `UNICODE_RANGES` | `unicode-range` per script, so a downloaded face is fetched only when needed |
157
+ | `fontFace(opts)` | An `@font-face` block with the range, weight and `font-display` filled in |
158
+ | `fontFamilyRule(selector, script)` | A one-line declaration block |
159
+
160
+ The Arabic stack is `"Noto Naskh Arabic", "Noto Sans Arabic", "Amiri", "Scheherazade New",
161
+ "Geeza Pro", "Segoe UI", "Noto Sans", sans-serif`. It starts with a naskh text face because that
162
+ is what Arabic prose is set in — and because a face without the glyphs makes the browser fall back
163
+ per glyph, which is what "one word, two fonts" looks like.
164
+
165
+ ### Audit
166
+
167
+ ```ts
168
+ import { audit, formatAudit } from "bidi-kit";
169
+
170
+ audit('<span dir="rtl">مرحبا</span>');
171
+ // [{ rule: "inline-direction-without-isolation", severity: "warning", index: 0, … }]
172
+ ```
173
+
174
+ Rules: `bidi-control-character` (error), `inline-direction-without-isolation`,
175
+ `physical-text-align`, `physical-css-property`, `document-without-lang`. It is a lint, not a
176
+ proof.
177
+
178
+ ## CLI
179
+
180
+ ```bash
181
+ npx bidi-kit check page.html # exits 1 when a bidi control character is found
182
+ npx bidi-kit runs note.txt # prints each run and its direction
183
+ npx bidi-kit isolate note.txt
184
+ npx bidi-kit dir article.txt
185
+ ```
186
+
187
+ With no file, every command reads standard input:
188
+
189
+ ```bash
190
+ printf 'مرحبا، هذا نص.' | npx bidi-kit dir
191
+ ```
192
+
193
+ None of these examples carry trailing comments, deliberately: `cmd.exe` on Windows would pass the
194
+ `#` and the words after it to the command as arguments.
195
+
196
+ ## Why not just `dir="rtl"`?
197
+
198
+ Because a paragraph is not one direction. `dir` sets the base direction of the *block*, and the
199
+ Unicode bidi algorithm then decides the order of everything inside it — invisibly, per character,
200
+ using rules that are right in isolation and surprising in bulk. The two things the algorithm cannot
201
+ know are:
202
+
203
+ 1. **Where the author meant a boundary.** Punctuation and digits are neutral; their direction is
204
+ inherited. That is why a full stop after an Arabic name lands on the wrong side, and why a phone
205
+ number inside Arabic gets chopped into pieces that reassemble in the wrong order.
206
+ 2. **Which script owns a stray character.** `(`, `"`, `«` and `-` are shared, and mirroring only
207
+ works when the pairing is inside the same directional run.
208
+
209
+ An isolate (`<bdi>`, `U+2066`–`U+2069`) tells the algorithm "this is a complete unit, resolve it
210
+ internally" — which fixes both, provided the unit boundaries are right. That is the whole job of
211
+ this package: finding the boundaries, then using the mechanism the standard already has.
212
+
213
+ The old answer was `RLE … PDF` and `LRE … PDF`. Those are *embeddings*, which leak the surrounding
214
+ direction into the run and are deprecated in CSS for exactly that reason. bidi-kit never emits them.
215
+
216
+ ## Security: the invisible characters
217
+
218
+ Overrides and isolates are the raw material of display spoofing: `U+202E` reverses everything after
219
+ it, so `invoice\u202Efdp.exe` is displayed as `invoiceexe.pdf`. The same trick hides text in a code
220
+ review, a pull request diff, a filename, or a form field.
221
+
222
+ ```ts
223
+ import { stripBidiControls, audit } from "bidi-kit";
224
+
225
+ const safe = stripBidiControls(untrusted); // before storing, logging or rendering
226
+ audit(untrusted); // reports it as an error instead
227
+ ```
228
+
229
+ `stripBidiControls` removes `U+061C`, `U+200E`, `U+200F`, `U+202A`–`U+202E` and `U+2066`–`U+2069`
230
+ and touches nothing else.
231
+
232
+ ## What it does not do
233
+
234
+ - **It does not implement the Unicode bidi algorithm.** Browsers do that correctly; a second
235
+ implementation would only disagree with them. bidi-kit works out boundaries and isolation.
236
+ - **It does not shape Arabic**, and it does not join letters. That is the renderer's job.
237
+ - **It does not ship fonts.** `fontFace()` writes the rule; you choose the bytes, so the licence
238
+ and the subsetting stay your decision.
239
+ - **It does not do line breaking.** A wrapped RTL paragraph is still the browser's business;
240
+ the `unicode-bidi: plaintext` in `ROOT_CSS` is the only help that is safe to give.
241
+
242
+ ## Demo
243
+
244
+ ```bash
245
+ npm run build
246
+ npm run demo
247
+ ```
248
+
249
+ The demo is served on <http://localhost:4173>. `npm run demo` builds first if `dist` is missing.
250
+
251
+ The demo page shows five side-by-side comparisons — naive `textContent` versus bidi-kit — for an
252
+ English sentence ending in Arabic, an Arabic paragraph quoting French, numbers and an email in
253
+ Arabic, a French paragraph with an Arabic name, and Arabic with full tashkeel. Below them is a
254
+ playground that runs the real library on your own text and prints the runs it found.
255
+
256
+ ## Tests
257
+
258
+ ```bash
259
+ npm ci
260
+ npm test
261
+ npm run pack:check
262
+ ```
263
+
264
+ `npm test` builds ESM and CJS, then runs `node --test`. `npm run pack:check` builds and then asserts
265
+ what `npm publish` would upload — both module formats, the declarations, the CLI, the README and the
266
+ licence in; the sources and dependencies out.
267
+
268
+ 44 tests covering run boundaries, punctuation at every kind of edge, phone numbers, URLs, emails,
269
+ hashtags, guillemets, combining marks, base direction, isolates, control-character stripping, the
270
+ HTML builders, the font and CSS tokens, the audit rules, ESM/CJS parity, the absence of `node:`
271
+ imports in the browser build, and the demo server (page, both builds, and refusal to serve a path
272
+ outside the package). CI runs the same suite on Windows.
273
+
274
+ ## Windows
275
+
276
+ Everything here runs on Windows, and CI proves it on every push (the `bidi-kit on Windows` job):
277
+
278
+ - the build invokes `node_modules/typescript/bin/tsc` with the current Node binary, never the
279
+ `.bin/tsc` shim, which is a `.cmd` file on Windows and cannot be spawned directly;
280
+ - test discovery passes a glob to `node --test`, which expands it itself, so it does not depend on
281
+ the shell;
282
+ - `npm run pack:check` is a script, not a shell one-liner.
283
+
284
+ One thing to watch: `cmd.exe` has no inline comments. `npm publish # ready` sends `#` and `ready` to
285
+ npm as a tag, and npm will refuse. Copy the commands without the annotations.
286
+
287
+ ## Licence
288
+
289
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * bidi-kit on the command line.
4
+ *
5
+ * The three things that are hard to see in a browser — which run is which
6
+ * direction, what an invisible control character is doing, and whether a
7
+ * template has a physical `text-align` — are all easy to print in a terminal.
8
+ */
9
+ import { readFile } from "node:fs/promises";
10
+ import { existsSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ const entry = join(dirname(fileURLToPath(import.meta.url)), "..", "dist", "esm", "index.js");
15
+ if (!existsSync(entry)) {
16
+ console.error("bidi-kit is not built: run `npm run build` first.");
17
+ process.exit(2);
18
+ }
19
+ const { audit, formatAudit, segments, isolateRunsText, resolveDirection } = await import(entry);
20
+
21
+ const USAGE = `bidi-kit — mixed-direction text, checked from the terminal
22
+
23
+ Usage
24
+ bidi-kit check <file...> report bidi hazards in HTML or CSS (exit 1 on errors)
25
+ bidi-kit runs <file> print each run with its direction
26
+ bidi-kit isolate <file> print the text with every run isolated
27
+ bidi-kit dir <file> print the resolved paragraph direction
28
+
29
+ Use - to read stdin. With no file, stdin is read.`;
30
+
31
+ const [, , command = "check", ...rest] = process.argv;
32
+
33
+ async function readInputs(files) {
34
+ if (files.length === 0 || files.includes("-")) {
35
+ const chunks = [];
36
+ for await (const chunk of process.stdin) chunks.push(chunk);
37
+ return [{ name: "<stdin>", text: Buffer.concat(chunks).toString("utf8") }];
38
+ }
39
+ return Promise.all(
40
+ files.map(async (file) => ({ name: file, text: await readFile(file, "utf8") })),
41
+ );
42
+ }
43
+
44
+ if (command === "--help" || command === "-h" || command === "help") {
45
+ console.log(USAGE);
46
+ process.exit(0);
47
+ }
48
+
49
+ if (!["check", "runs", "isolate", "dir"].includes(command)) {
50
+ console.error(`unknown command: ${command}\n\n${USAGE}`);
51
+ process.exit(2);
52
+ }
53
+
54
+ const inputs = await readInputs(rest);
55
+ let failed = false;
56
+
57
+ for (const { name, text } of inputs) {
58
+ if (command === "check") {
59
+ const issues = audit(text);
60
+ if (issues.length === 0) continue;
61
+ console.log(formatAudit(issues, name === "<stdin>" ? undefined : name));
62
+ if (issues.some((issue) => issue.severity === "error")) failed = true;
63
+ }
64
+ if (command === "runs") {
65
+ for (const run of segments(text)) {
66
+ console.log(`${run.dir.padEnd(4)} ${String(run.start).padStart(4)} ${JSON.stringify(run.text)}`);
67
+ }
68
+ }
69
+ if (command === "isolate") {
70
+ console.log(isolateRunsText(text));
71
+ }
72
+ if (command === "dir") {
73
+ console.log(resolveDirection(text));
74
+ }
75
+ }
76
+
77
+ process.exit(failed ? 1 : 0);
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.audit = audit;
4
+ exports.formatAudit = formatAudit;
5
+ const RULES = [
6
+ {
7
+ id: "bidi-control-character",
8
+ severity: "error",
9
+ pattern: /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu,
10
+ message: "Invisible bidi control character. It reorders text without showing why; strip it from anything a stranger wrote.",
11
+ },
12
+ {
13
+ id: "inline-direction-without-isolation",
14
+ severity: "warning",
15
+ pattern: /<span[^>]*\bdir=/giu,
16
+ message: "<span dir=...> does not isolate. Use <bdi>, or add unicode-bidi: isolate to the rule.",
17
+ },
18
+ {
19
+ id: "physical-text-align",
20
+ severity: "warning",
21
+ pattern: /text-align\s*:\s*(left|right)\b/giu,
22
+ message: "text-align: left/right is physical. Use start/end so Arabic paragraphs align correctly.",
23
+ },
24
+ {
25
+ id: "physical-css-property",
26
+ severity: "warning",
27
+ pattern: /\b(padding|margin|border)-(left|right)\b/giu,
28
+ message: "Logical properties (padding-inline-start, margin-inline-end, border-inline-start) mirror with direction.",
29
+ },
30
+ {
31
+ id: "document-without-lang",
32
+ severity: "warning",
33
+ pattern: /<html(?![^>]*\blang=)[^>]*>/giu,
34
+ message: "<html> has no lang. Screen readers pick a voice from it, and Arabic is unreadable in an English voice.",
35
+ },
36
+ ];
37
+ /**
38
+ * Reports the markers that predict a bidi bug, for a string of HTML or CSS.
39
+ *
40
+ * This is a lint, not a proof: it finds patterns that are almost always wrong
41
+ * and never claims a document that passes is correct. It is meant for a CI step
42
+ * on content, and for the moment a translator asks why their paragraph is
43
+ * backwards.
44
+ */
45
+ function audit(source) {
46
+ const issues = [];
47
+ for (const rule of RULES) {
48
+ rule.pattern.lastIndex = 0;
49
+ for (const match of source.matchAll(rule.pattern)) {
50
+ const index = match.index ?? 0;
51
+ issues.push({
52
+ rule: rule.id,
53
+ severity: rule.severity,
54
+ message: rule.message,
55
+ index,
56
+ snippet: source.slice(index, index + 40),
57
+ });
58
+ }
59
+ }
60
+ return issues.sort((a, b) => a.index - b.index);
61
+ }
62
+ /** Formats {@link audit} output as one line per finding, for a terminal. */
63
+ function formatAudit(issues, file) {
64
+ if (issues.length === 0)
65
+ return "no bidi issues found";
66
+ return issues
67
+ .map((issue) => {
68
+ const where = file ? `${file}: ` : "";
69
+ return `${where}[${issue.severity}] ${issue.rule} at ${issue.index}: ${issue.message}`;
70
+ })
71
+ .join("\n");
72
+ }
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ROOT_CSS = exports.CSS = void 0;
4
+ exports.inlineStyle = inlineStyle;
5
+ const fonts_js_1 = require("./fonts.js");
6
+ /**
7
+ * The rules that keep mixed-script text from breaking, as a string you can
8
+ * drop in a `<style>` tag or a stylesheet.
9
+ *
10
+ * Every line here fixes a specific, reproducible glitch:
11
+ *
12
+ * - `unicode-bidi: isolate` stops an inline element's direction from leaking
13
+ * into its neighbours;
14
+ * - `text-align: start` makes alignment follow the text instead of the page —
15
+ * `left` is a bug the moment one paragraph is Arabic;
16
+ * - the line-height on Arabic blocks is not aesthetics: naskh faces put marks
17
+ * above and below the baseline, and a 1.2 line-height cuts them off;
18
+ * - `white-space: normal` (and no `text-overflow: ellipsis` on RTL) keeps a
19
+ * wrapped Arabic sentence from being reordered across lines.
20
+ */
21
+ exports.CSS = `:where([dir], [lang]):not(html, body) { unicode-bidi: isolate; }
22
+ [dir="rtl"] { text-align: right; direction: rtl; }
23
+ [dir="ltr"] { text-align: left; direction: ltr; }
24
+ [dir="auto"] { text-align: start; }
25
+ :where([lang^="ar"], [lang^="fa"], [lang^="ur"], [lang^="ps"], .script-arabic) {
26
+ font-family: ${fonts_js_1.FONT_STACKS.arabic};
27
+ font-feature-settings: ${fonts_js_1.ARABIC_FEATURES};
28
+ line-height: 1.9;
29
+ }
30
+ :where([lang^="he"], [lang^="yi"], .script-hebrew) {
31
+ font-family: ${fonts_js_1.FONT_STACKS.hebrew};
32
+ line-height: 1.7;
33
+ }
34
+ :where(bdi, [dir="auto"]) { unicode-bidi: isolate; }
35
+ `;
36
+ /**
37
+ * Rules to add once, on `html` or `body`, when a page mixes scripts and wants
38
+ * the browser to stop guessing.
39
+ */
40
+ exports.ROOT_CSS = `html { unicode-bidi: plaintext; }
41
+ body { text-align: start; }
42
+ :lang(ar) { font-variant-numeric: normal; }
43
+ `;
44
+ /** A single declaration block for one element, for inline-style applications. */
45
+ function inlineStyle(options = {}) {
46
+ const declarations = [];
47
+ if (options.dir) {
48
+ declarations.push(`direction: ${options.dir === "auto" ? "inherit" : options.dir}`);
49
+ declarations.push("unicode-bidi: isolate");
50
+ }
51
+ if (options.script) {
52
+ declarations.push(`font-family: ${fonts_js_1.FONT_STACKS[options.script]}`);
53
+ if (options.script === "arabic") {
54
+ declarations.push(`font-feature-settings: ${fonts_js_1.ARABIC_FEATURES}`);
55
+ declarations.push("line-height: 1.9");
56
+ }
57
+ }
58
+ return declarations.join("; ");
59
+ }
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UNICODE_RANGES = exports.ARABIC_FEATURES = exports.FONT_STACKS = void 0;
4
+ exports.fontStack = fontStack;
5
+ exports.fontFace = fontFace;
6
+ exports.fontFamilyRule = fontFamilyRule;
7
+ /**
8
+ * Font stacks per script.
9
+ *
10
+ * Two failures produce the "broken Arabic" look people blame on bidi:
11
+ *
12
+ * 1. the Latin face has no Arabic glyphs, so the browser falls back per glyph —
13
+ * the word changes shape halfway through and the diacritics sit too low;
14
+ * 2. the Arabic face is a *naskh* text face rendered at a Latin line-height,
15
+ * and the kasra, the hamza below and the tail of a final yeh are clipped.
16
+ *
17
+ * The stacks below put a known-good Arabic face first, keep a Latin face that
18
+ * does not interfere, and end in `sans-serif` rather than in nothing.
19
+ */
20
+ exports.FONT_STACKS = {
21
+ arabic: [
22
+ '"Noto Naskh Arabic"',
23
+ '"Noto Sans Arabic"',
24
+ '"Amiri"',
25
+ '"Scheherazade New"',
26
+ '"Geeza Pro"',
27
+ '"Segoe UI"',
28
+ '"Noto Sans"',
29
+ "sans-serif",
30
+ ].join(", "),
31
+ hebrew: ['"Noto Sans Hebrew"', '"Arial Hebrew"', '"Gisha"', '"David CLM"', "sans-serif"].join(", "),
32
+ latin: ['"Noto Sans"', "system-ui", "-apple-system", '"Segoe UI"', "Roboto", "sans-serif"].join(", "),
33
+ };
34
+ /** The stack to use for a locale tag; anything not RTL gets the Latin stack. */
35
+ function fontStack(locale) {
36
+ if (!locale)
37
+ return exports.FONT_STACKS.latin;
38
+ const language = locale.toLowerCase().split(/[-_]/)[0] ?? "";
39
+ if (language === "ar" || language === "fa" || language === "ur" || language === "ps") {
40
+ return exports.FONT_STACKS.arabic;
41
+ }
42
+ if (language === "he" || language === "yi")
43
+ return exports.FONT_STACKS.hebrew;
44
+ return exports.FONT_STACKS.latin;
45
+ }
46
+ /** The `font-feature-settings` that keep Arabic words from looking two-tone. */
47
+ exports.ARABIC_FEATURES = '"kern" 1, "liga" 1, "calt" 1, "rlig" 1, "init" 1, "medi" 1, "fina" 1';
48
+ /**
49
+ * The `unicode-range` for a script, so a downloaded face is only fetched for
50
+ * the characters it actually covers. Without it, a page with one Arabic
51
+ * headline downloads the Arabic font for every reader.
52
+ */
53
+ exports.UNICODE_RANGES = {
54
+ arabic: "U+0600-06FF, U+0750-077F, U+0870-088E, U+08A0-08FF, U+FB50-FDFF, U+FE70-FEFF, U+1EE00-1EEFF",
55
+ hebrew: "U+0590-05FF, U+FB1D-FB4F",
56
+ latin: "U+0000-00FF, U+0131, U+0152-0153, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193",
57
+ };
58
+ /**
59
+ * Builds an `@font-face` rule.
60
+ *
61
+ * It is deliberately a string and not a file: the package ships no fonts, so a
62
+ * consumer decides where the bytes come from — a local install, a CDN, or a
63
+ * self-hosted file — and this only removes the chance of getting the
64
+ * `unicode-range` and the metrics wrong while doing it.
65
+ */
66
+ function fontFace(options) {
67
+ const script = options.script ?? "arabic";
68
+ const sources = Array.isArray(options.src) ? options.src : [options.src];
69
+ const lines = [
70
+ ` font-family: "${options.family}";`,
71
+ ` src: ${sources.join(", ")};`,
72
+ ` font-weight: ${options.weight ?? "400"};`,
73
+ ` font-style: ${options.style ?? "normal"};`,
74
+ ` font-display: ${options.display ?? "swap"};`,
75
+ ` unicode-range: ${options.unicodeRange ?? exports.UNICODE_RANGES[script]};`,
76
+ ];
77
+ if (options.sizeAdjust)
78
+ lines.push(` size-adjust: ${options.sizeAdjust};`);
79
+ return `@font-face {\n${lines.join("\n")}\n}`;
80
+ }
81
+ /** A `font-family` declaration that pairs an Arabic face with a Latin one. */
82
+ function fontFamilyRule(selector, script = "arabic") {
83
+ return `${selector} {\n font-family: ${exports.FONT_STACKS[script]};\n}`;
84
+ }