An open source design system that's fully customizable and agent ready
TypeScript
chore(sandbox): a Chat Layout page with a case for each chat check (#10672)
Christopher Chedeau4e4c12a9dd52
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.jsonindex a8188d01c1..e1dca383db 100644--- a/apps/sandbox/scripts/next-export-routes.json+++ b/apps/sandbox/scripts/next-export-routes.json@@ -6,6 +6,7 @@"/404/","/components-patterns/","/pages/butter-palette/",+ "/pages/chat-layout/","/pages/codeblock-perf/","/pages/color-studio/","/pages/component-scores/",diff --git a/apps/sandbox/src/app/(raw)/pages/chat-layout/ChatLayoutCaseView.tsx b/apps/sandbox/src/app/(raw)/pages/chat-layout/ChatLayoutCaseView.tsxnew file mode 100644index 0000000000..d5a573ff2e--- /dev/null+++ b/apps/sandbox/src/app/(raw)/pages/chat-layout/ChatLayoutCaseView.tsx@@ -0,0 +1,210 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ChatLayoutCaseView.tsx+ * @input One of the Chat Layout page's cases (cases.ts).+ * @output That case's ChatLayout: a transcript, a composer that adds each sent+ * message and, in the streaming case, replies that stream in.+ * @position Rendered by the Chat Layout page.+ */++import {useEffect, useRef, useState} from 'react';+import {AtSymbolIcon, PaperClipIcon} from '@heroicons/react/24/outline';+import {Button} from '@astryxdesign/core/Button';+import {Card} from '@astryxdesign/core/Card';+import {+ ChatComposer,+ ChatComposerInput,+ ChatLayout,+ ChatMessage,+ ChatMessageBubble,+ ChatMessageList,+ ChatSystemMessage,+} from '@astryxdesign/core/Chat';+import {Icon} from '@astryxdesign/core/Icon';+import {Markdown} from '@astryxdesign/core/Markdown';+import {VStack} from '@astryxdesign/core/Stack';+import {CHAT_LAYOUT_CASE_INFO, type ChatLayoutCase} from './cases';++interface Message {+ id: number;+ sender: 'user' | 'assistant';+ text: string;+}++const CONVERSATION: Array<Omit<Message, 'id'>> = [+ {+ sender: 'user',+ text: 'Can you help me plan a weekend trip to the coast?',+ },+ {+ sender: 'assistant',+ text: 'Sure. A two-day trip works well: arrive on Saturday morning, walk the cliffs in the afternoon, and keep Sunday for the harbor and the market.',+ },+ {sender: 'user', text: 'What should I pack for changeable weather?'},+ {+ sender: 'assistant',+ text: 'Pack layers: a light rain jacket, a warm sweater and shoes with good grip. The wind on the cliffs is often stronger than in town.',+ },+ {sender: 'user', text: 'Is there a good place to watch the sunset?'},+ {+ sender: 'assistant',+ text: 'The headland past the lighthouse faces west. Get there about 30 minutes early, because the path is narrow and the light changes fast.',+ },+ {sender: 'user', text: 'And somewhere to eat after that?'},+ {+ sender: 'assistant',+ text: 'The harbor has a few small seafood places. Most close their kitchens at 9, so book a table for the evening if you can.',+ },+ {sender: 'user', text: 'How early does the market open on Sunday?'},+ {+ sender: 'assistant',+ text: 'It opens at 8. The bakery stalls sell out first, so go early and leave the harbor walk for later in the morning.',+ },+ {sender: 'user', text: 'Can I get there by train?'},+ {+ sender: 'assistant',+ text: 'Yes. The coast line runs every hour, and the station is a ten minute walk from the harbor. Trains on Sunday evening fill up, so take an earlier one home.',+ },+];++const REPLY =+ 'Here is a plan for Saturday. Take the 8:40 train and leave your bag at the station. Walk the cliff path north to the lighthouse, which takes about two hours with stops. Have lunch at the harbor, then rest before the sunset walk. Book dinner for 8:30 so the kitchen is still open when you get back.';++/** Characters a streamed reply grows by on each step, and the step, in ms. */+const STREAM_STEP = 6;+const STREAM_INTERVAL_MS = 50;++/** The reply the streaming case opens on, which streams in. */+const OPENING_REPLY_ID = 999;++function seedFor(chatCase: ChatLayoutCase): Message[] {+ // The long case repeats the conversation, so the transcript is several+ // screens tall on a phone.+ const turns = chatCase === 'long' ? 3 : 1;+ const seed: Message[] = Array.from({length: turns}, () => CONVERSATION)+ .flat()+ .map((message, index) => ({...message, id: index + 1}));+ return chatCase === 'streaming'+ ? [...seed, {id: OPENING_REPLY_ID, sender: 'assistant', text: ''}]+ : seed;+}++export function ChatLayoutCaseView({chatCase}: {chatCase: ChatLayoutCase}) {+ const info = CHAT_LAYOUT_CASE_INFO[chatCase];+ // The document scrolls the transcript. Server rendering has no document.+ const documentRef = useRef<HTMLElement | null>(+ typeof document === 'undefined' ? null : document.documentElement,+ );+ // The streaming case opens on a reply that streams in, and streams one+ // after each sent message.+ const [messages, setMessages] = useState(() => seedFor(chatCase));+ const [streamingId, setStreamingId] = useState<number | null>(+ chatCase === 'streaming' ? OPENING_REPLY_ID : null,+ );+ // Ids for the messages added after the page opens, above every seeded id.+ const nextId = useRef(1000);+ // A reply that has all its text no longer streams.+ const streamed = messages.find(message => message.id === streamingId);+ const activeId =+ streamed != null && streamed.text.length < REPLY.length+ ? streamingId+ : null;++ // Synchronizes the streamed reply's text with a timer, as a model's tokens+ // would arrive.+ useEffect(() => {+ if (activeId == null) {+ return undefined;+ }+ const timer = setInterval(() => {+ setMessages(previous =>+ previous.map(message =>+ message.id === activeId+ ? {+ ...message,+ text: REPLY.slice(0, message.text.length + STREAM_STEP),+ }+ : message,+ ),+ );+ }, STREAM_INTERVAL_MS);+ return () => clearInterval(timer);+ }, [activeId]);++ const send = (text: string) => {+ const userId = nextId.current++;+ const replyId = chatCase === 'streaming' ? nextId.current++ : null;+ setMessages(previous => [+ ...previous,+ {id: userId, sender: 'user', text},+ ...(replyId == null+ ? []+ : [{id: replyId, sender: 'assistant' as const, text: ''}]),+ ]);+ if (replyId != null) {+ setStreamingId(replyId);+ }+ };++ const layout = (+ <ChatLayout+ scrollRef={info.scroll === 'document' ? documentRef : undefined}+ composer={+ <ChatComposer+ onSubmit={send}+ input={<ChatComposerInput placeholder="Message" />}+ headerActions={+ chatCase === 'composer' ? (+ <>+ <Button+ label="Mention"+ variant="ghost"+ size="sm"+ icon={<Icon icon={AtSymbolIcon} />}+ isIconOnly+ />+ <Button+ label="Attach"+ variant="ghost"+ size="sm"+ icon={<Icon icon={PaperClipIcon} />}+ isIconOnly+ />+ </>+ ) : undefined+ }+ />+ }>+ <ChatMessageList>+ <ChatSystemMessage>{info.label}</ChatSystemMessage>+ {messages.map(message =>+ message.sender === 'user' ? (+ <ChatMessage key={message.id} sender="user">+ <ChatMessageBubble>{message.text}</ChatMessageBubble>+ </ChatMessage>+ ) : (+ <ChatMessage key={message.id} sender="assistant">+ <Markdown density="compact" isStreaming={message.id === activeId}>+ {message.text}+ </Markdown>+ </ChatMessage>+ ),+ )}+ </ChatMessageList>+ </ChatLayout>+ );++ if (info.scroll === 'document') {+ return layout;+ }+ return (+ <VStack height="100dvh" padding={4}>+ <Card height="70dvh" padding={0}>+ <VStack height="100%">{layout}</VStack>+ </Card>+ </VStack>+ );+}diff --git a/apps/sandbox/src/app/(raw)/pages/chat-layout/cases.ts b/apps/sandbox/src/app/(raw)/pages/chat-layout/cases.tsnew file mode 100644index 0000000000..e001dd1a2c--- /dev/null+++ b/apps/sandbox/src/app/(raw)/pages/chat-layout/cases.ts@@ -0,0 +1,50 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file cases.ts+ * @input A `?case=` value from the Chat Layout page's URL.+ * @output The page's cases: what each shows and what scrolls its transcript.+ * @position Read by the Chat Layout page and its test.+ */++export const CHAT_LAYOUT_CASES = [+ 'long',+ 'composer',+ 'streaming',+ 'docked',+] as const;++export type ChatLayoutCase = (typeof CHAT_LAYOUT_CASES)[number];++export interface ChatLayoutCaseInfo {+ /** What the case shows. The transcript opens with it. */+ label: string;+ /**+ * What scrolls the transcript. `document`: the page itself scrolls, and the+ * dock is fixed to the bottom of the viewport. `panel`: ChatLayout scrolls+ * itself inside a fixed-height panel, and the dock sticks to its bottom.+ */+ scroll: 'document' | 'panel';+}++export const CHAT_LAYOUT_CASE_INFO: Record<ChatLayoutCase, ChatLayoutCaseInfo> =+ {+ long: {label: 'A long conversation', scroll: 'document'},+ composer: {+ label: 'The composer and its actions, for the software keyboard',+ scroll: 'document',+ },+ streaming: {+ label: 'A reply streams in, and the conversation follows it',+ scroll: 'document',+ },+ docked: {+ label: 'The composer docked at the bottom of a fixed-height panel',+ scroll: 'panel',+ },+ };++/** The case a `?case=` value names. An unknown or missing value is `long`. */+export function parseChatLayoutCase(value: string | null): ChatLayoutCase {+ return CHAT_LAYOUT_CASES.find(chatCase => chatCase === value) ?? 'long';+}diff --git a/apps/sandbox/src/app/(raw)/pages/chat-layout/chatLayoutPage.test.tsx b/apps/sandbox/src/app/(raw)/pages/chat-layout/chatLayoutPage.test.tsxnew file mode 100644index 0000000000..93bcad5c05--- /dev/null+++ b/apps/sandbox/src/app/(raw)/pages/chat-layout/chatLayoutPage.test.tsx@@ -0,0 +1,66 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {renderToString} from 'react-dom/server';+import {MemoryRouter} from 'react-router-dom';+import {describe, expect, it} from 'vitest';+import ChatLayoutPage from './page';+import {+ CHAT_LAYOUT_CASES,+ CHAT_LAYOUT_CASE_INFO,+ parseChatLayoutCase,+} from './cases';++function renderPage(search: string): string {+ return renderToString(+ <MemoryRouter initialEntries={[`/pages/chat-layout/${search}`]}>+ <ChatLayoutPage />+ </MemoryRouter>,+ );+}++describe('Chat Layout page', () => {+ it('reads each case from ?case=, and opens on the long case otherwise', () => {+ for (const chatCase of CHAT_LAYOUT_CASES) {+ expect(parseChatLayoutCase(chatCase)).toBe(chatCase);+ }+ expect(parseChatLayoutCase(null)).toBe('long');+ expect(parseChatLayoutCase('unknown')).toBe('long');+ });++ it.each(CHAT_LAYOUT_CASES)(+ 'renders the %s case: its label, the transcript and the composer',+ chatCase => {+ const html = renderPage(`?case=${chatCase}`);++ expect(html).toContain(CHAT_LAYOUT_CASE_INFO[chatCase].label);+ expect(html).toContain(+ 'Can you help me plan a weekend trip to the coast?',+ );+ expect(html).toContain('aria-label="Message input"');+ expect(html).toContain('aria-label="Send"');+ },+ );++ it('renders the long case when the URL names no case', () => {+ expect(renderPage('')).toContain(CHAT_LAYOUT_CASE_INFO.long.label);+ });++ it('shows the composer actions in the composer case only', () => {+ expect(renderPage('?case=composer')).toContain('aria-label="Attach"');+ expect(renderPage('?case=long')).not.toContain('aria-label="Attach"');+ });++ it('renders the docked case inside a fixed-height panel, and the others as the page itself', () => {+ // A document-scroll case renders ChatLayout's root as the page's first+ // element. The docked case renders the panel's stack around a Card.+ for (const chatCase of CHAT_LAYOUT_CASES) {+ const html = renderPage(`?case=${chatCase}`);+ const isPanel = CHAT_LAYOUT_CASE_INFO[chatCase].scroll === 'panel';++ expect(/^<!--\$--><div class="(astryx-[\w-]+)/.exec(html)?.[1]).toBe(+ isPanel ? 'astryx-stack' : 'astryx-chat-layout',+ );+ expect(html.includes('astryx-card')).toBe(isPanel);+ }+ });+});diff --git a/apps/sandbox/src/app/(raw)/pages/chat-layout/page.tsx b/apps/sandbox/src/app/(raw)/pages/chat-layout/page.tsxnew file mode 100644index 0000000000..58c20c8d5c--- /dev/null+++ b/apps/sandbox/src/app/(raw)/pages/chat-layout/page.tsx@@ -0,0 +1,33 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file page.tsx+ * @input `?case=`: long (the default), composer, streaming or docked. cases.ts+ * names what each shows and what scrolls its transcript.+ * @output A full page ChatLayout with no sandbox chrome, for phone checks of+ * its keyboard, touch and scroll behavior.+ * @position Raw page. In long, composer and streaming the document scrolls and+ * the dock is fixed to the viewport. In docked, ChatLayout scrolls itself+ * inside a fixed-height panel, with the dock at the panel's bottom.+ */++import {Suspense} from 'react';+import {useSearchParams} from 'react-router-dom';+import {ChatLayoutCaseView} from './ChatLayoutCaseView';+import {parseChatLayoutCase} from './cases';++function ChatLayoutCases() {+ const [searchParams] = useSearchParams();+ const chatCase = parseChatLayoutCase(searchParams.get('case'));+ return <ChatLayoutCaseView key={chatCase} chatCase={chatCase} />;+}++export default function ChatLayoutPage() {+ return (+ <Suspense>+ <ChatLayoutCases />+ </Suspense>+ );+}diff --git a/apps/sandbox/src/app/sandboxPages.ts b/apps/sandbox/src/app/sandboxPages.tsindex a214265228..3c2800f341 100644--- a/apps/sandbox/src/app/sandboxPages.ts+++ b/apps/sandbox/src/app/sandboxPages.ts@@ -93,6 +93,12 @@ export const categories: SandboxCategory[] = [description:'Interactive mobile interaction prototypes (bottom sheets, action sheets, drawers) for the component migration table',},+ {+ name: 'Chat Layout',+ href: '/pages/chat-layout/',+ description:+ 'A full page ChatLayout for phone checks. ?case= long (the default), composer or streaming scroll the document; docked scrolls a fixed-height panel',+ },{name: 'TextArea Counter',href: '/pages/textarea-counter/',diff --git a/apps/sandbox/src/hydration-policy.ts b/apps/sandbox/src/hydration-policy.tsindex e90e7561bb..47609a6053 100644--- a/apps/sandbox/src/hydration-policy.ts+++ b/apps/sandbox/src/hydration-policy.ts@@ -5,13 +5,14 @@* @input Route and URL search string.* @output Whether React can safely hydrate instead of client-rendering.* @position Prevents mismatches for iframe themes and for pages whose first- * render reads URL controls (Shell Lab, Perf Scenes).+ * render reads URL controls (Shell Lab, Perf Scenes, Chat Layout).*//** Pages whose first render reads the query string. */const QUERY_RENDERED_PAGES = new Set(['/pages/shell-lab/','/pages/perf-scenes/',+ '/pages/chat-layout/',]);export function canHydrate(route: string | undefined, search: string): boolean {diff --git a/apps/sandbox/src/route-manifest.test.ts b/apps/sandbox/src/route-manifest.test.tsindex 54b454cb51..89436679a5 100644--- a/apps/sandbox/src/route-manifest.test.ts+++ b/apps/sandbox/src/route-manifest.test.ts@@ -110,6 +110,8 @@ describe('Sandbox static export contract', () => {);expect(canHydrate('/pages/component-scores/', '?filter=all')).toBe(true);expect(canHydrate('/pages/shell-lab/', '')).toBe(true);+ expect(canHydrate('/pages/chat-layout/', '?case=docked')).toBe(false);+ expect(canHydrate('/pages/chat-layout/', '')).toBe(true);expect(canHydrate('/pages/perf-scenes/', '?scene=table')).toBe(false);expect(canHydrate('/pages/perf-scenes/', '')).toBe(true);});