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

textDirection.ts

34 lines1.3 KB

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 if (!RTL_LETTER.test(text)) return LETTER.test(text) ? "ltr" : undefined;
14 let rtlWords = 0;
15 let ltrWords = 0;
16 let first: TextDirection | undefined;
17 for (const word of text.split(/\s+/)) {
18 const letter = LETTER.exec(word)?.[0];
19 if (!letter) continue;
20 const direction = RTL_LETTER.test(letter) ? "rtl" : "ltr";
21 first ??= direction;
22 if (direction === "rtl") rtlWords += 1;
23 else ltrWords += 1;
24 }
25 if (rtlWords === ltrWords) return first;
26 return rtlWords > ltrWords ? "rtl" : "ltr";
28​
29const MARKDOWN_CODE_OR_URL =
30 /(`{3,}|~{3,})[\s\S]*?(?:\1|$)|(`{1,2})(?!`)[\s\S]*?(?<!`)\2(?!`)|https?:\/\/\S+/g;
31​
32export function markdownProseDirection(markdown: string): TextDirection | undefined {
33 return textDirection(markdown.replace(MARKDOWN_CODE_OR_URL, " "));