@hachej/boring-ui-kit 0.3.2 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -18
- package/THIRD_PARTY_NOTICES.md +35 -0
- package/bin/boring-ui-blocks.mjs +286 -0
- package/dist/canvas-editor-native.d.ts +4 -1
- package/dist/canvas-editor-native.js +8 -6
- package/dist/canvas-editor.js +1 -1
- package/dist/canvas-proposals.d.ts +3 -1
- package/dist/canvas-proposals.js +4 -3
- package/dist/experience-document-viewer.d.ts +3 -0
- package/dist/experience-document-viewer.js +6 -5
- package/dist/experience.d.ts +3 -0
- package/dist/experience.js +2 -1
- package/dist/file-tree-view.d.ts +76 -3
- package/dist/file-tree-view.js +172 -39
- package/dist/file-tree.d.ts +3 -0
- package/dist/file-tree.js +17 -2
- package/dist/html-viewer.d.ts +4 -0
- package/dist/html-viewer.js +5 -3
- package/dist/markdown-autosave.d.ts +13 -0
- package/dist/markdown-autosave.js +94 -0
- package/dist/markdown-editor.d.ts +16 -0
- package/dist/markdown-editor.js +81 -17
- package/dist/markdown-extensions.js +9 -1
- package/dist/markdown-proposal-diff.d.ts +2 -1
- package/dist/markdown-proposal-diff.js +3 -2
- package/dist/markdown-safety.js +3 -1
- package/dist/native-chat.js +1 -1
- package/dist/remote-chat.d.ts +18 -0
- package/dist/remote-chat.js +149 -7
- package/dist/text-buffer.js +3 -2
- package/dist/text-draft-controls.d.ts +3 -1
- package/dist/text-draft-controls.js +3 -2
- package/dist/viewer-components.d.ts +14 -0
- package/dist/viewer-components.js +1 -0
- package/package.json +8 -4
- package/r/app-shell.json +39 -20
- package/r/button.json +19 -11
- package/r/dock.json +2 -2
- package/r/documents.json +17 -14
- package/r/feedback-preview.json +8 -2
- package/r/feedback.json +46 -325
- package/r/file-tree.json +14 -6
- package/r/html-viewer.json +8 -42
- package/r/markdown-editor.json +38 -87
- package/r/pi-ambient.json +15 -8
- package/r/pi-app.json +30 -24
- package/r/pi-chat.json +101 -70
- package/r/pi-workspace.json +7 -5
- package/r/provider-setup.json +9 -4
- package/r/registry.json +471 -893
- package/r/task-list-viewer.json +11 -21
- package/r/theme.json +23 -4
- package/r/version-history.json +24 -0
- package/r/viewers.json +139 -320
- package/styles/file-tree.css +41 -42
- package/dist/file-tree-shadcn.d.ts +0 -8
- package/dist/file-tree-shadcn.js +0 -14
package/r/app-shell.json
CHANGED
|
@@ -2,30 +2,35 @@
|
|
|
2
2
|
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
3
|
"name": "app-shell",
|
|
4
4
|
"title": "App shell: layouts, list/detail and agent layer",
|
|
5
|
-
"description": "AppShell with three layouts. B \"workspace\" puts a ListDetail on a screen (phone: the list, then the detail as a stack step with Back; wide: a 20rem list and the detail side by side, sidebar as an icon rail). C \"chat\" wraps the app's own AgentWorkspace (untouched, passed as the nav item's render; install the pi-app item yourself) in the same sidebar, account menu and header; it takes no shell agent. A \"screen\": one screen at a time, every screen kept mounted. On a phone bottom tabs (at most four; more give three plus a « Plus » sheet) and an avatar button that opens the account sheet; on a wide screen the shadcn sidebar (icon rail, NavUser). One header per screen through useScreenHeader (title, subtitle, back, up to two actions, the rest behind « … »). The account menu holds « Améliorer l'app » (the improve agent), the app's own entries and sign out. AppSheet is the one bottom sheet (one open at a time, Back closes it). It mounts the AgentLayer: one agent's PiChat above the app (phone: a drawer with peek, half and full snap points; wide: a right panel), the improve agent in the same layer, optional push-to-talk and point mode. Also useAgentContext and readAgentContext (the screen on show travels as `context` with each submit) and useBackLayer, the one Back manager. Built on
|
|
5
|
+
"description": "AppShell with three layouts. B \"workspace\" puts a ListDetail on a screen (phone: the list, then the detail as a stack step with Back; wide: a 20rem list and the detail side by side, sidebar as an icon rail). C \"chat\" wraps the app's own AgentWorkspace (untouched, passed as the nav item's render; install the pi-app item yourself) in the same sidebar, account menu and header; it takes no shell agent. A \"screen\": one screen at a time, every screen kept mounted. On a phone bottom tabs (at most four; more give three plus a « Plus » sheet) and an avatar button that opens the account sheet; on a wide screen the shadcn sidebar (icon rail, NavUser). One header per screen through useScreenHeader (title, subtitle, back, up to two actions, the rest behind « … »). The account menu holds « Améliorer l'app » (the improve agent), the app's own entries and sign out. AppSheet is the one bottom sheet (one open at a time, Back closes it). It mounts the AgentLayer: one agent's PiChat above the app (phone: a drawer with peek, half and full snap points; wide: a right panel), the improve agent in the same layer, optional push-to-talk and point mode. Also useAgentContext and readAgentContext (the screen on show travels as `context` with each submit) and useBackLayer, the one Back manager. Built on explicitly pinned Base UI drawer and dropdown-menu recipes, plus the sidebar and avatar of the host's own shadcn style.",
|
|
6
6
|
"dependencies": [
|
|
7
|
-
"@hachej/boring-feedback@^0.
|
|
8
|
-
"@hachej/boring-ui-kit@^0.
|
|
7
|
+
"@hachej/boring-feedback@^0.4.1",
|
|
8
|
+
"@hachej/boring-ui-kit@^0.4.1",
|
|
9
9
|
"@base-ui/react@^1.9.0",
|
|
10
10
|
"react@^19.0.0",
|
|
11
11
|
"react-dom@^19.0.0",
|
|
12
12
|
"lucide-react@^1.51.0"
|
|
13
13
|
],
|
|
14
14
|
"registryDependencies": [
|
|
15
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.
|
|
16
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.
|
|
17
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.
|
|
18
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.
|
|
19
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.
|
|
15
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.1/r/pi-chat.json",
|
|
16
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.1/r/dock.json",
|
|
17
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.1/r/feedback.json",
|
|
18
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.1/r/utils.json",
|
|
19
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.1/r/button.json",
|
|
20
20
|
"drawer",
|
|
21
21
|
"sidebar",
|
|
22
22
|
"avatar",
|
|
23
|
-
"dropdown-menu"
|
|
23
|
+
"dropdown-menu",
|
|
24
|
+
"button",
|
|
25
|
+
"switch",
|
|
26
|
+
"badge",
|
|
27
|
+
"card",
|
|
28
|
+
"separator"
|
|
24
29
|
],
|
|
25
30
|
"files": [
|
|
26
31
|
{
|
|
27
32
|
"path": "registry/app-shell/agent-layer.tsx",
|
|
28
|
-
"content": "'use client';\n\n// The AgentLayer: ONE agent's PiChat above the app. Compact (below 768px): a bottom drawer with three fixed snap points, peek, half and\n// full (shadcn `drawer`, Base UI variant). Expanded: a `Dock` (the `dock` item) beside the app, docked on the left or the right (default right)\n// or floating over it; the person chooses and the choice is remembered. The same layer shows\n// the product manager (« Améliorer l’app ») when the account menu asks for it. Push-to-talk is an option of the agent.\n// Host concern: Pi has no layout. The chat is the borrowed NativeChatController rendered by PiChat; the screen context travels as the\n// submit's `context` (agent-context.ts). Nothing here is configurable beyond AgentSpec.\nimport { createPortal } from 'react-dom';\nimport { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { ComponentType, CSSProperties, HTMLAttributes, PointerEvent as ReactPointerEvent, ReactElement, ReactNode, Ref, RefObject } from 'react';\nimport { ArrowLeftIcon, ChevronDownIcon, ChevronUpIcon, Loader2Icon, MicIcon, PanelLeftIcon, PanelRightIcon, PictureInPicture2Icon, SparklesIcon, XIcon } from 'lucide-react';\nimport { Drawer as DrawerPrimitive } from '@base-ui/react/drawer';\nimport { createVoiceCapture } from '@hachej/boring-feedback/page';\nimport type { VoiceCapture, VoiceRefusal } from '@hachej/boring-feedback/page';\nimport type { FeedbackSession } from '@hachej/boring-feedback/ui';\nimport type { NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { Drawer, DrawerContent } from '@/components/ui/drawer';\nimport { useIsMobile } from '@/hooks/use-mobile';\nimport { Dock, DockLayout, DockMain } from '../dock/dock';\nimport type { DockApi } from '../dock/dock';\nimport { PiChat } from '../pi-chat/pi-chat';\nimport type { PiChatProps } from '../pi-chat/pi-chat';\nimport { chatTextFor } from '../pi-chat/locale';\nimport { NoteBubble, useComposerFeedback } from '../feedback/feedback-session';\nimport { feedbackLabelsFr } from '../feedback/feedback-labels';\nimport { PointBar, usePointing } from '../feedback/point-mode';\nimport { cn } from '../utils/utils';\nimport { useBackLayer } from './back';\nimport { closeShellLayer, registerAgentLayerCloser } from './shell-layer';\nimport { appShellText } from './text';\nimport type { AppShellLocale, AppShellText } from './text';\nimport { useVisualViewport } from './use-visual-viewport';\nimport { AgentContextProvider } from './agent-context';\nimport { HeaderActions } from './header-actions';\nimport type { ScreenHeaderAction } from './header-actions';\n\nexport interface AgentSpec {\n readonly controller: NativeChatController;\n /** The agent's name in the expanded sidebar (default: the chat's title, then « Assistant »). */\n readonly label?: string;\n /** The agent's icon in the sidebar (default: the sparkles of the header trigger). */\n readonly icon?: ComponentType<{ className?: string }>;\n readonly chatProps?: Omit<PiChatProps, 'controller'>;\n /** Push-to-talk. `send` 'auto' submits the transcript; 'draft' (default) only fills the composer. */\n readonly voice?: { readonly transcribe: (audio: Blob, signal: AbortSignal) => Promise<string>; readonly send?: 'auto' | 'draft' };\n /** Point mode (the product manager, in practice). */\n readonly feedback?: FeedbackSession;\n /** Host actions in the layer's title row (before the dock controls, or the snap and close controls when compact), as the screen header's. Two shown, the rest in « … ». Not at peek. */\n readonly headerActions?: readonly ScreenHeaderAction[];\n}\n\n/** Compact: closed, peek, half or full. Expanded: closed or open. */\nexport type AgentLayerState = 'closed' | 'peek' | 'half' | 'full' | 'open';\ntype Which = 'agent' | 'improve';\ntype Snap = 'closed' | 'peek' | 'half' | 'full';\n\nexport interface AgentLayerApi {\n readonly state: AgentLayerState;\n readonly showing: Which | null;\n open(which?: Which, at?: 'half' | 'full'): void;\n close(): void;\n readonly expanded: boolean;\n}\n\n// The three fixed snap points: a peek (one composer row and a line of the last reply, `PEEK_REM` above the tab bar), 55% and the full height.\nconst PEEK_REM = 6;\n/** The shell's z-scale (tabs 20, peek 30, drawer and panel 40, other sheets 50, point bar 60). */\nconst Z = { tabs: 20, peek: 30, layer: 40, sheet: 50, point: 60 } as const;\nconst HALF = 0.55;\nconst FULL = 1;\n/** Hold the trigger this long before it records; shorter is a tap. */\nconst HOLD_MS = 350;\n\n/**\n * What a close request from the drawer becomes. A swipe, an outside press, a lost focus and Escape never close the layer: they step down\n * to peek (half without an `agent`), so the modal state goes and the coach stays reachable. Only the Close control closes it. `reason` is\n * Base UI's `details.reason` (`'swipe'`, `'outside-press'`, `'focus-out'`, `'escape-key'`, `'close-watcher'`, `'close-press'`, `'trigger-press'`,\n * `'imperative-action'`, `'none'`).\n */\nexport function nextSnapOnClose(reason: string, hasPeek: boolean): 'peek' | 'half' | 'close' {\n return reason === 'swipe' || reason === 'outside-press' || reason === 'focus-out' || reason === 'escape-key' ? (hasPeek ? 'peek' : 'half') : 'close';\n}\n\ntype VoicePhase = 'idle' | 'starting' | 'recording' | 'transcribing';\ninterface Voice {\n readonly phase: VoicePhase;\n readonly seconds: number;\n readonly problem: string | undefined;\n readonly start: () => void;\n readonly finish: () => void;\n readonly cancel: () => void;\n}\n\ninterface Internal extends AgentLayerApi {\n readonly agent: AgentSpec | undefined;\n readonly improve: AgentSpec | undefined;\n readonly snap: Snap;\n readonly setSnap: (snap: Snap) => void;\n readonly showAgent: () => void;\n /** Until this time (ms) an outside press is the AgentTrigger's own click. */\n readonly triggerUntil: { current: number };\n readonly voice: Voice;\n /** The peek height in px: `PEEK_REM` plus the tab bar the peek sits above. */\n readonly peekPoint: string;\n /** The measured tab bar height in px, given explicitly to the parts portalled to the body (they cannot inherit the shell's variables). */\n readonly tabbar: number;\n /** The persistent element holding both chats: it moves between the drawer and the panel, so closing never unmounts a chat. */\n readonly host: HTMLElement | null;\n /** The shell's `locale`: the layer's own words when the agent spec sets none (`agent.chatProps.locale` first). */\n readonly locale: AppShellLocale | undefined;\n /** Expanded only: the side the dock sits on while docked (the viewer's choice, remembered). */\n readonly side: DockSide;\n readonly setSide: (side: DockSide) => void;\n /** Set by a dock control: the next placement or side change puts focus back on the panel's first dock control. */\n readonly restoreFocus: { current: boolean };\n}\n\ntype DockSide = 'left' | 'right';\n/** The dock's remembered state lives under this prefix (DockLayout's storageKey): `<key>.agent.floating`, `.width`, and the side. */\nconst DOCK_KEY = 'boring.app-shell';\nconst SIDE_KEY = `${DOCK_KEY}.agent.side`;\n\nconst LayerContext = createContext<Internal | null>(null);\n\nfunction useInternal(): Internal {\n const layer = useContext(LayerContext);\n if (!layer) throw new Error('useAgentLayer needs an AgentLayerProvider');\n return layer;\n}\n\n/** The layer's state and controls. */\nexport function useAgentLayer(): AgentLayerApi {\n const { state, showing, open, close, expanded } = useInternal();\n return useMemo(() => ({ state, showing, open, close, expanded }), [state, showing, open, close, expanded]);\n}\n\nconst REFUSAL: Readonly<Record<VoiceRefusal, 'voiceDenied' | 'voiceNoMicrophone' | 'voiceBusy' | 'voiceInsecure' | 'voiceUnsupported' | 'voiceStartFailed'>> = {\n denied: 'voiceDenied', 'no-microphone': 'voiceNoMicrophone', busy: 'voiceBusy', insecure: 'voiceInsecure', unsupported: 'voiceUnsupported', failed: 'voiceStartFailed',\n};\n\n/** The agent's push-to-talk: record on `start`, transcribe on `finish`, then submit or fill the composer. One microphone capture per mount. */\nfunction useVoice(agent: AgentSpec | undefined, locale: AppShellLocale | undefined, done: (outcome: 'sent' | 'drafted') => void): Voice {\n const [phase, setPhase] = useState<VoicePhase>('idle');\n const [seconds, setSeconds] = useState(0);\n const [problem, setProblem] = useState<string | undefined>();\n const capture = useRef<VoiceCapture | null>(null);\n const run = useRef(0);\n const work = useRef<AbortController | null>(null);\n const phaseRef = useRef<VoicePhase>('idle');\n const latest = useRef({ agent, done, locale });\n latest.current = { agent, done, locale };\n const set = (next: VoicePhase) => { phaseRef.current = next; setPhase(next); };\n const words = () => chatTextFor(latest.current.agent?.chatProps?.locale ?? latest.current.locale).labels;\n\n useEffect(() => () => { run.current += 1; capture.current?.cancel(); work.current?.abort(); }, []);\n useEffect(() => {\n if (phase !== 'recording') return;\n setSeconds(0);\n const started = Date.now();\n const timer = setInterval(() => setSeconds(Math.floor((Date.now() - started) / 1000)), 250);\n return () => clearInterval(timer);\n }, [phase]);\n\n const start = useCallback(() => {\n if (!latest.current.agent?.voice || phaseRef.current !== 'idle') return;\n const attempt = ++run.current;\n setProblem(undefined);\n set('starting');\n capture.current ??= createVoiceCapture();\n // Called synchronously from the person's gesture, so the browser ties the permission prompt to it.\n void capture.current.start().then(result => {\n if (attempt !== run.current) { capture.current?.cancel(); return; }\n if (result.kind === 'refused') { set('idle'); setProblem(result.code ? words()[REFUSAL[result.code]] : result.reason); return; }\n set('recording');\n });\n }, []);\n\n const cancel = useCallback(() => {\n run.current += 1;\n capture.current?.cancel();\n work.current?.abort();\n work.current = null;\n setProblem(undefined);\n set('idle');\n }, []);\n\n const finish = useCallback(() => {\n const current = latest.current.agent;\n if (!current?.voice) return;\n if (phaseRef.current === 'starting') { cancel(); return; }\n if (phaseRef.current !== 'recording') return;\n const attempt = run.current;\n set('transcribing');\n void (async () => {\n const recording = await capture.current?.stop().catch(() => null);\n if (attempt !== run.current) return;\n if (!recording) { set('idle'); setProblem(words().voiceNothingHeard); return; }\n const abort = new AbortController();\n work.current = abort;\n try {\n const spoken = (await current.voice!.transcribe(recording.audio, abort.signal)).trim();\n if (attempt !== run.current) return;\n if (!spoken) { setProblem(words().voiceNothingHeard); return; }\n const fill = () => {\n const draft = current.controller.getSnapshot().draft.text;\n current.controller.setText(`${draft}${draft === '' || /\\s$/.test(draft) ? '' : ' '}${spoken}`);\n latest.current.done('drafted');\n };\n if (current.voice!.send === 'auto') {\n // Admission is awaited: the text is reported as sent only when the submission was admitted. A refusal puts it back in the composer\n // (the controller does that); a rejection (an earlier submission still unconfirmed) is caught here and the transcript is kept as a draft.\n try { if (await current.controller.send(undefined, { text: spoken })) latest.current.done('sent'); else latest.current.done('drafted'); }\n catch { fill(); }\n } else fill();\n } catch { if (attempt === run.current) setProblem(words().voiceTranscribeFailed); }\n finally { if (work.current === abort) work.current = null; if (attempt === run.current) set('idle'); }\n })();\n }, [cancel]);\n\n return useMemo(() => ({ phase, seconds, problem, start, finish, cancel }), [phase, seconds, problem, start, finish, cancel]);\n}\n\n/** The height in px of the tab bar the peek sits above (`--app-shell-tabbar` on the shell root), and one rem. */\nfunction useMeasuredPeek(probe: RefObject<HTMLDivElement | null>): { readonly peekPoint: string; readonly tabbar: number } {\n const [px, setPx] = useState(PEEK_REM * 16);\n const [tabbar, setTabbar] = useState(0);\n useLayoutEffect(() => {\n const measure = () => {\n const tab = probe.current?.offsetHeight ?? 0;\n const rem = parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;\n setPx(Math.round(PEEK_REM * rem + tab));\n setTabbar(tab);\n };\n measure();\n window.addEventListener('resize', measure);\n const observer = typeof ResizeObserver === 'undefined' || !probe.current ? undefined : new ResizeObserver(measure);\n if (observer && probe.current) observer.observe(probe.current);\n return () => { window.removeEventListener('resize', measure); observer?.disconnect(); };\n }, [probe]);\n return { peekPoint: `${px}px`, tabbar };\n}\n\n/** Places the layer in the app. `agent` is the one assistant; `improve` is the product manager. Either may be absent. */\nexport function AgentLayerProvider({ agent, improve, locale, children }: { readonly agent?: AgentSpec | undefined; readonly improve?: AgentSpec | undefined; readonly locale?: AppShellLocale | undefined; readonly children: ReactNode }): ReactElement {\n const compact = useIsMobile();\n const expanded = !compact;\n const [snap, setSnapState] = useState<Snap>('closed');\n const [shown, setShown] = useState<Which>(agent ? 'agent' : 'improve');\n const probe = useRef<HTMLDivElement>(null);\n const { peekPoint, tabbar } = useMeasuredPeek(probe);\n const triggerUntil = useRef(0);\n const restoreFocus = useRef(false);\n const [side, setSideState] = useState<DockSide>('right');\n // The side is the viewer's, remembered beside the Dock's own placement; read after mount so server and client markup agree.\n useLayoutEffect(() => { try { const saved = globalThis.localStorage?.getItem(SIDE_KEY); if (saved === 'left' || saved === 'right') setSideState(saved); } catch { /* a convenience */ } }, []);\n const setSide = useCallback((next: DockSide) => { setSideState(next); try { globalThis.localStorage?.setItem(SIDE_KEY, next); } catch { /* a convenience */ } }, []);\n const specs = useRef({ agent, improve });\n specs.current = { agent, improve };\n\n const setSnap = useCallback((next: Snap) => setSnapState(next), []);\n const close = useCallback(() => setSnapState('closed'), []);\n // One full-screen layer at a time: opening the agent or product manager closes a view of the app (`useShellLayer`), and a view closes these.\n useEffect(() => registerAgentLayerCloser(close), [close]);\n const open = useCallback((which?: Which, at: 'half' | 'full' = 'half') => {\n const { agent: a, improve: i } = specs.current;\n const target = which ?? (a ? 'agent' : 'improve');\n if (target === 'agent' ? !a : !i) return;\n closeShellLayer();\n setShown(target);\n setSnapState(at);\n }, []);\n const showAgent = useCallback(() => { if (specs.current.agent) setShown('agent'); }, []);\n\n // A spec that goes away takes the layer with it.\n const shownSpec = shown === 'agent' ? agent : improve;\n useEffect(() => { if (!shownSpec) { setSnapState('closed'); if (shown === 'improve' && agent) setShown('agent'); else if (shown === 'agent' && improve) setShown('improve'); } }, [shownSpec, shown, agent, improve]);\n\n // The chats live in one element that is moved into the open drawer or panel; React keeps them mounted (and so their presentation state\n // and uploads) while the layer is closed, on a phone and on a wide screen. Nothing is mounted before the layer is first opened.\n const [host] = useState(() => typeof document === 'undefined' ? null : Object.assign(document.createElement('div'), { className: 'flex min-h-0 flex-1 flex-col [&_[data-boring=pi-chat]>header]:hidden' }));\n const opened = useRef(false);\n if (snap !== 'closed') opened.current = true;\n\n const voice = useVoice(agent, locale, outcome => {\n if (outcome === 'drafted') { setShown('agent'); setSnapState('half'); }\n });\n\n const state: AgentLayerState = snap === 'closed' ? 'closed' : expanded ? 'open' : snap;\n const value = useMemo<Internal>(() => ({\n state, showing: snap === 'closed' ? null : shown, open, close, expanded, agent, improve, snap, setSnap, showAgent, triggerUntil, voice, peekPoint, tabbar, host, locale, side, setSide, restoreFocus,\n }), [state, snap, shown, open, close, expanded, agent, improve, setSnap, showAgent, triggerUntil, voice, peekPoint, tabbar, host, locale, side, setSide]);\n\n // The shell's z-scale (tabs 20, peek 30, drawer and panel 40, other sheets 50, point bar 60) as custom properties; `display: contents` keeps the box tree unchanged.\n const scale = { '--app-shell-z-tabs': Z.tabs, '--app-shell-z-peek': Z.peek, '--app-shell-z-layer': Z.layer, '--app-shell-z-sheet': Z.sheet, '--app-shell-z-point': Z.point } as CSSProperties;\n return <AgentContextProvider>\n <LayerContext.Provider value={value}>\n <div data-app-shell=\"\" className=\"contents\" style={scale}>\n <div ref={probe} aria-hidden=\"true\" className=\"pointer-events-none invisible fixed top-0 left-0 w-0\" style={{ height: 'var(--app-shell-tabbar, 0px)' }} />\n {children}\n {host && opened.current && createPortal(<Chats showing={shown} />, host)}\n </div>\n </LayerContext.Provider>\n </AgentContextProvider>;\n}\n\n/** The header button that opens the layer: a tap opens half; with `agent.voice`, press and hold records and a slide off cancels. Absent without `agent`. */\nexport function AgentTrigger({ className, children }: { readonly className?: string; readonly children?: ReactNode }) {\n const layer = useInternal();\n const { agent, voice } = layer;\n const text = appShellText(agent?.chatProps?.locale ?? layer.locale);\n const hold = useRef<{ timer: ReturnType<typeof setTimeout> | undefined; held: boolean; id: number } | null>(null);\n if (!agent) return null;\n\n const toggle = () => {\n layer.triggerUntil.current = Date.now() + 500;\n if (layer.state !== 'closed' && layer.showing === 'agent' && layer.expanded) layer.close();\n else layer.open('agent', 'half');\n };\n const release = (event: ReactPointerEvent<HTMLButtonElement>) => {\n const current = hold.current;\n hold.current = null;\n if (!current) return;\n clearTimeout(current.timer);\n if (event.currentTarget.hasPointerCapture?.(current.id)) event.currentTarget.releasePointerCapture(current.id);\n if (current.held) { if (event.type === 'pointerup') voice.finish(); else voice.cancel(); }\n else if (event.type === 'pointerup') toggle();\n };\n const down = (event: ReactPointerEvent<HTMLButtonElement>) => {\n if (event.button !== 0) return;\n const target = event.currentTarget;\n target.setPointerCapture?.(event.pointerId);\n const state = { timer: undefined as ReturnType<typeof setTimeout> | undefined, held: false, id: event.pointerId };\n hold.current = state;\n if (agent.voice) {\n state.timer = setTimeout(() => {\n state.held = true;\n if (layer.snap === 'closed') layer.setSnap('peek');\n layer.showAgent();\n voice.start();\n }, HOLD_MS);\n }\n };\n const move = (event: ReactPointerEvent<HTMLButtonElement>) => {\n const current = hold.current;\n if (!current?.held) return;\n const box = event.currentTarget.getBoundingClientRect();\n const slack = 24;\n if (event.clientX < box.left - slack || event.clientX > box.right + slack || event.clientY < box.top - slack || event.clientY > box.bottom + slack) {\n hold.current = null;\n voice.cancel();\n }\n };\n return <button type=\"button\" data-agent-trigger=\"\" data-testid=\"agent-trigger\" aria-label={text.open} aria-expanded={layer.state !== 'closed'}\n onPointerDown={down} onPointerUp={release} onPointerCancel={release} onPointerMove={move} onContextMenu={event => event.preventDefault()}\n onClick={event => { if (event.detail === 0) toggle(); }}\n className={cn('inline-flex min-h-9 min-w-9 touch-none items-center justify-center rounded-md text-foreground outline-none select-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/60 pointer-coarse:min-h-11 pointer-coarse:min-w-11', className)}>\n {children ?? <SparklesIcon className=\"size-4\" aria-hidden=\"true\" />}\n </button>;\n}\n\nconst clock = (seconds: number) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;\n\n/** Push-to-talk in the composer row (PiChat's `tools` slot): press and hold, release to send or fill; a slide off cancels. */\nfunction TalkButton({ text }: { readonly text: AppShellText }) {\n const { voice } = useInternal();\n const recording = voice.phase === 'recording' || voice.phase === 'starting';\n const busy = voice.phase === 'transcribing';\n const down = (event: ReactPointerEvent<HTMLButtonElement>) => { event.currentTarget.setPointerCapture?.(event.pointerId); voice.start(); };\n const up = (event: ReactPointerEvent<HTMLButtonElement>) => { if (event.currentTarget.hasPointerCapture?.(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); if (event.type === 'pointerup') voice.finish(); else voice.cancel(); };\n const move = (event: ReactPointerEvent<HTMLButtonElement>) => {\n if (!recording) return;\n const box = event.currentTarget.getBoundingClientRect(), slack = 24;\n if (event.clientX < box.left - slack || event.clientX > box.right + slack || event.clientY < box.top - slack || event.clientY > box.bottom + slack) voice.cancel();\n };\n return <button type=\"button\" data-testid=\"agent-talk\" data-state={voice.phase} disabled={busy} aria-label={text.holdToTalk} title={text.holdToTalk}\n onPointerDown={down} onPointerUp={up} onPointerCancel={up} onPointerMove={move} onContextMenu={event => event.preventDefault()}\n className={cn('inline-flex size-11 shrink-0 touch-none items-center justify-center rounded-lg bg-muted text-foreground outline-none select-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/60 disabled:opacity-60', recording && 'bg-destructive text-white hover:bg-destructive/90')}>\n {busy ? <Loader2Icon className=\"size-5 animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" /> : <MicIcon className=\"size-5\" aria-hidden=\"true\" />}\n </button>;\n}\n\n/** What went wrong with the microphone, in the flow under the title row (never over the messages). */\nfunction VoiceProblem() {\n const { voice } = useInternal();\n return voice.problem ? <p role=\"alert\" data-testid=\"agent-voice-problem\" className=\"m-0 shrink-0 px-3 pb-1 text-xs leading-4 text-destructive\">{voice.problem}</p> : null;\n}\n\n/** One agent's PiChat. It stays mounted while hidden, so its scroll, focus and drafts survive a swap with the other spec. */\nfunction SpecChat({ spec, visible, role }: { readonly spec: AgentSpec; readonly visible: boolean; readonly role: Which }) {\n const layer = useInternal();\n const locale = spec.chatProps?.locale ?? layer.locale;\n // One annotate toggle: pins on desktop, point mode (which hides the layer while the person taps the app) on touch and compact screens.\n const feedback = useComposerFeedback(spec.feedback);\n const pointing = usePointing(spec.feedback);\n // The pin's mic uses the shell's transcription: this agent's own, else the coach's.\n const transcribe = (spec.voice ?? layer.agent?.voice)?.transcribe;\n const fr = locale === 'fr';\n return <div data-spec={role} hidden={!visible} className={cn('min-h-0 min-w-0 flex-1', visible ? 'flex flex-col' : 'hidden')}>\n <PiChat {...spec.chatProps} {...(locale ? { locale } : {})} controller={spec.controller} {...(feedback ? { feedback } : {})}\n {...(role === 'agent' && spec.voice ? { tools: <>{spec.chatProps?.tools}<TalkButton text={appShellText(locale)} /></> } : {})} />\n {/* The note editor of ordinary feedback lives inside the layer, in the modal's focus tree; while pointing the layer steps aside and AgentLayer renders it. */}\n {/* In the flow, inside the visible content box: the popup is transformed (a fixed element would be placed against its off-screen bottom). */}\n {spec.feedback && visible && !pointing && <div className=\"shrink-0 px-2 pb-2 empty:hidden\">\n <NoteBubble session={spec.feedback} {...(transcribe ? { transcribe } : {})} {...(fr ? { labels: feedbackLabelsFr } : {})} /></div>}\n </div>;\n}\n\n/** Where the chats show: the persistent host element is moved in once, when the drawer or panel mounts. */\nfunction ChatSlot() {\n const { host } = useInternal();\n const place = useCallback((slot: HTMLDivElement | null) => { if (slot && host) slot.appendChild(host); }, [host]);\n // Coarse pointers: the chat's own transcript buttons (copy, show earlier) get the layer's 44px rule from here, without touching pi-chat.\n return <div ref={place} className=\"flex min-h-0 flex-1 flex-col [&_[data-testid=transcript]_button]:pointer-coarse:min-h-11 [&_[data-testid=transcript]_button]:pointer-coarse:min-w-11\" />;\n}\n\n/** Both specs, each mounted once it has been shown. */\nfunction Chats({ showing }: { readonly showing: Which }) {\n const { agent, improve } = useInternal();\n const seen = useRef(new Set<Which>());\n seen.current.add(showing);\n return <>\n {agent && seen.current.has('agent') && <SpecChat spec={agent} visible={showing === 'agent'} role=\"agent\" />}\n {improve && seen.current.has('improve') && <SpecChat spec={improve} visible={showing === 'improve'} role=\"improve\" />}\n </>;\n}\n\nconst ICON_BUTTON = 'inline-flex size-9 shrink-0 items-center justify-center rounded-md text-foreground outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/60 pointer-coarse:min-h-11 pointer-coarse:min-w-11';\n\n/** Title row: « ← » when the improve view has an agent to go back to, the title, then Expand or Collapse (compact only), the dock controls (expanded only) and Close. */\nfunction Header({ text, title, compactSnap, closeRef, controls, className, ...rest }: { readonly text: AppShellText; readonly title: string; readonly compactSnap?: Snap; readonly closeRef?: Ref<HTMLButtonElement>; readonly controls?: ReactNode } & Omit<HTMLAttributes<HTMLDivElement>, 'title'>) {\n const layer = useInternal();\n const back = layer.showing === 'improve' && layer.agent;\n const actions = (layer.showing === 'improve' ? layer.improve : layer.agent)?.headerActions ?? [];\n return <div data-testid=\"agent-layer-header\" {...rest} className={cn('flex shrink-0 items-center gap-1 px-2 pb-1', className)}>\n {back && <button type=\"button\" data-testid=\"agent-layer-back\" aria-label={text.back} title={text.back} onClick={layer.showAgent} className={ICON_BUTTON}><ArrowLeftIcon className=\"size-4\" aria-hidden=\"true\" /></button>}\n <h2 data-testid=\"agent-layer-title\" className=\"m-0 min-w-0 flex-1 truncate px-1 text-sm font-semibold\">{title}</h2>\n {actions.length > 0 && <HeaderActions actions={actions} compact={compactSnap !== undefined} text={text} prefix=\"agent-layer\" run={id => actions.find(action => action.id === id)?.onSelect()} />}\n {compactSnap === 'half' && <button type=\"button\" data-testid=\"agent-layer-expand\" aria-label={text.expand} title={text.expand} onClick={() => layer.setSnap('full')} className={ICON_BUTTON}><ChevronUpIcon className=\"size-4\" aria-hidden=\"true\" /></button>}\n {compactSnap === 'full' && <button type=\"button\" data-testid=\"agent-layer-collapse\" aria-label={text.collapse} title={text.collapse} onClick={() => layer.setSnap('half')} className={ICON_BUTTON}><ChevronDownIcon className=\"size-4\" aria-hidden=\"true\" /></button>}\n {controls}\n <button type=\"button\" ref={closeRef} data-testid=\"agent-layer-close\" aria-label={text.close} title={text.close} onClick={layer.close} className={ICON_BUTTON}><XIcon className=\"size-4\" aria-hidden=\"true\" /></button>\n </div>;\n}\n\nfunction useTitle(): { text: AppShellText; title: string } {\n const layer = useInternal();\n const spec = layer.showing === 'improve' ? layer.improve : layer.agent;\n const text = appShellText(spec?.chatProps?.locale ?? layer.locale);\n const title = layer.showing === 'improve' ? text.improve : (spec?.chatProps?.labels?.title ?? text.assistant);\n return { text, title };\n}\n\nconst toSnap = (point: number | string | null, peekPoint: string): Snap | null =>\n point === peekPoint ? 'peek' : point === HALF ? 'half' : point === FULL ? 'full' : null;\n\nfunction CompactSheet({ pointing }: { readonly pointing: boolean }) {\n const layer = useInternal();\n const { snap, agent, voice } = layer;\n const hasPeek = Boolean(agent);\n const { text, title } = useTitle();\n const vv = useVisualViewport();\n const closeRef = useRef<HTMLButtonElement>(null);\n const vetoed = useRef(false);\n // Set while the layer closes; cleared when it opens again (a close is final until the trigger or a choice opens the layer).\n const closing = useRef(false);\n useEffect(() => { if (snap !== 'closed') closing.current = false; }, [snap]);\n const open = snap !== 'closed' && !pointing;\n const peek = snap === 'peek';\n const points = useMemo(() => hasPeek ? [layer.peekPoint, HALF, FULL] : [HALF, FULL], [hasPeek, layer.peekPoint]);\n const value = peek ? layer.peekPoint : snap === 'full' ? FULL : HALF;\n const recording = voice.phase !== 'idle';\n\n useBackLayer(snap === 'half' || snap === 'full', layer.close, 'agent');\n\n // The popup is taller than what shows and slides down by `--drawer-snap-point-offset` (a registered, non-inheriting property, so only the\n // popup itself can read it): padding the popup by that offset makes its content box exactly the visible part. At peek the tab bar below is left out too.\n // The popup is portalled to the body, outside the shell root: it is given the measured tab bar height and the z-values explicitly.\n const style = { '--app-shell-vv-height': vv ? `${vv.height}px` : '100dvh', '--app-shell-tabbar': `${layer.tabbar}px`, '--app-shell-z-layer': Z.layer,\n paddingBottom: peek ? 'calc(var(--drawer-snap-point-offset, 0px) + var(--app-shell-tabbar, 0px))' : 'var(--drawer-snap-point-offset, 0px)' } as CSSProperties;\n // Entering the modal half or full from the non-modal peek does not rerun Base UI's initial focus: if focus is still on the page, take it to Close.\n const wasPeek = useRef(false);\n useEffect(() => {\n const entering = wasPeek.current && !peek && open;\n wasPeek.current = peek;\n if (!entering) return;\n // The element that held focus when the sheet left peek (a page control now behind the modal). Base UI re-applies its modal guards as the\n // sheet moves, so retake focus once they have settled and again after the slide, but only while focus is still stranded there (or lost to the body).\n const stranded = document.activeElement;\n const take = () => {\n const popup = closeRef.current?.closest('[data-slot=drawer-popup]');\n const active = document.activeElement;\n // Still stranded, or dropped to the body by the modal guards: retake. Focus that went anywhere else is the person's and is left alone.\n if (popup && (active === stranded || active === document.body || active === null) && !popup.contains(active)) closeRef.current?.focus({ preventScroll: true });\n };\n const early = setTimeout(take, 60), late = setTimeout(take, 520);\n return () => { clearTimeout(early); clearTimeout(late); };\n }, [peek, open]);\n return <Drawer open={open} modal={!peek} showSwipeHandle swipeDirection=\"down\" snapPoints={points} snapPoint={value}\n onOpenChange={(next, details) => {\n if (next) return;\n const outcome = nextSnapOnClose(details.reason, hasPeek);\n if (outcome === 'close') { closing.current = true; layer.close(); return; }\n details.cancel();\n vetoed.current = true;\n setTimeout(() => { vetoed.current = false; }, 120);\n // Focus leaving the non-modal peek changes nothing, and neither does the click that finished a press on the AgentTrigger (outside the\n // drawer, so it counts as an outside press): the trigger already chose the snap.\n if (details.reason === 'focus-out' || Date.now() < layer.triggerUntil.current) return;\n layer.setSnap(outcome);\n }}\n onSnapPointChange={point => {\n // Vetoing a swipe-close makes the drawer snap back to where it was: that echo must not undo the snap we chose.\n // Base UI also reports the first snap point (peek) as the drawer closes: that echo must not reopen the layer.\n if (vetoed.current || closing.current) return;\n const next = toSnap(point, layer.peekPoint);\n if (next && (next !== 'peek' || hasPeek)) layer.setSnap(next);\n }}>\n <DrawerContent data-testid=\"agent-layer\" aria-label={title} data-state={snap} data-peek={peek} initialFocus={() => closeRef.current ?? false} style={style}\n className={cn('app-shell box-border z-(--app-shell-z-layer) data-[swipe-direction=down]:bottom-(--drawer-keyboard-inset,0px) data-[swipe-axis=y]:[--drawer-content-max-height:calc(var(--app-shell-vv-height,100dvh)-1.5rem)]',\n // The peek is the top PEEK_REM of the popup; the part that overlaps the tab bar is clipped away, so the tabs stay visible and tappable.\n 'data-[peek=true]:not-data-swiping:[clip-path:inset(0_0_calc(100%_-_6rem)_0)]')}>\n <DrawerPrimitive.VirtualKeyboardProvider>\n <div data-testid=\"agent-layer-sheet\" onFocusCapture={event => { if ((event.target as HTMLElement).matches('[data-testid=composer-input]')) layer.setSnap('full'); }}\n className={cn('relative flex min-h-0 flex-1 flex-col overflow-hidden overscroll-contain',\n // The layer's own header carries the title and Close, so the chat's is hidden. At peek: one line of the last reply above the\n // composer, no empty-state overlay, room for Close.\n '[&_[data-boring=pi-chat]>header]:hidden',\n // At peek: ONE compact row (a one-line input, the microphone and Send; the other composer controls wait for half), and the last\n // reply as a single truncated line above it.\n peek && ['[&_[data-boring=pi-chat]>.relative]:overflow-hidden [&_[data-boring=pi-chat]>.relative>.pointer-events-none]:hidden',\n '[&_[data-boring=pi-chat]>footer]:px-2 [&_[data-boring=pi-chat]>footer]:pt-1 [&_[data-boring=pi-chat]>footer]:pb-2',\n '[&_[data-testid=transcript]]:gap-0 [&_[data-testid=transcript]]:p-0 [&_[data-testid=transcript]]:px-3 [&_[data-testid=transcript]>*]:max-h-5 [&_[data-testid=transcript]>*]:truncate [&_[data-testid=transcript]_button]:hidden',\n '[&_[data-testid=composer]]:flex [&_[data-testid=composer]]:items-center [&_[data-testid=composer]]:rounded-full',\n '[&_[data-testid=composer-input]]:min-h-11 [&_[data-testid=composer-input]]:max-h-11 [&_[data-testid=composer-input]]:flex-1 [&_[data-testid=composer-input]]:px-4 [&_[data-testid=composer-input]]:py-2.5',\n '[&_[data-testid=composer]>div]:p-0 [&_[data-testid=composer]>div]:pr-1 [&_[data-testid=composer]>div>.flex-1]:hidden',\n '[&_[data-testid=composer-plus]]:hidden [&_[data-testid=composer-annotate]]:hidden'])}>\n {!peek && <Header text={text} title={title} compactSnap={snap} closeRef={closeRef} />}\n {!peek && <VoiceProblem />}\n {peek && recording && <div role=\"status\" data-testid=\"agent-listening\" data-phase={voice.phase} className=\"absolute inset-0 z-20 flex items-center justify-center gap-2 bg-popover text-sm font-medium\">\n <MicIcon className=\"size-4 text-destructive\" aria-hidden=\"true\" />{voice.phase === 'transcribing' ? <Loader2Icon className=\"size-4 animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" /> : `${text.listening} ${clock(voice.seconds)}`}\n </div>}\n {/* The transcript scrolls and never drags the sheet: only the handle and the title row swipe. */}\n <div data-base-ui-swipe-ignore=\"\" className=\"flex min-h-0 flex-1 flex-col\"><ChatSlot /></div>\n </div>\n </DrawerPrimitive.VirtualKeyboardProvider>\n </DrawerContent>\n </Drawer>;\n}\n\n/** The panel inside the dock: the same element docked or floating, so a placement change keeps focus and the chats where they are. */\nfunction DockPanel({ api, side }: { readonly api: DockApi; readonly side: DockSide }) {\n const layer = useInternal();\n const { text, title } = useTitle();\n const open = layer.snap !== 'closed';\n const floating = api.floating;\n const box = useRef<HTMLDivElement>(null);\n const drag = useRef<{ dx: number; dy: number } | null>(null);\n const [pos, setPos] = useState<{ left: number; top: number } | null>(null);\n useEffect(() => {\n if (!open) return;\n const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape' && !event.defaultPrevented) layer.close(); };\n document.addEventListener('keydown', onKey);\n return () => document.removeEventListener('keydown', onKey);\n }, [open, layer]);\n // A dock control (or the divider's Alt+Arrow) moves or removes the element that had focus: it goes to the panel's first dock control instead of the page.\n useLayoutEffect(() => {\n const lost = !document.activeElement || document.activeElement === document.body;\n const wanted = layer.restoreFocus.current || (open && lost && api.placement !== 'closed');\n layer.restoreFocus.current = false;\n if (wanted) box.current?.querySelector<HTMLElement>('[data-dock-control]')?.focus({ preventScroll: true });\n }, [api.placement, side, layer.restoreFocus]);\n // A dragged window stays reachable: its remembered position is clamped to the viewport on open, on placement change and on every resize.\n const [viewport, setViewport] = useState(0);\n useEffect(() => { const resize = () => setViewport(count => count + 1); window.addEventListener('resize', resize); return () => window.removeEventListener('resize', resize); }, []);\n useLayoutEffect(() => {\n const rect = box.current?.getBoundingClientRect();\n if (!pos || !floating || !open || !rect || !rect.width) return;\n const left = Math.min(Math.max(pos.left, 0), Math.max(0, innerWidth - rect.width)), top = Math.min(Math.max(pos.top, 0), Math.max(0, innerHeight - rect.height));\n if (left !== pos.left || top !== pos.top) setPos({ left, top });\n }, [pos, floating, open, viewport]);\n const act = (run: () => void) => () => { layer.restoreFocus.current = true; run(); };\n const control = (id: string, label: string, Icon: ComponentType<{ className?: string }>, run: () => void) =>\n <button type=\"button\" key={id} data-testid={`agent-layer-${id}`} data-dock-control=\"\" aria-label={label} title={label} onClick={act(run)} className={ICON_BUTTON}><Icon className=\"size-4\" aria-hidden=\"true\" /></button>;\n const controls = <>\n {!floating && control('float', text.float, PictureInPicture2Icon, () => api.float())}\n {(floating || side === 'right') && control('dock-left', text.dockLeft, PanelLeftIcon, () => { layer.setSide('left'); api.dock(); })}\n {(floating || side === 'left') && control('dock-right', text.dockRight, PanelRightIcon, () => { layer.setSide('right'); api.dock(); })}\n </>;\n const down = (event: ReactPointerEvent<HTMLDivElement>) => {\n const rect = box.current?.getBoundingClientRect();\n if (!floating || !rect || event.button !== 0 || (event.target as HTMLElement).closest('button, a[href]')) return;\n drag.current = { dx: event.clientX - rect.left, dy: event.clientY - rect.top };\n event.currentTarget.setPointerCapture?.(event.pointerId);\n };\n const move = (event: ReactPointerEvent<HTMLDivElement>) => {\n const grab = drag.current, rect = box.current?.getBoundingClientRect();\n if (!grab || !rect) return;\n setPos({ left: Math.min(Math.max(event.clientX - grab.dx, 0), Math.max(0, innerWidth - rect.width)), top: Math.min(Math.max(event.clientY - grab.dy, 0), Math.max(0, innerHeight - rect.height)) });\n };\n const end = () => { drag.current = null; };\n return <div ref={box} data-testid=\"agent-layer\" data-state={open ? 'open' : 'closed'} data-placement={api.placement} data-side={side} role={floating ? 'dialog' : 'complementary'} aria-label={title}\n style={floating ? pos ?? { right: 16, bottom: 16 } : undefined}\n className={cn('app-shell flex min-h-0 flex-col bg-background text-foreground',\n floating ? 'fixed z-(--app-shell-z-layer) h-[min(36rem,calc(100dvh-2rem))] w-[min(24rem,calc(100vw-2rem))] overflow-hidden rounded-xl border border-border shadow-xl'\n : cn('h-full min-w-0 flex-1', side === 'right' ? 'border-l border-border' : 'border-r border-border'))}>\n <Header text={text} title={title} controls={controls} className={cn('pt-2', floating && 'cursor-move touch-none select-none')} onPointerDown={down} onPointerMove={move} onPointerUp={end} onPointerCancel={end} />\n <div className=\"flex min-h-0 flex-1 flex-col overflow-hidden\"><VoiceProblem /><ChatSlot /></div>\n </div>;\n}\n\nfunction AgentDock({ side }: { readonly side: DockSide }) {\n const layer = useInternal();\n const { title } = useTitle();\n return <Dock id=\"agent\" side={side} floatable defaultWidth={384} minWidth={320} dragBelow={260} open={layer.snap !== 'closed'} onOpenChange={next => { if (!next) layer.close(); }} labels={{ region: title }}>\n {api => <DockPanel api={api} side={side} />}\n </Dock>;\n}\n\n/**\n * Wraps the app's content (placed once by the shell): on a wide screen the agent dock sits on its left or right and the content reflows,\n * or it floats over the content; on a phone this is only the content (the layer is the bottom drawer). Host concern: Pi has no layout.\n */\nexport function AgentDockLayout({ children }: { readonly children: ReactNode }): ReactElement {\n const layer = useInternal();\n const dock = layer.expanded && (layer.agent || layer.improve) ? <AgentDock side={layer.side} /> : null;\n return <DockLayout storageKey={DOCK_KEY} persist=\"local\">\n {layer.side === 'left' && dock}\n <DockMain>{children}</DockMain>\n {layer.side === 'right' && dock}\n </DockLayout>;\n}\n\n/** The layer itself: the drawer on a phone (the wide dock is `AgentDockLayout`). Placed once by the shell, for point mode on both. */\nexport function AgentLayer(): ReactElement | null {\n const layer = useInternal();\n const pointingAgent = usePointing(layer.agent?.feedback), pointingImprove = usePointing(layer.improve?.feedback);\n const session = pointingAgent ? layer.agent?.feedback : pointingImprove ? layer.improve?.feedback : undefined;\n // Back ends pointing first (the `point` priority); the layer keeps its own history entry underneath.\n useBackLayer(session !== undefined, () => session?.discard(), 'point');\n if (!layer.agent && !layer.improve) return null;\n const pointed = pointingAgent ? layer.agent : layer.improve;\n const transcribe = (pointed?.voice ?? layer.agent?.voice)?.transcribe;\n const locale = pointed?.chatProps?.locale ?? layer.locale;\n // Point mode: the compact sheet steps aside (the wide dock does not cover the app); the bar sits above the tab bar, outside the layer.\n return <>\n {!layer.expanded && <CompactSheet pointing={session !== undefined} />}\n {session && <>\n <PointBar session={session} bottomOffset={`${layer.tabbar}px`} className=\"z-[60]\" {...(locale === 'fr' ? { labels: feedbackLabelsFr } : {})} />\n <NoteBubble session={session} {...(transcribe ? { transcribe } : {})} {...(locale === 'fr' ? { labels: feedbackLabelsFr } : {})} />\n </>}\n </>;\n}\n",
|
|
33
|
+
"content": "'use client';\n\n// The AgentLayer: ONE agent's PiChat above the app. Compact (below 768px): a bottom drawer with three fixed snap points, peek, half and\n// full (shadcn `drawer`, Base UI variant). Expanded: a `Dock` (the `dock` item) beside the app, docked on the left or the right (default right)\n// or floating over it; the person chooses and the choice is remembered. The same layer shows\n// the product manager (« Améliorer l’app ») when the account menu asks for it. Push-to-talk is an option of the agent.\n// Host concern: Pi has no layout. The chat is the borrowed NativeChatController rendered by PiChat; the screen context travels as the\n// submit's `context` (agent-context.ts). Nothing here is configurable beyond AgentSpec.\nimport { createPortal } from 'react-dom';\nimport { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { ComponentType, CSSProperties, HTMLAttributes, PointerEvent as ReactPointerEvent, ReactElement, ReactNode, Ref, RefObject } from 'react';\nimport { ArrowLeftIcon, ChevronDownIcon, ChevronUpIcon, Loader2Icon, MicIcon, PanelLeftIcon, PanelRightIcon, PictureInPicture2Icon, SparklesIcon, XIcon } from 'lucide-react';\n// Behaviour only: Base UI's keyboard-inset provider for the host drawer's content. It renders nothing visible.\nimport * as BaseDrawerParts from '@base-ui/react/drawer';\nimport { Button } from '@/components/ui/button';\nimport { Card } from '@/components/ui/card';\nimport { Separator } from '@/components/ui/separator';\nimport { createVoiceCapture } from '@hachej/boring-feedback/page';\nimport type { VoiceCapture, VoiceRefusal } from '@hachej/boring-feedback/page';\nimport type { FeedbackSession } from '@hachej/boring-feedback/ui';\nimport type { NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { Drawer, DrawerContent } from '@/components/ui/drawer';\nimport { useIsMobile } from '@/hooks/use-mobile';\nimport { Dock, DockLayout, DockMain } from '../dock/dock';\nimport type { DockApi } from '../dock/dock';\nimport { PiChat } from '../pi-chat/pi-chat';\nimport type { PiChatProps } from '../pi-chat/pi-chat';\nimport { chatTextFor } from '../pi-chat/locale';\nimport { NoteBubble, useComposerFeedback } from '../feedback/feedback-session';\nimport { feedbackLabelsFr } from '../feedback/feedback-labels';\nimport { PointBar, usePointing } from '../feedback/point-mode';\nimport { cn } from '../utils/utils';\nimport { useBackLayer } from './back';\nimport { closeShellLayer, registerAgentLayerCloser } from './shell-layer';\nimport { appShellText } from './text';\nimport type { AppShellLocale, AppShellText } from './text';\nimport { useVisualViewport } from './use-visual-viewport';\nimport { AgentContextProvider } from './agent-context';\nimport { HeaderActions } from './header-actions';\nimport type { ScreenHeaderAction } from './header-actions';\n\nexport interface AgentSpec {\n readonly controller: NativeChatController;\n /** The agent's name in the expanded sidebar (default: the chat's title, then « Assistant »). */\n readonly label?: string;\n /** The agent's icon in the sidebar (default: the sparkles of the header trigger). */\n readonly icon?: ComponentType<{ className?: string }>;\n readonly chatProps?: Omit<PiChatProps, 'controller'>;\n /** Push-to-talk. `send` 'auto' submits the transcript; 'draft' (default) only fills the composer. */\n readonly voice?: { readonly transcribe: (audio: Blob, signal: AbortSignal) => Promise<string>; readonly send?: 'auto' | 'draft' };\n /** Point mode (the product manager, in practice). */\n readonly feedback?: FeedbackSession;\n /** Host actions in the layer's title row (before the dock controls, or the snap and close controls when compact), as the screen header's. Two shown, the rest in « … ». Not at peek. */\n readonly headerActions?: readonly ScreenHeaderAction[];\n}\n\n/** Compact: closed, peek, half or full. Expanded: closed or open. */\nexport type AgentLayerState = 'closed' | 'peek' | 'half' | 'full' | 'open';\ntype Which = 'agent' | 'improve';\ntype Snap = 'closed' | 'peek' | 'half' | 'full';\n\nexport interface AgentLayerApi {\n readonly state: AgentLayerState;\n readonly showing: Which | null;\n open(which?: Which, at?: 'half' | 'full'): void;\n close(): void;\n readonly expanded: boolean;\n}\n\n// The three fixed snap points: a peek (one composer row and a line of the last reply, `PEEK_REM` above the tab bar), 55% and the full height.\nconst PEEK_REM = 6;\n/** The shell's z-scale (tabs 20, peek 30, drawer and panel 40, other sheets 50, point bar 60). */\nconst Z = { tabs: 20, peek: 30, layer: 40, sheet: 50, point: 60 } as const;\nconst HALF = 0.55;\nconst FULL = 1;\n/** Hold the trigger this long before it records; shorter is a tap. */\nconst HOLD_MS = 350;\n\n/**\n * What a close request from the drawer becomes. A swipe, an outside press, a lost focus and Escape never close the layer: they step down\n * to peek (half without an `agent`), so the modal state goes and the coach stays reachable. Only the Close control closes it. `reason` is\n * Base UI's `details.reason` (`'swipe'`, `'outside-press'`, `'focus-out'`, `'escape-key'`, `'close-watcher'`, `'close-press'`, `'trigger-press'`,\n * `'imperative-action'`, `'none'`).\n */\nexport function nextSnapOnClose(reason: string, hasPeek: boolean): 'peek' | 'half' | 'close' {\n return reason === 'swipe' || reason === 'outside-press' || reason === 'focus-out' || reason === 'escape-key' ? (hasPeek ? 'peek' : 'half') : 'close';\n}\n\ntype VoicePhase = 'idle' | 'starting' | 'recording' | 'transcribing';\ninterface Voice {\n readonly phase: VoicePhase;\n readonly seconds: number;\n readonly problem: string | undefined;\n readonly start: () => void;\n readonly finish: () => void;\n readonly cancel: () => void;\n}\n\ninterface Internal extends AgentLayerApi {\n readonly agent: AgentSpec | undefined;\n readonly improve: AgentSpec | undefined;\n readonly snap: Snap;\n readonly setSnap: (snap: Snap) => void;\n /** Whether the wide layout's dock is floating over the app (reported by the panel); with `expanded` it gives the chats' placement. */\n readonly dockFloating: boolean;\n readonly setDockFloating: (floating: boolean) => void;\n readonly showAgent: () => void;\n /** Until this time (ms) an outside press is the AgentTrigger's own click. */\n readonly triggerUntil: { current: number };\n readonly voice: Voice;\n /** The peek height in px: `PEEK_REM` plus the tab bar the peek sits above. */\n readonly peekPoint: string;\n /** The measured tab bar height in px, given explicitly to the parts portalled to the body (they cannot inherit the shell's variables). */\n readonly tabbar: number;\n /** The persistent element holding both chats: it moves between the drawer and the panel, so closing never unmounts a chat. */\n readonly host: HTMLElement | null;\n /** The shell's `locale`: the layer's own words when the agent spec sets none (`agent.chatProps.locale` first). */\n readonly locale: AppShellLocale | undefined;\n /** Expanded only: the side the dock sits on while docked (the viewer's choice, remembered). */\n readonly side: DockSide;\n readonly setSide: (side: DockSide) => void;\n /** Set by a dock control: the next placement or side change puts focus back on the panel's first dock control. */\n readonly restoreFocus: { current: boolean };\n}\n\ntype DockSide = 'left' | 'right';\n/** The dock's remembered state lives under this prefix (DockLayout's storageKey): `<key>.agent.floating`, `.width`, and the side. */\nconst DOCK_KEY = 'boring.app-shell';\nconst SIDE_KEY = `${DOCK_KEY}.agent.side`;\n\nconst LayerContext = createContext<Internal | null>(null);\n\nfunction useInternal(): Internal {\n const layer = useContext(LayerContext);\n if (!layer) throw new Error('useAgentLayer needs an AgentLayerProvider');\n return layer;\n}\n\n/** The layer's state and controls. */\nexport function useAgentLayer(): AgentLayerApi {\n const { state, showing, open, close, expanded } = useInternal();\n return useMemo(() => ({ state, showing, open, close, expanded }), [state, showing, open, close, expanded]);\n}\n\nconst REFUSAL: Readonly<Record<VoiceRefusal, 'voiceDenied' | 'voiceNoMicrophone' | 'voiceBusy' | 'voiceInsecure' | 'voiceUnsupported' | 'voiceStartFailed'>> = {\n denied: 'voiceDenied', 'no-microphone': 'voiceNoMicrophone', busy: 'voiceBusy', insecure: 'voiceInsecure', unsupported: 'voiceUnsupported', failed: 'voiceStartFailed',\n};\n\n/** The agent's push-to-talk: record on `start`, transcribe on `finish`, then submit or fill the composer. One microphone capture per mount. */\nfunction useVoice(agent: AgentSpec | undefined, locale: AppShellLocale | undefined, done: (outcome: 'sent' | 'drafted') => void): Voice {\n const [phase, setPhase] = useState<VoicePhase>('idle');\n const [seconds, setSeconds] = useState(0);\n const [problem, setProblem] = useState<string | undefined>();\n const capture = useRef<VoiceCapture | null>(null);\n const run = useRef(0);\n const work = useRef<AbortController | null>(null);\n const phaseRef = useRef<VoicePhase>('idle');\n const latest = useRef({ agent, done, locale });\n latest.current = { agent, done, locale };\n const set = (next: VoicePhase) => { phaseRef.current = next; setPhase(next); };\n const words = () => chatTextFor(latest.current.agent?.chatProps?.locale ?? latest.current.locale).labels;\n\n useEffect(() => () => { run.current += 1; capture.current?.cancel(); work.current?.abort(); }, []);\n useEffect(() => {\n if (phase !== 'recording') return;\n setSeconds(0);\n const started = Date.now();\n const timer = setInterval(() => setSeconds(Math.floor((Date.now() - started) / 1000)), 250);\n return () => clearInterval(timer);\n }, [phase]);\n\n const start = useCallback(() => {\n if (!latest.current.agent?.voice || phaseRef.current !== 'idle') return;\n const attempt = ++run.current;\n setProblem(undefined);\n set('starting');\n capture.current ??= createVoiceCapture();\n // Called synchronously from the person's gesture, so the browser ties the permission prompt to it.\n void capture.current.start().then(result => {\n if (attempt !== run.current) { capture.current?.cancel(); return; }\n if (result.kind === 'refused') { set('idle'); setProblem(result.code ? words()[REFUSAL[result.code]] : result.reason); return; }\n set('recording');\n });\n }, []);\n\n const cancel = useCallback(() => {\n run.current += 1;\n capture.current?.cancel();\n work.current?.abort();\n work.current = null;\n setProblem(undefined);\n set('idle');\n }, []);\n\n const finish = useCallback(() => {\n const current = latest.current.agent;\n if (!current?.voice) return;\n if (phaseRef.current === 'starting') { cancel(); return; }\n if (phaseRef.current !== 'recording') return;\n const attempt = run.current;\n set('transcribing');\n void (async () => {\n const recording = await capture.current?.stop().catch(() => null);\n if (attempt !== run.current) return;\n if (!recording) { set('idle'); setProblem(words().voiceNothingHeard); return; }\n const abort = new AbortController();\n work.current = abort;\n try {\n const spoken = (await current.voice!.transcribe(recording.audio, abort.signal)).trim();\n if (attempt !== run.current) return;\n if (!spoken) { setProblem(words().voiceNothingHeard); return; }\n const fill = () => {\n const draft = current.controller.getSnapshot().draft.text;\n current.controller.setText(`${draft}${draft === '' || /\\s$/.test(draft) ? '' : ' '}${spoken}`);\n latest.current.done('drafted');\n };\n if (current.voice!.send === 'auto') {\n // Admission is awaited: the text is reported as sent only when the submission was admitted. A refusal puts it back in the composer\n // (the controller does that); a rejection (an earlier submission still unconfirmed) is caught here and the transcript is kept as a draft.\n try { if (await current.controller.send(undefined, { text: spoken })) latest.current.done('sent'); else latest.current.done('drafted'); }\n catch { fill(); }\n } else fill();\n } catch { if (attempt === run.current) setProblem(words().voiceTranscribeFailed); }\n finally { if (work.current === abort) work.current = null; if (attempt === run.current) set('idle'); }\n })();\n }, [cancel]);\n\n return useMemo(() => ({ phase, seconds, problem, start, finish, cancel }), [phase, seconds, problem, start, finish, cancel]);\n}\n\n/** The height in px of the tab bar the peek sits above (`--app-shell-tabbar` on the shell root), and one rem. */\nfunction useMeasuredPeek(probe: RefObject<HTMLDivElement | null>): { readonly peekPoint: string; readonly tabbar: number } {\n const [px, setPx] = useState(PEEK_REM * 16);\n const [tabbar, setTabbar] = useState(0);\n useLayoutEffect(() => {\n const measure = () => {\n const tab = probe.current?.offsetHeight ?? 0;\n const rem = parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;\n setPx(Math.round(PEEK_REM * rem + tab));\n setTabbar(tab);\n };\n measure();\n window.addEventListener('resize', measure);\n const observer = typeof ResizeObserver === 'undefined' || !probe.current ? undefined : new ResizeObserver(measure);\n if (observer && probe.current) observer.observe(probe.current);\n return () => { window.removeEventListener('resize', measure); observer?.disconnect(); };\n }, [probe]);\n return { peekPoint: `${px}px`, tabbar };\n}\n\n/** Places the layer in the app. `agent` is the one assistant; `improve` is the product manager. Either may be absent. */\nexport function AgentLayerProvider({ agent, improve, locale, children }: { readonly agent?: AgentSpec | undefined; readonly improve?: AgentSpec | undefined; readonly locale?: AppShellLocale | undefined; readonly children: ReactNode }): ReactElement {\n const compact = useIsMobile();\n const expanded = !compact;\n const [snap, setSnapState] = useState<Snap>('closed');\n const [dockFloating, setDockFloating] = useState(false);\n const [shown, setShown] = useState<Which>(agent ? 'agent' : 'improve');\n const probe = useRef<HTMLDivElement>(null);\n const { peekPoint, tabbar } = useMeasuredPeek(probe);\n const triggerUntil = useRef(0);\n const restoreFocus = useRef(false);\n const [side, setSideState] = useState<DockSide>('right');\n // The side is the viewer's, remembered beside the Dock's own placement; read after mount so server and client markup agree.\n useLayoutEffect(() => { try { const saved = globalThis.localStorage?.getItem(SIDE_KEY); if (saved === 'left' || saved === 'right') setSideState(saved); } catch { /* a convenience */ } }, []);\n const setSide = useCallback((next: DockSide) => { setSideState(next); try { globalThis.localStorage?.setItem(SIDE_KEY, next); } catch { /* a convenience */ } }, []);\n const specs = useRef({ agent, improve });\n specs.current = { agent, improve };\n\n const setSnap = useCallback((next: Snap) => setSnapState(next), []);\n const close = useCallback(() => setSnapState('closed'), []);\n // One full-screen layer at a time: opening the agent or product manager closes a view of the app (`useShellLayer`), and a view closes these.\n useEffect(() => registerAgentLayerCloser(close), [close]);\n const open = useCallback((which?: Which, at: 'half' | 'full' = 'half') => {\n const { agent: a, improve: i } = specs.current;\n const target = which ?? (a ? 'agent' : 'improve');\n if (target === 'agent' ? !a : !i) return;\n closeShellLayer();\n setShown(target);\n setSnapState(at);\n }, []);\n const showAgent = useCallback(() => { if (specs.current.agent) setShown('agent'); }, []);\n\n // A spec that goes away takes the layer with it.\n const shownSpec = shown === 'agent' ? agent : improve;\n useEffect(() => { if (!shownSpec) { setSnapState('closed'); if (shown === 'improve' && agent) setShown('agent'); else if (shown === 'agent' && improve) setShown('improve'); } }, [shownSpec, shown, agent, improve]);\n\n // The chats live in one element that is moved into the open drawer or panel; React keeps them mounted (and so their presentation state\n // and uploads) while the layer is closed, on a phone and on a wide screen. Nothing is mounted before the layer is first opened.\n const [host] = useState(() => typeof document === 'undefined' ? null : Object.assign(document.createElement('div'), { className: 'flex min-h-0 flex-1 flex-col [&_[data-boring=pi-chat]>header]:hidden' }));\n const opened = useRef(false);\n if (snap !== 'closed') opened.current = true;\n\n const voice = useVoice(agent, locale, outcome => {\n if (outcome === 'drafted') { setShown('agent'); setSnapState('half'); }\n });\n\n const state: AgentLayerState = snap === 'closed' ? 'closed' : expanded ? 'open' : snap;\n const value = useMemo<Internal>(() => ({\n state, showing: snap === 'closed' ? null : shown, open, close, expanded, agent, improve, snap, setSnap, dockFloating, setDockFloating, showAgent, triggerUntil, voice, peekPoint, tabbar, host, locale, side, setSide, restoreFocus,\n }), [state, snap, shown, open, close, expanded, agent, improve, setSnap, dockFloating, showAgent, triggerUntil, voice, peekPoint, tabbar, host, locale, side, setSide]);\n\n // The shell's z-scale (tabs 20, peek 30, drawer and panel 40, other sheets 50, point bar 60) as custom properties; `display: contents` keeps the box tree unchanged.\n const scale = { '--app-shell-z-tabs': Z.tabs, '--app-shell-z-peek': Z.peek, '--app-shell-z-layer': Z.layer, '--app-shell-z-sheet': Z.sheet, '--app-shell-z-point': Z.point } as CSSProperties;\n return <AgentContextProvider>\n <LayerContext.Provider value={value}>\n <div data-app-shell=\"\" className=\"contents\" style={scale}>\n <div ref={probe} aria-hidden=\"true\" className=\"pointer-events-none invisible fixed top-0 left-0 w-0\" style={{ height: 'var(--app-shell-tabbar, 0px)' }} />\n {children}\n {host && opened.current && createPortal(<Chats showing={shown} />, host)}\n </div>\n </LayerContext.Provider>\n </AgentContextProvider>;\n}\n\n/** The header button that opens the layer: a tap opens half; with `agent.voice`, press and hold records and a slide off cancels. Absent without `agent`. */\nexport function AgentTrigger({ className, children }: { readonly className?: string; readonly children?: ReactNode }) {\n const layer = useInternal();\n const { agent, voice } = layer;\n const text = appShellText(agent?.chatProps?.locale ?? layer.locale);\n const hold = useRef<{ timer: ReturnType<typeof setTimeout> | undefined; held: boolean; id: number } | null>(null);\n if (!agent) return null;\n\n const toggle = () => {\n layer.triggerUntil.current = Date.now() + 500;\n if (layer.state !== 'closed' && layer.showing === 'agent' && layer.expanded) layer.close();\n else layer.open('agent', 'half');\n };\n const release = (event: ReactPointerEvent<HTMLButtonElement>) => {\n const current = hold.current;\n hold.current = null;\n if (!current) return;\n clearTimeout(current.timer);\n if (event.currentTarget.hasPointerCapture?.(current.id)) event.currentTarget.releasePointerCapture(current.id);\n if (current.held) { if (event.type === 'pointerup') voice.finish(); else voice.cancel(); }\n else if (event.type === 'pointerup') toggle();\n };\n const down = (event: ReactPointerEvent<HTMLButtonElement>) => {\n if (event.button !== 0) return;\n const target = event.currentTarget;\n target.setPointerCapture?.(event.pointerId);\n const state = { timer: undefined as ReturnType<typeof setTimeout> | undefined, held: false, id: event.pointerId };\n hold.current = state;\n if (agent.voice) {\n state.timer = setTimeout(() => {\n state.held = true;\n if (layer.snap === 'closed') layer.setSnap('peek');\n layer.showAgent();\n voice.start();\n }, HOLD_MS);\n }\n };\n const move = (event: ReactPointerEvent<HTMLButtonElement>) => {\n const current = hold.current;\n if (!current?.held) return;\n const box = event.currentTarget.getBoundingClientRect();\n const slack = 24;\n if (event.clientX < box.left - slack || event.clientX > box.right + slack || event.clientY < box.top - slack || event.clientY > box.bottom + slack) {\n hold.current = null;\n voice.cancel();\n }\n };\n return <Button variant=\"ghost\" size=\"icon\" data-agent-trigger=\"\" data-testid=\"agent-trigger\" aria-label={text.open} title={text.open} aria-expanded={layer.state !== 'closed'}\n onPointerDown={down} onPointerUp={release} onPointerCancel={release} onPointerMove={move} onContextMenu={event => event.preventDefault()}\n onClick={event => { if (event.detail === 0) toggle(); }}\n className={cn('touch-none', className)}>\n {children ?? <SparklesIcon data-icon=\"inline-start\" aria-hidden=\"true\" />}\n </Button>;\n}\n\nconst clock = (seconds: number) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;\n\n/** Push-to-talk in the composer row (PiChat's `tools` slot): press and hold, release to send or fill; a slide off cancels. */\nfunction TalkButton({ text }: { readonly text: AppShellText }) {\n const { voice } = useInternal();\n const recording = voice.phase === 'recording' || voice.phase === 'starting';\n const busy = voice.phase === 'transcribing';\n const down = (event: ReactPointerEvent<HTMLButtonElement>) => { event.currentTarget.setPointerCapture?.(event.pointerId); voice.start(); };\n const up = (event: ReactPointerEvent<HTMLButtonElement>) => { if (event.currentTarget.hasPointerCapture?.(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); if (event.type === 'pointerup') voice.finish(); else voice.cancel(); };\n const move = (event: ReactPointerEvent<HTMLButtonElement>) => {\n if (!recording) return;\n const box = event.currentTarget.getBoundingClientRect(), slack = 24;\n if (event.clientX < box.left - slack || event.clientX > box.right + slack || event.clientY < box.top - slack || event.clientY > box.bottom + slack) voice.cancel();\n };\n return <Button variant=\"ghost\" size=\"icon\" data-testid=\"agent-talk\" data-state={voice.phase} disabled={busy} aria-label={text.holdToTalk} title={text.holdToTalk}\n onPointerDown={down} onPointerUp={up} onPointerCancel={up} onPointerMove={move} onContextMenu={event => event.preventDefault()}\n className=\"touch-none\">\n {busy ? <Loader2Icon data-icon=\"inline-start\" className=\"animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" /> : <MicIcon data-icon=\"inline-start\" aria-hidden=\"true\" />}\n </Button>;\n}\n\n/** What went wrong with the microphone, in the flow under the title row (never over the messages). */\nfunction VoiceProblem() {\n const { voice } = useInternal();\n return voice.problem ? <p role=\"alert\" data-testid=\"agent-voice-problem\" className=\"m-0 shrink-0 px-3 pb-1 text-xs leading-4 text-destructive\">{voice.problem}</p> : null;\n}\n\n/** One agent's PiChat. It stays mounted while hidden, so its scroll, focus and drafts survive a swap with the other spec. */\nfunction SpecChat({ spec, visible, role }: { readonly spec: AgentSpec; readonly visible: boolean; readonly role: Which }) {\n const layer = useInternal();\n const locale = spec.chatProps?.locale ?? layer.locale;\n // One annotate toggle: pins on desktop, point mode (which hides the layer while the person taps the app) on touch and compact screens.\n const feedback = useComposerFeedback(spec.feedback);\n const pointing = usePointing(spec.feedback);\n // The pin's mic uses the shell's transcription: this agent's own, else the coach's.\n const transcribe = (spec.voice ?? layer.agent?.voice)?.transcribe;\n const fr = locale === 'fr';\n return <div data-spec={role} hidden={!visible} className={cn('min-h-0 min-w-0 flex-1', visible ? 'flex flex-col' : 'hidden')}>\n <PiChat {...spec.chatProps} {...(locale ? { locale } : {})} controller={spec.controller} keyboardInset={false} placement={layer.expanded && !layer.dockFloating ? 'docked' : 'floating'} {...(feedback ? { feedback } : {})}\n {...(role === 'agent' && spec.voice ? { tools: <>{spec.chatProps?.tools}<TalkButton text={appShellText(locale)} /></> } : {})} />\n {/* The note editor of ordinary feedback lives inside the layer, in the modal's focus tree; while pointing the layer steps aside and AgentLayer renders it. */}\n {/* In the flow, inside the visible content box: the popup is transformed (a fixed element would be placed against its off-screen bottom). */}\n {spec.feedback && visible && !pointing && <div className=\"shrink-0 px-2 pb-2 empty:hidden\">\n <NoteBubble session={spec.feedback} {...(transcribe ? { transcribe } : {})} {...(fr ? { labels: feedbackLabelsFr } : {})} /></div>}\n </div>;\n}\n\n/** Where the chats show: the persistent host element is moved in once, when the drawer or panel mounts. */\nfunction ChatSlot() {\n const { host } = useInternal();\n const place = useCallback((slot: HTMLDivElement | null) => { if (slot && host) slot.appendChild(host); }, [host]);\n // Coarse pointers: the chat's own transcript buttons (copy, show earlier) get the layer's 44px rule from here, without touching pi-chat.\n return <div ref={place} className=\"flex min-h-0 flex-1 flex-col [&_[data-testid=transcript]_button]:pointer-coarse:min-h-11 [&_[data-testid=transcript]_button]:pointer-coarse:min-w-11\" />;\n}\n\n/** Both specs, each mounted once it has been shown. */\nfunction Chats({ showing }: { readonly showing: Which }) {\n const { agent, improve } = useInternal();\n const seen = useRef(new Set<Which>());\n seen.current.add(showing);\n return <>\n {agent && seen.current.has('agent') && <SpecChat spec={agent} visible={showing === 'agent'} role=\"agent\" />}\n {improve && seen.current.has('improve') && <SpecChat spec={improve} visible={showing === 'improve'} role=\"improve\" />}\n </>;\n}\n\n/** Title row: « ← » when the improve view has an agent to go back to, the title, then Expand or Collapse (compact only), the dock controls (expanded only) and Close. */\nfunction Header({ text, title, compactSnap, closeRef, controls, className, ...rest }: { readonly text: AppShellText; readonly title: string; readonly compactSnap?: Snap; readonly closeRef?: Ref<HTMLButtonElement>; readonly controls?: ReactNode } & Omit<HTMLAttributes<HTMLDivElement>, 'title'>) {\n const layer = useInternal();\n const back = layer.showing === 'improve' && layer.agent;\n const actions = (layer.showing === 'improve' ? layer.improve : layer.agent)?.headerActions ?? [];\n return <div data-testid=\"agent-layer-header\" {...rest} className={cn('flex shrink-0 items-center gap-1 px-2 pb-1', className)}>\n {back && <Button variant=\"ghost\" size=\"icon\" data-testid=\"agent-layer-back\" aria-label={text.back} title={text.back} onClick={layer.showAgent}><ArrowLeftIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}\n <h2 data-testid=\"agent-layer-title\" className=\"m-0 min-w-0 flex-1 truncate px-1 text-sm font-semibold\">{title}</h2>\n {actions.length > 0 && <HeaderActions actions={actions} compact={compactSnap !== undefined} text={text} prefix=\"agent-layer\" run={id => actions.find(action => action.id === id)?.onSelect()} />}\n {compactSnap === 'half' && <Button variant=\"ghost\" size=\"icon\" data-testid=\"agent-layer-expand\" aria-label={text.expand} title={text.expand} onClick={() => layer.setSnap('full')}><ChevronUpIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}\n {compactSnap === 'full' && <Button variant=\"ghost\" size=\"icon\" data-testid=\"agent-layer-collapse\" aria-label={text.collapse} title={text.collapse} onClick={() => layer.setSnap('half')}><ChevronDownIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}\n {controls}\n <Button variant=\"ghost\" size=\"icon\" ref={closeRef} data-testid=\"agent-layer-close\" aria-label={text.close} title={text.close} onClick={layer.close}><XIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n </div>;\n}\n\nfunction useTitle(): { text: AppShellText; title: string } {\n const layer = useInternal();\n const spec = layer.showing === 'improve' ? layer.improve : layer.agent;\n const text = appShellText(spec?.chatProps?.locale ?? layer.locale);\n const title = layer.showing === 'improve' ? text.improve : (spec?.chatProps?.labels?.title ?? text.assistant);\n return { text, title };\n}\n\nconst toSnap = (point: number | string | null, peekPoint: string): Snap | null =>\n point === peekPoint ? 'peek' : point === HALF ? 'half' : point === FULL ? 'full' : null;\n\nfunction CompactSheet({ pointing }: { readonly pointing: boolean }) {\n const layer = useInternal();\n const { snap, agent, voice } = layer;\n const hasPeek = Boolean(agent);\n const { text, title } = useTitle();\n const vv = useVisualViewport();\n const closeRef = useRef<HTMLButtonElement>(null);\n const vetoed = useRef(false);\n // Set while the layer closes; cleared when it opens again (a close is final until the trigger or a choice opens the layer).\n const closing = useRef(false);\n useEffect(() => { if (snap !== 'closed') closing.current = false; }, [snap]);\n const open = snap !== 'closed' && !pointing;\n const peek = snap === 'peek';\n const points = useMemo(() => hasPeek ? [layer.peekPoint, HALF, FULL] : [HALF, FULL], [hasPeek, layer.peekPoint]);\n const value = peek ? layer.peekPoint : snap === 'full' ? FULL : HALF;\n const recording = voice.phase !== 'idle';\n\n useBackLayer(snap === 'half' || snap === 'full', layer.close, 'agent');\n\n // The popup is taller than what shows and slides down by `--drawer-snap-point-offset` (a registered, non-inheriting property, so only the\n // popup itself can read it): padding the popup by that offset makes its content box exactly the visible part. At peek the tab bar below is left out too.\n // The popup is portalled to the body, outside the shell root: it is given the measured tab bar height and the z-values explicitly.\n const style = { '--app-shell-vv-height': vv ? `${vv.height}px` : '100dvh', '--app-shell-tabbar': `${layer.tabbar}px`, '--app-shell-z-layer': Z.layer,\n paddingBottom: peek ? 'calc(var(--drawer-snap-point-offset, 0px) + var(--app-shell-tabbar, 0px))' : 'var(--drawer-snap-point-offset, 0px)' } as CSSProperties;\n // Entering the modal half or full from the non-modal peek does not rerun Base UI's initial focus: if focus is still on the page, take it to Close.\n const wasPeek = useRef(false);\n useEffect(() => {\n const entering = wasPeek.current && !peek && open;\n wasPeek.current = peek;\n if (!entering) return;\n // The element that held focus when the sheet left peek (a page control now behind the modal). Base UI re-applies its modal guards as the\n // sheet moves, so retake focus once they have settled and again after the slide, but only while focus is still stranded there (or lost to the body).\n const stranded = document.activeElement;\n const take = () => {\n const popup = closeRef.current?.closest('[data-slot=drawer-popup]');\n const active = document.activeElement;\n // Still stranded, or dropped to the body by the modal guards: retake. Focus that went anywhere else is the person's and is left alone.\n if (popup && (active === stranded || active === document.body || active === null) && !popup.contains(active)) closeRef.current?.focus({ preventScroll: true });\n };\n const early = setTimeout(take, 60), late = setTimeout(take, 520);\n return () => { clearTimeout(early); clearTimeout(late); };\n }, [peek, open]);\n return <Drawer open={open} modal={!peek} showSwipeHandle swipeDirection=\"down\" snapPoints={points} snapPoint={value}\n onOpenChange={(next, details) => {\n if (next) return;\n const outcome = nextSnapOnClose(details.reason, hasPeek);\n if (outcome === 'close') { closing.current = true; layer.close(); return; }\n details.cancel();\n vetoed.current = true;\n setTimeout(() => { vetoed.current = false; }, 120);\n // Focus leaving the non-modal peek changes nothing, and neither does the click that finished a press on the AgentTrigger (outside the\n // drawer, so it counts as an outside press): the trigger already chose the snap.\n if (details.reason === 'focus-out' || Date.now() < layer.triggerUntil.current) return;\n layer.setSnap(outcome);\n }}\n onSnapPointChange={point => {\n // Vetoing a swipe-close makes the drawer snap back to where it was: that echo must not undo the snap we chose.\n // Base UI also reports the first snap point (peek) as the drawer closes: that echo must not reopen the layer.\n if (vetoed.current || closing.current) return;\n const next = toSnap(point, layer.peekPoint);\n if (next && (next !== 'peek' || hasPeek)) layer.setSnap(next);\n }}>\n <DrawerContent data-testid=\"agent-layer\" aria-label={title} data-state={snap} data-peek={peek} initialFocus={() => closeRef.current ?? false} style={style}\n className={cn('app-shell box-border z-(--app-shell-z-layer) data-[swipe-direction=down]:bottom-(--drawer-keyboard-inset,0px) data-[swipe-axis=y]:[--drawer-content-max-height:calc(var(--app-shell-vv-height,100dvh)-1.5rem)]',\n // The peek is the top PEEK_REM of the popup; the part that overlaps the tab bar is clipped away, so the tabs stay visible and tappable.\n 'data-[peek=true]:not-data-swiping:[clip-path:inset(0_0_calc(100%_-_6rem)_0)]')}>\n <BaseDrawerParts.Drawer.VirtualKeyboardProvider>\n <div data-testid=\"agent-layer-sheet\" onFocusCapture={event => { if ((event.target as HTMLElement).matches('[data-testid=composer-input]')) layer.setSnap('full'); }}\n className={cn('relative flex min-h-0 flex-1 flex-col overflow-hidden overscroll-contain',\n // The layer's own header carries the title and Close, so the chat's is hidden. At peek: one line of the last reply above the\n // composer, no empty-state overlay, room for Close.\n '[&_[data-boring=pi-chat]>header]:hidden',\n // At peek: ONE compact row (a one-line input, the microphone and Send; the other composer controls wait for half), and the last\n // reply as a single truncated line above it.\n peek && ['[&_[data-boring=pi-chat]>.relative]:overflow-hidden [&_[data-boring=pi-chat]>.relative>.pointer-events-none]:hidden',\n '[&_[data-boring=pi-chat]>footer]:px-2 [&_[data-boring=pi-chat]>footer]:pt-1 [&_[data-boring=pi-chat]>footer]:pb-2',\n '[&_[data-testid=transcript]]:gap-0 [&_[data-testid=transcript]]:p-0 [&_[data-testid=transcript]]:px-3 [&_[data-testid=transcript]>*]:max-h-5 [&_[data-testid=transcript]>*]:truncate [&_[data-testid=transcript]_button]:hidden',\n '[&_[data-testid=composer]_[data-slot=input-group]]:flex-row! [&_[data-testid=composer]_[data-slot=input-group]]:items-center',\n '[&_[data-testid=composer-input]]:min-h-11 [&_[data-testid=composer-input]]:max-h-11 [&_[data-testid=composer-input]]:flex-1 [&_[data-testid=composer-input]]:px-4 [&_[data-testid=composer-input]]:py-2.5',\n '[&_[data-testid=composer-controls]]:w-auto [&_[data-testid=composer-controls]]:shrink-0 [&_[data-testid=composer-controls]]:py-0 [&_[data-testid=composer-controls]>span.flex-1]:hidden',\n '[&_[data-testid=composer-plus]]:hidden [&_[data-testid=composer-annotate]]:hidden'])}>\n {!peek && <Header text={text} title={title} compactSnap={snap} closeRef={closeRef} />}\n {!peek && <VoiceProblem />}\n {peek && recording && <div role=\"status\" data-testid=\"agent-listening\" data-phase={voice.phase} className=\"absolute inset-0 z-20 flex items-center justify-center gap-2 bg-popover text-sm font-medium\">\n <MicIcon className=\"size-4 text-destructive\" aria-hidden=\"true\" />{voice.phase === 'transcribing' ? <Loader2Icon className=\"size-4 animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" /> : `${text.listening} ${clock(voice.seconds)}`}\n </div>}\n {/* The transcript scrolls and never drags the sheet: only the handle and the title row swipe. */}\n <div data-base-ui-swipe-ignore=\"\" className=\"flex min-h-0 flex-1 flex-col\"><ChatSlot /></div>\n </div>\n </BaseDrawerParts.Drawer.VirtualKeyboardProvider>\n </DrawerContent>\n </Drawer>;\n}\n\n/** The panel inside the dock: the same element docked or floating, so a placement change keeps focus and the chats where they are. */\nfunction DockPanel({ api, side }: { readonly api: DockApi; readonly side: DockSide }) {\n const layer = useInternal();\n const { text, title } = useTitle();\n const open = layer.snap !== 'closed';\n const floating = api.floating;\n // The chats report this as their placement: the phone drawer and the floating panel are `floating`, the dock is `docked`.\n const { setDockFloating } = layer;\n useLayoutEffect(() => { setDockFloating(floating); return () => setDockFloating(false); }, [floating, setDockFloating]);\n const box = useRef<HTMLDivElement>(null);\n const drag = useRef<{ dx: number; dy: number } | null>(null);\n const [pos, setPos] = useState<{ left: number; top: number } | null>(null);\n useEffect(() => {\n if (!open) return;\n const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape' && !event.defaultPrevented) layer.close(); };\n document.addEventListener('keydown', onKey);\n return () => document.removeEventListener('keydown', onKey);\n }, [open, layer]);\n // A dock control (or the divider's Alt+Arrow) moves or removes the element that had focus: it goes to the panel's first dock control instead of the page.\n useLayoutEffect(() => {\n const lost = !document.activeElement || document.activeElement === document.body;\n const wanted = layer.restoreFocus.current || (open && lost && api.placement !== 'closed');\n layer.restoreFocus.current = false;\n if (wanted) box.current?.querySelector<HTMLElement>('[data-dock-control]')?.focus({ preventScroll: true });\n }, [api.placement, side, layer.restoreFocus]);\n // A dragged window stays reachable: its remembered position is clamped to the viewport on open, on placement change and on every resize.\n const [viewport, setViewport] = useState(0);\n useEffect(() => { const resize = () => setViewport(count => count + 1); window.addEventListener('resize', resize); return () => window.removeEventListener('resize', resize); }, []);\n useLayoutEffect(() => {\n const rect = box.current?.getBoundingClientRect();\n if (!pos || !floating || !open || !rect || !rect.width) return;\n const left = Math.min(Math.max(pos.left, 0), Math.max(0, innerWidth - rect.width)), top = Math.min(Math.max(pos.top, 0), Math.max(0, innerHeight - rect.height));\n if (left !== pos.left || top !== pos.top) setPos({ left, top });\n }, [pos, floating, open, viewport]);\n const act = (run: () => void) => () => { layer.restoreFocus.current = true; run(); };\n const control = (id: string, label: string, Icon: ComponentType<{ className?: string }>, run: () => void) =>\n <Button variant=\"ghost\" size=\"icon\" key={id} data-testid={`agent-layer-${id}`} data-dock-control=\"\" aria-label={label} title={label} onClick={act(run)}><Icon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>;\n const controls = <>\n {!floating && control('float', text.float, PictureInPicture2Icon, () => api.float())}\n {(floating || side === 'right') && control('dock-left', text.dockLeft, PanelLeftIcon, () => { layer.setSide('left'); api.dock(); })}\n {(floating || side === 'left') && control('dock-right', text.dockRight, PanelRightIcon, () => { layer.setSide('right'); api.dock(); })}\n </>;\n const down = (event: ReactPointerEvent<HTMLDivElement>) => {\n const rect = box.current?.getBoundingClientRect();\n if (!floating || !rect || event.button !== 0 || (event.target as HTMLElement).closest('button, a[href]')) return;\n drag.current = { dx: event.clientX - rect.left, dy: event.clientY - rect.top };\n event.currentTarget.setPointerCapture?.(event.pointerId);\n };\n const move = (event: ReactPointerEvent<HTMLDivElement>) => {\n const grab = drag.current, rect = box.current?.getBoundingClientRect();\n if (!grab || !rect) return;\n setPos({ left: Math.min(Math.max(event.clientX - grab.dx, 0), Math.max(0, innerWidth - rect.width)), top: Math.min(Math.max(event.clientY - grab.dy, 0), Math.max(0, innerHeight - rect.height)) });\n };\n const end = () => { drag.current = null; };\n // Floating, the host's Card is drawn behind the layer (a sibling layer, so docking or floating never remounts the chat).\n return <div ref={box} data-testid=\"agent-layer\" data-state={open ? 'open' : 'closed'} data-placement={api.placement} data-side={side} role={floating ? 'dialog' : 'complementary'} aria-label={title}\n style={floating ? pos ?? { right: 16, bottom: 16 } : undefined}\n className={cn('app-shell relative flex min-h-0 flex-col',\n floating ? 'fixed isolate z-(--app-shell-z-layer) h-[min(36rem,calc(100dvh-2rem))] w-[min(24rem,calc(100vw-2rem))]'\n : 'h-full min-w-0 flex-1 bg-background text-foreground')}>\n {floating && <Card aria-hidden=\"true\" data-boring=\"chrome\" className=\"pointer-events-none absolute inset-0 -z-10\" />}\n {!floating && <Separator orientation=\"vertical\" className={cn('absolute inset-y-0', side === 'right' ? 'left-0' : 'right-0')} />}\n <Header text={text} title={title} controls={controls} className={cn('pt-2', floating && 'cursor-move touch-none select-none')} onPointerDown={down} onPointerMove={move} onPointerUp={end} onPointerCancel={end} />\n <div className=\"flex min-h-0 flex-1 flex-col overflow-hidden\"><VoiceProblem /><ChatSlot /></div>\n </div>;\n}\n\nfunction AgentDock({ side }: { readonly side: DockSide }) {\n const layer = useInternal();\n const { title } = useTitle();\n return <Dock id=\"agent\" side={side} floatable defaultWidth={384} minWidth={320} dragBelow={260} open={layer.snap !== 'closed'} onOpenChange={next => { if (!next) layer.close(); }} labels={{ region: title }}>\n {api => <DockPanel api={api} side={side} />}\n </Dock>;\n}\n\n/**\n * Wraps the app's content (placed once by the shell): on a wide screen the agent dock sits on its left or right and the content reflows,\n * or it floats over the content; on a phone this is only the content (the layer is the bottom drawer). Host concern: Pi has no layout.\n */\nexport function AgentDockLayout({ children }: { readonly children: ReactNode }): ReactElement {\n const layer = useInternal();\n const dock = layer.expanded && (layer.agent || layer.improve) ? <AgentDock side={layer.side} /> : null;\n return <DockLayout storageKey={DOCK_KEY} persist=\"local\">\n {layer.side === 'left' && dock}\n <DockMain>{children}</DockMain>\n {layer.side === 'right' && dock}\n </DockLayout>;\n}\n\n/** The layer itself: the drawer on a phone (the wide dock is `AgentDockLayout`). Placed once by the shell, for point mode on both. */\nexport function AgentLayer(): ReactElement | null {\n const layer = useInternal();\n const pointingAgent = usePointing(layer.agent?.feedback), pointingImprove = usePointing(layer.improve?.feedback);\n const session = pointingAgent ? layer.agent?.feedback : pointingImprove ? layer.improve?.feedback : undefined;\n // Back ends pointing first (the `point` priority); the layer keeps its own history entry underneath.\n useBackLayer(session !== undefined, () => session?.discard(), 'point');\n if (!layer.agent && !layer.improve) return null;\n const pointed = pointingAgent ? layer.agent : layer.improve;\n const transcribe = (pointed?.voice ?? layer.agent?.voice)?.transcribe;\n const locale = pointed?.chatProps?.locale ?? layer.locale;\n // Point mode: the compact sheet steps aside (the wide dock does not cover the app); the bar sits above the tab bar, outside the layer.\n return <>\n {!layer.expanded && <CompactSheet pointing={session !== undefined} />}\n {session && <>\n <PointBar session={session} bottomOffset={`${layer.tabbar}px`} className=\"z-[60]\" {...(locale === 'fr' ? { labels: feedbackLabelsFr } : {})} />\n <NoteBubble session={session} {...(transcribe ? { transcribe } : {})} {...(locale === 'fr' ? { labels: feedbackLabelsFr } : {})} />\n </>}\n </>;\n}\n",
|
|
29
34
|
"type": "registry:component",
|
|
30
35
|
"target": "components/app-shell/agent-layer.tsx"
|
|
31
36
|
},
|
|
@@ -61,45 +66,51 @@
|
|
|
61
66
|
},
|
|
62
67
|
{
|
|
63
68
|
"path": "registry/app-shell/app-shell.tsx",
|
|
64
|
-
"content": "'use client';\n\n// The app shell. Layout A (`screen`): one screen at a time. Compact: bottom tabs (at most four; more give three plus « Plus »). Expanded:\n// the shadcn sidebar (icon rail plus NavUser). Layout B (`workspace`): the same, with a screen made of a `ListDetail`; the sidebar starts\n// as the icon rail because the list pane is the wide navigation. Layout C (`chat`): the one nav item renders the app's `AgentWorkspace`,\n// untouched, below the same sidebar, account menu and header; there is no shell agent (the page is the chat). The shell imports nothing from pi-app: a layout C app installs the `pi-app` item itself. One header per screen\n// (`useScreenHeader`). The AgentLayer is mounted once, here.\n// Host concern: Pi has no layout; the screen on show travels as the agent's context (useAgentContext -> createPromptContext).\nimport { useState } from 'react';\nimport type { ReactNode } from 'react';\nimport { SidebarProvider } from '@/components/ui/sidebar';\nimport { AccountAvatar,
|
|
69
|
+
"content": "'use client';\n\n// The app shell. Layout A (`screen`): one screen at a time. Compact: bottom tabs (at most four; more give three plus « Plus »). Expanded:\n// the shadcn sidebar (icon rail plus NavUser). Layout B (`workspace`): the same, with a screen made of a `ListDetail`; the sidebar starts\n// as the icon rail because the list pane is the wide navigation. Layout C (`chat`): the one nav item renders the app's `AgentWorkspace`,\n// untouched, below the same sidebar, account menu and header; there is no shell agent (the page is the chat). The shell imports nothing from pi-app: a layout C app installs the `pi-app` item itself. One header per screen\n// (`useScreenHeader`). The AgentLayer is mounted once, here.\n// Host concern: Pi has no layout; the screen on show travels as the agent's context (useAgentContext -> createPromptContext).\nimport { useState } from 'react';\nimport type { ReactNode } from 'react';\nimport { SidebarProvider } from '@/components/ui/sidebar';\nimport { Button } from '@/components/ui/button';\nimport { AccountAvatar, AccountChoices } from './account';\nimport type { AccountSpec } from './account';\nimport { AgentDockLayout, AgentLayer, AgentLayerProvider } from './agent-layer';\nimport type { AgentSpec } from './agent-layer';\nimport { ScreenActiveContext, useAgentContext } from './agent-context';\nimport { useIsCompact } from './compact';\nimport { HeaderProvider, ScreenHeader } from './header';\nimport { AppSidebar, TabBar } from './nav';\nimport type { NavItem } from './nav';\nimport { AppSheet } from './app-sheet';\nimport { appShellText } from './text';\nimport type { AppShellLocale, AppShellText } from './text';\n\nexport interface AppShellProps {\n /** A `screen` (tabs), B `workspace` (list and detail), C `chat` (the app's `AgentWorkspace`; no `agent`). */\n readonly layout: 'screen' | 'workspace' | 'chat';\n readonly title: string;\n readonly nav: readonly NavItem[];\n readonly agent?: AgentSpec;\n /** The product manager: adds « Améliorer l’app » to the account menu. */\n readonly improve?: AgentSpec;\n readonly account?: AccountSpec;\n /** The language of the shell's own words and the layer's (« Se déconnecter », « Plus », « Ouvrir l’assistant »…). The agent's `chatProps.locale` wins when it sets one; else this; else English. */\n readonly locale?: AppShellLocale;\n /** The app's router owns the URL; the shell only reports the choice. */\n readonly route: { readonly id: string; readonly onChange: (id: string) => void };\n}\n\n/** Registers what is on show for the agent. A screen's own `useAgentContext` is mounted later and wins. */\nfunction ShellContext({ name }: { readonly name: string }): null {\n useAgentContext({ name, params: {} });\n return null;\n}\n\nfunction ScreenBody({ item }: { readonly item: NavItem }): ReactNode { return item.render(); }\n\n/** Every screen stays mounted; the ones not on show are `hidden` and do not register a header or a context. */\nfunction Screens({ items, activeId, scrolls }: { readonly items: readonly NavItem[]; readonly activeId: string; readonly scrolls: boolean }) {\n return <div className=\"relative min-h-0 flex-1\">\n {items.map(item => <ScreenActiveContext.Provider key={item.id} value={item.id === activeId}>\n <div hidden={item.id !== activeId} data-testid={`screen-${item.id}`} className={scrolls ? 'h-full overflow-y-auto overscroll-contain' : 'h-full overflow-hidden'}><ScreenBody item={item} /></div>\n </ScreenActiveContext.Provider>)}\n </div>;\n}\n\nfunction Shell({ layout, title, nav, agent, improve, account, route, text }: { readonly layout: AppShellProps['layout']; readonly title: string; readonly nav: readonly NavItem[]; readonly agent: AgentSpec | undefined; readonly improve: boolean; readonly account: AccountSpec | undefined; readonly route: AppShellProps['route']; readonly text: AppShellText }) {\n const compact = useIsCompact();\n const [accountOpen, setAccountOpen] = useState(false);\n const active = nav.find(item => item.id === route.id) ?? nav[0];\n if (!active) return null;\n const hasAccount = Boolean(account) || improve;\n const avatar = hasAccount ? <>\n <Button variant=\"ghost\" size=\"icon\" data-testid=\"account-button\" aria-label={account?.name ?? text.account} title={account?.name ?? text.account} onClick={() => setAccountOpen(true)}><AccountAvatar account={account} /></Button>\n <AppSheet open={accountOpen} onOpenChange={setAccountOpen} title={text.account}>\n <AccountChoices account={account} improve={improve} text={text} done={() => setAccountOpen(false)} />\n </AppSheet>\n </> : null;\n // The structure is the same compact or expanded, so a resize never remounts a screen.\n return <SidebarProvider data-testid=\"app-shell\" defaultOpen={layout === 'screen'} className=\"app-shell h-dvh min-h-0 overflow-hidden\">\n {!compact && <AppSidebar title={title} items={nav} activeId={active.id} onChange={route.onChange} agent={agent} account={account} improve={improve} text={text} />}\n <AgentDockLayout>\n <div data-slot=\"sidebar-inset\" className=\"relative flex min-h-0 min-w-0 w-full flex-1 flex-col overflow-hidden bg-background\">\n <ShellContext name={active.label} />\n <ScreenHeader fallbackTitle={active.label} compact={compact} avatar={avatar} text={text} />\n <Screens items={nav} activeId={active.id} scrolls={layout === 'screen'} />\n {compact && <TabBar items={nav} activeId={active.id} onChange={route.onChange} text={text} />}\n </div>\n </AgentDockLayout>\n <AgentLayer />\n </SidebarProvider>;\n}\n\nexport function AppShell(props: AppShellProps) {\n const { layout, agent, improve, title, nav, account, route } = props;\n if (layout === 'chat' && agent) throw new Error('AppShell layout \"chat\" takes no `agent`: the page is the chat (use `improve` for the product manager)');\n const text = appShellText((agent ?? improve)?.chatProps?.locale ?? props.locale);\n return <AgentLayerProvider agent={agent} improve={improve} locale={props.locale}>\n <HeaderProvider><Shell layout={layout} title={title} nav={nav} agent={agent} account={account} route={route} improve={Boolean(improve)} text={text} /></HeaderProvider>\n </AgentLayerProvider>;\n}\n",
|
|
65
70
|
"type": "registry:component",
|
|
66
71
|
"target": "components/app-shell/app-shell.tsx"
|
|
67
72
|
},
|
|
68
73
|
{
|
|
69
74
|
"path": "registry/app-shell/list-detail.tsx",
|
|
70
|
-
"content": "'use client';\n\n// The one list/detail primitive of layout B. Expanded: the list (20rem, its own scroll) and the detail side by side. Compact: one pane at a\n// time; opening a detail is a stack step (one history entry, Back returns to the list) and the list stays mounted, hidden, so its scroll is\n// kept. Host concern: Pi has no layout. A deep link that mounts with a detail needs nothing more: the Back manager's entry sits above the\n// one the page was opened on, and the app's `onBack` (called by Back, and by « ← » which is Back) clears the selection and replaces the URL.\nimport { useContext } from 'react';\nimport type { ReactNode } from 'react';\nimport { cn } from '../utils/utils';\nimport { ScreenActiveContext } from './agent-context';\nimport { useBackLayer } from './back';\nimport { useIsCompact } from './compact';\nimport { useScreenHeader } from './header';\n\nexport interface ListDetailProps {\n /** The list pane (the app's own list; a card list when compact is the app's choice through `useIsCompact`). */\n readonly list: ReactNode;\n /** `null` = nothing selected. */\n readonly detail: ReactNode | null;\n /** Clears the selection and replaces the URL: called by compact Back and by the header's « ← » (which goes through the browser's Back). */\n readonly onBack: () => void;\n /** The detail's header title when compact (default: the screen's own). */\n readonly title?: string;\n}\n\n/** Which panes show: both when expanded; when compact the detail if one is selected, else the list. */\nexport function listDetailView(compact: boolean, detail: ReactNode | null): 'list' | 'detail' | 'both' {\n return !compact ? 'both' : detail === null ? 'list' : 'detail';\n}\n\nexport function ListDetail({ list, detail, onBack, title }: ListDetailProps) {\n const compact = useIsCompact();\n const active = useContext(ScreenActiveContext);\n const view = listDetailView(compact, detail);\n const stacked = view === 'detail';\n useBackLayer(active && stacked, onBack, 'stack');\n // « ← » is the browser's Back, so there is one path: the popstate calls `onBack`, and the URL the entry below holds is the one the app then replaces.\n useScreenHeader(stacked ? { back: () => history.back(), ...(title ? { title } : {}) } : {}, { overlay: true });\n return <div data-testid=\"list-detail\" data-view={view} className=\"flex h-full min-h-0\">\n <div hidden={view === 'detail'} data-testid=\"list-pane\" className={cn('min-h-0 overflow-y-auto overscroll-contain', compact ? 'w-full' : 'w-80 shrink-0
|
|
75
|
+
"content": "'use client';\n\n// The one list/detail primitive of layout B. Expanded: the list (20rem, its own scroll) and the detail side by side. Compact: one pane at a\n// time; opening a detail is a stack step (one history entry, Back returns to the list) and the list stays mounted, hidden, so its scroll is\n// kept. Host concern: Pi has no layout. A deep link that mounts with a detail needs nothing more: the Back manager's entry sits above the\n// one the page was opened on, and the app's `onBack` (called by Back, and by « ← » which is Back) clears the selection and replaces the URL.\nimport { useContext } from 'react';\nimport type { ReactNode } from 'react';\nimport { Separator } from '@/components/ui/separator';\nimport { cn } from '../utils/utils';\nimport { ScreenActiveContext } from './agent-context';\nimport { useBackLayer } from './back';\nimport { useIsCompact } from './compact';\nimport { useScreenHeader } from './header';\n\nexport interface ListDetailProps {\n /** The list pane (the app's own list; a card list when compact is the app's choice through `useIsCompact`). */\n readonly list: ReactNode;\n /** `null` = nothing selected. */\n readonly detail: ReactNode | null;\n /** Clears the selection and replaces the URL: called by compact Back and by the header's « ← » (which goes through the browser's Back). */\n readonly onBack: () => void;\n /** The detail's header title when compact (default: the screen's own). */\n readonly title?: string;\n}\n\n/** Which panes show: both when expanded; when compact the detail if one is selected, else the list. */\nexport function listDetailView(compact: boolean, detail: ReactNode | null): 'list' | 'detail' | 'both' {\n return !compact ? 'both' : detail === null ? 'list' : 'detail';\n}\n\nexport function ListDetail({ list, detail, onBack, title }: ListDetailProps) {\n const compact = useIsCompact();\n const active = useContext(ScreenActiveContext);\n const view = listDetailView(compact, detail);\n const stacked = view === 'detail';\n useBackLayer(active && stacked, onBack, 'stack');\n // « ← » is the browser's Back, so there is one path: the popstate calls `onBack`, and the URL the entry below holds is the one the app then replaces.\n useScreenHeader(stacked ? { back: () => history.back(), ...(title ? { title } : {}) } : {}, { overlay: true });\n return <div data-testid=\"list-detail\" data-view={view} className=\"flex h-full min-h-0\">\n <div hidden={view === 'detail'} data-testid=\"list-pane\" className={cn('min-h-0 overflow-y-auto overscroll-contain', compact ? 'w-full' : 'w-80 shrink-0')}>{list}</div>\n {!compact && view !== 'detail' && <Separator orientation=\"vertical\" />}\n <div hidden={view === 'list'} data-testid=\"detail-pane\" className={cn('min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain', detail === null && 'bg-muted/30')}>{detail}</div>\n </div>;\n}\n",
|
|
71
76
|
"type": "registry:component",
|
|
72
77
|
"target": "components/app-shell/list-detail.tsx"
|
|
73
78
|
},
|
|
74
79
|
{
|
|
75
80
|
"path": "registry/app-shell/header.tsx",
|
|
76
|
-
"content": "'use client';\n\n// One header per screen. A screen calls `useScreenHeader` and the shell renders it; the most recently mounted caller wins as a whole\n// (a `ListDetail` inside a screen overlays « ← » and a title and keeps the screen's actions) and unmounting restores the previous one. A\n// screen the shell has hidden does not count (ScreenActiveContext). Host concern: Pi has no layout.\nimport { createContext, createElement, useContext, useLayoutEffect, useRef, useSyncExternalStore } from 'react';\nimport type { ComponentType, ReactNode } from 'react';\nimport { ArrowLeftIcon } from 'lucide-react';\nimport { SidebarTrigger } from '@/components/ui/sidebar';\nimport { ScreenActiveContext } from './agent-context';\nimport { HeaderActions
|
|
81
|
+
"content": "'use client';\n\n// One header per screen. A screen calls `useScreenHeader` and the shell renders it; the most recently mounted caller wins as a whole\n// (a `ListDetail` inside a screen overlays « ← » and a title and keeps the screen's actions) and unmounting restores the previous one. A\n// screen the shell has hidden does not count (ScreenActiveContext). Host concern: Pi has no layout.\nimport { createContext, createElement, useContext, useLayoutEffect, useRef, useSyncExternalStore } from 'react';\nimport type { ComponentType, ReactNode } from 'react';\nimport { ArrowLeftIcon } from 'lucide-react';\nimport { SidebarTrigger } from '@/components/ui/sidebar';\nimport { Button } from '@/components/ui/button';\nimport { Separator } from '@/components/ui/separator';\nimport { ScreenActiveContext } from './agent-context';\nimport { HeaderActions } from './header-actions';\nimport type { ScreenHeaderAction } from './header-actions';\nimport { AgentTrigger } from './agent-layer';\nimport type { AppShellText } from './text';\n\ninterface Icon { className?: string }\nexport interface ScreenHeaderSpec {\n /** Default: the active nav label. */\n readonly title?: string;\n readonly subtitle?: string;\n /** Shows « ← ». */\n readonly back?: () => void;\n /** At most two are shown; the others go in « … ». */\n readonly actions?: readonly ScreenHeaderAction[];\n}\n\nexport type { ScreenHeaderAction } from './header-actions';\n\ninterface Entry { spec: ScreenHeaderSpec; readonly overlay: boolean }\ninterface Store {\n readonly entries: Entry[];\n version: number;\n readonly listeners: Set<() => void>;\n}\n\nconst HeaderContext = createContext<Store | null>(null);\n\n/** A number per icon component, so a change of icon is a change of header. */\nconst icons = new WeakMap<object, number>();\nlet iconCount = 0;\nconst iconId = (icon: ComponentType<Icon>): number => { let id = icons.get(icon); if (id === undefined) { iconCount += 1; id = iconCount; icons.set(icon, id); } return id; };\n\nconst touch = (store: Store) => { store.version += 1; for (const listener of [...store.listeners]) listener(); };\n\n/** Holds the screens' headers. `AppShell` mounts one. */\nexport function HeaderProvider({ children }: { readonly children: ReactNode }) {\n const store = useRef<Store>({ entries: [], version: 0, listeners: new Set() });\n return createElement(HeaderContext.Provider, { value: store.current }, children);\n}\n\n/**\n * Registers the calling screen's header while it is mounted and on show. The latest spec is always read at click time. An `overlay`\n * (the shell's own `ListDetail`) is merged over the screen's header whatever the effect order: it adds « ← » and a title, and keeps the actions.\n */\nexport function useScreenHeader(spec: ScreenHeaderSpec, options?: { readonly overlay?: boolean }): void {\n const store = useContext(HeaderContext);\n const active = useContext(ScreenActiveContext);\n const entry = useRef<Entry>({ spec, overlay: options?.overlay === true });\n entry.current.spec = spec;\n const key = JSON.stringify([spec.title, spec.subtitle, Boolean(spec.back), spec.actions?.map(action => [action.id, action.label, action.showLabel, action.href, action.target, action.rel, iconId(action.icon)])]);\n useLayoutEffect(() => {\n if (!store || !active) return;\n const mine = entry.current;\n store.entries.push(mine);\n touch(store);\n return () => { const at = store.entries.indexOf(mine); if (at >= 0) store.entries.splice(at, 1); touch(store); };\n }, [store, active]);\n useLayoutEffect(() => { if (store && active) touch(store); }, [store, active, key]);\n}\n\n/** The header of the screen on show (the most recently mounted caller), or undefined. Re-renders when screens come and go or change their header. */\nexport function useTopHeader(): { readonly spec: ScreenHeaderSpec } | undefined {\n const store = useContext(HeaderContext);\n useSyncExternalStore(\n listener => { store?.listeners.add(listener); return () => { store?.listeners.delete(listener); }; },\n () => store?.version ?? 0,\n () => 0,\n );\n // A getter, so a click reads the live specs (a callback that changed without a visible change is still the current one).\n return store?.entries.length ? { get spec() { return mergedSpec(store.entries); } } : undefined;\n}\n\n/** The latest ordinary entry is the whole header; explicit overlays (the shell's `ListDetail`) are merged over it field by field. */\nfunction mergedSpec(entries: readonly Entry[]): ScreenHeaderSpec {\n const base = entries.filter(entry => !entry.overlay).at(-1);\n const spec: Record<string, unknown> = { ...base?.spec };\n for (const entry of entries) if (entry.overlay) for (const [field, value] of Object.entries(entry.spec)) if (value !== undefined) spec[field] = value;\n return spec as ScreenHeaderSpec;\n}\n\n\n/**\n * The header of the screen on show: the avatar button (compact) or the sidebar trigger (expanded) or « ← », then the title and subtitle,\n * then up to two actions, « … » and the agent trigger. `avatar` is the compact account button.\n */\nexport function ScreenHeader({ fallbackTitle, compact, avatar, text }: { readonly fallbackTitle: string; readonly compact: boolean; readonly avatar: ReactNode; readonly text: AppShellText }) {\n const top = useTopHeader();\n const spec = top?.spec;\n const actions = spec?.actions ?? [];\n const run = (id: string) => top?.spec.actions?.find(action => action.id === id)?.onSelect();\n const back = spec?.back ? <Button variant=\"ghost\" size=\"icon\" data-testid=\"header-back\" aria-label={text.goBack} title={text.goBack} onClick={() => top?.spec.back?.()}><ArrowLeftIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button> : null;\n return <header data-testid=\"screen-header\" className=\"sticky top-0 z-10 flex min-h-14 shrink-0 items-center gap-1 bg-background px-2 pt-[env(safe-area-inset-top)]\">\n <Separator className=\"absolute inset-x-0 bottom-0\" />\n {compact ? (back ?? avatar) : <><SidebarTrigger />{back}</>}\n <div className=\"min-w-0 flex-1 px-1\">\n <h1 data-testid=\"header-title\" className=\"m-0 truncate text-base leading-tight font-semibold [font-family:var(--font-display,var(--font-sans))]\">{spec?.title ?? fallbackTitle}</h1>\n {spec?.subtitle && <p data-testid=\"header-subtitle\" className=\"m-0 truncate text-xs text-muted-foreground\">{spec.subtitle}</p>}\n </div>\n <HeaderActions actions={actions} compact={compact} text={text} prefix=\"header\" run={run} />\n {compact && back && avatar}\n <AgentTrigger />\n </header>;\n}\n",
|
|
77
82
|
"type": "registry:component",
|
|
78
83
|
"target": "components/app-shell/header.tsx"
|
|
79
84
|
},
|
|
80
85
|
{
|
|
81
86
|
"path": "registry/app-shell/header-actions.tsx",
|
|
82
|
-
"content": "'use client';\n\n// The header actions (`ScreenHeaderAction`) and their renderer, shared by the screen header and the AgentLayer header: up to two icon or label\n// buttons (or links), the rest in « … ». Imports nothing from header.tsx or agent-layer.tsx (the shell's import graph has no cycle).\nimport { useState } from 'react';\nimport type { ComponentType, MouseEvent } from 'react';\nimport { EllipsisIcon } from 'lucide-react';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport {
|
|
87
|
+
"content": "'use client';\n\n// The header actions (`ScreenHeaderAction`) and their renderer, shared by the screen header and the AgentLayer header: up to two icon or label\n// buttons (or links), the rest in « … ». Imports nothing from header.tsx or agent-layer.tsx (the shell's import graph has no cycle).\nimport { useState } from 'react';\nimport type { ComponentType, MouseEvent } from 'react';\nimport { EllipsisIcon } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { afterBack } from './back';\nimport { AppSheet, SHEET_ROW } from './app-sheet';\nimport type { AppShellText } from './text';\n\ninterface Icon { className?: string }\nexport interface ScreenHeaderAction {\n readonly id: string;\n /** The accessible name and the tooltip. */\n readonly label: string;\n readonly icon: ComponentType<Icon>;\n /** `'always'` also shows the label as text next to the icon (default: icon only, at every width). */\n readonly showLabel?: 'always';\n /** The action is a link (an anchor); `onSelect` still runs on click. `target` and `rel` are set only when the host passes them. */\n readonly href?: string;\n readonly target?: string;\n readonly rel?: string;\n readonly onSelect: () => void;\n}\n\n/** One action as a control: an anchor when it has `href`, else a button. `onSelect` is the caller's run (it reads the live action at click time). */\nfunction ActionControl({ action, prefix, onSelect }: { readonly action: ScreenHeaderAction; readonly prefix: string; readonly onSelect: () => void }) {\n const content = <><action.icon data-icon=\"inline-start\" aria-hidden=\"true\" />{action.showLabel === 'always' && action.label}</>;\n return <Button variant=\"ghost\" size={action.showLabel === 'always' ? 'default' : 'icon'}\n {...(action.href !== undefined ? { nativeButton: false, render: <a href={action.href} target={action.target} rel={action.rel} /> } : {})}\n data-testid={`${prefix}-action-${action.id}`} aria-label={action.label} title={action.label} onClick={onSelect}>{content}</Button>;\n}\n\n/** Up to two actions as controls; the rest go in « … » (a sheet when compact, a menu otherwise). `prefix` names the test ids. Shared with the AgentLayer header. */\nexport function HeaderActions({ actions, compact, text, prefix, run }: { readonly actions: readonly ScreenHeaderAction[]; readonly compact: boolean; readonly text: AppShellText; readonly prefix: string; readonly run: (id: string) => void }) {\n const shown = actions.slice(0, 2), extra = actions.slice(2);\n const [sheetOpen, setSheetOpen] = useState(false);\n // A link in the phone sheet: the sheet closes first and a same-tab navigation waits for its history entry (afterBack), so the Back\n // manager never undoes it. A new tab, or a modified click, keeps the browser's own default.\n const sheetLink = (event: MouseEvent<HTMLElement>, action: ScreenHeaderAction) => {\n setSheetOpen(false);\n if ((action.target !== undefined && action.target !== '_self') || event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) { afterBack(() => run(action.id)); return; }\n event.preventDefault();\n const href = action.href ?? '';\n afterBack(() => { run(action.id); window.location.assign(href); });\n };\n return <>\n {shown.map(action => <ActionControl key={action.id} action={action} prefix={prefix} onSelect={() => run(action.id)} />)}\n {extra.length > 0 && (compact\n ? <>\n <Button variant=\"ghost\" size=\"icon\" data-testid={`${prefix}-more`} aria-label={text.actions} title={text.actions} onClick={() => setSheetOpen(true)}><EllipsisIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n <AppSheet open={sheetOpen} onOpenChange={setSheetOpen} title={text.actions}>\n {extra.map(action => action.href === undefined\n ? <Button key={action.id} variant=\"ghost\" size=\"lg\" data-testid={`${prefix}-action-${action.id}`} className={SHEET_ROW} onClick={() => { setSheetOpen(false); afterBack(() => run(action.id)); }}><action.icon data-icon=\"inline-start\" />{action.label}</Button>\n : <Button key={action.id} variant=\"ghost\" size=\"lg\" nativeButton={false} render={<a href={action.href} target={action.target} rel={action.rel} />} data-testid={`${prefix}-action-${action.id}`} className={SHEET_ROW} onClick={event => sheetLink(event, action)}><action.icon data-icon=\"inline-start\" />{action.label}</Button>)}\n </AppSheet>\n </>\n : <DropdownMenu>\n <DropdownMenuTrigger render={<Button variant=\"ghost\" size=\"icon\" />} data-testid={`${prefix}-more`} aria-label={text.actions} title={text.actions}><EllipsisIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"app-shell w-48\">\n {extra.map(action => <DropdownMenuItem key={action.id} data-testid={`${prefix}-action-${action.id}`} className=\"pointer-coarse:min-h-11\" onClick={() => run(action.id)}\n render={action.href === undefined ? undefined : <a href={action.href} target={action.target} rel={action.rel} />}><action.icon className=\"size-4\" />{action.label}</DropdownMenuItem>)}\n </DropdownMenuContent>\n </DropdownMenu>)}\n </>;\n}\n\n",
|
|
83
88
|
"type": "registry:component",
|
|
84
89
|
"target": "components/app-shell/header-actions.tsx"
|
|
85
90
|
},
|
|
86
91
|
{
|
|
87
92
|
"path": "registry/app-shell/nav.tsx",
|
|
88
|
-
"content": "'use client';\n\n// The navigation: a bottom tab bar when compact, the shadcn sidebar (icon rail plus NavUser, the sidebar-07 and sidebar-08 patterns) when\n// expanded. Choosing an item only calls `route.onChange`: the app's router owns the URL, and the shell adds no history entry.\nimport { useEffect, useRef, useState } from 'react';\nimport type { ComponentType, KeyboardEvent, ReactNode } from 'react';\nimport { EllipsisIcon, SparklesIcon } from 'lucide-react';\nimport { Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupContent, SidebarHeader, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarRail, SidebarSeparator } from '@/components/ui/sidebar';\nimport {
|
|
93
|
+
"content": "'use client';\n\n// The navigation: a bottom tab bar when compact, the shadcn sidebar (icon rail plus NavUser, the sidebar-07 and sidebar-08 patterns) when\n// expanded. Choosing an item only calls `route.onChange`: the app's router owns the URL, and the shell adds no history entry.\nimport { useEffect, useRef, useState } from 'react';\nimport type { ComponentType, KeyboardEvent, ReactNode } from 'react';\nimport { EllipsisIcon, SparklesIcon } from 'lucide-react';\nimport { Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupContent, SidebarHeader, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarRail, SidebarSeparator } from '@/components/ui/sidebar';\nimport { Badge } from '@/components/ui/badge';\nimport { Button } from '@/components/ui/button';\nimport { Separator } from '@/components/ui/separator';\nimport { afterBack } from './back';\nimport { NavUser } from './account';\nimport { useAgentLayer } from './agent-layer';\nimport type { AgentSpec } from './agent-layer';\nimport type { AccountSpec } from './account';\nimport { AppSheet, SHEET_ROW } from './app-sheet';\nimport type { AppShellText } from './text';\n\nexport interface NavItem {\n readonly id: string;\n readonly label: string;\n readonly icon: ComponentType<{ className?: string }>;\n readonly badge?: boolean;\n readonly render: () => ReactNode;\n}\n\n/** The most tabs the bar shows. */\nconst MAX_TABS = 4;\n\n/** Up to four items are all tabs; more than four give three tabs and the rest behind « Plus ». */\nexport function splitNav<T>(items: readonly T[]): { readonly tabs: readonly T[]; readonly overflow: readonly T[] } {\n return items.length <= MAX_TABS ? { tabs: items, overflow: [] } : { tabs: items.slice(0, MAX_TABS - 1), overflow: items.slice(MAX_TABS - 1) };\n}\n\n/** The host's Badge marks a screen with news. Its classes only place it. */\nconst Dot = ({ className }: { readonly className?: string }) => <Badge aria-hidden=\"true\" data-testid=\"nav-badge\" className={className} />;\n\n/** Publishes the bar's measured height as `--app-shell-tabbar` on the document root (the drawer is portaled, so the shell root is too high up to reach it). */\nfunction useTabbarHeight(bar: { readonly current: HTMLElement | null }, shown: boolean): void {\n useEffect(() => {\n const root = document.documentElement;\n const node = bar.current;\n if (!shown || !node) { root.style.setProperty('--app-shell-tabbar', '0px'); return; }\n const measure = () => root.style.setProperty('--app-shell-tabbar', `${node.getBoundingClientRect().height}px`);\n measure();\n const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(measure) : undefined;\n observer?.observe(node);\n return () => { observer?.disconnect(); root.style.removeProperty('--app-shell-tabbar'); };\n }, [bar, shown]);\n}\n\n/** Layout for a tab on the host's Button: icon over label, filling its share of the bar. */\nconst TAB = 'relative h-auto min-w-0 flex-1 flex-col gap-0.5';\n\n/** The tab bar's arrow keys: Left and Right move the focus between the tabs (wrapping). */\nconst arrows = (event: KeyboardEvent<HTMLElement>) => {\n const buttons = [...event.currentTarget.querySelectorAll<HTMLElement>('[role=tab]')];\n const at = buttons.indexOf(document.activeElement as HTMLElement);\n const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0;\n if (at < 0 || !step) return;\n event.preventDefault();\n buttons[(at + step + buttons.length) % buttons.length]!.focus();\n};\n\n/** The compact tab bar. With one item there is none. Exported for tests. */\nexport function TabBar({ items, activeId, onChange, text }: { readonly items: readonly NavItem[]; readonly activeId: string; readonly onChange: (id: string) => void; readonly text: AppShellText }) {\n const bar = useRef<HTMLElement>(null);\n const [plusOpen, setPlusOpen] = useState(false);\n const shown = items.length > 1;\n useTabbarHeight(bar, shown);\n if (!shown) return null;\n const { tabs, overflow } = splitNav(items);\n const inOverflow = overflow.find(item => item.id === activeId);\n const tab = (item: NavItem) => <Button key={item.id} variant={item.id === activeId ? 'secondary' : 'ghost'} role=\"tab\" data-testid={`tab-${item.id}`} aria-selected={item.id === activeId} tabIndex={item.id === activeId ? 0 : -1}\n onClick={() => onChange(item.id)} className={TAB}>\n <item.icon />{item.label}{item.badge && <Dot className=\"absolute top-1 left-1/2 ml-2\" />}\n </Button>;\n const Plus = overflow.length ? (inOverflow?.icon ?? EllipsisIcon) : undefined;\n return <nav ref={bar} role=\"tablist\" aria-label={text.tabs} data-testid=\"tabbar\" data-feedback-ignore=\"\" onKeyDown={arrows}\n className=\"relative z-(--app-shell-z-tabs) box-border flex min-h-[calc(3.5rem+env(safe-area-inset-bottom))] shrink-0 bg-background pb-[env(safe-area-inset-bottom)]\">\n <Separator className=\"absolute inset-x-0 top-0\" />\n {tabs.map(tab)}\n {Plus && <>\n <Button variant={inOverflow ? 'secondary' : 'ghost'} role=\"tab\" data-testid=\"tab-plus\" aria-selected={Boolean(inOverflow)} aria-haspopup=\"dialog\" tabIndex={inOverflow ? 0 : -1} onClick={() => setPlusOpen(true)}\n className={TAB}>\n <Plus />{inOverflow?.label ?? text.more}{!inOverflow && overflow.some(item => item.badge) && <Dot className=\"absolute top-1 left-1/2 ml-2\" />}\n </Button>\n <AppSheet open={plusOpen} onOpenChange={setPlusOpen} title={text.more}>\n {overflow.map(item => <Button key={item.id} variant={item.id === activeId ? 'secondary' : 'ghost'} size=\"lg\" data-testid={`plus-${item.id}`} aria-current={item.id === activeId} className={SHEET_ROW}\n onClick={() => { setPlusOpen(false); afterBack(() => onChange(item.id)); }}>\n <item.icon data-icon=\"inline-start\" />{item.label}{item.badge && <Dot className=\"ml-auto\" />}\n </Button>)}\n </AppSheet>\n </>}\n </nav>;\n}\n\n/** The expanded sidebar: the app title, the nav items (none with one item) and the account in the footer. */\nexport function AppSidebar({ title, items, activeId, onChange, agent, account, improve, text }: {\n readonly title: string; readonly items: readonly NavItem[]; readonly activeId: string; readonly onChange: (id: string) => void;\n readonly agent: AgentSpec | undefined; readonly account: AccountSpec | undefined; readonly improve: boolean; readonly text: AppShellText;\n}) {\n const layer = useAgentLayer();\n const pressed = layer.state !== 'closed' && layer.showing === 'agent';\n const AgentIcon = agent?.icon ?? SparklesIcon;\n const agentLabel = agent?.label ?? agent?.chatProps?.labels?.title ?? text.assistant;\n return <Sidebar collapsible=\"icon\" variant=\"inset\" data-testid=\"app-sidebar\">\n <SidebarHeader><p data-testid=\"sidebar-title\" className=\"m-0 truncate px-2 py-1 text-base font-semibold group-data-[collapsible=icon]:hidden\">{title}</p></SidebarHeader>\n <SidebarContent>\n {items.length > 1 && <SidebarGroup><SidebarGroupContent><SidebarMenu>\n {items.map(item => <SidebarMenuItem key={item.id}>\n <SidebarMenuButton isActive={item.id === activeId} tooltip={item.label} data-testid={`nav-${item.id}`} className=\"pointer-coarse:min-h-11 pointer-coarse:min-w-11\" onClick={() => onChange(item.id)}>\n <item.icon />\n <span>{item.label}</span>\n {item.badge && <Dot className=\"ml-auto group-data-[collapsible=icon]:hidden\" />}\n </SidebarMenuButton>\n </SidebarMenuItem>)}\n </SidebarMenu></SidebarGroupContent></SidebarGroup>}\n {/* The assistant is a layer, never a destination: no route, it toggles the right panel. */}\n {agent && <>\n {items.length > 1 && <SidebarSeparator />}\n <SidebarGroup><SidebarGroupContent><SidebarMenu><SidebarMenuItem>\n <SidebarMenuButton isActive={pressed} aria-pressed={pressed} tooltip={agentLabel} data-testid=\"nav-agent\" className=\"pointer-coarse:min-h-11 pointer-coarse:min-w-11\"\n onClick={() => { if (pressed) layer.close(); else layer.open('agent', 'half'); }}>\n <AgentIcon /><span>{agentLabel}</span>\n </SidebarMenuButton>\n </SidebarMenuItem></SidebarMenu></SidebarGroupContent></SidebarGroup>\n </>}\n </SidebarContent>\n <SidebarFooter><NavUser account={account} improve={improve} text={text} /></SidebarFooter>\n <SidebarRail />\n </Sidebar>;\n}\n",
|
|
89
94
|
"type": "registry:component",
|
|
90
95
|
"target": "components/app-shell/nav.tsx"
|
|
91
96
|
},
|
|
92
97
|
{
|
|
93
98
|
"path": "registry/app-shell/account.tsx",
|
|
94
|
-
"content": "'use client';\n\n// The account
|
|
99
|
+
"content": "'use client';\n\n// The account choices: the compact sheet's content (`AccountChoices`) and the expanded sidebar's footer (`NavUser`, the sidebar-07 pattern).\n// Both list « Améliorer l’app » (when the app has an `improve` agent, opened in the AgentLayer), the app's own `menu`, then sign out.\nimport { useId } from 'react';\nimport { ChevronsUpDownIcon, LogOutIcon, MoonIcon, SparklesIcon } from 'lucide-react';\nimport { Avatar, AvatarFallback } from '@/components/ui/avatar';\nimport { Button } from '@/components/ui/button';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from '@/components/ui/sidebar';\nimport { useAgentLayer } from './agent-layer';\nimport { afterBack } from './back';\nimport { Switch } from '@/components/ui/switch';\nimport { DropdownMenuCheckboxItem } from '@/components/ui/dropdown-menu';\nimport { SHEET_ROW } from './app-sheet';\nimport type { AppShellText } from './text';\n\nexport interface AccountSpec {\n readonly name: string;\n readonly email?: string;\n readonly signOut?: () => void;\n readonly menu: readonly { readonly label: string; readonly onSelect: () => void }[];\n /** The app's resolved theme: one « Mode sombre » switch in the account menu. The host resolves `system` (its preference) to `light` or `dark` before it gets here. Absent: no row. */\n readonly theme?: { readonly value: 'light' | 'dark'; readonly onChange: (value: 'light' | 'dark') => void };\n}\n\n/** The switch's state: on is dark. */\nconst darkOn = (theme: NonNullable<AccountSpec['theme']>) => theme.value === 'dark';\n\nfunction ThemeSwitch({ theme, text }: { readonly theme: NonNullable<AccountSpec['theme']>; readonly text: AppShellText }) {\n const id = useId();\n return <div className=\"flex items-center gap-3\">\n <label htmlFor={id} className=\"flex min-h-11 items-center gap-3\"><MoonIcon aria-hidden=\"true\" />{text.darkMode}</label>\n <Switch id={id} data-testid=\"account-theme\" aria-label={text.darkMode} checked={darkOn(theme)} className=\"ml-auto\" onCheckedChange={on => theme.onChange(on ? 'dark' : 'light')} />\n </div>;\n}\n\n/** « Jean Dupont » gives « JD »; one word gives its first letter. */\nexport function initials(name: string): string {\n const letters = name.trim().split(/\\s+/).filter(Boolean).slice(0, 2).map(word => [...word][0]!.toUpperCase());\n return letters.join('') || '?';\n}\n\nexport function AccountAvatar({ account, size }: { readonly account: AccountSpec | undefined; readonly size?: 'default' | 'lg' }) {\n return <Avatar size={size === 'lg' ? 'lg' : 'default'}><AvatarFallback>{initials(account?.name ?? '')}</AvatarFallback></Avatar>;\n}\n\n/** The compact account sheet's content. Every choice closes the sheet first (`done`). */\nexport function AccountChoices({ account, improve, text, done }: { readonly account: AccountSpec | undefined; readonly improve: boolean; readonly text: AppShellText; readonly done: () => void }) {\n const layer = useAgentLayer();\n const choose = (action: () => void) => () => { done(); afterBack(action); };\n return <div data-testid=\"account-menu\" className=\"flex flex-col\">\n {account && <div className=\"flex items-center gap-3 px-4 py-3\">\n <AccountAvatar account={account} size=\"lg\" />\n <div className=\"min-w-0\"><p className=\"m-0 truncate font-medium\">{account.name}</p>{account.email && <p className=\"m-0 truncate text-xs text-muted-foreground\">{account.email}</p>}</div>\n </div>}\n {improve && <Button variant=\"ghost\" size=\"lg\" data-testid=\"account-improve\" className={SHEET_ROW} onClick={choose(() => layer.open('improve'))}><SparklesIcon data-icon=\"inline-start\" aria-hidden=\"true\" />{text.improve}</Button>}\n {account?.menu.map(entry => <Button key={entry.label} variant=\"ghost\" size=\"lg\" className={SHEET_ROW} onClick={choose(entry.onSelect)}>{entry.label}</Button>)}\n {account?.theme && <ThemeSwitch theme={account.theme} text={text} />}\n {account?.signOut && <Button variant=\"ghost\" size=\"lg\" data-testid=\"account-sign-out\" className={SHEET_ROW} onClick={choose(account.signOut)}><LogOutIcon data-icon=\"inline-start\" aria-hidden=\"true\" />{text.signOut}</Button>}\n </div>;\n}\n\n/** The expanded sidebar footer: avatar, name and a dropdown with the same entries as the compact sheet. */\nexport function NavUser({ account, improve, text }: { readonly account: AccountSpec | undefined; readonly improve: boolean; readonly text: AppShellText }) {\n const layer = useAgentLayer();\n if (!account && !improve) return null;\n return <SidebarMenu><SidebarMenuItem>\n <DropdownMenu>\n <DropdownMenuTrigger render={<SidebarMenuButton size=\"lg\" data-testid=\"nav-user\" className=\"pointer-coarse:min-h-11 pointer-coarse:min-w-11\" />}>\n <AccountAvatar account={account} />\n <div className=\"grid min-w-0 flex-1 text-left text-sm leading-tight\">\n <span className=\"truncate font-medium\">{account?.name ?? text.account}</span>\n {account?.email && <span className=\"truncate text-xs text-muted-foreground\">{account.email}</span>}\n </div>\n <ChevronsUpDownIcon className=\"ml-auto size-4\" aria-hidden=\"true\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent side=\"right\" align=\"end\" sideOffset={4} className=\"app-shell w-56 min-w-56\">\n {improve && <DropdownMenuItem className=\"pointer-coarse:min-h-11\" data-testid=\"account-improve\" onClick={() => layer.open('improve')}><SparklesIcon className=\"size-4\" aria-hidden=\"true\" />{text.improve}</DropdownMenuItem>}\n {account?.menu.map(entry => <DropdownMenuItem key={entry.label} className=\"pointer-coarse:min-h-11\" onClick={entry.onSelect}>{entry.label}</DropdownMenuItem>)}\n {account?.theme && <DropdownMenuCheckboxItem checked={darkOn(account.theme)} closeOnClick data-testid=\"account-theme\" className=\"pointer-coarse:min-h-11\" onCheckedChange={on => account.theme?.onChange(on ? 'dark' : 'light')}><MoonIcon aria-hidden=\"true\" />{text.darkMode}</DropdownMenuCheckboxItem>}\n {account?.signOut && <><DropdownMenuSeparator /><DropdownMenuItem className=\"pointer-coarse:min-h-11\" data-testid=\"account-sign-out\" onClick={account.signOut}><LogOutIcon className=\"size-4\" aria-hidden=\"true\" />{text.signOut}</DropdownMenuItem></>}\n </DropdownMenuContent>\n </DropdownMenu>\n </SidebarMenuItem></SidebarMenu>;\n}\n",
|
|
95
100
|
"type": "registry:component",
|
|
96
101
|
"target": "components/app-shell/account.tsx"
|
|
97
102
|
},
|
|
98
103
|
{
|
|
99
|
-
"path": "registry/app-shell/sheet.tsx",
|
|
100
|
-
"content": "'use client';\n\n// The one sheet of the shell (account, « Plus », « … », app flows): the shadcn `drawer`, a modal bottom sheet. Only one is open at a time\n// (opening one closes any other) and Back closes it (the Back manager's `sheet` layer). The agent layer is not an AppSheet.\nimport
|
|
104
|
+
"path": "registry/app-shell/app-sheet.tsx",
|
|
105
|
+
"content": "'use client';\n\n// The one sheet of the shell (account, « Plus », « … », app flows): the host's shadcn `drawer`, a modal bottom sheet. Only one is open at a time\n// (opening one closes any other) and Back closes it (the Back manager's `sheet` layer). The agent layer is not an AppSheet.\nimport type { ReactNode } from 'react';\nimport { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';\nimport { useBackLayer } from './back';\nimport { useExclusiveSheet } from './use-exclusive-sheet';\n\n/** A modal bottom sheet with a title. The scrim, Escape, a swipe down and Back close it. */\nexport function AppSheet({ open, onOpenChange, title, children }: { readonly open: boolean; readonly onOpenChange: (open: boolean) => void; readonly title: string; readonly children: ReactNode }) {\n const close = () => onOpenChange(false);\n useExclusiveSheet(open, close);\n useBackLayer(open, close, 'sheet');\n return <Drawer open={open} onOpenChange={next => { if (!next) close(); }} showSwipeHandle swipeDirection=\"down\">\n <DrawerContent data-testid=\"app-sheet\" className=\"app-shell max-h-[85dvh]\">\n <DrawerHeader><DrawerTitle>{title}</DrawerTitle></DrawerHeader>\n <div className=\"flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain px-2 pt-2 pb-[env(safe-area-inset-bottom)]\">{children}</div>\n </DrawerContent>\n </Drawer>;\n}\n\n/** Layout for a full-width sheet row on the host's ghost `Button`: at least 48px tall (44px is the touch minimum). */\nexport const SHEET_ROW = 'min-h-12 w-full justify-start gap-3';\n",
|
|
101
106
|
"type": "registry:component",
|
|
102
|
-
"target": "components/app-shell/sheet.tsx"
|
|
107
|
+
"target": "components/app-shell/app-sheet.tsx"
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
"path": "registry/app-shell/use-exclusive-sheet.ts",
|
|
111
|
+
"content": "'use client';\n\nimport { useEffect, useRef } from 'react';\n\ninterface Open { readonly close: () => void }\nconst opened = new Set<Open>();\n\n/** While `open`, this sheet is the only one: every other open sheet is asked to close when it opens. */\nexport function useExclusiveSheet(open: boolean, close: () => void): void {\n const latest = useRef(close);\n latest.current = close;\n useEffect(() => {\n if (!open) return;\n const mine: Open = { close: () => latest.current() };\n for (const other of [...opened]) other.close();\n opened.add(mine);\n return () => { opened.delete(mine); };\n }, [open]);\n}\n",
|
|
112
|
+
"type": "registry:hook",
|
|
113
|
+
"target": "components/app-shell/use-exclusive-sheet.ts"
|
|
103
114
|
},
|
|
104
115
|
{
|
|
105
116
|
"path": "registry/app-shell/compact.ts",
|
|
@@ -109,7 +120,7 @@
|
|
|
109
120
|
},
|
|
110
121
|
{
|
|
111
122
|
"path": "registry/app-shell/index.ts",
|
|
112
|
-
"content": "// The app shell: layouts A (`screen`), B (`workspace`) and C (`chat`) with their navigation, header and account menu, and the AgentLayer it mounts.\nexport { AppShell } from './app-shell';\nexport type { AppShellProps } from './app-shell';\nexport {
|
|
123
|
+
"content": "// The app shell: layouts A (`screen`), B (`workspace`) and C (`chat`) with their navigation, header and account menu, and the AgentLayer it mounts.\nexport { AppShell } from './app-shell';\nexport type { AppShellProps } from './app-shell';\nexport { AccountChoices, NavUser } from './account';\nexport type { AccountSpec } from './account';\nexport { ListDetail, listDetailView } from './list-detail';\nexport type { ListDetailProps } from './list-detail';\nexport { AppSheet } from './app-sheet';\nexport { useShellLayer } from './shell-layer';\nexport type { ShellLayer } from './shell-layer';\nexport { AppSidebar, TabBar } from './nav';\nexport type { NavItem } from './nav';\nexport { ScreenHeader, useScreenHeader } from './header';\nexport type { ScreenHeaderSpec } from './header';\nexport { useIsCompact } from './compact';\nexport { AgentDockLayout, AgentLayer, AgentTrigger, useAgentLayer } from './agent-layer';\nexport { readAgentContext, useAgentContext } from './agent-context';\n",
|
|
113
124
|
"type": "registry:lib",
|
|
114
125
|
"target": "components/app-shell/index.ts"
|
|
115
126
|
}
|
|
@@ -129,6 +140,14 @@
|
|
|
129
140
|
"margin": "0",
|
|
130
141
|
"font": "inherit"
|
|
131
142
|
}
|
|
143
|
+
},
|
|
144
|
+
"@layer utilities": {
|
|
145
|
+
"@media (max-width: 640px), (pointer: coarse)": {
|
|
146
|
+
".app-shell :is([data-slot=\"button\"], [data-slot=\"toggle\"], [class~=\"group/button\"], [class~=\"group/toggle\"])": {
|
|
147
|
+
"min-height": "2.75rem",
|
|
148
|
+
"min-width": "2.75rem"
|
|
149
|
+
}
|
|
150
|
+
}
|
|
132
151
|
}
|
|
133
152
|
},
|
|
134
153
|
"type": "registry:block"
|