@devries-cameron20 / t3code-1 / commits / c2dc2eaaf5
Fork 0

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

fix(web,mobile): Hebrew and Arabic read right to left in questions, citations, attachments and diff comments (#24050)

Co-authored-by: maria-rcks <maria@kuuro.net>

Tomer Danan committed Nov 1, 2026 at 04:29 UTC c2dc2eaaf5e66cf9ebebb49af7ca8fa7bd41597e
16 files changed +292 -50
apps/mobile/src/features/threads/PendingUserInputCard.tsx
+46 -4
@@ -2,6 +2,11 @@ import { Button } from "../../components/ui/Button";
2 import { QuestionAttachments } from "./QuestionAttachments";
3 import type { EnvironmentId, RuntimeRequestId } from "@t3tools/contracts";
4 import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
5 +import {
6 + markdownProseDirection,
7 + textDirection,
8 + type TextDirection,
9 +} from "@t3tools/shared/textDirection";
10 import { useRef } from "react";
11 import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
12 import Animated, {
@@ -61,7 +66,19 @@ export interface PendingUserInputCardProps {
66 /** Android cannot hit-test overlays beyond their parent's bounds; render its expanded card in-flow. */
67 const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
68
64 -function QuestionText(props: { readonly markdown: string; readonly environmentId: EnvironmentId }) {
69 +function proseDirectionStyle(text: string, setDirection: TextDirection | undefined) {
70 + const direction = textDirection(text);
71 + return {
72 + ...(direction ? { direction, writingDirection: direction } : null),
73 + textAlign: (direction === "rtl") === (setDirection === "rtl") ? "left" : "right",
74 + } as const;
75 +}
76 +
77 +function QuestionText(props: {
78 + readonly markdown: string;
79 + readonly environmentId: EnvironmentId;
80 + readonly setDirection: TextDirection | undefined;
81 +}) {
82 const styles = useMarkdownPreviewStyles();
83 const markdown = useLiveThreadLinkLabels(props.markdown, props.environmentId);
84 const openLink = useOpenPullRequest();
@@ -69,6 +86,11 @@ function QuestionText(props: { readonly markdown: string; readonly environmentId
86 <SelectableMarkdownText
87 markdown={markdown}
88 textStyle={styles.nativeTextStyle}
89 + writingDirection={markdownProseDirection(markdown)}
90 + // Android's renderer aligns relative to each paragraph's direction.
91 + textAlign={
92 + Platform.OS === "android" ? undefined : props.setDirection === "rtl" ? "right" : "left"
93 + }
94 onLinkPress={(href) => void openLink(href)}
95 />
96 );
@@ -79,6 +101,15 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
101 const canRespond = props.pendingUserInput.responseCapability !== "not_resumable";
102 const isResponding = props.respondingUserInputId === props.pendingUserInput.requestId;
103 const responseDisabled = !canRespond || isResponding;
104 + const setDirection = markdownProseDirection(
105 + props.pendingUserInput.questions
106 + .flatMap((question) => [
107 + question.header,
108 + question.question,
109 + ...question.options.flatMap((option) => [option.label, option.description ?? ""]),
110 + ])
111 + .join(" "),
112 + );
113
114 const cardCoverage = props.cardCoverage;
115 const barHeightRef = useRef(0);
@@ -217,10 +248,17 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
248 const draft = props.drafts[question.id];
249 return (
250 <View key={question.id} className="gap-2 pt-1">
220 - <Text className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted">
251 + <Text
252 + className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted"
253 + style={proseDirectionStyle(question.header, setDirection)}
254 + >
255 {question.header}
256 </Text>
223 - <QuestionText markdown={question.question} environmentId={props.environmentId} />
257 + <QuestionText
258 + markdown={question.question}
259 + environmentId={props.environmentId}
260 + setDirection={setDirection}
261 + />
262 <View className="gap-2">
263 {question.options.map((option) => {
264 const optionValue = option.value ?? option.label.trim();
@@ -251,11 +289,15 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
289 "font-t3-bold text-sm",
290 selected ? "text-foreground" : "text-foreground-secondary",
291 )}
292 + style={proseDirectionStyle(option.label, setDirection)}
293 >
294 {option.label}
295 </Text>
296 {description ? (
258 - <Text className="font-sans text-sm leading-5 text-foreground-muted">
297 + <Text
298 + className="font-sans text-sm leading-5 text-foreground-muted"
299 + style={proseDirectionStyle(description, setDirection)}
300 + >
301 {description}
302 </Text>
303 ) : null}
apps/mobile/src/native/EnrichedMarkdownText.tsx
+10 -6
@@ -264,13 +264,16 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
264 };
265 }, [props.contextClipboardFragment, props.markdown]);
266 const { fontScale } = useWindowDimensions();
267 - const markdownStyle = useMemo(
268 - () => ({
269 - ...enrichedStyle(props.textStyle, themeAppearance === "dark", fontScale),
267 + const markdownStyle = useMemo(() => {
268 + const style = enrichedStyle(props.textStyle, themeAppearance === "dark", fontScale);
269 + return {
270 + ...style,
271 + paragraph: props.textAlign
272 + ? { ...style.paragraph, textAlign: props.textAlign }
273 + : style.paragraph,
274 linkVariants,
271 - }),
272 - [props.textStyle, themeAppearance, fontScale, linkVariants],
273 - );
275 + };
276 + }, [props.textStyle, props.textAlign, themeAppearance, fontScale, linkVariants]);
277 const renderers = renderImage
278 ? {
279 image: (block: MarkdownImageBlock) => {
@@ -312,6 +315,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
315 <EnrichedMarkdownText
316 markdown={markdown}
317 markdownStyle={markdownStyle}
318 + writingDirection={props.writingDirection}
319 onLinksChange={onLinksChange}
320 renderers={renderers}
321 resolveImageSource={resolveNativeImageSource}
apps/mobile/src/native/SelectableMarkdownText.types.ts
+2
@@ -78,4 +78,6 @@ export interface SelectableMarkdownTextProps {
78 readonly onImagePress?: (href: string) => void;
79 readonly marginTop?: number;
80 readonly marginBottom?: number;
81 + readonly writingDirection?: "ltr" | "rtl";
82 + readonly textAlign?: "left" | "right";
83 }
apps/web/src/components/chat/AssistantCitationChip.tsx
+9 -3
@@ -31,6 +31,7 @@ import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCom
31 import { observeAssistantCitationCommentSource } from "./AssistantCitationSource";
32 import { composerFloatingLayerProps } from "./composerEventScope";
33 import { observeResize } from "~/lib/observeResize";
34 +import { textDirection } from "~/textDirection";
35
36 export function AssistantCitationChip({
37 citation,
@@ -130,7 +131,9 @@ export function AssistantCitationChip({
131 aria-label={`View cited assistant text: ${label}`}
132 >
133 <QuoteIcon aria-hidden="true" />
133 - <ContextChipLabel className="max-w-[16em]">{label}</ContextChipLabel>
134 + <ContextChipLabel className="max-w-[16em]" dir={textDirection(label)}>
135 + {label}
136 + </ContextChipLabel>
137 </Link>
138 );
139 if (!composer) {
@@ -268,10 +271,13 @@ function AssistantCitationQuote({ citation }: { citation: AssistantCitation }) {
271 getVirtualizedScrollFadeClassName(fade),
272 )}
273 >
271 - <blockquote className="border-l-2 border-border pl-3 text-muted-foreground">
274 + <blockquote
275 + className="border-l-2 border-border pl-3 text-muted-foreground"
276 + dir={textDirection(citation.text)}
277 + >
278 {citation.text}
279 </blockquote>
274 - {citation.comment ? <p>{citation.comment}</p> : null}
280 + {citation.comment ? <p dir={textDirection(citation.comment)}>{citation.comment}</p> : null}
281 </div>
282 );
283 }
apps/web/src/components/chat/AssistantCitationCommentEditor.tsx
+2
@@ -1,5 +1,6 @@
1 import { ASSISTANT_CITATION_MAX_COMMENT_LENGTH, type AssistantCitation } from "@t3tools/contracts";
2 import { useState, type Ref } from "react";
3 +import { textDirection } from "~/textDirection";
4
5 import { Button } from "../ui/button";
6
@@ -51,6 +52,7 @@ export function AssistantCitationCommentEditor({
52 aria-invalid={commentTooLong || undefined}
53 placeholder="Add an optional comment..."
54 rows={2}
55 + dir={textDirection(comment)}
56 className="field-sizing-content block max-h-40 min-h-16 w-full resize-none bg-transparent px-1 py-1.5 text-base outline-none placeholder:text-muted-foreground sm:text-sm"
57 value={comment}
58 onChange={(event) => {
apps/web/src/components/chat/ComposerPendingUserInputPanel.direction.browser.test.tsx new
+100
@@ -0,0 +1,100 @@
1 +import { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
2 +import { expect, it, vi } from "vite-plus/test";
3 +
4 +vi.mock(import("../ChatMarkdown"), () => ({
5 + default: (({ text }: { text: string }) => <p>{text}</p>) as never,
6 +}));
7 +
8 +import { render } from "../../../test/render";
9 +import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
10 +
11 +type Question = {
12 + header: string;
13 + question: string;
14 + options: { label: string; description: string }[];
15 +};
16 +
17 +const renderPanel = (questions: Question[], questionIndex = 0) =>
18 + render(
19 + <ComposerPendingUserInputPanel
20 + pendingUserInputs={[
21 + {
22 + requestId: RuntimeRequestId.make("question-direction"),
23 + createdAt: "2026-10-23T00:00:00.000Z",
24 + dismissible: false,
25 + responseCapability: "live",
26 + questions: questions.map((question, index) => ({
27 + ...question,
28 + id: `question-${index}`,
29 + multiSelect: false,
30 + })),
31 + },
32 + ]}
33 + cwd={undefined}
34 + threadRef={{ environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") }}
35 + respondingRequestIds={[]}
36 + answers={{}}
37 + questionIndex={questionIndex}
38 + onToggleOption={() => {}}
39 + onAdvance={() => {}}
40 + onDismiss={() => {}}
41 + />,
42 + );
43 +
44 +it("reads a mostly Hebrew question set right to left", async () => {
45 + await using screen = await renderPanel([
46 + {
47 + header: "גישה",
48 + question: "איך לבצע את המיגרציה?",
49 + options: [
50 + {
51 + label: "React Server Components בכל המסכים של האפליקציה",
52 + description: "מסך אחד בכל פעם",
53 + },
54 + { label: "Keep it on React 18", description: "English only" },
55 + ],
56 + },
57 + ]);
58 +
59 + const text = (value: string) => screen.getByText(value, { exact: true });
60 + await expect.element(text("גישה")).toHaveStyle({ direction: "rtl" });
61 + await expect
62 + .element(text("React Server Components בכל המסכים של האפליקציה"))
63 + .toHaveStyle({ direction: "rtl" });
64 + await expect.element(text("מסך אחד בכל פעם")).toHaveStyle({ direction: "rtl" });
65 + await expect
66 + .element(screen.getByRole("button", { name: /React Server/ }))
67 + .toHaveStyle({ direction: "rtl" });
68 + await expect.element(text("Keep it on React 18")).toHaveStyle({ direction: "ltr" });
69 +
70 + await screen.getByTitle("Hide the question and its options").click();
71 + await expect.element(text("איך לבצע את המיגרציה?")).toHaveStyle({ direction: "rtl" });
72 +});
73 +
74 +it("keeps one direction for the whole set when a single question is Hebrew", async () => {
75 + await using screen = await renderPanel(
76 + [
77 + {
78 + header: "Migration",
79 + question: "How should we move to React Server Components?",
80 + options: [
81 + { label: "Screen by screen", description: "Lower risk, each step tested alone." },
82 + { label: "Server Actions for all forms first", description: "Then the rest." },
83 + ],
84 + },
85 + {
86 + header: "גרסה",
87 + question: "בחר גרסה",
88 + options: [{ label: "גרסה 3 (חדשה!)", description: "!!!" }],
89 + },
90 + ],
91 + 1,
92 + );
93 +
94 + await expect
95 + .element(screen.getByRole("button", { name: /גרסה 3/ }))
96 + .toHaveStyle({ direction: "ltr" });
97 + await expect
98 + .element(screen.getByText("גרסה 3 (חדשה!)", { exact: true }))
99 + .toHaveStyle({ direction: "rtl" });
100 +});
apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
+30 -5
@@ -1,4 +1,5 @@
1 import { type RuntimeRequestId, type ScopedThreadRef } from "@t3tools/contracts";
2 +import { markdownProseDirection, textDirection } from "~/textDirection";
3 import { memo, use, useEffect, useEffectEvent, useRef, useState } from "react";
4 import { BackgroundThreadContext } from "./backgroundThread";
5 import { useStableCallback } from "~/hooks/useStableCallback";
@@ -179,8 +180,20 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
180 return null;
181 }
182
183 + const promptDirection = markdownProseDirection(
184 + prompt.questions
185 + .flatMap((question) => [
186 + question.header,
187 + question.question,
188 + ...question.options.flatMap((option) => [option.label, option.description ?? ""]),
189 + ])
190 + .join(" "),
191 + );
192 + const questionTextAlign = promptDirection === "rtl" ? "text-right" : "text-left";
193 +
194 return (
195 <Collapsible
196 + dir={promptDirection}
197 open={!isCollapsed}
198 onOpenChange={(open) => {
199 setCollapsedQuestionId(open ? null : activeQuestion.id);
@@ -197,13 +210,17 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
210 <ComposerBanner.Content>
211 <span
212 className={cn("min-w-0 truncate text-muted-foreground", isCollapsed && "max-w-1/2")}
213 + dir={textDirection(activeQuestion.header)}
214 >
215 {activeQuestion.header}
216 </span>
217 {isCollapsed ? (
218 <>
219 <ComposerBanner.Separator />
206 - <span className="min-w-0 flex-1 truncate text-secondary-label">
220 + <span
221 + className={cn("min-w-0 flex-1 truncate text-secondary-label", questionTextAlign)}
222 + dir={markdownProseDirection(activeQuestion.question)}
223 + >
224 {activeQuestion.question}
225 </span>
226 </>
@@ -245,7 +262,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
262 text={activeQuestion.question}
263 cwd={cwd}
264 threadRef={threadRef}
248 - className="pt-2 text-foreground/85"
265 + className={cn("pt-2 text-foreground/85", questionTextAlign)}
266 />
267 {/* Rows span the header row's width so the radios align with the question text and the shortcut column sits under the dismiss button. */}
268 <div className="-ms-2 mt-1.5 sm:-ms-1.5">
@@ -257,7 +274,8 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
274 const isSelected =
275 isOptimisticallySelected || draftSelectedOptions?.[index] === true;
276 const className = cn(
260 - "group flex w-full items-start gap-2.5 rounded-md bg-transparent py-1.5 ps-2 text-left sm:ps-1.5 outline-none transition-colors duration-150 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/25",
277 + questionTextAlign,
278 + "group flex w-full items-start gap-2.5 rounded-md bg-transparent py-1.5 ps-2 sm:ps-1.5 outline-none transition-colors duration-150 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/25",
279 isSelected ? "text-foreground" : "text-foreground/70 hover:bg-muted/30",
280 (disabled || isResponding) && "opacity-50 cursor-not-allowed",
281 !disabled && !isResponding && "cursor-pointer",
@@ -273,9 +291,16 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
291 )}
292 </span>
293 <div className="min-w-0 flex-1 flex flex-col gap-0.5">
276 - <span className="text-sm font-medium">{option.label}</span>
294 + <span className="text-sm font-medium" dir={textDirection(option.label)}>
295 + {option.label}
296 + </span>
297 {option.description && option.description !== option.label ? (
278 - <span className="text-secondary-label text-2xs">{option.description}</span>
298 + <span
299 + className="text-secondary-label text-2xs"
300 + dir={textDirection(option.description)}
301 + >
302 + {option.description}
303 + </span>
304 ) : null}
305 </div>
306 {index < 9 ? (
apps/web/src/components/chat/MarkdownCodeBlock.tsx
+1 -1
@@ -65,7 +65,7 @@ export function MarkdownCodeBlockFrame({
65 return (
66 <Wrapper
67 dir="ltr"
68 - 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"
68 + className="chat-markdown-codeblock my-[0.65rem] text-start overflow-hidden rounded-lg border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"
69 data-language={language}
70 data-wrap={wrapped ? "true" : "false"}
71 >
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+5 -1
@@ -859,7 +859,7 @@ describe("MessagesTimeline attachments", () => {
859 onOpen={onOpen}
860 />
861 );
862 - await using screen = await renderElement(preview());
862 + await using screen = await renderElement(<div dir="rtl">{preview()}</div>);
863 const audio = screen.container.querySelector("audio")!;
864 const duration = vi.spyOn(audio, "duration", "get").mockReturnValue(Infinity);
865 const play = vi.spyOn(audio, "play").mockResolvedValue();
@@ -884,6 +884,10 @@ describe("MessagesTimeline attachments", () => {
884 audio.dispatchEvent(new Event("durationchange"));
885 });
886 expect(screen.text()).toContain("0:03 / 0:10");
887 + expect(
888 + getComputedStyle(screen.container.querySelector("audio")!.previousElementSibling!)
889 + .direction,
890 + ).toBe("ltr");
891 expect(progress.style.width).toBe("30%");
892 await act(() => {
893 duration.mockReturnValue(NaN);
apps/web/src/components/chat/TimelineUserMessageRow.tsx
+2
@@ -74,6 +74,7 @@ import {
74 import { chatMarkdownClipboardPayload } from "../../markdown-clipboard";
75 import type { ChatMarkdownContextReference } from "../ChatMarkdown";
76 import { cn } from "~/lib/utils";
77 +import { markdownProseDirection } from "~/textDirection";
78 import { useMediaQuery } from "~/hooks/useMediaQuery";
79 import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
80 import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";
@@ -874,6 +875,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
875 <div
876 ref={folded ? revealFoldRef : undefined}
877 hidden={folded && !expanded}
878 + dir={markdownProseDirection(resolvedContext.text)}
879 className={cn(
880 folded && "px-3 pb-3",
881 folded && !ctx.findActive && "max-h-96 overflow-auto",
apps/web/src/components/diffs/DiffCommentAnnotation.tsx
+8 -1
@@ -3,6 +3,7 @@ import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
3
4 import { Button } from "~/components/ui/button";
5 import { Textarea } from "~/components/ui/textarea";
6 +import { textDirection } from "~/textDirection";
7
8 import { isCommentSubmitShortcut } from "./commentSubmitShortcut";
9
@@ -65,7 +66,12 @@ export function DiffCommentAnnotation({
66 onPointerDown={(event) => event.stopPropagation()}
67 >
68 <MessageCircle className="size-3.5 h-5 shrink-0 text-primary/70" aria-hidden="true" />
68 - <p className="min-w-0 flex-1 whitespace-pre-wrap text-sm leading-5">{displayedText}</p>
69 + <p
70 + className="min-w-0 flex-1 whitespace-pre-wrap text-sm leading-5"
71 + dir={textDirection(displayedText)}
72 + >
73 + {displayedText}
74 + </p>
75 {onDelete ? (
76 <span className="-my-1 -mr-1 flex shrink-0 opacity-0 transition-opacity group-hover/comment:opacity-100 focus-within:opacity-100 max-sm:opacity-100">
77 <Button
@@ -95,6 +101,7 @@ export function DiffCommentAnnotation({
101 autoFocus={focusOnMount}
102 size="sm"
103 value={displayedText}
104 + dir={textDirection(displayedText)}
105 placeholder={placeholder}
106 aria-label={`Comment on lines ${rangeLabel}`}
107 onChange={(event) => (onTextChange ?? setLocalDraftText)(event.target.value)}
apps/web/src/components/files/AudioPreview.tsx
+1 -1
@@ -156,7 +156,7 @@ function AudioChip(props: AudioPreviewProps) {
156 middleTruncateAttachmentName(props.name)
157 )}
158 </ContextChipLabel>
159 - <span className="shrink-0 self-baseline text-3xs text-current">
159 + <span dir="ltr" className="shrink-0 self-baseline text-3xs text-current">
160 {props.failed
161 ? "Unavailable"
162 : loading
apps/web/src/textDirection.test.ts
+37 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { textDirection } from "./textDirection";
3 +import { markdownProseDirection, textDirection } from "./textDirection";
4
5 describe("textDirection", () => {
6 it.each([
@@ -24,3 +24,39 @@ describe("textDirection", () => {
24 expect(textDirection("42 — 7 ✓")).toBeUndefined();
25 });
26 });
27 +
28 +describe("markdownProseDirection", () => {
29 + it.each([
30 + [
31 + "Hebrew around a code block",
32 + "תתקן את זה:\n```ts\nexport function useCheckout(props: CheckoutProps) {\n return props.items.length;\n}\n```\nותריץ שוב",
33 + "rtl",
34 + ],
35 + ["Hebrew around inline code", "לערוך את `apps/web/src/chat.tsx` או להשאיר `useMemo`?", "rtl"],
36 + ["Hebrew around double-backtick code", "תבדוק ``const a = `b c d e` + f`` עכשיו", "rtl"],
37 + [
38 + "Hebrew after a four-backtick fence",
39 + "````md\none two three four five six\n````\nשלום עולם, זה עובד",
40 + "rtl",
41 + ],
42 + [
43 + "Hebrew after a tilde fence",
44 + "~~~\nnpm run build --filter web --force\n~~~\nזה נכשל אצלי",
45 + "rtl",
46 + ],
47 + [
48 + "Hebrew before an unclosed fence",
49 + "שלום, הנה השגיאה:\n```\nError: cannot find module react dom client",
50 + "rtl",
51 + ],
52 + ["Hebrew around a URL", "ראה https://github.com/pingdotgg/t3code/pull/24050 לפני", "rtl"],
53 + ["English around inline code", "Should I edit `useMemo` or keep it?", "ltr"],
54 + ["English quoting one Hebrew word", "Please check the שלום label before the release", "ltr"],
55 + ])("reads %s", (_, markdown, direction) => {
56 + expect(markdownProseDirection(markdown)).toBe(direction);
57 + });
58 +
59 + it("leaves markdown without prose letters to its surroundings", () => {
60 + expect(markdownProseDirection("```\nconst a = 1;\n```")).toBeUndefined();
61 + });
62 +});
apps/web/src/textDirection.ts
+1 -27
@@ -1,27 +1 @@
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 - * `dir="auto"` misreads Arabic prose that opens with an English term.
10 - * Count words so mixed prose follows its main language; break ties with the first word.
11 - */
12 -export function textDirection(text: string): TextDirection | undefined {
13 - if (!RTL_LETTER.test(text)) return LETTER.test(text) ? "ltr" : undefined;
14 - let rtlWords = 0;
15 - let ltrWords = 0;
16 - let first: TextDirection | undefined;
17 - for (const word of text.split(/\s+/)) {
18 - const letter = LETTER.exec(word)?.[0];
19 - if (!letter) continue;
20 - const direction = RTL_LETTER.test(letter) ? "rtl" : "ltr";
21 - first ??= direction;
22 - if (direction === "rtl") rtlWords += 1;
23 - else ltrWords += 1;
24 - }
25 - if (rtlWords === ltrWords) return first;
26 - return rtlWords > ltrWords ? "rtl" : "ltr";
27 -}
1 +export * from "@t3tools/shared/textDirection";
packages/shared/package.json
+4
@@ -31,6 +31,10 @@
31 "types": "./src/themePreview.ts",
32 "import": "./src/themePreview.ts"
33 },
34 + "./textDirection": {
35 + "types": "./src/textDirection.ts",
36 + "import": "./src/textDirection.ts"
37 + },
38 "./projectFavicon": {
39 "types": "./src/projectFavicon.ts",
40 "import": "./src/projectFavicon.ts"
packages/shared/src/textDirection.ts new
+34
@@ -0,0 +1,34 @@
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 + * `dir="auto"` misreads Arabic prose that opens with an English term.
10 + * Count words so mixed prose follows its main language; break ties with the first word.
11 + */
12 +export function textDirection(text: string): TextDirection | undefined {
13 + if (!RTL_LETTER.test(text)) return LETTER.test(text) ? "ltr" : undefined;
14 + let rtlWords = 0;
15 + let ltrWords = 0;
16 + let first: TextDirection | undefined;
17 + for (const word of text.split(/\s+/)) {
18 + const letter = LETTER.exec(word)?.[0];
19 + if (!letter) continue;
20 + const direction = RTL_LETTER.test(letter) ? "rtl" : "ltr";
21 + first ??= direction;
22 + if (direction === "rtl") rtlWords += 1;
23 + else ltrWords += 1;
24 + }
25 + if (rtlWords === ltrWords) return first;
26 + return rtlWords > ltrWords ? "rtl" : "ltr";
27 +}
28 +
29 +const MARKDOWN_CODE_OR_URL =
30 + /(`{3,}|~{3,})[\s\S]*?(?:\1|$)|(`{1,2})(?!`)[\s\S]*?(?<!`)\2(?!`)|https?:\/\/\S+/g;
31 +
32 +export function markdownProseDirection(markdown: string): TextDirection | undefined {
33 + return textDirection(markdown.replace(MARKDOWN_CODE_OR_URL, " "));
34 +}