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): share styles and components across a canvas's artifacts (#9628)

Eric Hayesce7984a95c8c
diff --git a/apps/web/src/features/block-canvas/README.md b/apps/web/src/features/block-canvas/README.md
index fb2a1f4fb6..68f0795e8b 100644
--- a/apps/web/src/features/block-canvas/README.md
+++ b/apps/web/src/features/block-canvas/README.md
@@ -77,6 +77,14 @@ off-screen scripts stop and restart with fresh state. With the flag off, a node
shows its title and no script runs. The headless render bundle has no flag reader,
so its caller says whether to run artifacts, in the same sandbox.
+Each canvas has a library of named styles and components, in root Loro maps beside
+the scene, edited from the inspector. An artifact uses them with
+`<macro-style name="brand"></macro-style>` and
+`<macro-component name="card">children</macro-component>`, whose children replace
+the component's `<slot>`. They expand when the document is composed, so a library
+edit updates every artifact using it. JSON export carries only the scene, so a
+downloaded canvas loses its library.
+
## 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-sandbox.browser.e2e.ts b/apps/web/src/features/block-canvas/browser-test/artifact-sandbox.browser.e2e.ts
index 35e396a509..08479fe4ad 100644
--- a/apps/web/src/features/block-canvas/browser-test/artifact-sandbox.browser.e2e.ts
+++ b/apps/web/src/features/block-canvas/browser-test/artifact-sandbox.browser.e2e.ts
@@ -1,4 +1,5 @@
import { createScene, translation } from '@macro-inc/graphics';
+import type { ArtifactLibrary } from '@macro-inc/graphics/loro';
import { expect, type Frame, type Page, test } from '@playwright/test';
// A fresh page loads the render bundle unbundled from the dev server.
@@ -24,21 +25,26 @@ const artifactScene = (html: string) =>
},
]);
-async function renderArtifact(page: Page, html: string): Promise<Frame> {
+async function renderArtifact(
+ page: Page,
+ html: string,
+ artifactLibrary?: ArtifactLibrary
+): Promise<Frame> {
await page.goto('/canvas-render.html');
await page.waitForFunction(() => window.canvasRenderIdle === true, null, {
timeout: 150_000,
});
await page.evaluate(
- (document) =>
+ ({ document, artifactLibrary }) =>
window.renderCanvasSnapshot({
document,
+ artifactLibrary,
crop: { x: 0, y: 0, width: 640, height: 360 },
scale: 1,
revision: 'test',
artifacts: true,
}),
- artifactScene(html)
+ { document: artifactScene(html), artifactLibrary }
);
const element = await page.waitForSelector(
@@ -145,3 +151,18 @@ test('stops an artifact that keeps navigating away', async ({ page }) => {
0
);
});
+
+test('expands shared styles and components', async ({ page }) => {
+ const frame = await renderArtifact(
+ page,
+ '<macro-style name="brand"></macro-style><macro-component name="card">Hello</macro-component>',
+ {
+ styles: { brand: '#card { color: rgb(255, 0, 0); }' },
+ components: { card: '<p id="card"><slot></slot></p>' },
+ }
+ );
+
+ const card = frame.locator('#card');
+ await expect(card).toHaveText('Hello');
+ await expect(card).toHaveCSS('color', 'rgb(255, 0, 0)');
+});
diff --git a/apps/web/src/features/block-canvas/canvas-next.tsx b/apps/web/src/features/block-canvas/canvas-next.tsx
index f57437187c..0a82ee8b39 100644
--- a/apps/web/src/features/block-canvas/canvas-next.tsx
+++ b/apps/web/src/features/block-canvas/canvas-next.tsx
@@ -20,9 +20,13 @@ import {
} from '@macro-inc/graphics/loro';
import { fetchDocumentMetadata } from '@queries/storage/document-metadata';
import type { LoroDoc } from 'loro-crdt';
-import { onCleanup, Show } from 'solid-js';
+import { createSignal, onCleanup, Show } from 'solid-js';
import { CanvasBlockEmbed } from './block-embed-adapter';
import { createCanvasClipboard } from './clipboard';
+import {
+ ArtifactLibraryContext,
+ NO_ARTIFACT_LIBRARY,
+} from './context/artifact-library';
import { readSharedCanvas } from './core/collaboration';
import type { CanvasFile } from './core/document-format';
import { registerCanvasNextHotkeys } from './hotkeys';
@@ -82,31 +86,52 @@ export function CanvasNextEditor(props: {
: undefined;
let finishText = () => {};
props.onReady?.(editor, () => finishText());
+ const [artifactLibrary, setArtifactLibrary] = createSignal(
+ backend?.artifactLibrary.read() ?? NO_ARTIFACT_LIBRARY
+ );
+ if (backend)
+ onCleanup(
+ backend.artifactLibrary.subscribe(() =>
+ setArtifactLibrary(backend.artifactLibrary.read())
+ )
+ );
return (
- <StaticMarkdownContext>
- <Show
- when={props.canEdit && !props.isEmbedded}
- fallback={
- <CanvasReadOnlyView
+ <ArtifactLibraryContext.Provider
+ value={{
+ library: artifactLibrary,
+ // Read when used, so a change of access while open takes effect.
+ get edit() {
+ return backend && props.canEdit && !props.isEmbedded
+ ? backend.artifactLibrary.edit
+ : undefined;
+ },
+ }}
+ >
+ <StaticMarkdownContext>
+ <Show
+ when={props.canEdit && !props.isEmbedded}
+ fallback={
+ <CanvasReadOnlyView
+ editor={editor}
+ fitOnLoad={props.fitOnLoad}
+ presence={presence}
+ />
+ }
+ >
+ <EditableCanvasNext
+ documentId={props.documentId}
editor={editor}
- fitOnLoad={props.fitOnLoad}
presence={presence}
+ measureText={measurement.measure}
+ fitOnLoad={props.fitOnLoad}
+ canEdit={() => props.canEdit}
+ onFinishReady={(finish) => {
+ finishText = finish;
+ }}
/>
- }
- >
- <EditableCanvasNext
- documentId={props.documentId}
- editor={editor}
- presence={presence}
- measureText={measurement.measure}
- fitOnLoad={props.fitOnLoad}
- canEdit={() => props.canEdit}
- onFinishReady={(finish) => {
- finishText = finish;
- }}
- />
- </Show>
- </StaticMarkdownContext>
+ </Show>
+ </StaticMarkdownContext>
+ </ArtifactLibraryContext.Provider>
);
}
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 c572484881..7de56c86a9 100644
--- a/apps/web/src/features/block-canvas/components/artifact-inspector.tsx
+++ b/apps/web/src/features/block-canvas/components/artifact-inspector.tsx
@@ -3,6 +3,7 @@ import {
type ArtifactContent,
type ArtifactItem,
} from '@macro-inc/graphics';
+import { Input } from '@ui';
import { InspectorField } from './inspector-field';
import { InspectorSection } from './inspector-section';
@@ -13,8 +14,8 @@ export function ArtifactInspector(props: {
return (
<InspectorSection title="Artifact">
<InspectorField label="Title">
- <input
- class="w-full rounded border border-edge-muted bg-panel px-2 py-1 text-xs text-ink outline-none focus:border-edge-focus"
+ <Input
+ size="sm"
aria-label="Artifact title"
value={props.item.geometry.title}
onChange={(event) =>
diff --git a/apps/web/src/features/block-canvas/components/artifact-library-inspector.tsx b/apps/web/src/features/block-canvas/components/artifact-library-inspector.tsx
new file mode 100644
index 0000000000..dc9a2786d1
--- /dev/null
+++ b/apps/web/src/features/block-canvas/components/artifact-library-inspector.tsx
@@ -0,0 +1,73 @@
+import type {
+ ArtifactLibrary,
+ ArtifactLibraryEdit,
+ ArtifactLibraryKind,
+} from '@macro-inc/graphics/loro';
+import { ARTIFACT_LIBRARY_ENTRY_MAX_LENGTH } from '@macro-inc/graphics/loro';
+import { Button, Input } from '@ui';
+import { createSignal, For } from 'solid-js';
+import { InspectorField } from './inspector-field';
+import { InspectorSection } from './inspector-section';
+
+export function ArtifactLibraryInspector(props: {
+ library: ArtifactLibrary;
+ onEdit: (edit: ArtifactLibraryEdit) => void;
+}) {
+ const [name, setName] = createSignal('');
+ const add = (kind: ArtifactLibraryKind) => {
+ const trimmed = name().trim();
+ // Adding over an existing name would blank it for everyone.
+ if (!trimmed || Object.hasOwn(props.library[kind], trimmed)) return;
+
+ props.onEdit({ kind, name: trimmed, source: '' });
+ setName('');
+ };
+ const entries = (
+ kind: ArtifactLibraryKind,
+ label: (name: string) => string
+ ) => (
+ <For each={Object.keys(props.library[kind]).sort()}>
+ {(entry) => (
+ <InspectorField label={label(entry)}>
+ <textarea
+ class="h-24 w-full resize-y rounded border border-edge-muted bg-panel px-2 py-1 font-mono text-xs text-ink outline-none focus:border-edge-focus"
+ aria-label={label(entry)}
+ spellcheck={false}
+ maxLength={ARTIFACT_LIBRARY_ENTRY_MAX_LENGTH}
+ value={props.library[kind][entry]}
+ onChange={(event) =>
+ props.onEdit({
+ kind,
+ name: entry,
+ // An emptied entry is a removed entry.
+ source: event.currentTarget.value || null,
+ })
+ }
+ />
+ </InspectorField>
+ )}
+ </For>
+ );
+
+ return (
+ <InspectorSection title="Shared with this canvas's artifacts">
+ {entries('styles', (entry) => `Style: ${entry}`)}
+ {entries('components', (entry) => `Component: ${entry}`)}
+ <Input
+ size="sm"
+ aria-label="New shared entry name"
+ placeholder="Name"
+ value={name()}
+ onInput={(event) => setName(event.currentTarget.value)}
+ />
+ <div class="flex gap-1">
+ <Button variant="primary" size="sm" onClick={() => add('styles')}>
+ Add style
+ </Button>
+ <Button variant="primary" size="sm" onClick={() => add('components')}>
+ Add component
+ </Button>
+ </div>
+ </InspectorSection>
+ );
+}
diff --git a/apps/web/src/features/block-canvas/context/artifact-library.ts b/apps/web/src/features/block-canvas/context/artifact-library.ts
new file mode 100644
index 0000000000..29091e848e
--- /dev/null
+++ b/apps/web/src/features/block-canvas/context/artifact-library.ts
@@ -0,0 +1,18 @@
+import type {
+ ArtifactLibrary,
+ ArtifactLibraryEdit,
+} from '@macro-inc/graphics/loro';
+import { type Accessor, createContext, useContext } from 'solid-js';
+
+export const NO_ARTIFACT_LIBRARY: ArtifactLibrary = {
+ styles: {},
+ components: {},
+};
+
+export const ArtifactLibraryContext = createContext<{
+ library: Accessor<ArtifactLibrary>;
+ /** Absent for viewers and for canvases that are not shared. */
+ edit?: (edit: ArtifactLibraryEdit) => void;
+}>({ library: () => NO_ARTIFACT_LIBRARY });
+
+export const useArtifactLibrary = () => useContext(ArtifactLibraryContext);
diff --git a/apps/web/src/features/block-canvas/core/artifact-document.test.ts b/apps/web/src/features/block-canvas/core/artifact-document.test.ts
index eafd66cc3a..9e87c54606 100644
--- a/apps/web/src/features/block-canvas/core/artifact-document.test.ts
+++ b/apps/web/src/features/block-canvas/core/artifact-document.test.ts
@@ -5,6 +5,8 @@ import {
isArtifactLoadMarker,
} from './artifact-document';
+const NO_LIBRARY = { styles: {}, components: {} };
+
const parse = (html: string) =>
new DOMParser().parseFromString(html, 'text/html');
@@ -13,6 +15,7 @@ describe('composeArtifactDocument', () => {
const composed = composeArtifactDocument(
'<html><head><script>run()</script></head><body>Hi</body></html>',
{},
+ NO_LIBRARY,
'token'
);
@@ -28,6 +31,7 @@ describe('composeArtifactDocument', () => {
const composed = composeArtifactDocument(
'<script>run()</script>',
{},
+ NO_LIBRARY,
'token'
);
@@ -38,6 +42,7 @@ describe('composeArtifactDocument', () => {
const composed = composeArtifactDocument(
'<meta http-equiv="REFRESH" content="0;url=https://example.com"><p>Hi</p>',
{},
+ NO_LIBRARY,
'token'
);
@@ -49,16 +54,79 @@ describe('composeArtifactDocument', () => {
const composed = composeArtifactDocument(
'<p>Hi</p>',
{ '--color-ink': '#111' },
+ NO_LIBRARY,
'token'
);
expect(composed).toContain(':root{--color-ink:#111}');
});
+ it('expands components around their children, including nested ones', () => {
+ const composed = composeArtifactDocument(
+ '<macro-component name="card"><macro-component name="title">Hi</macro-component></macro-component>',
+ {},
+ {
+ styles: {},
+ components: {
+ card: '<section class="card"><slot></slot></section>',
+ title: '<h1><slot></slot></h1>',
+ },
+ },
+ 'token'
+ );
+
+ expect(parse(composed).body.innerHTML).toBe(
+ '<section class="card"><h1>Hi</h1></section>'
+ );
+ });
+
+ it('terminates on components that use each other', () => {
+ const composed = composeArtifactDocument(
+ '<macro-component name="a"></macro-component>',
+ {},
+ {
+ styles: {},
+ components: {
+ a: '<macro-component name="b"></macro-component>',
+ b: '<macro-component name="a"></macro-component>',
+ },
+ },
+ 'token'
+ );
+
+ expect(composed).not.toContain('macro-component');
+ });
+
+ it('stops expanding a component that fans out past the budget', () => {
+ const fanOut = '<macro-component name="a"></macro-component>'.repeat(20);
+ const composed = composeArtifactDocument(
+ '<macro-component name="a"></macro-component>',
+ {},
+ { styles: {}, components: { a: fanOut } },
+ 'token'
+ );
+
+ expect(composed).not.toContain('macro-component');
+ });
+
+ it('adds shared styles and drops unknown names', () => {
+ const composed = composeArtifactDocument(
+ '<macro-style name="brand"></macro-style><macro-style name="constructor"></macro-style><macro-component name="constructor">Kept</macro-component>',
+ {},
+ { styles: { brand: 'h1{color:red}' }, components: {} },
+ 'token'
+ );
+
+ expect(composed).toContain('<style>h1{color:red}</style>');
+ expect(composed).not.toContain('macro-style');
+ expect(parse(composed).body.textContent).toContain('Kept');
+ });
+
it('marks its own load before any artifact script can run', () => {
const composed = composeArtifactDocument(
'<script>run()</script>',
{},
+ NO_LIBRARY,
'secret'
);
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 e97dded3af..8d21a562ce 100644
--- a/apps/web/src/features/block-canvas/core/artifact-document.ts
+++ b/apps/web/src/features/block-canvas/core/artifact-document.ts
@@ -1,3 +1,5 @@
+import type { ArtifactLibrary } from '@macro-inc/graphics/loro';
+
/**
* The iframe's `sandbox` gives the document an opaque origin, so it cannot reach
* Macro's cookies, storage or DOM. This policy keeps it off the network: scripts
@@ -33,6 +35,64 @@ export function artifactThemeTokens(element: Element): Record<string, string> {
);
}
+/** 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;
+const MAX_EXPANDED_LENGTH = 2_000_000;
+
+const entry = (
+ entries: Readonly<Record<string, string>>,
+ name: string | null
+) =>
+ name !== null && Object.hasOwn(entries, name) ? entries[name] : undefined;
+
+/**
+ * `<macro-component name="card">` becomes that component, with its children in
+ * place of the component's `<slot>`. `<macro-style name="brand">` becomes a style
+ * element. An unknown component keeps its children, and an unknown style is dropped.
+ */
+function expandLibrary(parsed: Document, library: ArtifactLibrary) {
+ // One work list rather than re-querying after each expansion, which is quadratic.
+ const pending = Array.from(parsed.querySelectorAll('macro-component'));
+ let expansions = 0;
+ let expandedLength = 0;
+ while (pending.length) {
+ const use = pending.pop()!;
+ // Gone with a component that had no slot for it.
+ if (!use.isConnected) continue;
+
+ const source = entry(library.components, use.getAttribute('name'));
+ expansions += 1;
+ expandedLength += source?.length ?? 0;
+ if (
+ expansions > MAX_COMPONENT_EXPANSIONS ||
+ expandedLength > MAX_EXPANDED_LENGTH
+ ) {
+ // Past the budget, keep what the remaining uses wrap without expanding them.
+ use.replaceWith(...use.childNodes);
+ continue;
+ }
+
+ const template = parsed.createElement('template');
+ template.innerHTML = source ?? '<slot></slot>';
+ const nested = template.content.querySelectorAll('macro-component');
+ pending.push(...nested);
+ template.content.querySelector('slot')?.replaceWith(...use.childNodes);
+ use.replaceWith(template.content);
+ }
+
+ for (const use of parsed.querySelectorAll('macro-style')) {
+ const source = entry(library.styles, use.getAttribute('name'));
+ if (source === undefined) {
+ use.remove();
+ continue;
+ }
+
+ const style = parsed.createElement('style');
+ style.textContent = source;
+ use.replaceWith(style);
+ }
+}
/**
* Tells the host that its own document, not some page navigated to, has loaded.
* It runs before any artifact code and removes itself, keeping the token in a
@@ -58,9 +118,11 @@ export const isArtifactLoadMarker = (data: unknown, token: string) =>
export function composeArtifactDocument(
html: string,
tokens: Record<string, string>,
+ library: ArtifactLibrary,
loadToken: string
): string {
const parsed = new DOMParser().parseFromString(html, 'text/html');
+ expandLibrary(parsed, library);
for (const refresh of parsed.querySelectorAll('meta[http-equiv="refresh" i]'))
refresh.remove();
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 b8f6d8c110..0d63e62a25 100644
--- a/apps/web/src/features/block-canvas/views/artifact-frame.tsx
+++ b/apps/web/src/features/block-canvas/views/artifact-frame.tsx
@@ -7,6 +7,7 @@ import {
onMount,
Show,
} from 'solid-js';
+import { useArtifactLibrary } from '../context/artifact-library';
import {
ARTIFACT_SANDBOX,
artifactThemeTokens,
@@ -29,6 +30,7 @@ export function ArtifactFrame(props: {
eager?: boolean;
}) {
let host!: HTMLDivElement;
+ const artifacts = useArtifactLibrary();
const [size, setSize] = createSignal({ width: 0, height: 0 });
const [visible, setVisible] = createSignal(!!props.eager);
const [generation, setGeneration] = createSignal(0);
@@ -45,6 +47,7 @@ export function ArtifactFrame(props: {
composeArtifactDocument(
props.html,
artifactThemeTokens(document.documentElement),
+ artifacts.library(),
loadToken
)
);
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 55e13874f1..65cfd06edf 100644
--- a/apps/web/src/features/block-canvas/views/canvas-view.tsx
+++ b/apps/web/src/features/block-canvas/views/canvas-view.tsx
@@ -39,6 +39,7 @@ import {
} from 'solid-js';
import type { CanvasClipboard } from '../clipboard';
import { ArtifactInspector } from '../components/artifact-inspector';
+import { ArtifactLibraryInspector } from '../components/artifact-library-inspector';
import { ConnectorInspector } from '../components/connector-inspector';
import type { CanvasEmbedViewProps } from '../components/embed-view';
import { EraserTrail } from '../components/eraser-trail';
@@ -46,6 +47,7 @@ import { MediaUploadPreviews } from '../components/media-upload-previews';
import { SelectionLayoutInspector } from '../components/selection-layout-inspector';
import { StyleInspector } from '../components/style-inspector';
import { TextInspector } from '../components/text-inspector';
+import { useArtifactLibrary } from '../context/artifact-library';
import { setDocumentDisplayCommand } from '../core/document-display';
import {
selectionLayoutCommand,
@@ -116,6 +118,7 @@ export function CanvasView(props: {
return item?.type === 'artifact' ? item : undefined;
};
const artifactsFlag = useFeatureFlag(enableCanvasArtifacts);
+ const artifacts = useArtifactLibrary();
const selectedImage = () => {
const item = selectedItem();
return item?.type === 'image' ? item : undefined;
@@ -448,15 +451,25 @@ export function CanvasView(props: {
</Show>
<Show when={artifactsFlag().enabled && selectedArtifact()}>
{(artifact) => (
- <ArtifactInspector
- item={artifact()}
- onChange={(content) =>
- editor.execute(setArtifactCommand, {
- id: artifact().id,
- content,
- })
- }
- />
+ <>
+ <ArtifactInspector
+ item={artifact()}
+ onChange={(content) =>
+ editor.execute(setArtifactCommand, {
+ id: artifact().id,
+ content,
+ })
+ }
+ />
+ <Show when={artifacts.edit}>
+ {(edit) => (
+ <ArtifactLibraryInspector
+ library={artifacts.library()}
+ onEdit={edit()}
+ />
+ )}
+ </Show>
+ </>
)}
</Show>
<Show when={selectedImage()}>
diff --git a/apps/web/src/features/block-canvas/views/render-entry.tsx b/apps/web/src/features/block-canvas/views/render-entry.tsx
index 4add3cbf49..f8314038da 100644
--- a/apps/web/src/features/block-canvas/views/render-entry.tsx
+++ b/apps/web/src/features/block-canvas/views/render-entry.tsx
@@ -14,6 +14,7 @@ import {
type TextFitRequest,
type TextFitResult,
} from '@macro-inc/graphics';
+import type { ArtifactLibrary } from '@macro-inc/graphics/loro';
import {
ConnectorView,
EllipseView,
@@ -23,6 +24,10 @@ import {
} from '@macro-inc/graphics/solid';
import { Show } from 'solid-js';
import { render } from 'solid-js/web';
+import {
+ ArtifactLibraryContext,
+ NO_ARTIFACT_LIBRARY,
+} from '../context/artifact-library';
import { ArtifactFrame } from './artifact-frame';
import { CanvasTextContent, createCanvasTextMeasurer } from './text-content';
@@ -46,6 +51,7 @@ declare global {
revision: string;
/** Whether the requesting user has artifacts; off shows only titles. */
artifacts?: boolean;
+ artifactLibrary?: ArtifactLibrary;
}) => Promise<void>;
measureCanvasSnapshot: (snapshot: {
document: GraphicsDocument;
@@ -129,72 +135,78 @@ window.renderCanvasSnapshot = async (snapshot) => {
document.documentElement.style.colorScheme = 'light';
const unmount = render(
() => (
- <StaticMarkdownContext>
- <div
- data-canvas-revision={snapshot.revision}
- style={{
- position: 'fixed',
- inset: 0,
- background: '#ffffff',
- color: '#171717',
- }}
- >
- <GraphicsSurface
- editor={editor}
- hideSelection
- gridColor="transparent"
- input={{ editing: false }}
- renderers={{
- rectangle: (props) => (
- <RectangleView {...props} contentView={CanvasTextContent} />
- ),
- ellipse: (props) => (
- <EllipseView {...props} contentView={CanvasTextContent} />
- ),
- connector: (props) => (
- <ConnectorView {...props} contentView={CanvasTextContent} />
- ),
- text: (props) => (
- <TextView {...props} contentView={CanvasTextContent} />
- ),
- artifact: (props) => (
- <Show
- when={snapshot.artifacts}
- fallback={
- <div class="size-full border border-edge-muted p-2 text-xs">
- Artifact: {props.item.geometry.title}
- </div>
- }
- >
- <ArtifactFrame
- html={props.item.geometry.html}
- title={props.item.geometry.title}
- designWidth={props.item.geometry.designWidth}
- designHeight={props.item.geometry.designHeight}
- interactive={false}
- eager
- />
- </Show>
- ),
- image: (props) => (
- <div class="size-full border border-edge-muted p-2 text-xs">
- Image unavailable: {props.item.geometry.name}
- </div>
- ),
- video: (props) => (
- <div class="size-full border border-edge-muted p-2 text-xs">
- Video unavailable: {props.item.geometry.name}
- </div>
- ),
- document: (props) => (
- <div class="size-full border border-edge-muted p-2 text-xs">
- Document unavailable: {props.item.geometry.name}
- </div>
- ),
+ <ArtifactLibraryContext.Provider
+ value={{
+ library: () => snapshot.artifactLibrary ?? NO_ARTIFACT_LIBRARY,
+ }}
+ >
+ <StaticMarkdownContext>
+ <div
+ data-canvas-revision={snapshot.revision}
+ style={{
+ position: 'fixed',
+ inset: 0,
+ background: '#ffffff',
+ color: '#171717',
}}
- />
- </div>
- </StaticMarkdownContext>
+ >
+ <GraphicsSurface
+ editor={editor}
+ hideSelection
+ gridColor="transparent"
+ input={{ editing: false }}
+ renderers={{
+ rectangle: (props) => (
+ <RectangleView {...props} contentView={CanvasTextContent} />
+ ),
+ ellipse: (props) => (
+ <EllipseView {...props} contentView={CanvasTextContent} />
+ ),
+ connector: (props) => (
+ <ConnectorView {...props} contentView={CanvasTextContent} />
+ ),
+ text: (props) => (
+ <TextView {...props} contentView={CanvasTextContent} />
+ ),
+ artifact: (props) => (
+ <Show
+ when={snapshot.artifacts}
+ fallback={
+ <div class="size-full border border-edge-muted p-2 text-xs">
+ Artifact: {props.item.geometry.title}
+ </div>
+ }
+ >
+ <ArtifactFrame
+ html={props.item.geometry.html}
+ title={props.item.geometry.title}
+ designWidth={props.item.geometry.designWidth}
+ designHeight={props.item.geometry.designHeight}
+ interactive={false}
+ eager
+ />
+ </Show>
+ ),
+ image: (props) => (
+ <div class="size-full border border-edge-muted p-2 text-xs">
+ Image unavailable: {props.item.geometry.name}
+ </div>
+ ),
+ video: (props) => (
+ <div class="size-full border border-edge-muted p-2 text-xs">
+ Video unavailable: {props.item.geometry.name}
+ </div>
+ ),
+ document: (props) => (
+ <div class="size-full border border-edge-muted p-2 text-xs">
+ Document unavailable: {props.item.geometry.name}
+ </div>
+ ),
+ }}
+ />
+ </div>
+ </StaticMarkdownContext>
+ </ArtifactLibraryContext.Provider>
),
root
);
diff --git a/docs/agent-guide/canvas.md b/docs/agent-guide/canvas.md
index d24661e349..e610d44e97 100644
--- a/docs/agent-guide/canvas.md
+++ b/docs/agent-guide/canvas.md
@@ -32,6 +32,8 @@ Artifacts are behind the `enable-canvas-artifacts` flag. **Insert** offers
title and HTML. The document runs in a sandboxed frame; **Interact** or a
double-click passes pointer input to it, and **Done** or a click elsewhere returns
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="…">`.
## Multiplayer canvas
diff --git a/packages/graphics/src/loro/README.md b/packages/graphics/src/loro/README.md
index f829d1c7d7..5c6260c0fa 100644
--- a/packages/graphics/src/loro/README.md
+++ b/packages/graphics/src/loro/README.md
@@ -166,6 +166,11 @@ finished edits become one backend transaction. Tests cover conflicting strings,
text-versus-move, new labels versus moves, and local undo preserving remote moves.
Image, video and document references use the existing shape geometry mapping.
+A canvas's shared artifact styles and components use the `artifactStyles` and
+`artifactComponents` root maps, one last-writer-wins string per name. Clients that
+do not know them ignore them. `commit` takes library edits, so that a batch writes
+them in the same update as its scene change.
+
Artifact HTML and presentation order use their own `html` and `presentOrder`
registers, so content edits and moves merge independently. Like text, HTML is one
whole-string register: concurrent edits to the same artifact keep one version.
diff --git a/packages/graphics/src/loro/artifact-library.ts b/packages/graphics/src/loro/artifact-library.ts
new file mode 100644
index 0000000000..687072197d
--- /dev/null
+++ b/packages/graphics/src/loro/artifact-library.ts
@@ -0,0 +1,66 @@
+import type { LoroDoc } from 'loro-crdt';
+
+/**
+ * Styles and components that a canvas's artifacts share, keyed by name. They sit
+ * in root maps beside the scene: each entry is one last-writer-wins string, and
+ * clients that do not know them ignore them.
+ */
+export type ArtifactLibrary = Readonly<{
+ styles: Readonly<Record<string, string>>;
+ components: Readonly<Record<string, string>>;
+}>;
+export type ArtifactLibraryKind = keyof ArtifactLibrary;
+export type ArtifactLibraryEdit = Readonly<{
+ kind: ArtifactLibraryKind;
+ name: string;
+ /** Null removes the entry. */
+ source: string | null;
+}>;
+
+/** Authoring limit for hosts and AI edits; stored entries are not rejected. */
+export const ARTIFACT_LIBRARY_ENTRY_MAX_LENGTH = 64_000;
+
+const ROOTS: Record<ArtifactLibraryKind, string> = {
+ styles: 'artifactStyles',
+ components: 'artifactComponents',
+};
+
+function strings(value: unknown): Record<string, string> {
+ if (!value || typeof value !== 'object') return {};
+
+ return Object.fromEntries(
+ Object.entries(value).filter(
+ (entry): entry is [string, string] => typeof entry[1] === 'string'
+ )
+ );
+}
+
+export function readArtifactLibrary(doc: LoroDoc): ArtifactLibrary {
+ return {
+ styles: strings(doc.getMap(ROOTS.styles).toJSON()),
+ components: strings(doc.getMap(ROOTS.components).toJSON()),
+ };
+}
+
+/** Stages edits on the document's open transaction; the caller commits. */
+export function applyArtifactLibraryEdits(
+ doc: LoroDoc,
+ edits: readonly ArtifactLibraryEdit[]
+) {
+ for (const edit of edits) {
+ const entries = doc.getMap(ROOTS[edit.kind]);
+ if (edit.source === null) entries.delete(edit.name);
+ else entries.set(edit.name, edit.source);
+ }
+}
+
+export function subscribeArtifactLibrary(doc: LoroDoc, listener: () => void) {
+ const unsubscribes = [
+ doc.getMap(ROOTS.styles).subscribe(listener),
+ doc.getMap(ROOTS.components).subscribe(listener),
+ ];
+
+ return () => {
+ for (const unsubscribe of unsubscribes) unsubscribe();
+ };
+}
diff --git a/packages/graphics/src/loro/backend.ts b/packages/graphics/src/loro/backend.ts
index fed2142b9d..ea7d1c4ef3 100644
--- a/packages/graphics/src/loro/backend.ts
+++ b/packages/graphics/src/loro/backend.ts
@@ -3,6 +3,12 @@ import { LoroDoc, type PeerID, UndoManager } from 'loro-crdt';
import type { GraphicsBackend } from '../core/backend';
import type { GraphicsDocument } from '../core/model';
import { freezeDocument } from '../core/scene';
+import {
+ type ArtifactLibraryEdit,
+ applyArtifactLibraryEdits,
+ readArtifactLibrary,
+ subscribeArtifactLibrary,
+} from './artifact-library';
import { readScene, writeScene } from './scene-mapping';
import { canvasSchema } from './schema';
@@ -132,17 +138,29 @@ function graphicsBackend(
canUndo: !disposed && canEdit() && history.canUndo(),
canRedo: !disposed && canEdit() && history.canRedo(),
}),
- commit(next: GraphicsDocument) {
+ /** Library edits land in the same update as the scene change. */
+ commit(
+ next: GraphicsDocument,
+ libraryEdits: readonly ArtifactLibraryEdit[] = []
+ ) {
const validated = freezeDocument(next);
- local('local', () =>
+ local('local', () => {
mirror.setState({
scene: writeScene(
mirror.getState().scene,
projection.document,
validated
),
- })
- );
+ });
+ applyArtifactLibraryEdits(doc, libraryEdits);
+ });
+ },
+ artifactLibrary: {
+ read: () => readArtifactLibrary(doc),
+ subscribe: (listener: () => void) =>
+ subscribeArtifactLibrary(doc, listener),
+ edit: (edit: ArtifactLibraryEdit) =>
+ local('local', () => applyArtifactLibraryEdits(doc, [edit])),
},
undo() {
if (!disposed && history.canUndo())
diff --git a/packages/graphics/src/loro/index.ts b/packages/graphics/src/loro/index.ts
index 6e2106a1a3..997f604f75 100644
--- a/packages/graphics/src/loro/index.ts
+++ b/packages/graphics/src/loro/index.ts
@@ -1,3 +1,9 @@
+export {
+ ARTIFACT_LIBRARY_ENTRY_MAX_LENGTH,
+ type ArtifactLibrary,
+ type ArtifactLibraryEdit,
+ type ArtifactLibraryKind,
+} from './artifact-library';
export {
createLoroGraphicsBackend,
createLoroGraphicsBackendFromDoc,
diff --git a/packages/graphics/tests/loro.test.ts b/packages/graphics/tests/loro.test.ts
index 316e977157..007d95d7b2 100644
--- a/packages/graphics/tests/loro.test.ts
+++ b/packages/graphics/tests/loro.test.ts
@@ -341,3 +341,54 @@ it('artifact content and pose merge independently and survive a reload', () => {
b.execute(setArtifactCommand, { id: 'art', content: { designWidth: 0 } })
).toThrow('Invalid artifact geometry');
});
+
+it('syncs the artifact library between peers in one update with a scene change', async () => {
+ const seed = createLoroSeed(
+ createScene([
+ {
+ id: 'box',
+ type: 'rectangle',
+ placement: { parentId: 'scene-root', sortKey: 'a0' },
+ transform: translation(0, 0),
+ geometry: { width: 10, height: 10 },
+ appearance: { fill: '#000', stroke: '#000' },
+ },
+ ])
+ );
+ const left = createLoroGraphicsBackend(seed, '1', 'scene-root');
+ const right = createLoroGraphicsBackend(seed, '2', 'scene-root');
+ const updates: Uint8Array[] = [];
+ left.subscribeUpdates((bytes) => updates.push(bytes));
+
+ const notified = vi.fn();
+ right.artifactLibrary.subscribe(notified);
+
+ const moved = left.getDocument();
+ const box = moved.items.box;
+ if (box?.type !== 'rectangle') throw new Error('Missing box');
+ left.commit(
+ {
+ ...moved,
+ items: { ...moved.items, box: { ...box, transform: translation(5, 5) } },
+ },
+ [{ kind: 'styles', name: 'brand', source: 'h1{color:red}' }]
+ );
+ expect(updates).toHaveLength(1);
+
+ right.receive(updates[0]!);
+ await Promise.resolve();
+ expect(notified).toHaveBeenCalled();
+ expect(right.artifactLibrary.read().styles).toEqual({
+ brand: 'h1{color:red}',
+ });
+ expect(right.getDocument().items.box).toMatchObject({
+ transform: translation(5, 5),
+ });
+
+ left.artifactLibrary.edit({ kind: 'styles', name: 'brand', source: null });
+ right.receive(updates[1]!);
+ expect(right.artifactLibrary.read().styles).toEqual({});
+
+ left.dispose();
+ right.dispose();
+});