diff --git a/pkg/ui/package.json b/pkg/ui/package.json index cdd475dcc..36ced5e2c 100644 --- a/pkg/ui/package.json +++ b/pkg/ui/package.json @@ -1,6 +1,6 @@ { "name": "@hanzo/ui", - "version": "8.33.4", + "version": "8.33.5", "type": "module", "description": "Hanzo UI — the one canonical Hanzo component library, on @hanzo/gui + @hanzo/design. ONE substrate: every component renders through @hanzo/gui primitives, so the same import works on web, native (expo) and desktop (Tauri). Self-contained (theme.css), presentational, host-agnostic, clean-room.", "exports": { diff --git a/pkg/ui/scripts/composer.mjs b/pkg/ui/scripts/composer.mjs index 8ce02e0da..30269c301 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), chip: el.matches('[data-slot="composer-chip"]'), edge: parseFloat(s.borderTopWidth), edgeColor: s.borderTopColor, bg: s.backgroundColor, ink: { x: ink.left, r: ink.right } } }) .sort((a, b) => a.x - b.x) const fr = box(frame) @@ -198,14 +198,15 @@ for (const [width, height, ratio] of [ await tab.goto(`${base}?case=${kind}`, { waitUntil: 'domcontentloaded', timeout: 120_000 }) await tab.waitForSelector('[data-slot="composer-send"]', { state: 'attached', timeout: 120_000 }) await tab.waitForFunction((t) => document.documentElement.classList.contains(t), theme, { timeout: 10_000 }).catch(() => {}) + await tab.addStyleTag({ content: '*,*::before,*::after{transition:none!important;animation:none!important}' }) await settle(tab) const m = await measure(tab) const row = [...m.start, ...m.end] // +, the mic, its chevron and the last place; Dev adds the commands, and on a laptop the carried file after `+`. check(row.length === (kind === 'chat' ? 4 : phone ? 5 : 6), `${name}: the row draws its controls (${row.map((c) => c.name).join(', ')})`) - for (const c of row) if (c.name !== 'composer-carried') check(near(c.h, hit), `${name}: ${c.name} is ${hit}px tall (${round(c.h)})`) - for (const c of row) if (!['composer-carried', 'dictation-menu'].includes(c.name)) check(near(c.w, hit), `${name}: ${c.name} is ${hit}px wide (${round(c.w)})`) + for (const c of row) if (c.name !== 'composer-carried') check(near(c.h, c.name === 'composer-last' && phone ? 44 : hit), `${name}: ${c.name} is ${c.name === 'composer-last' && phone ? 44 : hit}px tall (${round(c.h)})`) + for (const c of row) if (!['composer-carried', 'dictation-menu'].includes(c.name)) check(near(c.w, c.name === 'composer-last' && phone ? 44 : hit), `${name}: ${c.name} is ${c.name === 'composer-last' && phone ? 44 : hit}px wide (${round(c.w)})`) const mid = row[0].cy for (const c of row) check(near(c.cy, mid), `${name}: ${c.name} on the row's centreline (${round(c.cy)} vs ${round(mid)})`) const end = gaps(m.end) @@ -233,17 +234,21 @@ 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)})`) + // Model, Effort and Mode are labelled controls (the label over the value); the pills and chips stay words. + const labelled = /^(Model|Effort|Mode): /.test(w.name) || w.chip + if (w.chip) check(phone ? w.h >= 44 - 0.5 : near(w.h, word), `${name}: ${w.name} is ${word}px tall (${round(w.h)})`) + else if (labelled) check(w.h >= (phone ? 44 : 34) - 0.5, `${name}: ${w.name} is at least ${phone ? 44 : 34}px tall (${round(w.h)})`) + else check(near(w.h, word), `${name}: ${w.name} is ${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((labelled ? w.edgeColor === 'rgba(0, 0, 0, 0)' : w.edge === 0) && w.bg === 'rgba(0, 0, 0, 0)', `${name}: ${w.name} shows no edge and no fill at rest (${w.edge}, ${w.edgeColor}, ${w.bg})`) } - if (m.words.length) { + if (m.words.length && !phone) { 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)})`) - check(near(m.frame.r - (m.words.at(-1).r - GUTTER), TEXT), `${name}: the last word ends as far in (${round(m.frame.r - m.words.at(-1).r + GUTTER)})`) + check(near(m.frame.r - m.words.at(-1).r, TEXT - 8), `${name}: the last word's box ends ${TEXT - 8}px in, its 8px padding making the text TEXT in (${round(m.frame.r - m.words.at(-1).r)})`) } if (kind === 'dev') check(m.carry.length === (phone ? 1 : 0), `${name}: on a phone the carried file above the field`) check(m.past.length === 0, `${name}: nothing runs past the frame (${m.past.join(', ')})`) 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..b8948611f --- /dev/null +++ b/pkg/ui/src/chat/Code.test.tsx @@ -0,0 +1,74 @@ +// @vitest-environment jsdom + +/** The code block's own controls: word wrap, download 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()) + +describe('Code', () => { + 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('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..771de708b 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 { Code2, Download, 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' + +/** Hand-off context a surface provides 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,55 @@ 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 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 +108,40 @@ 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 [wrap, setWrap] = useState(false) + const reducedMotion = useReducedMotion() + const ease = reducedMotion ? undefined : ('quickest' as const) + + 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/Preview.test.tsx b/pkg/ui/src/chat/Preview.test.tsx index 787437dc7..260427f50 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,33 @@ describe('an artifact', () => { expect(frame()).toBeNull() }) }) + +describe('Preview, the toolbar', () => { + const press = (slot: string) => act(() => host.querySelector(`[data-slot="${slot}"]`)!.click()) + + 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..cf3896482 100644 --- a/pkg/ui/src/chat/Preview.tsx +++ b/pkg/ui/src/chat/Preview.tsx @@ -26,9 +26,22 @@ */ import { SizableText, XStack, YStack } from '@hanzo/gui' import { useI18n } from '@hanzo/i18n/react' +import { Code2, Download } from '@hanzogui/lucide-icons-2' import 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 { useChatHandoff } from './Code' +import { save } from './save' +import { useReducedMotion } from './useReducedMotion' + +/** 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 +54,29 @@ 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 ease = useReducedMotion() ? undefined : ('quickest' as const) + + const button = { + render: