@devries-cameron20 / t3code-1 / commits / 3690c86253
Fork 0

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

fix(web): Arabic and Hebrew text reads and navigates right to left (#22777)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

يزن حمزه committed Oct 22, 2026 at 06:17 UTC 3690c862530c88781b28dce991697e5ea0dc26be
16 files changed +454 -25
apps/web/src/components/ChatMarkdown.tsx
+11 -4
@@ -202,6 +202,7 @@ import { MarkdownExternalLinkContent } from "./chat/MarkdownExternalLink";
202 import { MarkdownFileLink } from "./chat/MarkdownFileLink";
203 import { canUseMarkdownFileShellActions } from "./chat/MarkdownFileLink.logic";
204 import { handleMarkdownFragmentClick, rehypeHeadingIds } from "./chat/markdownFragments";
205 +import { rehypeTextDirection } from "./chat/markdownTextDirection";
206 import { hastHasText, hastPlainTextDeep, plainHastText } from "./chat/markdownHast.logic";
207 import {
208 extractCodeBlock,
@@ -384,11 +385,13 @@ function normalizeMarkdownLinkHrefKey(href: string): string {
385 const CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS = [
386 ...CHAT_MARKDOWN_REHYPE_PLUGINS,
387 rehypeHeadingIds,
388 + rehypeTextDirection,
389 ] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
390
389 -const CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS = [rehypeHeadingIds] satisfies NonNullable<
390 - ReactMarkdownOptions["rehypePlugins"]
391 ->;
391 +const CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS = [
392 + rehypeHeadingIds,
393 + rehypeTextDirection,
394 +] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
395
396 const NO_MARKDOWN_EDITORS: ReadonlyArray<EditorId> = [];
397
@@ -975,7 +978,11 @@ const CHAT_MARKDOWN_COMPONENTS = {
978 return <blockquote {...props}>{children}</blockquote>;
979 }
980 return (
978 - <div role="note" className={cn("my-1 border-l-2 pl-3", alert.borderClassName)}>
981 + <div
982 + role="note"
983 + dir={props.dir}
984 + className={cn("my-1 border-s-2 ps-3", alert.borderClassName)}
985 + >
986 <p
987 data-thread-find-ignore="true"
988 className={cn("flex items-center gap-1.5 font-medium", alert.titleClassName)}
apps/web/src/components/CommandPaletteResults.tsx
+13 -4
@@ -3,6 +3,7 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react";
3 import { ChevronRightIcon } from "lucide-react";
4 import { type ReactNode, type RefObject, useState } from "react";
5 import { cn } from "~/lib/utils";
6 +import { textDirection } from "~/textDirection";
7 import { shortcutLabelForCommand } from "../keybindings";
8 import {
9 type CommandPaletteActionItem,
@@ -154,6 +155,14 @@ export function CommandPaletteTitleIcon(props: { children: ReactNode }) {
155 return <span className="flex h-5 shrink-0 items-center self-start pt-0.5">{props.children}</span>;
156 }
157
158 +function CommandPaletteTitle({ title }: { title: ReactNode }) {
159 + return (
160 + <span className="truncate" dir={typeof title === "string" ? textDirection(title) : undefined}>
161 + {title}
162 + </span>
163 + );
164 +}
165 +
166 function DisabledCommandPaletteResultRow(props: {
167 item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
168 }) {
@@ -164,7 +173,7 @@ function DisabledCommandPaletteResultRow(props: {
173 <span className="flex min-w-0 flex-1 flex-col">
174 <span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
175 {props.item.titleLeadingContent}
167 - <span className="truncate">{props.item.title}</span>
176 + <CommandPaletteTitle title={props.item.title} />
177 </span>
178 {props.item.threadContentMatch ? (
179 <ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
@@ -178,7 +187,7 @@ function DisabledCommandPaletteResultRow(props: {
187 ) : (
188 <span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
189 {props.item.titleLeadingContent}
181 - <span className="truncate">{props.item.title}</span>
190 + <CommandPaletteTitle title={props.item.title} />
191 </span>
192 )}
193 {props.item.titleTrailingContent}
@@ -214,7 +223,7 @@ function CommandPaletteResultRow(props: {
223 <span className="flex min-w-0 flex-1 flex-col">
224 <span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
225 {props.item.titleLeadingContent}
217 - <span className="truncate">{props.item.title}</span>
226 + <CommandPaletteTitle title={props.item.title} />
227 </span>
228 {props.item.threadContentMatch ? (
229 <ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
@@ -228,7 +237,7 @@ function CommandPaletteResultRow(props: {
237 ) : (
238 <span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
239 {props.item.titleLeadingContent}
231 - <span className="truncate">{props.item.title}</span>
240 + <CommandPaletteTitle title={props.item.title} />
241 </span>
242 )}
243 {props.item.titleTrailingContent}
apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx
+62 -1
@@ -10,7 +10,8 @@ import {
10 import type { ServerProviderSkill } from "@t3tools/contracts";
11 import type { Editor } from "@tiptap/core";
12 import { createElement, createRef, useEffect, useState } from "react";
13 -import { describe, expect, it } from "vite-plus/test";
13 +import { describe, expect, it, vi } from "vite-plus/test";
14 +import { userEvent } from "vite-plus/test/browser";
15
16 import { act, render } from "../../test/render";
17
@@ -352,3 +353,63 @@ describe("composer context undo lifetime", () => {
353 },
354 );
355 });
356 +
357 +describe("an Arabic line", () => {
358 + async function focusEnd(editor: Editor) {
359 + await act(async () => {
360 + editor.commands.focus("end");
361 + });
362 + await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
363 + }
364 +
365 + it("leaves inline code through its start with ArrowRight, which points back", async () => {
366 + // Positions: اكتب at 1-5, sumBy at 6-11, الان at 12-16.
367 + await using screen = await mountEditor("اكتب `sumBy` الان");
368 + const { editor } = screen;
369 + await focusEnd(editor);
370 + const caret = () => ({
371 + head: editor.state.selection.head,
372 + inCode: (editor.state.storedMarks ?? editor.state.selection.$head.marks()).length > 0,
373 + });
374 + const visited = [caret()];
375 + while (visited.at(-1)!.head > 5) {
376 + const before = visited.at(-1)!;
377 + await userEvent.keyboard("{ArrowRight}");
378 + await vi.waitFor(() => {
379 + const after = caret();
380 + expect(after.head < before.head || after.inCode !== before.inCode).toBe(true);
381 + });
382 + visited.push(caret());
383 + }
384 + expect(visited.some((stop) => stop.inCode)).toBe(true);
385 + });
386 +
387 + it("shows the backticks on either side of inline code it is editing", async () => {
388 + await using screen = await mountEditor("اكتب `sumBy` الان");
389 + const { editor } = screen;
390 + await act(async () => {
391 + editor.commands.setTextSelection("اكتب su".length + 1);
392 + });
393 + const code = editor.view.dom.querySelector("code")!;
394 + const word = document.createRange();
395 + word.selectNodeContents([...code.childNodes].find((node) => node instanceof Text)!);
396 + const text = word.getBoundingClientRect();
397 + const [open, close] = [...editor.view.dom.querySelectorAll(".composer-rich-marker")].map(
398 + (marker) => marker.getBoundingClientRect(),
399 + );
400 + expect(open!.right).toBeLessThanOrEqual(text.left + 1);
401 + expect(close!.left).toBeGreaterThanOrEqual(text.right - 1);
402 + });
403 +
404 + it("starts the next line on the right", async () => {
405 + await using screen = await mountEditor("اكتب الدالة");
406 + const { editor } = screen;
407 + await focusEnd(editor);
408 + await userEvent.keyboard("{Shift>}{Enter}{/Shift}");
409 + await vi.waitFor(() => expect(editor.state.doc.childCount).toBe(2));
410 + const box = editor.view.dom.getBoundingClientRect();
411 + expect(editor.view.coordsAtPos(editor.state.selection.head).left).toBeGreaterThan(
412 + box.left + box.width / 2,
413 + );
414 + });
415 +});
apps/web/src/components/ComposerPromptEditorTiptap.tsx
+20 -3
@@ -56,6 +56,7 @@ import {
56 pastedPathQueryLength,
57 } from "~/composer-logic";
58 import { useStableCallback } from "~/hooks/useStableCallback";
59 +import { caretLineDirection, ComposerTextDirectionExtension } from "~/composer-text-direction";
60 import {
61 collectComposerPromptInlineTokens,
62 selectionTouchesMentionBoundary,
@@ -264,6 +265,7 @@ function ComposerMentionNodeView({ node }: NodeViewProps) {
265 const chip = (
266 <ContextChip
267 kind="mention"
268 + dir="ltr"
269 render={<button type="button" />}
270 onClick={() => actions.openMention(path)}
271 aria-label={`Preview ${path}`}
@@ -727,6 +729,7 @@ const ComposerMarkerPlugin = new Plugin({
729 function decorationsForSelection(state: EditorState): DecorationSet {
730 const { doc, selection } = state;
731 const caretSide = caretTakesMarksBefore(state) ? 3 : 0;
732 + const rtl = caretLineDirection(state) === "rtl";
733 const decorations: Decoration[] = [];
734 if (!selection.empty) {
735 doc.nodesBetween(selection.from, selection.to, (node, pos) => {
@@ -750,8 +753,19 @@ function decorationsForSelection(state: EditorState): DecorationSet {
753 marker.className = "composer-rich-marker";
754 marker.textContent = text;
755 marker.setAttribute("aria-hidden", "true");
756 + // Inline code is isolated left to right. In a right-to-left line its
757 + // opening backtick joins the closing one inside the isolate, or the line
758 + // would put both on the same side of the code.
759 + const codeMarks =
760 + rtl && baseSide === -1 && /^`+$/.test(text)
761 + ? doc.resolve(at).nodeAfter?.marks.filter((mark) => mark.type.spec.code)
762 + : undefined;
763 decorations.push(
754 - Decoration.widget(at, marker, { side, key: `marker-${at}-${side}-${marker.textContent}` }),
764 + Decoration.widget(at, marker, {
765 + side,
766 + key: `marker-${at}-${side}-${marker.textContent}`,
767 + ...(codeMarks?.length ? { marks: codeMarks } : {}),
768 + }),
769 );
770 }
771 }
@@ -852,6 +866,7 @@ function createComposerExtensions(richText: boolean) {
866 ...(richText ? {} : { bold: false, strike: false }),
867 }),
868 ComposerUndoGroupingExtension,
869 + ComposerTextDirectionExtension,
870 ComposerMentionExtension,
871 ComposerSkillExtension,
872 ComposerCitationExtension,
@@ -1146,6 +1161,8 @@ function ComposerPromptEditorTiptapInner(
1161 editorProps: {
1162 attributes: editorAttributes,
1163 handleKeyDown: (view, event) => {
1164 + // In a right-to-left line the start is on the right.
1165 + const backArrow = caretLineDirection(view.state) === "rtl" ? "ArrowRight" : "ArrowLeft";
1166 const boundary = event.metaKey
1167 ? event.key === "ArrowLeft" || event.key === "ArrowRight"
1168 ? "lineboundary"
@@ -1171,7 +1188,7 @@ function ComposerPromptEditorTiptapInner(
1188 event.preventDefault();
1189 event.stopPropagation();
1190 const backward =
1174 - event.key === "Home" || event.key === "ArrowLeft" || event.key === "ArrowUp";
1191 + event.key === "Home" || event.key === "ArrowUp" || event.key === backArrow;
1192 selection.modify(
1193 event.shiftKey ? "extend" : "move",
1194 backward ? "backward" : "forward",
@@ -1206,7 +1223,7 @@ function ComposerPromptEditorTiptapInner(
1223 view.state.selection.empty
1224 ) {
1225 const { $from } = view.state.selection;
1209 - const direction = event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 1;
1226 + const direction = event.key === "ArrowUp" || event.key === backArrow ? -1 : 1;
1227 const horizontal = event.key === "ArrowLeft" || event.key === "ArrowRight";
1228 // At the document's ends, native Up/Down can cross a marker without
1229 // changing the document position. Record the stop so DOM selection
apps/web/src/components/chat/ChatHeader.tsx
+10 -2
@@ -35,6 +35,7 @@ import {
35 } from "../WorkspaceBreadcrumb";
36 import { observeResize } from "~/lib/observeResize";
37 import { cn } from "~/lib/utils";
38 +import { textDirection } from "~/textDirection";
39 import { useClientSettings } from "../../hooks/useSettings";
40
41 interface ChatHeaderProps {
@@ -342,6 +343,7 @@ export const ChatHeader = memo(function ChatHeader({
343 {renamingTitle !== null ? (
344 <input
345 autoFocus
346 + dir="auto"
347 aria-label="Thread title"
348 className="min-w-0 flex-1 rounded-sm bg-transparent text-sm font-medium text-foreground outline-none ring-1 ring-inset ring-ring/50 focus:ring-ring"
349 defaultValue={renamingTitle}
@@ -375,7 +377,7 @@ export const ChatHeader = memo(function ChatHeader({
377 />
378 }
379 >
378 - <h2 className="min-w-0">
380 + <h2 className="min-w-0" dir={textDirection(activeThreadTitle)}>
381 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
382 </h2>
383 <ChevronDownIcon
@@ -389,7 +391,13 @@ export const ChatHeader = memo(function ChatHeader({
391 ) : (
392 <Tooltip>
393 <TooltipTrigger
392 - render={<h2 aria-label={activeThreadTitle} className="min-w-0 flex-1" />}
394 + render={
395 + <h2
396 + aria-label={activeThreadTitle}
397 + className="min-w-0 flex-1"
398 + dir={textDirection(activeThreadTitle)}
399 + />
400 + }
401 >
402 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
403 </TooltipTrigger>
apps/web/src/components/chat/MarkdownCodeBlock.tsx
+1
@@ -60,6 +60,7 @@ export function MarkdownCodeBlockFrame({
60 }) {
61 return (
62 <Wrapper
63 + dir="ltr"
64 className="chat-markdown-codeblock my-[0.65rem] overflow-hidden rounded-lg border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"
65 data-language={language}
66 data-wrap={wrapped ? "true" : "false"}
apps/web/src/components/chat/MarkdownFileLink.tsx
+2
@@ -328,6 +328,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
328 hasPrimaryAction ? (
329 <ContextChip
330 kind="mention"
331 + dir="ltr"
332 render={<a href={href} />}
333 className={MARKDOWN_FILE_LINK_CLASS_NAME}
334 data-markdown-copy={copyMarkdown}
@@ -356,6 +357,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
357 ) : (
358 <ContextChip
359 kind="mention"
360 + dir="ltr"
361 render={<button type="button" />}
362 aria-label={`File options for ${label}`}
363 aria-haspopup="menu"
apps/web/src/components/chat/markdownTextDirection.test.ts new
+39
@@ -0,0 +1,39 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { rehypeTextDirection } from "./markdownTextDirection";
4 +
5 +const text = (value: string) => ({ type: "text", value });
6 +const element = (tagName: string, children: object[]) => ({
7 + type: "element",
8 + tagName,
9 + properties: {} as Record<string, unknown>,
10 + children,
11 +});
12 +
13 +function directed(...blocks: ReturnType<typeof element>[]) {
14 + rehypeTextDirection()({ type: "root", children: blocks });
15 + return blocks;
16 +}
17 +
18 +describe("rehypeTextDirection", () => {
19 + it("keeps raw HTML list items apart when counting words", () => {
20 + const [list] = directed(
21 + element("ul", [element("li", [text("مرحبا")]), element("li", [text("hello world")])]),
22 + );
23 + expect(list!.properties.dir).toBe("ltr");
24 + });
25 +
26 + it("leaves inline code out of the count and isolates it", () => {
27 + const code = element("code", [text("useEffect useLayoutEffect React")]);
28 + const [paragraph] = directed(element("p", [text("استخدم "), code, text(" هنا")]));
29 + expect(paragraph!.properties.dir).toBe("rtl");
30 + expect(code.properties.dir).toBe("ltr");
31 + });
32 +
33 + it("leaves code blocks to their own left-to-right frame", () => {
34 + const code = element("code", [text("// احسب المجموع هنا")]);
35 + const [pre] = directed(element("pre", [code]));
36 + expect(pre!.properties.dir).toBeUndefined();
37 + expect(code.properties.dir).toBeUndefined();
38 + });
39 +});
apps/web/src/components/chat/markdownTextDirection.ts new
+67
@@ -0,0 +1,67 @@
1 +import { textDirection } from "~/textDirection";
2 +
3 +type 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.
13 +const 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 +
36 +function 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;
41 +}
42 +
43 +function 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);
50 +}
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 + */
58 +export function rehypeTextDirection() {
59 + return (tree: HastNode) => {
60 + for (const block of tree.children ?? []) {
61 + if (block.type !== "element" || block.tagName === "pre") continue;
62 + const dir = textDirection(proseText(block));
63 + if (dir) block.properties = { ...block.properties, dir };
64 + }
65 + isolateInlineCode(tree);
66 + };
67 +}
apps/web/src/components/sidebar/SidebarThreadRow.tsx
+4 -1
@@ -70,6 +70,7 @@ import { formatRelativeTimeLabel, parseTimestampDate } from "../../timestampForm
70 import type { SidebarThreadSummary } from "../../types";
71 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
72 import { cn } from "~/lib/utils";
73 +import { textDirection } from "~/textDirection";
74 import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
75 import {
76 animateSidebarLayoutChanges,
@@ -946,6 +947,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
947 <input
948 autoFocus
949 value={renamingTitle}
950 + dir="auto"
951 aria-label="Thread title"
952 onChange={(event) => onRenameTitleChange(event.target.value)}
953 onFocus={(event) => event.currentTarget.select()}
@@ -959,7 +961,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
961 <span
962 aria-hidden
963 className={cn(
962 - "min-w-0 flex-1 text-sm transition-opacity motion-reduce:transition-none",
964 + "min-w-0 flex-1 text-start text-sm transition-opacity motion-reduce:transition-none",
965 shouldRecede ? "font-normal" : "font-medium",
966 variant === "card"
967 ? cn(
@@ -984,6 +986,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
986 ),
987 isRegeneratingTitle && "opacity-55",
988 )}
989 + dir={textDirection(thread.title)}
990 >
991 {thread.title}
992 </span>
apps/web/src/composer-rich-text-doc.ts
+7 -2
@@ -126,9 +126,14 @@ function codePairCaretPlugin(type: MarkType) {
126 */
127 export const ComposerCodeExtension = Code.extend({
128 excludes: "code",
129 - // ArrowRight leaves code through the caret stops at styled edges, so the
130 - // stock exit (inserting a space at the end of a line) is not needed.
129 + // The forward arrow leaves code through the caret stops at styled edges, so
130 + // the stock exit (inserting a space at the end of a line) is not needed.
131 exitable: false,
132 + // Code reads left to right inside an Arabic or Hebrew line, and the isolate
133 + // keeps its punctuation from trading places with the text around it.
134 + addOptions() {
135 + return { ...this.parent!(), HTMLAttributes: { dir: "ltr" } };
136 + },
137 addProseMirrorPlugins() {
138 return [...(this.parent?.() ?? []), codePairCaretPlugin(this.type)];
139 },
apps/web/src/composer-text-direction.test.ts new
+62
@@ -0,0 +1,62 @@
1 +import { getSchemaByResolvedExtensions, resolveExtensions } from "@tiptap/core";
2 +import { Node as ProseMirrorNode } from "@tiptap/pm/model";
3 +import StarterKit from "@tiptap/starter-kit";
4 +import { describe, expect, it } from "vite-plus/test";
5 +
6 +import {
7 + buildDocJson,
8 + ComposerBlockExtensions,
9 + ComposerCodeBlockExtension,
10 + ComposerCodeExtension,
11 + ComposerListExtensions,
12 +} from "./composer-rich-text-doc";
13 +import { composerTextDirections } from "./composer-text-direction";
14 +
15 +const schema = getSchemaByResolvedExtensions(
16 + resolveExtensions([
17 + StarterKit.configure({
18 + blockquote: false,
19 + bulletList: false,
20 + codeBlock: false,
21 + heading: false,
22 + horizontalRule: false,
23 + listItem: false,
24 + orderedList: false,
25 + code: false,
26 + }),
27 + ComposerCodeExtension,
28 + ComposerCodeBlockExtension,
29 + ...ComposerListExtensions,
30 + ...ComposerBlockExtensions,
31 + ]),
32 +);
33 +
34 +function directions(value: string) {
35 + const doc = ProseMirrorNode.fromJSON(
36 + schema,
37 + buildDocJson(value, (name) => ({ label: name, description: null })),
38 + );
39 + return composerTextDirections(doc).blocks;
40 +}
41 +
42 +describe("composerTextDirections", () => {
43 + it("does not count inline code toward a line's direction", () => {
44 + expect(directions("`useEffect` و `useLayoutEffect` في `React`")).toEqual(["rtl"]);
45 + });
46 +
47 + it("gives a list one direction, from all of its items", () => {
48 + expect(directions("- Vitest\n- اختبر الدالة الجديدة\n- وأضف تعليق")).toEqual(["rtl"]);
49 + });
50 +
51 + it("continues the line above until a line has letters", () => {
52 + expect(directions("اكتب الدالة\n\n42\nfix it")).toEqual(["rtl", "rtl", "rtl", "ltr"]);
53 + });
54 +
55 + it("keeps a code block left to right inside Arabic text", () => {
56 + expect(directions("اكتب الدالة\n```\n// احسب مجموع القيم هنا\n```\nثم اختبرها")).toEqual([
57 + "rtl",
58 + "ltr",
59 + "rtl",
60 + ]);
61 + });
62 +});
apps/web/src/composer-text-direction.ts new
+90
@@ -0,0 +1,90 @@
1 +import { Extension } from "@tiptap/core";
2 +import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
3 +import { type EditorState, Plugin, PluginKey } from "@tiptap/pm/state";
4 +import { Decoration, DecorationSet } from "@tiptap/pm/view";
5 +
6 +import { textDirection, type TextDirection } from "~/textDirection";
7 +
8 +interface ComposerTextDirections {
9 + /** One entry per top-level block. */
10 + readonly blocks: ReadonlyArray<TextDirection | null>;
11 + readonly decorations: DecorationSet;
12 +}
13 +
14 +// Nodes are immutable and blocks are shared between documents, so a keystroke
15 +// only recounts the block it changed, and every reader of one document shares
16 +// one result.
17 +const blockDirections = new WeakMap<ProseMirrorNode, TextDirection | null>();
18 +const docDirections = new WeakMap<ProseMirrorNode, ComposerTextDirections>();
19 +
20 +function proseText(block: ProseMirrorNode): string {
21 + let text = "";
22 + block.descendants((node) => {
23 + if (node.isText) {
24 + text += node.marks.some((mark) => mark.type.spec.code) ? " " : node.text;
25 + } else if (node.isBlock || node.isAtom) {
26 + text += " ";
27 + }
28 + });
29 + return text;
30 +}
31 +
32 +function blockDirection(block: ProseMirrorNode): TextDirection | null {
33 + let direction = blockDirections.get(block);
34 + if (direction === undefined) {
35 + direction = textDirection(proseText(block)) ?? null;
36 + blockDirections.set(block, direction);
37 + }
38 + return direction;
39 +}
40 +
41 +/**
42 + * Lines inside a list or quote follow the block around them, which keeps the
43 + * bullets and the quote rule on the same side as the text. A line without
44 + * letters yet continues the one above, so a new line after Arabic starts on
45 + * the right. Code blocks stay left to right.
46 + */
47 +export function composerTextDirections(doc: ProseMirrorNode): ComposerTextDirections {
48 + const cached = docDirections.get(doc);
49 + if (cached) return cached;
50 + const blocks: Array<TextDirection | null> = [];
51 + const decorations: Decoration[] = [];
52 + let previous: TextDirection | null = null;
53 + doc.forEach((block, offset) => {
54 + if (block.type.spec.code) {
55 + blocks.push("ltr");
56 + return;
57 + }
58 + const dir = blockDirection(block) ?? previous;
59 + blocks.push(dir);
60 + if (dir) decorations.push(Decoration.node(offset, offset + block.nodeSize, { dir }));
61 + previous = dir;
62 + });
63 + const directions = { blocks, decorations: DecorationSet.create(doc, decorations) };
64 + docDirections.set(doc, directions);
65 + return directions;
66 +}
67 +
68 +export function caretLineDirection(state: EditorState): TextDirection | null {
69 + return composerTextDirections(state.doc).blocks[state.selection.$head.index(0)] ?? null;
70 +}
71 +
72 +export const ComposerTextDirectionExtension = Extension.create({
73 + name: "composer-text-direction",
74 + addProseMirrorPlugins() {
75 + return [
76 + new Plugin({
77 + key: new PluginKey("composer-text-direction"),
78 + props: {
79 + decorations: (state) => composerTextDirections(state.doc).decorations,
80 + // On Chrome, ProseMirror reads the arrow keys' direction from the
81 + // editor root, so the root follows the line holding the caret.
82 + attributes: (state): Record<string, string> => {
83 + const dir = caretLineDirection(state);
84 + return dir ? { dir } : {};
85 + },
86 + },
87 + }),
88 + ];
89 + },
90 +});
apps/web/src/index.css
+9 -8
@@ -1848,7 +1848,7 @@ code {
1848 custom property, so without this a task-list under a multi-digit ordered
1849 list would inherit the outer gutter instead of its own default. */
1850 --list-gutter: 1.25rem;
1851 - padding-left: 1.25rem;
1851 + padding-inline-start: 1.25rem;
1852 list-style-type: disc;
1853 }
1854
@@ -1859,7 +1859,7 @@ code {
1859 nested ol without its own widened marker doesn't inherit the outer one. */
1860 :is(.chat-markdown, .composer-tiptap) ol {
1861 --list-gutter: 1.25rem;
1862 - padding-left: var(--list-gutter, 1.25rem);
1862 + padding-inline-start: var(--list-gutter, 1.25rem);
1863 list-style-type: decimal;
1864 }
1865
@@ -1912,7 +1912,7 @@ code {
1912 }
1913
1914 .composer-tiptap ul {
1915 - padding-left: max(1.25rem, 2ch);
1915 + padding-inline-start: max(1.25rem, 2ch);
1916 }
1917
1918 :is(.chat-markdown, .composer-tiptap) ul ul {
@@ -1941,7 +1941,8 @@ code {
1941 }
1942
1943 .chat-markdown li.task-list-item input[type="checkbox"] {
1944 - margin: 0 0.35em 0.15em calc(-1 * var(--list-gutter, 1.25rem));
1944 + margin-block: 0 0.15em;
1945 + margin-inline: calc(-1 * var(--list-gutter, 1.25rem)) 0.35em;
1946 vertical-align: middle;
1947 }
1948
@@ -1979,8 +1980,8 @@ code {
1980 }
1981
1982 :is(.chat-markdown, .composer-tiptap) blockquote {
1982 - border-left: 2px solid var(--contrast-border);
1983 - padding-left: 0.8rem;
1983 + border-inline-start: 2px solid var(--contrast-border);
1984 + padding-inline-start: 0.8rem;
1985 color: var(--contrast-muted-foreground);
1986 }
1987
@@ -2132,7 +2133,7 @@ code {
2133 .chat-markdown th,
2134 .chat-markdown td {
2135 padding: 0.45rem 0.75rem;
2135 - text-align: left;
2136 + text-align: start;
2137 }
2138
2139 .chat-markdown thead th {
@@ -2401,7 +2402,7 @@ code {
2402 }
2403
2404 .composer-tiptap ul[data-type="taskList"] ul[data-type="taskList"] {
2404 - padding-left: 1.375rem;
2405 + padding-inline-start: 1.375rem;
2406 }
2407
2408 .composer-tiptap li[data-checked] {
apps/web/src/textDirection.test.ts new
+26
@@ -0,0 +1,26 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { textDirection } from "./textDirection";
4 +
5 +describe("textDirection", () => {
6 + it.each([
7 + ["Arabic", "اكتب دالة تجمع الأرقام", "rtl"],
8 + ["Hebrew", "תקן את הבאג", "rtl"],
9 + ["English", "fix the failing test", "ltr"],
10 + [
11 + "Arabic that opens with an English term",
12 + "StrictMode: يعيد الـ render مرتين في التطوير",
13 + "rtl",
14 + ],
15 + ["English quoting one Arabic word", "translate the label مرحبا for the login screen", "ltr"],
16 + ["a tie, by its first word", "React مكتبة", "ltr"],
17 + ["a tie that opens in Arabic", "مكتبة React", "rtl"],
18 + ["Arabic around numbers and punctuation", "عدّل السطر 42، ثم شغّل الاختبارات (3)", "rtl"],
19 + ])("reads %s", (_, text, direction) => {
20 + expect(textDirection(text)).toBe(direction);
21 + });
22 +
23 + it("leaves text without letters to its surroundings", () => {
24 + expect(textDirection("42 — 7 ✓")).toBeUndefined();
25 + });
26 +});
apps/web/src/textDirection.ts new
+31
@@ -0,0 +1,31 @@
1 +export type TextDirection = "ltr" | "rtl";
2 +
3 +// Hebrew through Arabic Extended-A, their presentation forms, and the
4 +// supplementary right-to-left blocks.
5 +const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u;
6 +const LETTER = /\p{L}/u;
7 +
8 +/**
9 + * The base direction for a block of prose, or undefined when it has no letters.
10 + *
11 + * `dir="auto"` follows the first letter, which lays out an Arabic line that
12 + * opens with an English term (`StrictMode: يعيد الـ render مرتين`) left to
13 + * right, and developers write that way constantly. Counting words keeps such a
14 + * line right to left, while English with one quoted Arabic word stays left to
15 + * right. A tie goes to the first word, as `dir="auto"` would.
16 + */
17 +export function textDirection(text: string): TextDirection | undefined {
18 + let rtlWords = 0;
19 + let ltrWords = 0;
20 + let first: TextDirection | undefined;
21 + for (const word of text.split(/\s+/)) {
22 + const letter = LETTER.exec(word)?.[0];
23 + if (!letter) continue;
24 + const direction = RTL_LETTER.test(letter) ? "rtl" : "ltr";
25 + first ??= direction;
26 + if (direction === "rtl") rtlWords += 1;
27 + else ltrWords += 1;
28 + }
29 + if (rtlWords === ltrWords) return first;
30 + return rtlWords > ltrWords ? "rtl" : "ltr";
31 +}