diff --git a/client/src/Providers/MessagePartsHostContext.tsx b/client/src/Providers/MessagePartsHostContext.tsx index 7e73f7b271..4f654372f1 100644 --- a/client/src/Providers/MessagePartsHostContext.tsx +++ b/client/src/Providers/MessagePartsHostContext.tsx @@ -34,6 +34,7 @@ import { import store, { ptcTraceByToolCallId, ptcTraceKey, sandboxStartingByToolCallId } from '~/store'; import { getAppPartRenderers } from '~/components/Chat/Messages/Content/Parts/slots'; import useSmoothStreaming from '~/hooks/Messages/useSmoothStreaming'; +import { chatDirectionAtom } from '~/store/chatDirection'; import { showThinkingAtom } from '~/store/showThinking'; import { fontSizeAtom } from '~/store/fontSize'; @@ -130,7 +131,7 @@ export const appMessagePartsHost: MessagePartsHost = { useShowThinking: () => useAtomValue(showThinkingAtom), useAutoExpandTools: () => useRecoilValue(store.autoExpandTools), useLaTeXParsing: () => useRecoilValue(store.LaTeXParsing), - useChatDirection: () => useRecoilValue(store.chatDirection), + useChatDirection: () => useAtomValue(chatDirectionAtom), useUserTextPreferences: useAppUserTextPreferences, /* The atom rather than the auth context: AuthContextProvider mirrors the user into it, and the * public share route mounts outside that provider. */ diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx index b49ed2bfe4..16555bf237 100644 --- a/client/src/components/Chat/Input/ChatForm.tsx +++ b/client/src/components/Chat/Input/ChatForm.tsx @@ -1,7 +1,7 @@ import { memo, useRef, useMemo, useEffect, useState, useCallback } from 'react'; -import { useAtom } from 'jotai'; import { useRecoilValue } from 'recoil'; import { useWatch } from 'react-hook-form'; +import { useAtom, useAtomValue } from 'jotai'; import { useNavigate } from 'react-router-dom'; import { useDirection } from '@radix-ui/react-direction'; import { useSteering, showStopButtonByIndex, useComposerRestoreHost } from '@librechat/chat/react'; @@ -62,6 +62,7 @@ import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode'; import AskUserQuestionPopover from './AskUserQuestionPopover'; import useComposerItems from '~/hooks/Input/useComposerItems'; import useAttachTarget from '~/hooks/Input/useAttachTarget'; +import { chatDirectionAtom } from '~/store/chatDirection'; import Hints, { composerHintId } from './Composer/Hints'; import PastedTextDialog from './Files/PastedTextDialog'; import DuringRunSendButton from './DuringRunSendButton'; @@ -187,7 +188,7 @@ const ChatForm = memo(function ChatForm({ const SpeechToText = useRecoilValue(store.speechToText); const TextToSpeech = useRecoilValue(store.textToSpeech); - const chatDirection = useRecoilValue(store.chatDirection); + const chatDirection = useAtomValue(chatDirectionAtom); const automaticPlayback = useRecoilValue(store.automaticPlayback); const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace); const { isTemporary } = useChatSettings(); diff --git a/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx b/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx index b04b1c4f7d..34364f09ab 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx +++ b/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx @@ -1,16 +1,17 @@ import React from 'react'; +import { getDefaultStore } from 'jotai'; import { Constants, ContentTypes } from 'librechat-data-provider'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import type { FileCitation, TMessage, TMessageContentParts } from 'librechat-data-provider'; +import { chatDirectionAtom } from '~/store/chatDirection'; import EditContentParts from '../EditContentParts'; const mockMutateAsync = jest.fn(); const mockSetMessages = jest.fn(); const mockAsk = jest.fn(); -let mockChatDirection = 'auto'; jest.mock('recoil', () => ({ - useRecoilValue: () => mockChatDirection, + useRecoilValue: () => undefined, })); jest.mock('~/store', () => ({ @@ -77,7 +78,7 @@ describe('EditContentParts', () => { mockMutateAsync.mockReset(); mockAsk.mockReset(); mockMutateAsync.mockResolvedValue({}); - mockChatDirection = 'auto'; + getDefaultStore().set(chatDirectionAtom, 'auto'); message.content = undefined; mockThread = [parentMessage, message]; }); @@ -653,7 +654,7 @@ describe('EditContentParts', () => { }); it('turns the editor around for a right-to-left chat direction', () => { - mockChatDirection = 'rtl'; + getDefaultStore().set(chatDirectionAtom, 'rtl'); render( { const localize = useLocalize(); - const [direction, setDirection] = useRecoilState(store.chatDirection); + const [direction, setDirection] = useAtom(chatDirectionAtom); const options = [ { value: 'auto', label: localize('com_ui_auto') }, diff --git a/client/src/store/__tests__/chatDirection.spec.ts b/client/src/store/__tests__/chatDirection.spec.ts index dac5d362a2..130fe6ba61 100644 --- a/client/src/store/__tests__/chatDirection.spec.ts +++ b/client/src/store/__tests__/chatDirection.spec.ts @@ -1,9 +1,10 @@ +import { createStore } from 'jotai'; + const DIRECTION_KEY = 'chatDirection'; -const readStoredDirection = async (): Promise => { - const { snapshot_UNSTABLE } = await import('recoil'); - const settings = await import('../settings'); - return snapshot_UNSTABLE().getLoadable(settings.default.chatDirection).valueOrThrow(); +const readStoredDirection = async () => { + const { chatDirectionAtom } = await import('../chatDirection'); + return createStore().get(chatDirectionAtom); }; describe('chatDirection', () => { @@ -23,11 +24,18 @@ describe('chatDirection', () => { ])('keeps a stored %s choice as %s', async (stored, expected) => { localStorage.setItem(DIRECTION_KEY, JSON.stringify(stored)); expect(await readStoredDirection()).toBe(expected); - expect(localStorage.getItem(DIRECTION_KEY)).toBe(JSON.stringify(expected)); }); it('falls back to auto for an unrecognized stored value', async () => { localStorage.setItem(DIRECTION_KEY, JSON.stringify('sideways')); expect(await readStoredDirection()).toBe('auto'); }); + + it('stores a choice where older clients read it', async () => { + const { chatDirectionAtom } = await import('../chatDirection'); + const store = createStore(); + store.set(chatDirectionAtom, 'rtl'); + expect(store.get(chatDirectionAtom)).toBe('rtl'); + expect(localStorage.getItem(DIRECTION_KEY)).toBe(JSON.stringify('rtl')); + }); }); diff --git a/client/src/store/chatDirection.ts b/client/src/store/chatDirection.ts new file mode 100644 index 0000000000..04f36d3d7c --- /dev/null +++ b/client/src/store/chatDirection.ts @@ -0,0 +1,18 @@ +import { atom } from 'jotai'; +import { createStorageAtom } from './jotai-utils'; + +/** `auto` lets each field resolve its direction from what is typed; the others force it. */ +export type ChatDirection = 'auto' | 'ltr' | 'rtl'; + +/** Older clients stored `LTR`/`RTL`; anything unrecognized falls back to `auto`. */ +export const normalizeChatDirection = (direction: unknown): ChatDirection => { + const value = typeof direction === 'string' ? direction.toLowerCase() : ''; + return value === 'ltr' || value === 'rtl' ? value : 'auto'; +}; + +const storedChatDirection = createStorageAtom('chatDirection', 'auto'); + +export const chatDirectionAtom = atom( + (get) => normalizeChatDirection(get(storedChatDirection)), + (_get, set, direction: ChatDirection) => set(storedChatDirection, direction), +); diff --git a/client/src/store/settings.ts b/client/src/store/settings.ts index dd043323f7..1e44231a54 100644 --- a/client/src/store/settings.ts +++ b/client/src/store/settings.ts @@ -23,15 +23,6 @@ const normalizeSavedSpeechEngine = ( return legacyExternalEngines.has(engine) ? STTEndpoints.external : STTEndpoints.browser; }; -/** `auto` lets each field resolve its direction from what is typed; the others force it. */ -export type ChatDirection = 'auto' | 'ltr' | 'rtl'; - -/** Older clients stored `LTR`/`RTL`; anything unrecognized falls back to `auto`. */ -const normalizeChatDirection = (direction: ChatDirection): ChatDirection => { - const value = typeof direction === 'string' ? direction.toLowerCase() : ''; - return value === 'ltr' || value === 'rtl' ? value : 'auto'; -}; - // Static atoms without localStorage const staticAtoms = { abortScroll: atom({ key: 'abortScroll', default: false }), @@ -68,11 +59,6 @@ const localStorageAtoms = { // Chat settings enterToSend: atomWithLocalStorage('enterToSend', false), maximizeChatSpace: atomWithLocalStorage('maximizeChatSpace', false), - chatDirection: atomWithLocalStorage( - 'chatDirection', - 'auto', - normalizeChatDirection, - ), autoExpandTools: atomWithLocalStorage(LocalStorageKeys.AUTO_EXPAND_TOOLS, false), saveDrafts: atomWithLocalStorage('saveDrafts', true), /** diff --git a/e2e/specs/mock/scenarios/rtl-direction.spec.ts b/e2e/specs/mock/scenarios/rtl-direction.spec.ts new file mode 100644 index 0000000000..7543d39e62 --- /dev/null +++ b/e2e/specs/mock/scenarios/rtl-direction.spec.ts @@ -0,0 +1,397 @@ +import { expect, test } from '@playwright/test'; +import type { Locator, Page, Route } from '@playwright/test'; +import { openSidebar } from './sidebar'; + +/** + * Interface and chat direction. A right-to-left locale marks the document `rtl` before the bundle + * runs, Radix subtrees and the toast swipe follow it, and switching language in Settings leaves + * `` on the locale actually shown. The chat direction setting is `auto`, `ltr` or + * `rtl`: a forced value mirrors the composer and the message editors, `auto` lets each field follow + * its text, and an empty composer follows the interface so its placeholder sits on the reading edge. + */ +test.describe.configure({ timeout: 120_000 }); + +const NO_PARENT = '00000000-0000-0000-0000-000000000000'; +const unique = (prefix: string) => `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`; +const escapeRe = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + +/** Seeds localStorage once per test, so a reload inside the test keeps what the app wrote since. */ +async function seedStorage(page: Page, values: Record) { + await page.addInitScript((entries) => { + if (sessionStorage.getItem('e2e-rtl-seeded') != null) { + return; + } + for (const [key, value] of Object.entries(entries)) { + if (value == null) { + localStorage.removeItem(key); + } else { + localStorage.setItem(key, value); + } + } + sessionStorage.setItem('e2e-rtl-seeded', '1'); + }, values); +} + +const documentDirection = (page: Page) => + page.evaluate(() => ({ + lang: document.documentElement.lang, + dir: document.documentElement.dir, + })); + +const computedDirection = (locator: Locator) => + locator.evaluate((element) => getComputedStyle(element).direction); + +async function openSettings(page: Page) { + await openSidebar(page); + await page.getByTestId('nav-user').filter({ visible: true }).first().click(); + await page.getByRole('menuitem', { name: 'Settings' }).click(); + const dialog = page.getByRole('dialog'); + await expect(dialog.getByRole('tablist')).toBeVisible({ timeout: 15000 }); + await openTab(dialog, 'general'); + return dialog; +} + +/** Phones show the tab list and a panel one at a time, so a hidden list is reached through Back. */ +async function openTab(dialog: Locator, id: string) { + const tab = dialog.locator(`[role="tab"][id$="-trigger-${id}"]`); + if (!(await tab.isVisible())) { + await dialog.getByRole('button', { name: /^(Back|عودة)$/ }).click(); + } + await tab.click(); + await expect(dialog.getByRole('tabpanel')).toBeVisible(); +} + +async function chooseOption(page: Page, trigger: Locator, name: string) { + await trigger.click(); + await page.getByRole('option', { name, exact: true }).click(); +} + +const languageSelect = (dialog: Locator) => + dialog.locator('[role="combobox"][aria-labelledby~="language-selector-label"]'); + +test.describe('before the bundle', () => { + /* A worker-served reload would bypass the route that holds the bundle back. */ + test.use({ serviceWorkers: 'block' }); + + test('a right-to-left locale marks the document rtl before the bundle runs @scenario:rtl-shell-direction-before-bundle', async ({ + page, + context, + }) => { + /* Module scripts are held, never answered: only the inline shell script can set `dir`, and a + * refused script would start the stale-asset recovery reload instead. */ + await page.route(/\/assets\/.*\.js(?:\?.*)?$/, () => new Promise(() => undefined)); + const load = async () => { + await page.goto('/', { timeout: 30000, waitUntil: 'commit' }); + await page.waitForFunction(() => document.body != null); + return (await documentDirection(page)).dir; + }; + + await seedStorage(page, { lang: JSON.stringify('ar-EG') }); + expect(await load()).toBe('rtl'); + + /* A value stored unquoted by an older client still counts. */ + await page.evaluate(() => localStorage.setItem('lang', 'he')); + expect(await load()).toBe('rtl'); + + /* The cookie wins over storage, as it does in `detectInitialLanguage`. */ + await page.evaluate(() => localStorage.setItem('lang', JSON.stringify('fa-IR'))); + const { origin } = new URL(page.url()); + await context.addCookies([{ name: 'lang', value: 'en-US', url: origin }]); + expect(await load()).toBe(''); + + await context.addCookies([{ name: 'lang', value: 'ug', url: origin }]); + await page.evaluate(() => localStorage.setItem('lang', JSON.stringify('en-US'))); + expect(await load()).toBe('rtl'); + }); +}); + +test('switching language in Settings leaves the document on the locale shown @scenario:language-switch-sets-document-direction', async ({ + page, +}) => { + await seedStorage(page, { lang: JSON.stringify('en-US') }); + await page.goto('/c/new', { timeout: 30000 }); + const dialog = await openSettings(page); + + await chooseOption(page, languageSelect(dialog), 'العربية'); + await expect.poll(() => documentDirection(page)).toEqual({ lang: 'ar', dir: 'rtl' }); + /* The selector's own value is `ar-EG`; nothing may overwrite the normalized locale later. */ + await page.waitForTimeout(500); + expect(await documentDirection(page)).toEqual({ lang: 'ar', dir: 'rtl' }); + + await chooseOption(page, languageSelect(dialog), 'English'); + await expect.poll(() => documentDirection(page)).toEqual({ lang: 'en', dir: 'ltr' }); + await page.waitForTimeout(500); + expect(await documentDirection(page)).toEqual({ lang: 'en', dir: 'ltr' }); +}); + +test('Radix subtrees follow a right-to-left interface @scenario:radix-subtrees-follow-interface-direction', async ({ + page, +}) => { + await seedStorage(page, { lang: JSON.stringify('en-US') }); + await page.goto('/c/new', { timeout: 30000 }); + const dialog = await openSettings(page); + const panel = dialog.getByRole('tabpanel'); + /* The nearest `dir` above the settings body is the one Radix Tabs writes on its root. */ + const radixDirection = () => + panel.evaluate((element) => element.closest('[dir]')?.getAttribute('dir') ?? null); + expect(await radixDirection()).toBe('ltr'); + expect(await computedDirection(panel)).toBe('ltr'); + + await chooseOption(page, languageSelect(dialog), 'العربية'); + await expect.poll(() => documentDirection(page)).toEqual({ lang: 'ar', dir: 'rtl' }); + + /* Radix Tabs used to write `dir="ltr"` here, turning the whole settings body LTR. */ + await expect.poll(radixDirection).toBe('rtl'); + await expect.poll(() => computedDirection(panel)).toBe('rtl'); +}); + +/** Drags the toast horizontally and reports how Radix settled the swipe (`end` dismisses it). */ +async function swipe(page: Page, toast: Locator, dx: number) { + await toast.evaluate((element) => { + const seen: string[] = []; + (window as unknown as { __swipes: string[] }).__swipes = seen; + new MutationObserver(() => seen.push(element.getAttribute('data-swipe') ?? '')).observe( + element, + { attributes: true, attributeFilter: ['data-swipe'] }, + ); + }); + const box = await toast.locator('.alert-root').boundingBox(); + expect(box).not.toBeNull(); + const y = (box?.y ?? 0) + (box?.height ?? 0) / 2; + const x = (box?.x ?? 0) + (box?.width ?? 0) / 2; + await page.mouse.move(x, y); + await page.mouse.down(); + for (let step = 1; step <= 10; step++) { + await page.mouse.move(x + (dx * step) / 10, y); + } + await page.mouse.up(); + return page.evaluate(() => (window as unknown as { __swipes: string[] }).__swipes); +} + +test('a toast swipes away toward the inline end @scenario:toast-swipes-toward-inline-end', async ({ + page, +}) => { + await page.route(/\/api\/convos\/import(?:\?.*)?$/, (route: Route) => + route.fulfill({ status: 500, contentType: 'application/json', body: '{}' }), + ); + await seedStorage(page, { lang: JSON.stringify('en-US') }); + await page.goto('/c/new', { timeout: 30000 }); + const dialog = await openSettings(page); + + /* A failed import raises an error toast; the dialog stays open across the language switch. */ + const raiseToast = async () => { + await openTab(dialog, 'data'); + await dialog + .locator('input[type="file"]') + .first() + .setInputFiles({ + name: 'chats.json', + mimeType: 'application/json', + buffer: Buffer.from('{}'), + }); + const toast = page.locator('.toast-root[data-state="open"]').last(); + await expect(toast).toBeVisible({ timeout: 15000 }); + return toast; + }; + + const ltrToast = await raiseToast(); + await expect(ltrToast).toHaveAttribute('data-swipe-direction', 'right'); + await expect(ltrToast).toBeHidden({ timeout: 10000 }); + + await openTab(dialog, 'general'); + await chooseOption(page, languageSelect(dialog), 'العربية'); + await expect.poll(() => documentDirection(page)).toEqual({ lang: 'ar', dir: 'rtl' }); + + const rtlToast = await raiseToast(); + await expect(rtlToast).toHaveAttribute('data-swipe-direction', 'left'); + /* Escape would dismiss the toast itself, so the dialog is closed by its button. */ + await dialog.getByRole('button', { name: 'Close Settings' }).click(); + await expect(dialog).toBeHidden(); + + /* Dragging toward the inline start is refused; toward the inline end (left) dismisses. */ + expect(await swipe(page, rtlToast, 160)).not.toContain('end'); + expect(await swipe(page, rtlToast, -160)).toContain('end'); + await expect(rtlToast).toBeHidden({ timeout: 10000 }); +}); + +test('the chat direction setting forces the composer or lets it follow the page @scenario:chat-direction-setting-forces-composer', async ({ + page, +}) => { + await seedStorage(page, { lang: JSON.stringify('en-US'), chatDirection: null }); + await page.goto('/c/new', { timeout: 30000 }); + const form = page.locator('form').filter({ has: page.getByTestId('text-input') }); + const input = page.getByTestId('text-input'); + await expect(input).toBeVisible({ timeout: 20000 }); + expect(await form.getAttribute('dir')).toBeNull(); + + const dialog = await openSettings(page); + const select = dialog.getByTestId('chatDirection'); + await expect(select).toContainText('Auto'); + await select.click(); + await expect(page.getByRole('option')).toHaveText(['Auto', 'Left to Right', 'Right to Left']); + await page.getByRole('option', { name: 'Right to Left', exact: true }).click(); + await expect(select).toContainText('Right to Left'); + await page.keyboard.press('Escape'); + await expect(dialog).toBeHidden(); + + await expect(form).toHaveAttribute('dir', 'rtl'); + await expect(input).toHaveAttribute('dir', 'rtl'); + expect(await computedDirection(input)).toBe('rtl'); + expect(await page.evaluate(() => localStorage.getItem('chatDirection'))).toBe('"rtl"'); + + /* A forced LTR holds inside a right-to-left interface too. */ + await page.evaluate(() => { + localStorage.setItem('chatDirection', JSON.stringify('ltr')); + localStorage.setItem('lang', JSON.stringify('ar-EG')); + }); + await page.reload(); + await expect.poll(() => documentDirection(page)).toEqual({ lang: 'ar', dir: 'rtl' }); + await expect(form).toHaveAttribute('dir', 'ltr'); + await expect(input).toHaveAttribute('dir', 'ltr'); + expect(await computedDirection(input)).toBe('ltr'); +}); + +test('a stored legacy chat direction keeps its meaning @scenario:chat-direction-legacy-value-migrates', async ({ + page, +}) => { + await seedStorage(page, { lang: JSON.stringify('en-US'), chatDirection: JSON.stringify('RTL') }); + await page.goto('/c/new', { timeout: 30000 }); + const form = page.locator('form').filter({ has: page.getByTestId('text-input') }); + await expect(page.getByTestId('text-input')).toBeVisible({ timeout: 20000 }); + await expect(form).toHaveAttribute('dir', 'rtl'); + + const dialog = await openSettings(page); + await expect(dialog.getByTestId('chatDirection')).toContainText('Right to Left'); + await page.keyboard.press('Escape'); + + /* An unrecognized stored value falls back to `auto` instead of breaking the composer. */ + await page.evaluate(() => localStorage.setItem('chatDirection', JSON.stringify('sideways'))); + await page.reload(); + await expect(page.getByTestId('text-input')).toBeVisible({ timeout: 20000 }); + expect(await form.getAttribute('dir')).toBeNull(); + const reopened = await openSettings(page); + await expect(reopened.getByTestId('chatDirection')).toContainText('Auto'); +}); + +test('an empty composer follows the interface until text gives it a direction @scenario:composer-empty-follows-interface', async ({ + page, +}) => { + await seedStorage(page, { lang: JSON.stringify('ar-EG'), chatDirection: JSON.stringify('auto') }); + await page.goto('/c/new', { timeout: 30000 }); + await expect.poll(() => documentDirection(page)).toEqual({ lang: 'ar', dir: 'rtl' }); + const input = page.getByTestId('text-input'); + await expect(input).toBeVisible({ timeout: 20000 }); + await expect(input).toHaveAttribute('dir', 'rtl'); + expect(await computedDirection(input)).toBe('rtl'); + + await input.click(); + await input.fill('hello world'); + await expect(input).toHaveAttribute('dir', 'auto'); + expect(await input.evaluate((element) => element.matches(':dir(ltr)'))).toBe(true); + + await input.fill('مرحبا'); + expect(await input.evaluate((element) => element.matches(':dir(rtl)'))).toBe(true); + + await input.fill(''); + await expect(input).toHaveAttribute('dir', 'rtl'); +}); + +async function routeEditableConversation(page: Page) { + const conversationId = unique('e2e-rtl-edit'); + const now = new Date(0).toISOString(); + const userId = `${conversationId}-user`; + const assistantId = `${conversationId}-assistant`; + const messages = [ + { + messageId: userId, + conversationId, + parentMessageId: NO_PARENT, + isCreatedByUser: true, + sender: 'User', + endpoint: 'Mock Provider A', + model: 'mock-model-a', + text: 'user question', + createdAt: now, + updatedAt: now, + }, + { + messageId: assistantId, + conversationId, + parentMessageId: userId, + isCreatedByUser: false, + sender: 'Assistant', + endpoint: 'Mock Provider A', + model: 'mock-model-a', + text: '', + content: [{ type: 'text', text: 'assistant answer' }], + createdAt: now, + updatedAt: now, + }, + ]; + const conversation = { + conversationId, + title: 'Direction editors', + endpoint: 'Mock Provider A', + endpointType: 'custom', + model: 'mock-model-a', + createdAt: now, + updatedAt: now, + }; + const convoIdRe = escapeRe(conversationId); + await page.route(new RegExp(`/api/convos/${convoIdRe}(?:\\?.*)?$`), (route: Route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(conversation), + }), + ); + await page.route(new RegExp(`/api/messages/${convoIdRe}(?:\\?.*)?$`), (route: Route) => + route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(messages) }), + ); + return { conversationId, userId, assistantId }; +} + +async function openEditor(page: Page, messageId: string, text: string) { + await page.getByText(text, { exact: true }).first().hover(); + await page.locator(`[id="edit-${messageId}"]`).click(); + const editor = page.locator('textarea.message-editor-text').filter({ visible: true }).first(); + await expect(editor).toBeVisible({ timeout: 10000 }); + return editor; +} + +test('the message editors follow the chat direction setting @scenario:message-editors-follow-chat-direction', async ({ + page, +}) => { + await seedStorage(page, { lang: JSON.stringify('en-US'), chatDirection: JSON.stringify('auto') }); + const { conversationId, userId, assistantId } = await routeEditableConversation(page); + await page.goto(`/c/${conversationId}`, { timeout: 30000 }); + await expect(page.getByText('assistant answer', { exact: true }).first()).toBeVisible({ + timeout: 20000, + }); + + let editor = await openEditor(page, userId, 'user question'); + await expect(editor).toHaveAttribute('dir', 'auto'); + await page.keyboard.press('Escape'); + await expect(editor).toBeHidden(); + + editor = await openEditor(page, assistantId, 'assistant answer'); + await expect(editor).toHaveAttribute('dir', 'auto'); + await page.keyboard.press('Escape'); + await expect(editor).toBeHidden(); + + await page.evaluate(() => localStorage.setItem('chatDirection', JSON.stringify('rtl'))); + await page.reload(); + await expect(page.getByText('assistant answer', { exact: true }).first()).toBeVisible({ + timeout: 20000, + }); + + editor = await openEditor(page, userId, 'user question'); + await expect(editor).toHaveAttribute('dir', 'rtl'); + expect(await computedDirection(editor)).toBe('rtl'); + await page.keyboard.press('Escape'); + await expect(editor).toBeHidden(); + + editor = await openEditor(page, assistantId, 'assistant answer'); + await expect(editor).toHaveAttribute('dir', 'rtl'); + expect(await computedDirection(editor)).toBe('rtl'); +}); diff --git a/packages/client/src/components/__tests__/TextareaAutosize.spec.tsx b/packages/client/src/components/__tests__/TextareaAutosize.spec.tsx new file mode 100644 index 0000000000..89d3b66857 --- /dev/null +++ b/packages/client/src/components/__tests__/TextareaAutosize.spec.tsx @@ -0,0 +1,15 @@ +import '@testing-library/jest-dom'; +import { render, screen } from '@testing-library/react'; +import { TextareaAutosize } from '../TextareaAutosize'; + +describe('TextareaAutosize direction', () => { + it('lets the text decide its direction when the caller does not', () => { + render(); + expect(screen.getByLabelText('draft')).toHaveAttribute('dir', 'auto'); + }); + + it('keeps a direction the caller forces', () => { + render(); + expect(screen.getByLabelText('draft')).toHaveAttribute('dir', 'rtl'); + }); +});