Skip to content

Commit 2967192

Browse files
yzn-hclaude
andcommitted
fix(web): Arabic and Hebrew text reads and navigates right to left
Every block in the composer and in chat messages was laid out with a left-to-right base direction, so Arabic and Hebrew lines were left aligned, their punctuation landed on the wrong side, list markers and quote rules sat on the left, and English terms or inline code inside a line reordered the words around them. Each top-level block now takes the direction of most of its words, with inline code left out of the count and isolated left to right. Code blocks stay left to right. List, quote and table spacing use logical properties, and thread titles in the sidebar, header and command palette follow their own text. In the composer, the custom arrow handling and ProseMirror's own both assumed ArrowLeft moves back. The editor root now follows the caret's line, which is where ProseMirror reads direction on Chrome, and the handler reads the same direction, so the caret no longer sticks at the edge of inline code in a right-to-left line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 21da306 commit 2967192

14 files changed

Lines changed: 385 additions & 24 deletions

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ import { MarkdownExternalLinkContent } from "./chat/MarkdownExternalLink";
202202
import { MarkdownFileLink } from "./chat/MarkdownFileLink";
203203
import { canUseMarkdownFileShellActions } from "./chat/MarkdownFileLink.logic";
204204
import { handleMarkdownFragmentClick, rehypeHeadingIds } from "./chat/markdownFragments";
205+
import { rehypeTextDirection } from "./chat/markdownTextDirection";
205206
import { hastHasText, hastPlainTextDeep, plainHastText } from "./chat/markdownHast.logic";
206207
import {
207208
extractCodeBlock,
@@ -384,11 +385,13 @@ function normalizeMarkdownLinkHrefKey(href: string): string {
384385
const CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS = [
385386
...CHAT_MARKDOWN_REHYPE_PLUGINS,
386387
rehypeHeadingIds,
388+
rehypeTextDirection,
387389
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
388390

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"]>;
392395

393396
const NO_MARKDOWN_EDITORS: ReadonlyArray<EditorId> = [];
394397

@@ -975,7 +978,11 @@ const CHAT_MARKDOWN_COMPONENTS = {
975978
return <blockquote {...props}>{children}</blockquote>;
976979
}
977980
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+
>
979986
<p
980987
data-thread-find-ignore="true"
981988
className={cn("flex items-center gap-1.5 font-medium", alert.titleClassName)}

‎apps/web/src/components/CommandPaletteResults.tsx‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react";
33
import { ChevronRightIcon } from "lucide-react";
44
import { type ReactNode, type RefObject, useState } from "react";
55
import { cn } from "~/lib/utils";
6+
import { textDirection } from "~/textDirection";
67
import { shortcutLabelForCommand } from "../keybindings";
78
import {
89
type CommandPaletteActionItem,
@@ -154,6 +155,14 @@ export function CommandPaletteTitleIcon(props: { children: ReactNode }) {
154155
return <span className="flex h-5 shrink-0 items-center self-start pt-0.5">{props.children}</span>;
155156
}
156157

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+
157166
function DisabledCommandPaletteResultRow(props: {
158167
item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
159168
}) {
@@ -164,7 +173,7 @@ function DisabledCommandPaletteResultRow(props: {
164173
<span className="flex min-w-0 flex-1 flex-col">
165174
<span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
166175
{props.item.titleLeadingContent}
167-
<span className="truncate">{props.item.title}</span>
176+
<CommandPaletteTitle title={props.item.title} />
168177
</span>
169178
{props.item.threadContentMatch ? (
170179
<ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
@@ -178,7 +187,7 @@ function DisabledCommandPaletteResultRow(props: {
178187
) : (
179188
<span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
180189
{props.item.titleLeadingContent}
181-
<span className="truncate">{props.item.title}</span>
190+
<CommandPaletteTitle title={props.item.title} />
182191
</span>
183192
)}
184193
{props.item.titleTrailingContent}
@@ -214,7 +223,7 @@ function CommandPaletteResultRow(props: {
214223
<span className="flex min-w-0 flex-1 flex-col">
215224
<span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
216225
{props.item.titleLeadingContent}
217-
<span className="truncate">{props.item.title}</span>
226+
<CommandPaletteTitle title={props.item.title} />
218227
</span>
219228
{props.item.threadContentMatch ? (
220229
<ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
@@ -228,7 +237,7 @@ function CommandPaletteResultRow(props: {
228237
) : (
229238
<span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
230239
{props.item.titleLeadingContent}
231-
<span className="truncate">{props.item.title}</span>
240+
<CommandPaletteTitle title={props.item.title} />
232241
</span>
233242
)}
234243
{props.item.titleTrailingContent}

‎apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ import {
1010
import type { ServerProviderSkill } from "@t3tools/contracts";
1111
import type { Editor } from "@tiptap/core";
1212
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";
1415

1516
import { act, render } from "../../test/render";
1617

@@ -352,3 +353,63 @@ describe("composer context undo lifetime", () => {
352353
},
353354
);
354355
});
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‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import {
5656
pastedPathQueryLength,
5757
} from "~/composer-logic";
5858
import { useStableCallback } from "~/hooks/useStableCallback";
59+
import { caretLineDirection, ComposerTextDirectionExtension } from "~/composer-text-direction";
5960
import {
6061
collectComposerPromptInlineTokens,
6162
selectionTouchesMentionBoundary,
@@ -727,6 +728,7 @@ const ComposerMarkerPlugin = new Plugin({
727728
function decorationsForSelection(state: EditorState): DecorationSet {
728729
const { doc, selection } = state;
729730
const caretSide = caretTakesMarksBefore(state) ? 3 : 0;
731+
const rtl = caretLineDirection(state) === "rtl";
730732
const decorations: Decoration[] = [];
731733
if (!selection.empty) {
732734
doc.nodesBetween(selection.from, selection.to, (node, pos) => {
@@ -750,8 +752,19 @@ function decorationsForSelection(state: EditorState): DecorationSet {
750752
marker.className = "composer-rich-marker";
751753
marker.textContent = text;
752754
marker.setAttribute("aria-hidden", "true");
755+
// Inline code is isolated left to right. In a right-to-left line its
756+
// opening backtick joins the closing one inside the isolate, or the line
757+
// would put both on the same side of the code.
758+
const codeMarks =
759+
rtl && baseSide === -1 && /^`+$/.test(text)
760+
? doc.resolve(at).nodeAfter?.marks.filter((mark) => mark.type.spec.code)
761+
: undefined;
753762
decorations.push(
754-
Decoration.widget(at, marker, { side, key: `marker-${at}-${side}-${marker.textContent}` }),
763+
Decoration.widget(at, marker, {
764+
side,
765+
key: `marker-${at}-${side}-${marker.textContent}`,
766+
...(codeMarks?.length ? { marks: codeMarks } : {}),
767+
}),
755768
);
756769
}
757770
}
@@ -852,6 +865,7 @@ function createComposerExtensions(richText: boolean) {
852865
...(richText ? {} : { bold: false, strike: false }),
853866
}),
854867
ComposerUndoGroupingExtension,
868+
ComposerTextDirectionExtension,
855869
ComposerMentionExtension,
856870
ComposerSkillExtension,
857871
ComposerCitationExtension,
@@ -1146,6 +1160,8 @@ function ComposerPromptEditorTiptapInner(
11461160
editorProps: {
11471161
attributes: editorAttributes,
11481162
handleKeyDown: (view, event) => {
1163+
// In a right-to-left line the start is on the right.
1164+
const backArrow = caretLineDirection(view.state) === "rtl" ? "ArrowRight" : "ArrowLeft";
11491165
const boundary = event.metaKey
11501166
? event.key === "ArrowLeft" || event.key === "ArrowRight"
11511167
? "lineboundary"
@@ -1171,7 +1187,7 @@ function ComposerPromptEditorTiptapInner(
11711187
event.preventDefault();
11721188
event.stopPropagation();
11731189
const backward =
1174-
event.key === "Home" || event.key === "ArrowLeft" || event.key === "ArrowUp";
1190+
event.key === "Home" || event.key === "ArrowUp" || event.key === backArrow;
11751191
selection.modify(
11761192
event.shiftKey ? "extend" : "move",
11771193
backward ? "backward" : "forward",
@@ -1206,7 +1222,7 @@ function ComposerPromptEditorTiptapInner(
12061222
view.state.selection.empty
12071223
) {
12081224
const { $from } = view.state.selection;
1209-
const direction = event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 1;
1225+
const direction = event.key === "ArrowUp" || event.key === backArrow ? -1 : 1;
12101226
const horizontal = event.key === "ArrowLeft" || event.key === "ArrowRight";
12111227
// At the document's ends, native Up/Down can cross a marker without
12121228
// changing the document position. Record the stop so DOM selection

‎apps/web/src/components/chat/ChatHeader.tsx‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
} from "../WorkspaceBreadcrumb";
3636
import { observeResize } from "~/lib/observeResize";
3737
import { cn } from "~/lib/utils";
38+
import { textDirection } from "~/textDirection";
3839
import { useClientSettings } from "../../hooks/useSettings";
3940

4041
interface ChatHeaderProps {
@@ -342,6 +343,7 @@ export const ChatHeader = memo(function ChatHeader({
342343
{renamingTitle !== null ? (
343344
<input
344345
autoFocus
346+
dir="auto"
345347
aria-label="Thread title"
346348
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"
347349
defaultValue={renamingTitle}
@@ -375,7 +377,7 @@ export const ChatHeader = memo(function ChatHeader({
375377
/>
376378
}
377379
>
378-
<h2 className="min-w-0">
380+
<h2 className="min-w-0" dir={textDirection(activeThreadTitle)}>
379381
<WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
380382
</h2>
381383
<ChevronDownIcon
@@ -389,7 +391,13 @@ export const ChatHeader = memo(function ChatHeader({
389391
) : (
390392
<Tooltip>
391393
<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+
}
393401
>
394402
<WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
395403
</TooltipTrigger>

‎apps/web/src/components/chat/MarkdownCodeBlock.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ export function MarkdownCodeBlockFrame({
6060
}) {
6161
return (
6262
<Wrapper
63+
dir="ltr"
6364
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"
6465
data-language={language}
6566
data-wrap={wrapped ? "true" : "false"}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
function proseText(node: HastNode): string {
12+
if (node.type === "text") return node.value ?? "";
13+
if (node.tagName === "code") return " ";
14+
return (node.children ?? []).map(proseText).join("");
15+
}
16+
17+
function isolateInlineCode(node: HastNode): void {
18+
if (node.tagName === "pre") return;
19+
if (node.tagName === "code") {
20+
node.properties = { ...node.properties, dir: "ltr" };
21+
return;
22+
}
23+
node.children?.forEach(isolateInlineCode);
24+
}
25+
26+
/**
27+
* Gives each top-level block the direction of its own words, so an Arabic or
28+
* Hebrew reply reads right to left beside English ones. Lines inside a list or
29+
* quote follow it, keeping markers and rules on one side. Inline code is left
30+
* out of the count and isolated left to right, so its punctuation stays put.
31+
*/
32+
export function rehypeTextDirection() {
33+
return (tree: HastNode) => {
34+
for (const block of tree.children ?? []) {
35+
if (block.type !== "element" || block.tagName === "pre") continue;
36+
const dir = textDirection(proseText(block));
37+
if (dir) block.properties = { ...block.properties, dir };
38+
}
39+
isolateInlineCode(tree);
40+
};
41+
}

‎apps/web/src/components/sidebar/SidebarThreadRow.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ import { formatRelativeTimeLabel, parseTimestampDate } from "../../timestampForm
7070
import type { SidebarThreadSummary } from "../../types";
7171
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
7272
import { cn } from "~/lib/utils";
73+
import { textDirection } from "~/textDirection";
7374
import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
7475
import {
7576
animateSidebarLayoutChanges,
@@ -940,6 +941,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
940941
<input
941942
autoFocus
942943
value={renamingTitle}
944+
dir="auto"
943945
aria-label="Thread title"
944946
onChange={(event) => onRenameTitleChange(event.target.value)}
945947
onFocus={(event) => event.currentTarget.select()}
@@ -978,6 +980,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
978980
),
979981
isRegeneratingTitle && "opacity-55",
980982
)}
983+
dir={textDirection(thread.title)}
981984
>
982985
{thread.title}
983986
</span>

‎apps/web/src/composer-rich-text-doc.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,9 +126,14 @@ function codePairCaretPlugin(type: MarkType) {
126126
*/
127127
export const ComposerCodeExtension = Code.extend({
128128
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.
131131
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+
},
132137
addProseMirrorPlugins() {
133138
return [...(this.parent?.() ?? []), codePairCaretPlugin(this.type)];
134139
},

0 commit comments

Comments
 (0)