From 271102f124770fe2735b2e130db1a5418c669ec7 Mon Sep 17 00:00:00 2001 From: James <279246542+jamessburnss1313-dev@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:14:53 +0000 Subject: [PATCH 1/5] chat: tighter user bubble with outside turn actions, separate Model/Effort/Mode, Step timer and Thought fix, Dictation and toaster fixes --- pkg/ui/scripts/composer.mjs | 8 +- pkg/ui/src/backends/gui/toaster.test.tsx | 11 + pkg/ui/src/backends/gui/toaster.tsx | 13 +- pkg/ui/src/chat/Chat.tsx | 4 + pkg/ui/src/chat/Code.test.tsx | 91 ++++ pkg/ui/src/chat/Code.tsx | 298 +++++++++++- pkg/ui/src/chat/Composer.tsx | 40 +- pkg/ui/src/chat/Dictation.test.tsx | 60 ++- pkg/ui/src/chat/Dictation.tsx | 75 ++- pkg/ui/src/chat/Failure.tsx | 21 +- pkg/ui/src/chat/Message.test.tsx | 49 ++ pkg/ui/src/chat/Message.tsx | 82 +++- pkg/ui/src/chat/Parts.test.tsx | 20 + pkg/ui/src/chat/Parts.tsx | 140 +++++- pkg/ui/src/chat/Preview.test.tsx | 45 +- pkg/ui/src/chat/Preview.tsx | 169 +++++-- pkg/ui/src/chat/Sidebar.test.tsx | 72 +++ pkg/ui/src/chat/Sidebar.tsx | 147 ++++-- pkg/ui/src/chat/Step.test.tsx | 23 + pkg/ui/src/chat/Step.tsx | 137 +++++- pkg/ui/src/chat/Tune.test.tsx | 45 ++ pkg/ui/src/chat/Tune.tsx | 590 ++++++++++++++++++----- pkg/ui/src/chat/VoiceSlot.test.tsx | 28 ++ pkg/ui/src/chat/VoiceSlot.tsx | 7 + pkg/ui/src/chat/index.ts | 2 +- pkg/ui/src/chat/save.ts | 12 + pkg/ui/src/chat/useReducedMotion.ts | 15 + pkg/ui/src/models/ModelPicker.tsx | 142 ++++-- pkg/ui/src/models/ModelPickerMenu.tsx | 92 +++- pkg/ui/src/product/UsageMeter.tsx | 4 +- 30 files changed, 2113 insertions(+), 329 deletions(-) create mode 100644 pkg/ui/src/chat/Code.test.tsx create mode 100644 pkg/ui/src/chat/Message.test.tsx create mode 100644 pkg/ui/src/chat/Sidebar.test.tsx create mode 100644 pkg/ui/src/chat/VoiceSlot.test.tsx create mode 100644 pkg/ui/src/chat/VoiceSlot.tsx create mode 100644 pkg/ui/src/chat/save.ts create mode 100644 pkg/ui/src/chat/useReducedMotion.ts diff --git a/pkg/ui/scripts/composer.mjs b/pkg/ui/scripts/composer.mjs index 8ce02e0da..c770145ce 100644 --- a/pkg/ui/scripts/composer.mjs +++ b/pkg/ui/scripts/composer.mjs @@ -97,7 +97,7 @@ const measure = (tab) => const range = document.createRange() range.selectNodeContents(text) const ink = range.getBoundingClientRect() - return { name: el.getAttribute('aria-label') || el.textContent, ...box(el), edge: parseFloat(s.borderTopWidth), bg: s.backgroundColor, ink: { x: ink.left, r: ink.right } } + return { name: el.getAttribute('aria-label') || el.textContent, ...box(el), edge: s.borderTopColor, bg: s.backgroundColor, ink: { x: ink.left, r: ink.right } } }) .sort((a, b) => a.x - b.x) const fr = box(frame) @@ -233,13 +233,13 @@ for (const [width, height, ratio] of [ // The last place: voice mode while empty, send hidden. check(m.talk?.shown && !m.send.shown, `${name}: at rest the last place is voice mode, send not drawn`) - // Under the frame: words of one height, no edge, no fill, at the text edge. + // Under the frame: labelled controls at least a word tall, a transparent edge and no fill at rest, at the text edge. check(m.words.some((w) => /^Effort: /.test(w.name)) && m.words.some((w) => /^Model: /.test(w.name)), `${name}: the model and the effort are words under the frame (${m.words.map((w) => w.name).join(', ')})`) if (kind === 'dev') check(m.words.filter((w) => /Where the run runs|Repository|Branch/.test(w.name)).length === 3, `${name}: the pills are words under the frame`) for (const w of m.words) { - check(near(w.h, word), `${name}: ${w.name} is ${word}px tall (${round(w.h)})`) + check(w.h >= word - 0.5, `${name}: ${w.name} is at least ${word}px tall (${round(w.h)})`) check(near(w.cy, m.words[0].cy) || phone, `${name}: ${w.name} on the words' line`) - check(w.edge === 0 && w.bg === 'rgba(0, 0, 0, 0)', `${name}: ${w.name} has no edge and no fill (${w.edge}, ${w.bg})`) + check(w.edge === 'rgba(0, 0, 0, 0)' && w.bg === 'rgba(0, 0, 0, 0)', `${name}: ${w.name} shows no edge and no fill at rest (${w.edge}, ${w.bg})`) } if (m.words.length) { if (kind === 'dev') check(near(m.words[0].x + GUTTER - m.frame.x, TEXT), `${name}: the first word's letters stand where the field's do (${round(m.words[0].x + GUTTER - m.frame.x)})`) diff --git a/pkg/ui/src/backends/gui/toaster.test.tsx b/pkg/ui/src/backends/gui/toaster.test.tsx index 04511d3e5..0c7f7b02e 100644 --- a/pkg/ui/src/backends/gui/toaster.test.tsx +++ b/pkg/ui/src/backends/gui/toaster.test.tsx @@ -153,3 +153,14 @@ describe('toast', () => { expect(await audit(t)).toEqual([]) }) }) + +describe('toaster placement', () => { + it('stands 296 wide, no wider than the screen less its inset, clear of the bottom safe area', () => { + act(() => void toast('Hello')) + run(50) + const viewport = document.querySelector('.is_ToastViewport')! + expect(viewport.className).toMatch(/_width-296px/) + expect(viewport.className).toMatch(/_maxW-calc100vw-/) + expect(viewport.className).toMatch(/_mb-envsafe-are/) + }) +}) diff --git a/pkg/ui/src/backends/gui/toaster.tsx b/pkg/ui/src/backends/gui/toaster.tsx index 442c28da3..40a643016 100644 --- a/pkg/ui/src/backends/gui/toaster.tsx +++ b/pkg/ui/src/backends/gui/toaster.tsx @@ -10,7 +10,7 @@ * record kit's shape — its Toast and Toaster (MIT, NOTICE): * * · 296 wide on the floating material (`glass(2)`), 8px corners, padding - * 8 8 4, 8px between toasts, at the bottom-right 12px in; on a phone (≤768) + * 8 8 4, 8px between toasts, at the bottom-right 24px in; on a phone (≤768) * the full width at the top with square corners. * · A header row: the status icon (16), the message (12px, quiet, medium), * then a "Cancel" text button and a 24px close button pushed right. @@ -73,7 +73,8 @@ export interface ToasterProps extends Omit { export const TOAST_DURATION = 6000 const WIDTH = 296 const GAP = 8 -const INSET = 12 +const INSET = 24 +const SAFE_BOTTOM = 'env(safe-area-inset-bottom, 0px)' as `var(--${string})` const STATUS: Record = { default: 'neutral', @@ -296,11 +297,13 @@ const Toaster = /* @__PURE__ */ forwardRef(function To const media = useMedia() const phone = !!(media as Record)['max-md'] const fallback = toastOptions?.duration ?? duration ?? TOAST_DURATION + const resolvedPosition = position ?? (phone ? 'top-center' : 'bottom-right') + const isBottom = resolvedPosition.startsWith('bottom') return ( (function To offset={offset ?? (phone ? 0 : INSET)} hotkey={hotkey} label={containerAriaLabel ?? i18n.t('Notifications')} - {...(phone ? { width: '100%' } : null)} + width={phone ? '100%' : WIDTH} + maxW={phone ? '100%' : 'calc(100vw - 48px)'} + mb={!phone && isBottom ? SAFE_BOTTOM : undefined} > } /> diff --git a/pkg/ui/src/chat/Chat.tsx b/pkg/ui/src/chat/Chat.tsx index d4f129f87..ffd3a4284 100644 --- a/pkg/ui/src/chat/Chat.tsx +++ b/pkg/ui/src/chat/Chat.tsx @@ -100,6 +100,8 @@ export interface ChatProps extends Omit { * `body={(t) => }`. */ body?: (turn: Turn) => ReactNode + /** Optional actions rendered underneath each turn, outside its bubble (copy, edit). */ + turnActions?: (turn: Turn) => ReactNode /** Shown instead of the thread while nothing has been said. */ empty?: ReactNode /** @@ -159,6 +161,7 @@ export function Chat({ send: onSend, stop: onStop, body, + turnActions, empty, center = false, composer, @@ -218,6 +221,7 @@ export function Chat({ key={turn.id} role={turn.role} busy={streaming && i === last && turn.role === 'assistant'} + actions={turnActions ? turnActions(turn) : undefined} > {body ? body(turn) : draw(turn.content)} diff --git a/pkg/ui/src/chat/Code.test.tsx b/pkg/ui/src/chat/Code.test.tsx new file mode 100644 index 000000000..d748566c8 --- /dev/null +++ b/pkg/ui/src/chat/Code.test.tsx @@ -0,0 +1,91 @@ +// @vitest-environment jsdom + +/** The code block's own controls: line numbers, word wrap, download, fold and hand-off. */ +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { GuiProvider } from '@hanzo/gui' + +import config from '../gui-config' +import { ChatHandoffProvider, Code } from './Code' + +declare global { + // eslint-disable-next-line no-var + var IS_REACT_ACT_ENVIRONMENT: boolean +} + +let host: HTMLDivElement +let root: Root + +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) + +afterEach(() => { + act(() => root.unmount()) + host.remove() +}) + +const mount = (ui: React.ReactNode) => + act(() => + root.render( + + {ui} + , + ), + ) +const press = (slot: string) => act(() => host.querySelector(`[data-slot="${slot}"]`)!.click()) +const lines = (n: number) => Array.from({ length: n }, (_, i) => `line ${i + 1}`).join('\n') + +describe('Code', () => { + it('turns line numbers on and off', () => { + mount({'a\nb'}) + const toggle = host.querySelector('[data-slot="code-lines-toggle"]')! + expect(toggle.getAttribute('aria-pressed')).toBe('false') + press('code-lines-toggle') + expect(host.querySelector('[data-slot="code-lines-toggle"]')!.getAttribute('aria-pressed')).toBe('true') + expect(host.textContent).toContain('2') + }) + + it('says whether it wraps', () => { + mount(x) + expect(host.querySelector('[data-slot="code-wrap-toggle"]')!.getAttribute('aria-pressed')).toBe('false') + press('code-wrap-toggle') + expect(host.querySelector('[data-slot="code-wrap-toggle"]')!.getAttribute('aria-pressed')).toBe('true') + }) + + it('downloads the snippet with an extension from its language', () => { + Object.assign(URL, { createObjectURL: () => 'blob:x', revokeObjectURL: () => {} }) + const names: string[] = [] + const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { + names.push(this.download) + }) + mount(print(1)) + press('code-download') + expect(names).toEqual(['snippet.py']) + click.mockRestore() + }) + + it('folds a long block and opens it on demand', () => { + mount({lines(40)}) + expect(host.textContent).not.toContain('line 40') + press('code-fold') + expect(host.textContent).toContain('line 40') + }) + + it('hands its code to Dev only where the surface provides the hand-off', () => { + mount(x) + expect(host.querySelector('[data-slot="code-open-in-dev"]')).toBeNull() + const openInDev = vi.fn() + mount( + + x + , + ) + press('code-open-in-dev') + expect(openInDev).toHaveBeenCalledWith({ code: 'x', language: 'ts' }) + }) +}) diff --git a/pkg/ui/src/chat/Code.tsx b/pkg/ui/src/chat/Code.tsx index 03310980d..22e87bb2b 100644 --- a/pkg/ui/src/chat/Code.tsx +++ b/pkg/ui/src/chat/Code.tsx @@ -13,10 +13,30 @@ * plain text or its own highlighted nodes. */ import { ScrollView, SizableText, XStack, YStack } from '@hanzo/gui' -import { type ComponentProps, type ReactNode } from 'react' +import { useI18n } from '@hanzo/i18n/react' +import { ChevronDown, ChevronUp, Code2, Download, Hash, WrapText } from '@hanzogui/lucide-icons-2' +import { createContext, useContext, useState, type ComponentProps, type CSSProperties, type ReactNode } from 'react' -import { slot } from '../backends/gui/slot' +import { RING } from '../backends/gui/press' +import { slot, tip } from '../backends/gui/slot' import { CopyButton } from '../product/CopyButton' +import { save } from './save' +import { useReducedMotion } from './useReducedMotion' + +/** Cross-surface handoff context provided by Chat so any code block or HTML artifact can open cleanly in Hanzo Dev. */ +export interface ChatHandoffHandlers { + openInDev?: (payload: { code: string; language?: string; title?: string }) => void +} + +const ChatHandoffContext = createContext(null) + +export function ChatHandoffProvider({ value, children }: { value: ChatHandoffHandlers; children: ReactNode }) { + return {children} +} + +export function useChatHandoff(): ChatHandoffHandlers | null { + return useContext(ChatHandoffContext) +} /** * Monospace stack, applied through `style` rather than a `$mono` token. @@ -27,9 +47,61 @@ import { CopyButton } from '../product/CopyButton' * distinguishable. The CSS variable is honoured when the host defines Zen Mono * and falls back to the platform's own monospace when it does not. */ -const MONO = { +const MONO: CSSProperties = { fontFamily: 'var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace)', -} as const +} + +const MONO_WRAP: CSSProperties = { + ...MONO, + overflowWrap: 'anywhere', + wordBreak: 'break-word', +} + +const DIFF_ADD_BG = 'color-mix(in srgb, var(--state-success) 12%, transparent)' +const DIFF_DEL_BG = 'color-mix(in srgb, var(--state-error) 12%, transparent)' + +const FOLD_THRESHOLD = 32 +const FOLD_LINES = 22 + +const EXTENSIONS: Record = { + ts: 'ts', + typescript: 'ts', + tsx: 'tsx', + js: 'js', + javascript: 'js', + jsx: 'jsx', + py: 'py', + python: 'py', + sh: 'sh', + shell: 'sh', + zsh: 'sh', + bash: 'sh', + json: 'json', + jsonc: 'json', + css: 'css', + html: 'html', + htm: 'html', + sql: 'sql', + md: 'md', + markdown: 'md', + yaml: 'yaml', + yml: 'yml', + go: 'go', + golang: 'go', + rs: 'rs', + rust: 'rs', + diff: 'diff', + patch: 'diff', + txt: 'txt', + text: 'txt', + plaintext: 'txt', +} + +const extensionOf = (language: string): string => { + const clean = language.trim().toLowerCase() + const key = clean.includes('/') ? (clean.split('/').pop() ?? clean) : clean + return EXTENSIONS[key] ?? 'txt' +} export interface CodeProps extends Omit, 'children'> { children?: ReactNode @@ -42,7 +114,110 @@ export interface CodeProps extends Omit, 'children } export function Code({ children, language = 'text', value, actions, ...props }: CodeProps) { + const { t } = useI18n() + const handoff = useChatHandoff() const text = value ?? (typeof children === 'string' ? children : '') + const lines = text ? text.split('\n') : [] + const lineCount = lines.length + const hasCustomNodes = children != null && typeof children !== 'string' + const canLineRender = !hasCustomNodes && lineCount > 0 + const isDiff = canLineRender && language.trim().toLowerCase() === 'diff' + const foldable = canLineRender && lineCount > FOLD_THRESHOLD + + const [showLines, setShowLines] = useState(false) + const [wrap, setWrap] = useState(false) + const [expanded, setExpanded] = useState(false) + const reducedMotion = useReducedMotion() + const ease = reducedMotion ? undefined : ('quickest' as const) + + const visibleLines = foldable && !expanded ? lines.slice(0, FOLD_LINES) : lines + const renderRows = canLineRender && (showLines || isDiff || foldable) + const gutterWidth = Math.max(24, String(lineCount).length * 9 + 8) + + const headerLabel = + lineCount > 1 ? `${language} · ${t('{n} lines', { n: lineCount })}` : language + + const controlProps = (active: boolean) => + ({ + render: diff --git a/pkg/ui/src/chat/Message.test.tsx b/pkg/ui/src/chat/Message.test.tsx new file mode 100644 index 000000000..bab53c720 --- /dev/null +++ b/pkg/ui/src/chat/Message.test.tsx @@ -0,0 +1,49 @@ +// @vitest-environment jsdom + +/** A user turn is a tight bubble: its actions sit outside it, and a turn with none leaves no empty row. */ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it } from 'vitest' +import { GuiProvider } from '@hanzo/gui' +import type { ReactNode } from 'react' + +import config from '../gui-config' +import { Message } from './Message' + +const dom = (node: ReactNode) => { + const host = document.createElement('div') + host.innerHTML = renderToStaticMarkup( + + {node} + , + ) + return host +} + +describe('Message, a user turn', () => { + it('draws no row under the bubble when it has no actions', () => { + const host = dom(hello) + expect(host.querySelector('[data-slot="message-actions"]')).toBeNull() + expect(host.querySelector('[data-bubble="true"]')?.textContent).toBe('hello') + }) + + it('puts its actions below the bubble, not inside it', () => { + const host = dom( + Copy}> + hello + , + ) + const actions = host.querySelector('[data-slot="message-actions"]')! + expect(actions.textContent).toBe('Copy') + expect(host.querySelector('[data-bubble="true"]')!.contains(actions)).toBe(false) + }) + + it('keeps an assistant turn bubble-less, with its actions beneath its words', () => { + const host = dom( + Copy}> + hi + , + ) + expect(host.querySelector('[data-bubble]')).toBeNull() + expect(host.querySelector('[data-slot="message-body"]')!.contains(host.querySelector('[data-slot="message-actions"]'))).toBe(true) + }) +}) diff --git a/pkg/ui/src/chat/Message.tsx b/pkg/ui/src/chat/Message.tsx index 19ce7358d..c47b78577 100644 --- a/pkg/ui/src/chat/Message.tsx +++ b/pkg/ui/src/chat/Message.tsx @@ -17,6 +17,7 @@ import type { ComponentProps, ReactNode } from 'react' import { ink } from '../backends/gui/ink' import { slot } from '../backends/gui/slot' +import { useReducedMotion } from './useReducedMotion' /** * Who is speaking — and it is the WIRE's set, not a presentation set of our own. @@ -73,6 +74,8 @@ export function Message({ body, ...props }: MessageProps) { + const reducedMotion = useReducedMotion() + // `tool` takes the aside too — see the Role note above. Machine chatter about // a turn, not speech in it. if (role === 'system' || role === 'tool') @@ -95,37 +98,90 @@ export function Message({ ) const mine = role === 'user' + // A user turn is a tight bubble: no dead row inside it. Its actions sit + // outside, below it, so a hidden row never leaves a gap at the bottom. + if (mine) + return ( + + + + {ink(children)} + {busy ? : null} + + {actions ? ( + + {actions} + + ) : null} + + + ) + return ( - {icon && !mine ? {icon} : null} + {icon ? {icon} : null} {ink(children)} {busy ? : null} - {actions ? {actions} : null} + {actions ? ( + + {actions} + + ) : null} ) diff --git a/pkg/ui/src/chat/Parts.test.tsx b/pkg/ui/src/chat/Parts.test.tsx index a832e7a71..0a572c342 100644 --- a/pkg/ui/src/chat/Parts.test.tsx +++ b/pkg/ui/src/chat/Parts.test.tsx @@ -211,3 +211,23 @@ describe('Chat routes a list of parts here', () => { expect(markup).not.toContain('ignored') }) }) + +describe('a run of tool steps', () => { + const call = (name: string): MessagePart => ({ type: 'toolCall', name }) + const result = (name: string, status?: 'error'): MessagePart => ({ type: 'toolResult', name, ...(status ? { status } : {}) }) + + it('stays as it is for one or two steps', () => { + expect(draw([call('a'), result('a')])).not.toContain('data-step-group') + }) + + it('folds three or more into one row that counts them', () => { + const markup = draw([call('a'), result('a'), result('b', 'error')]) + expect(markup).toContain('data-step-group="3"') + expect(markup).toContain('1 error') + expect(markup).toContain('1 running') + }) + + it('does not fold steps that prose parts separate', () => { + expect(draw([call('a'), call('b'), { type: 'text', text: 'between' }, call('c'), call('d')])).not.toContain('data-step-group') + }) +}) diff --git a/pkg/ui/src/chat/Parts.tsx b/pkg/ui/src/chat/Parts.tsx index b6953e128..d1bf7a511 100644 --- a/pkg/ui/src/chat/Parts.tsx +++ b/pkg/ui/src/chat/Parts.tsx @@ -29,6 +29,7 @@ * a parser — so this package ships no parser and takes the rendered nodes. */ import { Image, SizableText, XStack, YStack } from '@hanzo/gui' +import { useI18n } from '@hanzo/i18n/react' import { Paperclip } from '@hanzogui/lucide-icons-2' import type { ComponentProps, ReactNode } from 'react' @@ -299,6 +300,112 @@ export function Piece({ part, prose, onRetry, onOpen, onSource }: PieceProps) { } } +type ToolStepPart = Extract + +const isToolStep = (part: MessagePart): part is ToolStepPart => + part.type === 'toolCall' || part.type === 'toolResult' + +const statusOf = (part: ToolStepPart): Ran => + part.type === 'toolCall' ? 'running' : (part.status ?? 'done') + +type RenderItem = + | { kind: 'single'; part: MessagePart; index: number } + | { kind: 'group'; parts: ToolStepPart[]; index: number } + +const GROUP_MIN = 3 + +/** + * Collapse runs of 3+ consecutive tool calls/results into one summary row so a + * multi-step turn stays calm and scannable; 1-2 consecutive steps stay inline. + */ +function groupRuns(parts: readonly MessagePart[]): RenderItem[] { + const items: RenderItem[] = [] + let i = 0 + while (i < parts.length) { + const current = parts[i]! + if (!isToolStep(current)) { + items.push({ kind: 'single', part: current, index: i }) + i += 1 + continue + } + const start = i + const run: ToolStepPart[] = [] + while (i < parts.length) { + const candidate = parts[i]! + if (!isToolStep(candidate)) break + run.push(candidate) + i += 1 + } + if (run.length >= GROUP_MIN) { + items.push({ kind: 'group', parts: run, index: start }) + } else { + for (let j = 0; j < run.length; j++) { + items.push({ kind: 'single', part: run[j]!, index: start + j }) + } + } + } + return items +} + +function StepGroup({ + parts, + baseIndex, + prose, + onRetry, + onOpen, + onSource, +}: PartActions & { parts: readonly ToolStepPart[]; baseIndex: number }) { + const { t } = useI18n() + + let running = 0 + let done = 0 + let error = 0 + let cancelled = 0 + for (const part of parts) { + const s = statusOf(part) + if (s === 'running') running += 1 + else if (s === 'error') error += 1 + else if (s === 'cancelled') cancelled += 1 + else done += 1 + } + + const groupStatus: Ran = + running > 0 ? 'running' : error > 0 ? 'error' : cancelled === parts.length ? 'cancelled' : 'done' + + const label = + running > 0 + ? t('Working through {n} steps…', { n: parts.length }) + : t('Used {n} tools', { n: parts.length }) + + const counts: string[] = [] + if (running > 0) counts.push(t('{n} running', { n: running })) + if (done > 0) counts.push(t('{n} done', { n: done })) + if (error > 0) counts.push(error === 1 ? t('1 error') : t('{n} errors', { n: error })) + if (cancelled > 0) counts.push(t('{n} cancelled', { n: cancelled })) + + return ( + + + {parts.map((part, j) => ( + + ))} + + + ) +} + export interface PartsProps extends PartActions, Omit, 'children'> { @@ -308,18 +415,31 @@ export interface PartsProps /** A turn's parts, in order, spaced. Goes in a `Message`'s children — `Chat` * puts it there for a turn whose content is a list. */ export function Parts({ parts, prose, onRetry, onOpen, onSource, ...props }: PartsProps) { + const items = groupRuns(join(parts)) return ( - {join(parts).map((part, i) => ( - - ))} + {items.map((item) => + item.kind === 'group' ? ( + + ) : ( + + ), + )} ) } diff --git a/pkg/ui/src/chat/Preview.test.tsx b/pkg/ui/src/chat/Preview.test.tsx index 787437dc7..69af618e8 100644 --- a/pkg/ui/src/chat/Preview.test.tsx +++ b/pkg/ui/src/chat/Preview.test.tsx @@ -16,10 +16,11 @@ import { act } from 'react' import type { ReactNode } from 'react' import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { GuiProvider } from '@hanzo/gui' import config from '../gui-config' +import { ChatHandoffProvider } from './Code' import { Parts } from './Parts' import { Preview } from './Preview' @@ -120,3 +121,45 @@ describe('an artifact', () => { expect(frame()).toBeNull() }) }) + +describe('Preview, the toolbar', () => { + const press = (slot: string) => act(() => host.querySelector(`[data-slot="${slot}"]`)!.click()) + + it('switches to the source and back, naming which is shown', () => { + mount() + const [shown, source] = [...host.querySelectorAll('[data-slot="preview-mode"] button')] + expect(shown!.getAttribute('aria-pressed')).toBe('true') + act(() => source!.click()) + expect(frame()).toBeNull() + expect(slots()).toContain('code') + expect(source!.getAttribute('aria-pressed')).toBe('true') + act(() => shown!.click()) + expect(frame()).not.toBeNull() + }) + + it('downloads the page under its title', () => { + const created = vi.fn(() => 'blob:x') + Object.assign(URL, { createObjectURL: created, revokeObjectURL: () => {} }) + const names: string[] = [] + const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { + names.push(this.download) + }) + mount() + press('preview-download') + expect(names).toEqual(['pricing-page.html']) + click.mockRestore() + }) + + it('offers Open in Dev only where the surface can take it there', () => { + mount() + expect(host.querySelector('[data-slot="preview-open-in-dev"]')).toBeNull() + const openInDev = vi.fn() + mount( + + + , + ) + press('preview-open-in-dev') + expect(openInDev).toHaveBeenCalledWith({ code: PAGE, language: 'html', title: 'Pricing' }) + }) +}) diff --git a/pkg/ui/src/chat/Preview.tsx b/pkg/ui/src/chat/Preview.tsx index e922cc0b2..9eed72126 100644 --- a/pkg/ui/src/chat/Preview.tsx +++ b/pkg/ui/src/chat/Preview.tsx @@ -26,9 +26,24 @@ */ import { SizableText, XStack, YStack } from '@hanzo/gui' import { useI18n } from '@hanzo/i18n/react' -import type { ComponentProps } from 'react' +import { Code2, Download, Eye } from '@hanzogui/lucide-icons-2' +import { useState, type ComponentProps } from 'react' -import { slot } from '../backends/gui/slot' +import { RING } from '../backends/gui/press' +import { slot, tip } from '../backends/gui/slot' +import { CopyButton } from '../product/CopyButton' +import { Code, useChatHandoff } from './Code' +import { save } from './save' +import { useReducedMotion } from './useReducedMotion' + +type Mode = 'preview' | 'code' + +/** The file a download is named after: the title, as a slug. */ +const slugify = (title: string): string => + title + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') || 'preview' export interface PreviewProps extends Omit, 'children'> { /** A self-contained HTML document. Script in it will not run. */ @@ -41,7 +56,60 @@ export interface PreviewProps extends Omit, 'child export function Preview({ markup, title, height = 320, ...props }: PreviewProps) { const { t } = useI18n() + const handoff = useChatHandoff() const named = title ?? t('Preview') + const [mode, setMode] = useState('preview') + const ease = useReducedMotion() ? undefined : ('quickest' as const) + + const button = { + render: