diff --git a/REFERENCE.md b/REFERENCE.md index eb806645..755ef492 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -350,9 +350,9 @@ CsvTable.rows: readonly (readonly CsvCell[])[] DataApp (component, @altertable/data-app-react): (props: DataAppProps) — Executes the primary view and its summary views, and owns controls, inspection, exports, and stories. DataApp.children: ReactNode DataApp.description?: ReactNode — Override the declared subtitle; null hides it. -DataApp.showToolbar?: boolean — Show page actions. Defaults to true; does not hide filters or data states. -DataApp.toolbarActions?: ReactNode -DataApp.footerActions?: ReactNode +DataApp.showToolbar?: boolean — Show page actions. Defaults to true; does not hide filters or data states. Embedded surfaces have no toolbar: the host runs page actions through its bridge. +DataApp.toolbarActions?: ReactNode — Standalone toolbar controls; embedded surfaces omit them. +DataApp.footerActions?: ReactNode — Standalone footer controls; embedded surfaces omit them. DataApp.footer?: ReactNode — Optional source, coverage, or methodology note below the app content. Compose prose and inline components; typography and spacing are provided. DataApp.showSearch?: boolean — Show declared search controls. Defaults to true; hiding preserves their values. DataApp.showFilters?: boolean — Show declared filter controls, including display options. Defaults to true; hiding preserves their values. @@ -366,9 +366,9 @@ DataApp (component, @altertable/data-app-react/ui): (props: DataAppProps) — Se DataApp.children: ReactNode DataApp.dataContext: DataContext DataApp.description?: ReactNode — Override the declared subtitle; null hides it. -DataApp.showToolbar?: boolean — Show page actions. Defaults to true; does not hide filters or data states. -DataApp.toolbarActions?: ReactNode -DataApp.footerActions?: ReactNode +DataApp.showToolbar?: boolean — Show page actions. Defaults to true; does not hide filters or data states. Embedded surfaces have no toolbar: the host runs page actions through its bridge. +DataApp.toolbarActions?: ReactNode — Standalone toolbar controls; embedded surfaces omit them. +DataApp.footerActions?: ReactNode — Standalone footer controls; embedded surfaces omit them. DataApp.footer?: ReactNode — Optional source, coverage, or methodology note below the app content. Compose prose and inline components; typography and spacing are provided. DataApp.csvExport?: CsvExport DataApp.queries?: DisclosedQuery[] @@ -398,9 +398,9 @@ DataAppProps (type, @altertable/data-app-react/ui) DataAppProps.children: ReactNode DataAppProps.dataContext: DataContext DataAppProps.description?: ReactNode — Override the declared subtitle; null hides it. -DataAppProps.showToolbar?: boolean — Show page actions. Defaults to true; does not hide filters or data states. -DataAppProps.toolbarActions?: ReactNode -DataAppProps.footerActions?: ReactNode +DataAppProps.showToolbar?: boolean — Show page actions. Defaults to true; does not hide filters or data states. Embedded surfaces have no toolbar: the host runs page actions through its bridge. +DataAppProps.toolbarActions?: ReactNode — Standalone toolbar controls; embedded surfaces omit them. +DataAppProps.footerActions?: ReactNode — Standalone footer controls; embedded surfaces omit them. DataAppProps.footer?: ReactNode — Optional source, coverage, or methodology note below the app content. Compose prose and inline components; typography and spacing are provided. DataAppProps.csvExport?: CsvExport DataAppProps.queries?: DisclosedQuery[] @@ -1311,6 +1311,7 @@ PresentStory.dataContext: DataContext PresentStory.theme?: ThemeController PresentStory.headerActions?: ReactNode PresentStory.footer?: ReactNode +PresentStory.trigger?: boolean — False renders only the presentation, which `?present=1&step=` opens. PresentStory.…: plus props inherited from React PresentStoryProps (type, @altertable/data-app-react/ui): = props listed as PresentStory.* QueryDefinitions (type, @altertable/data-app, @altertable/data-app/config, @altertable/data-app/contract): > = { readonly [x: string]: QueryDefinition; } diff --git a/dev/fixtures/annotation-state-app.tsx b/dev/fixtures/annotation-state-app.tsx index 12453d05..546d3813 100644 --- a/dev/fixtures/annotation-state-app.tsx +++ b/dev/fixtures/annotation-state-app.tsx @@ -49,7 +49,7 @@ const client = createDataClient({ return Promise.resolve({ status: 200, body: { - data: period === 'last-365' ? 84 : 42, + data: 42, requestId: period, queriedAt: '2026-10-07T00:00:00Z', queryIds: [], @@ -105,16 +105,7 @@ const content = view.content(source => ( )); function App() { return ( - []} - datasets={[dataset]} - toolbarActions={ - - } - > + []} datasets={[dataset]}> ); diff --git a/dev/fixtures/bundle-host.tsx b/dev/fixtures/bundle-host.tsx index a5e4d255..92767b94 100644 --- a/dev/fixtures/bundle-host.tsx +++ b/dev/fixtures/bundle-host.tsx @@ -1,11 +1,15 @@ import { + type DataAppActions, type DataAppLogger, type DataAppStatus, createNavigationHandler, createExternalLinkHandler, createSqlQueryHandler, } from '@altertable/data-app-embed'; -import { DataAppBridge } from '@altertable/data-app-embed/react'; +import { + DataAppBridge, + type DataAppBridgeHandle, +} from '@altertable/data-app-embed/react'; import { AnnotationBar, type AnnotationBarHandle, @@ -34,7 +38,17 @@ import { KEY_SEPARATOR } from '@altertable/data-app/internal'; import '@/packages/data-app-react/src/ui/Tooltip.css'; import '@/packages/data-app-react/src/ui/Kbd.css'; -import { Moon, Sun, PanelsTopLeft, AppWindow } from 'lucide-react'; +import { + Moon, + Sun, + PanelsTopLeft, + AppWindow, + RefreshCw, + Square, + Download, + Presentation, + Info, +} from 'lucide-react'; import { StrictMode, useEffectEvent, @@ -42,6 +56,7 @@ import { useRef, useState, type ComponentRef, + type RefObject, } from 'react'; import { createRoot } from 'react-dom/client'; @@ -107,7 +122,72 @@ const previewLabels = { standalone: 'Preview embedded app', }; +/** Page actions the embedded app offers, rendered by the host instead of an in-app toolbar. */ +function HostPageActions({ + actions, + run, + portalRoot, +}: { + actions: DataAppActions; + run: DataAppBridgeHandle['runAction']; + portalRoot: RefObject; +}) { + const { refresh, exportCsv, presentStory, aboutData } = actions; + const items = [ + refresh && { + label: refresh.refreshing + ? refresh.cancellable + ? 'Cancel refresh' + : 'Refreshing data' + : 'Refresh data', + icon: refresh.refreshing && refresh.cancellable ? Square : RefreshCw, + disabled: refresh.refreshing && !refresh.cancellable, + busy: refresh.refreshing, + run: () => + run({ type: refresh.refreshing ? 'cancelRefresh' : 'refresh' }), + }, + exportCsv && { + label: + exportCsv.tables.length > 1 ? 'Export all data (ZIP)' : 'Export CSV', + icon: Download, + disabled: !exportCsv.enabled, + run: () => run({ type: 'exportCsv' }), + }, + presentStory && { + label: 'Present story', + icon: Presentation, + disabled: !presentStory.enabled, + run: () => run({ type: 'presentStory' }), + }, + aboutData && { + label: 'Explore data', + icon: Info, + disabled: !aboutData.enabled, + run: () => run({ type: 'aboutData' }), + }, + ].filter(item => !!item); + return items.map(item => ( + + + + )); +} + function Host() { + const bridge = useRef(null); + const [actions, setActions] = useState({}); const [annotationFailure, setAnnotationFailure] = useState( hostOptions.has('annotation-error') ); @@ -177,9 +257,10 @@ function Host() { ? { annotations: { enabled: true, + // Without an in-frame toolbar, the host always owns annotation mode. + active: annotating, ...(isPlayground ? { - active: annotating, pinsVisible, showHint: annotations.length === 0, readOnly: sending || !annotationsHost.ready, @@ -336,6 +417,14 @@ function Host() { > Change surface + {hostOptions.has('annotations') && ( + + )} ); const testControls = ( @@ -379,6 +468,11 @@ function Host() { aria-label="Playground controls" className="playground-controls" > + bridge.current?.runAction(action)} + portalRoot={hostRef} + /> {showSizingControls && ( <> + )} + + + ); +} +``` + +See [page actions](embed.md#page-actions) for every action and its state. diff --git a/docs/stories-and-export.md b/docs/stories-and-export.md index 86787e1c..54d67df6 100644 --- a/docs/stories-and-export.md +++ b/docs/stories-and-export.md @@ -2,7 +2,7 @@ The bound `` from `@altertable/data-app-react` accepts an optional `story` callback and optional nonempty `datasets` list. Omit either prop to omit its toolbar -control. Supplied features use the displayed snapshot, including during refresh or +control, or the matching [page action](embed.md#page-actions) when embedded. Supplied features use the displayed snapshot, including during refresh or failure. A story callback returning `[]` leaves a disabled presentation action. Set `showToolbar={false}` to omit page actions together; data loading, error states, and declared filters remain available. Setup and static screens can use `` diff --git a/packages/data-app-bun/src/preview/host.tsx b/packages/data-app-bun/src/preview/host.tsx index 0852c79d..140e24b1 100644 --- a/packages/data-app-bun/src/preview/host.tsx +++ b/packages/data-app-bun/src/preview/host.tsx @@ -5,10 +5,7 @@ import { createSqlQueryHandler, type DataAppStatus, } from '@altertable/data-app-embed'; -import { - DataAppBridge, - DataAppRepairBanner, -} from '@altertable/data-app-embed/react'; +import { DataAppBridge } from '@altertable/data-app-embed/react'; import { DataSourceError, createMessageRouter, @@ -21,6 +18,8 @@ import { downloadBlob } from '@altertable/data-app/internal'; import { StrictMode, useEffect, useState } from 'react'; import { createRoot } from 'react-dom/client'; +import { RepairBanner } from './repair-banner.tsx'; + const openExternalLink = createExternalLinkHandler(); const fileExportRoute = defineMessageRoute({ @@ -136,7 +135,7 @@ function DevFileHost() { The data app failed to start. Check the browser console.

)} - + svg { grid-area: icon; margin-top: 1px; } +.atbl-repair-banner-status { grid-area: status; min-width: 0; overflow-wrap: anywhere; } +.atbl-repair-banner-title { font-weight: 600; } +.atbl-repair-banner-description, .atbl-repair-banner-feedback { display: block; margin-top: 2px; color: light-dark(#606a76, #a6b0bc); font-size: 12px; } +.atbl-repair-banner button { grid-area: actions; min-height: 32px; padding: 7px 12px; border: 1px solid light-dark(#cdd3da, #515b66); border-radius: 7px; background: light-dark(#ffffff, #292f36); color: inherit; font: inherit; font-weight: 500; } +.atbl-repair-banner button:disabled { opacity: .6; } +.atbl-repair-banner button:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; } +.atbl-repair-banner-feedback:empty { display: none; } +.atbl-repair-banner-feedback, .atbl-repair-banner pre { grid-column: 2 / -1; min-width: 0; margin: 0; } +.atbl-repair-banner pre { white-space: pre-wrap; overflow-wrap: anywhere; font: 11px/1.5 ui-monospace, monospace; } +@media (max-width: 600px) { .atbl-repair-banner { grid-template-columns: 18px minmax(0, 1fr); grid-template-areas: "icon status" ". actions"; } } +`; + +/** The preview cannot invoke an agent, so it offers the observed diagnostics to copy. */ +export function RepairBanner({ session }: { session: DataAppRepairSession }) { + const { report } = useSyncExternalStore( + listener => session.subscribe(listener), + session.snapshot, + session.snapshot + ); + const [clipboard, setClipboard] = useState<{ + report: AppDiagnosticReport; + status: 'pending' | 'failed'; + }>(); + if (!report?.failures.length) return null; + const current = clipboard?.report === report ? clipboard : undefined; + + async function copyDiagnostics(copied: AppDiagnosticReport) { + setClipboard({ report: copied, status: 'pending' }); + try { + await navigator.clipboard.writeText(JSON.stringify(copied, null, 2)); + setClipboard(undefined); + } catch { + setClipboard({ report: copied, status: 'failed' }); + } + } + + return ( +
+ + +

+ + Something isn’t working + + + Copy the diagnostics into your agent to request a fix. + +

+ + + {current && + (current.status === 'failed' + ? 'Couldn’t copy. Select and copy the diagnostics below.' + : 'Copying…')} + + {current?.status === 'failed' && ( +
{JSON.stringify(report, null, 2)}
+ )} +
+ ); +} diff --git a/packages/data-app-embed/src/host.ts b/packages/data-app-embed/src/host.ts index f7fe07a4..b731e2d8 100644 --- a/packages/data-app-embed/src/host.ts +++ b/packages/data-app-embed/src/host.ts @@ -1,4 +1,8 @@ -import { type DataAppLogger } from '@altertable/data-app/client'; +import { + type DataAppAction, + type DataAppActions, + type DataAppLogger, +} from '@altertable/data-app/client'; import { type DataAppAnnotationPresentation, MessageRoutingError, @@ -34,6 +38,9 @@ export type DataAppHost = { dispose: () => void; setPresentation: (presentation?: DataAppPresentation) => void; setLogger: (logger?: DataAppLogger) => void; + /** Runs an action the app offered through `onActionsChange`; ignored while disconnected. + * Call it from a user gesture so `presentStory` can show the frame fullscreen. */ + runAction: (action: DataAppAction) => void; }; export type DataAppHostOptions = { @@ -43,6 +50,8 @@ export type DataAppHostOptions = { logger?: DataAppLogger; onStatusChange?: (status: DataAppStatus) => void; onDiagnostic?: (event: DataAppDiagnostic) => void; + /** The page actions the connected app offers; empty while disconnected or when it offers none. */ + onActionsChange?: (actions: DataAppActions) => void; onMessage: MessageDispatcher; }; @@ -52,6 +61,13 @@ export type DataAppConnectionOptions = DataAppHostOptions & { window?: Window; }; +type FocusableElement = Element & HTMLOrSVGElement; + +/** HTML and SVG elements can take focus; checked by shape so frames from other realms qualify. */ +function isFocusable(element: Element): element is FocusableElement { + return 'focus' in element; +} + /** The bridge owns delivery and cancellation; the routed handler owns validation, authorization and execution. */ export function attachDataAppConnection({ iframe, @@ -61,6 +77,7 @@ export function attachDataAppConnection({ logger, onStatusChange, onDiagnostic, + onActionsChange, onMessage, repair, window: host = window, @@ -85,6 +102,13 @@ export function attachDataAppConnection({ let repairLease = repair?.session.connect(repair.revision); const unsubscribeRepair = repair?.session.subscribe(() => publishState()); const pending = new Map(); + let actions: DataAppActions = {}; + let actionsIdentity = '{}'; + // Set while a story this bridge opened shows the iframe fullscreen. + let ownsFullscreen = false; + // The host control that ran `presentStory`; it regains focus when that story closes. + let storyLauncher: FocusableElement | undefined; + const parentDocument = iframe.ownerDocument; const requestStartedAt = new Map(); function reportDiagnostic(event: BridgeDiagnostic) { @@ -163,6 +187,87 @@ export function attachDataAppConnection({ publishState(); } + function publishActions(next: DataAppActions) { + const identity = JSON.stringify(next); + if (identity === actionsIdentity) return; + actionsIdentity = identity; + const wasPresenting = actions.presentStory?.presenting === true; + actions = next; + if (!next.presentStory?.presenting) { + // Focus cannot return to the host page until it leaves fullscreen. + const exited = exitStoryFullscreen(); + if (wasPresenting) void exited.then(restoreStoryLauncher); + } + onActionsChange?.(next); + } + + function runAction(action: DataAppAction) { + if (disposed || !sessionId) return; + if ( + action.type === 'presentStory' && + actions.presentStory?.enabled && + !actions.presentStory.presenting + ) { + storyLauncher = focusedHostControl(); + enterStoryFullscreen(); + // The frame cannot take focus from the host, so move keyboard users to the story. + iframe.focus({ preventScroll: true }); + } + if (action.type === 'aboutData' && actions.aboutData?.enabled) + iframe.focus({ preventScroll: true }); + send('actionRun', { action }); + } + + function focusedHostControl() { + const active = parentDocument.activeElement; + return active && + active !== iframe && + active !== parentDocument.body && + isFocusable(active) + ? active + : undefined; + } + + /** Returns focus only from the frame or nowhere, never from a control the reader moved to. */ + function restoreStoryLauncher() { + const launcher = storyLauncher; + storyLauncher = undefined; + const active = parentDocument.activeElement; + if ( + launcher?.isConnected && + (active === null || active === iframe || active === parentDocument.body) + ) + launcher.focus({ preventScroll: true }); + } + + /** Stories fill the screen as they do standalone; the frame alone cannot without its own gesture. */ + function enterStoryFullscreen() { + if (!parentDocument.fullscreenEnabled || parentDocument.fullscreenElement) + return; + iframe.requestFullscreen().then( + () => { + ownsFullscreen = true; + }, + // Keep the story available when fullscreen is denied. + () => {} + ); + } + + function exitStoryFullscreen(): Promise { + if (!ownsFullscreen) return Promise.resolve(); + ownsFullscreen = false; + return parentDocument.fullscreenElement === iframe + ? parentDocument.exitFullscreen().catch(() => {}) + : Promise.resolve(); + } + + function closeStoryOnFullscreenExit() { + if (!ownsFullscreen || parentDocument.fullscreenElement === iframe) return; + ownsFullscreen = false; + if (actions.presentStory?.presenting && sessionId) + send('actionRun', { action: { type: 'closeStory' } }); + } + function cancelAll() { for (const controller of pending.values()) controller.abort(); pending.clear(); @@ -187,6 +292,7 @@ export function attachDataAppConnection({ ready(message) { if (message.documentId !== documentId) { cancelAll(); + publishActions({}); if (documentId) repairLease = repair?.session.connect(repair.revision); documentId = message.documentId; @@ -214,6 +320,9 @@ export function attachDataAppConnection({ runtimeError() { onStatusChange?.('failed'); }, + actionsUpdate({ actions }) { + publishActions(actions); + }, runtimeResize({ height }) { contentSizing.resize(height); }, @@ -226,6 +335,7 @@ export function attachDataAppConnection({ }, disconnect() { cancelAll(); + publishActions({}); documentId = undefined; sessionId = undefined; onStatusChange?.('disconnected'); @@ -348,11 +458,17 @@ export function attachDataAppConnection({ repairLease = repair?.session.connect(repair.revision); documentId = undefined; sessionId = undefined; + publishActions({}); onStatusChange?.('connecting'); send('connect', {}); } function dispose() { + void exitStoryFullscreen(); + parentDocument.removeEventListener( + 'fullscreenchange', + closeStoryOnFullscreenExit + ); disposed = true; unsubscribeRepair?.(); repairLease?.dispose(); @@ -372,9 +488,13 @@ export function attachDataAppConnection({ host.addEventListener('popstate', publishState); host.addEventListener('pagehide', cancelAll); host.addEventListener('click', publishAnnotationDismissal, true); + parentDocument.addEventListener( + 'fullscreenchange', + closeStoryOnFullscreenExit + ); // Reconnect an already-loaded iframe when its host bridge mounts again. onStatusChange?.('connecting'); send('connect', {}); - return { dispose, setPresentation, setLogger }; + return { dispose, setPresentation, setLogger, runAction }; } diff --git a/packages/data-app-embed/src/index.ts b/packages/data-app-embed/src/index.ts index 19917088..2f702062 100644 --- a/packages/data-app-embed/src/index.ts +++ b/packages/data-app-embed/src/index.ts @@ -15,7 +15,11 @@ export { startDataAppBootstrap } from './bootstrap.ts'; export { createNavigationHandler } from './navigation.ts'; export { createSqlQueryHandler } from './sql.ts'; export { type DataAppPresentation } from '@altertable/data-app/internal'; -export { type DataAppLogger } from '@altertable/data-app/client'; +export { + type DataAppAction, + type DataAppActions, + type DataAppLogger, +} from '@altertable/data-app/client'; export { createDataAppRepairSession, type DataAppRepairSession, diff --git a/packages/data-app-embed/src/react/bridge.tsx b/packages/data-app-embed/src/react/bridge.tsx index 86691d3d..98ff4c81 100644 --- a/packages/data-app-embed/src/react/bridge.tsx +++ b/packages/data-app-embed/src/react/bridge.tsx @@ -1,10 +1,12 @@ import { + useImperativeHandle, useRef, useLayoutEffect, useEffect, useState, type ComponentRef, type ComponentPropsWithoutRef, + type Ref, } from 'react'; import { attachDataAppBridge, type DataAppBridgeOptions } from '../bridge.ts'; @@ -16,11 +18,14 @@ export type DataAppBridgeProps = Pick< | 'onMessage' | 'onStatusChange' | 'onDiagnostic' + | 'onActionsChange' | 'presentation' | 'logger' | 'repair' -> & - ( +> & { + /** Runs page actions the app offers through `onActionsChange`. */ + ref?: Ref; +} & ( | { source: DataAppSource; title: string; @@ -48,6 +53,8 @@ export type DataAppBridgeProps = Pick< } ); +export type DataAppBridgeHandle = Pick; + /** Owns iframe setup and delivery. The consuming shell owns loading, error UI, and retries. */ export function DataAppBridge(props: DataAppBridgeProps) { if (props.source) { @@ -78,6 +85,12 @@ function useBridgeState(props: DataAppBridgeProps) { handlers.current = props; }); + useImperativeHandle( + props.ref, + () => ({ runAction: action => hostRef.current?.runAction(action) }), + [] + ); + useEffect(() => { hostRef.current?.setPresentation(props.presentation); hostRef.current?.setLogger(props.logger); @@ -120,6 +133,9 @@ function SourceBridge(props: SourceBridgeProps) { onDiagnostic(event) { return handlers.current.onDiagnostic?.(event); }, + onActionsChange(actions) { + return handlers.current.onActionsChange?.(actions); + }, }); hostRef.current = bridge; @@ -184,6 +200,9 @@ function ConnectionBridge(props: ConnectionBridgeProps) { onDiagnostic(event) { return handlers.current.onDiagnostic?.(event); }, + onActionsChange(actions) { + return handlers.current.onActionsChange?.(actions); + }, }); hostRef.current = bridge; diff --git a/packages/data-app-embed/src/react/index.ts b/packages/data-app-embed/src/react/index.ts index a1f4a74b..f54d7269 100644 --- a/packages/data-app-embed/src/react/index.ts +++ b/packages/data-app-embed/src/react/index.ts @@ -3,8 +3,8 @@ * @module @altertable/data-app-embed/react * @see https://github.com/altertable-ai/data-app/blob/main/docs/react-embed.md */ -export { DataAppBridge, type DataAppBridgeProps } from './bridge.tsx'; export { - DataAppRepairBanner, - type DataAppRepairProgress, -} from './repair-banner.tsx'; + DataAppBridge, + type DataAppBridgeHandle, + type DataAppBridgeProps, +} from './bridge.tsx'; diff --git a/packages/data-app-embed/src/react/repair-banner.tsx b/packages/data-app-embed/src/react/repair-banner.tsx deleted file mode 100644 index 09879124..00000000 --- a/packages/data-app-embed/src/react/repair-banner.tsx +++ /dev/null @@ -1,276 +0,0 @@ -import type { AppDiagnosticReport } from '@altertable/data-app/client'; -import { useEffect, useState, useSyncExternalStore } from 'react'; - -import { - AUTOMATIC_REPAIR_LIMIT, - type DataAppRepairSession, -} from '../repair.ts'; - -export type DataAppRepairProgress = { - /** - * Observed host activity. Use review when the agent stops with errors remaining. - * Clear progress on a new request or after the updated revision's diagnostics settle. - */ - phase: 'working' | 'building' | 'loading' | 'review'; - /** Optional agent activity, shown while working. */ - detail?: string; - /** Fallback start time in milliseconds since the Unix epoch for activity that predates this session. */ - startedAt?: number; -}; - -type RepairPhase = - | 'idle' - | 'preparing' - | DataAppRepairProgress['phase'] - | 'failed' - | 'unsupported' - | 'limited'; - -const messages: Record = { - idle: { - title: 'Something isn’t working', - description: 'You can keep using the app or try a fix.', - }, - preparing: { - title: 'Preparing a fix', - description: 'You can keep using the rest of the app.', - }, - working: { - title: 'Updating your app', - description: 'Your agent is fixing the reported errors.', - }, - building: { - title: 'Updating your app', - description: 'Building the updated app.', - }, - loading: { - title: 'Updating your app', - description: 'Loading the updated app.', - }, - review: { - title: 'The app still needs attention', - description: 'Your agent has stopped. You can request another fix.', - }, - failed: { - title: 'Couldn’t request a fix', - description: 'The request could not be saved or delivered. Try again.', - }, - unsupported: { - title: 'Something isn’t working', - description: 'Copy the diagnostics into your agent to request a fix.', - }, - limited: { - title: 'Automatic fixes are paused', - description: `${AUTOMATIC_REPAIR_LIMIT} automatic requests have been used. You can request another fix.`, - }, -}; - -const styles = ` -.atbl-repair-banner { - display: grid; grid-template-columns: 18px minmax(0, 1fr) auto; - grid-template-areas: "icon status actions"; align-items: start; - gap: 4px 12px; flex-shrink: 0; padding: 12px 16px; box-sizing: border-box; width: 100%; - color: light-dark(#252b32, #e6e9ed); background: light-dark(#fafbfc, #20252b); - border-bottom: 1px solid light-dark(#e3e6e8, #3b4248); - font: 13px/1.45 var(--atbl-font, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif); - -webkit-font-smoothing: antialiased; -} -.atbl-repair-banner > svg { grid-area: icon; margin-top: 1px; } -.atbl-repair-banner-actions { grid-area: actions; display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: 8px 12px; } -.atbl-repair-banner-status { grid-area: status; min-width: 0; overflow-wrap: anywhere; } -.atbl-repair-banner-title { font-weight: 600; } -.atbl-repair-banner-elapsed { margin-inline-start: 8px; font-size: 12px; font-weight: 400; color: light-dark(#606a76, #a6b0bc); white-space: nowrap; } -.atbl-repair-banner-feedback, .atbl-repair-banner-description { display: block; margin-top: 2px; color: light-dark(#606a76, #a6b0bc); font-size: 12px; line-height: 1.5; } -.atbl-repair-banner button { display: inline-flex; align-items: center; justify-content: center; flex: none; min-height: 32px; padding: 7px 12px; border: 1px solid light-dark(#cdd3da, #515b66); border-radius: 7px; background: light-dark(#ffffff, #292f36); color: inherit; font: inherit; line-height: 1; font-weight: 500; cursor: default; touch-action: manipulation; } -.atbl-repair-banner button > span { position: relative; top: -.5px; } -.atbl-repair-banner .atbl-repair-banner-copy-button { border-color: transparent; background: transparent; } -.atbl-repair-banner button:disabled { opacity: .6; } -.atbl-repair-banner button:active:not(:disabled) { transform: scale(.97); } -.atbl-repair-banner button:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; } -.atbl-repair-banner-feedback:empty { display: none; } -.atbl-repair-banner-feedback { grid-column: 2 / -1; min-width: 0; } -.atbl-repair-banner-fallback { grid-column: 2 / -1; min-width: 0; margin: 0; } -.atbl-repair-banner pre { white-space: pre-wrap; overflow-wrap: anywhere; font: 11px/1.5 var(--atbl-mono-font, ui-monospace, monospace); } -.atbl-repair-banner-spinner { animation: atbl-repair-spin 1s linear infinite; } -@keyframes atbl-repair-spin { to { transform: rotate(360deg); } } -@media (prefers-reduced-motion: reduce) { .atbl-repair-banner-spinner { animation: none; } .atbl-repair-banner button:active:not(:disabled) { transform: none; } } -@media (hover: hover) { .atbl-repair-banner button:hover:not(:disabled) { background: light-dark(#f0f2f5, #343d47); } } -@media (pointer: coarse) { .atbl-repair-banner button { min-height: 44px; } } -@media (max-width: 600px) { .atbl-repair-banner { grid-template-columns: 18px minmax(0, 1fr); grid-template-areas: "icon status" ". actions"; } .atbl-repair-banner-actions { padding-top: 4px; } } -@media (max-width: 420px) { .atbl-repair-banner { padding: 12px; gap: 4px 10px; align-items: start; } } -`; - -/** Shared in-flow host banner. Mount above the app iframe with the same repair session. */ -export function DataAppRepairBanner({ - session, - progress, -}: { - session: DataAppRepairSession; - /** Optional observed host activity; request acceptance alone does not mean an agent is working. */ - progress?: DataAppRepairProgress; -}) { - const [clipboard, setClipboard] = useState<{ - report: AppDiagnosticReport; - status: 'pending' | 'failed'; - }>(); - const { - report, - status, - automaticRequests, - startedAt: requestStartedAt, - } = useSyncExternalStore( - listener => session.subscribe(listener), - session.snapshot, - session.snapshot - ); - - const [lastFailure, setLastFailure] = useState({ session, report }); - if ( - lastFailure.session !== session || - (report?.failures.length && report !== lastFailure.report) - ) { - setLastFailure({ session, report }); - } - let phase: RepairPhase; - if (status === 'failed' || status === 'unsupported') { - phase = status; - } else if (status === 'pending') { - phase = 'preparing'; - } else if (progress) { - phase = progress.phase; - } else if (status === 'accepted') { - phase = 'preparing'; - } else if (automaticRequests >= AUTOMATIC_REPAIR_LIMIT) { - phase = 'limited'; - } else { - phase = 'idle'; - } - const inProgress = - phase === 'preparing' || - phase === 'working' || - phase === 'building' || - phase === 'loading'; - const startedAt = inProgress - ? (requestStartedAt ?? progress?.startedAt) - : undefined; - const hasActiveProgress = - progress !== undefined && progress.phase !== 'review'; - const visibleReport = report?.failures.length - ? report - : hasActiveProgress && lastFailure.session === session - ? lastFailure.report - : undefined; - if (!visibleReport?.failures.length && !hasActiveProgress) return null; - const feedback = messages[phase]; - const clipboardFailed = - clipboard?.status === 'failed' && clipboard.report === visibleReport; - - async function copyDiagnostics(report: AppDiagnosticReport) { - setClipboard({ report, status: 'pending' }); - try { - await navigator.clipboard.writeText(JSON.stringify(report, null, 2)); - setClipboard(undefined); - } catch { - setClipboard({ report, status: 'failed' }); - } - } - - return ( - <> - -
- - {inProgress ? ( - - ) : ( - <> - - - - )} - - - {feedback.title} - {startedAt !== undefined && ( - - )} - - {phase === 'working' - ? progress?.detail || feedback.description - : feedback.description} - - -
- {visibleReport && ( - - )} - -
- - {clipboard && - clipboard.report === visibleReport && - (clipboard.status === 'failed' - ? 'Couldn’t copy. Select and copy the diagnostics below.' - : 'Copying…')} - - {clipboardFailed && ( -
-            {JSON.stringify(visibleReport, null, 2)}
-          
- )} -
- - ); -} - -function ElapsedTime({ startedAt }: { startedAt: number }) { - const [now, setNow] = useState(Date.now); - useEffect(() => { - const timer = setInterval(() => setNow(Date.now()), 1000); - return () => clearInterval(timer); - }, []); - const seconds = Math.floor((now - startedAt) / 1000); - if (seconds < 1) return null; - return ( - - {seconds}s elapsed - - ); -} diff --git a/packages/data-app-embed/src/repair.ts b/packages/data-app-embed/src/repair.ts index d725e662..35faabcc 100644 --- a/packages/data-app-embed/src/repair.ts +++ b/packages/data-app-embed/src/repair.ts @@ -1,7 +1,7 @@ import { type AppDiagnosticReport } from '@altertable/data-app/client'; import { parseAppDiagnosticReport } from '@altertable/data-app/internal'; -export const AUTOMATIC_REPAIR_LIMIT = 3; +const AUTOMATIC_REPAIR_LIMIT = 3; /** Host-retained state for one app repair session. Never reset for revisions, healthy reports or manual requests. */ export type DataAppRepairState = { diff --git a/packages/data-app-embed/src/source.ts b/packages/data-app-embed/src/source.ts index 8a906877..0689dbde 100644 --- a/packages/data-app-embed/src/source.ts +++ b/packages/data-app-embed/src/source.ts @@ -30,6 +30,7 @@ export function attachDataAppSource({ onMessage, onStatusChange, onDiagnostic, + onActionsChange, repair, startupTimeoutMs = 30_000, }: DataAppSourceOptions): DataAppHost { @@ -86,6 +87,7 @@ export function attachDataAppSource({ onMessage, onStatusChange: status, onDiagnostic, + onActionsChange, repair, window: host, }); @@ -107,5 +109,6 @@ export function attachDataAppSource({ dispose, setPresentation: bridge.setPresentation, setLogger: bridge.setLogger, + runAction: bridge.runAction, }; } diff --git a/packages/data-app-react/src/annotations/AnnotationControls.tsx b/packages/data-app-react/src/annotations/AnnotationControls.tsx index 3a0249a0..5608e4a1 100644 --- a/packages/data-app-react/src/annotations/AnnotationControls.tsx +++ b/packages/data-app-react/src/annotations/AnnotationControls.tsx @@ -57,6 +57,8 @@ type AnnotationControlsProps = { presentation: DataAppAnnotationPresentation; displayedInput?: unknown; view?: string; + /** False leaves annotation mode to the host, as on embedded surfaces. */ + trigger?: boolean; }; type AnnotationSelection = { target: AnnotationTargetElement; @@ -78,6 +80,7 @@ export function AnnotationControls({ presentation, displayedInput, view, + trigger = true, }: AnnotationControlsProps) { const annotationClient = useDataAppAnnotations(); const [state, dispatch] = useReducer( @@ -86,7 +89,10 @@ export function AnnotationControls({ createAnnotationControlsState ); const { editor, hoveredTarget, saving } = state; - const active = presentation.active ?? state.annotationModeActive; + const hostOwnsMode = !trigger || presentation.active !== undefined; + const active = hostOwnsMode + ? (presentation.active ?? false) + : state.annotationModeActive; const pending = saving || presentation.readOnly === true; const editing = Boolean(editor); const editorDraftId = editor?.draft.id; @@ -282,7 +288,7 @@ export function AnnotationControls({ function setAnnotationMode(active: boolean) { dispatch({ type: 'annotationModeChanged', active }); - if (presentation.active !== undefined) { + if (hostOwnsMode) { void annotationClient .requestAnnotationModeChange({ active }) .catch(() => {}); @@ -430,7 +436,7 @@ export function AnnotationControls({ return ( <> - {presentation.active === undefined && ( + {!hostOwnsMode && ( ( toolbarActions, } = props; const app = useDataApp(); - const presentation = useDataAppPresentation(); + const transport = useDataAppTransport(); + const presentation = useDataAppPresentation(transport); const isEmbedded = presentation?.surface === 'embedded'; + // Page actions live in the in-frame toolbar when standalone and in the host when embedded. + const showActions = props.showToolbar !== false; + const hasToolbar = showActions && !isEmbedded; const themeController = useAppAppearance(app.appearance, presentation?.theme); const bodyRef = useRef>(null); useEffect(() => { @@ -109,62 +118,58 @@ export function DataAppFrame( environment={app.scope.environment} /> ); - const toolbar = - props.showToolbar === false ? null : ( - void request.refetch(), - onCancel: request.cancel - ? () => void request.cancel?.() - : undefined, - } - : undefined - } - story={ - props.story && - (findings.length - ? { - findings, - title: app.title, - scope, - dataContext, - theme: themeController, - } - : null) - } - aboutData={ - + const csvExport = + props.csvExport && (props.csvExport.loading ? null : props.csvExport.value); + const refresh = request + ? { + refreshing: + request.refreshing ?? + (request.view.kind === 'loading' || request.view.kind === 'updating'), + onRefresh: () => void request.refetch(), + onCancel: request.cancel ? () => void request.cancel?.() : undefined, + } + : undefined; + const storyProps = + props.story && + (findings.length + ? { + findings, + title: app.title, + scope, + dataContext, + theme: themeController, } - > - {presentation?.annotations?.enabled && ( - - )} - {toolbarActions} - - ); + : null); + const annotations = presentation?.annotations?.enabled ? ( + + ) : null; + const toolbar = hasToolbar ? ( + + } + > + {annotations} + {toolbarActions} + + ) : null; const searchRegion = request?.searchControls && props.showSearch !== false ? ( @@ -197,8 +202,20 @@ export function DataAppFrame( } > + {!hasToolbar && annotations} {isEmbedded ? ( - toolbar + <> + {transport && showActions && ( + + )} + ) : ( ('idle'); - const [retryTableName, setRetryTableName] = useState(); + async function download(table?: CsvTable) { - if (!csv?.tables.length) return; - setOpen(false); + if (!csv?.tables.length || status === 'pending') return; setRetryTableName(table?.name); setStatus('pending'); try { @@ -31,6 +30,31 @@ export function ExportControl({ csv }: { csv?: CsvExport }) { } } + const errorToast = + status === 'error' && csv ? ( + + void download(csv.tables.find(table => table.name === retryTableName)) + } + > + Couldn’t export data. + + ) : null; + + return { status, download, errorToast }; +} + +export function ExportControl({ csv }: { csv?: CsvExport }) { + const [open, setOpen] = useState(false); + const { status, download: runDownload, errorToast } = useCsvExport(csv); + + function download(table?: CsvTable) { + setOpen(false); + return runDownload(table); + } + if (!csv?.tables.length) { return ( - {status === 'error' && ( - - void download( - csv.tables.find(table => table.name === retryTableName) - ) - } - > - Couldn’t export data. - - )} + {errorToast} {csv.tables.length === 1 ? ( void; + onCancel?: () => void; + }; + /** Null offers a disabled export while its data is unavailable. */ + csvExport?: CsvExport | null; + /** Null offers a disabled story while its findings are unavailable. */ + story?: PresentStoryProps | null; + dataContext: DataContext; + queries?: DisclosedQuery[]; +}; + +/** Offers page actions to the embedding host instead of a toolbar, and renders the + * surfaces those actions open: the story presentation, inspection sheet, and export errors. */ +export function HostActions({ + transport, + refresh, + csvExport, + story, + dataContext, + queries, +}: HostActionsProps) { + const [aboutOpen, setAboutOpen] = useState(false); + const exporter = useCsvExport(csvExport ?? undefined); + // The story's open state lives in the URL, shared with Back/Forward and saved links. + const presenting = + useSyncExternalStore(subscribeSearch, isPresenting, () => false) && !!story; + const actions: DataAppActions = { + ...(refresh && { + refresh: { + refreshing: refresh.refreshing, + cancellable: refresh.onCancel !== undefined, + }, + }), + ...(csvExport !== undefined && { + exportCsv: { + enabled: !!csvExport?.tables.length && exporter.status !== 'pending', + tables: csvExport?.tables.map(table => table.name) ?? [], + }, + }), + ...(story !== undefined && { + presentStory: { enabled: !!story, presenting }, + }), + aboutData: { enabled: true }, + }; + + // Report the latest offer after every render; the transport skips unchanged sets. + // Bootstraps that predate page actions lack these methods, so the app offers none. + useEffect(() => { + transport.setActions?.(actions); + }); + useEffect(() => () => transport.setActions?.({}), [transport]); + + const run = useEffectEvent((action: DataAppAction) => { + switch (action.type) { + case 'refresh': + if (refresh && !refresh.refreshing) refresh.onRefresh(); + break; + case 'cancelRefresh': + if (refresh?.refreshing) refresh.onCancel?.(); + break; + case 'exportCsv': { + const table = + action.table === undefined + ? undefined + : csvExport?.tables.find(item => item.name === action.table); + if (action.table === undefined || table) void exporter.download(table); + break; + } + case 'presentStory': + if (story && !presenting) openStoryPresentation(story); + break; + case 'closeStory': + if (presenting) writeSearch({ present: null, step: null }); + break; + case 'aboutData': + setAboutOpen(true); + break; + } + }); + useEffect(() => transport.onAction?.(action => run(action)), [transport]); + + return ( + <> + {exporter.errorToast} + {story && } + + + ); +} diff --git a/packages/data-app-react/src/ui/PresentStory.tsx b/packages/data-app-react/src/ui/PresentStory.tsx index 6ad66286..64853cb6 100644 --- a/packages/data-app-react/src/ui/PresentStory.tsx +++ b/packages/data-app-react/src/ui/PresentStory.tsx @@ -44,8 +44,19 @@ export type PresentStoryProps = { theme?: ThemeController; headerActions?: ReactNode; footer?: ReactNode; + /** False renders only the presentation, which `?present=1&step=` opens. */ + trigger?: boolean; } & Omit, 'title'>; +/** Opens a rendered story at its first finding through the URL, as Back/Forward would. */ +export function openStoryPresentation({ + findings, + dataContext, +}: Pick) { + const first = storySteps(findings, dataContext)[0]; + if (first) writeSearch({ present: '1', step: first.id }, 'push'); +} + const stepKeys: Record number> = { ArrowRight(index) { return index + 1; @@ -80,6 +91,7 @@ export function PresentStory({ theme, headerActions, footer, + trigger: showTrigger = true, children, className, onClick, @@ -198,7 +210,11 @@ export function PresentStory({ writePresentation(firstStep.id, 'push'); } - useShortcut(shortcuts.playStory, openPresentation, !unavailable); + useShortcut( + shortcuts.playStory, + openPresentation, + showTrigger && !unavailable + ); function goTo(nextIndex: number) { const next = steps[nextIndex]; @@ -228,25 +244,27 @@ export function PresentStory({ return ( <> - - { - onClick?.(event); - if (!event.defaultPrevented) void openPresentation(); - }} - > - {children} - - + {showTrigger && ( + + { + onClick?.(event); + if (!event.defaultPrevented) void openPresentation(); + }} + > + {children} + + + )} (() => presentationFromBridgeState(getDataAppTransport()?.snapshot())); - - useEffect(() => { - let disposed = false; - let detach: (() => void) | undefined; - - function attach(bridge: IframeTransport) { - if (disposed) return; - const unsubscribe = bridge.subscribe(state => - setPresentation(presentationFromBridgeState(state)) - ); - // Bootstraps that predate content sizing cannot apply it. - const releaseSizing = bridge.supportContentSizing?.(); - setPresentation(presentationFromBridgeState(bridge.snapshot())); - detach = () => { - unsubscribe(); - releaseSizing?.(); - }; - } - - const bridge = getDataAppTransport(); - if (bridge) attach(bridge); - else - void localFrameBridge() - ?.connect?.() - .then(attach) - .catch(() => {}); - - return () => { - disposed = true; - detach?.(); - }; - }, []); - - return presentation; +export function useDataAppPresentation( + transport: IframeTransport | undefined +): DataAppPresentation | undefined { + const subscribe = useCallback( + (listener: () => void) => transport?.subscribe(listener) ?? (() => {}), + [transport] + ); + const state = useSyncExternalStore( + subscribe, + () => transport?.snapshot(), + () => undefined + ); + + // Bootstraps that predate content sizing cannot apply it. + useEffect(() => transport?.supportContentSizing?.(), [transport]); + + return presentationFromBridgeState(state); } diff --git a/packages/data-app-react/src/ui/useDataAppTransport.ts b/packages/data-app-react/src/ui/useDataAppTransport.ts new file mode 100644 index 00000000..80f6d07c --- /dev/null +++ b/packages/data-app-react/src/ui/useDataAppTransport.ts @@ -0,0 +1,30 @@ +import { + getDataAppTransport, + type IframeTransport, +} from '@altertable/data-app/client'; +import { localFrameBridge } from '@altertable/data-app/internal'; +import { useEffect, useState } from 'react'; + +/** The parent bridge, once installed or verified; undefined for standalone pages. */ +export function useDataAppTransport() { + const [transport, setTransport] = useState( + getDataAppTransport + ); + + useEffect(() => { + if (transport) return; + let disposed = false; + void localFrameBridge() + ?.connect?.() + .then(bridge => { + if (!disposed) setTransport(bridge); + }) + .catch(() => {}); + + return () => { + disposed = true; + }; + }, [transport]); + + return transport; +} diff --git a/packages/data-app/src/authoring/contract.ts b/packages/data-app/src/authoring/contract.ts index 4e6cb691..a3034b98 100644 --- a/packages/data-app/src/authoring/contract.ts +++ b/packages/data-app/src/authoring/contract.ts @@ -16,6 +16,7 @@ import { type CheckedOperationFilters, type FilterInput, } from '../core/operation-filters.ts'; +import { isRecord } from '../core/record.ts'; export type { DateTimeRangeInput, DateTimeRangePolicy, @@ -318,19 +319,13 @@ function operationInputContract( return { input: parseOwn, checks: operation.checks }; } function input(value: unknown) { - invariant( - value && typeof value === 'object' && !Array.isArray(value), - 'Expected operation input.' - ); + invariant(isRecord(value), 'Expected operation input.'); const own: Record = {}; const selected: Record = {}; for (const [name, field] of Object.entries(value)) (Object.hasOwn(filters, name) ? selected : own)[name] = field; const parsed = parseOwn(own); - invariant( - !!parsed && typeof parsed === 'object', - 'Expected parsed input object.' - ); + invariant(isRecord(parsed), 'Expected parsed input object.'); for (const name of Object.keys(parsed)) invariant( !Object.hasOwn(filters, name), diff --git a/packages/data-app/src/client/frame-sizing.ts b/packages/data-app/src/client/frame-sizing.ts index 78d2d239..0484703c 100644 --- a/packages/data-app/src/client/frame-sizing.ts +++ b/packages/data-app/src/client/frame-sizing.ts @@ -1,4 +1,5 @@ import { isDataAppPresentation } from '../core/presentation.ts'; +import { isRecord } from '../core/record.ts'; /** Reports the document height to a parent that sizes the iframe to its content. * Sizing applies only while the parent requests it and a UI owner whose styles support it @@ -55,10 +56,7 @@ export function createFrameSizing( return { /** A new session starts with a parent that has not received the current height. */ update(state: unknown, session: 'new' | 'current') { - const presentation = - state && typeof state === 'object' && 'presentation' in state - ? state.presentation - : undefined; + const presentation = isRecord(state) ? state.presentation : undefined; requested = isDataAppPresentation(presentation) && presentation.sizing === 'content'; diff --git a/packages/data-app/src/client/iframe.ts b/packages/data-app/src/client/iframe.ts index 0023d126..915317df 100644 --- a/packages/data-app/src/client/iframe.ts +++ b/packages/data-app/src/client/iframe.ts @@ -1,3 +1,4 @@ +import { type DataAppAction, type DataAppActions } from '../core/actions.ts'; import { createBridgeEndpoint } from '../core/bridge-endpoint.ts'; import { PARENT_PARAM, @@ -12,6 +13,7 @@ import { MessageRoutingError, type RoutedMessage, } from '../core/messages.ts'; +import { isRecord } from '../core/record.ts'; import { randomUuid } from '../core/uuid.ts'; import { appDiagnostics } from './diagnostics.ts'; import { createFrameSizing } from './frame-sizing.ts'; @@ -84,13 +86,15 @@ export function createIframeTransport({ }, 150); } const stateListeners = new Set<(state: unknown) => void>(); + // The page actions last offered to the host, compared by value. + let actions: DataAppActions = {}; + let actionsIdentity = '{}'; + const actionListeners = new Set<(action: DataAppAction) => void>(); const logger = createBridgeLogger( () => !disposed && !!sessionId && - !!hostState && - typeof hostState === 'object' && - 'logging' in hostState && + isRecord(hostState) && hostState.logging === true, entry => send('runtimeLog', { payload: entry }) ); @@ -129,11 +133,15 @@ export function createIframeTransport({ receiveState(message.state, 'new'); if (first) for (const entry of pending.values()) entry.start(); if (disposed) return; + if (actionsIdentity !== '{}') send('actionsUpdate', { actions }); if (mode === 'url') send('runtimeReady', {}); }, stateUpdate(message) { receiveState(message.state, 'current'); }, + actionRun(message) { + for (const listener of actionListeners) listener(message.action); + }, viewportUpdate(message) { frameSizing.viewport(message.top, message.bottom); }, @@ -295,6 +303,7 @@ export function createIframeTransport({ frame.removeEventListener('pagehide', disconnect); frame.removeEventListener('pageshow', resume); stateListeners.clear(); + actionListeners.clear(); } frame.addEventListener('pagehide', disconnect); @@ -332,6 +341,24 @@ export function createIframeTransport({ ready() { if (!disposed && sessionId) send('runtimeReady', {}); }, + /** Offers page actions to the host, replacing the previous set; `{}` withdraws them. + * Unchanged sets are not resent, so callers can report their latest set on every render. + * The current set is resent when the host reconnects. */ + setActions(value: DataAppActions) { + const identity = JSON.stringify(value); + if (disposed || identity === actionsIdentity) return; + actions = value; + actionsIdentity = identity; + if (sessionId) send('actionsUpdate', { actions }); + }, + /** Receives host requests to run offered page actions. */ + onAction(listener: (action: DataAppAction) => void) { + actionListeners.add(listener); + + return () => { + actionListeners.delete(listener); + }; + }, /** The UI owner calls this once its styles support content sizing; the parent's * `sizing: 'content'` presentation then applies until the returned release runs. */ supportContentSizing() { diff --git a/packages/data-app/src/client/index.ts b/packages/data-app/src/client/index.ts index 1d543d32..0b7df3d4 100644 --- a/packages/data-app/src/client/index.ts +++ b/packages/data-app/src/client/index.ts @@ -28,6 +28,7 @@ export { } from './iframe.ts'; export { createMessageClient } from './messages.ts'; export { type DataAppLogger } from '../core/logger.ts'; +export { type DataAppAction, type DataAppActions } from '../core/actions.ts'; export { createAnnotationClient } from './annotations.ts'; export { appDiagnostics } from './diagnostics.ts'; export { diff --git a/packages/data-app/src/core/actions.ts b/packages/data-app/src/core/actions.ts new file mode 100644 index 00000000..9dbdd3dc --- /dev/null +++ b/packages/data-app/src/core/actions.ts @@ -0,0 +1,100 @@ +import { isRecord } from './record.ts'; + +/** Page actions an embedded app offers its host, replaced as a whole on every change. + * An absent key means the app does not offer that action. */ +export type DataAppActions = { + /** Run `refresh`; while `refreshing`, run `cancelRefresh` if `cancellable`. */ + refresh?: { refreshing: boolean; cancellable: boolean }; + /** Run `exportCsv`. `tables` names the datasets an action's `table` may select. */ + exportCsv?: { enabled: boolean; tables: readonly string[] }; + /** Run `presentStory`; while `presenting`, run `closeStory`. */ + presentStory?: { enabled: boolean; presenting: boolean }; + /** Run `aboutData` to open the data inspector. */ + aboutData?: { enabled: boolean }; +}; + +/** A host request to run an offered page action. The app ignores unavailable actions. */ +export type DataAppAction = + | { type: 'refresh' } + | { type: 'cancelRefresh' } + /** Omit `table` to export every dataset, as a ZIP when there are several. */ + | { type: 'exportCsv'; table?: string } + | { type: 'presentStory' } + | { type: 'closeStory' } + | { type: 'aboutData' }; + +const MAX_TABLES = 64; + +export function parseDataAppActions(value: unknown): DataAppActions { + if (!isRecord(value)) throw new Error('Invalid actions.'); + const actions: DataAppActions = {}; + const { refresh, exportCsv } = value; + if (refresh !== undefined) { + if ( + !isRecord(refresh) || + typeof refresh.refreshing !== 'boolean' || + typeof refresh.cancellable !== 'boolean' + ) + throw new Error('Invalid refresh action.'); + actions.refresh = { + refreshing: refresh.refreshing, + cancellable: refresh.cancellable, + }; + } + if (exportCsv !== undefined) { + if ( + !isRecord(exportCsv) || + typeof exportCsv.enabled !== 'boolean' || + !Array.isArray(exportCsv.tables) || + exportCsv.tables.length > MAX_TABLES || + !exportCsv.tables.every( + table => typeof table === 'string' && table.length <= 256 + ) + ) + throw new Error('Invalid export action.'); + actions.exportCsv = { + enabled: exportCsv.enabled, + tables: [...(exportCsv.tables as string[])], + }; + } + const { presentStory } = value; + if (presentStory !== undefined) { + if ( + !isRecord(presentStory) || + typeof presentStory.enabled !== 'boolean' || + typeof presentStory.presenting !== 'boolean' + ) + throw new Error('Invalid story action.'); + actions.presentStory = { + enabled: presentStory.enabled, + presenting: presentStory.presenting, + }; + } + const { aboutData } = value; + if (aboutData !== undefined) { + if (!isRecord(aboutData) || typeof aboutData.enabled !== 'boolean') + throw new Error('Invalid inspection action.'); + actions.aboutData = { enabled: aboutData.enabled }; + } + return actions; +} + +export function parseDataAppAction(value: unknown): DataAppAction { + if (!isRecord(value)) throw new Error('Invalid action.'); + switch (value.type) { + case 'refresh': + case 'cancelRefresh': + case 'presentStory': + case 'closeStory': + case 'aboutData': + return { type: value.type }; + case 'exportCsv': + if (value.table !== undefined && typeof value.table !== 'string') + throw new Error('Invalid export table.'); + return value.table === undefined + ? { type: 'exportCsv' } + : { type: 'exportCsv', table: value.table }; + default: + throw new Error('Unknown action.'); + } +} diff --git a/packages/data-app/src/core/annotations.ts b/packages/data-app/src/core/annotations.ts index bc057753..6086cda2 100644 --- a/packages/data-app/src/core/annotations.ts +++ b/packages/data-app/src/core/annotations.ts @@ -1,4 +1,5 @@ import { defineMessageRoute } from './messages.ts'; +import { isRecord } from './record.ts'; export type DataAppAnnotationDraft = { id: string; @@ -34,7 +35,8 @@ export type DataAppAnnotationDraft = { export type DataAppAnnotationPresentation = { enabled: boolean; - /** When provided, the host owns the mode and renders the annotation trigger. */ + /** When provided, the host owns the mode and renders the annotation trigger. + * Without an in-frame toolbar, as on embedded surfaces, the host always owns it; omitted means inactive. */ active?: boolean; pinsVisible?: boolean; showHint?: boolean; @@ -290,8 +292,7 @@ export function isAnnotationPresentation( (typeof input.selectedAnnotationId === 'string' && input.selectedAnnotationId.length <= 128)) && (input.dismissal === undefined || - (input.dismissal !== null && - typeof input.dismissal === 'object' && + (isRecord(input.dismissal) && typeof input.dismissal.id === 'string' && input.dismissal.id.length <= 128 && typeof input.dismissal.occurredAt === 'number' && @@ -324,8 +325,7 @@ export function isAnnotationPresentation( target.anchor.y >= 0 && target.anchor.y <= 1)) && (target.region === undefined || - (typeof target.region === 'object' && - target.region !== null && + (isRecord(target.region) && ['x', 'y', 'width', 'height'].every(key => { const value = (target.region as Record)[key]; return ( diff --git a/packages/data-app/src/core/app-filters.ts b/packages/data-app/src/core/app-filters.ts index b8027a1e..0e1fa077 100644 --- a/packages/data-app/src/core/app-filters.ts +++ b/packages/data-app/src/core/app-filters.ts @@ -10,6 +10,7 @@ import type { NumberFilter, BooleanFilter } from './filters.ts'; import { invariant } from './invariant.ts'; import type { HistoryMode } from './navigation.ts'; import type { IsUnion } from './queries.ts'; +import { isRecord } from './record.ts'; export type { HistoryMode } from './navigation.ts'; /** Where a filter's or display option's control renders. */ @@ -84,9 +85,7 @@ export function defineAppFilters( const presentation = filter.presentation; invariant( presentation === undefined || - (presentation !== null && - typeof presentation === 'object' && - !Array.isArray(presentation) && + (isRecord(presentation) && (presentation.control === undefined || presentation.control === 'toolbar' || presentation.control === 'widget') && diff --git a/packages/data-app/src/core/appearance.ts b/packages/data-app/src/core/appearance.ts index c60480a4..c115ea93 100644 --- a/packages/data-app/src/core/appearance.ts +++ b/packages/data-app/src/core/appearance.ts @@ -13,6 +13,7 @@ import type { AppearanceSettings, AppearanceOptions, } from '../authoring/appearance.ts'; +import { isRecord } from './record.ts'; export type ThemeController = { getTheme: () => ThemePreference; @@ -39,10 +40,6 @@ const defaults: AppearanceSettings = { typography: { body: 'system', heading: 'system' }, }; -function record(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - function oneOf( value: unknown, options: readonly T[] @@ -65,8 +62,8 @@ function font(value: unknown): value is string { /** Preserve supported external settings and use defaults for invalid fields. */ export function parseAppearance(value: unknown): AppearanceSettings { - if (!record(value)) return normalizeAppearance(); - const typography = record(value.typography) ? value.typography : {}; + if (!isRecord(value)) return normalizeAppearance(); + const typography = isRecord(value.typography) ? value.typography : {}; return normalizeAppearance({ theme: oneOf(value.theme, ['light', 'dark', 'system']) diff --git a/packages/data-app/src/core/bridge-endpoint.ts b/packages/data-app/src/core/bridge-endpoint.ts index 58ce43c9..b69e4406 100644 --- a/packages/data-app/src/core/bridge-endpoint.ts +++ b/packages/data-app/src/core/bridge-endpoint.ts @@ -15,6 +15,7 @@ import { type BridgeEnvelope, type BridgeHandlers, } from './bridge.ts'; +import { isRecord } from './record.ts'; type ConnectionContext = Pick & { documentId?: string; @@ -86,12 +87,7 @@ export function createBridgeEndpoint({ const envelope = parseBridgeEnvelope(event.data); if (!envelope) { const data: unknown = event.data; - if ( - data && - typeof data === 'object' && - 'channel' in data && - data.channel === bridgeProtocol.channel - ) + if (isRecord(data) && data.channel === bridgeProtocol.channel) drop('invalid_envelope', 'type' in data ? data.type : undefined); return; } diff --git a/packages/data-app/src/core/bridge.ts b/packages/data-app/src/core/bridge.ts index 269344bd..b83207ec 100644 --- a/packages/data-app/src/core/bridge.ts +++ b/packages/data-app/src/core/bridge.ts @@ -1,4 +1,6 @@ +import { parseDataAppAction, parseDataAppActions } from './actions.ts'; import { isLogEntry } from './logger.ts'; +import { isRecord } from './record.ts'; /** Data app delivery protocol. IDs identify a document, a shell session, and an individual call. */ const BRIDGE = 'altertable:data-app'; @@ -174,6 +176,19 @@ export const bridgeProtocol = { session: 'current', parse: fields => ({ height: length(fields, 'height') }), }), + /** The page actions the app currently offers; replaces the previous set. */ + actionsUpdate: event({ + wire: 'actions:update', + from: 'app', + session: 'current', + parse: fields => ({ actions: parseDataAppActions(fields.actions) }), + }), + actionRun: event({ + wire: 'action:run', + from: 'host', + session: 'current', + parse: fields => ({ action: parseDataAppAction(fields.action) }), + }), /** CSS pixels of a content-sized frame hidden above and below the parent's visible area. */ viewportUpdate: event({ wire: 'viewport:update', @@ -239,9 +254,7 @@ export function bridgeMessageMetadata( const payload = message.payload; if ( message.route === 'data:query' && - payload && - typeof payload === 'object' && - 'operation' in payload && + isRecord(payload) && typeof payload.operation === 'string' ) metadata.operation = payload.operation.slice(0, 256); diff --git a/packages/data-app/src/core/date-time-filter.ts b/packages/data-app/src/core/date-time-filter.ts index c5b745c5..21c2a5cd 100644 --- a/packages/data-app/src/core/date-time-filter.ts +++ b/packages/data-app/src/core/date-time-filter.ts @@ -16,6 +16,7 @@ import { } from './date-time-range-value.ts'; import type { DateTimeRange } from './date-time-range.ts'; import { invariant } from './invariant.ts'; +import { isRecord } from './record.ts'; /** A picker suggestion. Text ranges use the same natural-language parser as typed input. */ export type DateTimeRangePreset = { @@ -159,11 +160,8 @@ export function dateTimeRangeFilter< value: unknown, now = new Date() ): DateTimeRangeSelection { - invariant( - !!value && typeof value === 'object' && !Array.isArray(value), - 'Choose a datetime range.' - ); - const selection = value as Record; + invariant(isRecord(value), 'Choose a datetime range.'); + const selection = value; invariant( Object.keys(selection).every( name => name === 'range' || name === 'comparison' @@ -245,11 +243,8 @@ export function dateTimeRangeFilter< presets, request, parseInput(value) { - invariant( - !!value && typeof value === 'object' && !Array.isArray(value), - 'Invalid datetime request.' - ); - const supplied = value as Record; + invariant(isRecord(value), 'Invalid datetime request.'); + const supplied = value; invariant( Object.keys(supplied).every(name => ['range', 'comparison', 'selection', 'reference'].includes(name) diff --git a/packages/data-app/src/core/date-time-range-value.ts b/packages/data-app/src/core/date-time-range-value.ts index 093f5d6b..54bd6380 100644 --- a/packages/data-app/src/core/date-time-range-value.ts +++ b/packages/data-app/src/core/date-time-range-value.ts @@ -9,6 +9,7 @@ import type { RelativeUnit, } from './date-time-range.ts'; import { invariant } from './invariant.ts'; +import { isRecord } from './record.ts'; import { fixedUnitMilliseconds } from './time-units.ts'; const anchors: Record = { @@ -35,13 +36,9 @@ export function parseDateTimeRange( value: unknown, { maxRangeDays }: { maxRangeDays?: number } = {} ): DateTimeRange { + invariant(isRecord(value), 'Choose a datetime range.'); invariant( - !!value && typeof value === 'object' && !Array.isArray(value), - 'Choose a datetime range.' - ); - const record = value as Record; - invariant( - Object.keys(record).every(key => key === 'from' || key === 'to'), + Object.keys(value).every(key => key === 'from' || key === 'to'), 'Unknown datetime range field.' ); function bound(raw: unknown): AbsoluteOrRelativeDateTime | null { @@ -55,41 +52,33 @@ export function parseDateTimeRange( ); return date; } + invariant(isRecord(raw), 'Invalid datetime bound.'); invariant( - typeof raw === 'object' && !Array.isArray(raw), - 'Invalid datetime bound.' - ); - const r = raw as Record; - invariant( - Object.keys(r).every(key => key === 'anchor' || key === 'offset') && - typeof r.anchor === 'string' && - Object.hasOwn(anchors, r.anchor), + Object.keys(raw).every(key => key === 'anchor' || key === 'offset') && + typeof raw.anchor === 'string' && + Object.hasOwn(anchors, raw.anchor), 'Invalid relative anchor.' ); invariant( - Array.isArray(r.offset) && r.offset.length <= 16, + Array.isArray(raw.offset) && raw.offset.length <= 16, 'Use at most 16 relative offsets.' ); - const offset = r.offset.map((o: unknown) => { - invariant( - !!o && typeof o === 'object' && !Array.isArray(o), - 'Invalid relative offset.' - ); - const v = o as Record; + const offset = raw.offset.map((o: unknown) => { + invariant(isRecord(o), 'Invalid relative offset.'); invariant( - Object.keys(v).every(key => key === 'amount' || key === 'unit') && - typeof v.amount === 'number' && - Number.isSafeInteger(v.amount) && - Math.abs(v.amount) <= 1_000_000 && - typeof v.unit === 'string' && - Object.hasOwn(units, v.unit), + Object.keys(o).every(key => key === 'amount' || key === 'unit') && + typeof o.amount === 'number' && + Number.isSafeInteger(o.amount) && + Math.abs(o.amount) <= 1_000_000 && + typeof o.unit === 'string' && + Object.hasOwn(units, o.unit), 'Invalid relative offset.' ); - return { amount: v.amount, unit: v.unit as RelativeUnit }; + return { amount: o.amount, unit: o.unit as RelativeUnit }; }); - return { anchor: r.anchor as RelativeAnchor, offset }; + return { anchor: raw.anchor as RelativeAnchor, offset }; } - const range = { from: bound(record.from), to: bound(record.to) }; + const range = { from: bound(value.from), to: bound(value.to) }; if (range.from instanceof Date && range.to instanceof Date) invariant(range.from < range.to, 'Start must be before end.'); invariant( diff --git a/packages/data-app/src/core/dimension-source.ts b/packages/data-app/src/core/dimension-source.ts index a50093dc..a378e70f 100644 --- a/packages/data-app/src/core/dimension-source.ts +++ b/packages/data-app/src/core/dimension-source.ts @@ -19,6 +19,7 @@ import { type QueryDefinitions, type QueryParameters, } from './queries.ts'; +import { isRecord } from './record.ts'; type Source = { query: string; queries: QueryDefinitions }; export const dimensionSource = Symbol('data-app.dimensionSource'); @@ -189,11 +190,8 @@ export function attachDimensionSelectors( ); selectors[name] = { input(value: unknown) { - invariant( - value && typeof value === 'object', - 'Invalid dimension request.' - ); - const member = (value as { member: unknown }).member; + invariant(isRecord(value), 'Invalid dimension request.'); + const member = value.member; invariant( member === null || filter.valid({ diff --git a/packages/data-app/src/core/dimension.ts b/packages/data-app/src/core/dimension.ts index 77a85bd7..8a01e19a 100644 --- a/packages/data-app/src/core/dimension.ts +++ b/packages/data-app/src/core/dimension.ts @@ -6,6 +6,7 @@ import type { import { facetSource } from './facets.ts'; import { invariant } from './invariant.ts'; import { KEY_SEPARATOR } from './keys.ts'; +import { isRecord } from './record.ts'; export type DimensionValue = string | number; export type DimensionMember = @@ -284,7 +285,7 @@ export function parseFacetOptions( const options: DimensionOption[] = []; const seen = new Set(); for (const item of value) { - invariant(item && typeof item === 'object', 'Invalid facet option.'); + invariant(isRecord(item), 'Invalid facet option.'); const option = item as DimensionOption; invariant( typeof option.value === filter.valueType && diff --git a/packages/data-app/src/core/external-link.ts b/packages/data-app/src/core/external-link.ts index 8aad2f70..377a7c07 100644 --- a/packages/data-app/src/core/external-link.ts +++ b/packages/data-app/src/core/external-link.ts @@ -1,4 +1,5 @@ import { defineMessageRoute } from './messages.ts'; +import { isRecord } from './record.ts'; /** Absolute HTTPS destinations only; URLs must not contain embedded credentials. */ export function parseExternalUrl(value: unknown): string { @@ -53,12 +54,8 @@ export const openExternalLinkRoute = /* @__PURE__ */ defineMessageRoute({ if (input.target === undefined) return { url }; if (input.target === 'tab' || input.target === 'window') return { url, target: input.target }; - if ( - input.target === 'event' && - input.keys && - typeof input.keys === 'object' - ) { - const keys = input.keys as Record; + if (input.target === 'event' && isRecord(input.keys)) { + const keys = input.keys; if ( typeof keys.shiftKey === 'boolean' && typeof keys.metaKey === 'boolean' && diff --git a/packages/data-app/src/core/filters.ts b/packages/data-app/src/core/filters.ts index 5f2639c4..77fb8f5e 100644 --- a/packages/data-app/src/core/filters.ts +++ b/packages/data-app/src/core/filters.ts @@ -4,6 +4,7 @@ import { type FilterPresentation, } from './app-filters.ts'; import { invariant } from './invariant.ts'; +import { isRecord } from './record.ts'; export type NumberOperator = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; export type NumberSelection = @@ -154,8 +155,7 @@ export function booleanFilter({ invariant(!!key.trim(), 'Boolean filter requires a URL key.'); function valid(value: BooleanSelection) { return ( - !!value && - typeof value === 'object' && + isRecord(value) && (value.kind === 'all' || (value.kind === 'is' && typeof value.value === 'boolean')) ); diff --git a/packages/data-app/src/core/messages.ts b/packages/data-app/src/core/messages.ts index 3ab7c003..9411cf84 100644 --- a/packages/data-app/src/core/messages.ts +++ b/packages/data-app/src/core/messages.ts @@ -7,6 +7,7 @@ import { type OutputOf, } from './operation-types.ts'; import { isQueryParameters, type QueryParameters } from './queries.ts'; +import { isRecord } from './record.ts'; export { type OperationContracts, type DataQueryInput, @@ -229,8 +230,7 @@ export function defineDataQueryRoute< (!Array.isArray(body.queries) || !body.queries.every( query => - query && - typeof query === 'object' && + isRecord(query) && typeof query.name === 'string' && typeof query.statement === 'string' && (query.params === undefined || isQueryParameters(query.params)) && diff --git a/packages/data-app/src/core/queries.ts b/packages/data-app/src/core/queries.ts index b9da271b..4ce2fa1b 100644 --- a/packages/data-app/src/core/queries.ts +++ b/packages/data-app/src/core/queries.ts @@ -10,6 +10,7 @@ import { expandParameterReferences, type StructuredParameter, } from './parameter-sql.ts'; +import { isRecord } from './record.ts'; export const MAX_QUERY_ROWS = 10_000; @@ -183,8 +184,7 @@ function serializeSelection( typeof value === 'string' ? JSON.parse(value) : value ) as DimensionSelection; const valid = - !!selection && - typeof selection === 'object' && + isRecord(selection) && (selection.kind === 'all' || ((selection.kind === 'include' || selection.kind === 'exclude') && Array.isArray(selection.members) && @@ -222,21 +222,14 @@ function isQueryParameterValue(value: unknown): value is QueryParameterValue { } export function isQueryParameters(value: unknown): value is QueryParameters { - return ( - !!value && - typeof value === 'object' && - !Array.isArray(value) && - Object.values(value).every(isQueryParameterValue) - ); + return isRecord(value) && Object.values(value).every(isQueryParameterValue); } function snapshotField( field: Field ): Readonly { invariant( - field && - typeof field === 'object' && - !Array.isArray(field) && + isRecord(field) && (field.type === 'string' || field.type === 'number' || field.type === 'boolean' || diff --git a/packages/data-app/src/core/record.ts b/packages/data-app/src/core/record.ts new file mode 100644 index 00000000..b9c05ff3 --- /dev/null +++ b/packages/data-app/src/core/record.ts @@ -0,0 +1,4 @@ +/** A non-null, non-array object, as parsed from JSON or received over the bridge. */ +export function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/tests/public-api/apps-annotations.test.ts b/tests/public-api/apps-annotations.test.ts index ad7f2a98..ab9302e9 100644 --- a/tests/public-api/apps-annotations.test.ts +++ b/tests/public-api/apps-annotations.test.ts @@ -30,7 +30,7 @@ for (const failure of [false, true]) { const revenueCard = await app .getByRole('region', { name: 'Revenue by month', exact: true }) .boundingBox(); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const selection = app.getByRole('button', { name: 'Annotation selection', exact: true, @@ -121,15 +121,18 @@ test('feedback retains the displayed input while a newer filter is still loading }) => { await page.goto('/annotations-host?annotations&annotation-state'); const app = page.frameLocator('iframe'); + // Retained data shows while the advanced period loads. + await expect + .poll(() => app.getByText('42', { exact: true }).isVisible()) + .toBe(true); await expect .poll(() => - app - .getByRole('group', { name: 'Page actions', exact: true }) - .getByText('Updating data', { exact: true }) - .isVisible() + page + .getByRole('status', { name: 'App refreshing', exact: true }) + .textContent() ) - .toBe(true); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + .toBe('true'); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const selection = app.getByRole('button', { name: 'Annotation selection', exact: true, @@ -250,7 +253,14 @@ test('narrative cards sharing evidence remain separate whole-card annotation tar }); const card = await narrative.boundingBox(); expect(card).toBeTruthy(); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); + await expect + .poll(() => + app + .getByRole('button', { name: 'Annotation selection', exact: true }) + .isVisible() + ) + .toBe(true); await page.mouse.click(card!.x + card!.width / 2, card!.y + card!.height / 2); const comment = app.getByRole('textbox', { name: 'Annotation text', @@ -283,7 +293,7 @@ test('outside clicks cancel unfinished edits and require a second click to selec const card = await app .getByRole('region', { name: 'Customers', exact: true }) .boundingBox(); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const selection = app.getByRole('button', { name: 'Annotation selection', exact: true, @@ -325,7 +335,7 @@ test('annotation mode scrolls by wheel and page keys while selected geometry fol }) => { await page.goto('/annotations-host?annotations&annotation-scroll'); const app = page.frameLocator('iframe'); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const selection = app.getByRole('button', { name: 'Annotation selection', exact: true, @@ -368,7 +378,7 @@ for (const [title, expectedId] of [ }) => { await page.goto('/annotations-host?annotations'); const app = page.frameLocator('iframe'); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const selection = app.getByRole('button', { name: 'Annotation selection', exact: true, @@ -402,7 +412,7 @@ test('touch panning preserves unfinished comments and an outside tap dismisses t }) => { await page.goto('/annotations-host?annotations&annotation-scroll'); const app = page.frameLocator('iframe'); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const selection = app.getByRole('button', { name: 'Annotation selection', exact: true, @@ -482,7 +492,7 @@ test('mouse region selection and saved pins follow the report while scrolling', }) => { await page.goto('/annotations-host?annotations&annotation-scroll'); const app = page.frameLocator('iframe'); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const layer = await app .getByRole('button', { name: 'Annotation selection', exact: true }) .boundingBox(); @@ -525,7 +535,7 @@ test('window deactivation and tab switching preserve unfinished comments until a }) => { await page.goto('/annotations-host?annotations'); const app = page.frameLocator('iframe'); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const selection = app.getByRole('button', { name: 'Annotation selection', exact: true, @@ -592,7 +602,7 @@ test('a delayed host dismissal cannot close an editor opened by a later selectio const card = await app .getByRole('region', { name: 'Customers', exact: true }) .boundingBox(); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const selection = app.getByRole('button', { name: 'Annotation selection', exact: true, @@ -658,7 +668,7 @@ test('saved collision fallback targets still resolve when their evidence becomes }) => { await page.goto('/annotations-host?annotations'); const app = page.frameLocator('iframe'); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const selection = app.getByRole('button', { name: 'Annotation selection', exact: true, @@ -699,7 +709,7 @@ test('explicit annotation identities remain authoritative alongside automatic ev '/annotations-host?annotations&annotation-explicit-collision' ); const app = page.frameLocator('iframe'); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const selection = app.getByRole('button', { name: 'Annotation selection', exact: true, @@ -737,7 +747,7 @@ test('a narrative retains its legacy evidence identity from loading through read .getByRole('button', { name: 'Explore Loading narrative', exact: true }) .count() ).toBe(0); - await app.getByRole('button', { name: 'Annotate', exact: true }).click(); + await page.getByRole('button', { name: 'Annotate', exact: true }).click(); const selection = app.getByRole('button', { name: 'Annotation selection', exact: true, diff --git a/tests/public-api/apps-authoring.test.ts b/tests/public-api/apps-authoring.test.ts index 2df9b284..8004ee5c 100644 --- a/tests/public-api/apps-authoring.test.ts +++ b/tests/public-api/apps-authoring.test.ts @@ -35,12 +35,12 @@ describe('authoring', () => { const app = page.frameLocator('iframe'); await expect .poll(() => - app - .getByRole('group', { name: 'Page actions', exact: true }) - .filter({ hasText: 'Loading data' }) - .isVisible() + page + .getByRole('group', { name: 'Host page actions', exact: true }) + .getByRole('button', { name: /refresh/ }) + .getAttribute('aria-busy') ) - .toBe(true); + .toBe('true'); await expect .poll(() => @@ -80,13 +80,13 @@ describe('authoring', () => { .toBe(0); await expect .poll(() => - app + page .getByRole('button', { name: 'Present story', exact: true }) .isDisabled() ) .toBe(true); const stableActions = ['Explore data', 'Export CSV', 'Present story'].map( - name => app.getByRole('button', { name, exact: true }) + name => page.getByRole('button', { name, exact: true }) ); await expect.poll(() => stableActions[1]!.isDisabled()).toBe(true); @@ -116,7 +116,7 @@ describe('authoring', () => { .evaluate(element => element.clientWidth); expect(width).toBeLessThanOrEqual(page.viewportSize()!.width); const queryCountBeforeStory = requests.length; - await app + await page .getByRole('button', { name: 'Present story', exact: true }) .click(); const story = app.getByRole('dialog'); @@ -162,12 +162,12 @@ describe('authoring', () => { .toBe(true); await expect .poll(() => - app - .getByRole('group', { name: 'Page actions', exact: true }) - .getByText('Updating data', { exact: true }) - .isVisible() + page + .getByRole('group', { name: 'Host page actions', exact: true }) + .getByRole('button', { name: /refresh/ }) + .getAttribute('aria-busy') ) - .toBe(true); + .toBe('true'); release!(); gate = Promise.resolve(); await expect @@ -207,7 +207,7 @@ describe('authoring', () => { .isVisible() ) .toBe(true); - await app + await page .getByRole('button', { name: 'Present story', exact: true }) .click(); await expect @@ -251,7 +251,7 @@ describe('authoring', () => { .toBe(true); await expect .poll(() => - app + page .getByRole('button', { name: 'Present story', exact: true }) .isDisabled() ) @@ -276,7 +276,7 @@ describe('authoring', () => { ) .toBe(true); const before = requests.length; - await app + await page .getByRole('button', { name: 'Refresh data', exact: true }) .click(); await expect.poll(() => requests.length).toBeGreaterThan(before); @@ -307,7 +307,7 @@ describe('authoring', () => { expect(totalRequests.every(request => request.limit === 1)).toBe(true); await expect .poll(() => - app + page .getByRole('button', { name: 'Refresh data', exact: true }) .isVisible() ) @@ -338,14 +338,14 @@ describe('authoring', () => { .toBe(true); await expect .poll(() => - app + page .getByRole('button', { name: 'Export CSV', exact: true }) .isDisabled() ) .toBe(true); await expect .poll(() => - app + page .getByRole('button', { name: 'Present story', exact: true }) .isDisabled() ) diff --git a/tests/public-api/apps-diagnostics.test.ts b/tests/public-api/apps-diagnostics.test.ts index 2aa4e052..c0e51207 100644 --- a/tests/public-api/apps-diagnostics.test.ts +++ b/tests/public-api/apps-diagnostics.test.ts @@ -1,5 +1,3 @@ -import { mkdir } from 'node:fs/promises'; - import type { Locator } from 'playwright'; import { expect } from 'vitest'; @@ -12,9 +10,6 @@ async function clickAt(button: Locator) { .mouse.click(box.x + box.width / 2, box.y + box.height / 2); } -const screenshotRoot = - process.env.DATA_APP_SCREENSHOT_DIR ?? '/tmp/data-app-diagnostics'; - test('public widget renderers isolate early failures without changing healthy grid and inline layout', async ({ page, }) => { @@ -133,7 +128,7 @@ test('overflow failures remain visible and repairable after earlier widgets are test('independent widget and operation failures share latest repair report and preserve layout', async ({ page, }) => { - await page.goto('/diagnostics?progress'); + await page.goto('/diagnostics'); const frame = page.frameLocator('iframe'); await expect.poll(() => frame.getByText('Chart ready').count()).toBe(2); const widget = frame.getByRole('region', { name: 'Revenue', exact: true }); @@ -173,27 +168,6 @@ test('independent widget and operation failures share latest repair report and p await expect .poll(() => page.getByLabel('Repair delivery status').textContent()) .toBe('accepted'); - const banner = page.getByRole('region', { name: 'App errors' }); - const copyBounds = (await banner - .getByRole('button', { name: 'Copy diagnostics', exact: true }) - .boundingBox())!; - const fixBounds = (await banner - .getByRole('button', { name: 'Fix errors', exact: true }) - .boundingBox())!; - expect(fixBounds.x).toBeGreaterThanOrEqual(copyBounds.x + copyBounds.width); - expect(fixBounds.y).toBe(copyBounds.y); - await expect - .poll(() => - banner - .getByRole('status', { name: 'Repair request status' }) - .textContent() - ) - .toContain('Preparing a fix'); - expect(await banner.textContent()).toContain( - 'You can keep using the rest of the app.' - ); - expect(await banner.textContent()).not.toContain('Repair request accepted'); - expect(await banner.getByText('View diagnostics').count()).toBe(0); // Keyboard activation of the widget uses the same whole-report request. const repair = frame.getByRole('button', { name: 'Fix error' }).first(); await repair.focus(); @@ -226,48 +200,6 @@ test('independent widget and operation failures share latest repair report and p ) ).toBe(true); await expect.poll(() => repair.isEnabled()).toBe(true); - await mkdir(screenshotRoot, { recursive: true }); - await banner.screenshot({ - path: `${screenshotRoot}/diagnostics-banner-light.png`, - animations: 'disabled', - }); - await page - .getByRole('region', { name: 'App preview', exact: true }) - .screenshot({ - path: `${screenshotRoot}/diagnostics-light.png`, - animations: 'disabled', - }); - await page.getByRole('button', { name: 'working', exact: true }).click(); - await page.getByRole('button', { name: 'Change theme' }).click(); - await page.setViewportSize({ width: 375, height: 1100 }); - await page.emulateMedia({ reducedMotion: 'reduce' }); - expect( - await banner - .getByRole('progressbar', { name: 'Repair in progress' }) - .evaluate(node => getComputedStyle(node).animationName) - ).toBe('none'); - await expect - .poll(() => - frame - .locator(':root') - .evaluate(element => getComputedStyle(element).colorScheme) - ) - .toBe('dark'); - await banner.screenshot({ - path: `${screenshotRoot}/diagnostics-banner-dark-narrow.png`, - animations: 'disabled', - }); - await page - .getByRole('region', { name: 'App preview', exact: true }) - .screenshot({ - path: `${screenshotRoot}/diagnostics-dark-narrow.png`, - animations: 'disabled', - }); - expect( - await page.evaluate( - () => document.documentElement.scrollWidth <= innerWidth - ) - ).toBe(true); await frame.getByRole('button', { name: 'Hide failed widgets' }).click(); await expect .poll(() => page.getByLabel('Observed app errors').textContent()) @@ -275,7 +207,6 @@ test('independent widget and operation failures share latest repair report and p await expect .poll(() => page.getByRole('region', { name: 'App errors' }).isVisible()) .toBe(true); - await page.getByRole('button', { name: 'review', exact: true }).click(); await page.getByRole('button', { name: 'Fix errors' }).click(); await expect .poll(() => page.getByLabel('Repair requests').textContent()) @@ -312,23 +243,19 @@ test('fourth failing revision and recreated/reloaded viewers keep automatic allo } } await expect - .poll(() => page.getByRole('region', { name: 'App errors' }).textContent()) - .toContain('Automatic fixes are paused'); + .poll(() => page.getByLabel('Observed app errors').textContent()) + .not.toBe('0'); + expect(await page.getByLabel('Repair delivery status').textContent()).toBe( + 'idle' + ); expect(await page.getByLabel('Repair requests').textContent()).toBe('3'); - await mkdir(screenshotRoot, { recursive: true }); - await page - .getByRole('region', { name: 'App preview', exact: true }) - .screenshot({ - path: `${screenshotRoot}/diagnostics-limit.png`, - animations: 'disabled', - }); await page.getByRole('button', { name: 'Recreate viewer' }).click(); await frame.getByRole('button', { name: 'Break widgets' }).click(); await page.reload(); await frame.getByRole('button', { name: 'Break widgets' }).click(); await expect - .poll(() => page.getByRole('region', { name: 'App errors' }).textContent()) - .toContain('Automatic fixes are paused'); + .poll(() => page.getByRole('region', { name: 'App errors' }).count()) + .toBe(1); expect(await page.getByLabel('Repair requests').textContent()).toBe('3'); await page.getByRole('button', { name: 'Fix errors' }).click(); await expect @@ -349,10 +276,8 @@ for (const failure of ['save-failure', 'delivery-failure']) { const frame = page.frameLocator('iframe'); await frame.getByRole('button', { name: 'Break widgets' }).click(); await expect - .poll(() => - page.getByRole('region', { name: 'App errors' }).textContent() - ) - .toContain('could not be saved or delivered'); + .poll(() => page.getByLabel('Repair delivery status').textContent()) + .toBe('failed'); const before = failure === 'save-failure' ? '0' : '1'; expect(await page.getByLabel('Repair requests').textContent()).toBe(before); await frame.getByRole('button', { name: 'Break widgets' }).click(); @@ -368,10 +293,10 @@ for (const failure of ['save-failure', 'delivery-failure']) { }); } -test('multiple banner and widget buttons cannot bypass shared serialization', async ({ +test('multiple host and widget buttons cannot bypass shared serialization', async ({ page, }) => { - await page.goto('/diagnostics?progress'); + await page.goto('/diagnostics'); const frame = page.frameLocator('iframe'); await frame.getByRole('button', { name: 'Break widgets' }).click(); await expect @@ -380,7 +305,6 @@ test('multiple banner and widget buttons cannot bypass shared serialization', as await expect .poll(() => page.getByLabel('Repair delivery status').textContent()) .toBe('accepted'); - await page.getByRole('button', { name: 'review', exact: true }).click(); // Rapid clicks land wherever the buttons were, even after one becomes disabled. const targets = []; for (const button of [ @@ -402,15 +326,18 @@ test('multiple banner and widget buttons cannot bypass shared serialization', as ).toBe(1); }); -test('unsupported host exposes diagnostics and a manual recovery instruction', async ({ +test('an unsupported host cannot request repairs from the host or widgets', async ({ page, }) => { await page.goto('/diagnostics?unsupported'); const frame = page.frameLocator('iframe'); await frame.getByRole('button', { name: 'Break widgets' }).click(); await expect - .poll(() => page.getByRole('region', { name: 'App errors' }).textContent()) - .toContain('Copy the diagnostics into your agent'); + .poll(() => page.getByRole('region', { name: 'App errors' }).count()) + .toBe(1); + expect(await page.getByLabel('Repair delivery status').textContent()).toBe( + 'unsupported' + ); expect( await page.getByRole('button', { name: 'Fix errors' }).isDisabled() ).toBe(true); @@ -418,91 +345,6 @@ test('unsupported host exposes diagnostics and a manual recovery instruction', a await frame.getByRole('button', { name: 'Fix error' }).first().isDisabled() ).toBe(true); expect(await page.getByLabel('Repair requests').textContent()).toBe('0'); - await page.context().grantPermissions(['clipboard-read', 'clipboard-write']); - const copy = page.getByRole('button', { name: 'Copy diagnostics' }); - await copy.focus(); - await page.keyboard.press('Enter'); - await expect - .poll(() => page.evaluate(() => navigator.clipboard.readText())) - .toContain('"failures":'); - const copied = await page.evaluate(() => navigator.clipboard.readText()); - const report = JSON.parse(copied); - expect(report.failures).toHaveLength(6); - expect(report.pending).toBe(0); - expect(report.truncated).toBe(0); - expect(JSON.stringify(report)).not.toContain('sourcesContent'); - const banner = page.getByRole('region', { name: 'App errors' }); - expect(await banner.textContent()).not.toContain('Live SDK operations'); - expect(await banner.textContent()).not.toContain('Diagnostics copied.'); - await mkdir(screenshotRoot, { recursive: true }); - await page - .getByRole('region', { name: 'App preview', exact: true }) - .screenshot({ - path: `${screenshotRoot}/diagnostics-copy-light.png`, - animations: 'disabled', - }); - await page.getByRole('button', { name: 'Change theme' }).click(); - await page.setViewportSize({ width: 375, height: 1100 }); - await expect - .poll(() => - frame - .locator(':root') - .evaluate(element => getComputedStyle(element).colorScheme) - ) - .toBe('dark'); - await page - .getByRole('region', { name: 'App preview', exact: true }) - .screenshot({ - path: `${screenshotRoot}/diagnostics-copy-dark-narrow.png`, - animations: 'disabled', - }); - expect( - await page.evaluate( - () => document.documentElement.scrollWidth <= innerWidth - ) - ).toBe(true); - await frame.getByRole('button', { name: 'Hide failed widgets' }).click(); - await expect - .poll(() => page.getByLabel('Observed app errors').textContent()) - .toBe('4'); - - await copy.click(); - await expect - .poll(() => page.evaluate(() => navigator.clipboard.readText())) - .not.toBe(copied); - const latest = JSON.parse( - await page.evaluate(() => navigator.clipboard.readText()) - ); - expect(latest.failures).toHaveLength(4); - expect(await page.getByLabel('Repair requests').textContent()).toBe('0'); -}); - -test('clipboard rejection keeps a selectable complete report for manual recovery', async ({ - page, -}) => { - await page.goto('/diagnostics?unsupported'); - await page - .frameLocator('iframe') - .getByRole('button', { name: 'Break widgets' }) - .click(); - await page.context().grantPermissions([]); - await page.getByRole('button', { name: 'Copy diagnostics' }).click(); - await expect - .poll(() => - page - .getByRole('status', { name: 'Diagnostic clipboard status' }) - .textContent() - ) - .toContain('Couldn’t copy.'); - const report = JSON.parse( - (await page - .getByRole('region', { name: 'App errors' }) - .getByText(/"failures":/) - .textContent())! - ); - expect(report.failures).toHaveLength(6); - expect(report.pending).toBe(0); - expect(report.truncated).toBe(0); }); test('explicit widget widths remain stable when rendering fails at wide and narrow widths', async ({ @@ -528,180 +370,35 @@ test('explicit widget widths remain stable when rendering fails at wide and narr } }); -test('preparation stays loading after acceptance and transitions to activity, review and completion', async ({ +test('a repair request stays pending until the host accepts or rejects it', async ({ page, }) => { - await page.goto('/diagnostics?progress&controlled-delivery'); + await page.goto('/diagnostics?controlled-delivery'); const frame = page.frameLocator('iframe'); - const banner = page.getByRole('region', { name: 'App errors' }); - const status = banner.getByLabel('Repair request status'); - const loading = banner.getByRole('progressbar', { - name: 'Repair in progress', - }); - const fix = banner.getByRole('button', { name: 'Fix errors', exact: true }); + const status = page.getByLabel('Repair delivery status'); + const fix = page.getByRole('button', { name: 'Fix errors', exact: true }); await frame.getByRole('button', { name: 'Break widgets' }).click(); - await expect - .poll(() => page.getByLabel('Repair delivery status').textContent()) - .toBe('pending'); - expect(await status.textContent()).toContain('Preparing a fix'); - expect(await loading.isVisible()).toBe(true); - expect(await fix.isDisabled()).toBe(true); - await page - .getByRole('button', { name: 'Accept repair request', exact: true }) - .click(); - await expect - .poll(() => page.getByLabel('Repair delivery status').textContent()) - .toBe('accepted'); - expect(await status.textContent()).toContain('Preparing a fix'); - expect(await loading.isVisible()).toBe(true); + await expect.poll(() => status.textContent()).toBe('pending'); expect(await fix.isDisabled()).toBe(true); - expect( - await banner - .getByRole('button', { name: 'Copy diagnostics', exact: true }) - .isEnabled() - ).toBe(true); // Native disabled controls cannot issue another request when clicked. await clickAt(fix); expect(await page.getByLabel('Repair requests').textContent()).toBe('1'); - await page.getByRole('button', { name: 'working', exact: true }).click(); - await expect.poll(() => status.textContent()).toContain('Updating your app'); - expect(await loading.isVisible()).toBe(true); - expect(await fix.isDisabled()).toBe(true); - await page.getByRole('button', { name: 'review', exact: true }).click(); - await expect - .poll(() => status.textContent()) - .toContain('The app still needs attention'); - expect(await loading.count()).toBe(0); + await page + .getByRole('button', { name: 'Accept repair request', exact: true }) + .click(); + await expect.poll(() => status.textContent()).toBe('accepted'); expect(await fix.isEnabled()).toBe(true); await fix.click(); - expect(await fix.isDisabled()).toBe(true); - await clickAt(fix); + await expect.poll(() => status.textContent()).toBe('pending'); expect(await page.getByLabel('Repair requests').textContent()).toBe('2'); - await expect.poll(() => status.textContent()).toContain('Preparing a fix'); - expect(await loading.isVisible()).toBe(true); - await page.getByRole('button', { name: 'loading', exact: true }).click(); - expect(await status.textContent()).toContain('Preparing a fix'); - expect(await fix.isDisabled()).toBe(true); await page .getByRole('button', { name: 'Reject repair request', exact: true }) .click(); - await expect - .poll(() => status.textContent()) - .toContain('Couldn’t request a fix'); - expect(await loading.count()).toBe(0); + await expect.poll(() => status.textContent()).toBe('failed'); expect(await fix.isEnabled()).toBe(true); - await fix.click(); - await expect.poll(() => status.textContent()).toContain('Preparing a fix'); - expect(await loading.isVisible()).toBe(true); - await page - .getByRole('button', { name: 'Accept repair request', exact: true }) - .click(); - await expect - .poll(() => page.getByLabel('Repair delivery status').textContent()) - .toBe('accepted'); - expect(await status.textContent()).toContain('Preparing a fix'); - expect(await loading.isVisible()).toBe(true); - await page.getByRole('button', { name: 'working', exact: true }).click(); - await expect.poll(() => status.textContent()).toContain('Updating your app'); - expect(await loading.isVisible()).toBe(true); + await frame.getByRole('button', { name: 'Hide failed widgets' }).click(); await frame.getByRole('button', { name: 'Healthy clicks 0' }).click(); expect( await frame.getByRole('button', { name: 'Healthy clicks 1' }).isVisible() ).toBe(true); - await page - .getByRole('button', { name: 'Finish update', exact: true }) - .click(); - await expect.poll(() => banner.count()).toBe(0); -}); - -test('elapsed time starts with preparation, continues through activity and revisions, and resets for a retry', async ({ - page, -}) => { - await page.goto('/diagnostics?progress&controlled-delivery&automatic-limit'); - const frame = page.frameLocator('iframe'); - await expect.poll(() => frame.getByText('Chart ready').count()).toBe(2); - await frame.getByRole('button', { name: 'Break widgets' }).click(); - await expect - .poll(() => - page.getByRole('button', { name: 'Fix errors', exact: true }).isEnabled() - ) - .toBe(true); - // The installed clock keeps running until paused, so pause at a later time. - await page.clock.install({ time: new Date('2026-10-27T09:00:00Z') }); - await page.clock.pauseAt(new Date('2026-10-27T10:00:00Z')); - const banner = page.getByRole('region', { name: 'App errors' }); - const status = banner.getByLabel('Repair request status'); - const fix = banner.getByRole('button', { name: 'Fix errors', exact: true }); - const accept = page.getByRole('button', { - name: 'Accept repair request', - exact: true, - }); - await fix.click(); - await expect.poll(() => status.textContent()).toContain('Preparing a fix'); - expect(await banner.getByText(/\d+s elapsed/).count()).toBe(0); - await page.clock.runFor(999); - expect(await banner.getByText(/\d+s elapsed/).count()).toBe(0); - await page.clock.runFor(1); - expect( - await banner.getByText('1s elapsed', { exact: true }).isVisible() - ).toBe(true); - await accept.click(); - await expect - .poll(() => page.getByLabel('Repair delivery status').textContent()) - .toBe('accepted'); - await page.clock.runFor(2000); - expect(await status.textContent()).toContain('Preparing a fix'); - expect( - await banner.getByText('3s elapsed', { exact: true }).isVisible() - ).toBe(true); - await page.getByRole('button', { name: 'working', exact: true }).click(); - expect( - await banner.getByText('3s elapsed', { exact: true }).isVisible() - ).toBe(true); - await page.clock.runFor(1000); - expect( - await banner.getByText('4s elapsed', { exact: true }).isVisible() - ).toBe(true); - await page.getByRole('button', { name: 'review', exact: true }).click(); - expect(await banner.getByText(/\d+s elapsed/).count()).toBe(0); - await fix.click(); - await expect.poll(() => status.textContent()).toContain('Preparing a fix'); - expect(await banner.getByText(/\d+s elapsed/).count()).toBe(0); - await page.clock.runFor(999); - expect(await banner.getByText(/\d+s elapsed/).count()).toBe(0); - await page.clock.runFor(1); - expect( - await banner.getByText('1s elapsed', { exact: true }).isVisible() - ).toBe(true); - await accept.click(); - await page.getByRole('button', { name: 'building', exact: true }).click(); - expect(await fix.isDisabled()).toBe(true); - expect( - await banner.getByText('1s elapsed', { exact: true }).isVisible() - ).toBe(true); - await page - .getByRole('button', { name: 'Next revision', exact: true }) - .click(); - await expect.poll(() => frame.getByText('Chart ready').count()).toBe(2); - await page.getByRole('button', { name: 'loading', exact: true }).click(); - expect(await fix.isDisabled()).toBe(true); - await page.context().grantPermissions(['clipboard-read', 'clipboard-write']); - await banner - .getByRole('button', { name: 'Copy diagnostics', exact: true }) - .click(); - await expect - .poll( - async () => - JSON.parse(await page.evaluate(() => navigator.clipboard.readText())) - .failures.length - ) - .toBe(6); - expect( - await banner.getByText('1s elapsed', { exact: true }).isVisible() - ).toBe(true); - expect(await banner.textContent()).not.toContain('0s elapsed'); - await page - .getByRole('button', { name: 'Finish update', exact: true }) - .click(); - await expect.poll(() => banner.count()).toBe(0); }); diff --git a/tests/public-api/apps-embedding.test.ts b/tests/public-api/apps-embedding.test.ts index 5665dec9..01cde8a7 100644 --- a/tests/public-api/apps-embedding.test.ts +++ b/tests/public-api/apps-embedding.test.ts @@ -602,7 +602,7 @@ for (const source of ['bundle', 'packaged', 'url']) { }); } -test('a content-sized frame follows its app height and keeps its toolbar and sheets usable', async ({ +test('a content-sized frame follows its app height and keeps host actions and sheets usable', async ({ page, }) => { await page.goto('/bundle-host?content-sizing=1'); @@ -610,16 +610,23 @@ test('a content-sized frame follows its app height and keeps its toolbar and she const app = page.frameLocator('iframe'); const main = app.getByRole('main'); await expect.poll(() => main.isVisible()).toBe(true); - const toolbarAction = app.getByRole('button', { - name: 'Custom toolbar action', + const actions = page.getByRole('group', { + name: 'Host page actions', exact: true, }); - await expect.poll(() => toolbarAction.isVisible()).toBe(true); - await app.getByRole('button', { name: 'Export', exact: true }).click(); + const exportSummary = actions.getByRole('button', { + name: 'Export Summary CSV', + exact: true, + }); + await expect.poll(() => exportSummary.isEnabled()).toBe(true); + expect(await app.getByRole('group', { name: 'Page actions' }).count()).toBe( + 0 + ); + expect( + await app.getByRole('button', { name: 'Custom toolbar action' }).count() + ).toBe(0); const downloaded = page.waitForEvent('download'); - await app - .getByRole('menuitem', { name: 'Export Summary CSV', exact: true }) - .click(); + await exportSummary.click(); const download = await downloaded; expect(download.suggestedFilename()).toBe('Summary.csv'); const chunks: Buffer[] = []; @@ -652,7 +659,9 @@ test('a content-sized frame follows its app height and keeps its toolbar and she await expect.poll(frameHeight).toBeGreaterThanOrEqual(initial + 2000); expect(await overflow()).toBe(0); - await app.getByRole('button', { name: 'Explore data', exact: true }).click(); + await actions + .getByRole('button', { name: 'Explore data', exact: true }) + .click(); const sheet = app.getByRole('dialog'); const { height: viewport } = page.viewportSize()!; async function fitsViewport() { @@ -686,7 +695,7 @@ test('a content-sized frame follows its app height and keeps its toolbar and she await expect .poll(async () => Math.round(await frameHeight())) .toBe(Math.round(viewport * 0.8)); - await expect.poll(() => toolbarAction.isVisible()).toBe(true); + await expect.poll(() => exportSummary.isEnabled()).toBe(true); await page .getByRole('button', { name: 'Toggle content sizing', exact: true }) .click(); @@ -898,7 +907,7 @@ test('content-sized inspection fits a narrow viewport after resizing', async ({ await app .getByRole('searchbox', { name: 'Group', exact: true }) .fill('Alpha'); - await app.getByRole('button', { name: 'Explore data', exact: true }).click(); + await page.getByRole('button', { name: 'Explore data', exact: true }).click(); const sheet = app.getByRole('dialog'); await expect.poll(() => sheet.isVisible()).toBe(true); await page.setViewportSize({ width: 375, height: 480 }); diff --git a/tests/public-api/apps-export.test.ts b/tests/public-api/apps-export.test.ts index b848d979..8fdaface 100644 --- a/tests/public-api/apps-export.test.ts +++ b/tests/public-api/apps-export.test.ts @@ -29,7 +29,7 @@ describe('export', () => { ); }); - test('embedded toolbar exports displayed results through its host during updates and failures', async ({ + test('a host exports displayed results through offered actions during updates and failures', async ({ page, }) => { let release!: () => void; @@ -45,17 +45,24 @@ describe('export', () => { }); await page.goto('/starter-data-app'); const app = page.frameLocator('iframe'); - await expect - .poll(() => - app - .getByRole('group', { name: 'Page actions', exact: true }) - .filter({ hasText: 'Loading data' }) - .isVisible() - ) - .toBe(true); - await expect - .poll(() => app.getByRole('button', { name: 'Export CSV' }).isDisabled()) - .toBe(true); + const actions = page.getByRole('group', { + name: 'Host page actions', + exact: true, + }); + const exportButton = actions.getByRole('button', { + name: 'Export CSV', + exact: true, + }); + function refreshing() { + return actions + .getByRole('button', { name: /refresh/ }) + .getAttribute('aria-busy'); + } + expect(await app.getByRole('group', { name: 'Page actions' }).count()).toBe( + 0 + ); + await expect.poll(refreshing).toBe('true'); + await expect.poll(() => exportButton.isDisabled()).toBe(true); release(); gate = Promise.resolve(); await expect @@ -72,9 +79,7 @@ describe('export', () => { async function expectExport(filename: string, csv: string) { const downloaded = page.waitForEvent('download'); - await app - .getByRole('button', { name: 'Export CSV', exact: true }) - .click(); + await exportButton.click(); const download = await downloaded; expect(download.suggestedFilename()).toBe(filename); expect(await contents(download)).toBe(csv); @@ -90,14 +95,7 @@ describe('export', () => { await app .getByRole('searchbox', { name: 'Group', exact: true }) .fill('Beta'); - await expect - .poll(() => - app - .getByRole('group', { name: 'Page actions', exact: true }) - .getByText('Updating data', { exact: true }) - .isVisible() - ) - .toBe(true); + await expect.poll(refreshing).toBe('true'); await expectExport( 'sample-counts-all-data.csv', '\uFEFFGroup,Sample count\r\nAlpha,2200000\r\nBeta,0\r\n' @@ -143,9 +141,7 @@ describe('export', () => { .isVisible() ) .toBe(true); - await expect - .poll(() => app.getByRole('button', { name: 'Export CSV' }).isDisabled()) - .toBe(true); + await expect.poll(() => exportButton.isDisabled()).toBe(true); }); test('embedded export failures stay visible and allow retry', async ({ @@ -153,7 +149,11 @@ describe('export', () => { }) => { await page.goto('/starter-data-app?export-error'); const app = page.frameLocator('iframe'); - const button = app.getByRole('button', { name: 'Export CSV', exact: true }); + const button = page.getByRole('button', { + name: 'Export CSV', + exact: true, + }); + await expect.poll(() => button.isEnabled()).toBe(true); await button.click(); await expect .poll(() => app.getByRole('alert').textContent()) @@ -172,65 +172,91 @@ describe('export', () => { await expect.poll(() => button.isEnabled()).toBe(true); }); - for (const embedded of [false, true]) - test(`multiple datasets export CSVs and a ZIP ${embedded ? 'through the iframe host' : 'standalone'}`, async ({ - page, - }) => { - await page.goto(embedded ? '/bundle-host' : '/static?multiple-exports'); - const app = embedded ? page.frameLocator('iframe') : page; - const button = app.getByRole('button', { name: 'Export', exact: true }); - await button.focus(); - await expect - .poll(() => app.getByRole('tooltip').textContent()) - .toBe('Export data…'); - await button.press('ArrowDown'); - await expect - .poll(() => - app - .getByRole('menuitem', { name: 'Export Counts CSV', exact: true }) - .evaluate( - element => element === element.ownerDocument.activeElement - ) - ) - .toBe(true); - let downloaded = page.waitForEvent('download'); - await app - .getByRole('menuitem', { name: 'Export Summary CSV', exact: true }) - .click(); - let download = await downloaded; - expect(download.suggestedFilename()).toBe('Summary.csv'); - expect(await contents(download)).toBe('\uFEFFTotal\r\n0\r\n'); - await button.click(); - downloaded = page.waitForEvent('download'); - await app - .getByRole('menuitem', { name: 'Export all ZIP', exact: true }) - .click(); - download = await downloaded; - expect(download.suggestedFilename()).toBe('gallery.zip'); - const files = unzipSync(await bytes(download)); - expect(Object.keys(files)).toEqual(['Counts.csv', 'Summary.csv']); - expect(Array.from(files['Summary.csv']!.slice(0, 3))).toEqual([ - 239, 187, 191, - ]); - expect(strFromU8(files['Summary.csv']!)).toBe('Total\r\n0\r\n'); - await button.click(); - downloaded = page.waitForEvent('download'); - await app - .getByRole('menuitem', { name: 'Export all ZIP', exact: true }) - .click(); - expect((await downloaded).suggestedFilename()).toBe('gallery.zip'); - await button.click(); + test('multiple datasets export CSVs and a ZIP standalone', async ({ + page, + }) => { + await page.goto('/static?multiple-exports'); + const app = page; + const button = app.getByRole('button', { name: 'Export', exact: true }); + await button.focus(); + await expect + .poll(() => app.getByRole('tooltip').textContent()) + .toBe('Export data…'); + await button.press('ArrowDown'); + await expect + .poll(() => + app + .getByRole('menuitem', { name: 'Export Counts CSV', exact: true }) + .evaluate(element => element === element.ownerDocument.activeElement) + ) + .toBe(true); + let downloaded = page.waitForEvent('download'); + await app + .getByRole('menuitem', { name: 'Export Summary CSV', exact: true }) + .click(); + let download = await downloaded; + expect(download.suggestedFilename()).toBe('Summary.csv'); + expect(await contents(download)).toBe('\uFEFFTotal\r\n0\r\n'); + await button.click(); + downloaded = page.waitForEvent('download'); + await app + .getByRole('menuitem', { name: 'Export all ZIP', exact: true }) + .click(); + download = await downloaded; + expect(download.suggestedFilename()).toBe('gallery.zip'); + const files = unzipSync(await bytes(download)); + expect(Object.keys(files)).toEqual(['Counts.csv', 'Summary.csv']); + expect(Array.from(files['Summary.csv']!.slice(0, 3))).toEqual([ + 239, 187, 191, + ]); + expect(strFromU8(files['Summary.csv']!)).toBe('Total\r\n0\r\n'); + await button.click(); + downloaded = page.waitForEvent('download'); + await app + .getByRole('menuitem', { name: 'Export all ZIP', exact: true }) + .click(); + expect((await downloaded).suggestedFilename()).toBe('gallery.zip'); + await button.click(); - await app.getByRole('menu').press('Escape'); - await expect.poll(() => app.getByRole('menu').count()).toBe(0); - await expect - .poll(() => - button.evaluate( - element => element === element.ownerDocument.activeElement - ) + await app.getByRole('menu').press('Escape'); + await expect.poll(() => app.getByRole('menu').count()).toBe(0); + await expect + .poll(() => + button.evaluate( + element => element === element.ownerDocument.activeElement ) - .toBe(true); + ) + .toBe(true); + }); + + test('a host exports each offered dataset and a ZIP', async ({ page }) => { + await page.goto('/bundle-host'); + const actions = page.getByRole('group', { + name: 'Host page actions', + exact: true, }); + const summary = actions.getByRole('button', { + name: 'Export Summary CSV', + exact: true, + }); + await expect.poll(() => summary.isEnabled()).toBe(true); + expect( + await actions.getByRole('button', { name: 'Export Counts CSV' }).count() + ).toBe(1); + let downloaded = page.waitForEvent('download'); + await summary.click(); + let download = await downloaded; + expect(download.suggestedFilename()).toBe('Summary.csv'); + expect(await contents(download)).toBe('\uFEFFTotal\r\n0\r\n'); + downloaded = page.waitForEvent('download'); + await actions + .getByRole('button', { name: 'Export all ZIP', exact: true }) + .click(); + download = await downloaded; + expect(download.suggestedFilename()).toBe('gallery.zip'); + const files = unzipSync(await bytes(download)); + expect(Object.keys(files)).toEqual(['Counts.csv', 'Summary.csv']); + }); }); test('omitting presentation and export retains refresh and loaded content', async ({ diff --git a/tests/public-api/apps-presentation.test.ts b/tests/public-api/apps-presentation.test.ts index 8fcd5334..21ce285c 100644 --- a/tests/public-api/apps-presentation.test.ts +++ b/tests/public-api/apps-presentation.test.ts @@ -1,33 +1,33 @@ +import type { Locator } from 'playwright'; import { describe, expect } from 'vitest'; import { test } from '@/tests/public-api/browser'; +function isFocused(locator: Locator) { + return locator.evaluate( + element => element === element.ownerDocument.activeElement + ); +} + describe.each(['frame', 'content'])('present (%s sizing)', sizing => { const search = sizing === 'content' ? 'content-sizing=1&' : ''; - test('a hosted story enters fullscreen and restores the exploration on close', async ({ + test('a host presents the story fullscreen and the exploration resumes on close', async ({ page, }) => { await page.goto(`/starter-data-app?${search}`); const app = page.frameLocator('iframe'); - const launch = app.getByRole('button', { + const launch = page.getByRole('button', { name: 'Present story', exact: true, }); - await expect - .poll(() => launch.getAttribute('aria-keyshortcuts')) - .toBe('Meta+Shift+Enter Control+Shift+Enter'); - const modifier = await launch.evaluate(() => - /Macintosh|Mac OS X|iPhone|iPad/.test(navigator.userAgent) - ? 'Meta' - : 'Control' - ); - await launch.press(`${modifier}+Shift+Enter`); + await expect.poll(() => launch.isEnabled()).toBe(true); + expect( + await app.getByRole('button', { name: 'Present story' }).count() + ).toBe(0); + await launch.click(); await expect .poll(() => page.locator('iframe:fullscreen').isVisible()) .toBe(true); - await expect - .poll(() => app.locator('html:fullscreen').isVisible()) - .toBe(true); const story = app.getByRole('dialog'); await expect .poll(() => @@ -47,16 +47,82 @@ describe.each(['frame', 'content'])('present (%s sizing)', sizing => { await story .getByRole('button', { name: 'Exit presentation', exact: true }) .click(); + await expect.poll(() => story.count()).toBe(0); + await expect.poll(() => page.url()).not.toMatch(/present=1/); await expect.poll(() => page.locator(':fullscreen').count()).toBe(0); + + // Leaving fullscreen, as Escape does, also ends the presentation. + await launch.click(); + await expect.poll(() => story.isVisible()).toBe(true); + await expect + .poll(() => page.locator('iframe:fullscreen').isVisible()) + .toBe(true); + await page.evaluate(() => document.exitFullscreen()); await expect.poll(() => story.count()).toBe(0); await expect.poll(() => page.url()).not.toMatch(/present=1/); + }); + + test('closing a story run from the keyboard returns focus to its host launcher', async ({ + page, + }) => { + await page.goto(`/starter-data-app?${search}`); + const app = page.frameLocator('iframe'); + const launch = page.getByRole('button', { + name: 'Present story', + exact: true, + }); + await expect.poll(() => launch.isEnabled()).toBe(true); + await launch.focus(); + await page.keyboard.press('Enter'); + const story = app.getByRole('dialog'); await expect .poll(() => - launch.evaluate( - element => element === element.ownerDocument.activeElement - ) + story.getByRole('heading', { name: 'Total samples: 2.2M' }).isVisible() ) .toBe(true); + await story + .getByRole('button', { name: 'Exit presentation', exact: true }) + .press('Enter'); + await expect.poll(() => story.count()).toBe(0); + await expect.poll(() => isFocused(launch)).toBe(true); + + // Escape leaves fullscreen before the story sees it; that also closes the story. + await page.keyboard.press('Enter'); + await expect.poll(() => story.isVisible()).toBe(true); + await expect + .poll(() => page.locator('iframe:fullscreen').isVisible()) + .toBe(true); + await page.evaluate(() => document.exitFullscreen()); + await expect.poll(() => story.count()).toBe(0); + await expect.poll(() => isFocused(launch)).toBe(true); + }); + + test('a reader who moves to another host control keeps it when the story closes', async ({ + page, + }) => { + await page.goto(`/starter-data-app?${search}`); + // Without fullscreen, host controls stay reachable while the story is open. + await page.evaluate(() => { + HTMLIFrameElement.prototype.requestFullscreen = () => + Promise.reject(new Error('Fullscreen denied')); + }); + const app = page.frameLocator('iframe'); + const launch = page.getByRole('button', { + name: 'Present story', + exact: true, + }); + await expect.poll(() => launch.isEnabled()).toBe(true); + await launch.click(); + const story = app.getByRole('dialog'); + await expect.poll(() => story.isVisible()).toBe(true); + const explore = page.getByRole('button', { + name: 'Explore data', + exact: true, + }); + await explore.focus(); + await page.goBack(); + await expect.poll(() => story.count()).toBe(0); + expect(await isFocused(explore)).toBe(true); }); test('a saved presentation opens without fullscreen or a user gesture', async ({ @@ -79,27 +145,11 @@ describe.each(['frame', 'content'])('present (%s sizing)', sizing => { await app.getByRole('dialog').press('Escape'); await expect.poll(() => app.getByRole('dialog').count()).toBe(0); await expect.poll(() => page.url()).not.toMatch(/present=1/); - }); - - test('a host denying fullscreen still allows the story to open and close', async ({ - page, - }) => { - await page.goto(`/starter-data-app?${search}no-fullscreen=1`); - const app = page.frameLocator('iframe'); - await app - .getByRole('button', { name: 'Present story', exact: true }) - .click(); - const story = app.getByRole('dialog'); - await expect - .poll(() => - story.getByRole('heading', { name: 'Total samples: 2.2M' }).isVisible() + // Only a host-run presentation returns focus to the host launcher. + expect( + await isFocused( + page.getByRole('button', { name: 'Present story', exact: true }) ) - .toBe(true); - await expect.poll(() => page.locator(':fullscreen').count()).toBe(0); - await story - .getByRole('button', { name: 'Exit presentation', exact: true }) - .click(); - await expect.poll(() => story.count()).toBe(0); - await expect.poll(() => page.url()).not.toMatch(/present=1/); + ).toBe(false); }); }); diff --git a/tests/public-api/dev-app.test.ts b/tests/public-api/dev-app.test.ts index 25754398..a1630763 100644 --- a/tests/public-api/dev-app.test.ts +++ b/tests/public-api/dev-app.test.ts @@ -760,6 +760,79 @@ mountDataApp({ app, component: App }); } }); +test('dev:file offers observed app errors to copy, with a selectable fallback', async () => { + const directory = await temporaryDirectory(); + const entry = join(directory, 'index.tsx'); + await writeFile( + entry, + ` +import { useState } from 'react'; +import { defineDataApp } from '@altertable/data-app'; +import { mountDataApp } from '@altertable/data-app-react'; +import { DataWidget } from '@altertable/data-app-react/ui'; +const app = defineDataApp({ title: 'Preview', description: 'Preview', scope: { organization: 'test', environment: 'test' }, queries: {} }); +function Chart({ broken }: { broken: boolean }) { + if (broken) throw new Error('Series requires a numeric value'); + return

Chart ready

; +} +function App() { + const [broken, setBroken] = useState(false); + return <> + ; +} +mountDataApp({ app, component: App }); +` + ); + const server = await startFile(entry); + const browser = await chromium.launch(); + try { + for (const clipboard of [true, false]) { + const context = await browser.newContext({ + permissions: clipboard ? ['clipboard-read', 'clipboard-write'] : [], + }); + const page = await context.newPage(); + await page.goto(server.url); + const app = page.frameLocator('iframe'); + await app.getByText('Chart ready').waitFor(); + expect( + await page.getByRole('region', { name: 'App errors' }).count() + ).toBe(0); + await app.getByRole('button', { name: 'Break widget' }).click(); + const banner = page.getByRole('region', { name: 'App errors' }); + await banner.waitFor(); + expect(await banner.textContent()).toContain( + 'Copy the diagnostics into your agent to request a fix.' + ); + // The preview cannot invoke an agent, so neither it nor the widget offers a fix. + expect(await page.getByRole('button', { name: /^Fix/ }).count()).toBe(0); + expect( + await app.getByRole('button', { name: 'Fix error' }).isDisabled() + ).toBe(true); + await banner.getByRole('button', { name: 'Copy diagnostics' }).click(); + if (clipboard) { + await vi.waitFor(async () => { + const report = JSON.parse( + await page.evaluate(() => navigator.clipboard.readText()) + ); + expect(report.failures).toHaveLength(1); + expect(report.failures[0].message).toContain( + 'Series requires a numeric value' + ); + }); + } else { + await banner.getByText('Couldn’t copy.', { exact: false }).waitFor(); + const report = JSON.parse( + (await banner.getByText(/"failures":/).textContent())! + ); + expect(report.failures).toHaveLength(1); + } + await context.close(); + } + } finally { + await browser.close(); + } +}); + test('the public Bun preview serves injected data and rejects foreign requests', async () => { const directory = await temporaryDirectory(); const file = join(directory, 'index.tsx'); diff --git a/tests/public-api/fixtures/annotation-state-app.tsx b/tests/public-api/fixtures/annotation-state-app.tsx index 52965806..6d49e62c 100644 --- a/tests/public-api/fixtures/annotation-state-app.tsx +++ b/tests/public-api/fixtures/annotation-state-app.tsx @@ -52,7 +52,7 @@ const client = createDataClient<{ return Promise.resolve({ status: 200, body: { - data: period === 'last-365' ? 84 : 42, + data: 42, requestId: period, queriedAt: '2026-10-07T00:00:00Z', queryIds: [], @@ -108,16 +108,7 @@ const content = view.content(source => ( )); function App() { return ( - []} - datasets={[dataset]} - toolbarActions={ - - } - > + []} datasets={[dataset]}> ); diff --git a/tests/public-api/fixtures/annotations-app.tsx b/tests/public-api/fixtures/annotations-app.tsx index 518c5847..3a534859 100644 --- a/tests/public-api/fixtures/annotations-app.tsx +++ b/tests/public-api/fixtures/annotations-app.tsx @@ -81,7 +81,6 @@ function App() { }} dataContext={{ description: 'Test report', glossary: {} }} description="Report description" - toolbarActions={} footerActions={} > - {JSON.stringify(drafts)} - {sendAttempts} - + + {JSON.stringify(drafts)} + + + {sendAttempts} + + + {String(refreshing)} + + {JSON.stringify(submitted)} + {params.has('annotations') && ( + + )} {params.has('annotation-send') && ( <> - ({ id: draft.id, targetId: draft.target.id, @@ -168,6 +195,9 @@ function Host() { } : {}), }} + onActionsChange={actions => + setRefreshing(actions.refresh?.refreshing ?? false) + } onMessage={router.dispatch} /> diff --git a/tests/public-api/fixtures/bundle-host.tsx b/tests/public-api/fixtures/bundle-host.tsx index c68b629d..3d13dae2 100644 --- a/tests/public-api/fixtures/bundle-host.tsx +++ b/tests/public-api/fixtures/bundle-host.tsx @@ -2,11 +2,15 @@ import { createNavigationHandler, createExternalLinkHandler, createSqlQueryHandler, + type DataAppActions, type DataAppDiagnostic, type DataAppLogger, type DataAppStatus, } from '@altertable/data-app-embed'; -import { DataAppBridge } from '@altertable/data-app-embed/react'; +import { + DataAppBridge, + type DataAppBridgeHandle, +} from '@altertable/data-app-embed/react'; import { createHttpTransport } from '@altertable/data-app/client'; import { createMessageRouter, @@ -17,6 +21,7 @@ import { } from '@altertable/data-app/contract'; import { useReducer, + useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, @@ -57,7 +62,78 @@ const offscreen = { overflow: 'hidden', } as const; +/** Host-owned page actions, as a parent shell renders them from the app's offer. */ +function HostActionBar({ + actions, + run, +}: { + actions: DataAppActions; + run: DataAppBridgeHandle['runAction']; +}) { + const { refresh, exportCsv, presentStory, aboutData } = actions; + return ( +
+ {refresh && ( + + )} + {exportCsv && + (exportCsv.tables.length > 1 ? ( + <> + {exportCsv.tables.map(table => ( + + ))} + + + ) : ( + + ))} + {presentStory && ( + + )} + {aboutData && ( + + )} +
+ ); +} + function Host() { + const bridge = useRef(null); + const [actions, setActions] = useState({}); const [externalNavigation, setExternalNavigation] = useState(''); function navigateNewWindowOrTab( url: string, @@ -252,6 +328,10 @@ function Host() { Move embedded report )} + bridge.current?.runAction(action)} + />
{ diff --git a/tests/public-api/fixtures/diagnostics-host.tsx b/tests/public-api/fixtures/diagnostics-host.tsx index f61187cb..c8058d5f 100644 --- a/tests/public-api/fixtures/diagnostics-host.tsx +++ b/tests/public-api/fixtures/diagnostics-host.tsx @@ -2,11 +2,7 @@ import { createDataAppRepairSession, type DataAppRepairState, } from '@altertable/data-app-embed'; -import { - DataAppBridge, - DataAppRepairBanner, - type DataAppRepairProgress, -} from '@altertable/data-app-embed/react'; +import { DataAppBridge } from '@altertable/data-app-embed/react'; import { useEffect, useState, useSyncExternalStore } from 'react'; import { createRoot } from 'react-dom/client'; const params = new URLSearchParams(location.search); @@ -52,7 +48,6 @@ function Host() { const [revision, setRevision] = useState( Number(sessionStorage.getItem('revision') ?? '1') ); - const [progress, setProgress] = useState(); const [mount, setMount] = useState(0); const [session, setSession] = useState(makeSession); const diagnostics = useSyncExternalStore( @@ -70,8 +65,6 @@ function Host() { useEffect(() => { function listener() { setCount(requests.length); - // A new host request replaces activity from the previous attempt. - setProgress(undefined); } document.addEventListener('delivered', listener); return () => document.removeEventListener('delivered', listener); @@ -98,34 +91,6 @@ function Host() { - {params.has('progress') && ( - <> - {(['working', 'building', 'loading', 'review'] as const).map( - phase => ( - - ) - )} - - - )} {params.has('controlled-delivery') && ( <> +
+ )}