From b62e51e8c355e4e174ea10d3d1c8592da8f9b8c3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?=
Date: Mon, 16 Nov 2026 13:59:55 +0100
Subject: [PATCH 1/2] feat!: run embedded page actions from the host
Embedded apps no longer render a toolbar. They offer refresh, CSV export,
story, and inspection through onActionsChange, and the host runs them with
runAction(). Stories run from the host show the iframe fullscreen.
Stop exporting DataAppRepairBanner; hosts build their repair UI from
createDataAppRepairSession, and the dev preview keeps a private copy-only banner.
---
REFERENCE.md | 19 +-
dev/fixtures/annotation-state-app.tsx | 13 +-
dev/fixtures/bundle-host.tsx | 115 +++++-
docs/diagnostics.md | 39 +-
docs/embed.md | 44 ++-
docs/layout.md | 4 +
docs/react-embed.md | 46 ++-
docs/stories-and-export.md | 2 +-
packages/data-app-bun/src/preview/host.tsx | 9 +-
.../src/preview/repair-banner.tsx | 98 +++++
packages/data-app-embed/src/host.ts | 77 +++-
packages/data-app-embed/src/index.ts | 6 +-
packages/data-app-embed/src/react/bridge.tsx | 23 +-
packages/data-app-embed/src/react/index.ts | 8 +-
.../src/react/repair-banner.tsx | 276 -------------
packages/data-app-embed/src/repair.ts | 2 +-
packages/data-app-embed/src/source.ts | 3 +
.../src/annotations/AnnotationControls.tsx | 12 +-
.../data-app-react/src/ui/DataAppFrame.tsx | 133 ++++---
.../data-app-react/src/ui/ExportControl.tsx | 48 ++-
.../data-app-react/src/ui/HostActions.tsx | 128 ++++++
.../data-app-react/src/ui/PresentStory.tsx | 58 ++-
.../src/ui/useDataAppPresentation.ts | 63 +--
.../src/ui/useDataAppTransport.ts | 30 ++
packages/data-app/src/authoring/contract.ts | 11 +-
packages/data-app/src/client/frame-sizing.ts | 6 +-
packages/data-app/src/client/iframe.ts | 33 +-
packages/data-app/src/client/index.ts | 1 +
packages/data-app/src/core/actions.ts | 100 +++++
packages/data-app/src/core/annotations.ts | 10 +-
packages/data-app/src/core/app-filters.ts | 5 +-
packages/data-app/src/core/appearance.ts | 9 +-
packages/data-app/src/core/bridge-endpoint.ts | 8 +-
packages/data-app/src/core/bridge.ts | 19 +-
.../data-app/src/core/date-time-filter.ts | 15 +-
.../src/core/date-time-range-value.ts | 49 +--
.../data-app/src/core/dimension-source.ts | 8 +-
packages/data-app/src/core/dimension.ts | 3 +-
packages/data-app/src/core/external-link.ts | 9 +-
packages/data-app/src/core/filters.ts | 4 +-
packages/data-app/src/core/messages.ts | 4 +-
packages/data-app/src/core/queries.ts | 15 +-
packages/data-app/src/core/record.ts | 4 +
tests/public-api/apps-annotations.test.ts | 46 ++-
tests/public-api/apps-authoring.test.ts | 38 +-
tests/public-api/apps-diagnostics.test.ts | 363 ++----------------
tests/public-api/apps-embedding.test.ts | 31 +-
tests/public-api/apps-export.test.ts | 192 +++++----
tests/public-api/apps-presentation.test.ts | 58 +--
tests/public-api/dev-app.test.ts | 73 ++++
.../fixtures/annotation-state-app.tsx | 13 +-
tests/public-api/fixtures/annotations-app.tsx | 1 -
.../public-api/fixtures/annotations-host.tsx | 40 +-
tests/public-api/fixtures/bundle-host.tsx | 88 ++++-
.../public-api/fixtures/diagnostics-host.tsx | 52 +--
55 files changed, 1409 insertions(+), 1155 deletions(-)
create mode 100644 packages/data-app-bun/src/preview/repair-banner.tsx
delete mode 100644 packages/data-app-embed/src/react/repair-banner.tsx
create mode 100644 packages/data-app-react/src/ui/HostActions.tsx
create mode 100644 packages/data-app-react/src/ui/useDataAppTransport.ts
create mode 100644 packages/data-app/src/core/actions.ts
create mode 100644 packages/data-app/src/core/record.ts
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 && (
<>
)}
-
+
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.
+
+
+ void copyDiagnostics(report)}
+ >
+ Copy diagnostics
+
+
+ {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..142963a0 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;
};
@@ -61,6 +70,7 @@ export function attachDataAppConnection({
logger,
onStatusChange,
onDiagnostic,
+ onActionsChange,
onMessage,
repair,
window: host = window,
@@ -85,6 +95,11 @@ 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;
+ const parentDocument = iframe.ownerDocument;
const requestStartedAt = new Map();
function reportDiagnostic(event: BridgeDiagnostic) {
@@ -163,6 +178,49 @@ export function attachDataAppConnection({
publishState();
}
+ function publishActions(next: DataAppActions) {
+ const identity = JSON.stringify(next);
+ if (identity === actionsIdentity) return;
+ actionsIdentity = identity;
+ actions = next;
+ if (!next.presentStory?.presenting) exitStoryFullscreen();
+ onActionsChange?.(next);
+ }
+
+ function runAction(action: DataAppAction) {
+ if (disposed || !sessionId) return;
+ if (action.type === 'presentStory' && actions.presentStory?.enabled)
+ enterStoryFullscreen();
+ send('actionRun', { action });
+ }
+
+ /** 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() {
+ if (!ownsFullscreen) return;
+ ownsFullscreen = false;
+ if (parentDocument.fullscreenElement === iframe)
+ void parentDocument.exitFullscreen().catch(() => {});
+ }
+
+ 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 +245,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 +273,9 @@ export function attachDataAppConnection({
runtimeError() {
onStatusChange?.('failed');
},
+ actionsUpdate({ actions }) {
+ publishActions(actions);
+ },
runtimeResize({ height }) {
contentSizing.resize(height);
},
@@ -226,6 +288,7 @@ export function attachDataAppConnection({
},
disconnect() {
cancelAll();
+ publishActions({});
documentId = undefined;
sessionId = undefined;
onStatusChange?.('disconnected');
@@ -348,11 +411,17 @@ export function attachDataAppConnection({
repairLease = repair?.session.connect(repair.revision);
documentId = undefined;
sessionId = undefined;
+ publishActions({});
onStatusChange?.('connecting');
send('connect', {});
}
function dispose() {
+ exitStoryFullscreen();
+ parentDocument.removeEventListener(
+ 'fullscreenchange',
+ closeStoryOnFullscreenExit
+ );
disposed = true;
unsubscribeRepair?.();
repairLease?.dispose();
@@ -372,9 +441,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 (
- <>
-
-
-
-
-
- {visibleReport && (
- void copyDiagnostics(visibleReport)}
- >
- Copy diagnostics
-
- )}
- void session.requestRepair()}
- >
- Fix errors
-
-
-
- {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}
+
+
+ )}