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.
5export const RTL_LETTER =
6 /[\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFC\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u;
7export const LETTER = /\p{L}/u;
8const SENTENCE_END = /(?<=[.!?؟])(?<!\b(?:e\.g|i\.e)\.)\s+|\n+/i;
9
10function majority(
11 units: Iterable<TextDirection | undefined>,
12 tieDirection?: () => TextDirection | undefined,
13): TextDirection | undefined {
14 let rtl = 0;
15 let ltr = 0;
16 let first: TextDirection | undefined;
17 for (const direction of units) {
18 if (!direction) continue;
19 first ??= direction;
20 if (direction === "rtl") rtl += 1;
21 else ltr += 1;
22 }
23 if (rtl === ltr) return tieDirection ? tieDirection() : first;
24 return rtl > ltr ? "rtl" : "ltr";
25}
26
27export function hasRightToLeftLetter(text: string): boolean {
28 return RTL_LETTER.test(text);
29}
30
31function wordDirection(word: string): TextDirection | undefined {
32 const letter = LETTER.exec(word)?.[0];
33 if (!letter) return undefined;
34 return RTL_LETTER.test(letter) ? "rtl" : "ltr";
35}
36
37/**
38 * `dir="auto"` misreads Arabic prose that opens with an English term.
39 * Each sentence follows its main language by word count, and the text follows most of its
40 * sentences, so one long English sentence cannot outvote the Arabic ones around it.
41 * Sentence ties use the whole-text word majority, then the first word.
42 */
43export function textDirection(text: string): TextDirection | undefined {
44 if (!RTL_LETTER.test(text)) return LETTER.test(text) ? "ltr" : undefined;
45 return majority(
46 text.split(SENTENCE_END).map((sentence) => majority(sentence.split(/\s+/).map(wordDirection))),
47 () => majority(text.split(/\s+/).map(wordDirection)),
48 );
49}
50
51const MARKDOWN_CODE_OR_URL =
52 /(`{3,}|~{3,})[\s\S]*?(?:\1|$)|(`{1,2})(?!`)[\s\S]*?(?<!`)\2(?!`)|https?:\/\/\S+/g;
53
54export function markdownProseDirection(markdown: string): TextDirection | undefined {
55 return textDirection(markdown.replace(MARKDOWN_CODE_OR_URL, " "));
56}