Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

textDirection.ts

26 lines948 Bytes

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 * `dir="auto"` misreads Arabic prose that opens with an English term.
10 * Count words so mixed prose follows its main language; break ties with the first word.
11 */
12export function textDirection(text: string): TextDirection | undefined {
13 let rtlWords = 0;
14 let ltrWords = 0;
15 let first: TextDirection | undefined;
16 for (const word of text.split(/\s+/)) {
17 const letter = LETTER.exec(word)?.[0];
18 if (!letter) continue;
19 const direction = RTL_LETTER.test(letter) ? "rtl" : "ltr";
20 first ??= direction;
21 if (direction === "rtl") rtlWords += 1;
22 else ltrWords += 1;
23 }
24 if (rtlWords === ltrWords) return first;
25 return rtlWords > ltrWords ? "rtl" : "ltr";