From a91177dc94bdd4ca9c1dfcfdb76ce5daf3ebc183 Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 30 Nov 2026 20:56:36 +0000 Subject: [PATCH 1/6] feat: React stack The chat page and its components on React, mirroring Vue's names and test ids: Streamdown for Markdown (classes copied from vue-stream-markdown, so replies look the same), @ai-sdk/react, the shadcn React registry's message scroller and code block. composer.json lists both frameworks. Shared browser code no longer imports Vue: webmcp.ts offers a listener in place of a ref, and stored.ts keeps what the browser refuses to store in memory. Vue's copy button keeps the label it is given. composer.json also autoloads tests/Support for the E2E helper. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- composer.json | 6 +- package.json | 3 + .../saucebase-ai-chat-development/SKILL.md | 12 +- resources/js/lib/stored.test.ts | 51 ++ resources/js/lib/stored.ts | 41 + resources/js/lib/webmcp.test.ts | 23 +- resources/js/lib/webmcp.ts | 28 +- resources/js/react/app.tsx | 33 + resources/js/react/chat.css | 60 ++ .../js/react/components/ChatArtifact.tsx | 100 +++ .../js/react/components/ChatCodeBlock.tsx | 70 ++ resources/js/react/components/ChatImage.tsx | 64 ++ resources/js/react/components/ChatInput.tsx | 213 +++++ .../js/react/components/ChatInputBar.tsx | 47 ++ .../js/react/components/ChatMarkdown.tsx | 136 +++ resources/js/react/components/ChatMessage.tsx | 109 +++ resources/js/react/components/ChatPanel.tsx | 63 ++ .../js/react/components/ChatScrollButton.tsx | 57 ++ .../js/react/components/ChatSessions.tsx | 490 +++++++++++ resources/js/react/components/ChatSources.tsx | 49 ++ resources/js/react/components/ChatSteps.tsx | 164 ++++ .../js/react/components/ChatUsageBar.tsx | 71 ++ .../js/react/components/WebMcpMenuItem.tsx | 233 ++++++ resources/js/react/components/artifact.ts | 16 + resources/js/react/components/ui/bubble.tsx | 124 +++ resources/js/react/components/ui/button.tsx | 66 ++ .../js/react/components/ui/code-block.tsx | 249 ++++++ .../js/react/components/ui/hover-card.tsx | 41 + .../react/components/ui/message-scroller.tsx | 129 +++ resources/js/react/components/ui/message.tsx | 91 ++ resources/js/react/components/ui/spinner.tsx | 10 + resources/js/react/components/ui/trace.tsx | 162 ++++ .../js/react/hooks/use-highlighted-code.ts | 79 ++ resources/js/react/hooks/useDictation.ts | 94 +++ resources/js/react/hooks/useStored.ts | 30 + resources/js/react/lib/highlighter.tsx | 126 +++ resources/js/react/pages/Index.tsx | 774 ++++++++++++++++++ .../js/vue/components/WebMcpMenuItem.vue | 13 +- .../ui/code-block/CodeBlockCopyButton.vue | 2 +- 40 files changed, 4115 insertions(+), 19 deletions(-) create mode 100644 resources/js/lib/stored.test.ts create mode 100644 resources/js/lib/stored.ts create mode 100644 resources/js/react/app.tsx create mode 100644 resources/js/react/chat.css create mode 100644 resources/js/react/components/ChatArtifact.tsx create mode 100644 resources/js/react/components/ChatCodeBlock.tsx create mode 100644 resources/js/react/components/ChatImage.tsx create mode 100644 resources/js/react/components/ChatInput.tsx create mode 100644 resources/js/react/components/ChatInputBar.tsx create mode 100644 resources/js/react/components/ChatMarkdown.tsx create mode 100644 resources/js/react/components/ChatMessage.tsx create mode 100644 resources/js/react/components/ChatPanel.tsx create mode 100644 resources/js/react/components/ChatScrollButton.tsx create mode 100644 resources/js/react/components/ChatSessions.tsx create mode 100644 resources/js/react/components/ChatSources.tsx create mode 100644 resources/js/react/components/ChatSteps.tsx create mode 100644 resources/js/react/components/ChatUsageBar.tsx create mode 100644 resources/js/react/components/WebMcpMenuItem.tsx create mode 100644 resources/js/react/components/artifact.ts create mode 100644 resources/js/react/components/ui/bubble.tsx create mode 100644 resources/js/react/components/ui/button.tsx create mode 100644 resources/js/react/components/ui/code-block.tsx create mode 100644 resources/js/react/components/ui/hover-card.tsx create mode 100644 resources/js/react/components/ui/message-scroller.tsx create mode 100644 resources/js/react/components/ui/message.tsx create mode 100644 resources/js/react/components/ui/spinner.tsx create mode 100644 resources/js/react/components/ui/trace.tsx create mode 100644 resources/js/react/hooks/use-highlighted-code.ts create mode 100644 resources/js/react/hooks/useDictation.ts create mode 100644 resources/js/react/hooks/useStored.ts create mode 100644 resources/js/react/lib/highlighter.tsx create mode 100644 resources/js/react/pages/Index.tsx diff --git a/README.md b/README.md index 9d484f2..1993151 100644 --- a/README.md +++ b/README.md @@ -22,9 +22,9 @@ A module for [Saucebase](https://github.com/saucebase-dev/saucebase), the AI-rea - **Dictation** in the message box - **Admin panel**: provider API keys, the models users can pick, extra instructions, image settings, and a read-only conversation viewer - **Test mode**: a demo provider answers, so you can build and try the chat without a key or tokens -- **WebMCP**: the visitor's own browser agent can ask the assistant and read or switch chats +- **WebMCP** (beta, off until turned on): the visitor's own browser agent can ask the assistant and read or switch chats - **Two layouts**: a "Chat" item in the app sidebar and the chats in a panel of their own, or the chats in the app sidebar for a chat-first app -- **Vue** (React to come) +- **Vue and React** ## Install @@ -54,6 +54,7 @@ In the admin panel, under **Settings → AI chat** (people with the `manage ai c - **API keys** for each provider, stored encrypted. A key set in `.env` (laravel/ai's `config/ai.php`) works too, and the admin shows which keys come from there. - **Models**: the ones users can pick, and the default. Only providers with a key are offered. - **Instructions** added to the assistant's own. +- **WebMCP (beta)**: off by default. On, the chat offers its tools to the visitor's own browser agent, in browsers that support WebMCP (a draft standard). - **Images**: the provider, model and quality `generate_image` uses. `.env` can set them too (`AI_CHAT_IMAGE_PROVIDER`, `AI_CHAT_IMAGE_MODEL`, `AI_CHAT_IMAGE_QUALITY`); without either, laravel/ai's default for images. The conversation viewer is under **Chats**. diff --git a/composer.json b/composer.json index 7298c57..3de9433 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,8 @@ }, "saucebase": { "frameworks": [ - "vue" + "vue", + "react" ] }, "branch-alias": { @@ -29,7 +30,8 @@ "psr-4": { "Modules\\AiChat\\": "src/", "Modules\\AiChat\\Database\\Factories\\": "database/factories/", - "Modules\\AiChat\\Database\\Seeders\\": "database/seeders/" + "Modules\\AiChat\\Database\\Seeders\\": "database/seeders/", + "Modules\\AiChat\\Tests\\Support\\": "tests/Support/" } }, "autoload-dev": { diff --git a/package.json b/package.json index 33fc0c5..fd72fe2 100644 --- a/package.json +++ b/package.json @@ -3,9 +3,12 @@ "private": true, "type": "module", "dependencies": { + "@ai-sdk/react": "^4.0.181", "@ai-sdk/vue": "^4.0.181", + "@shadcn/react": "^0.3.1", "ai": "^7.0.181", "shiki": "^4.6.0", + "streamdown": "^2.8.1", "vue-stream-markdown": "^1.1.0" } } diff --git a/resources/boost/skills/saucebase-ai-chat-development/SKILL.md b/resources/boost/skills/saucebase-ai-chat-development/SKILL.md index ea019d6..586b26d 100644 --- a/resources/boost/skills/saucebase-ai-chat-development/SKILL.md +++ b/resources/boost/skills/saucebase-ai-chat-development/SKILL.md @@ -19,8 +19,8 @@ Paths are relative to `modules/ai-chat/` unless they say otherwise. Commands run | Admin | `src/Settings/AiChatSettings.php`, `src/Filament/Pages/AiChatSettings.php`, `src/Filament/Resources/Conversations/` | | Jobs | `src/Jobs/GenerateConversationTitle.php` | | Test mode | `src/Ai/Demo/` (`Demos`, `DemoProvider`, `DemoGateway`), demos in `resources/demos/*.json` | -| Page | `resources/js/vue/pages/Index.vue`, `components/ChatMessage.vue`, `ChatSteps.vue`, `ChatSessions.vue` (date groups, search, rename, delete), `ChatPanel.vue` (the list's own sidebar), `ChatScrollButton.vue`, `ChatInputBar.vue` (the strip above the box, `ChatInput`'s `top` slot), `ChatUsageBar.vue`, `WebMcpMenuItem.vue` | -| Browser lib | `resources/js/lib/tools.ts` (step labels, images), `sessions.ts` (date groups), `dictation.ts`, `chatTools.ts` + `webmcp.ts` (WebMCP) | +| Page | Vue and React mirror each other, same names and test ids: `resources/js/{vue,react}/pages/Index`, `components/ChatMessage.vue`, `ChatSteps.vue`, `ChatSessions.vue` (date groups, search, rename, delete), `ChatPanel.vue` (the list's own sidebar), `ChatScrollButton.vue`, `ChatInputBar.vue` (the strip above the box, `ChatInput`'s `top` slot), `ChatUsageBar.vue`, `WebMcpMenuItem.vue` | +| Browser lib | `resources/js/lib/tools.ts` (step labels, images), `sessions.ts` (date groups), `dictation.ts`, `chatTools.ts` + `webmcp.ts` (WebMCP). Plain TypeScript, shared by both stacks: no `vue` or `react` imports here | ## Adding a tool @@ -66,7 +66,7 @@ Search: `GET chat/sessions/search?q=` (`Sessions::search()`), the user's chats b ## WebMCP -`Index.vue` registers its tools with `registerWebMcpTools()`; `offeredTools` lists them for the sidebar's WebMCP panel (`dashboard::sidebar.end`), also in browsers without WebMCP, where it shows the steps to turn it on. +Beta: off until an admin turns it on (`AiChatSettings::$webmcp_enabled`, the page's `webmcp` prop). The page then registers its tools with `registerWebMcpTools()`; `offeredTools()` lists them (`onOfferedToolsChange()` to follow: React's `useSyncExternalStore`, a ref in Vue) for the sidebar's WebMCP panel (`dashboard::sidebar.end`), also in browsers without WebMCP, where it shows the steps to turn it on. ## Limits @@ -83,6 +83,12 @@ Search: `GET chat/sessions/search?q=` (`Sessions::search()`), the user's chats b - `ui/message-scroller/useMessageScroller.ts` is patched (`markHandled`): anchors already in a loaded transcript or a prepended page count as handled. Upstream, the first swap that kept the child count took the transcript's first question for a new one and scrolled to the top. Keep the patch when updating the component. - Messages are `content-visibility: auto`, sized at a 10rem estimate until laid out. A message arriving in the session starts `visible` and joins them two frames later (`settled` in `Index.vue`), once the browser has its real size: at the estimate, the scroller placed a new question 118px off and the view dropped, then jumped back when the reply ended. Loaded messages (the page's, older pages) are settled from the start. - The message box is opaque in dark mode too (`InputGroup`'s own `dark:bg-input/30` is see-through): a top bar runs under its edge. +- React renders Markdown with Streamdown, whose own elements carry Tailwind classes from its dist files, which the app doesn't scan (`@source` covers modules, not `node_modules`). `ChatMarkdown.tsx` gives every element it uses its own classes, vue-stream-markdown's values so replies match Vue, and drops Streamdown's `node` prop (`domProps()`), which would land in the HTML; `inlineCode` set makes `code` receive fenced blocks only (Streamdown's `pre` marks them, so leave `pre` alone). Vue's tables have a copy/download/fullscreen bar; React's have none yet. +- React's `ChatScrollButton` scrolls to the end when the last question's id changes, not the count: older pages prepended above raised the count and slid the view off them. +- The two stacks' UI kits differ in defaults; match Vue by hand: React's model `SelectContent` takes `position="popper"` (Radix defaults to item-aligned, a short scrolling list), and its phone sheet `preventDefault`s `onOpenAutoFocus` (Radix skips links and focuses the search box, bringing up a phone's keyboard). The React highlighter's languages mirror Vue's `ui/code-block/highlighter.ts`. +- A `SidebarMenuButton` tooltip opens on focus even when hidden (expanded, or on a phone) and takes the first Escape: in Vue's phone sheet Escape closed an invisible tooltip, not the sheet. `ChatSessions` gives New chat a tooltip only when collapsed to icons. +- React's page: the SDK's `onFinish`/`onError` are made with the first render, so they only record the event in state; effects act on it with current values. +- The panel's resize handle reads "Resize sidebar" in React (core's React `SidebarResizer` takes no label); Vue's falls through "Resize chat list". - A vue-stream-markdown node renderer (`ChatCodeBlock`) sets `inheritAttrs: false`: the library passes it `parentNode`, `markdownParser` and more, which would land on its root element, and `parentNode` warns on every streamed chunk. - `AiChatSettings` properties carry no `@var` array shapes: spatie/laravel-settings parses them for casts. diff --git a/resources/js/lib/stored.test.ts b/resources/js/lib/stored.test.ts new file mode 100644 index 0000000..a9305a1 --- /dev/null +++ b/resources/js/lib/stored.test.ts @@ -0,0 +1,51 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { readStored, subscribeStored, writeStored } from './stored'; + +function storage(failWrites = false) { + const items = new Map(); + + return { + getItem: (key: string) => items.get(key) ?? null, + setItem: (key: string, value: string) => { + if (failWrites) { + throw new Error('QuotaExceededError'); + } + + items.set(key, value); + }, + }; +} + +describe('stored values', () => { + afterEach(() => vi.unstubAllGlobals()); + + it('keeps a value in localStorage', () => { + vi.stubGlobal('localStorage', storage()); + + writeStored('ai-chat:test-kept', '320'); + + expect(readStored('ai-chat:test-kept')).toBe('320'); + }); + + // Private mode or a full quota: the change still holds for this page. + it('holds a value it could not store for the rest of the page', () => { + vi.stubGlobal('localStorage', storage(true)); + + writeStored('ai-chat:test-refused', '320'); + + expect(readStored('ai-chat:test-refused')).toBe('320'); + }); + + it('tells subscribers about a write', () => { + vi.stubGlobal('localStorage', storage()); + vi.stubGlobal('window', { addEventListener: vi.fn(), removeEventListener: vi.fn() }); + const listener = vi.fn(); + const stop = subscribeStored(listener); + + writeStored('ai-chat:test-told', '1'); + stop(); + writeStored('ai-chat:test-told', '2'); + + expect(listener).toHaveBeenCalledTimes(1); + }); +}); diff --git a/resources/js/lib/stored.ts b/resources/js/lib/stored.ts new file mode 100644 index 0000000..ab86989 --- /dev/null +++ b/resources/js/lib/stored.ts @@ -0,0 +1,41 @@ +/** + * Values kept in localStorage (as strings), with a store's subscribe for React's + * useSyncExternalStore. A value the browser refuses to store (private mode, a full quota) + * is held in memory instead, so the change still holds for the rest of the page. + */ +const refused = new Map(); +const listeners = new Set<() => void>(); + +export function readStored(key: string): string | null { + if (refused.has(key)) { + return refused.get(key) ?? null; + } + + try { + return localStorage.getItem(key); + } catch { + return null; + } +} + +export function writeStored(key: string, value: string): void { + try { + localStorage.setItem(key, value); + refused.delete(key); + } catch { + refused.set(key, value); + } + + listeners.forEach((listener) => listener()); +} + +/** Writes here, and in other tabs (the `storage` event). Returns the unsubscribe. */ +export function subscribeStored(listener: () => void): () => void { + listeners.add(listener); + window.addEventListener('storage', listener); + + return () => { + listeners.delete(listener); + window.removeEventListener('storage', listener); + }; +} diff --git a/resources/js/lib/webmcp.test.ts b/resources/js/lib/webmcp.test.ts index 46b1704..6ea8efd 100644 --- a/resources/js/lib/webmcp.test.ts +++ b/resources/js/lib/webmcp.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; import { chatTools, type ChatToolsContext } from './chatTools'; -import { offeredTools, registerWebMcpTools, type WebMcpTool } from './webmcp'; +import { offeredTools, onOfferedToolsChange, registerWebMcpTools, type WebMcpTool } from './webmcp'; function context(overrides: Partial = {}): ChatToolsContext { return { @@ -77,10 +77,27 @@ describe('registerWebMcpTools', () => { it('lists what the page offers until withdrawn, with or without WebMCP, so the panel can show it', () => { const withdraw = registerWebMcpTools(tools, {}); - expect(offeredTools.value.map((offered) => offered.name)).toEqual(tools.map((offered) => offered.name)); + expect(offeredTools().map((offered) => offered.name)).toEqual(tools.map((offered) => offered.name)); withdraw(); - expect(offeredTools.value).toEqual([]); + expect(offeredTools()).toEqual([]); + }); + + // Plain JavaScript, so both stacks read it: React through useSyncExternalStore, Vue through a ref. + it('tells listeners when the offer changes, and keeps one list between changes', () => { + const listener = vi.fn(); + const stop = onOfferedToolsChange(listener); + + const withdraw = registerWebMcpTools(tools, {}); + expect(listener).toHaveBeenCalledTimes(1); + expect(offeredTools()).toBe(offeredTools()); + + withdraw(); + expect(listener).toHaveBeenCalledTimes(2); + + stop(); + registerWebMcpTools(tools, {})(); + expect(listener).toHaveBeenCalledTimes(2); }); it('registers every tool and withdraws them all together', () => { diff --git a/resources/js/lib/webmcp.ts b/resources/js/lib/webmcp.ts index 48de0da..e4b4a0d 100644 --- a/resources/js/lib/webmcp.ts +++ b/resources/js/lib/webmcp.ts @@ -3,8 +3,6 @@ * the page, inside the user's session, so there are no tokens and no second * auth surface. https://github.com/webmachinelearning/webmcp */ -import { shallowRef } from 'vue'; - export interface WebMcpTool { name: string; description: string; @@ -26,8 +24,26 @@ interface ModelContext { ): Promise; } -/** What the open page offers, listed by the WebMCP panel even where the browser can't call it yet. */ -export const offeredTools = shallowRef([]); +let offered: WebMcpTool[] = []; +const listeners = new Set<() => void>(); + +function offer(tools: WebMcpTool[]): void { + offered = tools; + listeners.forEach((listener) => listener()); +} + +/** + * What the open page offers, listed by the WebMCP panel even where the browser can't call it + * yet. The same list until the offer changes, so React's useSyncExternalStore can read it. + */ +export const offeredTools = (): WebMcpTool[] => offered; + +/** Called on every change of the offer; returns the unsubscribe. Plain JavaScript, so both stacks read it. */ +export function onOfferedToolsChange(listener: () => void): () => void { + listeners.add(listener); + + return () => listeners.delete(listener); +} /** Whether this browser can hand the tools to an agent. */ export const webMcpSupported = typeof document !== 'undefined' && 'modelContext' in document; @@ -52,8 +68,8 @@ export function registerWebMcpTools( ): () => void { const context = target?.modelContext; - offeredTools.value = [...offeredTools.value, ...tools]; - const withdraw = () => (offeredTools.value = offeredTools.value.filter((offered) => !tools.includes(offered))); + offer([...offered, ...tools]); + const withdraw = () => offer(offered.filter((tool) => !tools.includes(tool))); if (!context) { return withdraw; diff --git a/resources/js/react/app.tsx b/resources/js/react/app.tsx new file mode 100644 index 0000000..e734abd --- /dev/null +++ b/resources/js/react/app.tsx @@ -0,0 +1,33 @@ +import { usePage } from '@inertiajs/react'; +import { registerGlobalComponent } from '@saucebase/react/lib/globalComponents'; +import { registerIcon } from '@saucebase/react/lib/navigation'; +import type { ComponentType } from 'react'; +import IconChat from '~icons/heroicons/chat-bubble-left-right'; +import { ChatSessions } from './components/ChatSessions'; +import { WebMcpMenuItem } from './components/WebMcpMenuItem'; + +/** Only while the list lives in the app sidebar (`ai-chat.sessions` = sidebar); else the chat's own panel holds it. */ +function inAppSidebar(Component: ComponentType): ComponentType { + return function InAppSidebar() { + const page = usePage(); + const where = (page.props.chat as { sessions_in?: string } | undefined) + ?.sessions_in; + + return where === 'sidebar' ? : null; + }; +} + +const SidebarSessions = inAppSidebar(ChatSessions); +const SidebarWebMcp = inAppSidebar(WebMcpMenuItem); + +/** + * Called before the first render, on the server too. + */ +export function setup() { + // The "Chat" item (routes/navigation.php), with the list on the chat page. + registerIcon('chat', IconChat); + // New chat and the history, in the app sidebar between the nav and the bottom links. + registerGlobalComponent('dashboard::sidebar.content', SidebarSessions); + // What the visitor's browser agent can do here, while a page offers WebMCP tools. + registerGlobalComponent('dashboard::sidebar.end', SidebarWebMcp); +} diff --git a/resources/js/react/chat.css b/resources/js/react/chat.css new file mode 100644 index 0000000..b9eda83 --- /dev/null +++ b/resources/js/react/chat.css @@ -0,0 +1,60 @@ +/* + * The chat fills the window below the header and scrolls inside, never the page. + * height: 1px makes the layout's min-height (the window, less an announcement + * banner) a definite height its flex children can fill. + */ +[data-slot='sidebar-wrapper']:has([data-chat-page]) { + height: 1px; +} + +[data-slot='sidebar-inset']:has([data-chat-page]) { + min-height: 0; + overflow: hidden; +} + +[data-slot='sidebar-inset'] > main:has([data-chat-page]) { + display: flex; + min-height: 0; + flex-direction: column; +} + +[data-slot='sidebar-inset'] + > main:has([data-chat-page]) + > .page-transition-wrapper { + min-height: 0; + flex: 1; +} + +/* The scroll button's dots while a reply streams. A fixed travel: animate-bounce moves a + quarter of the element's height, a 1px twitch on a 4px dot. */ +[data-chat-dots] > span { + width: 0.25rem; + height: 0.25rem; + border-radius: calc(infinity * 1px); + background-color: currentColor; + animation: ai-chat-dot-bounce 0.9s ease-in-out infinite; +} + +[data-chat-dots] > span:nth-child(2) { + animation-delay: 0.15s; +} + +[data-chat-dots] > span:nth-child(3) { + animation-delay: 0.3s; +} + +@keyframes ai-chat-dot-bounce { + 0%, + 100% { + transform: translateY(0); + } + 50% { + transform: translateY(-4px); + } +} + +@media (prefers-reduced-motion: reduce) { + [data-chat-dots] > span { + animation: none; + } +} diff --git a/resources/js/react/components/ChatArtifact.tsx b/resources/js/react/components/ChatArtifact.tsx new file mode 100644 index 0000000..906ae7e --- /dev/null +++ b/resources/js/react/components/ChatArtifact.tsx @@ -0,0 +1,100 @@ +import { useT } from '@saucebase/react/i18n'; +import IconDownload from '~icons/heroicons/arrow-down-tray'; +import IconClose from '~icons/heroicons/x-mark'; +import { useHighlightedCode } from '../hooks/use-highlighted-code'; +import type { Artifact } from './artifact'; +import { Button } from './ui/button'; +import { + CodeBlock, + CodeBlockActions, + CodeBlockContent, + CodeBlockCopyButton, + CodeBlockHeader, + CodeBlockLine, + CodeBlockTitle, +} from './ui/code-block'; + +/** + * A long code block or an image, opened beside the chat: a column on wide screens, the + * whole screen on phones. + */ +export function ChatArtifact({ + artifact, + onClose, +}: { + artifact: Artifact; + onClose: () => void; +}) { + const t = useT(); + const lines = useHighlightedCode( + artifact.kind === 'code' ? artifact.code : '', + artifact.kind === 'code' ? artifact.language : 'text', + ); + + return ( + + ); +} diff --git a/resources/js/react/components/ChatCodeBlock.tsx b/resources/js/react/components/ChatCodeBlock.tsx new file mode 100644 index 0000000..faf8e02 --- /dev/null +++ b/resources/js/react/components/ChatCodeBlock.tsx @@ -0,0 +1,70 @@ +import { useT } from '@saucebase/react/i18n'; +import IconExpand from '~icons/heroicons/arrows-pointing-out'; +import { useHighlightedCode } from '../hooks/use-highlighted-code'; +import { ARTIFACT_MIN_LINES, useOpenArtifact } from './artifact'; +import { Button } from './ui/button'; +import { + CodeBlock, + CodeBlockActions, + CodeBlockContent, + CodeBlockCopyButton, + CodeBlockHeader, + CodeBlockLine, + CodeBlockTitle, +} from './ui/code-block'; + +/** + * A fenced code block in a reply, highlighted as it streams, with copy; a long + * one also opens in the side panel. + */ +export function ChatCodeBlock({ + language, + code, +}: { + language: string; + code: string; +}) { + const t = useT(); + const lines = useHighlightedCode(code, language); + const openArtifact = useOpenArtifact(); + const long = code.split('\n').length >= ARTIFACT_MIN_LINES; + + return ( + + + {language} + + {openArtifact && long && ( + + )} + + + + + {lines.map((line, index) => ( + {line} + ))} + + + ); +} diff --git a/resources/js/react/components/ChatImage.tsx b/resources/js/react/components/ChatImage.tsx new file mode 100644 index 0000000..2133e73 --- /dev/null +++ b/resources/js/react/components/ChatImage.tsx @@ -0,0 +1,64 @@ +import { useT } from '@saucebase/react/i18n'; +import IconDownload from '~icons/heroicons/arrow-down-tray'; +import IconExpand from '~icons/heroicons/arrows-pointing-out'; +import type { GeneratedImage } from '../../lib/tools'; +import { useOpenArtifact } from './artifact'; +import { Button } from './ui/button'; + +/** An image the assistant made: opens large in the side panel, or downloads. */ +export function ChatImage({ image }: { image: GeneratedImage }) { + const t = useT(); + const openArtifact = useOpenArtifact(); + const open = () => + openArtifact?.({ kind: 'image', title: image.prompt, url: image.url }); + + return ( +
+ +
+ {openArtifact && ( + + )} + +
+ {image.prompt && ( +
+ {image.prompt} +
+ )} +
+ ); +} diff --git a/resources/js/react/components/ChatInput.tsx b/resources/js/react/components/ChatInput.tsx new file mode 100644 index 0000000..2fc9b14 --- /dev/null +++ b/resources/js/react/components/ChatInput.tsx @@ -0,0 +1,213 @@ +import { + InputGroup, + InputGroupAddon, + InputGroupButton, + InputGroupTextarea, +} from '@/components/ui/input-group'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import { cn } from '@/lib/utils'; +import { useT } from '@saucebase/react/i18n'; +import { + forwardRef, + type KeyboardEvent, + type ReactNode, + useImperativeHandle, + useRef, +} from 'react'; +import IconSend from '~icons/heroicons/arrow-up'; +import IconMic from '~icons/heroicons/microphone'; +import IconStop from '~icons/heroicons/stop'; +import IconStopSolid from '~icons/heroicons/stop-solid'; +import { type Usage, usageState } from '../../lib/usage'; +import { useDictation } from '../hooks/useDictation'; + +export type ChatInputHandle = { focus: () => void }; + +/** + * The message box: text, the model picker, voice input where the browser can listen (the + * Web Speech API; not Firefox), send or stop. `top` holds a ChatInputBar above it (the page + * puts the month's usage there). + */ +export const ChatInput = forwardRef< + ChatInputHandle, + { + value: string; + onValueChange: (value: string) => void; + model: string | null; + onModelChange: (model: string) => void; + /** The models the admin offers. Fewer than two: no picker. */ + models: { label: string; model: string }[]; + busy?: boolean; + usage?: Usage | null; + top?: ReactNode; + className?: string; + onSend: () => void; + onStop: () => void; + } +>(function ChatInput( + { + value, + onValueChange, + model, + onModelChange, + models, + busy, + usage, + top, + className, + onSend, + onStop, + }, + ref, +) { + const t = useT(); + const form = useRef(null); + const dictation = useDictation(value, onValueChange); + + // At the limit the server would refuse it: the text stays in the box instead. + const canSend = + value.trim() !== '' && !busy && usageState(usage ?? null) !== 'reached'; + + useImperativeHandle(ref, () => ({ + focus: () => form.current?.querySelector('textarea')?.focus(), + })); + + function send(): void { + dictation.stop(); + + if (canSend) { + onSend(); + } + } + + function onKeyDown(event: KeyboardEvent): void { + if ( + event.key === 'Enter' && + !event.shiftKey && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + send(); + } + } + + return ( +
{ + event.preventDefault(); + send(); + }} + > + {top} + {/* Opaque in dark mode too (the input's own bg-input/30 is see-through): a top bar runs under it. */} + + onValueChange(event.target.value)} + placeholder={ + dictation.listening + ? t('Listening…') + : t('Message the assistant') + } + aria-label={t('Message')} + rows={1} + maxLength={4000} + className="max-h-48 min-h-12" + data-testid="chat-input" + onKeyDown={onKeyDown} + /> + + {models.length > 1 && ( + + )} + + + + {dictation.supported && ( + + {dictation.listening ? ( + + ) : ( + + )} + + )} + + {busy ? ( + + + + ) : ( + + + + )} + + +
+ ); +}); diff --git a/resources/js/react/components/ChatInputBar.tsx b/resources/js/react/components/ChatInputBar.tsx new file mode 100644 index 0000000..504bf01 --- /dev/null +++ b/resources/js/react/components/ChatInputBar.tsx @@ -0,0 +1,47 @@ +import { cn } from '@/lib/utils'; +import { useT } from '@saucebase/react/i18n'; +import type { ComponentProps } from 'react'; +import IconClose from '~icons/heroicons/x-mark'; + +/** + * A strip above the message box, tucked behind its top edge: a notice, a mode, a + * shortcut. Goes in ChatInput's `top`. Its content is the children (text or any + * component); colours come in through `className` (`bg-orange-700 text-white`). + */ +export function ChatInputBar({ + className, + children, + onDismiss, + ...props +}: ComponentProps<'div'> & { + /** Shows a ✕ that calls it; the page decides whether the bar comes back. */ + onDismiss?: () => void; +}) { + const t = useT(); + + return ( + // pb-6/-mb-4: its bottom runs under the box, which is positioned and paints over it. +
+
+ {children} +
+ {onDismiss && ( + + )} +
+ ); +} diff --git a/resources/js/react/components/ChatMarkdown.tsx b/resources/js/react/components/ChatMarkdown.tsx new file mode 100644 index 0000000..ee37af7 --- /dev/null +++ b/resources/js/react/components/ChatMarkdown.tsx @@ -0,0 +1,136 @@ +import { cn } from '@/lib/utils'; +import { type Components, Streamdown } from 'streamdown'; +import { ChatCodeBlock } from './ChatCodeBlock'; + +/** + * Streamdown styles its own elements with Tailwind classes from its dist files, which the + * app's Tailwind doesn't scan (`@source` covers modules, not node_modules). So every element + * a reply uses is rendered here, with classes from this file, which it does scan. The classes + * are vue-stream-markdown's, so replies look the same on both stacks. + */ +/** Streamdown hands each element its syntax-tree `node`; spread as is, it lands in the HTML as `node="[object Object]"`. */ +function domProps(props: T): Omit { + const rest = { ...props }; + delete rest.node; + + return rest; +} + +const components: Components = { + h1: ({ children, ...props }) => ( +

+ {children} +

+ ), + h2: ({ children, ...props }) => ( +

+ {children} +

+ ), + h3: ({ children, ...props }) => ( +

+ {children} +

+ ), + h4: ({ children, ...props }) => ( +

+ {children} +

+ ), + h5: ({ children, ...props }) => ( +
+ {children} +
+ ), + h6: ({ children, ...props }) => ( +
+ {children} +
+ ), + p: (props) =>

, + ul: (props) => ( +

    + ), + ol: (props) => ( +
      + ), + li: (props) =>
    1. , + strong: (props) => ( + + ), + a: ({ href, children, ...props }) => ( + + {children} + + ), + blockquote: (props) => ( +
      + ), + hr: () =>
      , + table: (props) => ( +
      + + + ), + th: (props) => ( +
      + ), + td: (props) => ( + + ), + img: ({ alt, ...props }) => ( + {alt + ), + // With `inlineCode` set, Streamdown sends `code` only fenced blocks (its `pre` marks them). + code: ({ className, children }) => ( + + ), + inlineCode: ({ children }) => ( + + {children} + + ), +}; + +/** A reply's text as Markdown, as it streams; code blocks are ours (highlight, copy, panel). */ +export function ChatMarkdown({ + content, + className, +}: { + content: string; + className?: string; +}) { + return ( + *:first-child]:mt-0! [&>*:last-child]:mb-0!', + className, + )} + > + {content} + + ); +} diff --git a/resources/js/react/components/ChatMessage.tsx b/resources/js/react/components/ChatMessage.tsx new file mode 100644 index 0000000..92fb937 --- /dev/null +++ b/resources/js/react/components/ChatMessage.tsx @@ -0,0 +1,109 @@ +import { cn } from '@/lib/utils'; +import { useT } from '@saucebase/react/i18n'; +import type { UIMessage } from 'ai'; +import type { ComponentProps } from 'react'; +import IconRetry from '~icons/heroicons/arrow-path'; +import { + imagesIn, + showsNothing, + sourcesIn, + type Step, + stepsIn, +} from '../../lib/tools'; +import { ChatImage } from './ChatImage'; +import { ChatMarkdown } from './ChatMarkdown'; +import { ChatSources } from './ChatSources'; +import { ChatSteps } from './ChatSteps'; +import { Bubble, BubbleContent } from './ui/bubble'; +import { Button } from './ui/button'; +import { CodeBlockCopyButton } from './ui/code-block'; +import { Message, MessageContent, MessageFooter } from './ui/message'; + +type Parts = Parameters[0]; + +// Before the first words: the same line the reasoning will take over, so nothing moves. +const waiting: Step[] = [{ kind: 'reasoning', text: '', streaming: true }]; + +/** One turn of the conversation: the user's bubble, or the assistant's steps, answer and its actions. */ +export function ChatMessage({ + message, + streaming, + last, + onRetry, + ...props +}: Omit, 'children'> & { + message: Pick; + streaming?: boolean; + /** The newest reply: it can be asked again. */ + last?: boolean; + onRetry?: () => void; +}) { + const t = useT(); + const text = message.parts + .filter((part) => part.type === 'text') + .map((part) => part.text) + .join(''); + + if (message.role === 'user') { + return ( + + + + {text} + + + + ); + } + + const parts = message.parts as Parts; + + return ( + + + + {imagesIn(parts).map((image) => ( + + ))} + {text && } + + + {text && !streaming && ( + + + {last && ( + + )} + + )} + + ); +} diff --git a/resources/js/react/components/ChatPanel.tsx b/resources/js/react/components/ChatPanel.tsx new file mode 100644 index 0000000..199edc3 --- /dev/null +++ b/resources/js/react/components/ChatPanel.tsx @@ -0,0 +1,63 @@ +import { SidebarResizer } from '@/components/SidebarResizer'; +import { + Sidebar, + SidebarContent, + SidebarFooter, + SidebarProvider, +} from '@/components/ui/sidebar'; +import { clampSidebarWidth } from '@/hooks/useSidebarState'; +import { cn } from '@/lib/utils'; +import { type CSSProperties, useState } from 'react'; +import { useStored } from '../hooks/useStored'; +import { ChatSessions } from './ChatSessions'; +import { WebMcpMenuItem } from './WebMcpMenuItem'; + +/** + * The chat's own sidebar (`ai-chat.sessions` = page): New chat, search and the chats, WebMCP + * at the foot, beside the app sidebar. A sidebar of its own (a nested provider), so the list's + * sidebar parts work as in the app's; resizable, its width kept apart from the app sidebar's. + */ +export function ChatPanel({ className }: { className?: string }) { + const [stored, setStored] = useStored( + 'ai-chat:panel-width', + null, + ); + const width = + typeof stored === 'number' && Number.isFinite(stored) + ? clampSidebarWidth(stored) + : null; + const [resizing, setResizing] = useState(false); + + return ( + + + + + + + + + + {/* contained: on this panel's edge, measured from its left, not fixed to the window. */} + + + ); +} diff --git a/resources/js/react/components/ChatScrollButton.tsx b/resources/js/react/components/ChatScrollButton.tsx new file mode 100644 index 0000000..8e98e5d --- /dev/null +++ b/resources/js/react/components/ChatScrollButton.tsx @@ -0,0 +1,57 @@ +import { useT } from '@saucebase/react/i18n'; +import { useEffect, useRef } from 'react'; +import IconArrowDown from '~icons/heroicons/arrow-down'; +import { + MessageScrollerButton, + useMessageScroller, +} from './ui/message-scroller'; + +/** + * The end of the chat. A new question takes the view to the end once, so it shows above the + * box; then the reply never drags the view, and while the end is out of view this button sits + * over it, as in ChatGPT: dots while the reply streams below, then an arrow; either goes there. + */ +export function ChatScrollButton({ + busy, + question, +}: { + busy?: boolean; + /** + * The id of the chat's last question: another one was just asked. Not a count of them, + * which older messages loaded above also raise (the view then slid off them to the end). + */ + question: string | undefined; +}) { + const t = useT(); + const { scrollToEnd } = useMessageScroller(); + const before = useRef(question); + + useEffect(() => { + if (question !== before.current) { + scrollToEnd({ behavior: 'smooth' }); + } + + before.current = question; + }, [question, scrollToEnd]); + + return ( + + {busy ? ( + + + + + + ) : ( + + )} + + {busy ? t('Generating response') : t('Scroll to the end')} + + + ); +} diff --git a/resources/js/react/components/ChatSessions.tsx b/resources/js/react/components/ChatSessions.tsx new file mode 100644 index 0000000..286c7c5 --- /dev/null +++ b/resources/js/react/components/ChatSessions.tsx @@ -0,0 +1,490 @@ +import { + AlertDialog, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog'; +import { Button } from '@/components/ui/button'; +import { + Collapsible, + CollapsibleContent, + CollapsibleTrigger, +} from '@/components/ui/collapsible'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; +import { + SidebarGroup, + SidebarGroupContent, + SidebarGroupLabel, + SidebarInput, + SidebarMenu, + SidebarMenuAction, + SidebarMenuButton, + SidebarMenuItem, + useSidebar, +} from '@/components/ui/sidebar'; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from '@/components/ui/tooltip'; +import { Link, router, usePage } from '@inertiajs/react'; +import { useT } from '@saucebase/react/i18n'; +import { useCallback, useEffect, useRef, useState } from 'react'; +import IconChevronRight from '~icons/heroicons/chevron-right'; +import IconHistory from '~icons/heroicons/clock'; +import IconMore from '~icons/heroicons/ellipsis-horizontal'; +import IconRename from '~icons/heroicons/pencil'; +import IconNewChat from '~icons/heroicons/pencil-square'; +import IconDelete from '~icons/heroicons/trash'; +import IconPin from '~icons/lucide/pin'; +import IconUnpin from '~icons/lucide/pin-off'; +import { + groupSessions, + type Session, + type SessionList, +} from '../../lib/sessions'; + +const update = { only: ['chat'], preserveScroll: true, preserveState: true }; + +/** + * New chat, search and the user's chats: in the app sidebar (core's + * `dashboard::sidebar.content`) when `ai-chat.sessions` is `sidebar`, in the chat's own + * panel (ChatPanel) when it is `page`. + */ +export function ChatSessions() { + const t = useT(); + const page = usePage(); + const { toggleSidebar } = useSidebar(); + + const list = (page.props.chat as { sessions?: SessionList } | undefined) + ?.sessions; + const sessions = list?.data ?? []; + + // Searched on the server, by title: the list holds only the newest chats. + const [query, setQuery] = useState(''); + const [found, setFound] = useState(null); + const latestQuery = useRef(query); + latestQuery.current = query; + + const search = useCallback(async (text: string) => { + const q = text.trim(); + + if (!q) { + setFound(null); + + return; + } + + try { + const response = await fetch( + route('ai-chat.sessions.search', { q }), + { + headers: { Accept: 'application/json' }, + }, + ); + + // A later keystroke may have answered first. + if (response.ok && latestQuery.current.trim() === q) { + setFound(((await response.json()) as { data: Session[] }).data); + } + } catch { + // Offline: the results stay as they were, and the next keystroke tries again. + } + }, []); + + useEffect(() => { + const timer = setTimeout(() => search(query), 250); + + return () => clearTimeout(timer); + }, [query, search]); + + // A rename, pin or delete reloads the list: the results follow it. + const searching = useRef(false); + searching.current = found !== null; + useEffect(() => { + if (searching.current) { + search(latestQuery.current); + } + }, [list, search]); + + const results = found?.length + ? [{ label: 'Search results', sessions: found }] + : []; + const groups = found === null ? groupSessions(sessions) : results; + + // From the URL, so the highlight is right on every page the sidebar renders on. + const currentId = page.url.match(/^\/chat\/([^/?#]+)/)?.[1] ?? null; + + // Rename in place: Enter or leaving the field saves, Escape cancels. + const [renaming, setRenaming] = useState(null); + const [draft, setDraft] = useState(''); + + // The menu hands focus back to its trigger as it closes, which would blur (and so save) the + // field just opened: on that close, the field takes it instead. + function focusRename(event: Event): void { + const field = document.querySelector( + 'input[data-testid^="chat-rename-"]', + ); + + if (field) { + event.preventDefault(); + field.select(); + } + } + + function saveRename(session: Session): void { + const title = draft.trim(); + setRenaming(null); + + if (title && title !== session.title) { + router.patch( + route('ai-chat.update', session.id), + { title }, + update, + ); + } + } + + function togglePin(session: Session): void { + router.patch( + route('ai-chat.update', session.id), + { pinned: !session.pinned_at }, + update, + ); + } + + // The server lists a page more from now on, so every later reload keeps them. + const [loadingMore, setLoadingMore] = useState(false); + + function showMore(): void { + router.post( + route('ai-chat.sessions.more'), + {}, + { + ...update, + onStart: () => setLoadingMore(true), + onFinish: () => setLoadingMore(false), + }, + ); + } + + const [deleting, setDeleting] = useState(null); + + function confirmDelete(): void { + if (deleting) { + // The server stays on the open chat, or moves to a new one when that was the one deleted. + router.delete(route('ai-chat.destroy', deleting.id), { + preserveScroll: true, + }); + setDeleting(null); + } + } + + return ( + <> + + + + + + + + {t('New chat')} + + + + + {sessions.length > 0 && ( + + + setQuery(event.target.value) + } + type="search" + placeholder={t('Search chats')} + aria-label={t('Search chats')} + data-testid="chat-search" + onKeyDown={(event) => + event.key === 'Escape' && setQuery('') + } + /> + + )} + + {/* Collapsed, the list is hidden and this opens the sidebar to it. */} + + + + {t('Chat history')} + + + + + + + {/* The sidebar's only scroll container: min-h-0 lets it take the leftover height and scroll. */} + {sessions.length > 0 && ( + + + + + {t('Chats')} + + + + + + {groups.map((group) => ( + +

      + {t(group.label)} +

      + + {group.sessions.map((session) => ( + + {renaming === session.id ? ( + + setDraft( + event.target + .value, + ) + } + maxLength={100} + aria-label={t( + 'Chat name', + )} + className="bg-background ring-sidebar-ring h-8 w-full rounded-md px-2 text-sm outline-hidden focus-visible:ring-2" + data-testid={`chat-rename-${session.id}`} + onKeyDown={(event) => { + if ( + event.key === + 'Enter' + ) { + event.preventDefault(); + saveRename( + session, + ); + } else if ( + event.key === + 'Escape' + ) { + event.preventDefault(); + setRenaming( + null, + ); + } + }} + onBlur={() => + saveRename(session) + } + /> + ) : ( + <> + + + + { + session.title + } + + + + + {/* The tooltip's trigger fills the button rather than wrapping + it, as in the Vue version: a menu trigger wrapped in a + tooltip anchors to the tooltip. */} + + + + + + + + + + {t( + 'More', + )} + + + + + + + togglePin( + session, + ) + } + > + {session.pinned_at ? ( + + ) : ( + + )} + {session.pinned_at + ? t( + 'Unpin', + ) + : t( + 'Pin', + )} + + { + setDraft( + session.title, + ); + setRenaming( + session.id, + ); + }} + > + + {t( + 'Rename', + )} + + + setDeleting( + session, + ) + } + > + + {t( + 'Delete', + )} + + + + + )} + + ))} + +
      + ))} + + {found !== null && !found.length && ( +

      + {t('No chats found')} +

      + )} + + {found === null && list?.has_more && ( + + + + {t('Show more')} + + + + )} +
      +
      +
      + )} + + !open && setDeleting(null)} + > + + + {t('Delete chat?')} + + {t( + '“:title” and its messages will be deleted. This can’t be undone.', + { + title: deleting?.title ?? '', + }, + )} + + + + {t('Cancel')} + + + + + + ); +} diff --git a/resources/js/react/components/ChatSources.tsx b/resources/js/react/components/ChatSources.tsx new file mode 100644 index 0000000..3f3df83 --- /dev/null +++ b/resources/js/react/components/ChatSources.tsx @@ -0,0 +1,49 @@ +import { useT } from '@saucebase/react/i18n'; +import IconLink from '~icons/heroicons/link'; +import type { Source } from '../../lib/tools'; +import { HoverCard, HoverCardContent, HoverCardTrigger } from './ui/hover-card'; + +const host = (url: string) => new URL(url).hostname.replace(/^www\./, ''); + +/** The links a reply cited, under it: a chip each, the full title and address on hover. */ +export function ChatSources({ sources }: { sources: Source[] }) { + const t = useT(); + + if (!sources.length) { + return null; + } + + return ( +
      + + {t('Sources')} + + {sources.map((source, index) => ( + + + + {index + 1} + {host(source.url)} + + + +

      {source.title}

      +

      + + {source.url} +

      +
      +
      + ))} +
      + ); +} diff --git a/resources/js/react/components/ChatSteps.tsx b/resources/js/react/components/ChatSteps.tsx new file mode 100644 index 0000000..bb93319 --- /dev/null +++ b/resources/js/react/components/ChatSteps.tsx @@ -0,0 +1,164 @@ +import { useT } from '@saucebase/react/i18n'; +import IconCheck from '~icons/heroicons/check-circle'; +import IconError from '~icons/heroicons/exclamation-circle'; +import IconBrain from '~icons/heroicons/light-bulb'; +import { type Step, toolLabel } from '../../lib/tools'; +import { ChatMarkdown } from './ChatMarkdown'; +import { Spinner } from './ui/spinner'; +import { + Trace, + TraceCollapsible, + TraceCollapsibleContent, + TraceCollapsibleTrigger, + TraceIcon, + TraceLine, + TraceTitle, +} from './ui/trace'; + +function asJson(value: unknown): string { + if (typeof value === 'string') { + try { + return JSON.stringify(JSON.parse(value), null, 2); + } catch { + return value; + } + } + + return JSON.stringify(value, null, 2); +} + +/** A tool's line: spinning while it runs, red when it failed. */ +function toolStatus( + step: Step, + streaming?: boolean, +): 'running' | 'error' | undefined { + if (step.kind === 'reasoning') { + return undefined; + } + + if (step.state === 'failed') { + return 'error'; + } + + return step.state === 'running' && streaming ? 'running' : undefined; +} + +function ToolIcon({ status }: { status: 'running' | 'error' | undefined }) { + if (status === 'running') { + return ; + } + + return status === 'error' ? : ; +} + +const hasInput = (input: unknown) => + input !== undefined && + !(Array.isArray(input) && input.length === 0) && + !( + typeof input === 'object' && + input !== null && + Object.keys(input).length === 0 + ); + +/** + * What the assistant did before answering: its reasoning and the tools it called, in + * order, each line opening onto its detail. + * + * Reasoning is built on Trace, like shadcn's Reasoning: a plain "Thinking…" line until its + * first words, then a closed line that opens onto the thought. Closed while it streams too: + * a thought that opened, grew and closed again moved the reply under the reader and pulled + * the view back up. + */ +export function ChatSteps({ + steps, + streaming, +}: { + steps: Step[]; + /** The reply is still coming: an unfinished line spins. */ + streaming?: boolean; +}) { + const t = useT(); + + if (!steps.length) { + return null; + } + + const thinking = (step: Step) => + step.kind === 'reasoning' && !!streaming && step.streaming; + + return ( + + {steps.map((step, index) => + // No words yet: nothing to open. + step.kind === 'reasoning' && !step.text ? ( + + + + + {t('Thinking…')} + + ) : ( + + + {step.kind === 'reasoning' ? ( + + + + + + {thinking(step) + ? t('Thinking…') + : t('Thought')} + + + ) : ( + + + + + + {t(toolLabel(step.name, step.state))} + + + )} + + + {step.kind === 'reasoning' ? ( + // Markdown, like a reply: models write their thoughts with headings and bold. + + ) : ( +
      + {hasInput(step.input) && ( +
      +                                            {asJson(step.input)}
      +                                        
      + )} + {step.error ? ( +

      + {step.error} +

      + ) : ( + step.output !== undefined && ( +
      +                                                {asJson(step.output)}
      +                                            
      + ) + )} +
      + )} +
      +
      + ), + )} +
      + ); +} diff --git a/resources/js/react/components/ChatUsageBar.tsx b/resources/js/react/components/ChatUsageBar.tsx new file mode 100644 index 0000000..9a47ec7 --- /dev/null +++ b/resources/js/react/components/ChatUsageBar.tsx @@ -0,0 +1,71 @@ +import { Link } from '@inertiajs/react'; +import { useT } from '@saucebase/react/i18n'; +import { type Usage, usageState } from '../../lib/usage'; +import { useStored } from '../hooks/useStored'; +import { ChatInputBar } from './ChatInputBar'; + +const month = () => new Date().toISOString().slice(0, 7); + +/** + * The month's messages, above the box: a muted bar from 80% of the allowance (dismissed + * until next month), an orange one at the limit, which stays. + */ +export function ChatUsageBar({ usage }: { usage: Usage | null }) { + const t = useT(); + const [dismissed, setDismissed] = useStored('ai-chat:usage-dismissed', ''); + const state = usageState(usage); + + if (!usage) { + return null; + } + + const upgrade = (className: string) => + usage.upgrade_url && ( + + {t('Upgrade')} + + ); + + if (state === 'reached') { + return ( + + + {t("You've used all :limit messages this month.", { + limit: String(usage.limit), + })} + + {upgrade( + 'font-medium underline underline-offset-2 hover:no-underline', + )} + + ); + } + + if (state === 'counting' && dismissed !== month()) { + return ( + setDismissed(month())} + > + + {t("You've used :used of :limit messages this month.", { + used: String(usage.used), + limit: String(usage.limit), + })} + + {upgrade( + 'text-foreground font-medium underline underline-offset-2 hover:no-underline', + )} + + ); + } + + return null; +} diff --git a/resources/js/react/components/WebMcpMenuItem.tsx b/resources/js/react/components/WebMcpMenuItem.tsx new file mode 100644 index 0000000..f611402 --- /dev/null +++ b/resources/js/react/components/WebMcpMenuItem.tsx @@ -0,0 +1,233 @@ +import { Badge } from '@/components/ui/badge'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog'; +import { + SidebarGroup, + SidebarGroupContent, + SidebarMenu, + SidebarMenuBadge, + SidebarMenuButton, + SidebarMenuItem, +} from '@/components/ui/sidebar'; +import { useT } from '@saucebase/react/i18n'; +import { useEffect, useState, useSyncExternalStore } from 'react'; +import IconBot from '~icons/lucide/bot'; +import IconBotOff from '~icons/lucide/bot-off'; +import IconCheck from '~icons/lucide/check'; +import IconCopy from '~icons/lucide/copy'; +import IconEye from '~icons/lucide/eye'; +import IconPencil from '~icons/lucide/pencil'; +import { + offeredTools, + onOfferedToolsChange, + webMcpSupported, + type WebMcpTool, +} from '../../lib/webmcp'; +import { Button } from './ui/button'; + +// The server offers no tools: one list, so React reads the same snapshot every time. +const NONE: WebMcpTool[] = []; + +/** + * What the visitor's own browser agent can do on this page (core's + * `dashboard::sidebar.end`). Shown only while a page offers tools; without WebMCP in the + * browser it lists them anyway, with the steps to turn it on. + */ +export function WebMcpMenuItem() { + const t = useT(); + const tools = useSyncExternalStore( + onOfferedToolsChange, + offeredTools, + () => NONE, + ); + const [copied, setCopied] = useState(false); + + useEffect(() => { + if (!copied) { + return; + } + + const timer = setTimeout(() => setCopied(false), 2000); + + return () => clearTimeout(timer); + }, [copied]); + + if (!tools.length) { + return null; + } + + const label = webMcpSupported ? 'WebMCP tools' : 'WebMCP is available'; + const Icon = webMcpSupported ? IconBot : IconBotOff; + const prompt = t( + "Open :url. Discover and use this page's WebMCP tools to help me", + { + url: route('ai-chat.index'), + }, + ); + + return ( + + + + + + + + + {t(label)} + + + + + {webMcpSupported ? ( + + {tools.length} + + ) : ( + + {t('Off')} + + )} + + + + + + + {t('WebMCP')} + + {tools.length} + + + + {webMcpSupported + ? t( + 'Your AI agent can call any of these directly, as you.', + ) + : t( + 'Your own AI agent could operate this page. Two steps to enable it:', + )} + + + + {/* chrome:// URLs can't be linked from a page, so they are shown to copy. */} + {!webMcpSupported && ( +
        +
      1. + + chrome://flags/#enable-webmcp-testing + {' '} + → {t('Enabled')} → {t('Relaunch')} +
      2. +
      3. + + chrome://inspect/#remote-debugging + {' '} + → {t('allow remote debugging')} +
      4. +
      + )} + +
      +
      +

      + {t('Prompt for your agent')} +

      + +
      +

      + {prompt} +

      +
      + +
        + {tools.map((tool) => { + const ToolIcon = tool.readOnly + ? IconEye + : IconPencil; + + return ( +
      • +
        + + + {tool.name} + +
        +

        + {tool.description} +

        +
      • + ); + })} +
      +
      +
      +
      +
      +
      +
      + ); +} diff --git a/resources/js/react/components/artifact.ts b/resources/js/react/components/artifact.ts new file mode 100644 index 0000000..3bc1eab --- /dev/null +++ b/resources/js/react/components/artifact.ts @@ -0,0 +1,16 @@ +import { createContext, useContext } from 'react'; + +/** A piece of a reply opened on its own, beside the chat: a long code block or an image. */ +export type Artifact = + | { kind: 'code'; title: string; language: string; code: string } + | { kind: 'image'; title: string; url: string }; + +/** Provided by the chat page; replies call it to open an artifact in the side panel. */ +export const OpenArtifactContext = createContext< + ((artifact: Artifact) => void) | null +>(null); + +export const useOpenArtifact = () => useContext(OpenArtifactContext); + +/** Code at least this long is worth a panel of its own. */ +export const ARTIFACT_MIN_LINES = 15; diff --git a/resources/js/react/components/ui/bubble.tsx b/resources/js/react/components/ui/bubble.tsx new file mode 100644 index 0000000..21ba391 --- /dev/null +++ b/resources/js/react/components/ui/bubble.tsx @@ -0,0 +1,124 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" +import { cn } from "@/lib/utils" +import { Slot } from "radix-ui" + +function BubbleGroup({ className, ...props }: React.ComponentProps<"div">) { + return ( +
      + ) +} + +const bubbleVariants = cva( + "group/bubble relative flex w-fit max-w-[80%] min-w-0 flex-col gap-1 group-data-[align=end]/message:self-end data-[align=end]:self-end data-[variant=ghost]:max-w-full", + { + variants: { + variant: { + default: + "*:data-[slot=bubble-content]:bg-primary *:data-[slot=bubble-content]:text-primary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-primary/80", + secondary: + "*:data-[slot=bubble-content]:bg-secondary *:data-[slot=bubble-content]:text-secondary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)]", + muted: + "*:data-[slot=bubble-content]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--muted),var(--foreground)_5%)]", + tinted: + "*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.93_calc(c*0.4)_h)] *:data-[slot=bubble-content]:text-foreground dark:*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.3_calc(c*0.4)_h)] [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.88_calc(c*0.5)_h)] dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.35_calc(c*0.5)_h)]", + outline: + "*:data-[slot=bubble-content]:border-border *:data-[slot=bubble-content]:bg-background [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-input/30", + ghost: + "border-none *:data-[slot=bubble-content]:rounded-none *:data-[slot=bubble-content]:bg-transparent *:data-[slot=bubble-content]:p-0 [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted/50", + destructive: + "*:data-[slot=bubble-content]:bg-destructive/10 *:data-[slot=bubble-content]:text-destructive dark:*:data-[slot=bubble-content]:bg-destructive/20 [&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/20 dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/30", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +function Bubble({ + variant = "default", + align = "start", + className, + ...props +}: React.ComponentProps<"div"> & + VariantProps & { + align?: "start" | "end" + }) { + return ( +
      + ) +} + +function BubbleContent({ + asChild = false, + className, + ...props +}: React.ComponentProps<"div"> & { + asChild?: boolean +}) { + const Comp = asChild ? Slot.Root : "div" + + return ( + + ) +} + +const bubbleReactionsVariants = cva( + "absolute z-10 flex w-fit shrink-0 items-center justify-center gap-1 rounded-full bg-muted px-1.5 py-0.5 text-sm ring-3 ring-card has-[button]:p-0", + { + variants: { + side: { + top: "top-0 -translate-y-3/4", + bottom: "bottom-0 translate-y-3/4", + }, + align: { + start: "left-3", + end: "right-3", + }, + }, + defaultVariants: { + side: "bottom", + align: "end", + }, + } +) + +function BubbleReactions({ + side = "bottom", + align = "end", + className, + ...props +}: React.ComponentProps<"div"> & { + align?: "start" | "end" + side?: "top" | "bottom" +}) { + return ( +
      + ) +} + +export { BubbleGroup, Bubble, BubbleContent, BubbleReactions } diff --git a/resources/js/react/components/ui/button.tsx b/resources/js/react/components/ui/button.tsx new file mode 100644 index 0000000..d9c37b0 --- /dev/null +++ b/resources/js/react/components/ui/button.tsx @@ -0,0 +1,66 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" +import { cn } from "@/lib/utils" +import { Slot } from "radix-ui" + +const buttonVariants = cva( + "group/button inline-flex shrink-0 items-center justify-center rounded-md border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground hover:bg-primary/80", + outline: + "border-border bg-background shadow-xs hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50", + secondary: + "bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground", + ghost: + "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50", + destructive: + "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: + "h-9 gap-1.5 px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2", + xs: "h-6 gap-1 rounded-[min(var(--radius-md),8px)] px-2 text-xs in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3", + sm: "h-8 gap-1 rounded-[min(var(--radius-md),10px)] px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5", + lg: "h-10 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2", + icon: "size-9", + "icon-xs": + "size-6 rounded-[min(var(--radius-md),8px)] in-data-[slot=button-group]:rounded-md [&_svg:not([class*='size-'])]:size-3", + "icon-sm": + "size-8 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-md", + "icon-lg": "size-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +function Button({ + className, + variant = "default", + size = "default", + asChild = false, + ...props +}: React.ComponentProps<"button"> & + VariantProps & { + asChild?: boolean + }) { + const Comp = asChild ? Slot.Root : "button" + + return ( + + ) +} + +export { Button, buttonVariants } diff --git a/resources/js/react/components/ui/code-block.tsx b/resources/js/react/components/ui/code-block.tsx new file mode 100644 index 0000000..a1d68c7 --- /dev/null +++ b/resources/js/react/components/ui/code-block.tsx @@ -0,0 +1,249 @@ +"use client" + +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" +import { cn } from "@/lib/utils" + +import { Button } from "./button" +import { CheckIcon, CopyIcon } from "lucide-react" + +const codeBlockVariants = cva( + "group/code-block relative flex w-full min-w-0 flex-col overflow-hidden rounded-lg text-sm has-[>[data-slot=code-block-content]:focus-visible]:ring-3 has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/50 data-[size=sm]:text-xs", + { + variants: { + variant: { + default: + "border border-input text-foreground has-[>[data-slot=code-block-content]:focus-visible]:border-ring dark:bg-input/30", + destructive: + "border border-destructive/30 text-destructive dark:border-destructive/40", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +function CodeBlock({ + className, + variant = "default", + size = "default", + ...props +}: React.ComponentProps<"div"> & + VariantProps & { size?: "default" | "sm" }) { + return ( +
      + ) +} + +function CodeBlockHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
      [data-slot=code-block-title]]:min-w-0", + className + )} + {...props} + /> + ) +} + +function CodeBlockTitle({ className, ...props }: React.ComponentProps<"div">) { + return ( +
      + ) +} + +function CodeBlockActions({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
      &]:absolute [[data-slot=code-block]>&]:end-3 [[data-slot=code-block]>&]:top-3 [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:m-0 [[data-slot=code-block]>&]:opacity-0 [[data-slot=code-block]>&]:transition-opacity [[data-slot=code-block]>&]:group-focus-within/code-block:opacity-100 [[data-slot=code-block]>&]:group-hover/code-block:opacity-100 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:end-2 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:pointer-coarse:opacity-100 [[data-slot=code-block]>&]:*:[button]:bg-background [[data-slot=code-block]>&]:*:[button]:ring-1 [[data-slot=code-block]>&]:*:[button]:ring-foreground/10", + className + )} + {...props} + /> + ) +} + +function CodeBlockCopyButton({ + value, + variant = "ghost", + size = "icon-xs", + className, + onClick, + ...props +}: React.ComponentProps & { value: string }) { + const [copied, setCopied] = React.useState(false) + + React.useEffect(() => { + if (!copied) { + return + } + + const timeout = setTimeout(() => setCopied(false), 2000) + return () => clearTimeout(timeout) + }, [copied]) + + return ( + <> + + + {copied ? "Copied" : ""} + + + ) +} + +function CodeBlockContent({ + className, + children, + style, + wrap = false, + lineNumbers = false, + startLine = 1, + ...props +}: React.ComponentProps<"pre"> & { + wrap?: boolean + lineNumbers?: boolean + startLine?: number +}) { + return ( +
      +      
      +        {lineNumbers && typeof children === "string"
      +          ? children
      +              .replace(/\n$/, "")
      +              .split("\n")
      +              .map((line, index) => (
      +                {line}
      +              ))
      +          : children}
      +      
      +    
      + ) +} + +const codeBlockLineVariants = cva( + "relative -mx-4 block min-h-lh px-4 group-data-[size=sm]/code-block:-mx-3 group-data-[size=sm]/code-block:px-3 before:min-w-6 before:text-end before:text-muted-foreground after:absolute after:start-1 after:top-0 after:text-muted-foreground after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:gap-x-3 in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']", + { + variants: { + variant: { + default: "", + added: "bg-muted after:content-['+']", + removed: "bg-destructive/10 after:text-destructive after:content-['−']", + highlighted: "bg-muted", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +function CodeBlockLine({ + className, + variant = "default", + children, + ...props +}: React.ComponentProps<"span"> & VariantProps) { + // An empty line holds a newline so copying a selection keeps blank lines. + const empty = + children === undefined || + children === null || + children === "" || + (Array.isArray(children) && children.length === 0) + + return ( + + + {empty ? "\n" : children} + + + ) +} + +function CodeBlockFooter({ className, ...props }: React.ComponentProps<"div">) { + return ( +
      + ) +} + +export { + CodeBlock, + CodeBlockHeader, + CodeBlockTitle, + CodeBlockActions, + CodeBlockCopyButton, + CodeBlockContent, + CodeBlockLine, + CodeBlockFooter, +} diff --git a/resources/js/react/components/ui/hover-card.tsx b/resources/js/react/components/ui/hover-card.tsx new file mode 100644 index 0000000..ec07b71 --- /dev/null +++ b/resources/js/react/components/ui/hover-card.tsx @@ -0,0 +1,41 @@ +import * as React from "react" +import { cn } from "@/lib/utils" +import { HoverCard as HoverCardPrimitive } from "radix-ui" + +function HoverCard({ + ...props +}: React.ComponentProps) { + return +} + +function HoverCardTrigger({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function HoverCardContent({ + className, + align = "center", + sideOffset = 4, + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +export { HoverCard, HoverCardTrigger, HoverCardContent } diff --git a/resources/js/react/components/ui/message-scroller.tsx b/resources/js/react/components/ui/message-scroller.tsx new file mode 100644 index 0000000..dcf1878 --- /dev/null +++ b/resources/js/react/components/ui/message-scroller.tsx @@ -0,0 +1,129 @@ +import * as React from "react" +import { + MessageScroller as MessageScrollerPrimitive, + useMessageScroller, + useMessageScrollerScrollable, + useMessageScrollerVisibility, +} from "@shadcn/react/message-scroller" +import { cn } from "@/lib/utils" + +import { Button } from "./button" +import { ArrowDownIcon } from "lucide-react" + +function MessageScrollerProvider( + props: React.ComponentProps +) { + return +} + +function MessageScroller({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function MessageScrollerViewport({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function MessageScrollerContent({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function MessageScrollerItem({ + className, + scrollAnchor = false, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function MessageScrollerButton({ + direction = "end", + className, + children, + render, + variant = "secondary", + size = "icon-sm", + ...props +}: React.ComponentProps & + Pick, "variant" | "size">) { + return ( + } + {...props} + > + {children ?? ( + <> + + + {direction === "end" ? "Scroll to end" : "Scroll to start"} + + + )} + + ) +} + +export { + MessageScrollerProvider, + MessageScroller, + MessageScrollerViewport, + MessageScrollerContent, + MessageScrollerItem, + MessageScrollerButton, + useMessageScroller, + useMessageScrollerScrollable, + useMessageScrollerVisibility, +} diff --git a/resources/js/react/components/ui/message.tsx b/resources/js/react/components/ui/message.tsx new file mode 100644 index 0000000..c308b84 --- /dev/null +++ b/resources/js/react/components/ui/message.tsx @@ -0,0 +1,91 @@ +import * as React from "react" +import { cn } from "@/lib/utils" + +function MessageGroup({ className, ...props }: React.ComponentProps<"div">) { + return ( +
      + ) +} + +function Message({ + className, + align = "start", + ...props +}: React.ComponentProps<"div"> & { align?: "start" | "end" }) { + return ( +
      + ) +} + +function MessageAvatar({ className, ...props }: React.ComponentProps<"div">) { + return ( +
      + ) +} + +function MessageContent({ className, ...props }: React.ComponentProps<"div">) { + return ( +
      + ) +} + +function MessageHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
      + ) +} + +function MessageFooter({ className, ...props }: React.ComponentProps<"div">) { + return ( +
      + ) +} + +export { + MessageGroup, + Message, + MessageAvatar, + MessageContent, + MessageFooter, + MessageHeader, +} diff --git a/resources/js/react/components/ui/spinner.tsx b/resources/js/react/components/ui/spinner.tsx new file mode 100644 index 0000000..8dca22b --- /dev/null +++ b/resources/js/react/components/ui/spinner.tsx @@ -0,0 +1,10 @@ +import { cn } from "@/lib/utils" +import { Loader2Icon } from "lucide-react" + +function Spinner({ className, ...props }: React.ComponentProps<"svg">) { + return ( + + ) +} + +export { Spinner } diff --git a/resources/js/react/components/ui/trace.tsx b/resources/js/react/components/ui/trace.tsx new file mode 100644 index 0000000..c421c9a --- /dev/null +++ b/resources/js/react/components/ui/trace.tsx @@ -0,0 +1,162 @@ +import * as React from "react" +import { cn } from "@/lib/utils" + +import { + Collapsible, + CollapsibleContent, + CollapsibleTrigger, +} from "@/components/ui/collapsible" +import { ChevronRightIcon } from "lucide-react" + +function Trace({ className, ...props }: React.ComponentProps<"div">) { + return ( +
      [data-slot=trace-line]]:flex *:has-[>[data-slot=trace-line]]:w-fit *:has-[>[data-slot=trace-line]]:max-w-full *:has-[>[data-slot=trace-line]]:min-w-0 *:has-[>[data-slot=trace-line]]:rounded-md *:has-[>[data-slot=trace-line]]:text-left *:has-[>[data-slot=trace-line]]:outline-none *:has-[>[data-slot=trace-line]]:focus-visible:ring-3 *:has-[>[data-slot=trace-line]]:focus-visible:ring-ring/50", + className + )} + {...props} + /> + ) +} + +function TraceLine({ + className, + status, + ...props +}: React.ComponentProps<"span"> & { + status?: "running" | "error" | "pending" +}) { + return ( + + ) +} + +function TraceIcon({ className, ...props }: React.ComponentProps<"span">) { + return ( +