Open History to see the last commit
1export type TextDirection = "ltr" | "rtl";
2
3// Hebrew through Arabic Extended-A, their presentation forms, and the
4// supplementary right-to-left blocks.
5const RTL_LETTER = /[-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u;
6const LETTER = /\p{L}/u;
7
8/**
9 * The base direction for a block of prose, or undefined when it has no letters.
10 *
11 * `dir="auto"` follows the first letter, which lays out an Arabic line that
12 * opens with an English term (`StrictMode: يعيد الـ render مرتين`) left to
13 * right, and developers write that way constantly. Counting words keeps such a
14 * line right to left, while English with one quoted Arabic word stays left to
15 * right. A tie goes to the first word, as `dir="auto"` would.
16 */
17export function textDirection(text: string): TextDirection | undefined {
18 let rtlWords = 0;
19 let ltrWords = 0;
20 let first: TextDirection | undefined;
21 for (const word of text.split(/\s+/)) {
22 const letter = LETTER.exec(word)?.[0];
23 if (!letter) continue;
24 const direction = RTL_LETTER.test(letter) ? "rtl" : "ltr";
25 first ??= direction;
26 if (direction === "rtl") rtlWords += 1;
27 else ltrWords += 1;
28 }
29 if (rtlWords === ltrWords) return first;
30 return rtlWords > ltrWords ? "rtl" : "ltr";
31}