Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(graphics): add artifact shape kind (#9602)
Eric Hayes90db518416ae
diff --git a/apps/web/src/features/block-canvas/primitives/create-canvas-state.ts b/apps/web/src/features/block-canvas/primitives/create-canvas-state.tsindex ee68810be8..4dd01391f6 100644--- a/apps/web/src/features/block-canvas/primitives/create-canvas-state.ts+++ b/apps/web/src/features/block-canvas/primitives/create-canvas-state.ts@@ -26,7 +26,7 @@ export type CanvasTool =| 'pan'| 'arrow'| 'line'- | Exclude<ShapeKind, 'image' | 'video' | 'document'>;+ | Exclude<ShapeKind, 'image' | 'video' | 'document' | 'artifact'>;export type CanvasState = ReturnType<typeof createCanvasState>;export function createCanvasState(diff --git a/packages/graphics/README.md b/packages/graphics/README.mdindex 218c4810ee..07bc0675c5 100644--- a/packages/graphics/README.md+++ b/packages/graphics/README.md@@ -36,7 +36,7 @@ Keys must be unique among siblings; different parents may reuse keys. Comparisonuses code-unit ordering, never locale-sensitive sorting. Rendering and reversehit testing consume the same depth-first scene order.Flat scenes are ordinary trees with shapes directly under the surface. Additional-typed kinds are text, connector, image, video and document; their feature contracts+typed kinds are text, connector, image, video, document and artifact; their feature contractsare documented below. Shape labels are owned by rectangle, ellipse or connectorgeometry.@@ -478,6 +478,15 @@ other shapes. `insertShapesCommand` inserts an ordered batch in one undo step.Default Solid renderers show placeholders; hosts provide asset and preview views.No upload, storage-service, player or application preview dependency enters core.+### Artifacts++`artifact` stores box dimensions, a title, a self-contained HTML document, its+design size and a presentation sort key. The HTML lays out at the design size and+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.+### Host-measured text fittingdiff --git a/packages/graphics/src/core/artifact-commands.ts b/packages/graphics/src/core/artifact-commands.tsnew file mode 100644index 0000000000..8eed065ff6--- /dev/null+++ b/packages/graphics/src/core/artifact-commands.ts@@ -0,0 +1,34 @@+import type { GraphicsCommand } from './commands';+import { type ArtifactGeometry, artifactDefinition } from './shapes/artifact';++export type ArtifactContent = Partial<+ Pick<+ ArtifactGeometry,+ 'title' | 'html' | 'designWidth' | 'designHeight' | 'presentOrder'+ >+>;++/** One completed content edit is one document operation; box size and pose+ * stay with transform commands. */+export const setArtifactCommand: GraphicsCommand<{+ id: string;+ content: ArtifactContent;+}> = {+ id: 'set-artifact',+ apply: ({ document }, { id, content }) => {+ const before = document.items[id];+ if (before?.type !== 'artifact') throw new Error('Not an artifact');++ const geometry = { ...before.geometry, ...content };+ if (!artifactDefinition.validateGeometry(geometry))+ throw new Error('Invalid artifact geometry');++ const item = { ...before, geometry };+ if (artifactDefinition.sameGeometry(before, item)) return { document };++ return {+ document: { ...document, items: { ...document.items, [id]: item } },+ selection: [id],+ };+ },+};diff --git a/packages/graphics/src/core/index.ts b/packages/graphics/src/core/index.tsindex be72980f21..b3c42e3268 100644--- a/packages/graphics/src/core/index.ts+++ b/packages/graphics/src/core/index.ts@@ -1,5 +1,6 @@export * from './affine';export { resolveAppearance } from './appearance';+export * from './artifact-commands';export type { GraphicsBackend } from './backend';export {fitImageCamera,@@ -73,6 +74,7 @@ export {selectionContainsPoint,selectionFrame,} from './selection-frame';+export * from './shapes/artifact';export {type ConnectorAnchor,type ConnectorBinding,diff --git a/packages/graphics/src/core/model.ts b/packages/graphics/src/core/model.tsindex 8af3cdabbe..96e2379cc7 100644--- a/packages/graphics/src/core/model.ts+++ b/packages/graphics/src/core/model.ts@@ -1,5 +1,6 @@import type { Matrix } from './affine';import type { SortKey } from './ordering';+import type { ArtifactGeometry } from './shapes/artifact';import type { ConnectorGeometry } from './shapes/connector';import type { EllipseGeometry } from './shapes/ellipse';import type { DocumentGeometry, MediaGeometry } from './shapes/embedded';@@ -31,6 +32,7 @@ export type ShapeGeometryMap = {image: MediaGeometry;video: MediaGeometry;document: DocumentGeometry;+ artifact: ArtifactGeometry;};export type ShapeKind = keyof ShapeGeometryMap;export type Appearance = Readonly<{diff --git a/packages/graphics/src/core/shapes/artifact.ts b/packages/graphics/src/core/shapes/artifact.tsnew file mode 100644index 0000000000..4dd1f513b1--- /dev/null+++ b/packages/graphics/src/core/shapes/artifact.ts@@ -0,0 +1,40 @@+import { type BoxGeometry, validBoxGeometry } from './box-geometry';+import { boxShapeDefinition } from './embedded';++/**+ * A self-contained HTML document drawn into its box. Graphics treats `html` as+ * opaque content; hosts own sandboxing and rendering. The document lays out at+ * its design size and scales to fit the box. `presentOrder` is a sort key for+ * stepping through artifacts in presentation.+ */+export type ArtifactGeometry = BoxGeometry &+ Readonly<{+ title: string;+ html: string;+ designWidth: number;+ designHeight: number;+ presentOrder: string;+ }>;++const positive = (value: unknown) =>+ typeof value === 'number' && Number.isFinite(value) && value > 0;++export const validArtifactGeometry = (v: unknown): v is ArtifactGeometry =>+ validBoxGeometry(v) &&+ 'title' in v &&+ typeof v.title === 'string' &&+ 'html' in v &&+ typeof v.html === 'string' &&+ 'designWidth' in v &&+ positive(v.designWidth) &&+ 'designHeight' in v &&+ positive(v.designHeight) &&+ 'presentOrder' in v &&+ typeof v.presentOrder === 'string' &&+ !!v.presentOrder;++export const artifactDefinition = boxShapeDefinition(+ 'artifact',+ 'Artifact',+ validArtifactGeometry+);diff --git a/packages/graphics/src/core/shapes/embedded.ts b/packages/graphics/src/core/shapes/embedded.tsindex b4e0bdeff5..1dfc375854 100644--- a/packages/graphics/src/core/shapes/embedded.ts+++ b/packages/graphics/src/core/shapes/embedded.ts@@ -30,7 +30,10 @@ export const validMediaSource = (v: unknown): v is MediaSource =>(v.type === 'url' &&typeof v.url === 'string' &&/^(https?:\/\/|\/(?!\/))[^\s]+$/i.test(v.url)));-function definition<K extends 'image' | 'video' | 'document'>(+/** Shared contract for kinds that occupy a plain resizable box. */+export function boxShapeDefinition<+ K extends 'image' | 'video' | 'document' | 'artifact',+>(type: K,label: string,validate: (v: unknown) => v is ShapeGeometryMap[K]@@ -76,9 +79,9 @@ const validMedia = (v: unknown): v is MediaGeometry =>validMediaSource(v.source) &&'name' in v &&typeof v.name === 'string';-export const imageDefinition = definition('image', 'Image', validMedia);-export const videoDefinition = definition('video', 'Video', validMedia);-export const documentDefinition = definition(+export const imageDefinition = boxShapeDefinition('image', 'Image', validMedia);+export const videoDefinition = boxShapeDefinition('video', 'Video', validMedia);+export const documentDefinition = boxShapeDefinition('document','Document',(v): v is DocumentGeometry =>diff --git a/packages/graphics/src/core/shapes/registry.ts b/packages/graphics/src/core/shapes/registry.tsindex 2a010107d8..47a067fe30 100644--- a/packages/graphics/src/core/shapes/registry.ts+++ b/packages/graphics/src/core/shapes/registry.ts@@ -1,4 +1,5 @@import type { GraphicsItem, ShapeItem, ShapeKind } from '../model';+import { artifactDefinition } from './artifact';import { connectorDefinition } from './connector';import type { ShapeDefinition } from './definition';import { ellipseDefinition } from './ellipse';@@ -23,6 +24,7 @@ export const shapeDefinitions: {image: imageDefinition,video: videoDefinition,document: documentDefinition,+ artifact: artifactDefinition,});export const shapeKinds = Object.freeze(Object.keys(shapeDefinitions) as ShapeKind[]diff --git a/packages/graphics/src/loro/README.md b/packages/graphics/src/loro/README.mdindex db832ccf77..f829d1c7d7 100644--- a/packages/graphics/src/loro/README.md+++ b/packages/graphics/src/loro/README.md@@ -166,6 +166,9 @@ 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.+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.Their source bytes, resolved URLs, loading state and playback are host concerns.### Canvas host integrationdiff --git a/packages/graphics/src/loro/scene-mapping.ts b/packages/graphics/src/loro/scene-mapping.tsindex 39d184cd6a..d021eed0ec 100644--- a/packages/graphics/src/loro/scene-mapping.ts+++ b/packages/graphics/src/loro/scene-mapping.ts@@ -56,12 +56,7 @@ export function readScene(forest: CanvasForest, rootId: string) {...spatial,...shapePayload(kind,- restoreText(- kind,- pose.geometry,- node.data.textContent ?? null,- node.data.labelStyle ?? null- )+ restoreRegisters(kind, pose.geometry, node.data)),appearance: {fill,@@ -88,19 +83,26 @@ function textContent(node: GraphicsItem | undefined): string | null {function poseGeometry(node: GraphicsItem | undefined) {if (!isShape(node)) return null;if (node.type === 'text') return { ...node.geometry, content: '' };+ if (node.type === 'artifact') {+ const { html: _html, presentOrder: _order, ...pose } = node.geometry;+ return pose;+ }if (canLabel(node)) {const { label: _label, ...box } = node.geometry;return box;}return node.geometry;}-function restoreText(- kind: ShapeKind,- geometry: object,- content: string | null,- labelStyle: NodeData['labelStyle']-) {+function restoreRegisters(kind: ShapeKind, geometry: object, data: NodeData) {+ const content = data.textContent ?? null;+ const labelStyle = data.labelStyle ?? null;if (kind === 'text') return { ...geometry, content };+ if (kind === 'artifact')+ return {+ ...geometry,+ html: data.html ?? '',+ presentOrder: data.presentOrder ?? '',+ };if (kind === 'rectangle' || kind === 'ellipse' || kind === 'connector')return content !== null && labelStyle? { ...geometry, label: { ...labelStyle, content } }@@ -108,6 +110,14 @@ function restoreText(return geometry;}+function artifactRegisters(node: GraphicsItem) {+ if (node.type !== 'artifact') return { html: null, presentOrder: null };+ return {+ html: node.geometry.html,+ presentOrder: node.geometry.presentOrder,+ };+}+function labelStyle(node: GraphicsItem | undefined): NodeData['labelStyle'] {if (!canLabel(node) || !node.geometry.label) return null;const { content: _content, ...style } = node.geometry.label;@@ -183,6 +193,7 @@ export function writeScene(textContent: textContent(node),labelStyle: labelStyle(node),...appearance,+ ...artifactRegisters(node),};if (poseChanged)nextData.pose = {@@ -193,30 +204,36 @@ export function writeScene(};nextData.textContent = textContent(node);nextData.labelStyle = labelStyle(node);- if (isShape(node)) {- const oldAppearance = isShape(old)- ? resolveAppearance(old.appearance)- : undefined;- if (!oldAppearance || oldAppearance.fill !== appearance.fill)- nextData.fill = appearance.fill;- if (!oldAppearance || oldAppearance.stroke !== appearance.stroke)- nextData.stroke = appearance.stroke;- if (- !oldAppearance ||- oldAppearance.strokeStyle !== appearance.strokeStyle- )- nextData.strokeStyle = appearance.strokeStyle;- for (const key of ['strokeWidth', 'opacity', 'cornerRadius'] as const) {- if (!oldAppearance || oldAppearance[key] !== appearance[key])- nextData[key] = appearance[key];- }- }+ if (node.type === 'artifact')+ Object.assign(nextData, artifactRegisters(node));+ if (isShape(node)) writeChangedAppearance(nextData, old, appearance);return { data: nextData, children: project(id) };});}return project(next.rootId);}+/** Write only changed style registers, so concurrent restyles merge per field. */+function writeChangedAppearance(+ nextData: NodeData,+ old: GraphicsItem | undefined,+ appearance: ReturnType<typeof resolveAppearance>+) {+ const oldAppearance = isShape(old)+ ? resolveAppearance(old.appearance)+ : undefined;+ if (!oldAppearance || oldAppearance.fill !== appearance.fill)+ nextData.fill = appearance.fill;+ if (!oldAppearance || oldAppearance.stroke !== appearance.stroke)+ nextData.stroke = appearance.stroke;+ if (!oldAppearance || oldAppearance.strokeStyle !== appearance.strokeStyle)+ nextData.strokeStyle = appearance.strokeStyle;+ for (const key of ['strokeWidth', 'opacity', 'cornerRadius'] as const) {+ if (!oldAppearance || oldAppearance[key] !== appearance[key])+ nextData[key] = appearance[key];+ }+}+const isNewerKind = (node: CanvasForest[number]) =>node.data.kind !== 'group' && !isShapeKind(node.data.kind);diff --git a/packages/graphics/src/loro/schema.ts b/packages/graphics/src/loro/schema.tsindex 236f3c3784..715f022a04 100644--- a/packages/graphics/src/loro/schema.ts+++ b/packages/graphics/src/loro/schema.ts@@ -64,6 +64,16 @@ export const canvasNodeSchema = schema.LoroMap({),opacity: schema.Number(),cornerRadius: schema.Number(),+ /** Artifact HTML and presentation sort key, independent of pose; null on+ * other kinds. Like text, the HTML is one whole-string register. */+ html: schema.Value(+ (value): value is string | null =>+ value === null || typeof value === 'string'+ ),+ presentOrder: schema.Value(+ (value): value is string | null =>+ value === null || typeof value === 'string'+ ),});export type NodeData = InferType<typeof canvasNodeSchema>;export const canvasSchema = schema(diff --git a/packages/graphics/src/solid/selection-outline.tsx b/packages/graphics/src/solid/selection-outline.tsxindex e323531571..8a26b7a91e 100644--- a/packages/graphics/src/solid/selection-outline.tsx+++ b/packages/graphics/src/solid/selection-outline.tsx@@ -37,6 +37,13 @@ const outlines: { [K in ShapeKind]: Component<OutlineProps<K>> } = {vector-effect="non-scaling-stroke"/>),+ artifact: (props) => (+ <rect+ width={props.item.geometry.width}+ height={props.item.geometry.height}+ vector-effect="non-scaling-stroke"+ />+ ),document: (props) => (<rectwidth={props.item.geometry.width}diff --git a/packages/graphics/src/solid/shape-renderers.tsx b/packages/graphics/src/solid/shape-renderers.tsxindex f42a369132..990f502071 100644--- a/packages/graphics/src/solid/shape-renderers.tsx+++ b/packages/graphics/src/solid/shape-renderers.tsx@@ -1,6 +1,7 @@import type { Component } from 'solid-js';import { Dynamic } from 'solid-js/web';import type { ShapeItem, ShapeKind } from '../core/model';+import { ArtifactPlaceholder } from './shapes/artifact';import { ConnectorView } from './shapes/connector';import { EllipseView } from './shapes/ellipse';import { EmbeddedPlaceholder } from './shapes/embedded';@@ -24,6 +25,7 @@ export const defaultRenderers: ItemRenderers = {image: EmbeddedPlaceholder,video: EmbeddedPlaceholder,document: EmbeddedPlaceholder,+ artifact: ArtifactPlaceholder,};export function ShapeView<K extends ShapeKind>(props: ShapeViewProps<K> & { renderers: ItemRenderers }diff --git a/packages/graphics/src/solid/shapes/artifact.tsx b/packages/graphics/src/solid/shapes/artifact.tsxnew file mode 100644index 0000000000..619578f2c8--- /dev/null+++ b/packages/graphics/src/solid/shapes/artifact.tsx@@ -0,0 +1,19 @@+import type { ShapeViewProps } from '../shape-renderers';++/** Hosts run artifact HTML in their own sandbox; graphics never executes it. */+export function ArtifactPlaceholder(props: ShapeViewProps<'artifact'>) {+ return (+ <div+ style={{+ width: '100%',+ height: '100%',+ border: '1px solid currentColor',+ display: 'grid',+ 'place-items': 'center',+ opacity: props.item.appearance.opacity ?? 1,+ }}+ >+ {props.item.geometry.title || 'Artifact'}+ </div>+ );+}diff --git a/packages/graphics/tests/loro.test.ts b/packages/graphics/tests/loro.test.tsindex 99b2f8d322..316e977157 100644--- a/packages/graphics/tests/loro.test.ts+++ b/packages/graphics/tests/loro.test.ts@@ -6,6 +6,7 @@ import {freezeDocument,type GraphicsEditor,IDENTITY,+ setArtifactCommand,translation,worldMatrix,} from '../src/core';@@ -295,3 +296,48 @@ it('rejects unsupported proposals before touching Loro or local history', () =>expect(worldMatrix(b.document, 'a')).toEqual(translation(10, 20));expect(worldMatrix(b.document, 'b')).toEqual(translation(160, 30));});++it('artifact content and pose merge independently and survive a reload', () => {+ const document = createScene([+ {+ id: 'art',+ type: 'artifact',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(0, 0),+ geometry: {+ width: 640,+ height: 360,+ title: 'Intro',+ html: '<h1>Hello</h1>',+ designWidth: 1280,+ designHeight: 720,+ presentOrder: 'a0',+ },+ appearance: { fill: 'transparent', stroke: 'transparent' },+ },+ ]);+ const { lab, a, b } = setup(document);+ move(a, 'art', 40);+ b.execute(setArtifactCommand, {+ id: 'art',+ content: { html: '<h1>Hi</h1>', presentOrder: 'a1' },+ });+ lab.syncNow();+ converge(a, b);+ expect(worldMatrix(a.document, 'art')[4]).toBe(40);+ expect(a.document.items.art).toMatchObject({+ geometry: { html: '<h1>Hi</h1>', presentOrder: 'a1', title: 'Intro' },+ });++ const reloaded = createLoroGraphicsBackend(+ createLoroSeed(a.document),+ '3',+ document.rootId+ );+ disposers.push(reloaded.dispose);+ expect(reloaded.getDocument().items.art).toEqual(a.document.items.art);++ expect(() =>+ b.execute(setArtifactCommand, { id: 'art', content: { designWidth: 0 } })+ ).toThrow('Invalid artifact geometry');+});diff --git a/services/ai-editing-worker/src/canvas/operations.ts b/services/ai-editing-worker/src/canvas/operations.tsindex 62d8d0640e..3a56c033da 100644--- a/services/ai-editing-worker/src/canvas/operations.ts+++ b/services/ai-editing-worker/src/canvas/operations.ts@@ -307,6 +307,14 @@ export function prepareCanvasEdit(height: op.height,},}))+ .with({ type: 'artifact' }, (item) => ({+ ...item,+ geometry: {+ ...item.geometry,+ width: op.width,+ height: op.height,+ },+ })).exhaustive(),},},