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