Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pkg/ui/package.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
21 changes: 13 additions & 8 deletions pkg/ui/scripts/composer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(', ')})`)
Expand Down
11 changes: 11 additions & 0 deletions pkg/ui/src/backends/gui/toaster.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement>('.is_ToastViewport')!
expect(viewport.className).toMatch(/_width-296px/)
expect(viewport.className).toMatch(/_maxW-calc100vw-/)
expect(viewport.className).toMatch(/_mb-envsafe-are/)
})
})
13 changes: 9 additions & 4 deletions pkg/ui/src/backends/gui/toaster.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -73,7 +73,8 @@ export interface ToasterProps extends Omit<GuiToasterProps, 'toastOptions'> {
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<string, FeedbackStatus> = {
default: 'neutral',
Expand Down Expand Up @@ -296,11 +297,13 @@ const Toaster = /* @__PURE__ */ forwardRef<GuiElement, ToasterProps>(function To
const media = useMedia()
const phone = !!(media as Record<string, boolean>)['max-md']
const fallback = toastOptions?.duration ?? duration ?? TOAST_DURATION
const resolvedPosition = position ?? (phone ? 'top-center' : 'bottom-right')
const isBottom = resolvedPosition.startsWith('bottom')
return (
<Toast
{...rest}
theme={theme}
position={position ?? (phone ? 'top-center' : 'bottom-right')}
position={resolvedPosition}
gap={gap ?? GAP}
visibleToasts={limit}
duration={Number.POSITIVE_INFINITY}
Expand All @@ -311,7 +314,9 @@ const Toaster = /* @__PURE__ */ forwardRef<GuiElement, ToasterProps>(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}
>
<Limit limit={limit} />
<Toast.List renderItem={({ toast: t, index }) => <ToastItem key={t.id} t={t} index={index} fallback={fallback} phone={phone} />} />
Expand Down
4 changes: 4 additions & 0 deletions pkg/ui/src/chat/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ export interface ChatProps extends Omit<ThreadProps, 'children' | 'ref'> {
* `body={(t) => <Parts parts={t.content as MessagePart[]} prose={md} />}`.
*/
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
/**
Expand Down Expand Up @@ -159,6 +161,7 @@ export function Chat({
send: onSend,
stop: onStop,
body,
turnActions,
empty,
center = false,
composer,
Expand Down Expand Up @@ -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)}
</Message>
Expand Down
74 changes: 74 additions & 0 deletions pkg/ui/src/chat/Code.test.tsx
Original file line number Diff line number Diff line change
@@ -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(
<GuiProvider config={config} defaultTheme="dark">
{ui}
</GuiProvider>,
),
)
const press = (slot: string) => act(() => host.querySelector<HTMLElement>(`[data-slot="${slot}"]`)!.click())

describe('Code', () => {
it('says whether it wraps', () => {
mount(<Code value="x">x</Code>)
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(<Code language="python" value="print(1)">print(1)</Code>)
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(<Code language="ts" value="x">x</Code>)
expect(host.querySelector('[data-slot="code-open-in-dev"]')).toBeNull()
const openInDev = vi.fn()
mount(
<ChatHandoffProvider value={{ openInDev }}>
<Code language="ts" value="x">x</Code>
</ChatHandoffProvider>,
)
press('code-open-in-dev')
expect(openInDev).toHaveBeenCalledWith({ code: 'x', language: 'ts' })
})
})
Loading
Loading