@devries-cameron20 / t3code Mirror · read-only / commits / 0317d4f4e5
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

fix(mobile): Arabic paragraphs that open with an English word render right to left (#39109)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Mahmoud Nasr committed Nov 19, 2026 at 14:46 UTC 0317d4f4e5d7d3b5aba37bed0d61c304fb24d7ae
6 files changed +148 -3
apps/mobile/src/lib/enrichedLinkPresentation.test.ts
+1
@@ -68,6 +68,7 @@ describe("Enriched link presentation", () => {
68 "Try (model:codex/gpt-6.1).",
69 "Try [model:codex/gpt-6.1] next",
70 '"model:codex/gpt-6.1"',
71 + "‏model:codex/gpt-6.1 هذا شرح",
72 ]) {
73 const source = regex?.exec(text)?.[0];
74 expect(source, text).toBe("model:codex/gpt-6.1");
apps/mobile/src/lib/enrichedLinkPresentation.ts
+2 -1
@@ -174,8 +174,9 @@ export function enrichedModelLinkRegex(models?: ReadonlyArray<SelectableMarkdown
174 .map((model) => model.source)
175 .sort((a, b) => b.length - a.length)
176 .map((source) => source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
177 + // LRM and RLM can open a paragraph whose first word runs against the text direction.
178 return new RegExp(
178 - `(?<![^\\s,(\\["'])(?:${alternatives.join("|")})(?=$|[\\s,"']|[.;:!?\\)\\]]+(?=$|[\\s,"']))`,
179 + `(?<![^\\s,(\\["'\\u200E\\u200F])(?:${alternatives.join("|")})(?=$|[\\s,"']|[.;:!?\\)\\]]+(?=$|[\\s,"']))`,
180 "u",
181 );
182 }
apps/mobile/src/lib/markdownDocument.ts
+62
@@ -9,6 +9,7 @@ import {
9 parseMarkdownFileLink,
10 } from "@t3tools/shared/markdownLinks";
11 import { isWindowsAbsolutePath } from "@t3tools/shared/path";
12 +import { hasRightToLeftLetter, textDirection } from "@t3tools/shared/textDirection";
13
14 const parser = unified().use(remarkParse).use(remarkGfm).use(remarkKeepWindowsProsePaths);
15 export type MarkdownNode = Root | RootContent;
@@ -562,3 +563,64 @@ export function markdownWithFileEmbeds(
563 parts.push(markdown.slice(offset));
564 return { markdown: parts.join(""), fileHrefs };
565 }
566 +
567 +const DIRECTION_MARK = { ltr: "‎", rtl: "‏" } as const;
568 +
569 +function proseText(node: MarkdownNode): string {
570 + if (node.type === "text") return node.value;
571 + if (node.type === "inlineCode" || node.type === "code") return " ";
572 + if (!("children" in node)) return "";
573 + const text = node.children.map(proseText).join("");
574 + return node.type === "paragraph" || node.type === "heading" || node.type === "tableCell"
575 + ? ` ${text} `
576 + : text;
577 +}
578 +
579 +// The native renderer scans inline code too when it picks a paragraph's direction.
580 +function renderedText(node: MarkdownNode): string {
581 + if (node.type === "text" || node.type === "inlineCode") return node.value;
582 + if (!("children" in node)) return "";
583 + return node.children.map(renderedText).join("");
584 +}
585 +
586 +// A mark inside `[label]` or `<url>` would break the reference or autolink.
587 +function firstLeafOffset(node: MarkdownNode): number | undefined {
588 + if (
589 + !("children" in node) ||
590 + node.children.length === 0 ||
591 + node.type === "link" ||
592 + node.type === "linkReference"
593 + ) {
594 + return node.position?.start.offset;
595 + }
596 + return firstLeafOffset(node.children[0]!);
597 +}
598 +
599 +/**
600 + * The native renderer gives each paragraph the direction of its first letter, so an Arabic
601 + * line that opens with an English name renders left to right. Like the web's
602 + * `rehypeTextDirection`, each top-level block follows the majority of its words, and a
603 + * paragraph whose first letter disagrees gets a direction mark that the renderer reads first.
604 + */
605 +export function markdownWithTextDirection(markdown: string): string {
606 + if (!hasRightToLeftLetter(markdown)) return markdown;
607 + const edits: MarkdownEdit[] = [];
608 + for (const block of parser.parse(markdown).children) {
609 + if (block.type === "code" || block.type === "html") continue;
610 + const direction = textDirection(proseText(block));
611 + if (!direction) continue;
612 + const mark = (node: MarkdownNode) => {
613 + if (node.type === "paragraph" || node.type === "heading" || node.type === "tableCell") {
614 + const offset = firstLeafOffset(node);
615 + const first = renderedText(node).match(/\p{L}/u)?.[0];
616 + if (offset !== undefined && first && textDirection(first) !== direction) {
617 + edits.push({ start: offset, end: offset, content: DIRECTION_MARK[direction] });
618 + }
619 + return;
620 + }
621 + if ("children" in node) node.children.forEach(mark);
622 + };
623 + mark(block);
624 + }
625 + return applyMarkdownEdits(markdown, edits);
626 +}
apps/mobile/src/lib/markdownTextDirection.test.ts new
+71
@@ -0,0 +1,71 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +import { markdownWithTextDirection } from "./markdownDocument";
3 +
4 +const LRM = "‎";
5 +const RLM = "‏";
6 +
7 +describe("markdownWithTextDirection", () => {
8 + it("marks Arabic list items that open with an English name", () => {
9 + const markdown = [
10 + "## للنمو والتقوية",
11 + "",
12 + "- **Plantur**، Haarserum 100 مل، 14,95 €. سيروم مخصص للشعر الطويل بالكافيين، أغلى واحد في القائمة.",
13 + "- **Bali Curls**، زيت إكليل الجبل للفروة والشعر، موجه للشعر اللي بيخف.",
14 + ].join("\n");
15 +
16 + expect(markdownWithTextDirection(markdown)).toBe(
17 + [
18 + "## للنمو والتقوية",
19 + "",
20 + `- **${RLM}Plantur**، Haarserum 100 مل، 14,95 €. سيروم مخصص للشعر الطويل بالكافيين، أغلى واحد في القائمة.`,
21 + `- **${RLM}Bali Curls**، زيت إكليل الجبل للفروة والشعر، موجه للشعر اللي بيخف.`,
22 + ].join("\n"),
23 + );
24 + });
25 +
26 + it("keeps an English list on one side when one item opens in Arabic", () => {
27 + const markdown = "- Install the package first.\n- مرحبا then run the build and tests.";
28 + expect(markdownWithTextDirection(markdown)).toBe(
29 + `- Install the package first.\n- ${LRM}مرحبا then run the build and tests.`,
30 + );
31 + });
32 +
33 + it("skips code and keeps task list checkboxes intact", () => {
34 + const markdown = "```\nconst a = 'مرحبا';\n```\n\n- [ ] npm تشغيل الأوامر من المجلد الرئيسي";
35 + expect(markdownWithTextDirection(markdown)).toBe(
36 + `\`\`\`\nconst a = 'مرحبا';\n\`\`\`\n\n- [ ] ${RLM}npm تشغيل الأوامر من المجلد الرئيسي`,
37 + );
38 + });
39 +
40 + it("keeps words apart across table cells", () => {
41 + const markdown = "| Name | الاسم | الوصف |\n| --- | --- | --- |\n| Price | السعر | القيمة |";
42 + expect(markdownWithTextDirection(markdown)).toBe(
43 + `| ${RLM}Name | الاسم | الوصف |\n| --- | --- | --- |\n| ${RLM}Price | السعر | القيمة |`,
44 + );
45 + });
46 +
47 + it("puts the mark before a link so references and autolinks still parse", () => {
48 + const markdown = [
49 + "[Plantur] هذا شرح عربي طويل للمنتج",
50 + "",
51 + "<https://example.com> هذا شرح عربي طويل للرابط",
52 + "",
53 + "[Plantur]: /product",
54 + ].join("\n");
55 + expect(markdownWithTextDirection(markdown)).toBe(
56 + [
57 + `${RLM}[Plantur] هذا شرح عربي طويل للمنتج`,
58 + "",
59 + `${RLM}<https://example.com> هذا شرح عربي طويل للرابط`,
60 + "",
61 + "[Plantur]: /product",
62 + ].join("\n"),
63 + );
64 + });
65 +
66 + it("marks Arabic paragraphs that open with inline code", () => {
67 + expect(markdownWithTextDirection("`npm` تشغيل الأوامر من المجلد الرئيسي")).toBe(
68 + `${RLM}\`npm\` تشغيل الأوامر من المجلد الرئيسي`,
69 + );
70 + });
71 +});
apps/mobile/src/native/EnrichedMarkdownText.tsx
+8 -2
@@ -10,6 +10,7 @@ import {
10 markdownForNativeParsing,
11 markdownWithInlineFileLinks,
12 markdownWithTableBreaks,
13 + markdownWithTextDirection,
14 } from "../lib/markdownDocument";
15 import { useGT } from "gt-react-native";
16 import { isValidElement, useMemo, useState, type ReactElement, type ReactNode } from "react";
@@ -249,7 +250,9 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
250 const { markdown, fileHrefs } = useMemo(() => {
251 if (!fileEmbedLabel) {
252 return {
252 - markdown: markdownForNativeRendering(props.markdown, ENRICHED_INLINE_FILE_LINK_REGEX),
253 + markdown: markdownWithTextDirection(
254 + markdownForNativeRendering(props.markdown, ENRICHED_INLINE_FILE_LINK_REGEX),
255 + ),
256 fileHrefs: new Set<string>(),
257 };
258 }
@@ -258,7 +261,10 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
261 ENRICHED_INLINE_FILE_LINK_REGEX,
262 );
263 const files = markdownWithFileEmbeds(content, fileEmbedLabel);
261 - return { ...files, markdown: markdownWithTableBreaks(files.markdown) };
264 + return {
265 + ...files,
266 + markdown: markdownWithTextDirection(markdownWithTableBreaks(files.markdown)),
267 + };
268 }, [props.markdown, fileEmbedLabel]);
269 const [parsedLinkUrls, setParsedLinkUrls] = useState<ReadonlyArray<string>>([]);
270 const onLinksChange = (links: MarkdownLinkOccurrence[]) => {
packages/shared/src/textDirection.ts
+4
@@ -23,6 +23,10 @@ function majority(
23 return rtl > ltr ? "rtl" : "ltr";
24 }
25
26 +export function hasRightToLeftLetter(text: string): boolean {
27 + return RTL_LETTER.test(text);
28 +}
29 +
30 function wordDirection(word: string): TextDirection | undefined {
31 const letter = LETTER.exec(word)?.[0];
32 if (!letter) return undefined;