Skip to content

Commit 3690c86

Browse files
yzn-hclaude
andauthored
fix(web): Arabic and Hebrew text reads and navigates right to left (#22777)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent defb7e6 commit 3690c86

16 files changed

Lines changed: 454 additions & 25 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: 20 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,
@@ -264,6 +265,7 @@ function ComposerMentionNodeView({ node }: NodeViewProps) {
264265
const chip = (
265266
<ContextChip
266267
kind="mention"
268+
dir="ltr"
267269
render={<button type="button" />}
268270
onClick={() => actions.openMention(path)}
269271
aria-label={`Preview ${path}`}
@@ -727,6 +729,7 @@ const ComposerMarkerPlugin = new Plugin({
727729
function decorationsForSelection(state: EditorState): DecorationSet {
728730
const { doc, selection } = state;
729731
const caretSide = caretTakesMarksBefore(state) ? 3 : 0;
732+
const rtl = caretLineDirection(state) === "rtl";
730733
const decorations: Decoration[] = [];
731734
if (!selection.empty) {
732735
doc.nodesBetween(selection.from, selection.to, (node, pos) => {
@@ -750,8 +753,19 @@ function decorationsForSelection(state: EditorState): DecorationSet {
750753
marker.className = "composer-rich-marker";
751754
marker.textContent = text;
752755
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;
753763
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+
}),
755769
);
756770
}
757771
}
@@ -852,6 +866,7 @@ function createComposerExtensions(richText: boolean) {
852866
...(richText ? {} : { bold: false, strike: false }),
853867
}),
854868
ComposerUndoGroupingExtension,
869+
ComposerTextDirectionExtension,
855870
ComposerMentionExtension,
856871
ComposerSkillExtension,
857872
ComposerCitationExtension,
@@ -1146,6 +1161,8 @@ function ComposerPromptEditorTiptapInner(
11461161
editorProps: {
11471162
attributes: editorAttributes,
11481163
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";
11491166
const boundary = event.metaKey
11501167
? event.key === "ArrowLeft" || event.key === "ArrowRight"
11511168
? "lineboundary"
@@ -1171,7 +1188,7 @@ function ComposerPromptEditorTiptapInner(
11711188
event.preventDefault();
11721189
event.stopPropagation();
11731190
const backward =
1174-
event.key === "Home" || event.key === "ArrowLeft" || event.key === "ArrowUp";
1191+
event.key === "Home" || event.key === "ArrowUp" || event.key === backArrow;
11751192
selection.modify(
11761193
event.shiftKey ? "extend" : "move",
11771194
backward ? "backward" : "forward",
@@ -1206,7 +1223,7 @@ function ComposerPromptEditorTiptapInner(
12061223
view.state.selection.empty
12071224
) {
12081225
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;
12101227
const horizontal = event.key === "ArrowLeft" || event.key === "ArrowRight";
12111228
// At the document's ends, native Up/Down can cross a marker without
12121229
// 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"}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
328328
hasPrimaryAction ? (
329329
<ContextChip
330330
kind="mention"
331+
dir="ltr"
331332
render={<a href={href} />}
332333
className={MARKDOWN_FILE_LINK_CLASS_NAME}
333334
data-markdown-copy={copyMarkdown}
@@ -356,6 +357,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
356357
) : (
357358
<ContextChip
358359
kind="mention"
360+
dir="ltr"
359361
render={<button type="button" />}
360362
aria-label={`File options for ${label}`}
361363
aria-haspopup="menu"
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
});

0 commit comments

Comments
 (0)