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