AI-native design editor. Open-source Figma alternative.
feat(demo): rebuild /demo as a guided tour that follows the app theme (#1097)
Danila Poyarkov1ae876701a07
diff --git a/.github/workflows/app.yml b/.github/workflows/app.ymlindex bfd1f5045..04d5036c5 100644--- a/.github/workflows/app.yml+++ b/.github/workflows/app.yml@@ -24,6 +24,9 @@ jobs:- name: Format checkrun: bun run format:check+ # The demo document's shader fills are drawn at build time in a headless Chromium.+ - run: bunx playwright install --with-deps chromium+- run: bun run build- uses: cloudflare/wrangler-action@v4diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.ymlindex 4aff9f1e7..ed16b46f5 100644--- a/.github/workflows/preview.yml+++ b/.github/workflows/preview.yml@@ -26,6 +26,9 @@ jobs:- name: Format checkrun: bun run format:check+ # The demo document's shader fills are drawn at build time in a headless Chromium.+ - run: bunx playwright install --with-deps chromium+- run: bun run build- name: Upload preview artifactdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 001d58f3e..b1286351a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,17 @@- A selected layer resizes and rotates where Figma's does: every edge resizes along its whole length within 7.5 px outside it and up to a tenth of the side inside it, corners within 7.5 px, and the area outside a corner within 16 px rotates; a frame's name takes a press before rotation but not before resizing. Layers under 24 px keep these zones outside them, and a layer under 10 px on both sides has none, taking presses within 16 px across its centre instead. A selection draws Figma's four corner handles, without the edge midpoints, and none on such a small layer.- Pasted layers keep how they were turned and flipped on the canvas, as in Figma, so a layer copied out of a rotated frame stays at its angle in an upright one, and paste to replace keeps the copied layer's angle too. Layers copied out of a frame or section keep their offset from its box on the canvas, and move into the frame only when they start past its far edge, or, for top-level layers, miss it: then layers that fit are centred on that axis, and larger ones go to the frame's top-left, or are centred if top-level. Layers overlapping an edge stay where they are, and layers copied from different places are placed each from its own.+- The demo at `/demo` is a tour of one player card in eight chapters stacked on one canvas, each showing one thing with a numbered card that says what to try and draws the piece of the app to click: preview, the artwork slot, the controls' behaviours, the theme's modes, shader fills, the Code tab, Lint on a card with planted issues, and sharing and opening your own files. It opens on the first chapter with the rest below it and follows the app's light or dark theme. The welcome dialog on first launch offers it next to AI setup, and File > Open the Tour opens it any time.++### Fixed++- Preview draws controls as the canvas does: in the variable modes the canvas is showing, also after a mode switch or a variable edit, with icons and vector layers as drawn and shader fills playing behind their layers from the canvas's own shader players.+- Opening a page also loads the pages holding the component sets its instances use, so the variant picker and preview can switch to any variant of a set kept on a page not opened yet. Library copies on Figma's internal canvas stay as the file stores them, and a page that opens later no longer re-reads components an earlier page already built.+- A slot frame whose corner radius or other field is bound to a variable stays a slot when the file is saved and reopened.+- An instance whose own content makes it taller or wider than its component, such as a hug frame around longer text, reopens at its saved size.+- SVG export, and the HTML, JSX, and preview drawings built on it, draw a vector's open strokes beside its filled regions, such as the bar of a skip icon, instead of the regions alone.+- The contrast check asks 3:1 of large text, 24 px or 18.66 px bold, as WCAG AA does, and 4.5:1 of the rest, holding a text layer to the strictest threshold any of its style runs needs.+### Fixeddiff --git a/bun.lock b/bun.lockindex 83e6ebdd9..fa61c1442 100644--- a/bun.lock+++ b/bun.lock@@ -596,11 +596,15 @@"tools/generate/demo": {"name": "@open-pencil/demo-tools","dependencies": {+ "@iconify-json/lucide": "^1.2.139","@open-pencil/core": "workspace:*","@open-pencil/design-jsx": "workspace:*","@open-pencil/package-artifacts-tools": "workspace:*","@open-pencil/scene-graph": "workspace:*",+ "@playwright/test": "^1.63.0",+ "js-base64": "^3.9.3","proper-lockfile": "4.1.2",+ "shaders": "4.0.4",},"devDependencies": {"@types/bun": "^1.3.14",diff --git a/desktop/generated/menu.json b/desktop/generated/menu.jsonindex 5aae1acb4..bb3a2c1a1 100644--- a/desktop/generated/menu.json+++ b/desktop/generated/menu.json@@ -20,6 +20,10 @@"id": "open-storage-workspace","label": "Open Storage Workspace…"},+ {+ "id": "open-tour",+ "label": "Open the Tour"+ },{"type": "separator"},diff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.tsindex 94d0948f3..fa5e60939 100644--- a/packages/core/src/editor/pages.ts+++ b/packages/core/src/editor/pages.ts@@ -1,6 +1,6 @@import { limitAsync } from 'es-toolkit/promise'-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { instanceMainComponent, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'import type { Color } from '@open-pencil/scene-graph/primitives'import {@@ -58,6 +58,29 @@ interface PageDrawing {): Promise<void>}+/**+ * The other pages that hold the component sets instances on `pageId` show a variant of,+ * nested instances included. A set on Figma's internal canvas is a copy of a library's, kept+ * with only what the file uses, so its page is left out.+ */+export function componentSetPages(graph: SceneGraph, pageId: string): string[] {+ const pages = new Set<string>()+ const visit = (id: string): void => {+ for (const node of graph.getChildren(id)) {+ if (node.type === 'INSTANCE') {+ const component = instanceMainComponent(graph, node)+ const set = component?.parentId ? graph.getNode(component.parentId) : undefined+ const setPageId = set?.type === 'COMPONENT_SET' ? graph.pageOf(set.id) : null+ const setPage = setPageId ? graph.getNode(setPageId) : undefined+ if (setPage && setPage.id !== pageId && !setPage.internalOnly) pages.add(setPage.id)+ }+ visit(node.id)+ }+ }+ visit(pageId)+ return [...pages]+}+export function createPageActions(ctx: EditorContext, drawing?: PageDrawing) {const pageViewportStore = createPageViewportStore(ctx)function syncPageColor() {@@ -183,6 +206,19 @@ export function createPageActions(ctx: EditorContext, drawing?: PageDrawing) {options.onProgress?.({ phase: 'populating-page', detail: page.name })const populated = await populatePage(pageId, generation, options.signal)if (populated === null || generation !== pageSwitchGeneration) return null+ // A file brings in only the variants a page uses; switching a variant, in the panel or in+ // preview, needs the rest of its set, laid out with its fonts, so the pages holding those+ // sets are prepared with this one, and the pages of sets their variants use in turn.+ const seen = new Set([pageId])+ const pending = componentSetPages(ctx.graph, pageId)+ for (let setPageId = pending.shift(); setPageId !== undefined; setPageId = pending.shift()) {+ if (seen.has(setPageId)) continue+ seen.add(setPageId)+ const ready = await preparePageNodes(setPageId)+ throwIfAborted(options.signal)+ if (!ready || generation !== pageSwitchGeneration) return null+ pending.push(...componentSetPages(ctx.graph, setPageId))+ }await resolvePageFonts(pageId, page.name, options)throwIfAborted(options.signal)diff --git a/packages/core/src/editor/play/states.ts b/packages/core/src/editor/play/states.tsindex 2e1a73c16..c0513efad 100644--- a/packages/core/src/editor/play/states.ts+++ b/packages/core/src/editor/play/states.ts@@ -2,6 +2,7 @@ import {applyComponentPropertyValue,componentPropertyDefinitions,findLayerByPath,+ resolvedPaintBindings,type SceneGraph,type SceneNode} from '@open-pencil/scene-graph'@@ -114,6 +115,12 @@ export function resolvePlayState(componentSets: true,shareTables: true})+ // A bound paint keeps the color it was saved with while the canvas draws the variable live, in+ // whatever mode is showing now; the copy takes what the canvas draws, variants included.+ for (const node of graph.getAllNodes()) {+ const paints = resolvedPaintBindings(graph, node)+ if (paints.fills || paints.strokes) graph.updateNode(node.id, paints)+ }const ordered = [...states].sort(([a], [b]) => a.split('/').length - b.split('/').length)for (const [path, state] of ordered) {const instance = findLayerByPath(graph, rootId, path)diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex 62fdaa740..b052d04f2 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -62,6 +62,7 @@ import type { ExportImageOptions } from './types'const noop = () => undefinedexport { FigmaNodeProxy } from './proxy'+export { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'export type { FigmaEffect } from './effects'export type { ExportImageOptions } from './types'export type {diff --git a/packages/core/src/io/formats/svg/paths.ts b/packages/core/src/io/formats/svg/paths.tsindex e4d7431ba..78c69e774 100644--- a/packages/core/src/io/formats/svg/paths.ts+++ b/packages/core/src/io/formats/svg/paths.ts@@ -218,14 +218,20 @@ export function vectorNetworkToSVGPaths(): string[] {const { vertices, segments, regions } = network- if (regions.length > 0) {- return regions.map((region) =>- region.loops.map((loop) => traceOrderedSegments(loop, segments, vertices, decimals)).join('')- )+ if (regions.length === 0) {+ const path = unfilledSegmentsToPath(network, decimals)+ return path ? [path] : []}-- const path = unfilledSegmentsToPath(network, decimals)- return path ? [path] : []+ const paths = regions.map((region) =>+ region.loops.map((loop) => traceOrderedSegments(loop, segments, vertices, decimals)).join('')+ )+ // Segments no region encloses, such as an icon's open strokes beside its filled shapes,+ // draw as open paths after the regions.+ const enclosed = new Set(regions.flatMap((region) => region.loops.flat()))+ const open = segments.filter((_, index) => !enclosed.has(index))+ const loose =+ open.length > 0 && unfilledSegmentsToPath({ vertices, segments: open, regions: [] }, decimals)+ return loose ? [...paths, loose] : paths}/** The outline of a polygon or star whose corners are rounded, as path data. */diff --git a/packages/core/src/lint/linter.ts b/packages/core/src/lint/linter.tsindex 36c85331b..93ce82b8b 100644--- a/packages/core/src/lint/linter.ts+++ b/packages/core/src/lint/linter.ts@@ -15,6 +15,17 @@ import type {} from './types'import { getNodePath } from './utils'+/** The size and weight of each stretch of a text layer's characters, as the canvas draws them. */+function effectiveTextStyles(node: SceneNode): { fontSize: number; fontWeight: number }[] {+ const base = { fontSize: node.fontSize, fontWeight: node.fontWeight }+ const runs = node.styleRuns.map((run) => ({+ fontSize: run.style.fontSize ?? base.fontSize,+ fontWeight: run.style.fontWeight ?? base.fontWeight+ }))+ const covered = node.styleRuns.reduce((total, run) => total + run.length, 0)+ return covered < node.text.length || runs.length === 0 ? [base, ...runs] : runs+}+export class Linter {private rules = new Map<string, Rule>()private ruleConfigs = new Map<string, { severity: Severity; options?: Record<string, unknown> }>()@@ -111,6 +122,7 @@ export class Linter {componentId: raw.componentId || undefined,text: raw.text,fontSize: raw.fontSize,+ textStyles: raw.type === 'TEXT' ? effectiveTextStyles(raw) : undefined,styleRunCount: raw.styleRuns.length,boundVariables: raw.boundVariables,fills: raw.fills.map((f, index) => ({diff --git a/packages/core/src/lint/rules/color-contrast.ts b/packages/core/src/lint/rules/color-contrast.tsindex c321a7db5..a0a946f45 100644--- a/packages/core/src/lint/rules/color-contrast.ts+++ b/packages/core/src/lint/rules/color-contrast.ts@@ -2,7 +2,28 @@ import { colorToHex, contrastRatio } from '@open-pencil/scene-graph/color'import { defineRule } from '#core/lint/rule'+/** WCAG AA: 4.5:1 for text, 3:1 for large text, which is 24px, or 18.66px when bold. */const MIN_CONTRAST = 4.5+const MIN_LARGE_CONTRAST = 3+const LARGE_TEXT_PX = 24+const LARGE_BOLD_TEXT_PX = 18.66+const BOLD_WEIGHT = 700++function minContrast(style: { fontSize: number; fontWeight: number }): number {+ const large =+ style.fontSize >= LARGE_TEXT_PX ||+ (style.fontSize >= LARGE_BOLD_TEXT_PX && style.fontWeight >= BOLD_WEIGHT)+ return large ? MIN_LARGE_CONTRAST : MIN_CONTRAST+}++/** The strictest threshold any stretch of the text needs. */+function requiredContrast(node: {+ fontSize: number+ textStyles?: { fontSize: number; fontWeight: number }[]+}): number {+ const styles = node.textStyles ?? [{ fontSize: node.fontSize, fontWeight: 0 }]+ return Math.max(...styles.map(minContrast))+}export default defineRule({meta: {@@ -20,14 +41,15 @@ export default defineRule({const bg = parent.fills.find((f) => f.type === 'SOLID' && f.visible && f.color)?.colorif (bg) {const ratio = contrastRatio(textColor, bg)- if (ratio < MIN_CONTRAST)+ const minRatio = requiredContrast(node)+ if (ratio < minRatio)context.report({node,message: `Contrast ratio ${ratio.toFixed(2)}:1 is below WCAG AA`,suggest: 'Increase contrast between text and background',data: {ratio: Math.floor(ratio * 100) / 100,- minRatio: MIN_CONTRAST,+ minRatio,foreground: colorToHex({ ...textColor, a: 1 }),background: colorToHex({ ...bg, a: 1 })}diff --git a/packages/core/src/lint/types.ts b/packages/core/src/lint/types.tsindex 6479a73b8..9c423f885 100644--- a/packages/core/src/lint/types.ts+++ b/packages/core/src/lint/types.ts@@ -100,6 +100,11 @@ export interface LintNode {componentId?: stringtext: stringfontSize: number+ /**+ * The size and weight of every stretch of a text layer's characters: one per style run, and+ * the layer's own where no run covers the text.+ */+ textStyles?: { fontSize: number; fontWeight: number }[]styleRunCount: numberboundVariables: Record<string, string>fills: Array<{diff --git a/packages/core/tests/editor/pages/loading.test.ts b/packages/core/tests/editor/pages/loading.test.tsindex 4058e0360..34141ebdf 100644--- a/packages/core/tests/editor/pages/loading.test.ts+++ b/packages/core/tests/editor/pages/loading.test.ts@@ -264,3 +264,41 @@ test("loading a page's layers from the opened file asks for one render", async (expect(renders).toBe(1)editor.dispose()})++test('preparing a page loads the pages holding the component sets its instances use', async () => {+ await initCodec()+ const source = new SceneGraph()+ const [design] = source.getPages()+ const set = (pageName: string, name: string) => {+ const page = source.addPage(pageName)+ const created = source.createNode('COMPONENT_SET', page.id, { name })+ const variant = (value: string) =>+ source.createNode('COMPONENT', created.id, {+ name: `State=${value}`,+ componentPropertyValues: { State: value }+ })+ return { off: variant('Off'), on: variant('On') }+ }+ // Only the switch's On variant holds a knob, from a set on a third page, so the design page+ // reaches that set through the switch's page alone.+ const knob = set('Parts', 'Knob')+ const toggle = set('Library', 'Switch')+ source.createInstance(knob.off.id, toggle.on.id)+ source.createInstance(toggle.off.id, design.id)+ const bytes = await exportFigFile(source)+ const graph = await parseFigFile(bytes.slice().buffer, { populate: 'none' })+ const editor = createEditor({ graph, skipInitialGraphSetup: true })+ const [first] = graph.getPages()+ const variants = (setName: string) => {+ const found = [...graph.getAllNodes()].find(+ (node) => node.type === 'COMPONENT_SET' && node.name === setName+ )+ return found ? graph.getChildren(found.id).map((node) => node.name) : []+ }++ expect(await editor.preparePage(first.id)).not.toBeNull()++ expect(variants('Switch')).toEqual(['State=Off', 'State=On'])+ expect(variants('Knob')).toEqual(['State=Off', 'State=On'])+ editor.dispose()+})diff --git a/packages/core/tests/editor/play/states.test.ts b/packages/core/tests/editor/play/states.test.tsindex 920e73272..39471b521 100644--- a/packages/core/tests/editor/play/states.test.ts+++ b/packages/core/tests/editor/play/states.test.ts@@ -120,4 +120,28 @@ describe('preview islands', () => {editor.replaceGraph(new SceneGraph())expect(editor.state.play).toEqual({ revision: 2 })})++ test('a copy paints bound colors in the mode the canvas is showing, not as they were saved', () => {+ const { graph, card } = switchCard()+ const collection = graph.createCollection('Theme')+ const dark = collection.defaultModeId+ graph.addMode(collection.id, 'light', 'Light', dark)+ const surface = graph.createVariable('Surface', 'COLOR', collection.id, {+ r: 0.1,+ g: 0.1,+ b: 0.1,+ a: 1+ })+ surface.valuesByMode.light = { r: 1, g: 1, b: 1, a: 1 }+ graph.updateNode(card.id, {+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, opacity: 1, visible: true }]+ })+ graph.bindVariable(card.id, 'fills/0/color', surface.id)+ graph.setActiveMode(collection.id, 'light')++ const shown = resolvePlayState(graph, card.id, new Map())++ expect(shown.getNode(card.id)?.fills[0]?.color).toEqual({ r: 1, g: 1, b: 1, a: 1 })+ expect(graph.getNode(card.id)?.fills[0]?.color).toEqual({ r: 0.1, g: 0.1, b: 0.1, a: 1 })+ })})diff --git a/packages/core/tests/io/formats/fig/roundtrip/instance-size.test.ts b/packages/core/tests/io/formats/fig/roundtrip/instance-size.test.tsnew file mode 100644index 000000000..1a7581123--- /dev/null+++ b/packages/core/tests/io/formats/fig/roundtrip/instance-size.test.ts@@ -0,0 +1,43 @@+import { expect, setDefaultTimeout, test } from 'bun:test'++import { populateAllFigPages } from '#core/io/formats/fig'++import { expectDefined } from '#core-tests/helpers/assert'++import { exportFigFile, initCodec, readFigFile, SceneGraph } from '@open-pencil/core'++setDefaultTimeout(60_000)++test('a hug instance keeps the height its own text laid it out to when reopened', async () => {+ await initCodec()+ const graph = new SceneGraph()+ const [page] = graph.getPages()+ const component = graph.createNode('COMPONENT', page.id, {+ name: 'Tip',+ width: 320,+ height: 60,+ layoutMode: 'VERTICAL',+ primaryAxisSizing: 'HUG',+ paddingTop: 20,+ paddingBottom: 20+ })+ graph.createNode('TEXT', component.id, {+ name: 'Body',+ text: 'One line.',+ width: 280,+ height: 20,+ textAutoResize: 'HEIGHT'+ })+ const instance = expectDefined(graph.createInstance(component.id, page.id), 'instance')+ const body = expectDefined(graph.getChildren(instance.id)[0], 'instance body')+ // Four lines of text, and the hug frame laid out around them.+ graph.updateNode(body.id, { text: 'Four lines of text, as the layout measured them.', height: 80 })+ graph.updateNode(instance.id, { height: 120 })++ const bytes = await exportFigFile(graph)+ const reopened = await readFigFile(new File([bytes.slice()], 'Tip.fig'))+ populateAllFigPages(reopened)+ const reopenedInstance = [...reopened.getAllNodes()].find((node) => node.type === 'INSTANCE')+ expect(reopenedInstance?.height).toBe(120)+ expect(reopened.getChildren(expectDefined(reopenedInstance, 'instance').id)[0]?.height).toBe(80)+})diff --git a/packages/core/tests/io/formats/svg/paths.test.ts b/packages/core/tests/io/formats/svg/paths.test.tsnew file mode 100644index 000000000..18077520a--- /dev/null+++ b/packages/core/tests/io/formats/svg/paths.test.ts@@ -0,0 +1,36 @@+import { expect, test } from 'bun:test'++import { vectorNetworkToSVGPaths } from '#core/io/formats/svg/paths'++import type { VectorNetwork } from '@open-pencil/scene-graph'++const corner = { x: 0, y: 0 }+const line = (start: number, end: number) => ({+ start,+ end,+ tangentStart: corner,+ tangentEnd: corner+})++/** A skip-back icon: a filled triangle beside a bar, which no region encloses. */+const network: VectorNetwork = {+ vertices: [+ { x: 19, y: 20 },+ { x: 9, y: 12 },+ { x: 19, y: 4 },+ { x: 5, y: 19 },+ { x: 5, y: 5 }+ ],+ segments: [line(0, 1), line(1, 2), line(2, 0), line(3, 4)],+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]+}++test('segments outside every region draw as open paths after the regions', () => {+ expect(vectorNetworkToSVGPaths(network)).toEqual(['M19 20L9 12L19 4L19 20Z', 'M5 19L5 5'])+})++test('a network with regions only draws the regions', () => {+ expect(vectorNetworkToSVGPaths({ ...network, segments: network.segments.slice(0, 3) })).toEqual(+ ['M19 20L9 12L19 4L19 20Z']+ )+})diff --git a/packages/core/tests/lint/rules.test.ts b/packages/core/tests/lint/rules.test.tsindex ceb6305af..edc8ba48e 100644--- a/packages/core/tests/lint/rules.test.ts+++ b/packages/core/tests/lint/rules.test.ts@@ -88,6 +88,54 @@ describe('color-contrast', () => {background: '#FFFFFF'})})++ test('large text needs 3:1, as WCAG AA asks of it', () => {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const card = graph.createNode('FRAME', pageId, { name: 'Card', fills: solid(WHITE) })+ // 3.2:1 against white.+ const grey = { r: 0.55, g: 0.55, b: 0.55, a: 1 }+ const text = (name: string, fontSize: number, fontWeight: number) =>+ graph.createNode('TEXT', card.id, { name, text: name, fontSize, fontWeight, fills: solid(grey) })+ const body = text('Body', 16, 400)+ const boldBody = text('Bold body', 18, 700)+ text('Display', 24, 400)+ text('Bold subhead', 19, 700)++ const messages = lint(graph, 'color-contrast')++ expect(messages.map((message) => message.nodeId)).toEqual([body.id, boldBody.id])+ expect(messages.map((message) => message.data?.minRatio)).toEqual([4.5, 4.5])+ })++ test('holds text to the strictest threshold any of its style runs needs', () => {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const card = graph.createNode('FRAME', pageId, { name: 'Card', fills: solid(WHITE) })+ // 3.2:1 against white: enough for large text, not for the rest.+ const grey = solid({ r: 0.55, g: 0.55, b: 0.55, a: 1 })+ const mixed = graph.createNode('TEXT', card.id, {+ name: 'Large with a small run',+ text: 'Heading note',+ fontSize: 24,+ fontWeight: 400,+ fills: grey,+ styleRuns: [{ start: 8, length: 4, style: { fontSize: 14 } }]+ })+ graph.createNode('TEXT', card.id, {+ name: 'Small made large throughout',+ text: 'Heading',+ fontSize: 14,+ fontWeight: 400,+ fills: grey,+ styleRuns: [{ start: 0, length: 7, style: { fontSize: 32 } }]+ })++ const messages = lint(graph, 'color-contrast')++ expect(messages.map((message) => message.nodeId)).toEqual([mixed.id])+ expect(messages[0]?.data?.minRatio).toBe(4.5)+ })})describe('no-deeply-nested', () => {diff --git a/packages/fig/src/document/components.ts b/packages/fig/src/document/components.tsindex ba710367f..bcaeb7b91 100644--- a/packages/fig/src/document/components.ts+++ b/packages/fig/src/document/components.ts@@ -16,7 +16,9 @@ export interface ComponentConstruction {export function planComponentConstruction(roots: readonly InstanceOccurrence[],readComponent: (id: string) => InstanceOccurrence,- index: ReadonlyMap<string, NodeChange>+ index: ReadonlyMap<string, NodeChange>,+ /** Components an earlier pass already built, which are neither read nor planned again. */+ isBuilt: (id: string) => boolean = () => false): ComponentConstruction[] {const sources = indexconst pageComponents = new Map<string, InstanceOccurrence>()@@ -50,6 +52,10 @@ export function planComponentConstruction(}const ensure = (id: string): void => {if (complete.has(id)) return+ if (isBuilt(id)) {+ complete.add(id)+ return+ }if (pending.has(id)) throw new Error(`Cyclic component dependency ${id}`)pending.add(id)const source = sources.get(id)diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.tsindex 5d08d60ac..0580cbbcd 100644--- a/packages/fig/src/document/materialize.ts+++ b/packages/fig/src/document/materialize.ts@@ -287,8 +287,8 @@ function materializeReader(options.onUnresolvedBinding(diagnostic)}const pages = reader.pages.map((page) => reader.readPage(page.id, options))- const plan = reader.planComponents(pages, options)const state = previous ?? createAssemblyState(reader, options)+ const plan = reader.planComponents(pages, options, (id) => state.components.has(id))return state.graph.applyImportedStateDuring(() => materializeReaderInto(pages, plan, blobs, state, previous !== undefined),() => `0:${state.nextImportedId++}`diff --git a/packages/fig/src/document/read.ts b/packages/fig/src/document/read.tsindex 63072958e..062c56e68 100644--- a/packages/fig/src/document/read.ts+++ b/packages/fig/src/document/read.ts@@ -308,12 +308,14 @@ function createScopedReader(},planComponents(roots: readonly ReturnType<typeof interpreter.page>[],- options: InterpretInstanceOptions = {}+ options: InterpretInstanceOptions = {},+ isBuilt?: (id: string) => boolean) {return planComponentConstruction(roots,(id) => sourceInterpreter.component(id, options),- index.sources+ index.sources,+ isBuilt)},readComponent: sourceInterpreter.componentdiff --git a/packages/fig/src/instance-overrides/interpret.ts b/packages/fig/src/instance-overrides/interpret.tsindex 27c6b87bd..1ff634740 100644--- a/packages/fig/src/instance-overrides/interpret.ts+++ b/packages/fig/src/instance-overrides/interpret.ts@@ -567,8 +567,13 @@ function interpretRoot(}applyInstanceLayoutScale(occurrence, source)applyPlacedConstraints(occurrence, base, source)- if (source.type === 'INSTANCE' && source.size)+ if (source.type === 'INSTANCE' && source.size) {occurrence.properties.size = structuredClone(source.size)+ // The size the file keeps for the instance is its own content laid out, such as a hug+ // frame around longer text than its component's, which a sync with the component must+ // not replace.+ occurrence.derivedSize = structuredClone(source.size)+ }if (derived) applyDerivedBounds(occurrence, source)}diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.tsindex 85a773506..a614eeafa 100644--- a/packages/fig/src/node-change/serialize.ts+++ b/packages/fig/src/node-change/serialize.ts@@ -435,11 +435,17 @@ function serializeVariableBindings()if (entries.length > 0) {nc.variableConsumptionMap = { entries }+ const bindings = mergeVariableConsumptionMaps(effectiveFigmaRawNodeFields(node), {+ parameterConsumptionMap: { entries }+ })+ // Component property references were written to the record before its bindings; a+ // record carries both in one map, so the bindings join them rather than replace them.+ const references = nc.parameterConsumptionMapObject.assign(nc,- mergeVariableConsumptionMaps(effectiveFigmaRawNodeFields(node), {- parameterConsumptionMap: { entries }- })+ references+ ? mergeVariableConsumptionMaps(bindings, { parameterConsumptionMap: references })+ : bindings)}}diff --git a/packages/fig/tests/document/read.test.ts b/packages/fig/tests/document/read.test.tsindex 2ef280dda..5308c07fc 100644--- a/packages/fig/tests/document/read.test.ts+++ b/packages/fig/tests/document/read.test.ts@@ -63,6 +63,8 @@ test('reads pages independently through one index with cross-page component expa}))).toEqual([{ sourceId: '1:4', parentSourceId: '1:2', pageSourceId: '1:2' }])expect(reader.planComponents([page]).map((component) => component.sourceId)).toEqual(['1:4'])+ // A component an earlier pass built is neither read again nor planned.+ expect(reader.planComponents([page], {}, (id) => id === '1:4')).toEqual([])const { graph, sources } = materializeDocument(changes)expect(graph.getPages().map((node) => node.name)).toEqual(['Design', 'Components'])const componentId = sources.get('1:4')diff --git a/packages/fig/tests/node-change/export/property-references.test.ts b/packages/fig/tests/node-change/export/property-references.test.tsnew file mode 100644index 000000000..d49d753aa--- /dev/null+++ b/packages/fig/tests/node-change/export/property-references.test.ts@@ -0,0 +1,58 @@+import { expect, test } from 'bun:test'++import { sceneNodeToKiwi } from '#fig/node-change/index'++import { SceneGraph } from '@open-pencil/scene-graph'++/** The fields a record's parameter map binds, in order. */+function parameterFields(record: { parameterConsumptionMap?: unknown }): string[] {+ const map = record.parameterConsumptionMap as+ | { entries?: Array<{ variableField?: string }> }+ | undefined+ return (map?.entries ?? []).map((entry) => entry.variableField ?? '')+}++test('a slot frame with a bound corner radius keeps its slot reference in the parameter map', () => {+ const graph = new SceneGraph()+ const [page] = graph.getPages()+ graph.addCollection({+ id: 'collection',+ name: 'Theme',+ modes: [{ modeId: 'mode', name: 'Mode' }],+ defaultModeId: 'mode',+ variableIds: []+ })+ graph.addVariable({+ id: 'radius',+ name: 'Radius',+ type: 'FLOAT',+ collectionId: 'collection',+ valuesByMode: { mode: 12 },+ description: '',+ hiddenFromPublishing: false+ })+ const component = graph.createNode('COMPONENT', page.id, {+ name: 'Card',+ componentPropertyDefinitions: [+ { id: 'prop:slot', name: 'Content', type: 'SLOT', defaultValue: '' }+ ]+ })+ graph.createNode('FRAME', component.id, {+ name: 'Content',+ cornerRadius: 12,+ boundVariables: { cornerRadius: 'radius' },+ componentPropertyReferences: [{ propertyId: 'prop:slot', field: 'SLOT_CONTENT' }]+ })++ const records = sceneNodeToKiwi(+ component,+ { sessionID: 1, localID: 1 },+ 0,+ { value: 2 },+ graph,+ []+ )+ const frame = records.find((record) => record.name === 'Content')+ expect(frame).toBeDefined()+ expect(parameterFields(frame ?? {}).sort()).toEqual(['CORNER_RADIUS', 'SLOT_CONTENT_ID'])+})diff --git a/packages/vue/AGENTS.md b/packages/vue/AGENTS.mdindex 90f651c02..1f4e6c553 100644--- a/packages/vue/AGENTS.md+++ b/packages/vue/AGENTS.md@@ -18,6 +18,7 @@ The app's `DesignPanel` retains at most one selection-property subtree through `## Preview islands- Preview runs controls as real components, never as canvas simulations: `packages/vue/src/canvas/islands/` renders each top-level layer that holds an instance with a behaviour as DOM in a shadow root over the canvas, projected through `@open-pencil/dom-css`, and mounts each behaviour's Reka UI primitives on its layers. Typing, focus, and keyboard handling belong to the browser and Reka.+- Islands adopt one token stylesheet `IslandLayer.vue` builds for all of them, with `:root` rewritten to `:host`, so the projection's `var()` references resolve in the modes their layers set; vector layers come from Core's `vectorElement`, and a shader fill draws each frame the canvas's own player publishes for its image through `canvas/surface/shader/frames.ts`, never a player of its own (`IslandShader.vue`).- Islands only map layers to Reka components. Which layer is a control, part, item, trigger, panel, or input comes from `behaviourControls` and `controlRoles` in `@open-pencil/dom-css`, which code export shares; never derive roles in Vue (`packages/dom-css/tests/behaviours/controls.test.ts`).- The concept, the pipeline from state to DOM, and how to add a kind are in `packages/docs/development/behaviours-and-preview.md`.- Variants draw control states: Core's `resolvePlayState` shows instances in a state on a private graph, and controls are keyed by layer path so a variant switch keeps their DOM, including a focused input. The document is never changed (`packages/core/tests/editor/play/states.test.ts`, `tests/e2e/components/behaviours.spec.ts`).diff --git a/packages/vue/src/canvas/islands/Island.vue b/packages/vue/src/canvas/islands/Island.vueindex 37d6b2836..467bc2c8e 100644--- a/packages/vue/src/canvas/islands/Island.vue+++ b/packages/vue/src/canvas/islands/Island.vue@@ -2,6 +2,7 @@import { computed, shallowRef, useTemplateRef, watch } from 'vue'import { resolvePlayState } from '@open-pencil/core/editor'+import { vectorElement } from '@open-pencil/core/io'import {behaviourControls,controlRoles,@@ -19,16 +20,16 @@ import { createIslandState, instanceStates } from './state'* root, with each control running as its Reka UI component. The design's variants draw the* controls' states; the document never changes.*/-const { rootId, revision } = defineProps<{+const { rootId, revision, tokens } = defineProps<{rootId: string/** Changing it starts every control again as designed. */revision: number+ /** The document's variables as custom properties, shared by every island of the canvas. */+ tokens: CSSStyleSheet}>()const editor = useEditor()-/** Styles of the island's own document; the app's styles do not reach into it. */-const ISLAND_CSS = ':host{all:initial;display:block}*,*::before,*::after{box-sizing:border-box}'-const container = useShadowContainer(useTemplateRef<HTMLElement>('host'), ISLAND_CSS)+const container = useShadowContainer(useTemplateRef<HTMLElement>('host'), [tokens])const controls = computed(() => {void editor.state.sceneVersion@@ -44,7 +45,7 @@ watch(const projection = computed(() => {void editor.state.sceneVersionconst graph = resolvePlayState(editor.graph, rootId, instanceStates(controls.value, state.value))- const [root] = sceneNodeToDesignDocument(graph, rootId).children+ const [root] = sceneNodeToDesignDocument(graph, rootId, { vectorElement }).childrenreturn { graph, root }})diff --git a/packages/vue/src/canvas/islands/IslandLayer.vue b/packages/vue/src/canvas/islands/IslandLayer.vueindex 939c13c18..f302a654a 100644--- a/packages/vue/src/canvas/islands/IslandLayer.vue+++ b/packages/vue/src/canvas/islands/IslandLayer.vue@@ -1,8 +1,10 @@<script setup lang="ts">-import { computed } from 'vue'+import { computedAsync } from '@vueuse/core'+import { computed, watch } from 'vue'import { playIslandRoots, type PlayState } from '@open-pencil/core/editor'import type { ViewportTransform } from '@open-pencil/core/geometry'+import { tokenStylesheet } from '@open-pencil/dom-css/export'import { useEditor } from '#vue/editor/context'@@ -26,6 +28,20 @@ const { view, canvas, drawn } = defineProps<{const placement = computed(() => drawn ?? view)const editor = useEditor()+/**+ * The document's variables as custom properties, which the islands' `var()` references read in+ * the modes their layers set. Built once for every island while previewing; an island is a+ * shadow root, so the stylesheet's `:root` is its host.+ */+const tokens = new CSSStyleSheet()+const tokensCSS = computedAsync(async () => {+ void editor.state.sceneVersion+ if (!view.play) return ''+ const { css } = await tokenStylesheet(editor.graph, { format: 'css' })+ return css.replaceAll(':root', ':host')+}, '')+watch(tokensCSS, (css) => tokens.replaceSync(css), { immediate: true })+const islands = computed(() => {void editor.state.sceneVersionif (!view.play) return []@@ -60,6 +76,7 @@ function forwardWheel(event: WheelEvent) {:key="island.id":root-id="island.id":revision="view.play.revision"+ :tokens="tokens"class="pointer-events-auto absolute":style="{ left: `${island.position.x}px`, top: `${island.position.y}px` }"/>diff --git a/packages/vue/src/canvas/islands/IslandShader.vue b/packages/vue/src/canvas/islands/IslandShader.vuenew file mode 100644index 000000000..2e90fe348--- /dev/null+++ b/packages/vue/src/canvas/islands/IslandShader.vue@@ -0,0 +1,71 @@+<script setup lang="ts">+import { useElementSize } from '@vueuse/core'+import { onScopeDispose, useTemplateRef, watch } from 'vue'++import { shaderFrames } from '#vue/canvas/surface/shader/frames'+import { useEditor } from '#vue/editor/context'++/**+ * A shader fill behind an island layer's content: the still frame the document keeps, and over+ * it each frame the canvas's own player draws for that shader, copied as it is drawn. The layer+ * is positioned and isolated by the projection, so this sits under everything it holds.+ */+const { image, frame } = defineProps<{+ /** The image the shader's paint shows, which names its player. */+ image: string+ /** The still frame the document keeps, shown until a frame is drawn and where none can be. */+ frame?: string+}>()++const host = useTemplateRef<HTMLElement>('host')+const canvas = useTemplateRef<HTMLCanvasElement>('canvas')+const { width, height } = useElementSize(host)+const frames = shaderFrames(useEditor())++function draw(source: CanvasImageSource) {+ const target = canvas.value+ const context = target?.getContext('2d')+ if (!target || !context) return+ const ratio = window.devicePixelRatio || 1+ const w = Math.max(1, Math.round(width.value * ratio))+ const h = Math.max(1, Math.round(height.value * ratio))+ if (target.width !== w || target.height !== h) {+ target.width = w+ target.height = h+ }+ context.drawImage(source, 0, 0, w, h)+}++let stop: (() => void) | null = null+watch(+ () => image,+ (value) => {+ stop?.()+ // Another shader's last frame would cover this one's still frame until it draws.+ const target = canvas.value+ target?.getContext('2d')?.clearRect(0, 0, target.width, target.height)+ stop = frames.listen(value, draw)+ },+ { immediate: true }+)+onScopeDispose(() => stop?.())+</script>++<template>+ <div+ ref="host"+ aria-hidden="true"+ style="position: absolute; inset: 0; z-index: -1; overflow: hidden; pointer-events: none"+ >+ <img+ v-if="frame"+ :src="frame"+ alt=""+ style="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover"+ />+ <canvas+ ref="canvas"+ style="position: absolute; inset: 0; width: 100%; height: 100%; display: block"+ />+ </div>+</template>diff --git a/packages/vue/src/canvas/islands/render.ts b/packages/vue/src/canvas/islands/render.tsindex fe67cc603..9a5f9a9c3 100644--- a/packages/vue/src/canvas/islands/render.ts+++ b/packages/vue/src/canvas/islands/render.ts@@ -7,9 +7,10 @@ import {type DesignElement,type DesignNode} from '@open-pencil/dom-css/export'-import { layerPath, type SceneGraph } from '@open-pencil/scene-graph'+import { layerPath, shaderOfPaint, type SceneGraph } from '@open-pencil/scene-graph'import { wrapRole } from './controls'+import IslandShader from './IslandShader.vue'import type { IslandState } from './state'export interface IslandRenderContext {@@ -31,6 +32,13 @@ export interface ElementOverride {children?: () => (VNode | string)[]}+/** The image a layer's shader fill shows: its first fill's, as the projection reads it. */+function shaderImage(element: DesignElement): string | undefined {+ const node = element.sourceSceneNode+ const fill = node?.fills.at(0)+ return node && fill ? (shaderOfPaint(node, fill)?.image ?? undefined) : undefined+}+/** Render an element as the design draws it, with a role's changes applied. */export function renderElement(context: IslandRenderContext,@@ -48,8 +56,17 @@ export function renderElement(...override.style}).filter(([key]) => !omitted.has(key)))- const children =+ const content =override.children ?? (() => element.children.map((child) => renderNode(context, child, path)))+ // A shader fill plays behind the content, whatever draws the content, from the canvas's own+ // player for the image its paint shows.+ const image = element.shader ? shaderImage(element) : undefined+ const children = () => [+ ...(image+ ? [h(IslandShader, { key: `${path}\0shader`, image, frame: element.shader?.frame })]+ : []),+ ...content()+ ]const { 'data-open-pencil-node-id': _id, ...attrs } = element.attrsreturn h(override.tag ?? element.tagName,diff --git a/packages/vue/src/canvas/islands/shadow.ts b/packages/vue/src/canvas/islands/shadow.tsindex 3c0670577..817c2be25 100644--- a/packages/vue/src/canvas/islands/shadow.ts+++ b/packages/vue/src/canvas/islands/shadow.ts@@ -1,17 +1,24 @@import { onMounted, shallowRef, type Ref } from 'vue'+/** Styles of an island's own document; the app's styles do not reach into it. */+const ISLAND_CSS = ':host{all:initial;display:block}*,*::before,*::after{box-sizing:border-box}'+/**- * A container inside a shadow root of `host`, created once `host` mounts, with `css` as the- * shadow root's only styles: the app's styles do not reach into it, nor its styles out.+ * A container inside a shadow root of `host`, created once `host` mounts, styled only by the+ * island's base styles and `shared`, sheets every island adopts: the app's styles do not reach+ * into it, nor its styles out.*/-export function useShadowContainer(host: Readonly<Ref<HTMLElement | null>>, css: string) {+export function useShadowContainer(+ host: Readonly<Ref<HTMLElement | null>>,+ shared: readonly CSSStyleSheet[] = []+) {const container = shallowRef<HTMLElement | null>(null)onMounted(() => {if (!host.value) returnconst shadow = host.value.attachShadow({ mode: 'open' })- const sheet = new CSSStyleSheet()- sheet.replaceSync(css)- shadow.adoptedStyleSheets = [sheet]+ const base = new CSSStyleSheet()+ base.replaceSync(ISLAND_CSS)+ shadow.adoptedStyleSheets = [base, ...shared]const mount = document.createElement('div')shadow.append(mount)container.value = mountdiff --git a/packages/vue/src/canvas/surface/lifecycle.ts b/packages/vue/src/canvas/surface/lifecycle.tsindex dbe6efed7..cc78e5a17 100644--- a/packages/vue/src/canvas/surface/lifecycle.ts+++ b/packages/vue/src/canvas/surface/lifecycle.ts@@ -20,7 +20,7 @@ import { createImagePreviewDecoder } from '#vue/canvas/surface/image-preview'import { useCanvasKitLoader } from '#vue/canvas/surface/kit-loader'import { createCanvasRenderLoop } from '#vue/canvas/surface/render-loop'import { useCanvasResizeObserver } from '#vue/canvas/surface/resize-observer'-import { createShaderRasterizer } from '#vue/canvas/surface/shader-rasterizer'+import { createShaderRasterizer } from '#vue/canvas/surface/shader/rasterizer'import type { UseCanvasOptions } from '#vue/canvas/surface/types'type SurfaceManagerState = {diff --git a/packages/vue/src/canvas/surface/shader/frames.ts b/packages/vue/src/canvas/surface/shader/frames.tsnew file mode 100644index 000000000..cc0661277--- /dev/null+++ b/packages/vue/src/canvas/surface/shader/frames.ts@@ -0,0 +1,42 @@+import type { Editor } from '@open-pencil/core/editor'++/**+ * Draws one fresh frame of a shader. The source is a WebGPU canvas that keeps the frame only+ * until the current task ends, so it is drawn from at once, never kept.+ */+export type ShaderFrameListener = (source: CanvasImageSource) => void++/**+ * Where the canvas's shader playback hands each frame it draws, by the image its paint shows,+ * to anything else that shows that shader: preview's islands draw their shader layers from it,+ * so every shader on the page has one player whatever shows it.+ */+export interface ShaderFrames {+ listen(image: string, listener: ShaderFrameListener): () => void+ publish(image: string, source: CanvasImageSource): void+}++const hubs = new WeakMap<Editor, ShaderFrames>()++/** The shader frames of `editor`'s documents, shared by its canvases and islands. */+export function shaderFrames(editor: Editor): ShaderFrames {+ let hub = hubs.get(editor)+ if (hub) return hub+ const listeners = new Map<string, Set<ShaderFrameListener>>()+ hub = {+ listen(image, listener) {+ const set = listeners.get(image) ?? new Set()+ set.add(listener)+ listeners.set(image, set)+ return () => {+ set.delete(listener)+ if (set.size === 0) listeners.delete(image)+ }+ },+ publish(image, source) {+ for (const listener of listeners.get(image) ?? []) listener(source)+ }+ }+ hubs.set(editor, hub)+ return hub+}diff --git a/packages/vue/src/canvas/surface/shader-playback.ts b/packages/vue/src/canvas/surface/shader/playback.tssimilarity index 97%rename from packages/vue/src/canvas/surface/shader-playback.tsrename to packages/vue/src/canvas/surface/shader/playback.tsindex e22ed3d3e..fabf61bd6 100644--- a/packages/vue/src/canvas/surface/shader-playback.ts+++ b/packages/vue/src/canvas/surface/shader/playback.ts@@ -7,7 +7,8 @@ import type { Editor, EditorState } from '@open-pencil/core/editor'import { readShaderPaints, shaderOfPaint, type ShaderPreset } from '@open-pencil/scene-graph'import type { Rect } from '@open-pencil/scene-graph/primitives'-import { canDrawShaders } from '#vue/canvas/surface/shader-rasterizer'+import { shaderFrames } from '#vue/canvas/surface/shader/frames'+import { canDrawShaders } from '#vue/canvas/surface/shader/rasterizer'/** The longest side a playing shader is drawn at, however large it is on screen. */const MAX_PLAY_EDGE = 1024@@ -83,6 +84,7 @@ export function useShaderPlayback(options: {markDirty: () => void}) {const { editor, getRenderer, getView, getViewport, markDirty } = options+ const frames = shaderFrames(editor)const players = new Map<string, Player>()/** Shaders that failed to start, by the preset that failed, which are not tried again. */const failed = new Map<string, string>()@@ -246,6 +248,8 @@ export function useShaderPlayback(options: {player.drawnAt = nowawait player.renderer?.renderFrame({ deltaSeconds: delta, waitForGpu: false })if (player.disposed) continue+ // Preview's islands draw their shader layers from this frame, in this same task.+ frames.publish(hash, player.canvas)if (!copyFrames && uploads(renderer, hash, player)) drew = trueelse {copyFrames = truediff --git a/packages/vue/src/canvas/surface/shader-rasterizer.ts b/packages/vue/src/canvas/surface/shader/rasterizer.tssimilarity index 100%rename from packages/vue/src/canvas/surface/shader-rasterizer.tsrename to packages/vue/src/canvas/surface/shader/rasterizer.tsdiff --git a/packages/vue/src/canvas/surface/use.ts b/packages/vue/src/canvas/surface/use.tsindex 18a0e4e25..eaa36f37a 100644--- a/packages/vue/src/canvas/surface/use.ts+++ b/packages/vue/src/canvas/surface/use.ts@@ -9,7 +9,7 @@ import {useCanvasSurfaceLifecycle} from '#vue/canvas/surface/lifecycle'import { createCanvasHitTests, createRulerVisibility } from '#vue/canvas/surface/overlays'-import { useShaderPlayback } from '#vue/canvas/surface/shader-playback'+import { useShaderPlayback } from '#vue/canvas/surface/shader/playback'import type { UseCanvasOptions } from '#vue/canvas/surface/types'export type { UseCanvasOptions } from '#vue/canvas/surface/types'diff --git a/packages/vue/src/controls/shader/preview.ts b/packages/vue/src/controls/shader/preview.tsindex e0ef9b46f..3808c7a84 100644--- a/packages/vue/src/controls/shader/preview.ts+++ b/packages/vue/src/controls/shader/preview.ts@@ -1,6 +1,6 @@import type { ShaderPreset } from '@open-pencil/scene-graph'-import { createShaderRasterizer } from '#vue/canvas/surface/shader-rasterizer'+import { createShaderRasterizer } from '#vue/canvas/surface/shader/rasterizer'import type { ShaderEffect } from './catalog'diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex f7a209bd1..4af40acc9 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -196,6 +196,9 @@"aiSetupWelcomeDescription": "Erstelle und bearbeite Designs auf einer offenen Arbeitsfläche. Importiere Figma-Dateien und mach sie zu deinen eigenen.","aiSetupWelcomeAITitle": "Mit KI gestalten","aiSetupWelcomeAIDescription": "Verbinde die KI, die du bereits nutzt, um die Arbeitsfläche zu bearbeiten und Designs zu prüfen. Du kannst das später in den Einstellungen ändern.",+ "aiSetupWelcomeTourTitle": "Rundgang",+ "aiSetupWelcomeTourDescription": "Eine kurze Datei führt durch Komponenten und Slots, funktionierende Steuerelemente, Modi, Shader, Code und Lint – mit einer Karte, die jeweils sagt, was du ausprobieren kannst.",+ "aiSetupTakeTour": "Rundgang öffnen","aiSetupStart": "KI einrichten","aiSetupSkip": "Mit dem Gestalten beginnen","aiSetupProgress": "Schritt {current} von {total}",diff --git a/packages/vue/src/i18n/locales/de/menu.json b/packages/vue/src/i18n/locales/de/menu.jsonindex f8e06a823..05bdfb4d0 100644--- a/packages/vue/src/i18n/locales/de/menu.json+++ b/packages/vue/src/i18n/locales/de/menu.json@@ -8,6 +8,7 @@"new": "Neu","open": "Öffnen…","openStorageWorkspace": "Speicher-Arbeitsbereich öffnen…",+ "openTour": "Rundgang öffnen","save": "Speichern","saveAs": "Speichern unter…","saveToStorage": "Im Speicher-Arbeitsbereich speichern…",diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex 61814676c..a8ad32c9b 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -196,6 +196,9 @@"aiSetupWelcomeDescription": "Crea y edita diseños en un lienzo abierto. Importa archivos de Figma y hazlos tuyos.","aiSetupWelcomeAITitle": "Diseña con IA","aiSetupWelcomeAIDescription": "Conecta la IA que ya usas para editar el lienzo y revisar diseños. Puedes cambiarlo más tarde en Ajustes.",+ "aiSetupWelcomeTourTitle": "Haz el recorrido",+ "aiSetupWelcomeTourDescription": "Un archivo breve que recorre componentes y slots, controles que funcionan, modos, shaders, código y lint, con una tarjeta en cada parte que te dice qué probar.",+ "aiSetupTakeTour": "Abrir el recorrido","aiSetupStart": "Configurar IA","aiSetupSkip": "Empezar a diseñar","aiSetupProgress": "Paso {current} de {total}",diff --git a/packages/vue/src/i18n/locales/es/menu.json b/packages/vue/src/i18n/locales/es/menu.jsonindex 2759910a9..34a1879a1 100644--- a/packages/vue/src/i18n/locales/es/menu.json+++ b/packages/vue/src/i18n/locales/es/menu.json@@ -8,6 +8,7 @@"new": "Nuevo","open": "Abrir…","openStorageWorkspace": "Abrir espacio de almacenamiento…",+ "openTour": "Abrir el recorrido","save": "Guardar","saveAs": "Guardar como…","saveToStorage": "Guardar en el espacio de almacenamiento…",diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex 7ec93bf38..d5561a4be 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -196,6 +196,9 @@"aiSetupWelcomeDescription": "Créez et modifiez des designs sur un canevas ouvert. Importez des fichiers Figma et appropriez-vous-les.","aiSetupWelcomeAITitle": "Concevez avec l’IA","aiSetupWelcomeAIDescription": "Connectez l’IA que vous utilisez déjà pour modifier le canevas et relire vos designs. Vous pourrez la changer plus tard dans les réglages.",+ "aiSetupWelcomeTourTitle": "Faites la visite",+ "aiSetupWelcomeTourDescription": "Un court fichier qui présente les composants et les slots, des contrôles qui fonctionnent, les modes, les shaders, le code et le lint, avec une carte qui indique quoi essayer à chaque étape.",+ "aiSetupTakeTour": "Ouvrir la visite","aiSetupStart": "Configurer l’IA","aiSetupSkip": "Commencer à concevoir","aiSetupProgress": "Étape {current} sur {total}",diff --git a/packages/vue/src/i18n/locales/fr/menu.json b/packages/vue/src/i18n/locales/fr/menu.jsonindex dbc43e514..5ada2dbf9 100644--- a/packages/vue/src/i18n/locales/fr/menu.json+++ b/packages/vue/src/i18n/locales/fr/menu.json@@ -8,6 +8,7 @@"new": "Nouveau","open": "Ouvrir…","openStorageWorkspace": "Ouvrir l’espace de stockage…",+ "openTour": "Ouvrir la visite","save": "Enregistrer","saveAs": "Enregistrer sous…","saveToStorage": "Enregistrer dans l’espace de stockage…",diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex bc56a75d1..220f8ac4e 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -196,6 +196,9 @@"aiSetupWelcomeDescription": "Crea e modifica design su una tela aperta. Importa file Figma e falli tuoi.","aiSetupWelcomeAITitle": "Progetta con l’IA","aiSetupWelcomeAIDescription": "Collega l’IA che usi già per modificare la tela e rivedere i design. Puoi cambiarla in seguito nelle Impostazioni.",+ "aiSetupWelcomeTourTitle": "Fai il tour",+ "aiSetupWelcomeTourDescription": "Un breve file che mostra componenti e slot, controlli funzionanti, modalità, shader, codice e lint, con una scheda per ogni parte che dice cosa provare.",+ "aiSetupTakeTour": "Apri il tour","aiSetupStart": "Configura l’IA","aiSetupSkip": "Inizia a progettare","aiSetupProgress": "Passo {current} di {total}",diff --git a/packages/vue/src/i18n/locales/it/menu.json b/packages/vue/src/i18n/locales/it/menu.jsonindex 6a34d07ac..944af19ff 100644--- a/packages/vue/src/i18n/locales/it/menu.json+++ b/packages/vue/src/i18n/locales/it/menu.json@@ -8,6 +8,7 @@"new": "Nuovo","open": "Apri…","openStorageWorkspace": "Apri area di archiviazione…",+ "openTour": "Apri il tour","save": "Salva","saveAs": "Salva con nome…","saveToStorage": "Salva nell’area di archiviazione…",diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex ef2486e39..2b0a0a972 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -196,6 +196,9 @@"aiSetupWelcomeDescription": "オープンなキャンバスでデザインを作成・編集できます。Figma ファイルを読み込んで自由に使えます。","aiSetupWelcomeAITitle": "AI でデザインする","aiSetupWelcomeAIDescription": "普段使っている AI を接続して、キャンバスの編集やデザインのレビューに使えます。あとから設定で変更できます。",+ "aiSetupWelcomeTourTitle": "ツアーを見る",+ "aiSetupWelcomeTourDescription": "コンポーネントとスロット、動くコントロール、モード、シェーダー、コード、チェックを順に紹介する短いファイルです。各パートのカードに試すことが書かれています。",+ "aiSetupTakeTour": "ツアーを開く","aiSetupStart": "AI を設定","aiSetupSkip": "デザインを始める","aiSetupProgress": "ステップ {current}/{total}",diff --git a/packages/vue/src/i18n/locales/ja/menu.json b/packages/vue/src/i18n/locales/ja/menu.jsonindex 94252e3ca..e42ffe0c9 100644--- a/packages/vue/src/i18n/locales/ja/menu.json+++ b/packages/vue/src/i18n/locales/ja/menu.json@@ -8,6 +8,7 @@"new": "新規作成","open": "開く…","openStorageWorkspace": "ストレージワークスペースを開く…",+ "openTour": "ツアーを開く","save": "保存","saveAs": "名前を付けて保存…","saveToStorage": "ストレージに保存…",diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex 5e02f2270..9424811af 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -196,6 +196,9 @@"aiSetupWelcomeDescription": "Twórz i edytuj projekty na otwartym płótnie. Importuj pliki Figma i dostosuj je do siebie.","aiSetupWelcomeAITitle": "Projektuj z AI","aiSetupWelcomeAIDescription": "Połącz AI, z którego już korzystasz, aby edytować płótno i przeglądać projekty. Możesz to później zmienić w ustawieniach.",+ "aiSetupWelcomeTourTitle": "Zobacz przewodnik",+ "aiSetupWelcomeTourDescription": "Krótki plik, który pokazuje komponenty i sloty, działające kontrolki, tryby, shadery, kod i lint, z kartą przy każdej części mówiącą, co wypróbować.",+ "aiSetupTakeTour": "Otwórz przewodnik","aiSetupStart": "Skonfiguruj AI","aiSetupSkip": "Zacznij projektować","aiSetupProgress": "Krok {current} z {total}",diff --git a/packages/vue/src/i18n/locales/pl/menu.json b/packages/vue/src/i18n/locales/pl/menu.jsonindex 9be4d2d2f..4d26d3dca 100644--- a/packages/vue/src/i18n/locales/pl/menu.json+++ b/packages/vue/src/i18n/locales/pl/menu.json@@ -8,6 +8,7 @@"new": "Nowy","open": "Otwórz…","openStorageWorkspace": "Otwórz obszar przechowywania…",+ "openTour": "Otwórz przewodnik","save": "Zapisz","saveAs": "Zapisz jako…","saveToStorage": "Zapisz w obszarze przechowywania…",diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex d5467ce6d..6be4b96c0 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -196,6 +196,9 @@"aiSetupWelcomeDescription": "Создавайте и редактируйте дизайн на открытом холсте. Импортируйте файлы Figma и распоряжайтесь ими как своими.","aiSetupWelcomeAITitle": "Дизайн с ИИ","aiSetupWelcomeAIDescription": "Подключите ИИ, которым вы уже пользуетесь, чтобы редактировать холст и проверять дизайн. Это можно изменить позже в настройках.",+ "aiSetupWelcomeTourTitle": "Пройдите тур",+ "aiSetupWelcomeTourDescription": "Короткий файл, который показывает компоненты и слоты, работающие элементы управления, режимы, шейдеры, код и линтер — с карточкой в каждой части о том, что попробовать.",+ "aiSetupTakeTour": "Открыть тур","aiSetupStart": "Настроить ИИ","aiSetupSkip": "Начать работу","aiSetupProgress": "Шаг {current} из {total}",diff --git a/packages/vue/src/i18n/locales/ru/menu.json b/packages/vue/src/i18n/locales/ru/menu.jsonindex 00f92292b..99cbb148f 100644--- a/packages/vue/src/i18n/locales/ru/menu.json+++ b/packages/vue/src/i18n/locales/ru/menu.json@@ -8,6 +8,7 @@"new": "Создать","open": "Открыть…","openStorageWorkspace": "Открыть рабочее пространство хранилища…",+ "openTour": "Открыть тур","save": "Сохранить","saveAs": "Сохранить как…","saveToStorage": "Сохранить в хранилище…",diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex dd86e1e4f..86bf0dce2 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -196,6 +196,9 @@"aiSetupWelcomeDescription": "在开放的画布上创建和编辑设计。导入 Figma 文件,随心使用。","aiSetupWelcomeAITitle": "用 AI 设计","aiSetupWelcomeAIDescription": "连接你已在使用的 AI,用来编辑画布和审查设计。之后可以在设置中更改。",+ "aiSetupWelcomeTourTitle": "参观导览",+ "aiSetupWelcomeTourDescription": "一个简短的文件,依次介绍组件与插槽、可用的控件、模式、着色器、代码和检查,每部分都有卡片告诉你可以尝试什么。",+ "aiSetupTakeTour": "打开导览","aiSetupStart": "设置 AI","aiSetupSkip": "开始设计","aiSetupProgress": "第 {current} 步,共 {total} 步",diff --git a/packages/vue/src/i18n/locales/zh-cn/menu.json b/packages/vue/src/i18n/locales/zh-cn/menu.jsonindex eff6dfb1a..b0f04d625 100644--- a/packages/vue/src/i18n/locales/zh-cn/menu.json+++ b/packages/vue/src/i18n/locales/zh-cn/menu.json@@ -8,6 +8,7 @@"new": "新建","open": "打开…","openStorageWorkspace": "打开存储工作区…",+ "openTour": "打开导览","save": "保存","saveAs": "另存为…","saveToStorage": "保存到存储工作区…",diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex 107fd209e..a7c90e919 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -219,6 +219,10 @@ export const aiMessageDefaults = {aiSetupWelcomeAITitle: 'Design with AI',aiSetupWelcomeAIDescription:'Connect the AI you already use to edit the canvas and review designs. You can change it later in Settings.',+ aiSetupWelcomeTourTitle: 'Take the tour',+ aiSetupWelcomeTourDescription:+ 'A short file that walks through components and slots, working controls, modes, shaders, code, and lint, with a card on each that says what to try.',+ aiSetupTakeTour: 'Open the tour',aiSetupStart: 'Set up AI',aiSetupSkip: 'Start designing',aiSetupProgress: params('Step {current} of {total}'),diff --git a/packages/vue/src/i18n/messages/menu.ts b/packages/vue/src/i18n/messages/menu.tsindex d0495645f..c3c13d507 100644--- a/packages/vue/src/i18n/messages/menu.ts+++ b/packages/vue/src/i18n/messages/menu.ts@@ -11,6 +11,7 @@ export const menuMessageDefaults = {new: 'New',open: 'Open…',openStorageWorkspace: 'Open storage workspace…',+ openTour: 'Open the Tour',save: 'Save',saveAs: 'Save as…',saveToStorage: 'Save to storage…',diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex dc13e2a38..fd60602c4 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -126,7 +126,7 @@ export type {export { useExport } from '#vue/document/export/use'export type { ExportFormatId, ExportFormatOption, ExportSetting } from '#vue/document/export/use'export { useFillControls } from '#vue/controls/fill/use'-export { canDrawShaders, createShaderRasterizer } from '#vue/canvas/surface/shader-rasterizer'+export { canDrawShaders, createShaderRasterizer } from '#vue/canvas/surface/shader/rasterizer'export {addShaderEffect,DEFAULT_SHADER_EFFECT,diff --git a/src/app/demo/document.ts b/src/app/demo/document.tsindex cde6785f1..43d89ca8f 100644--- a/src/app/demo/document.ts+++ b/src/app/demo/document.ts@@ -1,6 +1,10 @@+import { yieldToUI } from '@/app/document/io/browser'import type { EditorStore } from '@/app/editor/session'+import { resolvedAppTheme } from '@/app/shell/theme'+import { createTab } from '@/app/tabs'-import { fitDemoPagesOnFirstVisit } from './viewport'+import { followAppTheme } from './theme'+import { showFirstChapter } from './viewport'/** Built from `tools/generate/demo` before the app is served or bundled. */const DEMO_URL = '/demo.fig'@@ -8,8 +12,8 @@ const DEMO_FILE_NAME = 'Demo.fig'/*** Opens the bundled demo document like any `.fig` file: decoded off the main thread, behind- * the canvas loader, with pages materialized as they are visited. Each page is fitted to the- * viewport on its first visit.+ * the canvas loader. Once it is open it follows the app's theme and the view settles on the+ * first chapter.*/export async function openDemoDocument(store: EditorStore): Promise<void> {const blank = store.graph@@ -24,9 +28,14 @@ export async function openDemoDocument(store: EditorStore): Promise<void> {store.graph.getChildren(store.state.currentPageId).length === 0if (!untouched) returnawait store.openFigFile(file)- const [, ...later] = store.graph.getPages()- fitDemoPagesOnFirstVisit(- store,- later.map((page) => page.id)- )+ if (store.graph === blank) return+ followAppTheme(store, resolvedAppTheme)+ // Opening fits the whole page on the next frame; the first chapter comes after it.+ await yieldToUI()+ if (store.graph.getNode(store.state.currentPageId)) showFirstChapter(store)+}++/** Open the tour in a tab of its own, from the welcome dialog or the File menu. */+export function openTour(): Promise<void> {+ return openDemoDocument(createTab().store)}diff --git a/src/app/demo/theme.ts b/src/app/demo/theme.tsnew file mode 100644index 000000000..4a7d5e33b--- /dev/null+++ b/src/app/demo/theme.ts@@ -0,0 +1,61 @@+import { watch, type WatchSource } from 'vue'++import type { Editor } from '@open-pencil/core/editor'+import type { Color } from '@open-pencil/scene-graph'++type AppTheme = 'dark' | 'light'+type TourThemeEditor = Pick<+ Editor,+ 'graph' | 'setActiveMode' | 'setPageColor' | 'onEditorEvent' | 'requestRender'+>++/**+ * The tour's contract with `tools/generate/demo/src/document/theme.ts`: collections by these+ * names have a Dark and a Light mode, and the Theme collection's Page color is the page+ * background in each.+ */+const TOUR_COLLECTIONS = ['Theme', 'App chrome'] as const+const MODE_NAMES: Record<AppTheme, string> = { dark: 'Dark', light: 'Light' }+const PAGE_COLOR = 'Page'++function isColor(value: unknown): value is Color {+ return typeof value === 'object' && value !== null && 'r' in value && 'a' in value+}++/**+ * Show the tour in the app's theme: each tour collection reads its mode of that name wherever a+ * layer does not pin one, and the page takes the Page color. Neither is an edit, so the tour+ * opens with nothing to save.+ */+export function applyTourTheme(editor: TourThemeEditor, theme: AppTheme): void {+ const { graph } = editor+ graph.applyImportedStateDuring(() => {+ for (const collection of graph.variableCollections.values()) {+ if (!TOUR_COLLECTIONS.some((name) => name === collection.name)) continue+ const mode = collection.modes.find((candidate) => candidate.name === MODE_NAMES[theme])+ if (!mode) continue+ editor.setActiveMode(collection.id, mode.modeId)+ if (collection.name !== TOUR_COLLECTIONS[0]) continue+ const page = collection.variableIds+ .map((id) => graph.variables.get(id))+ .find((variable) => variable?.name === PAGE_COLOR)+ const color = page && graph.resolveVariable(page.id, mode.modeId)+ if (isColor(color)) editor.setPageColor(color)+ }+ })+ editor.requestRender()+}++/**+ * Keep the tour in the app's theme while it is open: now, and whenever the theme changes,+ * until the tab shows another document. Returns a function that stops following.+ */+export function followAppTheme(editor: TourThemeEditor, theme: WatchSource<AppTheme>) {+ const stopWatching = watch(theme, (value) => applyTourTheme(editor, value), { immediate: true })+ const stopListening = editor.onEditorEvent('graph:replaced', stop)+ function stop() {+ stopWatching()+ stopListening()+ }+ return stop+}diff --git a/src/app/demo/viewport.ts b/src/app/demo/viewport.tsindex 1a401c744..12cc968f6 100644--- a/src/app/demo/viewport.ts+++ b/src/app/demo/viewport.ts@@ -1,20 +1,25 @@import type { Editor } from '@open-pencil/core/editor'-type DemoViewportEditor = Pick<Editor, 'onEditorEvent' | 'zoomToFit'>+type DemoViewportEditor = Pick<Editor, 'graph' | 'state' | 'zoomToBounds'>-/** Fit a demo page once, then preserve the user's own viewport on return visits. */-export function fitDemoPagesOnFirstVisit(store: DemoViewportEditor, pageIds: string[]) {- const pending = new Set(pageIds)- const unbindPage = store.onEditorEvent('page:changed', (pageId) => {- if (!pending.delete(pageId)) return- store.zoomToFit()- if (pending.size === 0) dispose()- })- const unbindGraph = store.onEditorEvent('graph:replaced', dispose)+/** The air around the first chapter when the tour opens, in canvas units. */+const MARGIN = 80- function dispose() {- unbindPage()- unbindGraph()- }- return dispose+/**+ * Open the tour on its first chapter: the chapters are sections stacked on one page, so the+ * opening view fills the screen with the first and the rest follow below it.+ */+export function showFirstChapter(store: DemoViewportEditor): void {+ const first = store.graph+ .getChildren(store.state.currentPageId)+ .filter((node) => node.type === 'SECTION')+ .sort((a, b) => a.y - b.y || a.x - b.x)+ .at(0)+ if (!first) return+ store.zoomToBounds(+ first.x - MARGIN,+ first.y - MARGIN,+ first.x + first.width + MARGIN,+ first.y + first.height + MARGIN+ )}diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.tsindex 962e9216e..8c583256e 100644--- a/src/app/shell/menu/app-menu.ts+++ b/src/app/shell/menu/app-menu.ts@@ -20,6 +20,7 @@ import type { BuiltinIOFormatId } from '@open-pencil/core/io'import type { CommandPaletteGroup, CommandPaletteItem, MenuEntry } from '@open-pencil/vue'import { shortcutPlatform, useEditorCommands, useI18n } from '@open-pencil/vue'+import { openTour } from '@/app/demo/document'import { useEditorStore } from '@/app/editor/active-store'import { openVariablesDialog } from '@/app/editor/tokens/dialog'import { openSettingsDialog } from '@/app/settings/dialog'@@ -103,6 +104,7 @@ export function useAppMenu() {new: 'new',open: 'open','open-storage-workspace': 'openStorageWorkspace',+ 'open-tour': 'openTour',save: 'save','save-as': 'saveAs','save-to-storage': 'saveToStorage',@@ -170,6 +172,9 @@ export function useAppMenu() {},open: () => void openFileDialog(),'open-storage-workspace': () => openStorageWorkspace(router),+ 'open-tour': () => {+ openTour().catch((error: unknown) => console.error('[Tour] Could not open the tour:', error))+ },save: () => void store.saveFigFile(),'save-as': () => void store.saveFigFileAs(),'save-to-storage': () => void saveDocumentToStorage(store),diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.tsindex ec1fbe7ff..21716756a 100644--- a/src/app/shell/menu/schema.ts+++ b/src/app/shell/menu/schema.ts@@ -70,6 +70,7 @@ export const APP_MENU_SCHEMA = [{ id: 'open', label: 'Open…', shortcut: 'MOD+O' },{ id: 'open-recent', label: 'Open Recent', target: 'native' },{ id: 'open-storage-workspace', label: 'Open Storage Workspace…', handler: 'shell' },+ { id: 'open-tour', label: 'Open the Tour', handler: 'shell' },{ type: 'separator' },{ id: 'save', label: 'Save', shortcut: 'MOD+S' },{ id: 'save-as', label: 'Save As…', shortcut: 'MOD+SHIFT+S' },diff --git a/src/app/shell/menu/shell.ts b/src/app/shell/menu/shell.tsindex 049590fcd..05a1375f0 100644--- a/src/app/shell/menu/shell.ts+++ b/src/app/shell/menu/shell.ts@@ -1,5 +1,6 @@import { useI18n } from '@open-pencil/vue'+import { openTour } from '@/app/demo/document'import { requestAppExit } from '@/app/document/close/exit'import { openSettingsDialog } from '@/app/settings/dialog'import { setDesignIssuesOnCanvas, setSnappingPreference } from '@/app/settings/preferences/apply'@@ -55,6 +56,9 @@ export function useShellMenu() {'open-storage-workspace': () => {void import('@/router').then(({ default: router }) => openStorageWorkspace(router))},+ 'open-tour': () => {+ openTour().catch((error: unknown) => console.error('[Tour] Could not open the tour:', error))+ },settings: openSettingsDialog,'snap-geometry': () => {const current = appPreferences.value.editing.snapping.geometrydiff --git a/src/components/settings/ai-setup/AISetupDialog.vue b/src/components/settings/ai-setup/AISetupDialog.vueindex 361a0799a..8226a6f16 100644--- a/src/components/settings/ai-setup/AISetupDialog.vue+++ b/src/components/settings/ai-setup/AISetupDialog.vue@@ -4,6 +4,7 @@ import {aiSetupEntry,closeAISetup} from '@/app/ai/models/settings/onboarding/dialog'+import { openTour } from '@/app/demo/document'import { openSettingsDialog } from '@/app/settings/dialog'import { AppDialogRoot } from '@/components/ui/dialog'@@ -17,6 +18,14 @@ function openAdvancedSettings(): void {closeAISetup()openSettingsDialog('ai')}++/** The tour opens in a tab of its own; AI stays one click away in Settings. */+function takeTour(): void {+ closeAISetup()+ openTour().catch((error: unknown) => {+ console.error('[Tour] Could not open the tour:', error)+ })+}</script><template>@@ -26,6 +35,11 @@ function openAdvancedSettings(): void {data-test-id="ai-setup-dialog"@update:open="onOpenChange">- <AISetupFlow :entry="aiSetupEntry" @close="closeAISetup" @advanced="openAdvancedSettings" />+ <AISetupFlow+ :entry="aiSetupEntry"+ @close="closeAISetup"+ @advanced="openAdvancedSettings"+ @tour="takeTour"+ /></AppDialogRoot></template>diff --git a/src/components/settings/ai-setup/AISetupFlow.vue b/src/components/settings/ai-setup/AISetupFlow.vueindex 7cc5f03e4..aab0efbe0 100644--- a/src/components/settings/ai-setup/AISetupFlow.vue+++ b/src/components/settings/ai-setup/AISetupFlow.vue@@ -24,7 +24,7 @@ const { entry, agentsAvailable = IS_TAURI } = defineProps<{entry: AISetupEntryagentsAvailable?: boolean}>()-const emit = defineEmits<{ close: []; advanced: [] }>()+const emit = defineEmits<{ close: []; advanced: []; tour: [] }>()const { ai, common } = useI18n()const styles = tv(theme)()@@ -102,10 +102,21 @@ async function finish(): Promise<void> {<AppDialogBody><div :class="styles.body()" :data-ai-setup-step="phase === 'wizard' ? step : phase">- <section v-if="phase === 'welcome'" :class="styles.intro()">- <h3 :class="styles.introHeading()">{{ ai.aiSetupWelcomeAITitle }}</h3>- <p :class="styles.introText()">{{ ai.aiSetupWelcomeAIDescription }}</p>- </section>+ <template v-if="phase === 'welcome'">+ <section :class="styles.intro()">+ <h3 :class="styles.introHeading()">{{ ai.aiSetupWelcomeAITitle }}</h3>+ <p :class="styles.introText()">{{ ai.aiSetupWelcomeAIDescription }}</p>+ </section>+ <section :class="styles.tour()" data-test-id="ai-setup-tour">+ <div>+ <h3 :class="styles.introHeading()">{{ ai.aiSetupWelcomeTourTitle }}</h3>+ <p :class="styles.introText()">{{ ai.aiSetupWelcomeTourDescription }}</p>+ </div>+ <AppButton variant="outline" :class="styles.tourAction()" @click="emit('tour')">+ {{ ai.aiSetupTakeTour }}+ </AppButton>+ </section>+ </template><template v-else-if="phase === 'saved'"><AISetupReview :plan="plan" />diff --git a/src/theme/settings/ai-setup/flow.ts b/src/theme/settings/ai-setup/flow.tsindex 06e0e65d4..e3fd261da 100644--- a/src/theme/settings/ai-setup/flow.ts+++ b/src/theme/settings/ai-setup/flow.ts@@ -7,6 +7,8 @@ export default {intro: 'rounded-lg border border-accent/25 bg-accent/5 p-4',introHeading: 'text-sm font-semibold text-surface',introText: 'mt-2 text-xs leading-relaxed text-muted',+ tour: 'flex items-start justify-between gap-4 rounded-lg border border-border p-4',+ tourAction: 'shrink-0',group: 'flex flex-col gap-2',groupHeading: 'text-[11px] font-semibold text-muted',// Reads as a group heading; the gap below lives inside the animated content.diff --git a/tests/app/demo/theme.test.ts b/tests/app/demo/theme.test.tsnew file mode 100644index 000000000..910f64bd2--- /dev/null+++ b/tests/app/demo/theme.test.ts@@ -0,0 +1,77 @@+import { describe, expect, spyOn, test } from 'bun:test'++import { nextTick, ref } from 'vue'++import { SceneGraph } from '@open-pencil/scene-graph'++import { applyTourTheme, followAppTheme } from '@/app/demo/theme'+import { createEditorStore } from '@/app/editor/session'++const DARK_PAGE = { r: 0.05, g: 0.05, b: 0.07, a: 1 }+const LIGHT_PAGE = { r: 0.93, g: 0.93, b: 0.95, a: 1 }++/** A tour's two collections, and a collection of the user's own with the same mode names. */+function tour() {+ const store = createEditorStore()+ const graph = store.graph+ const collection = (name: string) => {+ const created = graph.createCollection(name)+ const dark = created.defaultModeId+ graph.renameMode(created.id, dark, 'Dark')+ const light = `${created.id}-light`+ graph.addMode(created.id, light, 'Light', dark)+ return { id: created.id, dark, light }+ }+ const theme = collection('Theme')+ const chrome = collection('App chrome')+ const brand = collection('Brand')+ const page = graph.createVariable('Page', 'COLOR', theme.id, DARK_PAGE)+ page.valuesByMode[theme.light] = LIGHT_PAGE+ return { store, graph, theme, chrome, brand }+}++const activeMode = (graph: ReturnType<typeof tour>['graph'], collectionId: string) =>+ graph.getNodeVariableModeId(graph.getPages()[0].id, collectionId)++describe('the tour in the app theme', () => {+ test('reads both tour collections in the theme’s mode and paints the page', () => {+ const { store, graph, theme, chrome, brand } = tour()+ applyTourTheme(store, 'light')+ expect(activeMode(graph, theme.id)).toBe(theme.light)+ expect(activeMode(graph, chrome.id)).toBe(chrome.light)+ expect(activeMode(graph, brand.id)).toBe(brand.dark)+ expect(store.state.pageColor).toMatchObject(LIGHT_PAGE)++ applyTourTheme(store, 'dark')+ expect(activeMode(graph, theme.id)).toBe(theme.dark)+ expect(store.state.pageColor).toMatchObject(DARK_PAGE)+ })++ test('opens with nothing to save and nothing to undo', () => {+ const { store } = tour()+ const before = store.hasUnsavedChanges()+ applyTourTheme(store, 'light')+ expect(store.hasUnsavedChanges()).toBe(before)+ expect(store.undo.canUndo).toBe(false)+ })++ test('follows the theme until the tab shows another document', async () => {+ const { store, graph, theme } = tour()+ const appTheme = ref<'dark' | 'light'>('dark')+ followAppTheme(store, appTheme)+ expect(activeMode(graph, theme.id)).toBe(theme.dark)+ appTheme.value = 'light'+ await nextTick()+ expect(activeMode(graph, theme.id)).toBe(theme.light)++ // Another document with a collection of the same name is not the tour.+ const other = new SceneGraph()+ const collection = other.createCollection('Theme')+ other.renameMode(collection.id, collection.defaultModeId, 'Dark')+ store.replaceGraph(other)+ const setMode = spyOn(store, 'setActiveMode')+ appTheme.value = 'dark'+ await nextTick()+ expect(setMode).not.toHaveBeenCalled()+ })+})diff --git a/tests/e2e/canvas/demo-workspace.spec.ts b/tests/e2e/canvas/demo-workspace.spec.tsindex d3483946c..9fda40674 100644--- a/tests/e2e/canvas/demo-workspace.spec.ts+++ b/tests/e2e/canvas/demo-workspace.spec.ts@@ -10,77 +10,115 @@ async function openDemo(page: Page) {await waitForDemo(page)return canvas}-test.use({ viewport: { width: 1200, height: 1300 } })-for (const [name, snapshot] of [- ['01 · Components & variables', 'demo-components-and-variables'],- ['02 · Typography', 'demo-typography'],- ['03 · Paint & effects', 'demo-paint'],- ['04 · Controls', 'demo-controls']-] as const) {- test(`demo startup and page navigation: ${name}`, async ({ page }) => {- const canvas = await openDemo(page)- const bounds = await page.evaluate(async (name) => {- const store = window.openPencil?.getStore?.()- if (!store) throw new Error('Editor unavailable')- const page = store.graph.getPages().find((page) => page.name === name)- if (!page) throw new Error(`Missing page: ${name}`)- await store.switchPage(page.id)- const [root] = store.graph.getChildren(page.id)- return {- x: root.x * store.state.zoom + store.state.panX,- y: root.y * store.state.zoom + store.state.panY,- width: root.width * store.state.zoom,- height: root.height * store.state.zoom- }- }, name)- const box = await canvas.canvas.boundingBox()- if (!box) throw new Error('Canvas unavailable')- expect(bounds.x).toBeGreaterThanOrEqual(0)- expect(bounds.y).toBeGreaterThanOrEqual(0)- expect(bounds.x + bounds.width).toBeLessThanOrEqual(box.width)- expect(bounds.y + bounds.height).toBeLessThanOrEqual(box.height)- await canvas.waitForRender()- canvas.assertNoErrors()- expect(await canvas.screenshotCanvasRegion(1200, 1300)).toMatchSnapshot(`${snapshot}.png`, {- maxDiffPixels: 100- })- })+async function setAppTheme(page: Page, theme: 'dark' | 'light') {+ await page.evaluate(async (value) => {+ const themeModulePath = '/src/app/shell/theme.ts'+ const themeModule = await import(themeModulePath)+ themeModule.useAppTheme().setTheme(value)+ }, theme)+ await page.waitForFunction((value) => document.documentElement.dataset.theme === value, theme)}-test('the demo opens as a document with every page', async ({ page }) => {- await openDemo(page)+test.use({ viewport: { width: 1200, height: 900 } })++test('the tour opens on its first chapter, the rest below it', async ({ page }) => {+ const canvas = await openDemo(page)const opened = await page.evaluate(() => {const store = window.openPencil?.getStore?.()if (!store) throw new Error('Editor unavailable')+ const pageId = store.state.currentPageId+ const sections = store.graph+ .getChildren(pageId)+ .filter((node) => node.type === 'SECTION')+ .sort((a, b) => a.y - b.y)+ const [first] = sectionsreturn {name: store.state.documentName,pages: store.graph.getPages().map((item) => item.name),- preparing: store.state.preparation !== null+ chapters: sections.map((section) => section.name),+ unsaved: store.hasUnsavedChanges(),+ first: {+ x: first.x * store.state.zoom + store.state.panX,+ y: first.y * store.state.zoom + store.state.panY,+ width: first.width * store.state.zoom,+ height: first.height * store.state.zoom+ }}})- expect(opened).toEqual({+ expect(opened).toMatchObject({name: 'Demo',- pages: [- '01 · Components & variables',- '02 · Typography',- '03 · Paint & effects',- '04 · Controls'+ pages: ['Tour'],+ chapters: [+ '1 · Hello',+ '2 · Slots',+ '3 · Controls',+ '4 · Modes',+ '5 · Shaders',+ '6 · Code',+ '7 · Lint',+ '8 · Yours'],- preparing: false+ unsaved: false+ })+ const box = await canvas.canvas.boundingBox()+ if (!box) throw new Error('Canvas unavailable')+ expect(opened.first.x).toBeGreaterThanOrEqual(0)+ expect(opened.first.y).toBeGreaterThanOrEqual(0)+ expect(opened.first.x + opened.first.width).toBeLessThanOrEqual(box.width)+ expect(opened.first.y + opened.first.height).toBeLessThanOrEqual(box.height)+ await canvas.waitForRender()+ canvas.assertNoErrors()+ expect(await canvas.screenshotCanvasRegion(1200, 900)).toMatchSnapshot('demo-tour-dark.png', {+ maxDiffPixels: 100+ })+})++test('the tour follows the app theme without becoming an edit', async ({ page }) => {+ const canvas = await openDemo(page)+ const read = () =>+ page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('Editor unavailable')+ const pageId = store.state.currentPageId+ const modeOf = (name: string) => {+ const collection = [...store.graph.variableCollections.values()].find(+ (item) => item.name === name+ )+ const modeId = collection && store.graph.getNodeVariableModeId(pageId, collection.id)+ return collection?.modes.find((mode) => mode.modeId === modeId)?.name+ }+ return {+ theme: modeOf('Theme'),+ chrome: modeOf('App chrome'),+ page: store.state.pageColor,+ unsaved: store.hasUnsavedChanges(),+ undo: store.undo.canUndo+ }+ })+ await setAppTheme(page, 'light')+ await expect.poll(async () => (await read()).theme).toBe('Light')+ const light = await read()+ expect(light).toMatchObject({ chrome: 'Light', unsaved: false, undo: false })+ expect(light.page.r).toBeGreaterThan(0.9)+ await canvas.waitForRender()+ expect(await canvas.screenshotCanvasRegion(1200, 900)).toMatchSnapshot('demo-tour-light.png', {+ maxDiffPixels: 100})++ await setAppTheme(page, 'dark')+ await expect.poll(async () => (await read()).theme).toBe('Dark')+ expect((await read()).page.r).toBeLessThan(0.1)})-test('demo tokens and main-component edits survive undo', async ({ page }) => {+test('tour tokens and main-component edits survive undo', async ({ page }) => {await openDemo(page)const result = await page.evaluate(async () => {const store = window.openPencil?.getStore?.()if (!store) throw new Error('Editor unavailable')const graph = store.graph- // The demo is opened from `.fig`, which gives variables and modes ids of its own.- const collection = [...graph.variableCollections.values()].find(- (item) => item.name === 'Announcement / Color'- )+ // The tour is opened from `.fig`, which gives variables and modes ids of its own.+ const collection = [...graph.variableCollections.values()].find((item) => item.name === 'Theme')const token = [...graph.variables.values()].find((item) => item.name === 'Accent' && item.collectionId === collection?.id)@@ -91,39 +129,35 @@ test('demo tokens and main-component edits survive undo', async ({ page }) => {const changed = structuredClone(token.valuesByMode[mode])store.undoAction()const restored = structuredClone(token.valuesByMode[mode])+const component = Array.from(graph.getAllNodes()).find(- (node) => node.type === 'COMPONENT' && node.name === 'Announcement'- )- if (!component) throw new Error('Announcement component unavailable')- const content = graph.getChildren(component.id).find((node) => node.name === 'Content')- if (!content) throw new Error('Component content unavailable')- const headline = graph.getChildren(content.id).find((node) => node.name === 'Headline')- if (!headline) throw new Error('Headline unavailable')- const instances = Array.from(graph.getAllNodes()).filter(- (node) => node.type === 'INSTANCE' && node.componentId === component.id+ (node) => node.type === 'COMPONENT' && node.name === 'Player')- const headlines = () =>- instances.map((instance) => {- const content = graph.getChildren(instance.id).find((node) => node.name === 'Content')- if (!content) throw new Error('Instance content unavailable')- return graph.getChildren(content.id).find((node) => node.name === 'Headline')?.text- })- store.updateNodeWithUndo(- headline.id,- { text: 'Open studio: bring your next idea' },- 'Edit demo headline'+ if (!component) throw new Error('Player component unavailable')+ const artist = (owner: string) => {+ const track = graph.getChildren(owner).find((node) => node.name === 'Track')+ return track && graph.getChildren(track.id).find((node) => node.name === 'Artist')+ }+ const headline = artist(component.id)+ if (!headline) throw new Error('Artist text unavailable')+ // Instances that leave Artist at the component's value follow its edits.+ const following = Array.from(graph.getAllNodes()).filter(+ (node) =>+ node.type === 'INSTANCE' &&+ node.componentId === component.id &&+ Object.keys(node.componentPropertyAssignments).length === 0)+ const artists = () => following.map((instance) => artist(instance.id)?.text)+ store.updateNodeWithUndo(headline.id, { text: 'Lumen & friends' }, 'Edit tour artist')await store.loadFontsForNodes([component.id])- const editedHeadlines = headlines()+ const edited = artists()store.undoAction()await store.loadFontsForNodes([component.id])- return { original, changed, restored, editedHeadlines, restoredHeadlines: headlines() }+ return { original, changed, restored, count: following.length, edited, reverted: artists() }})expect(result.changed).not.toEqual(result.original)expect(result.restored).toEqual(result.original)- expect(result.editedHeadlines).toEqual([- 'Open studio: bring your next idea',- 'Open studio: bring your next idea'- ])- expect(result.restoredHeadlines).toEqual(['Open studio', 'Open studio'])+ expect(result.count).toBeGreaterThan(1)+ expect(new Set(result.edited)).toEqual(new Set(['Lumen & friends']))+ expect(new Set(result.reverted)).toEqual(new Set(['Lumen']))})diff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-components-and-variables-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-components-and-variables-openpencil-darwin.pngdeleted file mode 100644index 600354e3d..000000000Binary files a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-components-and-variables-openpencil-darwin.png and /dev/null differdiff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-controls-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-controls-openpencil-darwin.pngdeleted file mode 100644index 1d42848e5..000000000Binary files a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-controls-openpencil-darwin.png and /dev/null differdiff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-paint-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-paint-openpencil-darwin.pngdeleted file mode 100644index 73b28ae0a..000000000Binary files a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-paint-openpencil-darwin.png and /dev/null differdiff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-tour-dark-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-tour-dark-openpencil-darwin.pngnew file mode 100644index 000000000..d195da658Binary files /dev/null and b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-tour-dark-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-tour-light-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-tour-light-openpencil-darwin.pngnew file mode 100644index 000000000..e71a2b776Binary files /dev/null and b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-tour-light-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-typography-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-typography-openpencil-darwin.pngdeleted file mode 100644index 068b963a9..000000000Binary files a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-typography-openpencil-darwin.png and /dev/null differdiff --git a/tests/e2e/color-picker/demo-card.spec.ts b/tests/e2e/color-picker/demo-card.spec.tsindex 33b62fdf8..89d3488d7 100644--- a/tests/e2e/color-picker/demo-card.spec.ts+++ b/tests/e2e/color-picker/demo-card.spec.ts@@ -26,10 +26,8 @@ async function selectDemoCard(page: Page, canvas: CanvasHelper) {const store = window.openPencil?.getStore?.()if (!store) throw new Error('OpenPencil store not initialized')const nodes = Array.from(store.graph.nodes.values())- const card =- nodes.find((node) => node.name === 'Card' && node.type === 'COMPONENT') ??- nodes.find((node) => node.name === 'Card')- // The card lives on whichever page the demo keeps its component library on.+ // The Lint chapter's button keeps a hard-coded fill on purpose, for the rules to find.+ const card = nodes.find((node) => node.name === 'Frame 3' && node.type === 'FRAME')let owner = cardwhile (owner && owner.type !== 'CANVAS') {owner = owner.parentId ? store.graph.getNode(owner.parentId) : undefined@@ -48,7 +46,7 @@ async function selectDemoCard(page: Page, canvas: CanvasHelper) {const designPanel = page.getByTestId('design-panel-single')await expect(designPanel).toBeVisible()- await expect(designPanel.getByRole('heading', { name: 'Card' })).toBeVisible()+ await expect(designPanel.getByRole('heading', { name: 'Frame 3' })).toBeVisible()}async function getSelectedFill(page: Page) {diff --git a/tests/e2e/stroke-picker/basic.spec.ts b/tests/e2e/stroke-picker/basic.spec.tsindex 616f959c8..78444859b 100644--- a/tests/e2e/stroke-picker/basic.spec.ts+++ b/tests/e2e/stroke-picker/basic.spec.ts@@ -94,9 +94,8 @@ test('stroke picker hsb saturation and brightness sliders update stroke color onconst store = window.openPencil?.getStore?.()if (!store) throw new Error('OpenPencil store not initialized')const nodes = Array.from(store.graph.nodes.values())- const card =- nodes.find((node) => node.name === 'Card' && node.type === 'COMPONENT') ??- nodes.find((node) => node.name === 'Card')+ // The Lint chapter's button keeps a hard-coded fill on purpose, for the rules to find.+ const card = nodes.find((node) => node.name === 'Frame 3' && node.type === 'FRAME')if (!card) throw new Error('Card not found')let owner: SceneNode | undefined = cardwhile (owner && owner.type !== 'CANVAS') {diff --git a/tests/engine/app/demo/viewport.test.ts b/tests/engine/app/demo/viewport.test.tsindex 17d7e8852..52cffbf76 100644--- a/tests/engine/app/demo/viewport.test.ts+++ b/tests/engine/app/demo/viewport.test.ts@@ -1,48 +1,52 @@import { expect, spyOn, test } from 'bun:test'import { createEditor } from '@open-pencil/core/editor'-import { SceneGraph } from '@open-pencil/scene-graph'-import { fitDemoPagesOnFirstVisit } from '@/app/demo/viewport'+import { showFirstChapter } from '@/app/demo/viewport'-test('fits only the first visit and preserves a custom viewport on return', async () => {+test('zooms to the topmost section with air around it', () => {const editor = createEditor()- const originalPage = editor.state.currentPageId- const next = editor.graph.addPage('Next')- editor.graph.createNode('FRAME', next.id, { x: 1000, y: 1000, width: 100, height: 100 })- const fit = spyOn(editor, 'zoomToFit')- const stop = fitDemoPagesOnFirstVisit(editor, [next.id])+ const pageId = editor.state.currentPageId+ editor.graph.createNode('SECTION', pageId, {+ name: '2 · Later',+ x: 0,+ y: 2000,+ width: 800,+ height: 600+ })+ editor.graph.createNode('SECTION', pageId, {+ name: '1 · First',+ x: 100,+ y: 50,+ width: 1000,+ height: 700+ })+ editor.graph.createNode('FRAME', pageId, {+ name: 'Loose',+ x: -500,+ y: -500,+ width: 10,+ height: 10+ })+ const zoom = spyOn(editor, 'zoomToBounds')try {- await editor.switchPage(next.id)- expect(fit).toHaveBeenCalledTimes(1)- editor.pan(120, 80)- const viewport = { panX: editor.state.panX, panY: editor.state.panY, zoom: editor.state.zoom }- await editor.switchPage(originalPage)- await editor.switchPage(next.id)- expect(fit).toHaveBeenCalledTimes(1)- expect({ panX: editor.state.panX, panY: editor.state.panY, zoom: editor.state.zoom }).toEqual(- viewport- )+ showFirstChapter(editor)+ expect(zoom).toHaveBeenCalledWith(20, -30, 1180, 830)} finally {- stop()- fit.mockRestore()+ zoom.mockRestore()editor.dispose()}})-test('stops fitting after the demo graph is replaced', async () => {+test('leaves the view alone on a page without sections', () => {const editor = createEditor()- const replacement = new SceneGraph()- const nextReplacement = replacement.addPage('User document')- const fit = spyOn(editor, 'zoomToFit')- const stop = fitDemoPagesOnFirstVisit(editor, [nextReplacement.id])+ editor.graph.createNode('FRAME', editor.state.currentPageId, { width: 10, height: 10 })+ const zoom = spyOn(editor, 'zoomToBounds')try {- editor.replaceGraph(replacement)- await editor.switchPage(nextReplacement.id)- expect(fit).not.toHaveBeenCalled()+ showFirstChapter(editor)+ expect(zoom).not.toHaveBeenCalled()} finally {- stop()- fit.mockRestore()+ zoom.mockRestore()editor.dispose()}})diff --git a/tests/engine/app/shell/menu/schema.test.ts b/tests/engine/app/shell/menu/schema.test.tsindex c03c56c02..7b0e7580a 100644--- a/tests/engine/app/shell/menu/schema.test.ts+++ b/tests/engine/app/shell/menu/schema.test.ts@@ -50,6 +50,7 @@ describe('APP_MENU_SCHEMA', () => {expect(shellEntries.map((entry) => ('type' in entry ? '' : entry.id))).toEqual(['open-storage-workspace',+ 'open-tour','view-design-issues','theme-light','theme-dark',diff --git a/tests/helpers/demo.ts b/tests/helpers/demo.tsindex a0b17c366..b4ade5496 100644--- a/tests/helpers/demo.ts+++ b/tests/helpers/demo.ts@@ -4,7 +4,7 @@ export async function waitForDemo(page: Page) {await page.waitForFunction(() => {const store = window.openPencil?.getStore?.()return (- store?.graph.getNode(store.state.currentPageId)?.name === '01 · Components & variables' &&+ store?.graph.getNode(store.state.currentPageId)?.name === 'Tour' &&store.state.preparation === null)})diff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex 753a131b3..3d76e37ad 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -36,7 +36,7 @@ Private tooling lives under `tools/<role>/<domain>/{src,tests}`; Steiger enforce## Demo document-The `/demo` document is built from `tools/generate/demo/src/document/` into the ignored `public/demo.fig`, and the app opens it like any `.fig` file; it is never generated in the browser. `ensureDemoDocument` runs from `vite.config.ts`, rebuilds only when its inputs' fingerprint changes, and runs the build in Bun; `bun run generate:demo` forces it. A section that needs something new from the engine adds that package's `src` to the fingerprint in `tools/generate/demo/src/ensure.ts`.+The `/demo` document is a tour of eight chapters on one page, each a section stacked top to bottom, built from `tools/generate/demo/src/document/`: `theme.ts` (the Theme and App chrome collections, each with a Dark and a Light mode that `src/app/demo/theme.ts` switches by name to follow the app's theme; every color in the tour, icons included, is bound to them), `callout.tsx` (the Tip component every chapter instances, whose Where slot each fills with a piece of the app from `chrome.tsx`, drawn to the dark theme's tokens with the target ringed), `player/` (the player card, its artwork slot, and its controls with behaviours), and one file per chapter under `chapters/`, laid out by `chapters/chapter.ts` as numeral, heading, subject, and tip; `src/app/demo/viewport.ts` opens the tour on the first chapter. It renders design JSX through `document/icons.ts`, which serves Lucide from the bundled icon JSON so the build needs no Iconify API, and writes the ignored `public/demo.fig`, which the app opens like any `.fig` file; it is never generated in the browser. `ensureDemoDocument` runs from `vite.config.ts`, rebuilds only when its inputs' fingerprint changes, and runs the build in Bun; `bun run generate:demo` forces it. A chapter that needs something new from the engine adds that package's `src` to the fingerprint in `tools/generate/demo/src/ensure.ts`. Shader fills get their still frames from `src/shaders/stills.ts`, which draws each preset in the Playwright Chromium with WebGPU (`bunx playwright install chromium` locally; the deploy and preview workflows install it); without the browser the build warns and the editor draws the frames when the demo opens.## Brand assetsdiff --git a/tools/checks/lint/tests/helpers/lint.ts b/tools/checks/lint/tests/helpers/lint.tsindex b6d1b76df..3b59e1562 100644--- a/tools/checks/lint/tests/helpers/lint.ts+++ b/tools/checks/lint/tests/helpers/lint.ts@@ -19,14 +19,31 @@ export async function lint(source: string,rules: Record<string, string>,relativePath = 'fixture.ts'+): Promise<Diagnostic[]> {+ return lintFiles({ [relativePath]: source }, rules)+}++/**+ * Lint several fixtures in one Oxlint run, by their path relative to a temporary directory;+ * each diagnostic's `filename` ends with that path. One process instead of one per fixture+ * keeps a table of cases quick under a busy test runner.+ */+export async function lintFiles(+ sources: Record<string, string>,+ rules: Record<string, string>): Promise<Diagnostic[]> {const root = await resolveWorkspaceRoot(import.meta.dir)const directory = await mkdtemp(join(tmpdir(), 'open-pencil-lint-'))try {- const sourcePath = join(directory, relativePath)+ const sourcePaths = await Promise.all(+ Object.entries(sources).map(async ([relativePath, source]) => {+ const sourcePath = join(directory, relativePath)+ await mkdir(dirname(sourcePath), { recursive: true })+ await writeFile(sourcePath, source)+ return sourcePath+ })+ )const configPath = join(directory, 'oxlint.json')- await mkdir(dirname(sourcePath), { recursive: true })- await writeFile(sourcePath, source)await writeFile(configPath,JSON.stringify({@@ -36,7 +53,14 @@ export async function lint(}))const child = Bun.spawn(- [join(root, 'node_modules/.bin/oxlint'), '-c', configPath, '--format', 'json', sourcePath],+ [+ join(root, 'node_modules/.bin/oxlint'),+ '-c',+ configPath,+ '--format',+ 'json',+ ...sourcePaths+ ],{ stdout: 'pipe', stderr: 'pipe' })const [stdout, stderr, code] = await Promise.all([diff --git a/tools/checks/lint/tests/plugin.test.ts b/tools/checks/lint/tests/plugin.test.tsindex 5c7417d32..bd52243a6 100644--- a/tools/checks/lint/tests/plugin.test.ts+++ b/tools/checks/lint/tests/plugin.test.ts@@ -16,7 +16,7 @@ import { AST_NODE_TYPES, type TSESTree } from '@typescript-eslint/utils'import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts-tools'-import { lint, ruleDiagnostics } from './helpers/lint.ts'+import { lint, lintFiles, ruleDiagnostics } from './helpers/lint.ts'const temporaryDirectories: string[] = []@@ -90,14 +90,22 @@ test('domain naming uses ownership prefixes, not control-kind suffixes', async (test('storage rule permits data keys but rejects storage access', async () => {const rule = 'no-direct-storage-access'- for (const [source, count] of [- ['const state = {localStorage: []}', 0],- ['localStorage.clear()', 1],- ['window.sessionStorage.clear()', 1],- ['const value = {localStorage}', 1]- ] as const) {- const diagnostics = await lint(source, { [`open-pencil/${rule}`]: 'error' })- expect(ruleDiagnostics(diagnostics, rule)).toHaveLength(count)+ const cases = {+ 'data-key.ts': ['const state = {localStorage: []}', 0],+ 'clear.ts': ['localStorage.clear()', 1],+ 'window-session.ts': ['window.sessionStorage.clear()', 1],+ 'shorthand.ts': ['const value = {localStorage}', 1]+ } as const+ const diagnostics = ruleDiagnostics(+ await lintFiles(+ Object.fromEntries(Object.entries(cases).map(([path, [source]]) => [path, source])),+ { [`open-pencil/${rule}`]: 'error' }+ ),+ rule+ )+ for (const [path, [, count]] of Object.entries(cases)) {+ const found = diagnostics.filter((diagnostic) => diagnostic.filename?.endsWith(path))+ expect(found, path).toHaveLength(count)}})diff --git a/tools/generate/demo/package.json b/tools/generate/demo/package.jsonindex f9605590a..c7792fd27 100644--- a/tools/generate/demo/package.json+++ b/tools/generate/demo/package.json@@ -12,11 +12,15 @@"test": "bun test tests"},"dependencies": {+ "@iconify-json/lucide": "^1.2.139","@open-pencil/core": "workspace:*","@open-pencil/design-jsx": "workspace:*","@open-pencil/package-artifacts-tools": "workspace:*","@open-pencil/scene-graph": "workspace:*",- "proper-lockfile": "4.1.2"+ "@playwright/test": "^1.63.0",+ "js-base64": "^3.9.3",+ "proper-lockfile": "4.1.2",+ "shaders": "4.0.4"},"devDependencies": {"@types/bun": "^1.3.14",diff --git a/tools/generate/demo/src/build.ts b/tools/generate/demo/src/build.tsindex 0173f7473..97e14644f 100644--- a/tools/generate/demo/src/build.ts+++ b/tools/generate/demo/src/build.ts@@ -1,19 +1,28 @@import { SkiaRenderer } from '@open-pencil/core/canvas'+import { setPageBackgrounds } from '@open-pencil/core/figma-api'import { exportFigFile, initCanvasKit } from '@open-pencil/core/io'import { computeAllLayouts, installTextMeasurer } from '@open-pencil/core/layout'import { fontManager, prepareGraphFonts } from '@open-pencil/core/text'import { SceneGraph } from '@open-pencil/scene-graph'+import { parseColor } from '@open-pencil/scene-graph/color'-import { createAnnouncementSection } from './document/announcement/section'-import { createControlsSection } from './document/controls/section'-import { createPaintSection } from './document/paint/section'-import { createComponentsSection } from './document/sections/components'-import { createDemoVariables } from './document/sections/variables'-import { createTypographySection } from './document/typography/section'+import { createTipComponent } from './document/callout'+import { arrangeChapters, type ChapterContext } from './document/chapters/chapter'+import { createCodeChapter } from './document/chapters/code'+import { createControlsChapter } from './document/chapters/controls'+import { createHelloChapter } from './document/chapters/hello'+import { createLintChapter } from './document/chapters/lint'+import { createModesChapter } from './document/chapters/modes'+import { createShadersChapter } from './document/chapters/shaders'+import { createSlotsChapter } from './document/chapters/slots'+import { createYoursChapter } from './document/chapters/yours'+import { createTheme, PAGE_BACKGROUND } from './document/theme'+import { drawShaderStills } from './shaders/stills'-const PAGE_ORIGIN = 60-const PAGE_GAP = 64-const INTER_STYLES = ['Regular', 'Medium', 'SemiBold', 'Bold']+const INTER_STYLES = ['Regular', 'Medium', 'SemiBold', 'Bold', 'ExtraBold']++/** The one page the tour is on. */+export const PAGE_NAME = 'Tour'/** A renderer on a 1×1 surface, for measuring text while laying the document out. */export async function measuringRenderer() {@@ -41,34 +50,46 @@ export async function withMeasuredText<T>(}}-/** Builds every page of the demo into a fresh graph, laid out with `renderer`'s text metrics. */-function buildDemoGraph(renderer: SkiaRenderer): Promise<SceneGraph> {+/**+ * Builds the tour into a fresh graph, laid out with `renderer`'s text metrics: one page whose+ * chapters stack top to bottom as sections.+ */+export function buildDemoGraph(renderer: SkiaRenderer): Promise<SceneGraph> {return withMeasuredText(renderer, async () => {const graph = new SceneGraph()- const [first] = graph.getPages()- graph.updateNode(first.id, { name: '01 · Components & variables' })- const typography = graph.addPage('02 · Typography')- const paint = graph.addPage('03 · Paint & effects')- const controls = graph.addPage('04 · Controls')+ const theme = createTheme(graph)+ const [page] = graph.getPages()+ graph.updateNode(page.id, { name: PAGE_NAME })+ setPageBackgrounds(graph, page, [+ { type: 'SOLID', color: parseColor(PAGE_BACKGROUND), opacity: 1, visible: true }+ ])- const announcement = await createAnnouncementSection(graph, first.id)- graph.updateNode(announcement.rootId, { x: PAGE_ORIGIN, y: PAGE_ORIGIN })- computeAllLayouts(graph, first.id)- await createComponentsSection(graph, first.id, {- x: PAGE_ORIGIN,- y: PAGE_ORIGIN + (graph.getNode(announcement.rootId)?.height ?? 0) + PAGE_GAP- })- createDemoVariables(graph)- await createTypographySection(graph, typography.id)- await createPaintSection(graph, paint.id)- await createControlsSection(graph, controls.id)+ // The tip every chapter uses; the last chapter takes it in under its own content.+ const tip = await createTipComponent(graph, theme, page.id)+ const context: ChapterContext = {+ graph,+ theme,+ pageId: page.id,+ tipId: tip.id,+ whereSlotId: tip.whereSlotId+ }- const pages = graph.getPages()- await prepareGraphFonts(+ // Main components first, so the chapters before them can place instances.+ const parts = await createControlsChapter(context)+ const player = await createSlotsChapter(context, parts)+ await createHelloChapter(context, player)+ await createModesChapter(context, player)+ await createShadersChapter(context)+ await createCodeChapter(context, player)+ await createLintChapter(context)+ await createYoursChapter(context)+ arrangeChapters(graph,- pages.map((page) => page.id)+ graph.getChildren(page.id).filter((node) => node.type === 'SECTION'))- for (const page of pages) computeAllLayouts(graph, page.id)++ await prepareGraphFonts(graph, [page.id])+ computeAllLayouts(graph, page.id)return graph})}@@ -76,5 +97,7 @@ function buildDemoGraph(renderer: SkiaRenderer): Promise<SceneGraph> {/** The demo document as `.fig` bytes, as `/demo` opens it. */export async function buildDemoDocument(): Promise<Uint8Array> {const { ck, renderer } = await measuringRenderer()- return exportFigFile(await buildDemoGraph(renderer), ck, renderer)+ const graph = await buildDemoGraph(renderer)+ await drawShaderStills(graph)+ return exportFigFile(graph, ck, renderer)}diff --git a/tools/generate/demo/src/document/announcement/component.ts b/tools/generate/demo/src/document/announcement/component.tsdeleted file mode 100644index fad72ed1c..000000000--- a/tools/generate/demo/src/document/announcement/component.ts+++ /dev/null@@ -1,121 +0,0 @@-import { renderTree } from '@open-pencil/core/design-jsx'-import { Component, Frame, Instance, Rectangle, Text } from '@open-pencil/design-jsx'-import type { ComponentPropertyDefinition, SceneGraph } from '@open-pencil/scene-graph'--import { ANNOUNCEMENT } from './content'-import type { AnnouncementTokens } from './tokens'--export const ANNOUNCEMENT_PROPERTIES = {- title: {- id: 'announcement-title',- name: 'Headline',- type: 'TEXT',- defaultValue: ANNOUNCEMENT.title- },- description: {- id: 'announcement-description',- name: 'Description',- type: 'TEXT',- defaultValue: ANNOUNCEMENT.description- },- details: {- id: 'announcement-details',- name: 'Details',- type: 'TEXT',- defaultValue: ANNOUNCEMENT.details- },- showDetails: {- id: 'announcement-show-details',- name: 'Show details',- type: 'BOOLEAN',- defaultValue: 'true'- }-} satisfies Record<string, ComponentPropertyDefinition>--interface AnnouncementSourceParents {- graphicParentId: string- componentParentId: string-}--export async function createAnnouncementComponent(- graph: SceneGraph,- parents: AnnouncementSourceParents,- tokens: AnnouncementTokens-) {- const graphic = await renderTree(- graph,- Component({- name: 'Announcement / motif',- grid: true,- columns: '1fr 1fr',- rows: '1fr 1fr',- gap: 6,- w: 56,- h: 56,- children: [1, 0.35, 0.35, 1].map((opacity) =>- Rectangle({ w: 'fill', h: 'fill', rounded: 3, bg: tokens.accent, opacity })- )- }),- { parentId: parents.graphicParentId }- )- const text = { font: 'Inter', color: tokens.ink }- const component = await renderTree(- graph,- Component({- name: 'Announcement',- properties: Object.values(ANNOUNCEMENT_PROPERTIES),- flex: 'row',- w: 600,- h: 'hug',- p: tokens.padding,- gap: tokens.padding,- bg: tokens.surface,- rounded: 16,- children: [- Instance({ name: 'Shared motif', of: graphic.id }),- Frame({- name: 'Content',- flex: 'col',- w: 'fill',- h: 'hug',- gap: tokens.gap,- children: [- Text({- ...text,- name: 'Headline',- w: 'fill',- size: 28,- weight: 600,- children: ANNOUNCEMENT.title,- propertyRefs: [{ propertyId: ANNOUNCEMENT_PROPERTIES.title.id, field: 'TEXT' }]- }),- Text({- ...text,- name: 'Description',- w: 'fill',- size: 14,- lineHeight: 22,- children: ANNOUNCEMENT.description,- propertyRefs: [{ propertyId: ANNOUNCEMENT_PROPERTIES.description.id, field: 'TEXT' }]- }),- Text({- ...text,- name: 'Details',- w: 'fill',- size: 12,- lineHeight: 16,- color: tokens.muted,- children: ANNOUNCEMENT.details,- propertyRefs: [- { propertyId: ANNOUNCEMENT_PROPERTIES.details.id, field: 'TEXT' },- { propertyId: ANNOUNCEMENT_PROPERTIES.showDetails.id, field: 'VISIBLE' }- ]- })- ]- })- ]- }),- { parentId: parents.componentParentId }- )- return { componentId: component.id, graphicId: graphic.id }-}diff --git a/tools/generate/demo/src/document/announcement/content.ts b/tools/generate/demo/src/document/announcement/content.tsdeleted file mode 100644index e21a7aeb6..000000000--- a/tools/generate/demo/src/document/announcement/content.ts+++ /dev/null@@ -1,9 +0,0 @@-export const ANNOUNCEMENT = {- title: 'Open studio',- description:- 'Bring a work in progress. Share an idea, ask a question, or spend an hour designing together.',- details: 'SAMPLE EVENT · SATURDAY, 14:00 · ONLINE'-}--export const EDITING_PROMPT =- 'Try editing the main headline, changing the Accent token, or hiding Details on one instance.'diff --git a/tools/generate/demo/src/document/announcement/section.ts b/tools/generate/demo/src/document/announcement/section.tsdeleted file mode 100644index 53903b6a1..000000000--- a/tools/generate/demo/src/document/announcement/section.ts+++ /dev/null@@ -1,142 +0,0 @@-import { renderTree } from '@open-pencil/core/design-jsx'-import { Frame, Instance, Text } from '@open-pencil/design-jsx'-import type { SceneGraph } from '@open-pencil/scene-graph'--import { ANNOUNCEMENT_PROPERTIES, createAnnouncementComponent } from './component'-import { EDITING_PROMPT } from './content'-import { createAnnouncementTokens } from './tokens'--export async function createAnnouncementSection(graph: SceneGraph, parentId: string) {- const tokens = createAnnouncementTokens(graph)- const label = { font: 'Inter', size: 12, color: '#536487' }- const root = await renderTree(- graph,- Frame({- name: 'Announcement system',- flex: 'col',- w: 'hug',- h: 'hug',- gap: 32,- p: 32,- bg: '#FFFFFF',- children: Text({- font: 'Inter',- size: 20,- weight: 600,- color: '#172554',- children: 'One announcement. Different spaces.'- })- }),- { parentId }- )- const examples = await renderTree(- graph,- Frame({ name: 'Linked examples', flex: 'row', w: 'hug', h: 'hug', gap: 32 }),- { parentId: root.id }- )- const sources = await renderTree(- graph,- Frame({- name: 'Editable sources',- flex: 'col',- w: 'hug',- h: 'hug',- gap: 16,- children: Text({ ...label, children: 'EDIT THE SOURCES BELOW · WATCH THE EXAMPLES ABOVE' })- }),- { parentId: root.id }- )- const sourceRow = await renderTree(- graph,- Frame({ name: 'Source components', flex: 'row', w: 'hug', h: 'hug', gap: 24 }),- { parentId: sources.id }- )- const graphicSource = await renderTree(- graph,- Frame({- name: 'Shared motif source',- flex: 'col',- w: 192,- h: 'hug',- gap: 16,- children: [- Text({ ...label, color: '#9747FF', children: '01 / SHARED MOTIF' }),- Text({- ...label,- w: 'fill',- lineHeight: 18,- children: 'Edit these shapes. Every announcement uses this component.'- })- ]- }),- { parentId: sourceRow.id }- )- const announcementSource = await renderTree(- graph,- Frame({- name: 'Main announcement source',- flex: 'col',- w: 600,- h: 'hug',- gap: 16,- children: [- Text({ ...label, color: '#9747FF', children: '02 / MAIN ANNOUNCEMENT' }),- Text({- ...label,- w: 'fill',- lineHeight: 18,- children: 'Edit the headline or description here to update both linked examples.'- })- ]- }),- { parentId: sourceRow.id }- )- const { componentId, graphicId } = await createAnnouncementComponent(- graph,- {- graphicParentId: graphicSource.id,- componentParentId: announcementSource.id- },- tokens- )- const instanceIds: string[] = []- for (const example of [- { label: 'WIDE / ALL DETAILS', width: 600, showDetails: 'true' },- { label: 'NARROW / DETAILS HIDDEN', width: 360, showDetails: 'false' }- ]) {- const slot = await renderTree(- graph,- Frame({- name: example.label,- flex: 'col',- w: example.width,- h: 'hug',- gap: 16,- children: Text({ ...label, children: example.label })- }),- { parentId: examples.id }- )- const instance = await renderTree(- graph,- Instance({- of: componentId,- w: 'fill',- properties: { [ANNOUNCEMENT_PROPERTIES.showDetails.id]: example.showDetails }- }),- { parentId: slot.id }- )- instanceIds.push(instance.id)- }- await renderTree(- graph,- Text({- ...label,- name: 'Editing instructions',- w: 900,- lineHeight: 18,- children: EDITING_PROMPT- }),- { parentId: root.id }- )- return { rootId: root.id, componentId, graphicId, instanceIds }-}diff --git a/tools/generate/demo/src/document/announcement/tokens.ts b/tools/generate/demo/src/document/announcement/tokens.tsdeleted file mode 100644index c4f3cf0d9..000000000--- a/tools/generate/demo/src/document/announcement/tokens.ts+++ /dev/null@@ -1,60 +0,0 @@-import { defineVars } from '@open-pencil/design-jsx'-import type { SceneGraph } from '@open-pencil/scene-graph'-import { parseColor } from '@open-pencil/scene-graph/color'--export function createAnnouncementTokens(graph: SceneGraph) {- graph.addCollection({- id: 'announcement-colors',- name: 'Announcement / Color',- modes: [{ modeId: 'default', name: 'Default' }],- defaultModeId: 'default',- variableIds: []- })- for (const [id, name, hex] of [- ['announcement-accent', 'Accent', '#4F46E5'],- ['announcement-surface', 'Surface', '#EEF2FF'],- ['announcement-ink', 'Text/Primary', '#172554'],- ['announcement-muted', 'Text/Secondary', '#536487']- ]) {- graph.addVariable({- id,- name,- type: 'COLOR',- collectionId: 'announcement-colors',- valuesByMode: { default: parseColor(hex) },- description: '',- hiddenFromPublishing: false- })- }- graph.addCollection({- id: 'announcement-spacing',- name: 'Announcement / Spacing',- modes: [{ modeId: 'default', name: 'Default' }],- defaultModeId: 'default',- variableIds: []- })- for (const [id, name, value] of [- ['announcement-padding', 'Padding', 24],- ['announcement-gap', 'Content gap', 12]- ] as const) {- graph.addVariable({- id,- name,- type: 'FLOAT',- collectionId: 'announcement-spacing',- valuesByMode: { default: value },- description: '',- hiddenFromPublishing: false- })- }- return defineVars({- accent: 'announcement-accent',- surface: 'announcement-surface',- ink: 'announcement-ink',- muted: 'announcement-muted',- padding: 'announcement-padding',- gap: 'announcement-gap'- })-}--export type AnnouncementTokens = ReturnType<typeof createAnnouncementTokens>diff --git a/tools/generate/demo/src/document/callout.tsx b/tools/generate/demo/src/document/callout.tsxnew file mode 100644index 000000000..1a5b81567--- /dev/null+++ b/tools/generate/demo/src/document/callout.tsx@@ -0,0 +1,168 @@+/** @jsxImportSource @open-pencil/design-jsx */+/**+ * The tour's callout: one card per page with a step number, what to try, and the shortcut.+ * It is a component with text properties, so its instances are the first thing a visitor who+ * clicks one sees in the panel.+ */+import { Component, Frame, Instance, Text, type TreeNode } from '@open-pencil/design-jsx'+import {+ createComponentPropertyId,+ createSlotProperty,+ updateSlotProperty,+ type ComponentPropertyDefinition,+ type SceneGraph+} from '@open-pencil/scene-graph'++import { previewButton } from './chrome'+import { renderTree } from './icons'+import type { Theme } from './theme'++export const TIP_PROPERTIES = {+ step: { id: 'tip-step', name: 'Step', type: 'TEXT', defaultValue: '1' },+ title: { id: 'tip-title', name: 'Title', type: 'TEXT', defaultValue: 'Try this' },+ body: {+ id: 'tip-body',+ name: 'Body',+ type: 'TEXT',+ defaultValue: 'Select something on the canvas and look at the panel on the right.'+ },+ keys: { id: 'tip-keys', name: 'Shortcut', type: 'TEXT', defaultValue: '⌥ ⌘ ↩' },+ showKeys: { id: 'tip-show-keys', name: 'Show shortcut', type: 'BOOLEAN', defaultValue: 'true' }+} satisfies Record<string, ComponentPropertyDefinition>++export const TIP_WIDTH = 320+/** The slot a tip shows where to click in: a piece of the app's chrome with the target ringed. */+export const WHERE_SLOT_NAME = 'Where'++/** The Tip main component on the page, with its Where slot defined. */+export async function createTipComponent(+ graph: SceneGraph,+ theme: Theme,+ pageId: string+): Promise<{ id: string; whereSlotId: string }> {+ const { id } = await renderTree(graph, tipComponent(theme), { parentId: pageId, x: 0, y: 0 })+ const where = graph.getChildren(id).find((child) => child.name === WHERE_SLOT_NAME)+ const whereSlotId = createComponentPropertyId()+ if (!where || !createSlotProperty(graph, where.id, whereSlotId)) {+ throw new Error('The tip has no Where frame to make a slot of')+ }+ updateSlotProperty(graph, id, whereSlotId, {+ description: 'Where to click: a piece of the app with the target ringed.',+ slotSettings: { maxChildren: 1 }+ })+ return { id, whereSlotId }+}++function tipComponent(theme: Theme): TreeNode {+ const { vars } = theme+ return (+ <Component+ name="Tip"+ properties={Object.values(TIP_PROPERTIES)}+ flex="col"+ w={TIP_WIDTH}+ h="hug"+ p={20}+ gap={12}+ rounded={16}+ bg={vars.surface}+ stroke={vars.line}+ >+ <Frame name="Heading" flex="row" w="fill" h="hug" gap={12} items="center">+ <Frame+ name="Step"+ flex="row"+ w={28}+ h={28}+ rounded={14}+ justify="center"+ items="center"+ bg={vars.accent}+ >+ <Text+ name="Number"+ font="Inter"+ size={13}+ weight={700}+ color={vars.onAccent}+ propertyRefs={[{ propertyId: TIP_PROPERTIES.step.id, field: 'TEXT' }]}+ >+ {TIP_PROPERTIES.step.defaultValue}+ </Text>+ </Frame>+ <Text+ name="Title"+ font="Inter"+ size={15}+ weight={600}+ color={vars.text}+ propertyRefs={[{ propertyId: TIP_PROPERTIES.title.id, field: 'TEXT' }]}+ >+ {TIP_PROPERTIES.title.defaultValue}+ </Text>+ </Frame>+ <Text+ name="Body"+ font="Inter"+ size={13}+ lineHeight={20}+ w="fill"+ color={vars.muted}+ propertyRefs={[{ propertyId: TIP_PROPERTIES.body.id, field: 'TEXT' }]}+ >+ {TIP_PROPERTIES.body.defaultValue}+ </Text>+ <Frame name={WHERE_SLOT_NAME} flex="col" w="fill" h="hug" items="start">+ {previewButton(theme)}+ </Frame>+ <Frame+ name="Shortcut"+ flex="row"+ w="hug"+ h="hug"+ px={10}+ py={6}+ rounded={8}+ bg={vars.raised}+ propertyRefs={[{ propertyId: TIP_PROPERTIES.showKeys.id, field: 'VISIBLE' }]}+ >+ <Text+ name="Keys"+ font="Inter"+ size={12}+ weight={600}+ color={vars.text}+ propertyRefs={[{ propertyId: TIP_PROPERTIES.keys.id, field: 'TEXT' }]}+ >+ {TIP_PROPERTIES.keys.defaultValue}+ </Text>+ </Frame>+ </Component>+ )+}++export interface Tip {+ step: number+ title: string+ body: string+ /** The shortcut to show, if the step has one. */+ keys?: string+ /** The piece of the app to show in the Where slot, with its target ringed. */+ where?: TreeNode+}++export function tipInstance(componentId: string, tip: Tip): TreeNode {+ return (+ <Instance+ of={componentId}+ name={`Tip ${tip.step}`}+ properties={{+ [TIP_PROPERTIES.step.id]: String(tip.step),+ [TIP_PROPERTIES.title.id]: tip.title,+ [TIP_PROPERTIES.body.id]: tip.body,+ [TIP_PROPERTIES.keys.id]: tip.keys ?? '',+ [TIP_PROPERTIES.showKeys.id]: tip.keys ? 'true' : 'false'+ }}+ />+ )+}diff --git a/tools/generate/demo/src/document/chapters/chapter.ts b/tools/generate/demo/src/document/chapters/chapter.tsnew file mode 100644index 000000000..b7d413464--- /dev/null+++ b/tools/generate/demo/src/document/chapters/chapter.ts@@ -0,0 +1,183 @@+/**+ * How every chapter of the tour is laid out: a section on the one page, holding a numbered+ * heading, the chapter's subject below it, and the Tip card to the subject's right. One subject+ * and one tip per chapter; nothing else. Chapters stack top to bottom, so scrolling reads the+ * tour in order and zooming out shows it whole.+ */+import { computeAllLayouts } from '@open-pencil/core/layout'+import { Frame, Section, Text } from '@open-pencil/design-jsx'+import type { TreeNode } from '@open-pencil/design-jsx'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import { tipInstance, type Tip } from '../callout'+import { renderTree } from '../icons'+import { fillSlot } from '../slot-content'+import type { Theme } from '../theme'++/** Where the first chapter sits on the page. */+export const PAGE_ORIGIN = 0+/** The air inside a chapter's section. */+export const CHAPTER_PADDING = 96+/** The gap between chapters along the strip. */+export const CHAPTER_GAP = 240+const HEADING_GAP = 72+const TIP_GAP = 64+const HEADING_WIDTH = 720++export interface ChapterContext {+ graph: SceneGraph+ theme: Theme+ pageId: string+ /** The Tip main component every chapter's callout is an instance of. */+ tipId: string+ /** Its Where slot, which each callout fills with the piece of the app to click. */+ whereSlotId: string+}++export interface Heading {+ title: string+ subtitle: string+}++export interface Chapter {+ /** The chapter's section, sized to its content. */+ section: SceneNode+ /** The chapter's subject, for chapters that add to it. */+ subject: SceneNode+}++/** Render `tree` under `parentId` at (`x`, `y`) and return the layer, with its size laid out. */+export async function place(+ { graph }: ChapterContext,+ tree: TreeNode,+ parentId: string,+ x: number,+ y: number+): Promise<SceneNode> {+ const { id } = await renderTree(graph, tree, { parentId, x, y })+ const node = graph.getNode(id)+ if (!node) throw new Error(`"${tree.props.name ?? tree.type}" did not render`)+ return node+}++function heading({ vars }: Theme, index: number, { title, subtitle }: Heading): TreeNode {+ return Frame({+ name: 'Heading',+ flex: 'col',+ w: HEADING_WIDTH,+ h: 'hug',+ gap: 20,+ children: [+ Text({+ name: 'Number',+ font: 'Inter',+ size: 88,+ weight: 800,+ letterSpacing: -4,+ color: vars.numeral,+ children: String(index).padStart(2, '0')+ }),+ Text({+ name: 'Title',+ font: 'Inter',+ size: 48,+ weight: 700,+ letterSpacing: -1,+ color: vars.text,+ children: title+ }),+ Text({+ name: 'Subtitle',+ font: 'Inter',+ size: 18,+ lineHeight: 28,+ w: 'fill',+ color: vars.muted,+ children: subtitle+ })+ ]+ })+}++/**+ * Lay a chapter out in a section of its own: heading, then `subject` under it, then `tip` to+ * the subject's right, top aligned. `fill` adds to the subject once it exists, before the tip+ * is placed beside it, for content that needs the subject's layers, such as instances of a+ * component in it. The section is left at the page origin; `arrangeChapters` places it.+ */+export async function layoutChapter(+ context: ChapterContext,+ options: {+ index: number+ name: string+ heading: Heading+ subject: TreeNode+ tip: Tip+ fill?: (subject: SceneNode) => Promise<void>+ }+): Promise<Chapter> {+ const { graph, pageId } = context+ const section = await place(+ context,+ Section({+ name: `${options.index} · ${options.name}`,+ w: 100,+ h: 100,+ bg: context.theme.vars.section+ }),+ pageId,+ PAGE_ORIGIN,+ PAGE_ORIGIN+ )+ const pad = CHAPTER_PADDING+ const head = await place(+ context,+ heading(context.theme, options.index, options.heading),+ section.id,+ pad,+ pad+ )+ const top = pad + head.height + HEADING_GAP+ let subject = await place(context, options.subject, section.id, pad, top)+ if (options.fill) {+ await options.fill(subject)+ computeAllLayouts(graph, pageId)+ subject = graph.getNode(subject.id) ?? subject+ }+ const tip = await place(+ context,+ tipInstance(context.tipId, options.tip),+ section.id,+ pad + subject.width + TIP_GAP,+ top+ )+ if (options.tip.where) {+ await fillSlot(graph, tip.id, context.whereSlotId, options.tip.where)+ computeAllLayouts(graph, pageId)+ }+ fitSection(context, section.id)+ return { section: graph.getNode(section.id) ?? section, subject }+}++/** Size a section around everything in it, with the chapter's padding past the furthest edges. */+export function fitSection({ graph }: ChapterContext, sectionId: string): void {+ const children = graph.getChildren(sectionId)+ graph.updateNode(sectionId, {+ width: Math.max(...children.map((child) => child.x + child.width)) + CHAPTER_PADDING,+ height: Math.max(...children.map((child) => child.y + child.height)) + CHAPTER_PADDING+ })+}++/**+ * Place the chapters' sections top to bottom in reading order, `CHAPTER_GAP` apart, and order+ * them the same way in the layer list, which reads the first child first.+ */+export function arrangeChapters(graph: SceneGraph, sections: readonly SceneNode[]): void {+ const ordered = [...sections].sort((a, b) => a.name.localeCompare(b.name))+ let y = PAGE_ORIGIN+ for (const [index, section] of ordered.entries()) {+ graph.updateNode(section.id, { x: PAGE_ORIGIN, y })+ y += (graph.getNode(section.id)?.height ?? section.height) + CHAPTER_GAP+ if (section.parentId) graph.insertChildAt(section.id, section.parentId, index)+ }+}diff --git a/tools/generate/demo/src/document/chapters/code.ts b/tools/generate/demo/src/document/chapters/code.tsnew file mode 100644index 000000000..80f6e31ae--- /dev/null+++ b/tools/generate/demo/src/document/chapters/code.ts@@ -0,0 +1,25 @@+import { Instance } from '@open-pencil/design-jsx'++import { panelTabs } from '../chrome'+import { layoutChapter, type Chapter, type ChapterContext } from './chapter'+import type { Player } from './slots'++/** Code: the player once more, for the Code tab to read. */+export function createCodeChapter(context: ChapterContext, player: Player): Promise<Chapter> {+ return layoutChapter(context, {+ index: 6,+ name: 'Code',+ heading: {+ title: 'It is code, too.',+ subtitle:+ 'Anything on the canvas reads as HTML, Vue, or React, with CSS or Tailwind. Components with behaviours come out as Reka UI components, variables as tokens.'+ },+ subject: Instance({ of: player.id }),+ tip: {+ step: 6,+ title: 'Open the Code tab',+ body: 'Select the player and switch the panel from Design to Code. Choose a framework and a styling, then copy, or export the selection as a file from the Export section.',+ where: panelTabs(context.theme, 'Code')+ }+ })+}diff --git a/tools/generate/demo/src/document/chapters/controls.ts b/tools/generate/demo/src/document/chapters/controls.tsnew file mode 100644index 000000000..9e0ab30a1--- /dev/null+++ b/tools/generate/demo/src/document/chapters/controls.ts@@ -0,0 +1,59 @@+import { Frame } from '@open-pencil/design-jsx'+import type { SceneGraph } from '@open-pencil/scene-graph'++import { previewPill } from '../chrome'+import type { PlayerParts } from '../player/card'+import { optionToggle, playToggle, progressSlider, skipButton } from '../player/controls'+import { layoutChapter, type ChapterContext } from './chapter'++/** The variant of the set `setId` named `name`. */+export function variantOf(graph: SceneGraph, setId: string, name: string): string {+ const variant = graph.getChildren(setId).find((child) => child.name === name)+ if (!variant) throw new Error(`The set has no variant "${name}"`)+ return variant.id+}++/**+ * Controls: the main components the player is built from, each with a behaviour. Returns the+ * variants the player's instances show.+ */+export async function createControlsChapter(context: ChapterContext): Promise<PlayerParts> {+ const { graph, theme } = context+ const { subject: board } = await layoutChapter(context, {+ index: 3,+ name: 'Controls',+ heading: {+ title: 'They work.',+ subtitle:+ 'Each main component has a behaviour from the panel: a slider, two toggles, a button. In preview they run as real Reka UI controls, drawn by their own variants.'+ },+ subject: Frame({+ name: 'Controls',+ flex: 'col',+ w: 'hug',+ h: 'hug',+ gap: 32,+ p: 32,+ rounded: theme.vars.radius,+ bg: theme.vars.surface,+ stroke: theme.vars.line,+ children: [progressSlider(theme), playToggle(theme), optionToggle(theme), skipButton(theme)]+ }),+ tip: {+ step: 3,+ title: 'Press play',+ body: 'Open preview and press the play button: it swaps to pause. Drag the slider. Nothing you do in preview changes the document; Reset puts it all back.',+ keys: '⌥ ⌘ ↩',+ where: previewPill(theme)+ }+ })+ const [slider, play, option, skip] = graph.getChildren(board.id)+ return {+ slider: slider.id,+ play: variantOf(graph, play.id, 'Playing=Off'),+ shuffle: variantOf(graph, option.id, 'Pressed=On, Icon=Shuffle'),+ repeat: variantOf(graph, option.id, 'Pressed=Off, Icon=Repeat'),+ back: variantOf(graph, skip.id, 'Direction=Back, Interaction=Default'),+ forward: variantOf(graph, skip.id, 'Direction=Forward, Interaction=Default')+ }+}diff --git a/tools/generate/demo/src/document/chapters/hello.ts b/tools/generate/demo/src/document/chapters/hello.tsnew file mode 100644index 000000000..fb8da079a--- /dev/null+++ b/tools/generate/demo/src/document/chapters/hello.ts@@ -0,0 +1,61 @@+import { Frame, Instance, shader } from '@open-pencil/design-jsx'+import type { ShaderPreset } from '@open-pencil/scene-graph'++import { previewButton } from '../chrome'+import { layoutChapter, type Chapter, type ChapterContext } from './chapter'+import type { Player } from './slots'++export const HERO_WIDTH = 880+export const HERO_HEIGHT = 640++/** The hero's background: a slow mesh of the theme's violets. */+export const HERO_PRESET: ShaderPreset = {+ components: [+ {+ type: 'MeshGradient',+ props: {+ stops: [+ { color: '#0F0F13', position: 0 },+ { color: '#2E1065', position: 0.3 },+ { color: '#7C3AED', position: 0.6 },+ { color: '#E879F9', position: 0.85 },+ { color: '#FDE68A', position: 1 }+ ],+ speed: 0.6,+ swirl: 0.4+ }+ }+ ]+}++/** Hello: the player on a live background, and the one thing to try first. */+export function createHelloChapter(context: ChapterContext, player: Player): Promise<Chapter> {+ return layoutChapter(context, {+ index: 1,+ name: 'Hello',+ heading: {+ title: 'Hello.',+ subtitle:+ 'This file is a short tour. Scroll down, or drag the canvas with the hand tool, to follow it: every chapter shows one thing and a card tells you what to try. Nothing here is a mock-up: it is all editable.'+ },+ subject: Frame({+ name: 'Hero',+ flex: 'row',+ w: HERO_WIDTH,+ h: HERO_HEIGHT,+ justify: 'center',+ items: 'center',+ rounded: 32,+ overflow: 'hidden',+ bg: shader(HERO_PRESET),+ children: [Instance({ of: player.id })]+ }),+ tip: {+ step: 1,+ title: 'Press preview',+ body: 'The background starts to move and the player becomes a real control: press play, drag the progress, toggle shuffle. Esc brings you back.',+ keys: '⌥ ⌘ ↩',+ where: previewButton(context.theme)+ }+ })+}diff --git a/tools/generate/demo/src/document/chapters/lint.ts b/tools/generate/demo/src/document/chapters/lint.tsnew file mode 100644index 000000000..af6c85417--- /dev/null+++ b/tools/generate/demo/src/document/chapters/lint.ts@@ -0,0 +1,60 @@+import { Frame, Text } from '@open-pencil/design-jsx'++import { panelTabs } from '../chrome'+import { layoutChapter, type Chapter, type ChapterContext } from './chapter'++/** Lint: a card with issues planted in it, for the Lint tab to find. */+export function createLintChapter(context: ChapterContext): Promise<Chapter> {+ const { vars } = context.theme+ return layoutChapter(context, {+ index: 7,+ name: 'Lint',+ heading: {+ title: 'It checks itself.',+ subtitle:+ 'Lint reads the document the way a reviewer would: contrast, touch targets, layer names, spacing, colors that bypass the variables. The same rules run from the CLI, so a CI job can fail on them.'+ },+ subject: Frame({+ name: 'Sign-in',+ flex: 'col',+ w: 360,+ h: 'hug',+ p: 24,+ gap: 16,+ rounded: vars.radius,+ bg: vars.surface,+ stroke: vars.line,+ children: [+ Text({ font: 'Inter', size: 20, weight: 600, color: vars.text, children: 'Welcome back' }),+ Text({+ name: 'Faint label',+ font: 'Inter',+ size: 13,+ // Too faint to read in either mode: under 2:1 against the card, where text needs 4.5:1.+ color: vars.faint,+ children: 'Signed in as [email protected]'+ }),+ // A default name and a hard-coded color, both of which the rules notice.+ Frame({+ name: 'Frame 3',+ flex: 'row',+ w: 'fill',+ h: 44,+ justify: 'center',+ items: 'center',+ rounded: vars.cornerRadius,+ bg: '#7C3AED',+ children: [+ Text({ font: 'Inter', size: 14, weight: 600, color: '#FFFFFF', children: 'Continue' })+ ]+ })+ ]+ }),+ tip: {+ step: 7,+ title: 'Open the Lint tab',+ body: 'This card has a label too faint to read and a layer still called Frame 3, on purpose. Lint lists them by severity; click one to select the layer and fix it in the panel.',+ where: panelTabs(context.theme, 'Lint')+ }+ })+}diff --git a/tools/generate/demo/src/document/chapters/modes.ts b/tools/generate/demo/src/document/chapters/modes.tsnew file mode 100644index 000000000..ed4eb647c--- /dev/null+++ b/tools/generate/demo/src/document/chapters/modes.ts@@ -0,0 +1,52 @@+import { Frame, Instance } from '@open-pencil/design-jsx'++import { variablesRow } from '../chrome'+import { layoutChapter, type Chapter, type ChapterContext } from './chapter'+import type { Player } from './slots'++/** Modes: the same player twice, each frame reading the Theme collection in its own mode. */+export async function createModesChapter(+ context: ChapterContext,+ player: Player+): Promise<Chapter> {+ const { graph, theme } = context+ const stage = (name: string) =>+ Frame({+ name,+ flex: 'col',+ w: 'hug',+ h: 'hug',+ p: 40,+ rounded: 32,+ bg: theme.vars.raised,+ children: [Instance({ of: player.id })]+ })+ const chapter = await layoutChapter(context, {+ index: 4,+ name: 'Modes',+ heading: {+ title: 'It has modes.',+ subtitle:+ 'Every color and radius in the player is a variable from one Theme collection. Each frame reads it in its own mode; nothing else differs. The rest of the tour follows the app’s theme the same way.'+ },+ subject: Frame({+ name: 'Modes',+ flex: 'row',+ w: 'hug',+ h: 'hug',+ gap: 40,+ children: [stage('Dark'), stage('Light')]+ }),+ tip: {+ step: 4,+ title: 'Switch the mode',+ body: 'With nothing selected, open the Theme collection from the panel’s Variables section and change a value in one mode: the player in that mode follows, the other stays.',+ where: variablesRow(theme, `${graph.variables.size} / ${graph.variableCollections.size}`)+ }+ })+ // Both stages pin their mode, so they show dark and light whichever theme the app is in.+ const [dark, light] = graph.getChildren(chapter.subject.id)+ graph.updateNode(dark.id, { variableModes: { [theme.collectionId]: theme.modeIds.dark } })+ graph.updateNode(light.id, { variableModes: { [theme.collectionId]: theme.modeIds.light } })+ return chapter+}diff --git a/tools/generate/demo/src/document/chapters/shaders.ts b/tools/generate/demo/src/document/chapters/shaders.tsnew file mode 100644index 000000000..18010f17b--- /dev/null+++ b/tools/generate/demo/src/document/chapters/shaders.ts@@ -0,0 +1,75 @@+import { Frame, Rectangle, Text, shader } from '@open-pencil/design-jsx'+import type { TreeNode } from '@open-pencil/design-jsx'+import type { ShaderPreset } from '@open-pencil/scene-graph'++import { fillRow } from '../chrome'+import { COVER_PRESET } from '../player/card'+import type { Theme } from '../theme'+import { layoutChapter, type Chapter, type ChapterContext } from './chapter'++const TILE = 320++/** Three presets from the `shaders` library, each a fill on an ordinary rectangle. */+const PRESETS: { name: string; preset: ShaderPreset }[] = [+ { name: 'Aurora', preset: COVER_PRESET },+ {+ name: 'Flowing gradient',+ preset: {+ components: [+ {+ type: 'FlowingGradient',+ props: { colorA: '#0F0F13', colorB: '#6D28D9', colorC: '#F472B6', colorD: '#FDE68A' }+ }+ ]+ }+ },+ {+ name: 'Plasma',+ preset: {+ components: [+ { type: 'Plasma', props: { colorA: '#8B5CF6', colorB: '#0F0F13', density: 1.5 } }+ ]+ }+ }+]++function tile({ vars }: Theme, { name, preset }: (typeof PRESETS)[number]): TreeNode {+ return Frame({+ name,+ flex: 'col',+ w: 'hug',+ h: 'hug',+ gap: 14,+ children: [+ Rectangle({ name: 'Shader', w: TILE, h: TILE, rounded: vars.radius, bg: shader(preset) }),+ Text({ font: 'Inter', size: 14, weight: 500, color: vars.muted, children: name })+ ]+ })+}++/** Shaders: a fill that moves, on plain rectangles, with its preset editable in the fill picker. */+export function createShadersChapter(context: ChapterContext): Promise<Chapter> {+ return layoutChapter(context, {+ index: 5,+ name: 'Shaders',+ heading: {+ title: 'Fills can move.',+ subtitle:+ 'A shader is a fill like any other: pick it in the fill picker, stack effects, tune their sliders, or paste a preset from shaders.com. Files keep a still of it, and preview plays it.'+ },+ subject: Frame({+ name: 'Shaders',+ flex: 'row',+ w: 'hug',+ h: 'hug',+ gap: 32,+ children: PRESETS.map((entry) => tile(context.theme, entry))+ }),+ tip: {+ step: 5,+ title: 'Change a shader',+ body: 'Select a square and click its fill in the panel. The Shader tab lists the effects it is made of: drag a slider, add an effect on top, or replace the preset.',+ where: fillRow(context.theme, 'Aurora, Linear …')+ }+ })+}diff --git a/tools/generate/demo/src/document/chapters/slots.ts b/tools/generate/demo/src/document/chapters/slots.tsnew file mode 100644index 000000000..f15eb8e34--- /dev/null+++ b/tools/generate/demo/src/document/chapters/slots.ts@@ -0,0 +1,135 @@+import { Frame, Instance, Text, linearGradient } from '@open-pencil/design-jsx'+import type { TreeNode } from '@open-pencil/design-jsx'+import {+ createComponentPropertyId,+ createSlotProperty,+ updateSlotProperty+} from '@open-pencil/scene-graph'++import { slotRow } from '../chrome'+import { Icon } from '../elements'+import { renderTree } from '../icons'+import { ARTWORK_NAME, PLAYER_PROPERTIES, playerComponent, type PlayerParts } from '../player/card'+import { fillSlot } from '../slot-content'+import type { Theme } from '../theme'+import { layoutChapter, type ChapterContext } from './chapter'++export interface Player {+ /** The Player main component. */+ id: string+ /** Its artwork slot property. */+ slotId: string+}++/** A cover made of a gradient and an icon. */+function iconCover({ vars }: Theme): TreeNode {+ return Frame({+ name: 'Cover',+ flex: 'row',+ w: 'fill',+ h: 'fill',+ justify: 'center',+ items: 'center',+ fills: [+ linearGradient(+ [+ ['#F97316', 0],+ ['#EC4899', 1]+ ],+ { transform: { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 } }+ )+ ],+ children: [Icon({ name: 'lucide:disc-3', size: 160, color: vars.onAccent })]+ })+}++/** A cover made of type. */+function typeCover({ vars }: Theme): TreeNode {+ return Frame({+ name: 'Cover',+ flex: 'col',+ w: 'fill',+ h: 'fill',+ p: 24,+ justify: 'end',+ bg: vars.accent,+ children: [+ Text({+ font: 'Inter',+ size: 96,+ weight: 800,+ lineHeight: 84,+ letterSpacing: -4,+ color: vars.onAccent,+ children: 'LO\nFI'+ })+ ]+ })+}++/**+ * Slots: the Player main component, whose artwork is a slot, and instances that fill the slot+ * with their own layers.+ */+export async function createSlotsChapter(+ context: ChapterContext,+ parts: PlayerParts+): Promise<Player> {+ const { graph, theme } = context+ const player: Player = { id: '', slotId: createComponentPropertyId() }+ await layoutChapter(context, {+ index: 2,+ name: 'Slots',+ heading: {+ title: 'It is a component.',+ subtitle:+ 'The player on the left is the main component. Its artwork is a slot: every instance keeps the player and brings its own cover.'+ },+ subject: Frame({+ name: 'Players',+ flex: 'row',+ w: 'hug',+ h: 'hug',+ gap: 40,+ items: 'start',+ children: [playerComponent(theme, parts)]+ }),+ tip: {+ step: 2,+ title: 'Change a cover',+ body: 'Select the middle player: its Artwork slot reads Modified. Drop any layer into the slot, or use the slot’s menu to reset it to the component’s cover.',+ where: slotRow(theme)+ },+ async fill(row) {+ const [component] = graph.getChildren(row.id)+ player.id = component.id+ const artwork = graph.getChildren(component.id).find((child) => child.name === ARTWORK_NAME)+ if (!artwork || !createSlotProperty(graph, artwork.id, player.slotId)) {+ throw new Error('The player has no artwork frame to make a slot of')+ }+ updateSlotProperty(graph, component.id, player.slotId, {+ description: 'The cover. Any layer goes here; the player keeps everything else.',+ slotSettings: { minChildren: 1, maxChildren: 1, stretchChildOnInsert: true }+ })+ const covers: { title: string; artist: string; cover: TreeNode }[] = [+ { title: 'Side B', artist: 'The Tapes', cover: iconCover(theme) },+ { title: 'Lo-fi Hours', artist: 'Various', cover: typeCover(theme) }+ ]+ for (const { title, artist, cover } of covers) {+ const instance = await renderTree(+ graph,+ Instance({+ of: component.id,+ properties: {+ [PLAYER_PROPERTIES.title.id]: title,+ [PLAYER_PROPERTIES.artist.id]: artist+ }+ }),+ { parentId: row.id }+ )+ await fillSlot(graph, instance.id, player.slotId, cover)+ }+ }+ })+ return player+}diff --git a/tools/generate/demo/src/document/chapters/yours.ts b/tools/generate/demo/src/document/chapters/yours.tsnew file mode 100644index 000000000..f4d3c1f6e--- /dev/null+++ b/tools/generate/demo/src/document/chapters/yours.ts@@ -0,0 +1,122 @@+import { Frame, Text } from '@open-pencil/design-jsx'+import type { TreeNode } from '@open-pencil/design-jsx'++import { menuBar } from '../chrome'+import { Icon, type IconProps } from '../elements'+import type { Theme } from '../theme'+import {+ CHAPTER_PADDING,+ fitSection,+ layoutChapter,+ type Chapter,+ type ChapterContext+} from './chapter'++const TIP_COMPONENT_GAP = 96++const WAYS: { icon: IconProps['name']; title: string; body: string }[] = [+ {+ icon: 'lucide:users',+ title: 'Share it',+ body: 'Press Share at the top right. The link opens this document in another browser with live cursors, selection, and a voice call. No account and no server in between.'+ },+ {+ icon: 'lucide:folder-open',+ title: 'Open your own',+ body: 'Drop a .fig onto the canvas, paste layers copied in Figma, or paste HTML and CSS. All of it becomes editable layers.'+ },+ {+ icon: 'lucide:sparkles',+ title: 'Ask the AI',+ body: 'The AI tab builds and edits with the same tools this tour used. Bring a key from any provider; it stays on your machine.'+ },+ {+ icon: 'lucide:terminal',+ title: 'Script it',+ body: 'npx @open-pencil/cli inspects, lints, exports, and edits documents from a terminal, a CI job, or an agent. The MCP server gives agents the same tools.'+ }+]++function way({ vars }: Theme, { icon, title, body }: (typeof WAYS)[number]): TreeNode {+ return Frame({+ name: title,+ flex: 'row',+ w: 'fill',+ h: 'hug',+ gap: 20,+ items: 'start',+ children: [+ Frame({+ name: 'Icon',+ flex: 'row',+ w: 44,+ h: 44,+ rounded: vars.cornerRadius,+ justify: 'center',+ items: 'center',+ bg: vars.raised,+ children: [Icon({ name: icon, size: 22, color: vars.accent })]+ }),+ Frame({+ name: 'Text',+ flex: 'col',+ w: 'fill',+ h: 'hug',+ gap: 6,+ children: [+ Text({ font: 'Inter', size: 17, weight: 600, color: vars.text, children: title }),+ Text({+ font: 'Inter',+ size: 14,+ lineHeight: 22,+ w: 'fill',+ color: vars.muted,+ children: body+ })+ ]+ })+ ]+ })+}++/** Yours: what to do once the tour is over, and the Tip component itself. */+export async function createYoursChapter(context: ChapterContext): Promise<Chapter> {+ const { graph, theme } = context+ const chapter = await layoutChapter(context, {+ index: 8,+ name: 'Yours',+ heading: {+ title: 'Now make it yours.',+ subtitle:+ 'The tour ends here. The document does not: everything in it is yours to edit, and it works with what you already have.'+ },+ subject: Frame({+ name: 'Ways',+ flex: 'col',+ w: 640,+ h: 'hug',+ gap: 32,+ p: 32,+ rounded: theme.vars.radius,+ bg: theme.vars.surface,+ stroke: theme.vars.line,+ children: WAYS.map((entry) => way(theme, entry))+ }),+ tip: {+ step: 8,+ title: 'Keep it',+ body: 'File → Save writes a .fig you can open here again, or in Figma. The card you are reading is a component as well: its main component sits under the list.',+ keys: '⌘ S',+ where: menuBar(theme, 'File')+ }+ })+ // The Tip component every chapter's card comes from closes the tour, under the list.+ const { section, subject } = chapter+ graph.reparentNode(context.tipId, section.id)+ graph.updateNode(context.tipId, {+ x: CHAPTER_PADDING,+ y: subject.y + subject.height + TIP_COMPONENT_GAP+ })+ fitSection(context, section.id)+ return chapter+}diff --git a/tools/generate/demo/src/document/chrome.tsx b/tools/generate/demo/src/document/chrome.tsxnew file mode 100644index 000000000..e5698501b--- /dev/null+++ b/tools/generate/demo/src/document/chrome.tsx@@ -0,0 +1,296 @@+/** @jsxImportSource @open-pencil/design-jsx */+/**+ * Pieces of OpenPencil's own chrome, drawn at the app's sizes in its colors, so a tip can show+ * where to click rather than describe it. A ring in the tour's accent marks the target. Colors+ * come from the App chrome collection, which follows the app's dark or light theme; sizes were+ * measured from 2× screenshots of the header, menu bar, and panel.+ */+import {+ Frame,+ Text,+ type BaseProps,+ type DesignVariable,+ type TreeNode+} from '@open-pencil/design-jsx'++import { Icon, type IconProps } from './elements'+import type { Theme } from './theme'++const FONT = 'Inter'++function label(children: string, color: DesignVariable, weight = 500): TreeNode {+ return (+ <Text font={FONT} size={13} weight={weight} color={color}>+ {children}+ </Text>+ )+}++function icon(name: IconProps['name'], color: DesignVariable, size = 16): TreeNode {+ return <Icon name={name} size={size} color={color} />+}++function spacer(): TreeNode {+ return <Frame name="Spacer" w="fill" h={1} />+}++/** The ring that marks what to click, drawn around `children`. */+function target(theme: Theme, children: TreeNode[], props: BaseProps = {}): TreeNode {+ return (+ <Frame+ name="Target"+ flex="row"+ w="hug"+ h="hug"+ items="center"+ p={3}+ rounded={10}+ stroke={theme.vars.accent}+ strokeWidth={2}+ {...props}+ >+ {children}+ </Frame>+ )+}++/**+ * A fragment's own panel, the color of the chrome it is cut from, edged so it stands apart from+ * the card it sits on in either theme.+ */+function panel(+ theme: Theme,+ name: string,+ bg: DesignVariable,+ children: TreeNode[],+ props: BaseProps = {}+): TreeNode {+ return (+ <Frame+ name={name}+ flex="row"+ w="hug"+ h="hug"+ items="center"+ gap={8}+ p={10}+ rounded={10}+ bg={bg}+ stroke={theme.chrome.border}+ {...props}+ >+ {children}+ </Frame>+ )+}++/** The top right of the window: Share, and the preview button next to it. */+export function previewButton(theme: Theme): TreeNode {+ const c = theme.chrome+ return panel(theme, 'Header', c.header, [+ <Frame name="Share" flex="row" h={30} px={12} gap={6} items="center" rounded={6} bg={c.blue}>+ {icon('lucide:share-2', c.onBlue, 14)}+ {label('Share', c.onBlue, 600)}+ </Frame>,+ target(theme, [+ <Frame name="Preview" flex="row" w={30} h={30} justify="center" items="center" rounded={6}>+ {icon('lucide:play', c.text)}+ </Frame>+ ])+ ])+}++/** The pill that replaces the header while previewing. */+export function previewPill(theme: Theme): TreeNode {+ const c = theme.chrome+ return panel(theme, 'Preview pill', c.panel, [+ label('Demo', c.text, 600),+ target(theme, [+ <Frame+ name="Previewing"+ flex="row"+ h={28}+ px={10}+ gap={6}+ items="center"+ rounded={6}+ bg={c.previewChip}+ >+ {icon('lucide:play', c.previewText, 14)}+ {label('Previewing', c.previewText, 600)}+ </Frame>+ ]),+ <Frame name="Reset" flex="row" h={28} px={10} gap={6} items="center" rounded={6} bg={c.field}>+ {icon('lucide:rotate-ccw', c.text, 14)}+ {label('Reset', c.text, 600)}+ </Frame>,+ icon('lucide:x', c.muted)+ ])+}++const TABS = [+ ['Design', null],+ ['Code', 'lucide:code'],+ ['AI', 'lucide:sparkles'],+ ['Lint', 'lucide:list-checks']+] as const++/** The panel's tab strip, with `active` lit. */+export function panelTabs(theme: Theme, active: (typeof TABS)[number][0]): TreeNode {+ const c = theme.chrome+ const tab = (name: string, iconName: IconProps['name'] | null) => {+ const lit = name === active+ const color = lit ? c.text : c.muted+ const content = (+ <Frame name={name} flex="col" h="hug" gap={6} items="center">+ <Frame name="Label" flex="row" gap={6} items="center">+ {iconName ? icon(iconName, color, 14) : null}+ {label(name, color, 600)}+ </Frame>+ <Frame name="Underline" w="fill" h={2} rounded={1} bg={lit ? c.blue : c.panel} />+ </Frame>+ )+ return lit ? target(theme, [content], { p: 4 }) : content+ }+ return panel(+ theme,+ 'Tabs',+ c.panel,+ TABS.map(([name, iconName]) => tab(name, iconName)),+ { gap: 14, px: 12 }+ )+}++/** The slot row of an instance's component properties. */+export function slotRow(theme: Theme): TreeNode {+ const c = theme.chrome+ return panel(+ theme,+ 'Slot row',+ c.panel,+ [+ <Frame name="Rows" flex="col" w="hug" h="hug" gap={8}>+ {label('Component properties', c.component, 600)}+ <Frame name="Artwork" flex="col" w="fill" h="hug" gap={6}>+ {label('Artwork', c.muted)}+ {target(+ theme,+ [+ <Frame+ name="State"+ flex="row"+ w={214}+ h={32}+ px={10}+ gap={10}+ items="center"+ rounded={6}+ bg={c.field}+ >+ <Frame+ name="Slot"+ w={14}+ h={14}+ rounded={3}+ stroke={c.slot}+ strokeWidth={1.5}+ strokeDash={[2, 2]}+ />+ {label('Modified', c.text)}+ {spacer()}+ {label('1 item', c.muted)}+ </Frame>,+ icon('lucide:plus', c.text),+ icon('lucide:ellipsis', c.text)+ ],+ { gap: 8, px: 6 }+ )}+ </Frame>+ </Frame>+ ],+ { p: 12 }+ )+}++/** A fill row of the Fill section, naming the paint it shows. */+export function fillRow(theme: Theme, paint: string): TreeNode {+ const c = theme.chrome+ return panel(+ theme,+ 'Fill row',+ c.panel,+ [+ <Frame name="Rows" flex="col" w="hug" h="hug" gap={8}>+ <Frame name="Heading" flex="row" w="fill" items="center">+ {label('Fill', c.text, 700)}+ {spacer()}+ {icon('lucide:plus', c.text)}+ </Frame>+ <Frame name="Row" flex="row" gap={10} items="center">+ {target(theme, [+ <Frame+ name="Paint"+ flex="row"+ h={32}+ px={8}+ gap={8}+ items="center"+ rounded={6}+ bg={c.field}+ >+ <Frame name="Swatch" w={16} h={16} rounded={3} bg={c.checker} />+ {label(paint, c.text)}+ <Frame name="Divider" w={1} h={16} bg={c.border} />+ {label('100 %', c.text)}+ </Frame>+ ])}+ {icon('lucide:eye', c.text)}+ {icon('lucide:minus', c.text)}+ </Frame>+ </Frame>+ ],+ { p: 12 }+ )+}++/**+ * The Variables section of the page panel, whose button opens the collections; `count` is what+ * the section shows, variables over collections.+ */+export function variablesRow(theme: Theme, count: string): TreeNode {+ const c = theme.chrome+ return panel(+ theme,+ 'Variables row',+ c.panel,+ [+ <Frame name="Rows" flex="col" w={240} h="hug" gap={10}>+ <Frame name="Heading" flex="row" w="fill" items="center">+ {label('Variables', c.text, 700)}+ {spacer()}+ {target(theme, [icon('lucide:square-arrow-out-up-right', c.text)])}+ </Frame>+ {label(count, c.muted)}+ </Frame>+ ],+ { p: 12 }+ )+}++const MENUS = ['File', 'Edit', 'View', 'Object', 'Text'] as const++/** The menu bar, with `active` marked. */+export function menuBar(theme: Theme, active: (typeof MENUS)[number]): TreeNode {+ const c = theme.chrome+ return panel(+ theme,+ 'Menu bar',+ c.panel,+ MENUS.map((name) =>+ name === active+ ? target(theme, [label(name, c.text)], { px: 6, py: 2 })+ : label(name, c.muted)+ ),+ { gap: 16, px: 14 }+ )+}diff --git a/tools/generate/demo/src/document/colors.ts b/tools/generate/demo/src/document/colors.tsdeleted file mode 100644index d8654a765..000000000--- a/tools/generate/demo/src/document/colors.ts+++ /dev/null@@ -1,37 +0,0 @@-import { BLACK } from '@open-pencil/core/constants'-import type { Color, Fill, GradientStop, Stroke } from '@open-pencil/scene-graph'--export const DEMO_COLORS = {- white: { r: 1, g: 1, b: 1, a: 1 },- black: BLACK,- gray50: { r: 0.98, g: 0.98, b: 0.98, a: 1 },- gray100: { r: 0.96, g: 0.96, b: 0.97, a: 1 },- gray200: { r: 0.9, g: 0.9, b: 0.92, a: 1 },- gray500: { r: 0.55, g: 0.55, b: 0.58, a: 1 },- blue: { r: 0.23, g: 0.51, b: 0.96, a: 1 },- indigo: { r: 0.38, g: 0.35, b: 0.95, a: 1 },- purple: { r: 0.59, g: 0.28, b: 0.96, a: 1 },- green: { r: 0.13, g: 0.77, b: 0.42, a: 1 },- orange: { r: 0.96, g: 0.52, b: 0.13, a: 1 },- red: { r: 0.91, g: 0.22, b: 0.22, a: 1 },- teal: { r: 0.08, g: 0.73, b: 0.73, a: 1 }-} satisfies Record<string, Color>--export function solid(color: Color, opacity = 1): Fill {- return { type: 'SOLID', color, opacity, visible: true }-}--export function gradient(stops: GradientStop[]): Fill {- return {- type: 'GRADIENT_LINEAR',- color: stops[0].color,- opacity: 1,- visible: true,- gradientStops: stops,- gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }- }-}--export function thinStroke(color: Color): Stroke[] {- return [{ type: 'SOLID', color, weight: 1, opacity: 1, visible: true, align: 'INSIDE' as const }]-}diff --git a/tools/generate/demo/src/document/controls/components.tsx b/tools/generate/demo/src/document/controls/components.tsxdeleted file mode 100644index 15f9f26a3..000000000--- a/tools/generate/demo/src/document/controls/components.tsx+++ /dev/null@@ -1,143 +0,0 @@-/** @jsxImportSource @open-pencil/design-jsx */-/**- * The demo's controls, written with Reka UI's element names: each is a main component (or set)- * with a behaviour, ready to place and to run in preview.- */-import {- Button,- Checkbox,- Component,- Slider,- Switch,- Tabs,- Text,- TextField,- type BaseProps,- type TreeNode-} from '@open-pencil/design-jsx'--export const CONTROL_COLORS = {- ink: '#172554',- muted: '#536487',- accent: '#4F46E5',- accentHover: '#4338CA',- accentPressed: '#3730A3',- line: '#CBD5E1',- tile: '#EEF2FF',- surface: '#FFFFFF',- disabled: '#E2E8F0'-}--const { ink, muted, accent, accentHover, accentPressed, line, tile, surface, disabled } =- CONTROL_COLORS--function buttonVariant(state: string, look: BaseProps, color = surface): TreeNode {- return (- <Component name={`Interaction=${state}`} flex="row" px={16} py={8} rounded={8} {...look}>- <Text font="Inter" size={13} weight={600} color={color}>- Save- </Text>- </Component>- )-}--/** A button whose variants draw its interaction states. */-export const BUTTON = (- <Button.Root name="Button" states="Interaction" flex="row" gap={12} p={16}>- {buttonVariant('Default', { bg: accent })}- {buttonVariant('Hover', { bg: accentHover })}- {buttonVariant('Pressed', { bg: accentPressed })}- {buttonVariant('Focus', { bg: accent, stroke: ink, strokeWidth: 2 })}- {buttonVariant('Disabled', { bg: disabled }, muted)}- </Button.Root>-)--export const SWITCH = (- <Switch.Root name="Switch" modelValue="State" flex="row" gap={16} p={16}>- <Component name="State=Off" w={40} h={22} rounded={11} bg={line}>- <Switch.Thumb x={2} y={2} w={18} h={18} rounded={9} bg={surface} />- </Component>- <Component name="State=On" w={40} h={22} rounded={11} bg={accent}>- <Switch.Thumb x={20} y={2} w={18} h={18} rounded={9} bg={surface} />- </Component>- </Switch.Root>-)--export const CHECKBOX = (- <Checkbox.Root name="Checkbox" modelValue="Checked" flex="row" gap={16} p={16}>- <Component- name="Checked=Off"- w={18}- h={18}- rounded={4}- bg={surface}- stroke={line}- strokeWidth={1.5}- />- <Component name="Checked=On" w={18} h={18} rounded={4} bg={accent}>- <Checkbox.Indicator x={5} y={5} w={8} h={8} rounded={2} bg={surface} />- </Component>- </Checkbox.Root>-)--export const SLIDER = (- <Slider.Root name="Slider" w={220} h={20} min={0} max={100} step={1} defaultValue={60}>- <Slider.Track x={0} y={8} w={220} h={4} rounded={2} bg={tile} />- <Slider.Range x={0} y={8} w={132} h={4} rounded={2} bg={accent} />- <Slider.Thumb- x={122}- y={0}- w={20}- h={20}- rounded={10}- bg={surface}- stroke={accent}- strokeWidth={2}- />- </Slider.Root>-)--export const TEXT_FIELD = (- <TextField.Root- name="Text field"- w={260}- h={36}- rounded={8}- bg={surface}- stroke={line}- flex="row"- items="center"- px={12}- >- <TextField.Input font="Inter" size={13} color={ink}>- </TextField.Input>- </TextField.Root>-)--const TABS_CONTENT = [- ['Profile', 'Your name and photo, as teammates see them.'],- ['Notifications', 'Choose what reaches your inbox.'],- ['Billing', 'Plan, invoices, and payment method.']-] as const--export const TABS = (- <Tabs.Root name="Tabs" w={300} flex="col" gap={12}>- <Tabs.List flex="row" gap={4} p={4} rounded={8} bg={tile}>- {TABS_CONTENT.map(([title]) => (- <Tabs.Trigger px={12} py={6} rounded={6}>- <Text font="Inter" size={12} weight={600} color={ink}>- {title}- </Text>- </Tabs.Trigger>- ))}- </Tabs.List>- {TABS_CONTENT.map(([, panel]) => (- <Tabs.Content w={300} flex="col">- <Text font="Inter" size={13} color={muted} w="fill">- {panel}- </Text>- </Tabs.Content>- ))}- </Tabs.Root>-)diff --git a/tools/generate/demo/src/document/controls/section.ts b/tools/generate/demo/src/document/controls/section.tsdeleted file mode 100644index fc96d2aee..000000000--- a/tools/generate/demo/src/document/controls/section.ts+++ /dev/null@@ -1,138 +0,0 @@-import { renderTree } from '@open-pencil/core/design-jsx'-import { Frame, Instance, Text } from '@open-pencil/design-jsx'-import type { TreeNode } from '@open-pencil/design-jsx'-import type { SceneGraph } from '@open-pencil/scene-graph'--import { BUTTON, CHECKBOX, CONTROL_COLORS, SLIDER, SWITCH, TABS, TEXT_FIELD } from './components'--const { ink, muted, line, surface, tile } = CONTROL_COLORS-const ORIGIN = 60-const GAP = 48--const text = (size: number, color: string, children: string, extra: object = {}) =>- Text({ font: 'Inter', size, color, children, ...extra })--/** A labelled row of the settings card: what the control sets, then the control. */-function settingRow(title: string, caption: string, control: TreeNode): TreeNode {- return Frame({- name: title,- flex: 'row',- w: 'fill',- h: 'hug',- gap: 24,- items: 'center',- children: [- Frame({- name: 'Label',- flex: 'col',- w: 'fill',- h: 'hug',- gap: 2,- children: [text(13, ink, title, { weight: 600 }), text(12, muted, caption, { w: 'fill' })]- }),- control- ]- })-}--/** Renders one control onto the board and returns its main component or set. */-async function renderControl(graph: SceneGraph, boardId: string, control: TreeNode) {- const result = await renderTree(graph, control, { parentId: boardId })- const node = graph.getNode(result.id)- if (!node) throw new Error('The control did not render')- return node-}--/** The variant of a set named `name`, or the component itself when it is not a set. */-function variant(graph: SceneGraph, id: string, name: string): string {- return graph.getChildren(id).find((child) => child.name === name)?.id ?? id-}--/**- * The Controls page: main components that behave as Reka UI controls, and a settings card- * built from their instances, which preview runs as live components.- */-export async function createControlsSection(graph: SceneGraph, pageId: string) {- const header = await renderTree(- graph,- Frame({- name: 'About this page',- flex: 'col',- w: 1056,- h: 'hug',- gap: 8,- children: [- text(20, ink, 'Components that work.', { weight: 600 }),- text(- 13,- muted,- 'Each main component has a behaviour from the Behaviour section: a switch, a slider, tabs, a text field. Press ⌥⌘↩ (View › Preview) and the card on the right runs as real Reka UI components; nothing you do there changes the document.',- { w: 'fill', lineHeight: 20 }- )- ]- }),- { parentId: pageId }- )- graph.updateNode(header.id, { x: ORIGIN, y: ORIGIN })-- const board = await renderTree(- graph,- Frame({- name: 'Components',- flex: 'col',- w: 480,- h: 'hug',- gap: 24,- p: 32,- rounded: 16,- bg: tile,- children: [text(12, muted, 'MAIN COMPONENTS', { weight: 600 })]- }),- { parentId: pageId }- )- const top = ORIGIN + (graph.getNode(header.id)?.height ?? 0) + GAP- graph.updateNode(board.id, { x: ORIGIN, y: top })-- const button = await renderControl(graph, board.id, BUTTON)- const toggle = await renderControl(graph, board.id, SWITCH)- const checkbox = await renderControl(graph, board.id, CHECKBOX)- const slider = await renderControl(graph, board.id, SLIDER)- const field = await renderControl(graph, board.id, TEXT_FIELD)- const tabs = await renderControl(graph, board.id, TABS)-- const card = await renderTree(- graph,- Frame({- name: 'Account settings',- flex: 'col',- w: 520,- h: 'hug',- gap: 24,- p: 32,- rounded: 16,- bg: surface,- stroke: line,- children: [- text(18, ink, 'Account settings', { weight: 600 }),- Instance({ of: tabs.id }),- settingRow(- 'Email alerts',- 'Hear about mentions and replies.',- Instance({ of: variant(graph, toggle.id, 'State=On') })- ),- settingRow(- 'Weekly digest',- 'A Monday summary of your projects.',- Instance({ of: variant(graph, checkbox.id, 'Checked=Off') })- ),- settingRow('Volume', 'Notification sounds.', Instance({ of: slider.id })),- settingRow('Email', 'Where alerts go.', Instance({ of: field.id })),- Instance({ of: variant(graph, button.id, 'Interaction=Default') })- ]- }),- { parentId: pageId }- )- graph.updateNode(card.id, { x: ORIGIN + 480 + GAP, y: top })-- return { rootIds: [header.id, board.id, card.id] }-}diff --git a/tools/generate/demo/src/document/effects.ts b/tools/generate/demo/src/document/effects.tsdeleted file mode 100644index 759a20db4..000000000--- a/tools/generate/demo/src/document/effects.ts+++ /dev/null@@ -1,47 +0,0 @@-import { TRANSPARENT } from '@open-pencil/core/constants'-import type { Color, Effect } from '@open-pencil/scene-graph'--export function dropShadow(- ox = 0,- oy = 4,- radius = 8,- spread = 0,- color: Color = { r: 0, g: 0, b: 0, a: 0.25 }-): Effect {- return {- type: 'DROP_SHADOW',- color,- offset: { x: ox, y: oy },- radius,- spread,- visible: true- }-}--export function innerShadow(- ox = 0,- oy = 2,- radius = 4,- spread = 0,- color: Color = { r: 0, g: 0, b: 0, a: 0.2 }-): Effect {- return {- type: 'INNER_SHADOW',- color,- offset: { x: ox, y: oy },- radius,- spread,- visible: true- }-}--export function blurEffect(type: Effect['type'], radius: number): Effect {- return {- type,- color: TRANSPARENT,- offset: { x: 0, y: 0 },- radius,- spread: 0,- visible: true- }-}diff --git a/tools/generate/demo/src/document/elements.ts b/tools/generate/demo/src/document/elements.tsnew file mode 100644index 000000000..ca5ce6e16--- /dev/null+++ b/tools/generate/demo/src/document/elements.ts@@ -0,0 +1,24 @@+import { node, type DesignVariable, type TreeNode } from '@open-pencil/design-jsx'++export interface IconProps {+ /** An Iconify name the demo bundles, such as `lucide:play`. */+ name: `lucide:${string}`+ size: number+ /** The variable the icon's paths are bound to, so the icon follows the tour's modes. */+ color: DesignVariable+ label?: string+}++/** The variable each icon element binds its paths to, read when the icon is rendered. */+export const iconColors = new WeakMap<TreeNode, DesignVariable>()++/**+ * An icon layer, as `<Icon>` in a design JSX string renders one, drawn in the variable's+ * value and bound to it once rendered (`renderTree` in `./icons`).+ */+export function Icon({ color, ...props }: IconProps): TreeNode {+ const value = typeof color.value === 'string' ? color.value : '#000000'+ const tree = node('icon', { ...props, color: value })+ iconColors.set(tree, color)+ return tree+}diff --git a/tools/generate/demo/src/document/icons.ts b/tools/generate/demo/src/document/icons.tsnew file mode 100644index 000000000..29f484197--- /dev/null+++ b/tools/generate/demo/src/document/icons.ts@@ -0,0 +1,87 @@+import { icons as lucide } from '@iconify-json/lucide'++import { designJSXRenderer } from '@open-pencil/core/design-jsx'+import { createIconifyProvider } from '@open-pencil/core/icons'+import type { RenderOptions, TreeNode } from '@open-pencil/design-jsx'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import { iconColors } from './elements'++type IconifyClient = NonNullable<Parameters<typeof createIconifyProvider>[0]>++const names = Object.keys(lucide.icons)++/** Lucide from the bundled icon JSON, so the demo builds without the Iconify API. */+const client: IconifyClient = {+ async fetchCollection(prefix, iconNames) {+ if (prefix !== lucide.prefix) throw new Error(`The demo bundles no "${prefix}" icons`)+ return {+ prefix,+ width: lucide.width,+ height: lucide.height,+ icons: Object.fromEntries(+ iconNames.flatMap((name) => {+ const icon = lucide.icons[name]+ return icon ? [[name, icon]] : []+ })+ )+ }+ },+ async search(query, options) {+ const needle = query.trim().toLowerCase()+ const found = names+ .filter((name) => name.includes(needle))+ .map((name) => `${lucide.prefix}:${name}`)+ return { icons: found.slice(0, options?.limit ?? 64), total: found.length }+ },+ async collections() {+ return [+ {+ prefix: lucide.prefix,+ name: 'Lucide',+ total: names.length,+ category: 'General',+ license: 'ISC',+ multicolor: false+ }+ ]+ },+ async collectionIcons(prefix) {+ return prefix === lucide.prefix ? names.map((name) => `${prefix}:${name}`) : []+ }+}++const renderer = designJSXRenderer(createIconifyProvider(client))++/** Bind every solid paint of an icon's paths to `variableId`. */+function bindIcon(graph: SceneGraph, icon: SceneNode, variableId: string): void {+ const visit = (node: SceneNode): void => {+ for (const field of ['fills', 'strokes'] as const) {+ node[field].forEach((paint, index) => {+ if (paint.type === 'SOLID')+ graph.bindVariable(node.id, `${field}/${index}/color`, variableId)+ })+ }+ for (const child of graph.getChildren(node.id)) visit(child)+ }+ visit(icon)+}++/**+ * Design JSX rendering with the bundled icons. Icons from `Icon` in `./elements` are bound to+ * their color variable once drawn, so they follow the tour's modes like everything else.+ */+export function renderTree(+ graph: SceneGraph,+ tree: TreeNode,+ options: RenderOptions = {}+): ReturnType<typeof renderer.renderTree> {+ return renderer.renderTree(graph, tree, {+ ...options,+ onNode(element, node) {+ options.onNode?.(element, node)+ const variableId = iconColors.get(element)?.id+ if (variableId && graph.variables.has(variableId)) bindIcon(graph, node, variableId)+ }+ })+}diff --git a/tools/generate/demo/src/document/paint/samples.ts b/tools/generate/demo/src/document/paint/samples.tsdeleted file mode 100644index eaf15e0e2..000000000--- a/tools/generate/demo/src/document/paint/samples.ts+++ /dev/null@@ -1,213 +0,0 @@-import {- Ellipse,- Frame,- Rectangle,- Text,- backgroundBlur,- dropShadow,- innerShadow,- layerBlur,- linearGradient,- radialGradient,- solid-} from '@open-pencil/design-jsx'-import type { TreeNode } from '@open-pencil/design-jsx'--export interface PaintExample {- title: string- caption: string- artwork: TreeNode-}--export interface PaintGroup {- title: string- examples: PaintExample[]-}--/** Only specimen artwork has fixed geometry; labels and section placement use layout. */-export function createPaintGroups(): PaintGroup[] {- const tile = { w: 72, h: 72, rounded: 16, bg: '#4F46E5' }- const pair = (children: TreeNode[]) =>- Frame({ flex: 'row', w: 232, h: 104, gap: 32, justify: 'center', items: 'center', children })- const stops = [- ['#4F46E5', 0],- ['#38BDF8', 1]- ] as const- const gradientStops = [...stops]- return [- {- title: '01 / PAINT · THE SAME PALETTE, DIFFERENT FILLS',- examples: [- {- title: 'Linear gradient',- caption: 'Indigo to sky, across a flat surface.',- artwork: Rectangle({- w: 232,- h: 104,- rounded: 12,- fills: [linearGradient(gradientStops)]- })- },- {- title: 'Radial gradient',- caption: 'The same stops, radiating from the center.',- artwork: Rectangle({- w: 232,- h: 104,- rounded: 12,- fills: [radialGradient(gradientStops)]- })- },- {- title: 'Layered fills',- caption: 'A warm Overlay fill above the gradient.',- artwork: Rectangle({- w: 232,- h: 104,- rounded: 12,- fills: [- linearGradient(gradientStops),- solid('#FBBF24', { blendMode: 'OVERLAY', opacity: 0.65 })- ]- })- }- ]- },- {- title: '02 / DEPTH · UNCHANGED GEOMETRY, DIFFERENT SHADOWS',- examples: [- {- title: 'Drop shadow',- caption: 'Flat on the left; an outer shadow on the right.',- artwork: pair([- Rectangle(tile),- Rectangle({ ...tile, effects: [dropShadow({ y: 6, radius: 10, color: '#17255440' })] })- ])- },- {- title: 'Inner shadow',- caption: 'The shadow stays inside the second shape.',- artwork: pair([- Rectangle(tile),- Rectangle({ ...tile, effects: [innerShadow({ y: 5, radius: 10, color: '#172554AA' })] })- ])- },- {- title: 'Combined depth',- caption: 'Outer and inner shadows on the same shape.',- artwork: pair([- Rectangle(tile),- Rectangle({- ...tile,- effects: [- dropShadow({ y: 6, radius: 10, color: '#17255440' }),- innerShadow({ y: 3, radius: 6, color: '#FFFFFF77' })- ]- })- ])- }- ]- },- {- title: '03 / BLUR · KNOW WHAT IS BEING SOFTENED',- examples: [- {- title: 'Layer blur',- caption: 'Only the right-hand shape is blurred.',- artwork: pair([Rectangle(tile), Rectangle({ ...tile, effects: [layerBlur(6)] })])- },- {- title: 'Background blur',- caption: 'A translucent pane softens the stripes behind it.',- artwork: Frame({- w: 232,- h: 104,- overflow: 'hidden',- rounded: 12,- children: [- ...['#4F46E5', '#38BDF8', '#4F46E5', '#38BDF8'].map((bg, index) =>- Rectangle({ x: index * 58, y: 0, w: 58, h: 104, bg })- ),- Rectangle({- name: 'Frosted pane',- x: 40,- y: 16,- w: 152,- h: 72,- rounded: 10,- bg: '#FFFFFF55',- effects: [backgroundBlur(10)]- })- ]- })- },- {- title: 'Text shadow',- caption: 'An effect on live glyphs, not a raster image.',- artwork: Frame({- flex: 'col',- w: 232,- h: 104,- justify: 'center',- children: Text({- font: 'Inter',- size: 32,- weight: 600,- color: '#4F46E5',- children: 'Still editable',- effects: [dropShadow({ y: 4, radius: 5, color: '#17255466' })]- })- })- }- ]- },- {- title: '04 / COMPOSITION · BLENDING, MASKING, AND CORNERS',- examples: [- {- title: 'Multiply + Screen',- caption: 'Overlapping layers retain their blend modes.',- artwork: Frame({- w: 232,- h: 104,- children: [- Ellipse({ x: 24, y: 12, w: 80, h: 80, bg: '#3B82F6', blendMode: 'MULTIPLY' }),- Ellipse({ x: 76, y: 12, w: 80, h: 80, bg: '#F43F5E', blendMode: 'MULTIPLY' }),- Ellipse({ x: 128, y: 12, w: 80, h: 80, bg: '#FBBF24', blendMode: 'SCREEN' })- ]- })- },- {- title: 'Alpha mask',- caption: 'The ellipse masks the following stripe layers.',- artwork: Frame({- w: 232,- h: 104,- children: [- Ellipse({- name: 'Editable mask',- x: 64,- y: 4,- w: 104,- h: 96,- bg: '#FFFFFF',- mask: 'alpha'- }),- ...['#4F46E5', '#38BDF8', '#FBBF24'].map((bg, index) =>- Rectangle({ x: 44, y: 4 + index * 32, w: 144, h: 32, bg })- )- ]- })- },- {- title: 'Independent corners',- caption: 'Equal corners versus alternating corner radii.',- artwork: pair([- Rectangle(tile),- Rectangle({ ...tile, roundedTL: 28, roundedTR: 4, roundedBR: 28, roundedBL: 4 })- ])- }- ]- }- ]-}diff --git a/tools/generate/demo/src/document/paint/section.ts b/tools/generate/demo/src/document/paint/section.tsdeleted file mode 100644index bebdd5348..000000000--- a/tools/generate/demo/src/document/paint/section.ts+++ /dev/null@@ -1,62 +0,0 @@-import { renderTree } from '@open-pencil/core/design-jsx'-import { Frame, Text } from '@open-pencil/design-jsx'-import type { SceneGraph } from '@open-pencil/scene-graph'--import { createArtworkTile, createExampleColumn } from '../sections/example'-import { createPaintGroups } from './samples'--export function createPaintSection(graph: SceneGraph, parentId: string) {- const text = { font: 'Inter', color: '#172554' }- const label = { ...text, size: 12, color: '#536487' }- return renderTree(- graph,- Frame({- name: 'Paint and effects',- flex: 'col',- w: 1056,- h: 'hug',- p: 32,- gap: 32,- bg: '#FFFFFF',- children: [- Text({ ...text, size: 20, weight: 600, children: 'Same shapes. Different possibilities.' }),- ...createPaintGroups().map((group) =>- Frame({- name: group.title,- flex: 'col',- w: 'fill',- h: 'hug',- gap: 16,- children: [- Text({ ...label, children: group.title }),- Frame({- name: 'Editable comparisons',- flex: 'row',- w: 'fill',- h: 'hug',- gap: 24,- children: group.examples.map((example) =>- createExampleColumn({- title: example.title,- caption: example.caption,- artwork: createArtworkTile(`${example.title} / artwork`, {- children: [example.artwork]- })- })- )- })- ]- })- ),- Text({- ...label,- w: 'fill',- lineHeight: 18,- children:- 'Select the actual shape or text layer to inspect its fills and effects. Every example stays editable.'- })- ]- }),- { parentId }- )-}diff --git a/tools/generate/demo/src/document/player/card.tsx b/tools/generate/demo/src/document/player/card.tsxnew file mode 100644index 000000000..1c0b52a0f--- /dev/null+++ b/tools/generate/demo/src/document/player/card.tsx@@ -0,0 +1,128 @@+/** @jsxImportSource @open-pencil/design-jsx */+/**+ * The player card: the one object the tour keeps coming back to. A main component with text+ * properties for the track, a slot for the artwork, and the controls as nested instances.+ */+import {+ Component,+ Frame,+ Instance,+ Rectangle,+ Text,+ shader,+ type TreeNode+} from '@open-pencil/design-jsx'+import type { ComponentPropertyDefinition, ShaderPreset } from '@open-pencil/scene-graph'++import type { Theme } from '../theme'++export const PLAYER_PROPERTIES = {+ title: { id: 'player-title', name: 'Title', type: 'TEXT', defaultValue: 'Night Drive' },+ artist: { id: 'player-artist', name: 'Artist', type: 'TEXT', defaultValue: 'Lumen' }+} satisfies Record<string, ComponentPropertyDefinition>++export const PLAYER_WIDTH = 360+export const ARTWORK_SIZE = 320+export const ARTWORK_NAME = 'Artwork'++/** The cover the component draws unless an instance puts something else in the slot. */+export const COVER_PRESET: ShaderPreset = {+ components: [+ {+ type: 'LinearGradient',+ props: {+ colorA: '#1B1035',+ colorB: '#0B0A14',+ start: { x: 0.5, y: 0 },+ end: { x: 0.5, y: 1 }+ }+ },+ {+ type: 'Aurora',+ props: { colorA: '#8B5CF6', colorB: '#22D3EE', colorC: '#F472B6', intensity: 90 }+ }+ ]+}++/** A cover that fills the artwork slot with a shader. */+export function shaderCover(preset: ShaderPreset, name = 'Cover'): TreeNode {+ return <Rectangle name={name} w="fill" h="fill" bg={shader(preset)} />+}++/** The main components a player is assembled from, by the variant each instance shows. */+export interface PlayerParts {+ slider: string+ play: string+ shuffle: string+ repeat: string+ back: string+ forward: string+}++export function playerComponent({ vars }: Theme, parts: PlayerParts): TreeNode {+ const time = (value: string) => (+ <Text font="Inter" size={12} color={vars.muted}>+ {value}+ </Text>+ )+ return (+ <Component+ name="Player"+ properties={Object.values(PLAYER_PROPERTIES)}+ flex="col"+ w={PLAYER_WIDTH}+ h="hug"+ p={20}+ gap={20}+ rounded={vars.radius}+ bg={vars.surface}+ stroke={vars.line}+ >+ <Frame+ name={ARTWORK_NAME}+ flex="col"+ w={ARTWORK_SIZE}+ h={ARTWORK_SIZE}+ rounded={vars.cornerRadius}+ overflow="hidden"+ >+ {shaderCover(COVER_PRESET)}+ </Frame>+ <Frame name="Track" flex="col" w="fill" h="hug" gap={4}>+ <Text+ name="Title"+ font="Inter"+ size={20}+ weight={600}+ color={vars.text}+ propertyRefs={[{ propertyId: PLAYER_PROPERTIES.title.id, field: 'TEXT' }]}+ >+ {PLAYER_PROPERTIES.title.defaultValue}+ </Text>+ <Text+ name="Artist"+ font="Inter"+ size={14}+ color={vars.muted}+ propertyRefs={[{ propertyId: PLAYER_PROPERTIES.artist.id, field: 'TEXT' }]}+ >+ {PLAYER_PROPERTIES.artist.defaultValue}+ </Text>+ </Frame>+ <Frame name="Progress" flex="col" w="fill" h="hug" gap={8}>+ <Instance of={parts.slider} />+ <Frame name="Times" flex="row" w="fill" h="hug" justify="between">+ {time('1:24')}+ {time('3:50')}+ </Frame>+ </Frame>+ <Frame name="Controls" flex="row" w="fill" h="hug" justify="between" items="center">+ <Instance of={parts.shuffle} />+ <Instance of={parts.back} />+ <Instance of={parts.play} />+ <Instance of={parts.forward} />+ <Instance of={parts.repeat} />+ </Frame>+ </Component>+ )+}diff --git a/tools/generate/demo/src/document/player/controls.tsx b/tools/generate/demo/src/document/player/controls.tsxnew file mode 100644index 000000000..38f6fd5f1--- /dev/null+++ b/tools/generate/demo/src/document/player/controls.tsx@@ -0,0 +1,117 @@+/** @jsxImportSource @open-pencil/design-jsx */+/**+ * The player's controls, written with Reka UI's element names: each is a main component or a+ * component set with a behaviour, so preview runs it as the real control.+ */+import { Button, Component, Slider, Toggle, type TreeNode } from '@open-pencil/design-jsx'++import { Icon } from '../elements'+import type { Theme } from '../theme'++export const TRACK_LENGTH = 230+export const TRACK_POSITION = 84+export const SLIDER_WIDTH = 320++/** The progress bar: a slider over the track's seconds. */+export function progressSlider({ vars }: Theme): TreeNode {+ const range = Math.round((SLIDER_WIDTH * TRACK_POSITION) / TRACK_LENGTH)+ return (+ <Slider.Root+ name="Progress"+ w={SLIDER_WIDTH}+ h={16}+ min={0}+ max={TRACK_LENGTH}+ step={1}+ defaultValue={TRACK_POSITION}+ >+ <Slider.Track x={0} y={6} w={SLIDER_WIDTH} h={4} rounded={2} bg={vars.line} />+ <Slider.Range x={0} y={6} w={range} h={4} rounded={2} bg={vars.accent} />+ <Slider.Thumb x={range - 8} y={0} w={16} h={16} rounded={8} bg={vars.text} />+ </Slider.Root>+ )+}++/** Play and pause: a toggle whose variants swap the icon. */+export function playToggle({ vars }: Theme): TreeNode {+ const variant = (state: 'Off' | 'On', icon: string) => (+ <Component+ name={`Playing=${state}`}+ flex="row"+ w={56}+ h={56}+ rounded={28}+ justify="center"+ items="center"+ bg={vars.accent}+ >+ <Icon name={icon} size={26} color={vars.onAccent} />+ </Component>+ )+ return (+ <Toggle.Root name="Play" modelValue="Playing" flex="row" gap={16} p={16}>+ {variant('Off', 'lucide:play')}+ {variant('On', 'lucide:pause')}+ </Toggle.Root>+ )+}++export const OPTIONS = [+ ['Shuffle', 'lucide:shuffle'],+ ['Repeat', 'lucide:repeat']+] as const++/** Shuffle and repeat: one set, two dimensions, so an instance picks the icon and the state. */+export function optionToggle({ vars }: Theme): TreeNode {+ return (+ <Toggle.Root name="Option" modelValue="Pressed" flex="row" gap={16} p={16}>+ {OPTIONS.flatMap(([option, icon]) =>+ (['Off', 'On'] as const).map((state) => (+ <Component+ name={`Pressed=${state}, Icon=${option}`}+ flex="row"+ w={40}+ h={40}+ rounded={vars.cornerRadius}+ justify="center"+ items="center"+ bg={state === 'On' ? vars.raised : undefined}+ >+ <Icon name={icon} size={20} color={state === 'On' ? vars.accent : vars.muted} />+ </Component>+ ))+ )}+ </Toggle.Root>+ )+}++export const DIRECTIONS = [+ ['Back', 'lucide:skip-back'],+ ['Forward', 'lucide:skip-forward']+] as const+const INTERACTIONS = ['Default', 'Hover', 'Pressed'] as const++/** Previous and next: a button set whose variants draw its interaction states. */+export function skipButton({ vars }: Theme): TreeNode {+ const background = { Default: undefined, Hover: vars.raised, Pressed: vars.line }+ return (+ <Button.Root name="Skip" states="Interaction" flex="row" gap={16} p={16}>+ {DIRECTIONS.flatMap(([direction, icon]) =>+ INTERACTIONS.map((interaction) => (+ <Component+ name={`Direction=${direction}, Interaction=${interaction}`}+ flex="row"+ w={44}+ h={44}+ rounded={22}+ justify="center"+ items="center"+ bg={background[interaction]}+ >+ <Icon name={icon} size={22} color={vars.muted} />+ </Component>+ ))+ )}+ </Button.Root>+ )+}diff --git a/tools/generate/demo/src/document/sections/components.ts b/tools/generate/demo/src/document/sections/components.tsdeleted file mode 100644index 4710eb61a..000000000--- a/tools/generate/demo/src/document/sections/components.ts+++ /dev/null@@ -1,452 +0,0 @@-import { renderTree } from '@open-pencil/core/design-jsx'-import {- Component,- ComponentSet,- Ellipse,- Frame,- Instance,- Rectangle,- Text,- linearGradient-} from '@open-pencil/design-jsx'-import type { TreeNode } from '@open-pencil/design-jsx'-import type { ComponentPropertyDefinition, SceneGraph, Vector } from '@open-pencil/scene-graph'--import { createArtworkTile, createExampleColumn } from './example'--const INK = '#172554'-const MUTED = '#536487'-const ACCENT = '#4F46E5'-const TILE = '#EEF2FF'-const SURFACE = '#FFFFFF'-const BORDER = '#DCE3F5'--const text = { font: 'Inter', color: INK }-const label = { ...text, size: 12, color: MUTED }-const caption = { ...label, size: 12 }--export const COMPONENT_PROPERTIES = {- buttonLabel: {- id: 'demo-button-label',- name: 'Label',- type: 'TEXT',- defaultValue: 'Get started'- },- cardTitle: {- id: 'demo-card-title',- name: 'Title',- type: 'TEXT',- defaultValue: 'Analytics overview'- },- cardDescription: {- id: 'demo-card-description',- name: 'Description',- type: 'TEXT',- defaultValue: 'Track your key metrics and performance indicators in real time.'- },- badgeLabel: {- id: 'demo-badge-label',- name: 'Label',- type: 'TEXT',- defaultValue: 'Live'- },- badgeDot: {- id: 'demo-badge-dot',- name: 'Show dot',- type: 'BOOLEAN',- defaultValue: 'true'- }-} satisfies Record<string, ComponentPropertyDefinition>--interface ComponentExample {- title: string- caption: string-}--const EXAMPLE_GROUPS: readonly { title: string; examples: readonly ComponentExample[] }[] = [- {- title: '01 / ACTIONS · ONE BUTTON, TWO VARIANTS',- examples: [- { title: 'Primary', caption: 'Filled with the accent variable.' },- { title: 'Secondary', caption: 'Outline treatment for lower emphasis.' }- ]- },- {- title: '02 / IDENTITY · AVATAR, BADGE, TAG',- examples: [- { title: 'Avatar', caption: 'Gradient identity mark.' },- { title: 'Badge', caption: 'Status label with a live dot.' },- { title: 'Tag', caption: 'Quiet category chip.' }- ]- },- {- title: '03 / SURFACES · CARD AND INPUT',- examples: [- { title: 'Card', caption: 'Titled surface with a progress bar.' },- { title: 'Input', caption: 'Search field with a placeholder.' }- ]- }-]--export async function createComponentsSection(- graph: SceneGraph,- parentId: string,- options: Partial<Vector> = {}-) {- const root = await renderTree(- graph,- Frame({- name: 'Components',- flex: 'col',- w: 1056,- h: 'hug',- p: 32,- gap: 32,- bg: SURFACE,- children: [- Text({- ...text,- size: 20,- weight: 600,- children: 'One library. Every screen stays in sync.'- })- ]- }),- { parentId, ...options }- )-- // Instance slots come first so the sources below can fill them afterwards.- const slots: Record<string, string> = {}- for (const group of EXAMPLE_GROUPS) {- const groupFrame = await renderTree(- graph,- Frame({- name: group.title,- flex: 'col',- w: 'fill',- h: 'hug',- gap: 16,- children: [Text({ ...label, children: group.title })]- }),- { parentId: root.id }- )- const row = await renderTree(- graph,- Frame({ name: 'Linked instances', flex: 'row', w: 'fill', h: 'hug', gap: 24 }),- { parentId: groupFrame.id }- )- for (const example of group.examples) {- const column = await renderTree(- graph,- createExampleColumn({- title: example.title,- caption: example.caption,- artwork: createArtworkTile(`${example.title} / artwork`, { padding: 24, center: true })- }),- { parentId: row.id }- )- const artworkId = graph.getNode(column.id)?.childIds[0]- if (!artworkId) throw new Error(`Missing component example artwork for ${example.title}`)- slots[example.title] = artworkId- }- }-- const sources = await renderTree(- graph,- Frame({- name: '04 / SOURCES · EDIT THESE TO UPDATE EVERY EXAMPLE',- flex: 'col',- w: 'fill',- h: 'hug',- gap: 16,- children: [Text({ ...label, children: '04 / SOURCES · EDIT THESE TO UPDATE EVERY EXAMPLE' })]- }),- { parentId: root.id }- )- const sourceRow = async (name: string) => {- const row = await renderTree(- graph,- Frame({ name, flex: 'row', w: 'fill', h: 'hug', gap: 24, items: 'start' }),- { parentId: sources.id }- )- return row.id- }- const controlsRow = await sourceRow('Component sources / controls')- const surfacesRow = await sourceRow('Component sources / identity and surfaces')- const sourceTile = async (name: string, hint: string, rowId: string) => {- const tile = await renderTree(- graph,- Frame({- name,- flex: 'col',- w: 'fill',- h: 'hug',- p: 20,- gap: 12,- items: 'center',- rounded: 12,- bg: TILE,- children: [- Frame({- name: `${name} / source`,- flex: 'row',- w: 'fill',- h: 'hug',- p: 16,- justify: 'center',- items: 'center'- }),- Text({ ...caption, children: hint })- ]- }),- { parentId: rowId }- )- const artworkId = graph.getNode(tile.id)?.childIds[0]- if (!artworkId) throw new Error(`Missing source artwork for ${name}`)- return artworkId- }-- const buttonVariant = (variant: string, fill: string, color: string, outline: boolean) =>- Component({- name: `Variant=${variant}`,- properties: [COMPONENT_PROPERTIES.buttonLabel],- flex: 'row',- px: 20,- py: 10,- rounded: 8,- justify: 'center',- items: 'center',- bg: fill,- stroke: outline ? BORDER : undefined,- strokeWidth: outline ? 1 : undefined,- children: [- Text({- ...text,- name: 'Label',- size: 14,- weight: 600,- color,- children: COMPONENT_PROPERTIES.buttonLabel.defaultValue,- propertyRefs: [{ propertyId: COMPONENT_PROPERTIES.buttonLabel.id, field: 'TEXT' }]- })- ]- })- const buttonSet = await renderTree(- graph,- ComponentSet({- name: 'Button',- flex: 'row',- w: 'hug',- h: 'hug',- gap: 16,- children: [- buttonVariant('Primary', ACCENT, SURFACE, false),- buttonVariant('Secondary', SURFACE, INK, true)- ]- }),- { parentId: await sourceTile('Button variants', 'Two variants of one set.', controlsRow) }- )- const variantIds = graph.getNode(buttonSet.id)?.childIds ?? []-- const avatar = await renderTree(- graph,- Component({- name: 'Avatar',- flex: 'row',- w: 48,- h: 48,- justify: 'center',- items: 'center',- rounded: 24,- fills: [- linearGradient([- ['#7C3AED', 0],- ['#3B82F6', 1]- ])- ]- }),- { parentId: await sourceTile('Avatar', 'Gradient identity mark.', controlsRow) }- )-- const badge = await renderTree(- graph,- Component({- name: 'Badge',- properties: [COMPONENT_PROPERTIES.badgeDot, COMPONENT_PROPERTIES.badgeLabel],- flex: 'row',- gap: 4,- px: 8,- py: 4,- rounded: 12,- justify: 'center',- items: 'center',- bg: '#ECFDF5',- children: [- Ellipse({- name: 'Dot',- w: 6,- h: 6,- bg: '#22C55E',- propertyRefs: [{ propertyId: COMPONENT_PROPERTIES.badgeDot.id, field: 'VISIBLE' }]- }),- Text({- ...text,- name: 'Label',- size: 12,- weight: 600,- color: '#15803D',- children: COMPONENT_PROPERTIES.badgeLabel.defaultValue,- propertyRefs: [{ propertyId: COMPONENT_PROPERTIES.badgeLabel.id, field: 'TEXT' }]- })- ]- }),- { parentId: await sourceTile('Badge', 'Label plus a toggleable dot.', controlsRow) }- )-- const tag = await renderTree(- graph,- Component({- name: 'Tag',- flex: 'row',- px: 12,- py: 4,- rounded: 14,- justify: 'center',- items: 'center',- bg: TILE,- children: [Text({ ...text, size: 12, weight: 500, color: ACCENT, children: 'Design' })]- }),- { parentId: await sourceTile('Tag', 'Quiet category chip.', surfacesRow) }- )-- const card = await renderTree(- graph,- Component({- name: 'Card',- properties: [COMPONENT_PROPERTIES.cardTitle, COMPONENT_PROPERTIES.cardDescription],- flex: 'col',- w: 280,- h: 'hug',- p: 20,- gap: 8,- rounded: 12,- bg: SURFACE,- stroke: BORDER,- strokeWidth: 1,- children: [- Text({- ...text,- name: 'Title',- w: 'fill',- size: 16,- weight: 600,- children: COMPONENT_PROPERTIES.cardTitle.defaultValue,- propertyRefs: [{ propertyId: COMPONENT_PROPERTIES.cardTitle.id, field: 'TEXT' }]- }),- Text({- ...text,- name: 'Description',- w: 'fill',- size: 13,- lineHeight: 18,- color: MUTED,- children: COMPONENT_PROPERTIES.cardDescription.defaultValue,- propertyRefs: [{ propertyId: COMPONENT_PROPERTIES.cardDescription.id, field: 'TEXT' }]- }),- Rectangle({ name: 'Progress track', w: 'fill', h: 8, rounded: 4, bg: '#EEF0F6' }),- Rectangle({- name: 'Progress',- w: 168,- h: 8,- rounded: 4,- fills: [- linearGradient([- ['#3B82F6', 0],- ['#14B8A6', 1]- ])- ]- })- ]- }),- { parentId: await sourceTile('Card', 'Titled surface with progress.', surfacesRow) }- )-- const input = await renderTree(- graph,- Component({- name: 'Input',- flex: 'row',- w: 240,- px: 12,- py: 10,- rounded: 8,- items: 'center',- bg: SURFACE,- stroke: BORDER,- strokeWidth: 1,- children: [- Text({- ...text,- name: 'Placeholder',- w: 'fill',- size: 14,- color: MUTED,- children: 'Search…'- })- ]- }),- { parentId: await sourceTile('Input', 'Search field with placeholder.', surfacesRow) }- )-- const place = async (name: string, node: TreeNode) => {- const artworkId = slots[name]- if (!artworkId) throw new Error(`Missing component example slot for ${name}`)- return renderTree(graph, node, { parentId: artworkId })- }-- const primaryId = variantIds[0]- const secondaryId = variantIds[1]- if (!primaryId || !secondaryId) throw new Error('Button variants were not created')- await place('Primary', Instance({ of: primaryId }))- await place(- 'Secondary',- Instance({- of: secondaryId,- properties: { [COMPONENT_PROPERTIES.buttonLabel.id]: 'Cancel' }- })- )- await place('Avatar', Instance({ of: avatar.id }))- await place(- 'Badge',- Instance({- of: badge.id,- properties: { [COMPONENT_PROPERTIES.badgeLabel.id]: 'Live' }- })- )- await place('Tag', Instance({ of: tag.id }))- await place(- 'Card',- Instance({- of: card.id,- properties: {- [COMPONENT_PROPERTIES.cardTitle.id]: 'Analytics overview',- [COMPONENT_PROPERTIES.cardDescription.id]: 'Every value here is a component property.'- }- })- )- await place('Input', Instance({ of: input.id }))-- await renderTree(- graph,- Text({- ...label,- w: 'fill',- lineHeight: 18,- children:- 'Edit any source below and every linked instance above updates. Text and visibility stay editable per instance.'- }),- { parentId: root.id }- )-- return { rootId: root.id }-}diff --git a/tools/generate/demo/src/document/sections/example.ts b/tools/generate/demo/src/document/sections/example.tsdeleted file mode 100644index cd2492f49..000000000--- a/tools/generate/demo/src/document/sections/example.ts+++ /dev/null@@ -1,52 +0,0 @@-import { Frame, Text } from '@open-pencil/design-jsx'-import type { TreeNode } from '@open-pencil/design-jsx'--const INK = '#172554'-const MUTED = '#536487'-const TILE = '#EEF2FF'--/** The framed artwork panel shared by the demo's specimen sections. */-export function createArtworkTile(- name: string,- options: { padding?: number; center?: boolean; children?: TreeNode[] } = {}-): TreeNode {- const props = {- name,- flex: 'row' as const,- w: 'fill' as const,- h: 'hug' as const,- p: options.padding ?? 16,- justify: 'center' as const,- rounded: 12,- bg: TILE,- children: options.children ?? []- }- return Frame(options.center ? { ...props, items: 'center' as const } : props)-}--/** A labelled specimen column: artwork panel, title, and caption. */-export function createExampleColumn(options: {- title: string- caption: string- artwork: TreeNode-}): TreeNode {- return Frame({- name: options.title,- flex: 'col',- w: 'fill',- h: 'hug',- gap: 8,- children: [- options.artwork,- Text({ font: 'Inter', color: INK, size: 14, weight: 600, children: options.title }),- Text({- font: 'Inter',- color: MUTED,- size: 12,- w: 'fill',- lineHeight: 18,- children: options.caption- })- ]- })-}diff --git a/tools/generate/demo/src/document/sections/variables.ts b/tools/generate/demo/src/document/sections/variables.tsdeleted file mode 100644index f79c531ad..000000000--- a/tools/generate/demo/src/document/sections/variables.ts+++ /dev/null@@ -1,145 +0,0 @@-import type { Color, SceneGraph } from '@open-pencil/scene-graph'--import { DEMO_COLORS } from '../colors'--export function createDemoVariables(graph: SceneGraph) {- graph.addCollection({- id: 'col-primitives',- name: 'Primitives',- modes: [- { modeId: 'light', name: 'Light' },- { modeId: 'dark', name: 'Dark' }- ],- defaultModeId: 'light',- variableIds: []- })-- const primitiveColors: Array<{- id: string- name: string- light: Color- dark: Color- }> = [- {- id: 'var-white',- name: 'White',- light: DEMO_COLORS.white,- dark: { r: 0.12, g: 0.12, b: 0.13, a: 1 }- },- { id: 'var-black', name: 'Black', light: DEMO_COLORS.black, dark: DEMO_COLORS.white },- {- id: 'var-gray-50',- name: 'Gray/50',- light: DEMO_COLORS.gray50,- dark: { r: 0.1, g: 0.1, b: 0.11, a: 1 }- },- {- id: 'var-gray-100',- name: 'Gray/100',- light: DEMO_COLORS.gray100,- dark: { r: 0.14, g: 0.14, b: 0.16, a: 1 }- },- {- id: 'var-gray-200',- name: 'Gray/200',- light: DEMO_COLORS.gray200,- dark: { r: 0.22, g: 0.22, b: 0.24, a: 1 }- },- {- id: 'var-gray-500',- name: 'Gray/500',- light: DEMO_COLORS.gray500,- dark: { r: 0.65, g: 0.65, b: 0.68, a: 1 }- },- {- id: 'var-blue',- name: 'Blue',- light: DEMO_COLORS.blue,- dark: { r: 0.33, g: 0.61, b: 1, a: 1 }- },- {- id: 'var-green',- name: 'Green',- light: DEMO_COLORS.green,- dark: { r: 0.23, g: 0.87, b: 0.52, a: 1 }- },- { id: 'var-red', name: 'Red', light: DEMO_COLORS.red, dark: { r: 1, g: 0.32, b: 0.32, a: 1 } }- ]-- for (const c of primitiveColors) {- graph.addVariable({- id: c.id,- name: c.name,- type: 'COLOR',- collectionId: 'col-primitives',- valuesByMode: { light: c.light, dark: c.dark },- description: '',- hiddenFromPublishing: false- })- }-- graph.addCollection({- id: 'col-semantic',- name: 'Semantic',- modes: [{ modeId: 'default', name: 'Default' }],- defaultModeId: 'default',- variableIds: []- })-- const semanticVars: Array<{ id: string; name: string; aliasId: string }> = [- { id: 'var-bg', name: 'Background', aliasId: 'var-white' },- { id: 'var-bg-secondary', name: 'Background/Secondary', aliasId: 'var-gray-50' },- { id: 'var-text-primary', name: 'Text/Primary', aliasId: 'var-black' },- { id: 'var-text-secondary', name: 'Text/Secondary', aliasId: 'var-gray-500' },- { id: 'var-border', name: 'Border', aliasId: 'var-gray-200' },- { id: 'var-accent', name: 'Accent', aliasId: 'var-blue' },- { id: 'var-success', name: 'Success', aliasId: 'var-green' },- { id: 'var-error', name: 'Error', aliasId: 'var-red' }- ]-- for (const s of semanticVars) {- graph.addVariable({- id: s.id,- name: s.name,- type: 'COLOR',- collectionId: 'col-semantic',- valuesByMode: { default: { aliasId: s.aliasId } },- description: '',- hiddenFromPublishing: false- })- }-- graph.addCollection({- id: 'col-spacing',- name: 'Spacing',- modes: [- { modeId: 'default', name: 'Default' },- { modeId: 'compact', name: 'Compact' }- ],- defaultModeId: 'default',- variableIds: []- })-- const spacingVars: Array<{ id: string; name: string; default: number; compact: number }> = [- { id: 'var-space-xs', name: 'Space/XS', default: 4, compact: 2 },- { id: 'var-space-sm', name: 'Space/SM', default: 8, compact: 4 },- { id: 'var-space-md', name: 'Space/MD', default: 16, compact: 12 },- { id: 'var-space-lg', name: 'Space/LG', default: 24, compact: 16 },- { id: 'var-space-xl', name: 'Space/XL', default: 32, compact: 24 },- { id: 'var-radius-sm', name: 'Radius/SM', default: 4, compact: 2 },- { id: 'var-radius-md', name: 'Radius/MD', default: 8, compact: 6 },- { id: 'var-radius-lg', name: 'Radius/LG', default: 16, compact: 12 }- ]-- for (const s of spacingVars) {- graph.addVariable({- id: s.id,- name: s.name,- type: 'FLOAT',- collectionId: 'col-spacing',- valuesByMode: { default: s.default, compact: s.compact },- description: '',- hiddenFromPublishing: false- })- }-}diff --git a/tools/generate/demo/src/document/slot-content.ts b/tools/generate/demo/src/document/slot-content.tsnew file mode 100644index 000000000..94dc67afb--- /dev/null+++ b/tools/generate/demo/src/document/slot-content.ts@@ -0,0 +1,28 @@+import type { TreeNode } from '@open-pencil/design-jsx'+import {+ claimSlotContent,+ instanceSlotFrames,+ slotPropertyId,+ slotScope,+ type SceneGraph+} from '@open-pencil/scene-graph'++import { renderTree } from './icons'++/** Replace what the instance shows in the slot: it owns the content from then on. */+export async function fillSlot(+ graph: SceneGraph,+ instanceId: string,+ slotId: string,+ content: TreeNode+): Promise<void> {+ const instance = graph.getNode(instanceId)+ const frame = instance+ ? instanceSlotFrames(graph, instance).find((slot) => slotPropertyId(slot) === slotId)+ : undefined+ const scope = frame ? slotScope(graph, frame.id) : null+ if (!frame || scope?.kind !== 'slot') throw new Error('The instance has no such slot')+ claimSlotContent(graph, scope)+ for (const childId of Array.from(frame.childIds)) graph.deleteNode(childId)+ await renderTree(graph, content, { parentId: frame.id })+}diff --git a/tools/generate/demo/src/document/theme.ts b/tools/generate/demo/src/document/theme.tsnew file mode 100644index 000000000..46cad1ce8--- /dev/null+++ b/tools/generate/demo/src/document/theme.ts@@ -0,0 +1,121 @@+import { defineVars, type DesignVariable } from '@open-pencil/design-jsx'+import type { SceneGraph } from '@open-pencil/scene-graph'+import { parseColor } from '@open-pencil/scene-graph/color'++/**+ * The tour's colors live in two collections, each with a Dark and a Light mode: Theme, for the+ * tour's own design, and App chrome, for the pieces of OpenPencil's interface the tips draw.+ * The app picks the mode that matches its own theme when it opens the tour, by these+ * collection and mode names, and paints the page in the Theme's Page color+ * (`src/app/demo/theme.ts`).+ */+export const COLLECTION_NAMES = { theme: 'Theme', chrome: 'App chrome' } as const+export const MODE_NAMES = { dark: 'Dark', light: 'Light' } as const++type Mode = keyof typeof MODE_NAMES+type Entry = readonly [key: string, name: string, dark: string | number, light: string | number]++const THEME_COLORS = [+ ['page', 'Page', '#0E0E12', '#ECECF1'],+ ['section', 'Section', '#131319', '#F7F7FA'],+ ['numeral', 'Text/Numeral', '#64647E', '#8B8BA0'],+ ['surface', 'Surface', '#1A1A20', '#FFFFFF'],+ ['raised', 'Surface/Raised', '#26262E', '#EDEDF2'],+ ['line', 'Line', '#33333D', '#DCDCE4'],+ ['text', 'Text', '#F5F5F7', '#141418'],+ ['muted', 'Text/Muted', '#9B9BAA', '#62627A'],+ ['faint', 'Text/Faint', '#4A4A58', '#C9C9D4'],+ ['accent', 'Accent', '#7C3AED', '#6D28D9'],+ ['onAccent', 'Accent/Text', '#FFFFFF', '#FFFFFF']+] as const satisfies readonly Entry[]++/** The page background the file is saved with: the Page color in the default, Dark mode. */+export const PAGE_BACKGROUND = THEME_COLORS[0][2]++const THEME_NUMBERS = [+ ['radius', 'Radius', 24, 20],+ ['cornerRadius', 'Radius/Control', 12, 10]+] as const satisfies readonly Entry[]++/** OpenPencil's own interface colors, from `src/app.css`, dark and light. */+const CHROME_COLORS = [+ ['panel', 'Panel', '#2A2A2A', '#FFFFFF'],+ ['header', 'Header', '#1E1E1E', '#F3F4F6'],+ ['field', 'Field', '#383838', '#F0F1F3'],+ ['border', 'Border', '#3A3A3A', '#D8DCE3'],+ ['text', 'Text', '#E6E6E6', '#1F2328'],+ ['muted', 'Text/Muted', '#A6A6A6', '#5F6673'],+ ['blue', 'Accent', '#2563EB', '#2563EB'],+ ['onBlue', 'Accent/Text', '#FFFFFF', '#FFFFFF'],+ ['previewChip', 'Preview/Chip', '#293246', '#DBE7FB'],+ ['previewText', 'Preview/Text', '#5A9AEA', '#1D4ED8'],+ ['component', 'Component', '#A78BFA', '#7C3AED'],+ ['slot', 'Slot', '#F472B6', '#DB2777'],+ ['checker', 'Checkerboard', '#4A4A4A', '#D8DCE3']+] as const satisfies readonly Entry[]++type Vars<T extends readonly Entry[]> = Record<T[number][0], DesignVariable>++function addCollection(+ graph: SceneGraph,+ prefix: string,+ name: string,+ entries: readonly Entry[]+): Record<string, DesignVariable> {+ const collectionId = `${prefix}-collection`+ const modeIds: Record<Mode, string> = { dark: `${prefix}-dark`, light: `${prefix}-light` }+ graph.addCollection({+ id: collectionId,+ name,+ modes: [+ { modeId: modeIds.dark, name: MODE_NAMES.dark },+ { modeId: modeIds.light, name: MODE_NAMES.light }+ ],+ defaultModeId: modeIds.dark,+ variableIds: []+ })+ const value = (raw: string | number) => (typeof raw === 'number' ? raw : parseColor(raw))+ for (const [key, variableName, dark, light] of entries) {+ graph.addVariable({+ id: `${prefix}-${key}`,+ name: variableName,+ type: typeof dark === 'number' ? 'FLOAT' : 'COLOR',+ collectionId,+ valuesByMode: { [modeIds.dark]: value(dark), [modeIds.light]: value(light) },+ description: '',+ hiddenFromPublishing: false+ })+ }+ // Each reference carries its dark value, for layers drawn before they are bound, such as icons.+ return defineVars(+ Object.fromEntries(+ entries.map(([key, variableName, dark]) => [+ key,+ { id: `${prefix}-${key}`, name: variableName, value: dark }+ ])+ )+ )+}++/** The tour's collections, with references to every variable in them. */+export function createTheme(graph: SceneGraph) {+ const vars = addCollection(graph, 'demo-theme', COLLECTION_NAMES.theme, [+ ...THEME_COLORS,+ ...THEME_NUMBERS+ ]) as Vars<typeof THEME_COLORS> & Vars<typeof THEME_NUMBERS>+ const chrome = addCollection(+ graph,+ 'demo-chrome',+ COLLECTION_NAMES.chrome,+ CHROME_COLORS+ ) as Vars<typeof CHROME_COLORS>+ return {+ vars,+ chrome,+ /** The Theme collection and its modes, for frames that pin one. */+ collectionId: 'demo-theme-collection',+ modeIds: { dark: 'demo-theme-dark', light: 'demo-theme-light' } satisfies Record<Mode, string>+ }+}++export type Theme = ReturnType<typeof createTheme>diff --git a/tools/generate/demo/src/document/typography/content.ts b/tools/generate/demo/src/document/typography/content.tsdeleted file mode 100644index 690cb6689..000000000--- a/tools/generate/demo/src/document/typography/content.ts+++ /dev/null@@ -1,49 +0,0 @@-import type { SceneNode } from '@open-pencil/scene-graph'--export const ARTICLE = {- eyebrow: 'A NOTE ON MAKING THINGS',- title: 'Leave room for\na better idea.',- introduction: 'Good typography gives every thought a place.',- body: 'Start with a clear headline. Give the supporting text enough space to breathe. Keep the details quiet, but never so quiet that they disappear.',- detail: 'FIELD NOTES / 01 · EDITABLE TEXT, NOT OUTLINES'-}--interface FeatureComparison {- title: string- text: string- font?: string- enabled: SceneNode['fontFeatures']- disabled: SceneNode['fontFeatures']- labels: readonly [string, string]-}--export const FEATURE_COMPARISONS: readonly FeatureComparison[] = [- {- title: 'Discretionary ligatures',- text: 'What!? Really?!',- font: 'Inter',- enabled: [{ tag: 'DLIG', enabled: true }],- disabled: [{ tag: 'DLIG', enabled: false }],- labels: ['DLIG ON', 'DLIG OFF']- },- {- title: 'Kerning',- text: 'AVATAR WAVE',- enabled: [{ tag: 'KERN', enabled: true }],- disabled: [{ tag: 'KERN', enabled: false }],- labels: ['KERN ON', 'KERN OFF']- },- {- title: 'Tabular and proportional figures',- text: '1,111.00 / 8,888.00',- enabled: [- { tag: 'TNUM', enabled: true },- { tag: 'PNUM', enabled: false }- ],- disabled: [- { tag: 'TNUM', enabled: false },- { tag: 'PNUM', enabled: true }- ],- labels: ['TNUM ON · PNUM OFF', 'TNUM OFF · PNUM ON']- }-]diff --git a/tools/generate/demo/src/document/typography/samples.ts b/tools/generate/demo/src/document/typography/samples.tsdeleted file mode 100644index 004ed1725..000000000--- a/tools/generate/demo/src/document/typography/samples.ts+++ /dev/null@@ -1,40 +0,0 @@-import { renderTree } from '@open-pencil/core/design-jsx'-import { Text } from '@open-pencil/design-jsx'-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'--interface TypographySample {- name: string- text: string- font?: string- fontFeatures?: SceneNode['fontFeatures']- decoration?: Pick<- SceneNode,- 'textDecoration' | 'textDecorationStyle' | 'textDecorationFills' | 'textDecorationThickness'- >-}--/** These native OpenType/decoration fields are not Design JSX shorthands. */-export async function createTypographySample(- graph: SceneGraph,- parentId: string,- sample: TypographySample-) {- const result = await renderTree(- graph,- Text({- name: sample.name,- children: sample.text,- font: sample.font ?? 'Inter',- size: 24,- lineHeight: 36,- w: 'fill',- color: '#172554'- }),- { parentId }- )- graph.updateNode(result.id, {- fontFeatures: sample.fontFeatures ?? [],- ...sample.decoration- })- return result.id-}diff --git a/tools/generate/demo/src/document/typography/section.ts b/tools/generate/demo/src/document/typography/section.tsdeleted file mode 100644index 1be20867c..000000000--- a/tools/generate/demo/src/document/typography/section.ts+++ /dev/null@@ -1,213 +0,0 @@-import { renderTree } from '@open-pencil/core/design-jsx'-import { Frame, Text } from '@open-pencil/design-jsx'-import type { SceneGraph } from '@open-pencil/scene-graph'-import { parseColor } from '@open-pencil/scene-graph/color'--import { ARTICLE, FEATURE_COMPARISONS } from './content'-import { createTypographySample } from './samples'--export async function createTypographySection(graph: SceneGraph, parentId: string) {- const text = { font: 'Inter', color: '#172554' }- const label = { ...text, size: 12, color: '#536487' }- const root = await renderTree(- graph,- Frame({- name: 'Typography workbench',- flex: 'col',- w: 1056,- h: 'hug',- gap: 32,- p: 32,- bg: '#FFFFFF',- children: [- Text({ ...text, size: 20, weight: 600, children: 'Type that holds together.' }),- Frame({- name: 'Hierarchy in context',- flex: 'row',- w: 'fill',- h: 'hug',- gap: 32,- children: [- Frame({- name: 'Editable article',- flex: 'col',- w: 600,- h: 'hug',- gap: 16,- p: 24,- rounded: 16,- bg: '#EEF2FF',- children: [- Text({ ...label, size: 12, children: ARTICLE.eyebrow }),- Text({- ...text,- name: 'Article headline',- w: 'fill',- size: 36,- lineHeight: 42,- weight: 600,- children: ARTICLE.title- }),- Text({- ...text,- name: 'Article introduction',- w: 'fill',- size: 18,- lineHeight: 26,- children: ARTICLE.introduction- }),- Text({- ...text,- name: 'Article body',- w: 'fill',- size: 14,- lineHeight: 22,- children: ARTICLE.body- }),- Text({ ...label, size: 12, children: ARTICLE.detail })- ]- }),- Frame({- name: 'Type hierarchy guide',- flex: 'col',- w: 'fill',- h: 'hug',- gap: 24,- children: [- Text({ ...label, children: '01 / HIERARCHY' }),- ...[- {- title: 'Headline · 36 / 42',- description: 'The first thing to read. Keep its rhythm when the words change.'- },- {- title: 'Introduction · 18 / 26',- description: 'A second voice, not a second headline.'- },- {- title: 'Body · 14 / 22',- description: 'Readable lines, generous leading, and a content-sized frame.'- },- {- title: 'Details · 12',- description: 'Supporting information with enough contrast to stay useful.'- }- ].map((item) =>- Frame({- flex: 'col',- w: 'fill',- h: 'hug',- gap: 6,- children: [- Text({ ...text, size: 14, weight: 600, children: item.title }),- Text({ ...label, w: 'fill', lineHeight: 18, children: item.description })- ]- })- )- ]- })- ]- })- ]- }),- { parentId }- )- const features = await renderTree(- graph,- Frame({- name: 'OpenType comparisons',- flex: 'col',- w: 'fill',- h: 'hug',- gap: 16,- children: Text({ ...label, children: '02 / OPENTYPE · THE SAME TEXT, DIFFERENT FEATURES' })- }),- { parentId: root.id }- )- const comparisonRow = await renderTree(- graph,- Frame({ name: 'Feature pairs', flex: 'row', w: 'fill', h: 'hug', gap: 24 }),- { parentId: features.id }- )- for (const comparison of FEATURE_COMPARISONS) {- const column = await renderTree(- graph,- Frame({- name: comparison.title,- flex: 'col',- w: 'fill',- h: 'hug',- gap: 8,- children: Text({ ...text, size: 14, weight: 600, children: comparison.title })- }),- { parentId: comparisonRow.id }- )- for (const [index, settings] of [comparison.enabled, comparison.disabled].entries()) {- await renderTree(graph, Text({ ...label, size: 12, children: comparison.labels[index] }), {- parentId: column.id- })- await createTypographySample(graph, column.id, {- name: `${comparison.title} / ${comparison.labels[index]}`,- text: comparison.text,- font: comparison.font,- fontFeatures: settings- })- }- }- await renderTree(- graph,- Text({- ...label,- w: 'fill',- lineHeight: 18,- children:- 'Feature support depends on the font. Raw tags are preserved even when a typeface has no matching alternate.'- }),- { parentId: features.id }- )- const decorations = await renderTree(- graph,- Frame({- name: 'Text decorations',- flex: 'col',- w: 'fill',- h: 'hug',- gap: 16,- children: Text({ ...label, children: '03 / DECORATION · NATIVE TEXT, NOT DRAWN LINES' })- }),- { parentId: root.id }- )- const decorationRow = await renderTree(- graph,- Frame({ name: 'Decoration samples', flex: 'row', w: 'fill', h: 'hug', gap: 24 }),- { parentId: decorations.id }- )- for (const sample of [- { name: 'Wavy underline', style: 'WAVY', color: '#E5484D', thickness: 1.6 },- { name: 'Dotted underline', style: 'DOTTED', color: '#4F46E5', thickness: 2 }- ] as const) {- const column = await renderTree(- graph,- Frame({ name: sample.name, flex: 'col', w: 'fill', h: 'hug', gap: 8 }),- { parentId: decorationRow.id }- )- await createTypographySample(graph, column.id, {- name: sample.name,- text: 'Keep this thought.',- decoration: {- textDecoration: 'UNDERLINE',- textDecorationStyle: sample.style,- textDecorationFills: [- { type: 'SOLID', color: parseColor(sample.color), opacity: 1, visible: true }- ],- textDecorationThickness: sample.thickness- }- })- await renderTree(- graph,- Text({ ...label, children: `${sample.name} · ${sample.thickness}px` }),- { parentId: column.id }- )- }- return { rootId: root.id }-}diff --git a/tools/generate/demo/src/shaders/page.ts b/tools/generate/demo/src/shaders/page.tsnew file mode 100644index 000000000..32a8695f8--- /dev/null+++ b/tools/generate/demo/src/shaders/page.ts@@ -0,0 +1,31 @@+/**+ * The page `drawShaderStills` opens in a browser: it draws a shader preset's first frame on a+ * WebGPU canvas and hands it back as a PNG data URL. Bundled for the browser at build time.+ */+import { createRendererFromJSON } from 'shaders/core'++import type { ShaderPreset } from '@open-pencil/scene-graph'++export interface ShaderStillPage {+ renderStill(preset: ShaderPreset, width: number, height: number): Promise<string>+}++const page: ShaderStillPage = {+ async renderStill(preset, width, height) {+ const canvas = document.createElement('canvas')+ canvas.width = width+ canvas.height = height+ const renderer = createRendererFromJSON(structuredClone(preset))+ try {+ await renderer.initialize(canvas)+ // The first frame only prepares the effects' pipelines; the second is the still.+ await renderer.renderFrame({ deltaSeconds: 0, waitForGpu: false })+ await renderer.renderFrame({ deltaSeconds: 0, waitForGpu: false })+ return canvas.toDataURL('image/png')+ } finally {+ renderer.dispose()+ }+ }+}++Object.assign(window, { shaderStill: page })diff --git a/tools/generate/demo/src/shaders/stills.ts b/tools/generate/demo/src/shaders/stills.tsnew file mode 100644index 000000000..62c65c17b--- /dev/null+++ b/tools/generate/demo/src/shaders/stills.ts@@ -0,0 +1,136 @@+import { fileURLToPath } from 'node:url'++import { chromium } from '@playwright/test'+import { toUint8Array } from 'js-base64'++import {+ isShaderFrameCurrent,+ shaderOfPaint,+ shaderPresetKey,+ withShaderPaints,+ type SceneGraph,+ type SceneNode,+ type ShaderPaint+} from '@open-pencil/scene-graph'++import type { ShaderStillPage } from './page'++/** Frames are drawn at twice the layer's size, as the editor draws them, up to this edge. */+const FRAME_SCALE = 2+const MAX_FRAME_EDGE = 1600++/** Headless Chromium has WebGPU only with SwiftShader, and only on a secure origin. */+const BROWSER_ARGS = [+ '--enable-unsafe-webgpu',+ '--use-angle=swiftshader',+ '--enable-unsafe-swiftshader'+]++interface Job {+ node: SceneNode+ shader: ShaderPaint+}++/** The shaders of `node`'s paints whose frame is missing or drawn for another size or preset. */+function staleShaders(graph: SceneGraph, node: SceneNode): ShaderPaint[] {+ const size = { width: node.width, height: node.height }+ return [...node.fills, ...node.strokes].flatMap((paint) => {+ const shader = shaderOfPaint(node, paint)+ if (!shader) return []+ return isShaderFrameCurrent(shader, size) && graph.images.has(shader.image) ? [] : [shader]+ })+}++function framePixels(node: SceneNode): { width: number; height: number } {+ const scale = Math.min(FRAME_SCALE, MAX_FRAME_EDGE / Math.max(node.width, node.height, 1))+ return {+ width: Math.max(1, Math.round(node.width * scale)),+ height: Math.max(1, Math.round(node.height * scale))+ }+}++/** The still page as one HTML document and its script, served from a loopback port. */+async function serveStillPage() {+ const built = await Bun.build({+ entrypoints: [fileURLToPath(new URL('page.ts', import.meta.url))],+ target: 'browser'+ })+ const [script] = built.outputs+ if (!built.success || !script) {+ throw new Error(+ built.logs.map((log) => log.message).join('\n') || 'The still page did not build'+ )+ }+ const js = await script.text()+ const html = '<!doctype html><meta charset="utf-8"><script type="module" src="/page.js"></script>'+ return Bun.serve({+ hostname: '127.0.0.1',+ port: 0,+ fetch: (request) =>+ new URL(request.url).pathname === '/page.js'+ ? new Response(js, { headers: { 'content-type': 'text/javascript' } })+ : new Response(html, { headers: { 'content-type': 'text/html' } })+ })+}++/**+ * Draw the first frame of every shader paint in `graph` whose frame is missing or stale, as+ * the editor would on opening the document, and store it as the paint's image. Needs the+ * Playwright Chromium; without it the frames are left for the editor to draw, which it does in+ * browsers with WebGPU.+ */+export async function drawShaderStills(graph: SceneGraph): Promise<number> {+ const jobs: Job[] = [...graph.getAllNodes()].flatMap((node) =>+ staleShaders(graph, node).map((shader) => ({ node, shader }))+ )+ if (jobs.length === 0) return 0+ const server = await serveStillPage()+ let browser: Awaited<ReturnType<typeof chromium.launch>> | null = null+ try {+ browser = await chromium.launch({ headless: true, args: BROWSER_ARGS })+ const page = await browser.newPage()+ await page.goto(`http://127.0.0.1:${server.port}/`)+ await page.waitForFunction(() => Reflect.has(window, 'shaderStill'))+ for (const { node, shader } of jobs) {+ const pixels = framePixels(node)+ // Runs in the page, so the check is written out here rather than shared.+ const dataURL = await page.evaluate(+ ({ preset, width, height }) => {+ const api: unknown = Reflect.get(window, 'shaderStill')+ if (typeof api !== 'object' || api === null || !('renderStill' in api)) {+ throw new Error('The still page did not load')+ }+ const render = api.renderStill as ShaderStillPage['renderStill']+ return render(preset, width, height)+ },+ { preset: shader.preset, ...pixels }+ )+ const [, encoded = ''] = dataURL.split(',')+ graph.images.set(shader.image, toUint8Array(encoded))+ const current = graph.getNode(node.id)+ if (!current) continue+ const frame = {+ width: node.width,+ height: node.height,+ preset: shaderPresetKey(shader.preset)+ }+ graph.updateNode(node.id, {+ pluginData: withShaderPaints(+ current,+ [...current.fills, ...current.strokes],+ [{ ...shader, frame }]+ )+ })+ }+ return jobs.length+ } catch (error: unknown) {+ const reason = error instanceof Error ? error.message.split('\n')[0] : String(error)+ console.warn(+ `Shader frames were not drawn (${reason}); the editor draws them when the demo opens in a browser with WebGPU.`+ )+ return 0+ } finally {+ await browser?.close()+ server.stop(true)+ }+}diff --git a/tools/generate/demo/tests/build.test.ts b/tools/generate/demo/tests/build.test.tsindex 419d4bb5c..b911818a7 100644--- a/tools/generate/demo/tests/build.test.ts+++ b/tools/generate/demo/tests/build.test.ts@@ -1,41 +1,115 @@-import { describe, expect, test } from 'bun:test'+import { beforeAll, describe, expect, test } from 'bun:test'-import { measuringRenderer, withMeasuredText } from '#demo/build'-import { createControlsSection } from '#demo/document/controls/section'+import { buildDemoGraph, measuringRenderer } from '#demo/build'import { exportFigFile, readFigFile } from '@open-pencil/core/io'import { populateAllFigPages } from '@open-pencil/core/io/formats/fig'-import { computeAllLayouts } from '@open-pencil/core/layout'-import { missingBindings, readBehaviour, SceneGraph } from '@open-pencil/scene-graph'--describe('demo controls', () => {- test('keep complete behaviours through the .fig the demo opens', async () => {- const { ck, renderer } = await measuringRenderer()- const built = await withMeasuredText(renderer, async () => {- const graph = new SceneGraph()- const [page] = graph.getPages()- await createControlsSection(graph, page.id)- computeAllLayouts(graph, page.id)- return graph- })- const bytes = await exportFigFile(built, ck, renderer)- const graph = await readFigFile(new File([bytes.slice()], 'Demo.fig'))- populateAllFigPages(graph)-- const controls = [...graph.getAllNodes()].flatMap((node) => {- const behaviour = node.type === 'INSTANCE' ? null : readBehaviour(node)- return behaviour- ? [{ kind: behaviour.kind, missing: missingBindings(graph, node, behaviour) }]- : []+import {+ instanceSlotFrames,+ missingBindings,+ ownsSlotContent,+ readBehaviour,+ readShaderPaints,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'++let graph: SceneGraph++/** The instances of the Player component, with the layers each shows in its artwork slot. */+function playerCovers(target: SceneGraph): { title: string; cover: string[]; owned: boolean }[] {+ return [...target.getAllNodes()]+ .filter((node) => node.type === 'INSTANCE' && node.name === 'Player')+ .flatMap((instance) => {+ const [slot] = instanceSlotFrames(target, instance)+ if (!slot) return []+ const component = instance.componentId ? target.getNode(instance.componentId) : undefined+ const title = component?.componentPropertyDefinitions.find((d) => d.name === 'Title')+ return [+ {+ title: title ? (instance.componentPropertyAssignments[title.id] ?? '') : '',+ cover: target.getChildren(slot.id).map((child) => `${child.type}:${child.name}`),+ owned: ownsSlotContent(target, slot)+ }+ ]})+}++function behaviours(target: SceneGraph): { kind: string; missing: string[] }[] {+ return [...target.getAllNodes()].flatMap((node: SceneNode) => {+ const behaviour = node.type === 'INSTANCE' ? null : readBehaviour(node)+ return behaviour+ ? [{ kind: behaviour.kind, missing: missingBindings(target, node, behaviour) }]+ : []+ })+}++beforeAll(async () => {+ const { ck, renderer } = await measuringRenderer()+ const built = await buildDemoGraph(renderer)+ // The .fig the app opens, without the shader stills: the editor draws those on open.+ const bytes = await exportFigFile(built, ck, renderer)+ graph = await readFigFile(new File([bytes.slice()], 'Demo.fig'))+ populateAllFigPages(graph)+})++describe('the demo document', () => {+ test('is one page of numbered chapters, top to bottom', () => {+ const [page, ...rest] = graph.getPages()+ expect(rest).toEqual([])+ const chapters = graph+ .getChildren(page.id)+ .filter((node) => node.type === 'SECTION')+ .sort((a, b) => a.y - b.y)+ expect(chapters.map((chapter) => chapter.name)).toEqual([+ '1 · Hello',+ '2 · Slots',+ '3 · Controls',+ '4 · Modes',+ '5 · Shaders',+ '6 · Code',+ '7 · Lint',+ '8 · Yours'+ ])+ // The layer list reads the first child first.+ expect(graph.getChildren(page.id)[0]?.name).toBe('1 · Hello')+ })++ test('keeps complete behaviours on the player controls', () => {+ const controls = behaviours(graph)expect(controls.map((control) => control.kind).sort()).toEqual(['button',- 'checkbox','slider',- 'switch',- 'tabs',- 'textField'+ 'toggle',+ 'toggle'])for (const control of controls) expect(control.missing).toEqual([])})++ test('keeps the covers its instances put in the artwork slot', () => {+ const owned = playerCovers(graph).filter((player) => player.owned)+ expect(owned.map((player) => player.cover)).toEqual([['FRAME:Cover'], ['FRAME:Cover']])+ expect(playerCovers(graph).filter((player) => !player.owned).length).toBeGreaterThan(0)+ })++ test('shows the light mode of the theme on one frame', () => {+ // Saving gives the collection and its modes Figma IDs; the names stay.+ const collection = [...graph.variableCollections.values()].find(+ (candidate) => candidate.name === 'Theme'+ )+ const light = [...graph.getAllNodes()].filter(+ (node) => node.name === 'Light' && Object.values(node.variableModes).length > 0+ )+ expect(light).toHaveLength(1)+ expect(collection?.modes.map((mode) => mode.name)).toEqual(['Dark', 'Light'])+ expect(Object.values(light[0].variableModes)).toEqual([+ collection?.modes.find((mode) => mode.name === 'Light')?.modeId+ ])+ })++ test('keeps a shader preset on every shader fill', () => {+ const shaders = [...graph.getAllNodes()].flatMap((node) => readShaderPaints(node))+ expect(shaders.length).toBeGreaterThanOrEqual(5)+ for (const shader of shaders) expect(shader.preset.components.length).toBeGreaterThan(0)+ })})diff --git a/tools/generate/demo/tests/typography.test.ts b/tools/generate/demo/tests/typography.test.tsdeleted file mode 100644index 168a42365..000000000--- a/tools/generate/demo/tests/typography.test.ts+++ /dev/null@@ -1,42 +0,0 @@-import { describe, expect, test } from 'bun:test'--import { createTypographySection } from '#demo/document/typography/section'--import { SceneGraph } from '@open-pencil/scene-graph'--describe('demo document', () => {- test('showcases OpenType features and native text decorations', async () => {- const graph = new SceneGraph()- const page = graph.addPage('Typography')-- await createTypographySection(graph, page.id)-- const nodes = [...graph.getAllNodes()]- const sample = (name: string) =>- nodes.find((node) => node.name === name && node.type === 'TEXT')-- expect(sample('Discretionary ligatures / DLIG ON')?.fontFeatures).toEqual([- { tag: 'DLIG', enabled: true }- ])- expect(sample('Discretionary ligatures / DLIG OFF')?.fontFeatures).toEqual([- { tag: 'DLIG', enabled: false }- ])- expect(sample('Tabular and proportional figures / TNUM ON · PNUM OFF')?.fontFeatures).toEqual([- { tag: 'TNUM', enabled: true },- { tag: 'PNUM', enabled: false }- ])-- expect(sample('Wavy underline')).toMatchObject({- textDecoration: 'UNDERLINE',- textDecorationStyle: 'WAVY',- textDecorationThickness: 1.6- })- expect(sample('Wavy underline')?.textDecorationFills[0]?.type).toBe('SOLID')- expect(sample('Dotted underline')).toMatchObject({- textDecoration: 'UNDERLINE',- textDecorationStyle: 'DOTTED',- textDecorationThickness: 2- })- expect(sample('Dotted underline')?.textDecorationFills[0]?.type).toBe('SOLID')- })-})