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 = /[-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u;
6export const 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
26export function hasRightToLeftLetter(text: string): boolean {
27 return RTL_LETTER.test(text);
28}
29
30function wordDirection(word: string): TextDirection | undefined {
31 const letter = LETTER.exec(word)?.[0];
32 if (!letter) return undefined;
33 return RTL_LETTER.test(letter) ? "rtl" : "ltr";
34}
35
36/**
37 * `dir="auto"` misreads Arabic prose that opens with an English term.
38 * Each sentence follows its main language by word count, and the text follows most of its
39 * sentences, so one long English sentence cannot outvote the Arabic ones around it.
40 * Sentence ties use the whole-text word majority, then the first word.
41 */
42export function textDirection(text: string): TextDirection | undefined {
43 if (!RTL_LETTER.test(text)) return LETTER.test(text) ? "ltr" : undefined;
44 return majority(
45 text.split(SENTENCE_END).map((sentence) => majority(sentence.split(/\s+/).map(wordDirection))),
46 () => majority(text.split(/\s+/).map(wordDirection)),
47 );
48}
49
50const MARKDOWN_CODE_OR_URL =
51 /(`{3,}|~{3,})[\s\S]*?(?:\1|$)|(`{1,2})(?!`)[\s\S]*?(?<!`)\2(?!`)|https?:\/\/\S+/g;
52
53export function markdownProseDirection(markdown: string): TextDirection | undefined {
54 return textDirection(markdown.replace(MARKDOWN_CODE_OR_URL, " "));
55}