Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(canvas): present artifacts full screen in order (#9642)

Eric Hayesd67125461f00
diff --git a/apps/web/src/features/block-canvas/README.md b/apps/web/src/features/block-canvas/README.md
index 68f0795e8b..9a2f714448 100644
--- a/apps/web/src/features/block-canvas/README.md
+++ b/apps/web/src/features/block-canvas/README.md
@@ -85,6 +85,15 @@ the component's `<slot>`. They expand when the document is composed, so a librar
edit updates every artifact using it. JSON export carries only the scene, so a
downloaded canvas loses its library.
+**Present** on a node opens `views/artifact-presentation.tsx`, full screen where the
+browser allows and otherwise covering the window. It steps through artifacts only,
+in `presentOrder`, stopping at each end; new artifacts go last, and the inspector
+reorders them. Arrow keys, Space and Page Up/Down step, and Esc exits. Focus inside
+a frame keeps keys from the host, so `composeArtifactDocument` adds a small script
+that forwards these keys unless the artifact handled them or the user is typing.
+The host treats those messages only as navigation. Touch devices use the on-screen
+buttons.
+
## Controls
The floating top toolbar uses the shared `Toolbar` and Phosphor icons for drawing
diff --git a/apps/web/src/features/block-canvas/browser-test/artifact.e2e.ts b/apps/web/src/features/block-canvas/browser-test/artifact.e2e.ts
index 2dcdeadda7..00bf87457c 100644
--- a/apps/web/src/features/block-canvas/browser-test/artifact.e2e.ts
+++ b/apps/web/src/features/block-canvas/browser-test/artifact.e2e.ts
@@ -45,3 +45,87 @@ test('edits an artifact from the inspector', async ({ page }) => {
frameFor(page, 'First').contentFrame().locator('#edited')
).toHaveText('Edited');
});
+
+test('presents artifacts in order, with keys working from inside a frame', async ({
+ page,
+}) => {
+ await page.goto('/artifact.html?edit');
+ const node = page.locator('[data-canvas-artifact="First"]');
+ await frameFor(page, 'First').waitFor();
+ await node.hover();
+ await node.getByRole('button', { name: 'Present' }).click();
+
+ const show = page.locator('[data-canvas-artifact-presentation]');
+ const counter = page.getByTestId('canvas-artifact-presentation-counter');
+ const target = show
+ .locator('iframe[data-canvas-artifact-frame]')
+ .contentFrame()
+ .locator('#target');
+ await expect(counter).toHaveText('1 / 2');
+ await expect(target).toHaveText('First');
+
+ await page.keyboard.press('ArrowRight');
+ await expect(counter).toHaveText('2 / 2');
+ await expect(target).toHaveText('Second');
+
+ // Stops at the end rather than wrapping.
+ await page.keyboard.press('ArrowRight');
+ await expect(counter).toHaveText('2 / 2');
+
+ await page.getByRole('button', { name: 'Previous artifact' }).click();
+ await expect(counter).toHaveText('1 / 2');
+
+ // With focus inside the frame, keys reach the host only through its bridge.
+ await show
+ .locator('iframe[data-canvas-artifact-frame]')
+ .contentFrame()
+ .locator('body')
+ .evaluate((body) => {
+ body.tabIndex = 0;
+ body.focus();
+ });
+ await show
+ .locator('iframe[data-canvas-artifact-frame]')
+ .contentFrame()
+ .locator('body')
+ .press('ArrowRight');
+ await expect(counter).toHaveText('2 / 2');
+ await show
+ .locator('iframe[data-canvas-artifact-frame]')
+ .contentFrame()
+ .locator('body')
+ .press('Escape');
+ await expect(show).toHaveCount(0);
+});
+
+test('reorders the presentation from the inspector', async ({ page }) => {
+ await page.goto('/artifact.html?edit');
+ await frameFor(page, 'First').waitFor();
+ await page.mouse.click(200, 150);
+
+ await expect(page.getByText('Presented 1 of 2')).toBeVisible();
+ await page.getByRole('button', { name: 'Later' }).click();
+ await expect(page.getByText('Presented 2 of 2')).toBeVisible();
+
+ // The selection overlay covers the node's own controls while it is selected.
+ await page
+ .getByRole('region', { name: 'Artifact' })
+ .getByRole('button', { name: 'Present' })
+ .click();
+ await expect(
+ page.getByTestId('canvas-artifact-presentation-counter')
+ ).toHaveText('2 / 2');
+});
+
+test('double-clicking a selected artifact starts interacting', async ({
+ page,
+}) => {
+ await page.goto('/artifact.html?edit');
+ const frame = frameFor(page, 'First');
+ await frame.waitFor();
+ await page.mouse.click(200, 150);
+ await expect(page.getByLabel('Artifact HTML')).toBeVisible();
+
+ await page.mouse.dblclick(200, 150);
+ await expect(frame).toHaveCSS('pointer-events', 'auto');
+});
diff --git a/apps/web/src/features/block-canvas/components/artifact-inspector.tsx b/apps/web/src/features/block-canvas/components/artifact-inspector.tsx
index 7de56c86a9..2b63a57977 100644
--- a/apps/web/src/features/block-canvas/components/artifact-inspector.tsx
+++ b/apps/web/src/features/block-canvas/components/artifact-inspector.tsx
@@ -3,13 +3,17 @@ import {
type ArtifactContent,
type ArtifactItem,
} from '@macro-inc/graphics';
-import { Input } from '@ui';
+import { Button, Input } from '@ui';
import { InspectorField } from './inspector-field';
import { InspectorSection } from './inspector-section';
export function ArtifactInspector(props: {
item: ArtifactItem;
onChange: (content: ArtifactContent) => void;
+ position: number;
+ count: number;
+ onMove: (delta: number) => void;
+ onPresent: () => void;
}) {
return (
<InspectorSection title="Artifact">
@@ -35,6 +39,29 @@ export function ArtifactInspector(props: {
}
/>
</InspectorField>
+ <Button variant="ghost" size="sm" onClick={props.onPresent}>
+ Present
+ </Button>
+ <InspectorField label={`Presented ${props.position} of ${props.count}`}>
+ <div class="flex gap-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={props.position <= 1}
+ onClick={() => props.onMove(-1)}
+ >
+ Earlier
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={props.position >= props.count}
+ onClick={() => props.onMove(1)}
+ >
+ Later
+ </Button>
+ </div>
+ </InspectorField>
</InspectorSection>
);
}
diff --git a/apps/web/src/features/block-canvas/core/artifact-document.ts b/apps/web/src/features/block-canvas/core/artifact-document.ts
index 8d21a562ce..6ce9925ddf 100644
--- a/apps/web/src/features/block-canvas/core/artifact-document.ts
+++ b/apps/web/src/features/block-canvas/core/artifact-document.ts
@@ -35,6 +35,20 @@ export function artifactThemeTokens(element: Element): Record<string, string> {
);
}
+/**
+ * Focus inside a frame keeps keys from the host, so the host cannot exit or step
+ * through a presentation. Forward the few it needs, unless the artifact handled
+ * them or the user is typing. The host trusts these only as navigation.
+ */
+const KEY_BRIDGE = `addEventListener('keydown', function (event) {
+ var escape = event.key === 'Escape';
+ if (!escape && event.defaultPrevented) return;
+ if (!escape && ['ArrowLeft', 'ArrowRight', ' ', 'PageUp', 'PageDown'].indexOf(event.key) === -1) return;
+ var target = event.target;
+ if (!escape && target.closest && target.closest('input,textarea,select,button,a,[contenteditable]')) return;
+ parent.postMessage({ macroArtifactKey: event.key }, '*');
+});`;
+
/** Bound cycles and fan-out between components. Expansion runs on the host's main
* thread, and a peer can store entries past the authoring limit. */
const MAX_COMPONENT_EXPANSIONS = 500;
@@ -139,6 +153,9 @@ export function composeArtifactDocument(
const marker = parsed.createElement('script');
marker.textContent = loadMarker(loadToken);
- parsed.head.prepend(policy, theme, marker);
+ const bridge = parsed.createElement('script');
+ bridge.textContent = KEY_BRIDGE;
+
+ parsed.head.prepend(policy, theme, marker, bridge);
return `<!doctype html>${parsed.documentElement.outerHTML}`;
}
diff --git a/apps/web/src/features/block-canvas/primitives/text-input.ts b/apps/web/src/features/block-canvas/primitives/text-input.ts
index c3f434a540..3c8c922c29 100644
--- a/apps/web/src/features/block-canvas/primitives/text-input.ts
+++ b/apps/web/src/features/block-canvas/primitives/text-input.ts
@@ -1,3 +1,7 @@
+import {
+ enableCanvasArtifacts,
+ isFeatureEnabled,
+} from '@core/constant/featureFlags';
import { screenToWorld, textTargetAt } from '@macro-inc/graphics';
import type { CanvasState } from './create-canvas-state';
/** Canvas text gestures stay separate from geometric drawing and pointer capture. */
@@ -37,6 +41,10 @@ export function attachTextInput(root: HTMLElement, state: CanvasState) {
if (item.geometry.display === 'embed') state.embeds.enter(item.id);
return;
}
+ if (item?.type === 'artifact') {
+ if (isFeatureEnabled(enableCanvasArtifacts)) state.embeds.enter(item.id);
+ return;
+ }
const id = textTargetAt(state.editor.document, p);
if (id) state.text.edit(id);
else state.text.begin(p);
@@ -46,7 +54,7 @@ export function attachTextInput(root: HTMLElement, state: CanvasState) {
if (
!(target instanceof Element) ||
target.closest(
- '[data-canvas-document], [data-canvas-text-editor], [aria-label="Text style"]'
+ '[data-canvas-document], [data-canvas-artifact], [data-canvas-text-editor], [aria-label="Text style"]'
)
)
return;
@@ -129,7 +137,7 @@ export function attachTextInput(root: HTMLElement, state: CanvasState) {
if (
!(event.target instanceof Element) ||
event.target.closest(
- '[data-canvas-document], [data-canvas-text-editor], [data-graphics-connector-end]'
+ '[data-canvas-document], [data-canvas-artifact], [data-canvas-text-editor], [data-graphics-connector-end]'
) ||
!event.target.closest('[aria-label="Graphics canvas"]')
)
diff --git a/apps/web/src/features/block-canvas/views/artifact-frame.tsx b/apps/web/src/features/block-canvas/views/artifact-frame.tsx
index 0d63e62a25..fdd346bfb6 100644
--- a/apps/web/src/features/block-canvas/views/artifact-frame.tsx
+++ b/apps/web/src/features/block-canvas/views/artifact-frame.tsx
@@ -28,8 +28,11 @@ export function ArtifactFrame(props: {
interactive: boolean;
/** Mount even offscreen, for renders that must capture every artifact. */
eager?: boolean;
+ /** A navigation key pressed while focus is inside the frame. */
+ onKey?: (key: string) => void;
}) {
let host!: HTMLDivElement;
+ let frame: HTMLIFrameElement | undefined;
const artifacts = useArtifactLibrary();
const [size, setSize] = createSignal({ width: 0, height: 0 });
const [visible, setVisible] = createSignal(!!props.eager);
@@ -77,6 +80,15 @@ export function ArtifactFrame(props: {
};
onMount(() => {
+ const forwardKey = (event: MessageEvent) => {
+ if (!frame || event.source !== frame.contentWindow) return;
+
+ const key: unknown = event.data?.macroArtifactKey;
+ if (typeof key === 'string') props.onKey?.(key);
+ };
+ window.addEventListener('message', forwardKey);
+ onCleanup(() => window.removeEventListener('message', forwardKey));
+
const sizes = new ResizeObserver(([entry]) => {
if (!entry) return;
setSize({
@@ -107,7 +119,7 @@ export function ArtifactFrame(props: {
}
>
<Show when={visible() ? mounted() : undefined} keyed>
- {(frame) => {
+ {(mount) => {
let element: HTMLIFrameElement | undefined;
let loads = 0;
let announced = 0;
@@ -133,9 +145,12 @@ export function ArtifactFrame(props: {
sandbox={ARTIFACT_SANDBOX}
allow=""
referrerPolicy="no-referrer"
- srcdoc={frame.content}
+ srcdoc={mount.content}
tabIndex={props.interactive ? 0 : -1}
- ref={element}
+ ref={(iframe) => {
+ element = iframe;
+ frame = iframe;
+ }}
onLoad={() => {
// The message and the load event can arrive in either order.
loads += 1;
diff --git a/apps/web/src/features/block-canvas/views/artifact-presentation.tsx b/apps/web/src/features/block-canvas/views/artifact-presentation.tsx
new file mode 100644
index 0000000000..57c452fab9
--- /dev/null
+++ b/apps/web/src/features/block-canvas/views/artifact-presentation.tsx
@@ -0,0 +1,145 @@
+import { beginInteraction } from '@app/observability/flow';
+import CaretLeft from '@icon/system/regular/caret-left.svg';
+import CaretRight from '@icon/system/regular/caret-right.svg';
+import X from '@icon/system/regular/x.svg';
+import { type GraphicsEditor, presentationOrder } from '@macro-inc/graphics';
+import { createMemo, createSignal, onCleanup, onMount, Show } from 'solid-js';
+import { Portal } from 'solid-js/web';
+import { ArtifactFrame } from './artifact-frame';
+
+/** Full screen, stepping through the canvas's artifacts in presentation order. */
+export function ArtifactPresentation(props: {
+ editor: GraphicsEditor;
+ startId: string;
+ onExit: () => void;
+}) {
+ let root!: HTMLDivElement;
+ const [document_, setDocument] = createSignal(props.editor.document);
+ onCleanup(props.editor.subscribeDocument(setDocument));
+
+ const artifacts = createMemo(() => presentationOrder(document_()));
+ const [currentId, setCurrentId] = createSignal(props.startId);
+ let lastIndex = 0;
+ // A peer can delete or reorder what is on screen. Stay near the same place.
+ const index = createMemo(() => {
+ const found = artifacts().findIndex((item) => item.id === currentId());
+ if (found !== -1) lastIndex = found;
+ return found !== -1
+ ? found
+ : Math.min(lastIndex, Math.max(artifacts().length - 1, 0));
+ });
+ const current = createMemo(() => artifacts()[index()]);
+
+ const go = (delta: number) => {
+ const next = artifacts()[index() + delta];
+ if (next) setCurrentId(next.id);
+ };
+ const handleKey = (key: string) => {
+ if (key === 'Escape') props.onExit();
+ else if (key === 'ArrowRight' || key === ' ' || key === 'PageDown') go(1);
+ else if (key === 'ArrowLeft' || key === 'PageUp') go(-1);
+ else return false;
+
+ return true;
+ };
+
+ onMount(() => {
+ const interaction = beginInteraction('canvas.artifact.present', {
+ attributes: {
+ 'artifact.id': props.startId,
+ 'artifact.count': artifacts().length,
+ },
+ });
+ root.focus();
+ void root.requestFullscreen?.().catch(() => {});
+ interaction.end();
+
+ // Capture: no canvas or app shortcut, such as delete, acts behind the show.
+ const onKeyDown = (event: KeyboardEvent) => {
+ event.stopPropagation();
+ if (handleKey(event.key)) event.preventDefault();
+ };
+ const onFullscreen = () => {
+ // Leaving full screen with the browser's own Esc ends the show.
+ if (!document.fullscreenElement) props.onExit();
+ };
+ window.addEventListener('keydown', onKeyDown, true);
+ document.addEventListener('fullscreenchange', onFullscreen);
+ onCleanup(() => {
+ window.removeEventListener('keydown', onKeyDown, true);
+ document.removeEventListener('fullscreenchange', onFullscreen);
+ if (document.fullscreenElement === root)
+ void document.exitFullscreen().catch(() => {});
+ });
+ });
+
+ return (
+ <Portal>
+ <div
+ ref={root}
+ tabIndex={-1}
+ role="dialog"
+ aria-label="Artifact presentation"
+ data-canvas-artifact-presentation
+ class="fixed inset-0 z-modal flex flex-col bg-[black] outline-none"
+ >
+ <div class="min-h-0 flex-1">
+ <Show when={current()?.id} keyed>
+ {(id) => (
+ <Show when={artifacts().find((item) => item.id === id)}>
+ {(artifact) => (
+ <ArtifactFrame
+ html={artifact().geometry.html}
+ title={artifact().geometry.title}
+ designWidth={artifact().geometry.designWidth}
+ designHeight={artifact().geometry.designHeight}
+ interactive
+ eager
+ onKey={handleKey}
+ />
+ )}
+ </Show>
+ )}
+ </Show>
+ </div>
+ <div class="flex shrink-0 items-center justify-center gap-2 p-2 text-[white] text-xs">
+ <button
+ type="button"
+ aria-label="Previous artifact"
+ class="rounded-full p-2 hover:bg-[white]/20 disabled:opacity-40"
+ disabled={index() === 0}
+ onClick={() => go(-1)}
+ >
+ <CaretLeft class="size-4" />
+ </button>
+ <span
+ class="tabular-nums"
+ data-testid="canvas-artifact-presentation-counter"
+ >
+ {index() + 1} / {artifacts().length}
+ </span>
+ <button
+ type="button"
+ aria-label="Next artifact"
+ class="rounded-full p-2 hover:bg-[white]/20 disabled:opacity-40"
+ disabled={index() >= artifacts().length - 1}
+ onClick={() => go(1)}
+ >
+ <CaretRight class="size-4" />
+ </button>
+ <span class="max-w-64 truncate px-2">
+ {current()?.geometry.title}
+ </span>
+ <button
+ type="button"
+ aria-label="Exit presentation"
+ class="rounded-full p-2 hover:bg-[white]/20"
+ onClick={props.onExit}
+ >
+ <X class="size-4" />
+ </button>
+ </div>
+ </div>
+ </Portal>
+ );
+}
diff --git a/apps/web/src/features/block-canvas/views/artifact-view.tsx b/apps/web/src/features/block-canvas/views/artifact-view.tsx
index 398f4903d9..ddee784c61 100644
--- a/apps/web/src/features/block-canvas/views/artifact-view.tsx
+++ b/apps/web/src/features/block-canvas/views/artifact-view.tsx
@@ -9,6 +9,7 @@ export function CanvasArtifactView(
active: boolean;
onEnter: () => void;
onExit: () => void;
+ onPresent: () => void;
}
) {
const flag = useFeatureFlag(enableCanvasArtifacts);
@@ -45,6 +46,9 @@ export function CanvasArtifactView(
designWidth={props.item.geometry.designWidth}
designHeight={props.item.geometry.designHeight}
interactive={props.active}
+ onKey={(key) => {
+ if (key === 'Escape' && props.active) props.onExit();
+ }}
/>
<div class="absolute right-2 top-2 flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 touch:opacity-100">
<button
@@ -58,6 +62,16 @@ export function CanvasArtifactView(
>
{props.active ? 'Done' : 'Interact'}
</button>
+ <button
+ type="button"
+ class="menu-surface rounded px-2 py-1 text-xs text-accent hover:bg-hover"
+ onClick={(event) => {
+ event.stopPropagation();
+ props.onPresent();
+ }}
+ >
+ Present
+ </button>
</div>
</Show>
</div>
diff --git a/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx b/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx
index 7e2a6936c4..7ccdd98fe3 100644
--- a/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx
+++ b/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx
@@ -1,5 +1,7 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { DocumentPreviewContent } from '@core/component/DocumentPreview';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import { enableCanvasArtifacts } from '@core/constant/featureFlags';
import type { GraphicsEditor } from '@macro-inc/graphics';
import type { GraphicsPresence } from '@macro-inc/graphics/loro';
import {
@@ -14,6 +16,7 @@ import {
TextView,
} from '@macro-inc/graphics/solid';
import { createSignal, onCleanup, onMount, Show } from 'solid-js';
+import { ArtifactPresentation } from './artifact-presentation';
import { CanvasArtifactView } from './artifact-view';
import { CanvasDrawingToolbar, CanvasZoomToolbar } from './canvas-toolbars';
import { CanvasMediaView } from './embedded-items';
@@ -27,6 +30,8 @@ export function CanvasReadOnlyView(props: {
}) {
const [tool, setTool] = createSignal<'select' | 'pan'>('select');
const [activeArtifact, setActiveArtifact] = createSignal<string>();
+ const [presenting, setPresenting] = createSignal<string>();
+ const artifactsFlag = useFeatureFlag(enableCanvasArtifacts);
const [scale, setScale] = createSignal(props.editor.getCamera().scale);
const [hasSelection, setHasSelection] = createSignal(
props.editor.getSession().selectedIds.length > 0
@@ -115,6 +120,7 @@ export function CanvasReadOnlyView(props: {
active={activeArtifact() === p.item.id}
onEnter={() => setActiveArtifact(p.item.id)}
onExit={() => setActiveArtifact(undefined)}
+ onPresent={() => setPresenting(p.item.id)}
/>
),
connector: (p) => (
@@ -153,6 +159,18 @@ export function CanvasReadOnlyView(props: {
/>
)}
</Show>
+ <Show when={artifactsFlag().enabled ? presenting() : undefined} keyed>
+ {(startId) => (
+ <ArtifactPresentation
+ editor={props.editor}
+ startId={startId}
+ onExit={() => {
+ setPresenting(undefined);
+ focus();
+ }}
+ />
+ )}
+ </Show>
<CanvasDrawingToolbar
readOnly
tool={tool()}
diff --git a/apps/web/src/features/block-canvas/views/canvas-view.tsx b/apps/web/src/features/block-canvas/views/canvas-view.tsx
index 65cfd06edf..6c2fd3110e 100644
--- a/apps/web/src/features/block-canvas/views/canvas-view.tsx
+++ b/apps/web/src/features/block-canvas/views/canvas-view.tsx
@@ -11,8 +11,11 @@ import {
canLabel,
type DocumentGeometry,
distributeCommand,
+ movedInPresentation,
+ presentationOrder,
screenToWorld,
setArtifactCommand,
+ setPresentationOrderCommand,
styleCommand,
} from '@macro-inc/graphics';
import { attachConnectorControls } from '@macro-inc/graphics/browser';
@@ -63,6 +66,7 @@ import type {
import type { CanvasInsertState } from '../primitives/create-insert-state';
import { attachTextInput } from '../primitives/text-input';
import { useCanvasMediaSource } from '../queries/media';
+import { ArtifactPresentation } from './artifact-presentation';
import { CanvasArtifactView } from './artifact-view';
import { CanvasContextMenu } from './canvas-context-menu';
import {
@@ -119,6 +123,7 @@ export function CanvasView(props: {
};
const artifactsFlag = useFeatureFlag(enableCanvasArtifacts);
const artifacts = useArtifactLibrary();
+ const [presenting, setPresenting] = createSignal<string>();
const selectedImage = () => {
const item = selectedItem();
return item?.type === 'image' ? item : undefined;
@@ -263,6 +268,18 @@ export function CanvasView(props: {
data-canvas-next
>
<main class="relative size-full overflow-hidden">
+ <Show when={artifactsFlag().enabled ? presenting() : undefined} keyed>
+ {(startId) => (
+ <ArtifactPresentation
+ editor={editor}
+ startId={startId}
+ onExit={() => {
+ setPresenting(undefined);
+ focus();
+ }}
+ />
+ )}
+ </Show>
<Show when={props.insert.location()} keyed>
{(location) => (
<CanvasInsertMenu
@@ -460,6 +477,24 @@ export function CanvasView(props: {
content,
})
}
+ position={
+ presentationOrder(state.document).findIndex(
+ (item) => item.id === artifact().id
+ ) + 1
+ }
+ count={presentationOrder(state.document).length}
+ onPresent={() => setPresenting(artifact().id)}
+ onMove={(delta) => {
+ const ids = movedInPresentation(
+ state.document,
+ artifact().id,
+ delta
+ );
+ if (ids)
+ editor.execute(setPresentationOrderCommand, {
+ ids,
+ });
+ }}
/>
<Show when={artifacts.edit}>
{(edit) => (
@@ -670,6 +705,7 @@ export function CanvasView(props: {
active={state.embeds.active() === itemProps.item.id}
onEnter={() => state.embeds.enter(itemProps.item.id)}
onExit={exitEmbed}
+ onPresent={() => setPresenting(itemProps.item.id)}
/>
),
document: (itemProps) => (
diff --git a/docs/agent-guide/canvas.md b/docs/agent-guide/canvas.md
index e610d44e97..e1e0c0b7c2 100644
--- a/docs/agent-guide/canvas.md
+++ b/docs/agent-guide/canvas.md
@@ -34,6 +34,9 @@ double-click passes pointer input to it, and **Done** or a click elsewhere retur
to the canvas. With the flag off, an artifact shows only its title and no script runs.
The inspector also adds and edits styles and components shared across the canvas;
HTML uses them with `<macro-style name="…">` and `<macro-component name="…">`.
+**Present** on a node opens the artifacts full screen in presentation order, which
+**Earlier** and **Later** in the inspector change. Check arrow keys and Esc both
+before and after clicking inside the frame.
## Multiplayer canvas
diff --git a/packages/graphics/README.md b/packages/graphics/README.md
index 07bc0675c5..6019ce5762 100644
--- a/packages/graphics/README.md
+++ b/packages/graphics/README.md
@@ -485,7 +485,8 @@ design size and a presentation sort key. The HTML lays out at the design size an
scales to fit the box. Core treats the HTML as opaque content: it never parses or
executes it, and the default Solid renderer shows a placeholder. Hosts own
sandboxed rendering. `setArtifactCommand` edits content fields in one undo step;
-box size and pose stay with transform commands.
+box size and pose stay with transform commands. `presentationOrder` lists artifacts
+for presenting, and `setPresentationOrderCommand` reorders them in one undo step.
### Host-measured text fitting
diff --git a/packages/graphics/src/core/artifact-commands.ts b/packages/graphics/src/core/artifact-commands.ts
index 8eed065ff6..30adcd86c5 100644
--- a/packages/graphics/src/core/artifact-commands.ts
+++ b/packages/graphics/src/core/artifact-commands.ts
@@ -1,4 +1,6 @@
+import { presentationOrder } from './artifact-order';
import type { GraphicsCommand } from './commands';
+import { sortKeysBetween } from './ordering';
import { type ArtifactGeometry, artifactDefinition } from './shapes/artifact';
export type ArtifactContent = Partial<
@@ -32,3 +34,38 @@ export const setArtifactCommand: GraphicsCommand<{
};
},
};
+
+/** Listed artifacts present first, in that order; the rest keep their order after
+ * them. One reorder is one undo step. */
+export const setPresentationOrderCommand: GraphicsCommand<{
+ ids: readonly string[];
+}> = {
+ id: 'set-presentation-order',
+ apply: ({ document }, { ids }) => {
+ const items = { ...document.items };
+ const listed = new Set(ids);
+ for (const id of ids) {
+ if (document.items[id]?.type !== 'artifact')
+ throw new Error('Not an artifact');
+ }
+
+ const ordered = [
+ ...ids,
+ ...presentationOrder(document)
+ .map((item) => item.id)
+ .filter((id) => !listed.has(id)),
+ ];
+ const keys = sortKeysBetween(null, null, ordered.length);
+ ordered.forEach((id, index) => {
+ const item = document.items[id];
+ if (item?.type !== 'artifact') return;
+
+ items[id] = {
+ ...item,
+ geometry: { ...item.geometry, presentOrder: keys[index]! },
+ };
+ });
+
+ return { document: { ...document, items } };
+ },
+};
diff --git a/packages/graphics/src/core/artifact-order.ts b/packages/graphics/src/core/artifact-order.ts
index 0bd17db357..a2b543a544 100644
--- a/packages/graphics/src/core/artifact-order.ts
+++ b/packages/graphics/src/core/artifact-order.ts
@@ -21,3 +21,20 @@ export function nextPresentOrder(document: GraphicsDocument): string {
const last = presentationOrder(document).at(-1);
return sortKeysBetween(last?.geometry.presentOrder ?? null, null, 1)[0]!;
}
+
+/** The whole presentation with one artifact moved by `delta` places, or undefined
+ * when it would leave the ends. */
+export function movedInPresentation(
+ document: GraphicsDocument,
+ id: string,
+ delta: number
+): string[] | undefined {
+ const ids = presentationOrder(document).map((item) => item.id);
+ const from = ids.indexOf(id);
+ const to = from + delta;
+ if (from === -1 || to < 0 || to >= ids.length) return undefined;
+
+ ids.splice(from, 1);
+ ids.splice(to, 0, id);
+ return ids;
+}
diff --git a/packages/graphics/tests/artifact-order.test.ts b/packages/graphics/tests/artifact-order.test.ts
index 5dacd5d122..ae50f0e526 100644
--- a/packages/graphics/tests/artifact-order.test.ts
+++ b/packages/graphics/tests/artifact-order.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import { createScene, translation } from '../src/core';
import {
+ movedInPresentation,
nextPresentOrder,
presentationOrder,
} from '../src/core/artifact-order';
@@ -42,4 +43,12 @@ describe('presentation order', () => {
expect(nextPresentOrder(scene) > 'a5').toBe(true);
});
+
+ it('moves an artifact within the presentation and stops at the ends', () => {
+ const scene = createScene([artifact('1', 'a0'), artifact('2', 'a1')]);
+
+ expect(movedInPresentation(scene, '1', 1)).toEqual(['2', '1']);
+ expect(movedInPresentation(scene, '1', -1)).toBeUndefined();
+ expect(movedInPresentation(scene, '2', 1)).toBeUndefined();
+ });
});