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

markdownTextDirection.ts

88 lines2.5 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, from its prose; an RTL letter decides as textDirection does. */
66function blockTextDirections(tree: HastNode) {
67 for (const block of tree.children ?? []) {
68 if (block.type !== "element" || block.tagName === "pre") continue;
69 const dir = scriptOf(block) === "rtl" ? textDirection(proseText(block)) : scriptOf(block);
70 if (dir) block.properties = { ...block.properties, dir };
71 }
73​
74/** "rtl" when any prose letter is right-to-left; otherwise what textDirection would say. */
75function scriptOf(node: HastNode): "rtl" | "ltr" | undefined {
76 let found: "ltr" | undefined;
77 const visit = (current: HastNode): boolean => {
78 if (current.type === "text") {
79 const value = current.value ?? "";
80 if (RTL_LETTER.test(value)) return true;
81 if (!found && LETTER.test(value)) found = "ltr";
82 return false;
83 }
84 if (current.tagName === "code") return false;
85 return (current.children ?? []).some(visit);
86 };
87 return visit(node) ? "rtl" : found;