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

markdownTextDirection.ts

90 lines2.6 KB

1import { LETTER, RTL_LETTER, textDirection } from "~/textDirection";
2​
3type HastNode = {
4 type?: string;
5 tagName?: string;
6 value?: string;
7 properties?: Record<string, unknown>;
8 children?: HastNode[];
9};
10​
11// Raw HTML such as `<li>a</li><li>b</li>` has no whitespace between its
12// blocks, so they add their own to keep the words apart.
13const BLOCK_TAGS = new Set([
14 "blockquote",
15 "br",
16 "details",
17 "div",
18 "h1",
19 "h2",
20 "h3",
21 "h4",
22 "h5",
23 "h6",
24 "hr",
25 "li",
26 "ol",
27 "p",
28 "summary",
29 "table",
30 "td",
31 "th",
32 "tr",
33 "ul",
34]);
35​
36function proseText(node: HastNode): string {
37 if (node.type === "text") return node.value ?? "";
38 if (node.tagName === "code") return " ";
39 const text = (node.children ?? []).map(proseText).join("");
40 return node.tagName && BLOCK_TAGS.has(node.tagName) ? ` ${text} ` : text;
42​
43function isolateInlineCode(node: HastNode): void {
44 if (node.tagName === "pre") return;
45 if (node.tagName === "code") {
46 node.properties = { ...node.properties, dir: "ltr" };
47 return;
48 }
49 node.children?.forEach(isolateInlineCode);
51​
52/**
53 * Gives each top-level block the direction of its own words, so an Arabic or
54 * Hebrew reply reads right to left beside English ones. Lines inside a list or
55 * quote follow it, keeping markers and rules on one side. Inline code is left
56 * out of the count and isolated left to right, so its punctuation stays put.
57 */
58export function rehypeTextDirection() {
59 return (tree: HastNode) => {
60 blockTextDirections(tree);
61 isolateInlineCode(tree);
62 };
64​
65/** Each top-level block's direction: an authored ltr or rtl dir, else what its prose says. */
66function blockTextDirections(tree: HastNode) {
67 for (const block of tree.children ?? []) {
68 if (block.type !== "element" || block.tagName === "pre") continue;
69 const authored = block.properties?.dir;
70 if (typeof authored === "string" && /^(?:ltr|rtl)$/i.test(authored)) continue;
71 const dir = scriptOf(block) === "rtl" ? textDirection(proseText(block)) : scriptOf(block);
72 if (dir) block.properties = { ...block.properties, dir };
73 }
75​
76/** "rtl" when any prose letter is right-to-left; otherwise what textDirection would say. */
77function scriptOf(node: HastNode): "rtl" | "ltr" | undefined {
78 let found: "ltr" | undefined;
79 const visit = (current: HastNode): boolean => {
80 if (current.type === "text") {
81 const value = current.value ?? "";
82 if (RTL_LETTER.test(value)) return true;
83 if (!found && LETTER.test(value)) found = "ltr";
84 return false;
85 }
86 if (current.tagName === "code") return false;
87 return (current.children ?? []).some(visit);
88 };
89 return visit(node) ? "rtl" : found;