TypeScript
fix(web,mobile): Hebrew and Arabic read right to left in questions, citations, attachments and diff comments (#24050)
Tomer Dananc2dc2eaaf5e6
diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsxindex 9ecbbb70f1d..523d8027519 100644--- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx+++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx@@ -2,6 +2,11 @@ import { Button } from "../../components/ui/Button";import { QuestionAttachments } from "./QuestionAttachments";import type { EnvironmentId, RuntimeRequestId } from "@t3tools/contracts";import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";+import {+ markdownProseDirection,+ textDirection,+ type TextDirection,+} from "@t3tools/shared/textDirection";import { useRef } from "react";import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";import Animated, {@@ -61,7 +66,19 @@ export interface PendingUserInputCardProps {/** Android cannot hit-test overlays beyond their parent's bounds; render its expanded card in-flow. */const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";-function QuestionText(props: { readonly markdown: string; readonly environmentId: EnvironmentId }) {+function proseDirectionStyle(text: string, setDirection: TextDirection | undefined) {+ const direction = textDirection(text);+ return {+ ...(direction ? { direction, writingDirection: direction } : null),+ textAlign: (direction === "rtl") === (setDirection === "rtl") ? "left" : "right",+ } as const;+}++function QuestionText(props: {+ readonly markdown: string;+ readonly environmentId: EnvironmentId;+ readonly setDirection: TextDirection | undefined;+}) {const styles = useMarkdownPreviewStyles();const markdown = useLiveThreadLinkLabels(props.markdown, props.environmentId);const openLink = useOpenPullRequest();@@ -69,6 +86,11 @@ function QuestionText(props: { readonly markdown: string; readonly environmentId<SelectableMarkdownTextmarkdown={markdown}textStyle={styles.nativeTextStyle}+ writingDirection={markdownProseDirection(markdown)}+ // Android's renderer aligns relative to each paragraph's direction.+ textAlign={+ Platform.OS === "android" ? undefined : props.setDirection === "rtl" ? "right" : "left"+ }onLinkPress={(href) => void openLink(href)}/>);@@ -79,6 +101,15 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {const canRespond = props.pendingUserInput.responseCapability !== "not_resumable";const isResponding = props.respondingUserInputId === props.pendingUserInput.requestId;const responseDisabled = !canRespond || isResponding;+ const setDirection = markdownProseDirection(+ props.pendingUserInput.questions+ .flatMap((question) => [+ question.header,+ question.question,+ ...question.options.flatMap((option) => [option.label, option.description ?? ""]),+ ])+ .join(" "),+ );const cardCoverage = props.cardCoverage;const barHeightRef = useRef(0);@@ -217,10 +248,17 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {const draft = props.drafts[question.id];return (<View key={question.id} className="gap-2 pt-1">- <Text className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted">+ <Text+ className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted"+ style={proseDirectionStyle(question.header, setDirection)}+ >{question.header}</Text>- <QuestionText markdown={question.question} environmentId={props.environmentId} />+ <QuestionText+ markdown={question.question}+ environmentId={props.environmentId}+ setDirection={setDirection}+ /><View className="gap-2">{question.options.map((option) => {const optionValue = option.value ?? option.label.trim();@@ -251,11 +289,15 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {"font-t3-bold text-sm",selected ? "text-foreground" : "text-foreground-secondary",)}+ style={proseDirectionStyle(option.label, setDirection)}>{option.label}</Text>{description ? (- <Text className="font-sans text-sm leading-5 text-foreground-muted">+ <Text+ className="font-sans text-sm leading-5 text-foreground-muted"+ style={proseDirectionStyle(description, setDirection)}+ >{description}</Text>) : null}diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsxindex 13739f0f24a..6fa8c229a95 100644--- a/apps/mobile/src/native/EnrichedMarkdownText.tsx+++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx@@ -264,13 +264,16 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {};}, [props.contextClipboardFragment, props.markdown]);const { fontScale } = useWindowDimensions();- const markdownStyle = useMemo(- () => ({- ...enrichedStyle(props.textStyle, themeAppearance === "dark", fontScale),+ const markdownStyle = useMemo(() => {+ const style = enrichedStyle(props.textStyle, themeAppearance === "dark", fontScale);+ return {+ ...style,+ paragraph: props.textAlign+ ? { ...style.paragraph, textAlign: props.textAlign }+ : style.paragraph,linkVariants,- }),- [props.textStyle, themeAppearance, fontScale, linkVariants],- );+ };+ }, [props.textStyle, props.textAlign, themeAppearance, fontScale, linkVariants]);const renderers = renderImage? {image: (block: MarkdownImageBlock) => {@@ -312,6 +315,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {<EnrichedMarkdownTextmarkdown={markdown}markdownStyle={markdownStyle}+ writingDirection={props.writingDirection}onLinksChange={onLinksChange}renderers={renderers}resolveImageSource={resolveNativeImageSource}diff --git a/apps/mobile/src/native/SelectableMarkdownText.types.ts b/apps/mobile/src/native/SelectableMarkdownText.types.tsindex ddb40d22db3..68600701526 100644--- a/apps/mobile/src/native/SelectableMarkdownText.types.ts+++ b/apps/mobile/src/native/SelectableMarkdownText.types.ts@@ -78,4 +78,6 @@ export interface SelectableMarkdownTextProps {readonly onImagePress?: (href: string) => void;readonly marginTop?: number;readonly marginBottom?: number;+ readonly writingDirection?: "ltr" | "rtl";+ readonly textAlign?: "left" | "right";}diff --git a/apps/web/src/components/chat/AssistantCitationChip.tsx b/apps/web/src/components/chat/AssistantCitationChip.tsxindex cbe5ad8cddb..2b90b09f68e 100644--- a/apps/web/src/components/chat/AssistantCitationChip.tsx+++ b/apps/web/src/components/chat/AssistantCitationChip.tsx@@ -31,6 +31,7 @@ import { resolveAssistantCitationCommentDismissal } from "./assistantCitationComimport { observeAssistantCitationCommentSource } from "./AssistantCitationSource";import { composerFloatingLayerProps } from "./composerEventScope";import { observeResize } from "~/lib/observeResize";+import { textDirection } from "~/textDirection";export function AssistantCitationChip({citation,@@ -130,7 +131,9 @@ export function AssistantCitationChip({aria-label={`View cited assistant text: ${label}`}><QuoteIcon aria-hidden="true" />- <ContextChipLabel className="max-w-[16em]">{label}</ContextChipLabel>+ <ContextChipLabel className="max-w-[16em]" dir={textDirection(label)}>+ {label}+ </ContextChipLabel></Link>);if (!composer) {@@ -268,10 +271,13 @@ function AssistantCitationQuote({ citation }: { citation: AssistantCitation }) {getVirtualizedScrollFadeClassName(fade),)}>- <blockquote className="border-l-2 border-border pl-3 text-muted-foreground">+ <blockquote+ className="border-l-2 border-border pl-3 text-muted-foreground"+ dir={textDirection(citation.text)}+ >{citation.text}</blockquote>- {citation.comment ? <p>{citation.comment}</p> : null}+ {citation.comment ? <p dir={textDirection(citation.comment)}>{citation.comment}</p> : null}</div>);}diff --git a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsxindex d9fd6064561..0a8357bb9ba 100644--- a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx+++ b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx@@ -1,5 +1,6 @@import { ASSISTANT_CITATION_MAX_COMMENT_LENGTH, type AssistantCitation } from "@t3tools/contracts";import { useState, type Ref } from "react";+import { textDirection } from "~/textDirection";import { Button } from "../ui/button";@@ -51,6 +52,7 @@ export function AssistantCitationCommentEditor({aria-invalid={commentTooLong || undefined}placeholder="Add an optional comment..."rows={2}+ dir={textDirection(comment)}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"value={comment}onChange={(event) => {diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.direction.browser.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.direction.browser.test.tsxnew file mode 100644index 00000000000..6e1b387a741--- /dev/null+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.direction.browser.test.tsx@@ -0,0 +1,100 @@+import { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";+import { expect, it, vi } from "vite-plus/test";++vi.mock(import("../ChatMarkdown"), () => ({+ default: (({ text }: { text: string }) => <p>{text}</p>) as never,+}));++import { render } from "../../../test/render";+import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";++type Question = {+ header: string;+ question: string;+ options: { label: string; description: string }[];+};++const renderPanel = (questions: Question[], questionIndex = 0) =>+ render(+ <ComposerPendingUserInputPanel+ pendingUserInputs={[+ {+ requestId: RuntimeRequestId.make("question-direction"),+ createdAt: "2026-10-23T00:00:00.000Z",+ dismissible: false,+ responseCapability: "live",+ questions: questions.map((question, index) => ({+ ...question,+ id: `question-${index}`,+ multiSelect: false,+ })),+ },+ ]}+ cwd={undefined}+ threadRef={{ environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") }}+ respondingRequestIds={[]}+ answers={{}}+ questionIndex={questionIndex}+ onToggleOption={() => {}}+ onAdvance={() => {}}+ onDismiss={() => {}}+ />,+ );++it("reads a mostly Hebrew question set right to left", async () => {+ await using screen = await renderPanel([+ {+ header: "גישה",+ question: "איך לבצע את המיגרציה?",+ options: [+ {+ label: "React Server Components בכל המסכים של האפליקציה",+ description: "מסך אחד בכל פעם",+ },+ { label: "Keep it on React 18", description: "English only" },+ ],+ },+ ]);++ const text = (value: string) => screen.getByText(value, { exact: true });+ await expect.element(text("גישה")).toHaveStyle({ direction: "rtl" });+ await expect+ .element(text("React Server Components בכל המסכים של האפליקציה"))+ .toHaveStyle({ direction: "rtl" });+ await expect.element(text("מסך אחד בכל פעם")).toHaveStyle({ direction: "rtl" });+ await expect+ .element(screen.getByRole("button", { name: /React Server/ }))+ .toHaveStyle({ direction: "rtl" });+ await expect.element(text("Keep it on React 18")).toHaveStyle({ direction: "ltr" });++ await screen.getByTitle("Hide the question and its options").click();+ await expect.element(text("איך לבצע את המיגרציה?")).toHaveStyle({ direction: "rtl" });+});++it("keeps one direction for the whole set when a single question is Hebrew", async () => {+ await using screen = await renderPanel(+ [+ {+ header: "Migration",+ question: "How should we move to React Server Components?",+ options: [+ { label: "Screen by screen", description: "Lower risk, each step tested alone." },+ { label: "Server Actions for all forms first", description: "Then the rest." },+ ],+ },+ {+ header: "גרסה",+ question: "בחר גרסה",+ options: [{ label: "גרסה 3 (חדשה!)", description: "!!!" }],+ },+ ],+ 1,+ );++ await expect+ .element(screen.getByRole("button", { name: /גרסה 3/ }))+ .toHaveStyle({ direction: "ltr" });+ await expect+ .element(screen.getByText("גרסה 3 (חדשה!)", { exact: true }))+ .toHaveStyle({ direction: "rtl" });+});diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsxindex 37a002e2c27..a19e7f205ce 100644--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx@@ -1,4 +1,5 @@import { type RuntimeRequestId, type ScopedThreadRef } from "@t3tools/contracts";+import { markdownProseDirection, textDirection } from "~/textDirection";import { memo, use, useEffect, useEffectEvent, useRef, useState } from "react";import { BackgroundThreadContext } from "./backgroundThread";import { useStableCallback } from "~/hooks/useStableCallback";@@ -179,8 +180,20 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(return null;}+ const promptDirection = markdownProseDirection(+ prompt.questions+ .flatMap((question) => [+ question.header,+ question.question,+ ...question.options.flatMap((option) => [option.label, option.description ?? ""]),+ ])+ .join(" "),+ );+ const questionTextAlign = promptDirection === "rtl" ? "text-right" : "text-left";+return (<Collapsible+ dir={promptDirection}open={!isCollapsed}onOpenChange={(open) => {setCollapsedQuestionId(open ? null : activeQuestion.id);@@ -197,13 +210,17 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(<ComposerBanner.Content><spanclassName={cn("min-w-0 truncate text-muted-foreground", isCollapsed && "max-w-1/2")}+ dir={textDirection(activeQuestion.header)}>{activeQuestion.header}</span>{isCollapsed ? (<><ComposerBanner.Separator />- <span className="min-w-0 flex-1 truncate text-secondary-label">+ <span+ className={cn("min-w-0 flex-1 truncate text-secondary-label", questionTextAlign)}+ dir={markdownProseDirection(activeQuestion.question)}+ >{activeQuestion.question}</span></>@@ -245,7 +262,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(text={activeQuestion.question}cwd={cwd}threadRef={threadRef}- className="pt-2 text-foreground/85"+ className={cn("pt-2 text-foreground/85", questionTextAlign)}/>{/* Rows span the header row's width so the radios align with the question text and the shortcut column sits under the dismiss button. */}<div className="-ms-2 mt-1.5 sm:-ms-1.5">@@ -257,7 +274,8 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(const isSelected =isOptimisticallySelected || draftSelectedOptions?.[index] === true;const className = cn(- "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",+ questionTextAlign,+ "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",isSelected ? "text-foreground" : "text-foreground/70 hover:bg-muted/30",(disabled || isResponding) && "opacity-50 cursor-not-allowed",!disabled && !isResponding && "cursor-pointer",@@ -273,9 +291,16 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard()}</span><div className="min-w-0 flex-1 flex flex-col gap-0.5">- <span className="text-sm font-medium">{option.label}</span>+ <span className="text-sm font-medium" dir={textDirection(option.label)}>+ {option.label}+ </span>{option.description && option.description !== option.label ? (- <span className="text-secondary-label text-2xs">{option.description}</span>+ <span+ className="text-secondary-label text-2xs"+ dir={textDirection(option.description)}+ >+ {option.description}+ </span>) : null}</div>{index < 9 ? (diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.tsx b/apps/web/src/components/chat/MarkdownCodeBlock.tsxindex 6b1822aac14..301843c4ebe 100644--- a/apps/web/src/components/chat/MarkdownCodeBlock.tsx+++ b/apps/web/src/components/chat/MarkdownCodeBlock.tsx@@ -65,7 +65,7 @@ export function MarkdownCodeBlockFrame({return (<Wrapperdir="ltr"- 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"+ 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"data-language={language}data-wrap={wrapped ? "true" : "false"}>diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsxindex 7fd73739d91..2fcaa596a5b 100644--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx@@ -859,7 +859,7 @@ describe("MessagesTimeline attachments", () => {onOpen={onOpen}/>);- await using screen = await renderElement(preview());+ await using screen = await renderElement(<div dir="rtl">{preview()}</div>);const audio = screen.container.querySelector("audio")!;const duration = vi.spyOn(audio, "duration", "get").mockReturnValue(Infinity);const play = vi.spyOn(audio, "play").mockResolvedValue();@@ -884,6 +884,10 @@ describe("MessagesTimeline attachments", () => {audio.dispatchEvent(new Event("durationchange"));});expect(screen.text()).toContain("0:03 / 0:10");+ expect(+ getComputedStyle(screen.container.querySelector("audio")!.previousElementSibling!)+ .direction,+ ).toBe("ltr");expect(progress.style.width).toBe("30%");await act(() => {duration.mockReturnValue(NaN);diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsxindex e73f5d1d1e9..dfda2a18938 100644--- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx+++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx@@ -74,6 +74,7 @@ import {import { chatMarkdownClipboardPayload } from "../../markdown-clipboard";import type { ChatMarkdownContextReference } from "../ChatMarkdown";import { cn } from "~/lib/utils";+import { markdownProseDirection } from "~/textDirection";import { useMediaQuery } from "~/hooks/useMediaQuery";import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";@@ -874,6 +875,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"<divref={folded ? revealFoldRef : undefined}hidden={folded && !expanded}+ dir={markdownProseDirection(resolvedContext.text)}className={cn(folded && "px-3 pb-3",folded && !ctx.findActive && "max-h-96 overflow-auto",diff --git a/apps/web/src/components/diffs/DiffCommentAnnotation.tsx b/apps/web/src/components/diffs/DiffCommentAnnotation.tsxindex a2394854b5a..b202df0f52f 100644--- a/apps/web/src/components/diffs/DiffCommentAnnotation.tsx+++ b/apps/web/src/components/diffs/DiffCommentAnnotation.tsx@@ -3,6 +3,7 @@ import { useLayoutEffect, useRef, useState, type ReactNode } from "react";import { Button } from "~/components/ui/button";import { Textarea } from "~/components/ui/textarea";+import { textDirection } from "~/textDirection";import { isCommentSubmitShortcut } from "./commentSubmitShortcut";@@ -65,7 +66,12 @@ export function DiffCommentAnnotation({onPointerDown={(event) => event.stopPropagation()}><MessageCircle className="size-3.5 h-5 shrink-0 text-primary/70" aria-hidden="true" />- <p className="min-w-0 flex-1 whitespace-pre-wrap text-sm leading-5">{displayedText}</p>+ <p+ className="min-w-0 flex-1 whitespace-pre-wrap text-sm leading-5"+ dir={textDirection(displayedText)}+ >+ {displayedText}+ </p>{onDelete ? (<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"><Button@@ -95,6 +101,7 @@ export function DiffCommentAnnotation({autoFocus={focusOnMount}size="sm"value={displayedText}+ dir={textDirection(displayedText)}placeholder={placeholder}aria-label={`Comment on lines ${rangeLabel}`}onChange={(event) => (onTextChange ?? setLocalDraftText)(event.target.value)}diff --git a/apps/web/src/components/files/AudioPreview.tsx b/apps/web/src/components/files/AudioPreview.tsxindex abd05015a94..b1873d3b1ab 100644--- a/apps/web/src/components/files/AudioPreview.tsx+++ b/apps/web/src/components/files/AudioPreview.tsx@@ -156,7 +156,7 @@ function AudioChip(props: AudioPreviewProps) {middleTruncateAttachmentName(props.name))}</ContextChipLabel>- <span className="shrink-0 self-baseline text-3xs text-current">+ <span dir="ltr" className="shrink-0 self-baseline text-3xs text-current">{props.failed? "Unavailable": loadingdiff --git a/apps/web/src/textDirection.test.ts b/apps/web/src/textDirection.test.tsindex a104133799c..3cc618e525f 100644--- a/apps/web/src/textDirection.test.ts+++ b/apps/web/src/textDirection.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vite-plus/test";-import { textDirection } from "./textDirection";+import { markdownProseDirection, textDirection } from "./textDirection";describe("textDirection", () => {it.each([@@ -24,3 +24,39 @@ describe("textDirection", () => {expect(textDirection("42 — 7 ✓")).toBeUndefined();});});++describe("markdownProseDirection", () => {+ it.each([+ [+ "Hebrew around a code block",+ "תתקן את זה:\n```ts\nexport function useCheckout(props: CheckoutProps) {\n return props.items.length;\n}\n```\nותריץ שוב",+ "rtl",+ ],+ ["Hebrew around inline code", "לערוך את `apps/web/src/chat.tsx` או להשאיר `useMemo`?", "rtl"],+ ["Hebrew around double-backtick code", "תבדוק ``const a = `b c d e` + f`` עכשיו", "rtl"],+ [+ "Hebrew after a four-backtick fence",+ "````md\none two three four five six\n````\nשלום עולם, זה עובד",+ "rtl",+ ],+ [+ "Hebrew after a tilde fence",+ "~~~\nnpm run build --filter web --force\n~~~\nזה נכשל אצלי",+ "rtl",+ ],+ [+ "Hebrew before an unclosed fence",+ "שלום, הנה השגיאה:\n```\nError: cannot find module react dom client",+ "rtl",+ ],+ ["Hebrew around a URL", "ראה https://github.com/pingdotgg/t3code/pull/24050 לפני", "rtl"],+ ["English around inline code", "Should I edit `useMemo` or keep it?", "ltr"],+ ["English quoting one Hebrew word", "Please check the שלום label before the release", "ltr"],+ ])("reads %s", (_, markdown, direction) => {+ expect(markdownProseDirection(markdown)).toBe(direction);+ });++ it("leaves markdown without prose letters to its surroundings", () => {+ expect(markdownProseDirection("```\nconst a = 1;\n```")).toBeUndefined();+ });+});diff --git a/apps/web/src/textDirection.ts b/apps/web/src/textDirection.tsindex 9f0adedd30e..8b1a9e8c2a3 100644--- a/apps/web/src/textDirection.ts+++ b/apps/web/src/textDirection.ts@@ -1,27 +1 @@-export type TextDirection = "ltr" | "rtl";--// Hebrew through Arabic Extended-A, their presentation forms, and the-// supplementary right-to-left blocks.-const RTL_LETTER = /[-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u;-const LETTER = /\p{L}/u;--/**- * `dir="auto"` misreads Arabic prose that opens with an English term.- * Count words so mixed prose follows its main language; break ties with the first word.- */-export function textDirection(text: string): TextDirection | undefined {- if (!RTL_LETTER.test(text)) return LETTER.test(text) ? "ltr" : undefined;- let rtlWords = 0;- let ltrWords = 0;- let first: TextDirection | undefined;- for (const word of text.split(/\s+/)) {- const letter = LETTER.exec(word)?.[0];- if (!letter) continue;- const direction = RTL_LETTER.test(letter) ? "rtl" : "ltr";- first ??= direction;- if (direction === "rtl") rtlWords += 1;- else ltrWords += 1;- }- if (rtlWords === ltrWords) return first;- return rtlWords > ltrWords ? "rtl" : "ltr";-}+export * from "@t3tools/shared/textDirection";diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex e3d0b2ce57c..f17f48f1c9e 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -31,6 +31,10 @@"types": "./src/themePreview.ts","import": "./src/themePreview.ts"},+ "./textDirection": {+ "types": "./src/textDirection.ts",+ "import": "./src/textDirection.ts"+ },"./projectFavicon": {"types": "./src/projectFavicon.ts","import": "./src/projectFavicon.ts"diff --git a/packages/shared/src/textDirection.ts b/packages/shared/src/textDirection.tsnew file mode 100644index 00000000000..5611e41720d--- /dev/null+++ b/packages/shared/src/textDirection.ts@@ -0,0 +1,34 @@+export type TextDirection = "ltr" | "rtl";++// Hebrew through Arabic Extended-A, their presentation forms, and the+// supplementary right-to-left blocks.+const RTL_LETTER = /[-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u;+const LETTER = /\p{L}/u;++/**+ * `dir="auto"` misreads Arabic prose that opens with an English term.+ * Count words so mixed prose follows its main language; break ties with the first word.+ */+export function textDirection(text: string): TextDirection | undefined {+ if (!RTL_LETTER.test(text)) return LETTER.test(text) ? "ltr" : undefined;+ let rtlWords = 0;+ let ltrWords = 0;+ let first: TextDirection | undefined;+ for (const word of text.split(/\s+/)) {+ const letter = LETTER.exec(word)?.[0];+ if (!letter) continue;+ const direction = RTL_LETTER.test(letter) ? "rtl" : "ltr";+ first ??= direction;+ if (direction === "rtl") rtlWords += 1;+ else ltrWords += 1;+ }+ if (rtlWords === ltrWords) return first;+ return rtlWords > ltrWords ? "rtl" : "ltr";+}++const MARKDOWN_CODE_OR_URL =+ /(`{3,}|~{3,})[\s\S]*?(?:\1|$)|(`{1,2})(?!`)[\s\S]*?(?<!`)\2(?!`)|https?:\/\/\S+/g;++export function markdownProseDirection(markdown: string): TextDirection | undefined {+ return textDirection(markdown.replace(MARKDOWN_CODE_OR_URL, " "));+}