AI-native design editor. Open-source Figma alternative.
feat: create, fill, and edit slots (#862)
Danila Poyarkov7ad6475e2b9b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3a7ef3a81..a0801f71a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -43,10 +43,15 @@- Choose PPTX in the Export panel's format list, alongside PNG, JPG, WEBP, SVG, and PDF.- Let AI and MCP agents verify and replay their edits with diff tools: `diff_visual` returns a pixel diff of two rendered nodes with the changed region, and `diff_apply` applies a `diff_create` or `diff_show` patch, including moved, added, and removed children, only when every node still matches it. The built-in AI chat enables `diff_create`, `diff_jsx`, and `diff_visual` by default.- Compare designs from the terminal with `openpencil diff`: `create`, `jsx`, `show`, `apply`, and `visual` work on a file or the running app, and `diff files` compares two documents page by page and exits with status 1 when they differ.+- Create and fill slots as in Figma. **Create slot** turns a frame of a main component into a slot, or wraps other selected layers in a new one, and the Slots section sets its name, description, layer limits, and preferred components or removes it. In instances, drop, paste, or move layers into a slot, or add components from **Add instances** in the properties panel, which shows each slot as Default or Modified with its item count and limits; **Reset slot** brings back the component content and **Delete contents** empties it. Slots are outlined in pink on the canvas and marked in the layers panel, and parts of an instance outside its slots cannot be dropped into, grouped, wrapped, or deleted, as in Figma.+- Create and inspect slots from scripts run through `eval` and from AI and MCP tools, as in Figma: `component.createSlot()` adds a slot frame and its `SLOT` property, slot frames read `type: 'SLOT'` with `resetSlot()` and `limitViolations`, `appendChild`, `insertChild`, and `remove()` work inside slots and refuse the rest of an instance, and `addComponentProperty` and `editComponentProperty` take a `description` and `slotSettings`.- Control the running app from the CLI and MCP: `openpencil documents` opens, creates, saves, closes, and brings documents to the front, `openpencil undo` and `redo` step back through changes made through the CLI and MCP, refusing to revert edits made in the editor, and `openpencil settings get` and `set` read and change theme, language, animations, snapping, canvas rendering, recovery, chat, and design check settings. MCP clients get the same through `activate_document`, `undo`, `redo`, `get_settings`, and `update_settings`; credentials, models, MCP connections, storage, and tool access stay out of reach. `openpencil tool list`, `describe`, and `call` run any MCP tool from the shell, against the running app or headlessly on a file.### Changed+- Give popovers, menus, dropdowns, and pickers one look and motion: the same rounded panel with a thin outline that reads in light and dark themes, a short fade and grow from the side they open on, and an immediate close; with reduced motion they appear at once.+- Add and remove items the same way across the properties panel: a section's + adds an item and a row's − removes it, now including grid columns and rows and variant properties. The + of a component set adds Property 1 ready to rename instead of showing a form, and a variant is removed with Delete like any layer.+- Pick variables, shared styles, and swap components from one searchable list that groups preferred components first and works with the keyboard.- Recommend the latest models in the AI model picker: Claude Sonnet 5.5 (the new Anthropic and OpenRouter default), Claude Opus 5.5, GPT-6.1 Sol (the new OpenAI default), GPT-6 Astra, and GPT-6 Luna, and replace the free OpenRouter models OpenRouter retired with Qwen3.8 27B and Gemma 4 31B. Saved profiles keep the model they chose.- The Linux AppImage no longer bundles `xdg-open`; opening links relies on the system's `xdg-utils`, as most desktop distributions provide.- With nothing selected, the Code tab explains that it shows the selection's code and offers Write JSX for new layers, instead of showing a template frame that looked like a real layer.@@ -60,6 +65,10 @@### Fixed+- Keep the canvas context menu open when you right-click again right after closing it, which could close it again at once, especially with reduced motion.+- Show and edit the component properties of an instance nested inside another instance; they were missing because the nested instance was read as its own component.+- Read and set `componentPropertyReferences` in the plugin API with property keys such as `Label#prop:1a2b`, as `componentPropertyDefinitions` lists them and Figma uses them, instead of internal property ids.+- Open Figma files that use slots with each instance's own slot content instead of its component's default, keep slot properties, their settings, and instance content when saving back to `.fig`, and keep an instance's slot content, and that of instances nested in it with the same names, when you switch its variant or swap it.- Report a failed MCP `save_file` or `new_document` save as an error instead of success, and ask for a path rather than opening a Save dialog when the document has never been saved.- Undo layers that MCP clients and the CLI create, delete, or rearrange in the running app, including `render` and `eval` changes, with Edit → Undo. Previously only their property edits were undoable.- Save a `.fig` file that was opened and not edited yet. In the app the save never finished, and MCP `save_file` timed out without writing the file.@@ -67,7 +76,6 @@- Give paints set through the plugin API, `eval`, and AI and MCP scripts an opacity of 1 and make them visible when the script leaves those out, as Figma does. Such paints were stored without them, which the Design panel could not show.- Show variable-bound colours and numbers correctly when a `.fig` exported from OpenPencil opens in Figma. Figma draws the value a bound field stores until something makes it resolve the variable again, and exports stored the colour from before the binding, so a bound fill appeared in its old colour. Each bound field is now written as it resolves in its layer's mode, or in the collection's default mode when the layer sets none.- Give strokes the same paints fills have. A `.fig` file's gradient or image stroke imported as opaque black, because a stroke could hold only one color; it now keeps its stops, transform, and image, and renders and saves the way the same paint does as a fill. The stroke panel opens the fill picker, so you can give a stroke a gradient or an image and its weight, align, cap, join, and dashes stay as they were ([#797](https://github.com/open-pencil/open-pencil/issues/797)).-- Open Figma files that use slots with each instance's own slot content instead of its component's default, keep slot properties, their settings, and instance content when saving back to `.fig`, and keep an instance's slot content when you switch its variant.- Stop showing a “signal is aborted without reason” error when you switch pages again before the previous page has finished loading.- Export layers with two shadows as one `effects` prop instead of repeating the `shadow` attribute, background blurs as `backgroundBlur` instead of a layer blur, hidden children with `visible={false}` instead of leaving them out, and per-corner radii even when the uniform radius is 0.- Apply `strokeAlign`, `strokeDash`, `minH`, and `maxH` in design JSX, which were accepted but ignored, and make `minW` and `maxW` set the layer's minimum and maximum width rather than only clamping its initial width.diff --git a/desktop/generated/menu.json b/desktop/generated/menu.jsonindex 6399d672d..059e0d557 100644--- a/desktop/generated/menu.json+++ b/desktop/generated/menu.json@@ -370,6 +370,10 @@"id": "selection.createInstance","label": "Create Instance"},+ {+ "id": "selection.createSlot",+ "label": "Create Slot"+ },{"id": "selection.goToMainComponent","label": "Go to Main Component"diff --git a/packages/core/src/canvas/labels/selection.ts b/packages/core/src/canvas/labels/selection.tsindex 01a198268..17552bf3a 100644--- a/packages/core/src/canvas/labels/selection.ts+++ b/packages/core/src/canvas/labels/selection.ts@@ -112,7 +112,7 @@ export function drawSingleSelectionSize(sizeFont: NonNullable<SkiaRenderer['sizeFont']>): void {const sizeText = `${Math.round(node.width)} × ${Math.round(node.height)}`- const pillColor = r.isComponentType(node.type) ? r.compColor() : r.selColor()+ const pillColor = r.outlineColor(node)const transform = frameLabelPlacement(node, graph, overlays.rotationPreview, {x: 0.5,y: 1diff --git a/packages/core/src/canvas/overlays/selection.ts b/packages/core/src/canvas/overlays/selection.tsindex cf06eed8a..58874bd03 100644--- a/packages/core/src/canvas/overlays/selection.ts+++ b/packages/core/src/canvas/overlays/selection.ts@@ -1,5 +1,6 @@import type { Canvas } from 'canvaskit-wasm'+import { slotPropertyId } from '@open-pencil/scene-graph'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { computeBounds, rotatedCorners } from '@open-pencil/scene-graph/geometry'import Matrix from '@open-pencil/scene-graph/matrix'@@ -33,7 +34,7 @@ export function drawHoverHighlight(const node = hoveredNodeId ? graph.getNode(hoveredNodeId) : undefinedif (!node) returnr.auxStroke.setStrokeWidth((node.type === 'SECTION' ? SECTION_HOVER_STROKE_WIDTH : 1) / r.zoom)- r.auxStroke.setColor(r.isComponentType(node.type) ? r.compColor() : r.selColor())+ r.auxStroke.setColor(r.outlineColor(node))r.auxStroke.setPathEffect(null)canvas.save()canvas.concat(createSceneGeometry(graph, preview).screenMatrix(node, r))@@ -116,8 +117,7 @@ function drawSingleSelection(// is suppressed (see drawTextEditOverlay) since it can't follow the path.if (editing && !isPathText) return- const useComponentColor = r.isComponentType(node.type)- r.selectionPaint.setColor(useComponentColor ? r.compColor() : r.selColor())+ r.selectionPaint.setColor(r.outlineColor(node))r.selectionPaint.setStrokeWidth(1 / r.zoom)const rotation = node.rotation@@ -155,8 +155,7 @@ export function drawSelection(const node = graph.getNode(id)if (!node) continue- const useComponentColor = r.isComponentType(node.type)- r.selectionPaint.setColor(useComponentColor ? r.compColor() : r.selColor())+ r.selectionPaint.setColor(r.outlineColor(node))r.selectionPaint.setStrokeWidth(1 / r.zoom)const rotation = node.rotation@@ -400,6 +399,8 @@ export function drawParentFrameOutlines(const parent = graph.getNode(node.parentId)if (!parent || parent.type === 'CANVAS') continueif (drawn.has(parent.id) || selectedIds.has(parent.id)) continue+ // Slots get their own dashed outline (overlays/slots.ts).+ if (slotPropertyId(parent)) continueconst grandparent = parent.parentId ? graph.getNode(parent.parentId) : nullif (!grandparent || grandparent.type === 'CANVAS') continuediff --git a/packages/core/src/canvas/overlays/slots.ts b/packages/core/src/canvas/overlays/slots.tsnew file mode 100644index 000000000..93185bff6--- /dev/null+++ b/packages/core/src/canvas/overlays/slots.ts@@ -0,0 +1,70 @@+import type { Canvas } from 'canvaskit-wasm'++import { instanceSlotFrames, slotPropertyId } from '@open-pencil/scene-graph'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import type { SkiaRenderer } from '#core/canvas/renderer'+import { SLOT_EMPTY_FILL_ALPHA } from '#core/constants'+import { createSceneGeometry, type RotationPreview } from '#core/geometry'++const SLOT_DASH = 4++/**+ * Slots worth outlining for these nodes: every slot of a component or instance, and the slot+ * a layer sits in. Figma outlines them in pink so content can be placed without hunting.+ */+function focusedSlots(graph: SceneGraph, ids: Iterable<string>): Map<string, SceneNode> {+ const slots = new Map<string, SceneNode>()+ for (const id of ids) {+ const node = graph.getNode(id)+ if (!node) continue+ if (node.type === 'INSTANCE' || node.type === 'COMPONENT')+ for (const frame of instanceSlotFrames(graph, node)) slots.set(frame.id, frame)+ let ancestor = node.parentId ? graph.getNode(node.parentId) : undefined+ while (ancestor && ancestor.type !== 'CANVAS') {+ if (slotPropertyId(ancestor)) {+ slots.set(ancestor.id, ancestor)+ break+ }+ if (ancestor.type === 'INSTANCE' || ancestor.type === 'COMPONENT') break+ ancestor = ancestor.parentId ? graph.getNode(ancestor.parentId) : undefined+ }+ }+ return slots+}++/** Dashed pink outlines around the slots of the hovered and selected layers; empty slots tinted. */+export function drawSlotOutlines(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ selectedIds: Set<string>,+ hoveredNodeId?: string | null,+ preview?: RotationPreview | null+): void {+ const ids = hoveredNodeId ? [...selectedIds, hoveredNodeId] : selectedIds+ const slots = focusedSlots(graph, ids)+ for (const id of selectedIds) slots.delete(id)+ if (hoveredNodeId) slots.delete(hoveredNodeId)+ if (slots.size === 0) return++ const geometry = createSceneGeometry(graph, preview)+ const dash = r.ck.PathEffect.MakeDash([SLOT_DASH / r.zoom, SLOT_DASH / r.zoom], 0)+ r.auxStroke.setStrokeWidth(1 / r.zoom)+ r.auxStroke.setColor(r.slotColor())+ r.auxStroke.setPathEffect(dash)+ r.auxFill.setColor(r.slotColor(SLOT_EMPTY_FILL_ALPHA))+ try {+ for (const frame of slots.values()) {+ canvas.save()+ canvas.concat(geometry.screenMatrix(frame, r))+ const rect = r.ck.LTRBRect(0, 0, frame.width, frame.height)+ if (frame.childIds.length === 0) canvas.drawRect(rect, r.auxFill)+ canvas.drawRect(rect, r.auxStroke)+ canvas.restore()+ }+ } finally {+ r.auxStroke.setPathEffect(null)+ dash.delete()+ }+}diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex cd63f7c64..4d8c2bc0c 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -1,5 +1,6 @@import { toUint8Array } from 'js-base64'+import { slotPropertyId } from '@open-pencil/scene-graph'import type { SceneNode, SceneGraph, Fill, Stroke } from '@open-pencil/scene-graph'import type { RenderColorSpace, ResolvedRenderColor } from '@open-pencil/scene-graph/color'import type { Color, Rect, Vector } from '@open-pencil/scene-graph/primitives'@@ -9,6 +10,7 @@ import type { SnapGuide } from '@open-pencil/scene-graph/snap'import {SELECTION_COLOR,COMPONENT_COLOR,+ SLOT_COLOR,CANVAS_BG_COLOR,DEFAULT_FONT_SIZE,COMPONENT_SET_DASH,@@ -413,6 +415,16 @@ export class SkiaRenderer {return this.ck.Color4f(COMPONENT_COLOR.r, COMPONENT_COLOR.g, COMPONENT_COLOR.b, alpha)}+ slotColor(alpha = 1) {+ return this.ck.Color4f(SLOT_COLOR.r, SLOT_COLOR.g, SLOT_COLOR.b, alpha)+ }++ /** The outline colour for a node: pink for slots, purple for components, blue otherwise. */+ outlineColor(node: SceneNode) {+ if (slotPropertyId(node)) return this.slotColor()+ return this.isComponentType(node.type) ? this.compColor() : this.selColor()+ }+isComponentType(type: string): boolean {return type === 'COMPONENT' || type === 'COMPONENT_SET' || type === 'INSTANCE'}diff --git a/packages/core/src/canvas/renderer/overlay-pass.ts b/packages/core/src/canvas/renderer/overlay-pass.tsindex 1821874f2..e7d92d0ad 100644--- a/packages/core/src/canvas/renderer/overlay-pass.ts+++ b/packages/core/src/canvas/renderer/overlay-pass.ts@@ -7,6 +7,7 @@ import { drawIssueHighlight, drawIssueMarkers } from '#core/canvas/issues/draw'import { layoutIssueMarkers } from '#core/canvas/issues/layout'import { drawMeasurementSegment } from '#core/canvas/overlays/measurement'import { drawCodeFocus } from '#core/canvas/overlays/selection'+import { drawSlotOutlines } from '#core/canvas/overlays/slots'import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'import { RULER_SIZE } from '#core/constants'@@ -91,6 +92,8 @@ export function drawOverlayPass(? null: overlays.hoveredNodeIddrawCodeFocus(r, canvas, graph, overlays.codeFocusNodeId, overlays.rotationPreview)+ if (!measuring)+ drawSlotOutlines(r, canvas, graph, selectedIds, hoveredNodeId, overlays.rotationPreview)r.drawHoverHighlight(canvas, graph, hoveredNodeId, overlays.rotationPreview)drawIssueHighlight(r, canvas, graph, overlays.designIssues?.highlight, overlays.rotationPreview)r.drawEnteredContainer(canvas, graph, overlays.enteredContainerId, overlays.rotationPreview)diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.tsindex 444fd254a..c85f0c3a5 100644--- a/packages/core/src/constants.ts+++ b/packages/core/src/constants.ts@@ -9,6 +9,9 @@ export const TRANSPARENT: Color = { r: 0, g: 0, b: 0, a: 0 }export const DEFAULT_SHADOW_COLOR: Color = { r: 0, g: 0, b: 0, a: 0.25 }export const SELECTION_COLOR = { r: 0.23, g: 0.51, b: 0.96, a: 1 } satisfies Colorexport const COMPONENT_COLOR = { r: 0.592, g: 0.278, b: 1, a: 1 } satisfies Color+/** Slot frames and their outlines, `#f24bbc` like the app's `--color-slot`. */+export const SLOT_COLOR = { r: 0.949, g: 0.294, b: 0.737, a: 1 } satisfies Color+export const SLOT_EMPTY_FILL_ALPHA = 0.08export const SNAP_COLOR = { r: 1.0, g: 0.0, b: 0.56, a: 1 } satisfies Colorexport const MEASUREMENT_COLOR = { r: 0.949, g: 0.282, b: 0.133, a: 1 } satisfies Colorexport const MEASUREMENT_PILL_PADDING_X = 5diff --git a/packages/core/src/editor/bridges/components.ts b/packages/core/src/editor/bridges/components.tsindex 329b7d560..e4fd6756a 100644--- a/packages/core/src/editor/bridges/components.ts+++ b/packages/core/src/editor/bridges/components.ts@@ -32,6 +32,10 @@ export function createComponentBridge(goToMainComponent: () =>components.goToMainComponent(selection.getSelectedNode(), pages.switchPage),getComponentSetPropertyDefs: components.getComponentSetPropertyDefs,+ createSlot: () => components.createSlot(selection.getSelectedNodes()),+ convertToSlot: components.convertToSlot,+ updateSlot: components.updateSlot,+ removeSlot: components.removeSlot,addPropertyDefinition: components.addPropertyDefinition,removePropertyDefinition: components.removePropertyDefinition,renamePropertyDefinition: components.renamePropertyDefinition,@@ -51,6 +55,9 @@ export function createComponentBridge(removeVariant: components.removeVariant,getInstanceComponentPropertyDefinitions: components.getInstanceComponentPropertyDefinitions,getInstanceComponentPropertyValue: components.getInstanceComponentPropertyValue,- setInstanceComponentProperty: components.setInstanceComponentProperty+ setInstanceComponentProperty: components.setInstanceComponentProperty,+ resetSlot: components.resetSlot,+ clearSlot: components.clearSlot,+ addInstanceToSlot: components.addInstanceToSlot}}diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.tsindex 2c736957f..e0841aecc 100644--- a/packages/core/src/editor/clipboard.ts+++ b/packages/core/src/editor/clipboard.ts@@ -18,6 +18,7 @@ import { replaceTargetsWithCreated, selectedReplacementTargets } from './clipboaimport { resolvePasteTarget } from './clipboard/paste-target'import { createClipboardPlacementActions } from './clipboard/placement'import { collectSubtrees, restoreSubtree, snapshotSubtree } from './clipboard/subtree-history'+import { acceptsChildren, prepareSlotEdits } from './components/slots'import type { EditorContext } from './types'type PasteOptions = {@@ -29,6 +30,8 @@ export function createClipboardActions(ctx: EditorContext) {const prevSelection = new Set(ctx.state.selectedIds)const selectedSet = new Set(selectedNodes.map((n) => n.id))const topLevel = selectedNodes.filter((n) => !n.parentId || !selectedSet.has(n.parentId))+ const parents = topLevel.map((node) => node.parentId ?? ctx.state.currentPageId)+ if (!prepareSlotEdits(ctx, parents)) returnconst newRootIds: string[] = []const allSnapshots = new Map<string, SceneNode>()@@ -137,12 +140,9 @@ export function createClipboardActions(ctx: EditorContext) {async function pasteFromHTML(html: string, cursorPos?: Vector, options: PasteOptions = {}) {const openPencil = parseOpenPencilClipboard(html)if (openPencil) {- const created = pasteOpenPencilNodes(- openPencil.nodes,- openPencil.images,- [],- cursorPos,- options+ // One undo step for the paste and any slot it claims.+ const created = ctx.undo.runBatch('Paste', () =>+ pasteOpenPencilNodes(openPencil.nodes, openPencil.images, [], cursorPos, options))await fontActions.loadFontsForNodes(created)return@@ -150,38 +150,45 @@ export function createClipboardActions(ctx: EditorContext) {const figma = await parseFigmaClipboard(html)if (figma) {- const prevSelection = new Set(ctx.state.selectedIds)- const replacementTargets = options.replaceSelection ? selectedReplacementTargets(ctx) : []- const pasteTarget = replacementTargets[0]?.parentId ?? resolvePasteTarget(ctx)- const operation = prepareClipboardImport(figma.nodes, ctx.graph, pasteTarget, figma.blobs)- let deliveryError: CommittedGraphEventError | undefined- try {- operation.commit()- } catch (error) {- if (!(error instanceof CommittedGraphEventError)) throw error- deliveryError = error- }- const created = operation.plan.rootIds- if (created.length === 0) return-- if (replacementTargets.length > 0) {- replaceTargetsWithCreated(- ctx,- placementActions.centerNodesAt,- created,- replacementTargets,- prevSelection,- operation- )- } else {- const { width: viewW, height: viewH } = ctx.getViewportSize()- const cx = cursorPos?.x ?? (-ctx.state.panX + viewW / 2) / ctx.state.zoom- const cy = cursorPos?.y ?? (-ctx.state.panY + viewH / 2) / ctx.state.zoom- placementActions.centerNodesAt(created, cx, cy)- computeAllLayouts(ctx.graph, ctx.state.currentPageId)- ctx.setSelectedIds(new Set(created))- pushCreatedNodesUndo(created, prevSelection, 'Paste', operation)- }+ // One undo step for the paste and any slot it claims.+ const pasted = ctx.undo.runBatch('Paste', () => {+ const prevSelection = new Set(ctx.state.selectedIds)+ const replacementTargets = options.replaceSelection ? selectedReplacementTargets(ctx) : []+ const pasteTarget = replacementTargets[0]?.parentId ?? resolvePasteTarget(ctx)+ if (!prepareSlotEdits(ctx, [pasteTarget])) return null+ const operation = prepareClipboardImport(figma.nodes, ctx.graph, pasteTarget, figma.blobs)+ let deliveryError: CommittedGraphEventError | undefined+ try {+ operation.commit()+ } catch (error) {+ if (!(error instanceof CommittedGraphEventError)) throw error+ deliveryError = error+ }+ const created = operation.plan.rootIds+ if (created.length === 0) return null++ if (replacementTargets.length > 0) {+ replaceTargetsWithCreated(+ ctx,+ placementActions.centerNodesAt,+ created,+ replacementTargets,+ prevSelection,+ operation+ )+ } else {+ const { width: viewW, height: viewH } = ctx.getViewportSize()+ const cx = cursorPos?.x ?? (-ctx.state.panX + viewW / 2) / ctx.state.zoom+ const cy = cursorPos?.y ?? (-ctx.state.panY + viewH / 2) / ctx.state.zoom+ placementActions.centerNodesAt(created, cx, cy)+ computeAllLayouts(ctx.graph, ctx.state.currentPageId)+ ctx.setSelectedIds(new Set(created))+ pushCreatedNodesUndo(created, prevSelection, 'Paste', operation)+ }+ return { created, deliveryError }+ })+ if (!pasted) return+ const { created, deliveryError } = pastedif (deliveryError) throw deliveryErrorawait Promise.all([@@ -219,6 +226,7 @@ export function createClipboardActions(ctx: EditorContext) {}const pasteTarget = replacementTargets[0]?.parentId ?? resolvePasteTarget(ctx)+ if (!prepareSlotEdits(ctx, [pasteTarget])) return createdconst dependencyRootIds: string[] = []for (const dependency of dependencies)dependencyRootIds.push(createNodeTree(dependency, ctx.state.currentPageId))@@ -311,10 +319,16 @@ export function createClipboardActions(ctx: EditorContext) {}/**- * Deletes layers with their children as one undo step, skipping locked ones. Deleted layers- * leave the selection, and undo restores the selection from before.+ * Deletes layers with their children as one undo step, skipping locked ones and, as in Figma,+ * layers of an instance outside its slots. Deleted layers leave the selection, and undo+ * restores the selection from before.*/function deleteNodes(nodeIds: Iterable<string>, nextSelection?: ReadonlySet<string>) {+ // One undo step for the delete and any slot it claims.+ ctx.undo.runBatch('Delete', () => deleteLayers(nodeIds, nextSelection))+ }++ function deleteLayers(nodeIds: Iterable<string>, nextSelection?: ReadonlySet<string>) {const entries: Array<{id: stringparentId: string@@ -325,11 +339,17 @@ export function createClipboardActions(ctx: EditorContext) {const node = ctx.graph.getNode(id)if (!node || node.locked) continueconst parentId = node.parentId ?? ctx.state.currentPageId+ if (!acceptsChildren(ctx, parentId)) continueconst parent = ctx.graph.getNode(parentId)const index = parent?.childIds.indexOf(id) ?? -1entries.push({ id, parentId, index, subtree: snapshotSubtree(ctx.graph, id) })}if (entries.length === 0) return+ prepareSlotEdits(+ ctx,+ entries.map((entry) => entry.parentId)+ )+ for (const entry of entries) entry.subtree = snapshotSubtree(ctx.graph, entry.id)const relayoutParents = () => {for (const parentId of new Set(entries.map((entry) => entry.parentId))) {diff --git a/packages/core/src/editor/clipboard/paste-target.ts b/packages/core/src/editor/clipboard/paste-target.tsindex 6f69a0520..ab97a1498 100644--- a/packages/core/src/editor/clipboard/paste-target.ts+++ b/packages/core/src/editor/clipboard/paste-target.ts@@ -1,9 +1,17 @@import { CONTAINER_TYPES } from '@open-pencil/scene-graph/node-defaults'+import { acceptingParent } from '#core/editor/components/slots'import type { EditorContext } from '#core/editor/types'-/** Where ordinary paste and file drops insert; replacement paste uses its target's parent. */+/**+ * Where ordinary paste and file drops insert; replacement paste uses its target's parent.+ * Never the locked part of an instance, only its slots.+ */export function resolvePasteTarget(ctx: Pick<EditorContext, 'graph' | 'state'>): string {+ return acceptingParent(ctx, pasteTargetCandidate(ctx))+}++function pasteTargetCandidate(ctx: Pick<EditorContext, 'graph' | 'state'>): string {if (ctx.state.enteredContainerId) return ctx.state.enteredContainerIdconst ids = [...ctx.state.selectedIds]if (ids.length !== 1) return ctx.state.currentPageIddiff --git a/packages/core/src/editor/components.ts b/packages/core/src/editor/components.tsindex 50070c37d..ae4b9381f 100644--- a/packages/core/src/editor/components.ts+++ b/packages/core/src/editor/components.ts@@ -6,6 +6,8 @@ import { randomHex } from '#core/random'import { createComponentFocusActions } from './components/focus'import { createComponentInstanceActions } from './components/instances'import { createComponentPropertyActions } from './components/properties'+import { createSlotActions } from './components/slots'+import { createSlotAuthoringActions } from './components/slots/authoring'import { createVariantActions } from './components/variants'import type { EditorContext } from './types'@@ -85,6 +87,8 @@ export function createComponentActions(ctx: EditorContext) {...instanceActions,...focusActions,...variantActions,- ...componentPropertyActions+ ...componentPropertyActions,+ ...createSlotActions(ctx),+ ...createSlotAuthoringActions(ctx)}}diff --git a/packages/core/src/editor/components/instances.ts b/packages/core/src/editor/components/instances.tsindex 40c6c19a9..92ff10d4e 100644--- a/packages/core/src/editor/components/instances.ts+++ b/packages/core/src/editor/components/instances.ts@@ -3,6 +3,7 @@ import type { SceneNode, Vector } from '@open-pencil/scene-graph'import { getAxisAlignedWorldBounds, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'import Matrix from '@open-pencil/scene-graph/matrix'+import { prepareSlotEdits } from '#core/editor/components/slots'import type { EditorContext } from '#core/editor/types'type InstanceCreateSnapshot = Partial<SceneNode> & { id: string }@@ -56,7 +57,7 @@ function alignInstanceWorldBounds(}export function createComponentInstanceActions(ctx: EditorContext) {- function createInstanceFromComponent(+ function createInstance(componentId: string,x?: number,y?: number,@@ -64,6 +65,7 @@ export function createComponentInstanceActions(ctx: EditorContext) {) {const component = ctx.graph.getNode(componentId)if (component?.type !== 'COMPONENT') return null+ if (!prepareSlotEdits(ctx, [parentId])) return nullconst previousSelection = new Set(ctx.state.selectedIds)const defaultPlacement = defaultInstancePlacement(ctx, component, parentId)@@ -94,6 +96,16 @@ export function createComponentInstanceActions(ctx: EditorContext) {return instanceId}+ /** Place an instance of a component; claiming a slot it lands in is part of the same undo step. */+ function createInstanceFromComponent(+ componentId: string,+ x?: number,+ y?: number,+ parentId = ctx.state.currentPageId+ ) {+ return ctx.undo.runBatch('Create instance', () => createInstance(componentId, x, y, parentId))+ }+function detachInstance(selectedNode: SceneNode | undefined) {if (selectedNode?.type !== 'INSTANCE') returndiff --git a/packages/core/src/editor/components/slots/authoring.ts b/packages/core/src/editor/components/slots/authoring.tsnew file mode 100644index 000000000..57877064a--- /dev/null+++ b/packages/core/src/editor/components/slots/authoring.ts@@ -0,0 +1,140 @@+import {+ canCreateSlot,+ createSlotProperty,+ removeComponentProperty,+ slotOwner,+ slotPropertyId,+ updateSlotProperty,+ type SceneNode,+ type SlotPropertyPatch+} from '@open-pencil/scene-graph'++import { wrapInAutoLayout } from '#core/editor/structure/auto-layout-wrap'+import type { EditorContext } from '#core/editor/types'+import { randomHex } from '#core/random'++import { recordSubtreeEdit } from './history'++type PropertyFields = Pick<+ SceneNode,+ 'componentPropertyDefinitions' | 'componentPropertyReferences'+>++function propertyFields(ctx: EditorContext, ids: readonly string[]): Map<string, PropertyFields> {+ const fields = new Map<string, PropertyFields>()+ for (const id of ids) {+ const node = ctx.graph.getNode(id)+ if (!node) continue+ fields.set(id, {+ componentPropertyDefinitions: structuredClone(node.componentPropertyDefinitions),+ componentPropertyReferences: structuredClone(node.componentPropertyReferences)+ })+ }+ return fields+}++/**+ * Run a change to a component's slot definitions as one undo step. The component's own+ * definitions and its frames' bindings are restored field by field; instances follow them on+ * sync, so only the instances in `instanceIds`, whose content the change drops, are recorded.+ */+function recordDefinitionEdit(+ ctx: EditorContext,+ label: string,+ nodeIds: readonly string[],+ instanceIds: readonly string[],+ mutate: () => void+): void {+ const apply = (fields: Map<string, PropertyFields>) => {+ for (const [id, values] of fields) ctx.graph.updateNode(id, structuredClone(values))+ ctx.requestRender()+ }+ ctx.undo.runBatch(label, () => {+ const before = propertyFields(ctx, nodeIds)+ if (instanceIds.length) recordSubtreeEdit(ctx, label, instanceIds, mutate)+ else mutate()+ const after = propertyFields(ctx, nodeIds)+ ctx.requestRender()+ ctx.undo.push({ label, forward: () => apply(after), inverse: () => apply(before) })+ })+}++/** Frames bound to this slot property in the component that defines it. */+function boundFrames(ctx: EditorContext, owner: SceneNode, propertyId: string): SceneNode[] {+ const frames: SceneNode[] = []+ const visit = (node: SceneNode): void => {+ for (const child of ctx.graph.getChildren(node.id)) {+ if (slotPropertyId(child) === propertyId) frames.push(child)+ if (child.type !== 'INSTANCE') visit(child)+ }+ }+ visit(owner)+ return frames+}++export function createSlotAuthoringActions(ctx: EditorContext) {+ /** Make a frame of a main component a slot. */+ function convertToSlot(frameId: string): string | null {+ const frame = ctx.graph.getNode(frameId)+ const owner = frame && canCreateSlot(ctx.graph, frame) ? slotOwner(ctx.graph, frame) : undefined+ if (!frame || !owner) return null+ const id = `prop:${randomHex(8)}`+ recordDefinitionEdit(ctx, 'Create slot', [owner.id, frame.id], [], () => {+ createSlotProperty(ctx.graph, frame.id, id)+ })+ return id+ }++ /**+ * Turn the selection into a slot, as Figma's Create slot does: a selected frame of a main+ * component becomes one; other layers are first wrapped in a new auto layout frame.+ */+ function createSlot(nodes: SceneNode[]): string | null {+ const first = nodes.at(0)+ if (!first) return null+ if (nodes.length === 1 && canCreateSlot(ctx.graph, first)) return convertToSlot(first.id)+ if (!slotOwner(ctx.graph, first)) return null+ return ctx.undo.runBatch('Create slot', () => {+ const frameId = wrapInAutoLayout(ctx, nodes)+ if (!frameId) return null+ ctx.graph.updateNode(frameId, { name: 'Slot' })+ return convertToSlot(frameId)+ })+ }++ /** Change a slot property's name, description, preferred components, or limits. */+ function updateSlot(ownerId: string, propertyId: string, patch: SlotPropertyPatch): void {+ recordDefinitionEdit(ctx, 'Edit slot', [ownerId], [], () => {+ updateSlotProperty(ctx.graph, ownerId, propertyId, patch)+ })+ }++ /**+ * Remove a slot property; its frames become ordinary frames again and instances go back to+ * the component's content.+ */+ function removeSlot(ownerId: string, propertyId: string): void {+ const owner = ctx.graph.getNode(ownerId)+ if (!owner) return+ const frames = boundFrames(ctx, owner, propertyId)+ const owning = [...ctx.graph.getAllNodes()]+ .filter(+ (node) =>+ node.type === 'INSTANCE' &&+ node.componentId === owner.id &&+ Object.hasOwn(node.componentPropertyAssignments, propertyId)+ )+ .map((instance) => instance.id)+ recordDefinitionEdit(+ ctx,+ 'Remove slot',+ [owner.id, ...frames.map((frame) => frame.id)],+ owning,+ () => {+ removeComponentProperty(ctx.graph, owner.id, propertyId)+ }+ )+ }++ return { createSlot, convertToSlot, updateSlot, removeSlot }+}diff --git a/packages/core/src/editor/components/slots/history.ts b/packages/core/src/editor/components/slots/history.tsnew file mode 100644index 000000000..32ce242bf--- /dev/null+++ b/packages/core/src/editor/components/slots/history.ts@@ -0,0 +1,44 @@+import type { SceneNode } from '@open-pencil/scene-graph'++import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'+import type { EditorContext } from '#core/editor/types'++/** Put back a recorded subtree in place of the live one, at the same position. */+function replaceSubtree(+ ctx: Pick<EditorContext, 'graph'>,+ rootId: string,+ snapshot: Map<string, SceneNode>+): void {+ const root = snapshot.get(rootId)+ const parentId = root?.parentId+ if (!root || !parentId) return+ const index = ctx.graph.getNode(parentId)?.childIds.indexOf(rootId) ?? -1+ ctx.graph.deleteNode(rootId)+ restoreSubtree(ctx.graph, root, parentId, snapshot)+ if (index >= 0) ctx.graph.insertChildAt(rootId, parentId, index)+}++/**+ * Run a slot edit as one undo step that restores whole subtrees: an instance whose slot+ * content changes, or a component and its instances when a slot is created or removed. Slot+ * edits unlink and recreate layers, which per-field undo cannot express.+ */+export function recordSubtreeEdit(+ ctx: EditorContext,+ label: string,+ rootIds: string | readonly string[],+ mutate: () => void+): void {+ const roots = typeof rootIds === 'string' ? [rootIds] : rootIds+ const before = roots.map((id) => snapshotSubtree(ctx.graph, id))+ mutate()+ const after = roots.map((id) => snapshotSubtree(ctx.graph, id))+ const apply = (snapshots: Map<string, SceneNode>[]) => {+ for (const [index, id] of roots.entries()) replaceSubtree(ctx, id, snapshots[index])+ for (const id of roots) ctx.runLayoutForNode(id)+ ctx.requestRender()+ }+ for (const id of roots) ctx.runLayoutForNode(id)+ ctx.requestRender()+ ctx.undo.push({ label, forward: () => apply(after), inverse: () => apply(before) })+}diff --git a/packages/core/src/editor/components/slots/index.ts b/packages/core/src/editor/components/slots/index.tsnew file mode 100644index 000000000..80b3680f2--- /dev/null+++ b/packages/core/src/editor/components/slots/index.ts@@ -0,0 +1,97 @@+import {+ claimSlotContent,+ clearSlotContent,+ ownsSlotContent,+ resetSlotContent,+ slotScope,+ type SlotScope+} from '@open-pencil/scene-graph'++import type { EditorContext } from '#core/editor/types'++import { recordSubtreeEdit } from './history'++type InstanceSlot = Extract<SlotScope, { kind: 'slot' }>++/**+ * Check every parent a structural edit touches. Returns false when one is a locked part of+ * an instance; otherwise claims each untouched slot first, so the edit lands in content the+ * instance owns. Call it before mutating, inside the edit's undo batch.+ */+export function prepareSlotEdits(ctx: EditorContext, parentIds: Iterable<string>): boolean {+ const slots = new Map<string, InstanceSlot>()+ for (const parentId of parentIds) {+ const scope = slotScope(ctx.graph, parentId)+ if (scope.kind === 'locked') return false+ if (scope.kind === 'slot') slots.set(scope.frame.id, scope)+ }+ for (const scope of slots.values()) {+ if (ownsSlotContent(ctx.graph, scope.frame, scope.propertyId)) continue+ recordSubtreeEdit(ctx, 'Edit slot', scope.instance.id, () => claimSlotContent(ctx.graph, scope))+ }+ return true+}++/** Whether layers may be added to or removed from this parent at all. */+export function acceptsChildren(ctx: Pick<EditorContext, 'graph'>, parentId: string): boolean {+ return slotScope(ctx.graph, parentId).kind !== 'locked'+}++/** The parent itself, or the nearest one outside the locked part of an instance. */+export function acceptingParent(ctx: Pick<EditorContext, 'graph'>, parentId: string): string {+ let id = parentId+ for (;;) {+ const scope = slotScope(ctx.graph, id)+ if (scope.kind !== 'locked' || !scope.instance.parentId) return id+ id = scope.instance.parentId+ }+}++export function createSlotActions(ctx: EditorContext) {+ function slotAt(frameId: string): InstanceSlot | undefined {+ const scope = slotScope(ctx.graph, frameId)+ return scope.kind === 'slot' && scope.frame.id === frameId ? scope : undefined+ }++ function resetSlot(frameId: string): void {+ const scope = slotAt(frameId)+ if (!scope) return+ recordSubtreeEdit(ctx, 'Reset slot', scope.instance.id, () =>+ resetSlotContent(ctx.graph, scope)+ )+ }++ function clearSlot(frameId: string): void {+ const scope = slotAt(frameId)+ if (!scope) return+ recordSubtreeEdit(ctx, 'Delete slot contents', scope.instance.id, () =>+ clearSlotContent(ctx.graph, scope)+ )+ }++ /** Append an instance of `componentId` to the slot and select it. */+ function addInstanceToSlot(frameId: string, componentId: string): string | null {+ const scope = slotAt(frameId)+ if (!scope || ctx.graph.getNode(componentId)?.type !== 'COMPONENT') return null+ const previousSelection = new Set(ctx.state.selectedIds)+ const created: { id: string | null } = { id: null }+ ctx.undo.runBatch('Add instance', () => {+ recordSubtreeEdit(ctx, 'Add instance', scope.instance.id, () => {+ claimSlotContent(ctx.graph, scope)+ created.id = ctx.graph.createInstance(componentId, frameId)?.id ?? null+ })+ const id = created.id+ if (!id) return+ // Undo removes the new instance, so it must not stay selected.+ ctx.setSelectedIds(new Set([id]))+ ctx.undo.push({+ label: 'Add instance',+ forward: () => ctx.setSelectedIds(new Set([id])),+ inverse: () => ctx.setSelectedIds(new Set(previousSelection))+ })+ })+ return created.id+ }++ return { resetSlot, clearSlot, addInstanceToSlot }+}diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.tsindex 4ee72e435..34a93843f 100644--- a/packages/core/src/editor/structure.ts+++ b/packages/core/src/editor/structure.ts@@ -1,6 +1,7 @@import type { SceneNode } from '@open-pencil/scene-graph'import { DEFAULT_FRAME_FILL } from '#core/constants'+import { acceptingParent, acceptsChildren, prepareSlotEdits } from '#core/editor/components/slots'import { wrapInAutoLayout as wrapInAutoLayoutImpl } from './structure/auto-layout-wrap'import {@@ -30,19 +31,26 @@ export function createStructureActions(ctx: EditorContext) {return !parentId || parentId === ctx.graph.rootId || parentId === ctx.state.currentPageId}- function reparentNodes(nodeIds: string[], newParentId: string) {+ /** Moves layers under a new parent; refuses the locked part of an instance. */+ function reparentNodes(nodeIds: string[], newParentId: string): boolean {const parent = ctx.graph.getNode(newParentId)- for (const id of nodeIds) {- const node = ctx.graph.getNode(id)- if (- node?.type === 'SECTION' &&- parent &&- parent.type !== 'CANVAS' &&- parent.type !== 'SECTION'- )- continue- ctx.graph.reparentNode(id, newParentId)+ // Sections only go into pages and other sections.+ const movable = nodeIds.filter(+ (id) =>+ ctx.graph.getNode(id)?.type !== 'SECTION' ||+ !parent ||+ parent.type === 'CANVAS' ||+ parent.type === 'SECTION'+ )+ if (movable.length === 0) return true+ const parents = new Set([newParentId])+ for (const id of movable) {+ const current = ctx.graph.getNode(id)?.parentId+ if (current && current !== newParentId) parents.add(current)}+ if (!prepareSlotEdits(ctx, parents)) return false+ for (const id of movable) ctx.graph.reparentNode(id, newParentId)+ return true}function wrapSelectionInContainer(@@ -54,7 +62,7 @@ export function createStructureActions(ctx: EditorContext) {}function wrapInAutoLayout(selectedNodes: SceneNode[]) {- wrapInAutoLayoutImpl(ctx, selectedNodes)+ return wrapInAutoLayoutImpl(ctx, selectedNodes)}function groupSelected(selectedNodes: SceneNode[]) {@@ -154,6 +162,8 @@ export function createStructureActions(ctx: EditorContext) {return {isTopLevel,+ acceptsChildren: (parentId: string) => acceptsChildren(ctx, parentId),+ acceptingParent: (parentId: string) => acceptingParent(ctx, parentId),...reorderActions,reparentNodes,wrapSelectionInContainer,diff --git a/packages/core/src/editor/structure/auto-layout-wrap.ts b/packages/core/src/editor/structure/auto-layout-wrap.tsindex 7e994a30f..8ec5de925 100644--- a/packages/core/src/editor/structure/auto-layout-wrap.ts+++ b/packages/core/src/editor/structure/auto-layout-wrap.ts@@ -1,17 +1,17 @@import type { LayoutMode, SceneNode } from '@open-pencil/scene-graph'import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'+import { prepareSlotEdits } from '#core/editor/components/slots'+import { sharedParentId } from '#core/editor/structure/container-wrap'import type { EditorContext } from '#core/editor/types'import { computeLayout } from '#core/layout'-export function wrapInAutoLayout(ctx: EditorContext, selectedNodes: SceneNode[]) {- if (selectedNodes.length === 0) return-- const parentId = selectedNodes[0].parentId ?? ctx.state.currentPageId- const sameParent = selectedNodes.every(- (n) => (n.parentId ?? ctx.state.currentPageId) === parentId- )- if (!sameParent) return+/** Wrap sibling layers in a new auto layout frame; returns the frame, or null if they are not siblings. */+export function wrapInAutoLayout(ctx: EditorContext, selectedNodes: SceneNode[]): string | null {+ const parentId = sharedParentId(ctx, selectedNodes)+ if (!parentId) return null+ // The locked part of an instance takes no new containers.+ if (!prepareSlotEdits(ctx, [parentId])) return nullconst prevSelection = new Set(ctx.state.selectedIds)const origPositions = selectedNodes.map((n) => ({ id: n.id, x: n.x, y: n.y, parentId }))@@ -67,4 +67,5 @@ export function wrapInAutoLayout(ctx: EditorContext, selectedNodes: SceneNode[])ctx.setSelectedIds(prevSelection)}})+ return frameId}diff --git a/packages/core/src/editor/structure/container-wrap.ts b/packages/core/src/editor/structure/container-wrap.tsindex 7bc9f3f65..eb46a9179 100644--- a/packages/core/src/editor/structure/container-wrap.ts+++ b/packages/core/src/editor/structure/container-wrap.ts@@ -1,24 +1,32 @@import type { SceneNode } from '@open-pencil/scene-graph'import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'+import { prepareSlotEdits } from '#core/editor/components/slots'import type { EditorContext } from '#core/editor/types'+/** The parent all these layers share, or null when they are not siblings. */+export function sharedParentId(ctx: EditorContext, nodes: readonly SceneNode[]): string | null {+ const first = nodes.at(0)+ if (!first) return null+ const parentId = first.parentId ?? ctx.state.currentPageId+ return nodes.every((node) => (node.parentId ?? ctx.state.currentPageId) === parentId)+ ? parentId+ : null+}+export function wrapSelectionInContainer(ctx: EditorContext,containerType: 'GROUP' | 'FRAME' | 'COMPONENT' | 'COMPONENT_SET',selectedNodes: SceneNode[],extraProps?: Partial<SceneNode>) {- if (selectedNodes.length === 0) return null-- const parentId = selectedNodes[0].parentId ?? ctx.state.currentPageId- const sameParent = selectedNodes.every(- (n) => (n.parentId ?? ctx.state.currentPageId) === parentId- )- if (!sameParent) return null+ const parentId = sharedParentId(ctx, selectedNodes)+ if (!parentId) return nullconst parent = ctx.graph.getNode(parentId)if (!parent) return null+ // The locked part of an instance takes no new containers.+ if (!prepareSlotEdits(ctx, [parentId])) return nullconst prevSelection = new Set(ctx.state.selectedIds)const nodeIds = selectedNodes.map((n) => n.id)diff --git a/packages/core/src/editor/structure/reorder.ts b/packages/core/src/editor/structure/reorder.tsindex e30549003..28d4c520d 100644--- a/packages/core/src/editor/structure/reorder.ts+++ b/packages/core/src/editor/structure/reorder.ts@@ -1,4 +1,5 @@import { assertNodeEditable } from '#core/editor/capabilities'+import { prepareSlotEdits } from '#core/editor/components/slots'import type { EditorContext } from '#core/editor/types'import { computeLayout } from '#core/layout'@@ -30,6 +31,7 @@ export function createStructureReorderActions(ctx: EditorContext) {const origX = node.xconst origY = node.yconst origIndex = ctx.graph.getNode(origParentId)?.childIds.indexOf(nodeId) ?? -1+ if (!prepareSlotEdits(ctx, [origParentId, parentId])) returndoReorderChild(nodeId, parentId, insertIndex)@@ -57,6 +59,7 @@ export function createStructureReorderActions(ctx: EditorContext) {const node = ctx.graph.getNode(nodeId)if (!node) returnconst origParentId = node.parentId ?? ctx.state.currentPageId+ if (!prepareSlotEdits(ctx, [origParentId, newParentId])) returnconst origIndex = ctx.graph.getNode(origParentId)?.childIds.indexOf(nodeId) ?? 0const origX = node.xconst origY = node.ydiff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.tsindex 76bb82cc3..e88d928d5 100644--- a/packages/core/src/figma-api/accessors/basic.ts+++ b/packages/core/src/figma-api/accessors/basic.ts@@ -4,6 +4,7 @@ import {TRANSFORM_FIELDS as NODE_TRANSFORM_FIELDS,findInstanceAncestor,rescaleNodeTree,+ slotPropertyId,type SceneNode} from '@open-pencil/scene-graph'import type { Rect } from '@open-pencil/scene-graph/primitives'@@ -59,8 +60,9 @@ export function installBasicNodeProxyAccessors(}},type: {- get(this: ProxyThis): SceneNode['type'] {- return raw(this, internals).type+ get(this: ProxyThis): SceneNode['type'] | 'SLOT' {+ const node = raw(this, internals)+ return slotPropertyId(node) ? 'SLOT' : node.type}},name: {diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.tsindex 87b41704d..5f84be431 100644--- a/packages/core/src/figma-api/compatibility.ts+++ b/packages/core/src/figma-api/compatibility.ts@@ -1,7 +1,7 @@/// <reference types="@figma/plugin-typings" />import type { FigmaAPI } from './index'-import type { FigmaComponentNode, FigmaComponentSetNode } from './node-types'+import type { FigmaComponentNode, FigmaComponentSetNode, FigmaSlotNode } from './node-types'import type { FigmaNodeProxy } from './proxy'type Expect<T extends true> = T@@ -90,6 +90,15 @@ type InstancePropertySurfaceMatch = Expect<const _instancePropertySurfaceMatch: InstancePropertySurfaceMatch = true+type SlotSurfaceMatch = Expect<+ Extends<+ Pick<FigmaComponentNode, 'createSlot'> &+ Pick<FigmaSlotNode, 'type' | 'resetSlot' | 'limitViolations'>,+ Pick<ComponentNode, 'createSlot'> & Pick<SlotNode, 'type' | 'resetSlot' | 'limitViolations'>+ >+>+const _slotSurfaceMatch: SlotSurfaceMatch = true+// `Effect` here is Figma's plugin-typings union; OpenPencil reads and writes a subset of it.type EffectShapeMatch = Expect<Extends<FigmaNodeProxy['effects'][number], Effect>>const _effectShapeMatch: EffectShapeMatch = truediff --git a/packages/core/src/figma-api/components.ts b/packages/core/src/figma-api/components.tsindex f9028f41f..9383922cd 100644--- a/packages/core/src/figma-api/components.ts+++ b/packages/core/src/figma-api/components.ts@@ -18,6 +18,12 @@ import { randomHex } from '#core/random'import type { NodeProxyInternals, ProxyThis } from './accessor-utils'import { graph, raw, updateNode } from './accessor-utils'import type { FigmaNodeProxy } from './proxy'+import {+ assertSlotSettings,+ figmaSlotSettings,+ mergeSlotSettings,+ type FigmaSlotSettings+} from './slots'type InstanceSwapPreferredValue = { type: 'COMPONENT' | 'COMPONENT_SET'; key: string }@@ -28,6 +34,8 @@ interface FigmaComponentPropertyDefinition {defaultValue: string | booleanpreferredValues?: InstanceSwapPreferredValue[]variantOptions?: string[]+ description?: string+ slotSettings?: FigmaSlotSettings}interface FigmaComponentProperty {@@ -140,8 +148,16 @@ function propertyMetadata(internals: NodeProxyInternals,definition: ComponentPropertyDefinition,includeVariantOptions: boolean-): Pick<FigmaComponentPropertyDefinition, 'preferredValues' | 'variantOptions'> {- const metadata: Pick<FigmaComponentPropertyDefinition, 'preferredValues' | 'variantOptions'> = {}+): Pick<+ FigmaComponentPropertyDefinition,+ 'preferredValues' | 'variantOptions' | 'description' | 'slotSettings'+> {+ const metadata: Pick<+ FigmaComponentPropertyDefinition,+ 'preferredValues' | 'variantOptions' | 'description' | 'slotSettings'+ > = {}+ if (definition.description) metadata.description = definition.description+ if (definition.slotSettings) metadata.slotSettings = figmaSlotSettings(definition.slotSettings)if (definition.preferredValues) {metadata.preferredValues = preferredValues(graph(target, internals), definition.preferredValues)}@@ -219,6 +235,8 @@ function editPropertyDefinitions(name?: stringdefaultValue?: string | booleanpreferredValues?: InstanceSwapPreferredValue[]+ description?: string+ slotSettings?: FigmaSlotSettings}): string {const node = raw(target, internals)@@ -245,6 +263,10 @@ function editPropertyDefinitions(if (changes.preferredValues) {updated.preferredValues = changes.preferredValues.map((value) => value.key)}+ if (changes.description !== undefined) updated.description = changes.description+ assertSlotSettings(definition.type, changes.slotSettings)+ if (changes.slotSettings)+ updated.slotSettings = mergeSlotSettings(definition.slotSettings, changes.slotSettings)updateNode(target, internals, {componentPropertyDefinitions: node.componentPropertyDefinitions.map((item) =>item.id === definition.id ? updated : item@@ -258,6 +280,26 @@ function propertyReferenceField(field: string): ComponentPropertyReferenceFieldreturn field === 'characters' ? 'TEXT' : 'VISIBLE'}+/**+ * Definitions a layer's references can name: those of the component it is part of, or of the+ * instance's component when it is a layer of an instance.+ */+function referableDefinitions(g: SceneGraph, node: SceneNode): ComponentPropertyDefinition[] {+ let owner = node.parentId ? g.getNode(node.parentId) : undefined+ while (owner && owner.type !== 'CANVAS') {+ if (owner.type === 'INSTANCE') return sharedComponentPropertyDefinitions(g, owner)+ if (owner.type === 'COMPONENT') {+ const set = owner.parentId ? g.getNode(owner.parentId) : undefined+ return [+ ...owner.componentPropertyDefinitions,+ ...(set?.type === 'COMPONENT_SET' ? set.componentPropertyDefinitions : [])+ ]+ }+ owner = owner.parentId ? g.getNode(owner.parentId) : undefined+ }+ return []+}+/** Figma's names: `slotContentId` is what a slot frame reports for its slot property. */function propertyReferenceName(field: ComponentPropertyReferenceField): string {if (field === 'INSTANCE_SWAP') return 'mainComponent'@@ -302,11 +344,16 @@ export function installComponentPropertyAccessors(node.type !== 'TEXT')return null+ // References name properties by key, `Name#id`, as componentPropertyDefinitions does.+ const definitions = referableDefinitions(graph(this, internals), node)return Object.fromEntries(- node.componentPropertyReferences.map((reference) => [- propertyReferenceName(reference.field),- reference.propertyId- ])+ node.componentPropertyReferences.map((reference) => {+ const definition = definitions.find((item) => item.id === reference.propertyId)+ return [+ propertyReferenceName(reference.field),+ definition ? propertyName(definition) : reference.propertyId+ ]+ }))},set(this: ProxyThis, value: Record<string, string> | null) {@@ -314,9 +361,11 @@ export function installComponentPropertyAccessors(updateNode(this, internals, { componentPropertyReferences: [] })return}+ const definitions = referableDefinitions(graph(this, internals), raw(this, internals))updateNode(this, internals, {- componentPropertyReferences: Object.entries(value).map(([field, propertyId]) => ({- propertyId,+ componentPropertyReferences: Object.entries(value).map(([field, key]) => ({+ propertyId:+ definitions.find((definition) => propertyName(definition) === key)?.id ?? key,field: propertyReferenceField(field)}))})@@ -388,7 +437,11 @@ export function installComponentPropertyAccessors(name: string,type: ComponentPropertyType,defaultValue: string | boolean,- options?: { preferredValues?: InstanceSwapPreferredValue[] }+ options?: {+ preferredValues?: InstanceSwapPreferredValue[]+ description?: string+ slotSettings?: FigmaSlotSettings+ }) {const node = raw(this, internals)if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET')@@ -405,6 +458,12 @@ export function installComponentPropertyAccessors(if (options?.preferredValues) {definition.preferredValues = options.preferredValues.map((value) => value.key)}+ if (options?.description !== undefined) definition.description = options.description+ assertSlotSettings(type, options?.slotSettings)+ if (type === 'SLOT') {+ definition.preferredValues ??= []+ definition.slotSettings = mergeSlotSettings(undefined, options?.slotSettings ?? {})+ }updateNode(this, internals, {componentPropertyDefinitions: [...node.componentPropertyDefinitions, definition]})@@ -415,7 +474,13 @@ export function installComponentPropertyAccessors(value(this: ProxyThis,name: string,- changes: { name?: string; defaultValue?: string | boolean }+ changes: {+ name?: string+ defaultValue?: string | boolean+ preferredValues?: InstanceSwapPreferredValue[]+ description?: string+ slotSettings?: FigmaSlotSettings+ }) {return editPropertyDefinitions(this, internals, name, changes)}diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex 94010a1a7..58ae71951 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -65,6 +65,7 @@ export type {FigmaPolygonNode,FigmaRectangleNode,FigmaSectionNode,+ FigmaSlotNode,FigmaStarNode,FigmaTextNode,FigmaVectorNodediff --git a/packages/core/src/figma-api/node-types.ts b/packages/core/src/figma-api/node-types.tsindex 89b3d4472..5dba43d08 100644--- a/packages/core/src/figma-api/node-types.ts+++ b/packages/core/src/figma-api/node-types.ts@@ -12,6 +12,7 @@ export type FigmaPolygonNode = FigmaNodeProxy & PolygonNodeexport type FigmaStarNode = FigmaNodeProxy & StarNodeexport type FigmaComponentNode = FigmaNodeProxy & ComponentNodeexport type FigmaComponentSetNode = FigmaNodeProxy & ComponentSetNode+export type FigmaSlotNode = FigmaNodeProxy & SlotNodeexport type FigmaSectionNode = FigmaNodeProxy & SectionNodeexport type FigmaGroupNode = FigmaNodeProxy & GroupNodeexport type FigmaBooleanOperationNode = FigmaNodeProxy & BooleanOperationNodediff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex 379cf755b..562750c26 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -1,4 +1,4 @@-import { recordInstanceOverride } from '@open-pencil/scene-graph'+import { recordInstanceOverride, slotPropertyId } from '@open-pencil/scene-graph'import type {SceneGraph,SceneNode,@@ -35,6 +35,7 @@ import type { FigmaFontName } from './fonts'import { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'import * as PluginData from './plugin-data'import { nodeProxyToJSON } from './serialization'+import { installSlotAccessors, prepareSlotMove, prepareSlotRemoval } from './slots'import * as TextProxy from './text'import * as Traversal from './traversal'import type { FigmaTransform } from './types'@@ -60,7 +61,8 @@ export class FigmaNodeProxy {[INTERNAL_API]: NodeProxyHostdeclare readonly id: string- declare readonly type: NodeType+ /** A slot frame reads as `'SLOT'`, as Figma's `SlotNode` does. */+ declare readonly type: NodeType | 'SLOT'declare name: stringdeclare readonly removed: booleandeclare x: number@@ -280,12 +282,14 @@ export class FigmaNodeProxy {appendChild(child: FigmaNodeProxy): void {assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])assertNodeEditable(this[INTERNAL_GRAPH], child[INTERNAL_ID])+ prepareSlotMove(this[INTERNAL_GRAPH], this[INTERNAL_ID], child[INTERNAL_ID], 'appendChild')this[INTERNAL_GRAPH].reparentNode(child[INTERNAL_ID], this[INTERNAL_ID])}insertChild(index: number, child: FigmaNodeProxy): void {assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])assertNodeEditable(this[INTERNAL_GRAPH], child[INTERNAL_ID])+ prepareSlotMove(this[INTERNAL_GRAPH], this[INTERNAL_ID], child[INTERNAL_ID], 'insertChild')this[INTERNAL_GRAPH].reparentNode(child[INTERNAL_ID], this[INTERNAL_ID])this[INTERNAL_GRAPH].reorderChild(child[INTERNAL_ID], this[INTERNAL_ID], index)}@@ -296,11 +300,19 @@ export class FigmaNodeProxy {const parentId = n.parentId ?? this[INTERNAL_API].currentPageIdconst cloned = this[INTERNAL_GRAPH].cloneTree(this[INTERNAL_ID], parentId)if (!cloned) throw new Error(`Failed to clone node ${this[INTERNAL_ID]}`)+ // A slot's copy is a plain frame: the slot binding belongs to the original alone.+ if (slotPropertyId(cloned))+ this[INTERNAL_GRAPH].updateNode(cloned.id, {+ componentPropertyReferences: cloned.componentPropertyReferences.filter(+ (reference) => reference.field !== 'SLOT_CONTENT'+ )+ })return this[INTERNAL_API].wrapNode(cloned.id)}remove(): void {assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])+ prepareSlotRemoval(this[INTERNAL_GRAPH], this[INTERNAL_ID])this[INTERNAL_GRAPH].deleteNode(this[INTERNAL_ID])}@@ -432,3 +444,4 @@ installTextNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)installLayoutNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)installVariableModeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)installComponentPropertyAccessors(FigmaNodeProxy.prototype, proxyInternals)+installSlotAccessors(FigmaNodeProxy.prototype, proxyInternals)diff --git a/packages/core/src/figma-api/slots.ts b/packages/core/src/figma-api/slots.tsnew file mode 100644index 000000000..ea35c0599--- /dev/null+++ b/packages/core/src/figma-api/slots.ts@@ -0,0 +1,155 @@+import {+ DEFAULT_SLOT_SETTINGS,+ claimSlotContent,+ componentPropertyDefinitions,+ createSlotProperty,+ resetSlotContent,+ slotLimitViolations,+ slotPropertyId,+ slotScope,+ type ComponentPropertyType,+ type SceneGraph,+ type SlotLimitViolation,+ type SlotSettings+} from '@open-pencil/scene-graph'++import { randomHex } from '#core/random'++import type { NodeProxyInternals, ProxyThis } from './accessor-utils'+import { assertProxyEditable, graph, nodeId, raw } from './accessor-utils'+import type { NodeProxyHost } from './proxy'++/** Figma's slot limits, where an unset count reads as null. */+export interface FigmaSlotSettings {+ stretchChildOnInsert?: boolean+ displayEmptyByDefault?: boolean+ minChildren?: number | null+ maxChildren?: number | null+ allowPreferredValuesOnly?: boolean+}++/** A count after a Figma change: null clears it, undefined keeps the current one. */+function count(change: number | null | undefined, current: number | undefined) {+ return change === null ? undefined : (change ?? current)+}++/** Apply Figma slot settings to a definition's own. */+export function mergeSlotSettings(+ current: SlotSettings | undefined,+ changes: FigmaSlotSettings+): SlotSettings {+ const base = { ...DEFAULT_SLOT_SETTINGS, ...current }+ const next: SlotSettings = {+ stretchChildOnInsert: changes.stretchChildOnInsert ?? base.stretchChildOnInsert,+ displayEmptyByDefault: changes.displayEmptyByDefault ?? base.displayEmptyByDefault,+ allowPreferredValuesOnly: changes.allowPreferredValuesOnly ?? base.allowPreferredValuesOnly+ }+ const minChildren = count(changes.minChildren, base.minChildren)+ const maxChildren = count(changes.maxChildren, base.maxChildren)+ if (minChildren !== undefined) next.minChildren = minChildren+ if (maxChildren !== undefined) next.maxChildren = maxChildren+ return next+}++export function figmaSlotSettings(settings: SlotSettings): FigmaSlotSettings {+ return {+ ...settings,+ minChildren: settings.minChildren ?? null,+ maxChildren: settings.maxChildren ?? null+ }+}++export function assertSlotSettings(+ type: ComponentPropertyType,+ settings: FigmaSlotSettings | undefined+): void {+ if (settings && type !== 'SLOT')+ throw new Error("slotSettings is only supported for 'SLOT' properties")+}++/**+ * Ready a move of `childId` into `parentId` the way Figma's appendChild does: the locked part+ * of an instance refuses it, and a slot on either side becomes the instance's own content.+ */+export function prepareSlotMove(+ g: SceneGraph,+ parentId: string,+ childId: string,+ method: 'appendChild' | 'insertChild'+): void {+ const target = slotScope(g, parentId)+ if (target.kind === 'locked')+ throw new Error(+ `in ${method}: Cannot move node. New parent is an instance or is inside of an instance`+ )+ const sourceParentId = g.getNode(childId)?.parentId+ const source = sourceParentId ? slotScope(g, sourceParentId) : undefined+ if (target.kind === 'slot') claimSlotContent(g, target)+ if (source?.kind === 'slot') claimSlotContent(g, source)+}++/**+ * Ready removing a layer the way Figma's remove() does: the locked part of an instance,+ * slot frames included, refuses it, and slot content becomes the instance's own first.+ */+export function prepareSlotRemoval(g: SceneGraph, nodeId: string): void {+ const parentId = g.getNode(nodeId)?.parentId+ if (!parentId) return+ const scope = slotScope(g, parentId)+ if (scope.kind === 'locked') throw new Error('in remove: Removing this node is not allowed')+ if (scope.kind === 'slot') claimSlotContent(g, scope)+}++function host(target: ProxyThis, internals: NodeProxyInternals): NodeProxyHost {+ return target[internals.api] as NodeProxyHost+}++/** The instance slot a proxy is, if it is the frame of one. */+function instanceSlot(target: ProxyThis, internals: NodeProxyInternals) {+ const scope = slotScope(graph(target, internals), nodeId(target, internals))+ return scope.kind === 'slot' && scope.frame.id === nodeId(target, internals) ? scope : undefined+}++/** `ComponentNode.createSlot` and the `SlotNode` members Figma's plugin API defines. */+export function installSlotAccessors(prototype: object, internals: NodeProxyInternals): void {+ Object.defineProperties(prototype, {+ createSlot: {+ // Figma appends a 100×100 frame named Slot, Slot 2, … and a SLOT property of that name.+ value(this: ProxyThis) {+ const component = raw(this, internals)+ if (component.type !== 'COMPONENT')+ throw new Error('createSlot() can only be called on components')+ assertProxyEditable(this, internals)+ const g = graph(this, internals)+ const frame = g.createNode('FRAME', component.id, { name: 'Slot' })+ const definition = createSlotProperty(g, frame.id, `prop:${randomHex(8)}`)+ if (!definition) throw new Error('Failed to create slot')+ g.updateNode(frame.id, { name: definition.name })+ return host(this, internals).wrapNode(frame.id)+ }+ },+ resetSlot: {+ value(this: ProxyThis) {+ if (!slotPropertyId(raw(this, internals)))+ throw new Error('resetSlot() can only be called on slots')+ assertProxyEditable(this, internals)+ const scope = instanceSlot(this, internals)+ if (scope) resetSlotContent(graph(this, internals), scope)+ }+ },+ limitViolations: {+ // Figma measures limits only where an instance shows the slot; a main component's slot+ // reports none.+ get(this: ProxyThis): SlotLimitViolation[] {+ const scope = instanceSlot(this, internals)+ if (!scope) return []+ const g = graph(this, internals)+ const definition = componentPropertyDefinitions(g, scope.instance).find(+ (item) => item.id === scope.propertyId+ )+ if (!definition) return []+ return slotLimitViolations(g, definition, g.getChildren(scope.frame.id))+ }+ }+ })+}diff --git a/packages/core/src/tools/stock-photo/apply.ts b/packages/core/src/tools/stock-photo/apply.tsindex 8bf4825b4..c78c33bad 100644--- a/packages/core/src/tools/stock-photo/apply.ts+++ b/packages/core/src/tools/stock-photo/apply.ts@@ -1,11 +1,11 @@-import type { SceneNode } from '@open-pencil/scene-graph'-import type { FigmaAPI } from '#core/figma-api'+import type { FigmaNodeProxy } from '#core/figma-api/proxy'import type { StockPhotoProvider, StockPhotoResult } from './providers'-const STOCK_PHOTO_TARGET_TYPES: ReadonlySet<SceneNode['type']> = new Set([+const STOCK_PHOTO_TARGET_TYPES: ReadonlySet<FigmaNodeProxy['type']> = new Set(['FRAME',+ 'SLOT','RECTANGLE','ROUNDED_RECTANGLE','ELLIPSE',diff --git a/packages/core/tests/editor/components/slots/authoring.test.ts b/packages/core/tests/editor/components/slots/authoring.test.tsnew file mode 100644index 000000000..675ce8ca4--- /dev/null+++ b/packages/core/tests/editor/components/slots/authoring.test.ts@@ -0,0 +1,102 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import { instanceSlotFrames, slotPropertyId } from '@open-pencil/scene-graph'++/** A Card component with a Body frame holding Default, and an instance of it. */+function setup() {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const card = editor.graph.createNode('COMPONENT', pageId, { name: 'Card' })+ const title = editor.graph.createNode('TEXT', card.id, { name: 'Title', text: 'Title' })+ const body = editor.graph.createNode('FRAME', card.id, { name: 'Body' })+ editor.graph.createNode('TEXT', body.id, { name: 'Default', text: 'Default' })+ const instance = editor.graph.createInstance(card.id, pageId)+ if (!instance) throw new Error('No instance')+ return { editor, card, title, body, instance }+}++/** Let component sync, scheduled on a microtask, reach the instances. */+const synced = () => Promise.resolve()++describe('authoring slots', () => {+ test('converting a frame defines a slot that existing instances pick up', async () => {+ const { editor, card, body, instance } = setup()+ const id = editor.convertToSlot(body.id)+ await synced()++ expect(card.componentPropertyDefinitions).toEqual([+ expect.objectContaining({ id, name: 'Body', type: 'SLOT' })+ ])+ expect(slotPropertyId(body)).toBe(id ?? '')+ expect(instanceSlotFrames(editor.graph, instance).map((frame) => frame.name)).toEqual(['Body'])++ editor.undo.undo()+ await synced()+ expect(editor.graph.getNode(card.id)?.componentPropertyDefinitions).toEqual([])+ expect(instanceSlotFrames(editor.graph, instance)).toEqual([])+ })++ test('other layers are wrapped in a new slot frame in one undo step', () => {+ const { editor, card, title } = setup()+ editor.select([title.id])+ const id = editor.createSlot()+ const frame = editor.graph.getChildren(card.id).find((child) => slotPropertyId(child) === id)+ expect(frame?.name).toBe('Slot')+ expect(editor.graph.getChildren(frame?.id ?? '').map((child) => child.name)).toEqual(['Title'])++ editor.undo.undo()+ expect(editor.graph.getNode(title.id)?.parentId).toBe(card.id)+ expect(editor.graph.getNode(card.id)?.componentPropertyDefinitions).toEqual([])+ })++ test('layers outside a main component or inside an instance cannot become slots', () => {+ const { editor, instance } = setup()+ const instanceBody = editor.graph.getChildren(instance.id).find((c) => c.type === 'FRAME')+ if (!instanceBody) throw new Error('Missing instance frame')+ editor.select([instance.id])+ expect(editor.createSlot()).toBeNull()+ expect(editor.convertToSlot(instanceBody.id)).toBeNull()+ })++ test('settings change and undo as one step', () => {+ const { editor, card, body } = setup()+ const id = editor.convertToSlot(body.id) ?? ''+ editor.updateSlot(card.id, id, {+ name: 'Content',+ slotSettings: { maxChildren: 2, allowPreferredValuesOnly: true }+ })+ expect(editor.graph.getNode(card.id)?.componentPropertyDefinitions[0]).toMatchObject({+ name: 'Content',+ slotSettings: { maxChildren: 2, allowPreferredValuesOnly: true }+ })+ editor.undo.undo()+ expect(editor.graph.getNode(card.id)?.componentPropertyDefinitions[0]).toMatchObject({+ name: 'Body',+ slotSettings: { allowPreferredValuesOnly: false }+ })+ })++ test('removing a slot frees the frame and drops instance content until undone', async () => {+ const { editor, card, body, instance } = setup()+ const id = editor.convertToSlot(body.id) ?? ''+ await synced()+ const [frame] = instanceSlotFrames(editor.graph, instance)+ editor.clearSlot(frame.id)+ expect(editor.graph.getNode(instance.id)?.componentPropertyAssignments).toEqual({ [id]: '' })++ editor.removeSlot(card.id, id)+ await synced()+ expect(editor.graph.getNode(card.id)?.componentPropertyDefinitions).toEqual([])+ expect(slotPropertyId(body)).toBeUndefined()+ expect(editor.graph.getNode(instance.id)?.componentPropertyAssignments).toEqual({})++ editor.undo.undo()+ await synced()+ expect(editor.graph.getNode(instance.id)?.componentPropertyAssignments).toEqual({ [id]: '' })+ const restoredInstance = editor.graph.getNode(instance.id)+ if (!restoredInstance) throw new Error('Missing instance after undo')+ const [restored] = instanceSlotFrames(editor.graph, restoredInstance)+ expect(editor.graph.getChildren(restored.id)).toEqual([])+ })+})diff --git a/packages/core/tests/editor/components/slots/content.test.ts b/packages/core/tests/editor/components/slots/content.test.tsnew file mode 100644index 000000000..4e62cbfc2--- /dev/null+++ b/packages/core/tests/editor/components/slots/content.test.ts@@ -0,0 +1,136 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import { ownsSlotContent, slotPropertyId, type SceneNode } from '@open-pencil/scene-graph'++/** A Card component whose `Body` slot holds `Default`, an instance of it, and a free layer. */+function setup() {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const card = editor.graph.createNode('COMPONENT', pageId, {+ name: 'Card',+ componentPropertyDefinitions: [+ { id: 'card:body', name: 'Body', type: 'SLOT', defaultValue: '' }+ ]+ })+ editor.graph.createNode('TEXT', card.id, { name: 'Title', text: 'Title' })+ const body = editor.graph.createNode('FRAME', card.id, {+ name: 'Body',+ componentPropertyReferences: [{ propertyId: 'card:body', field: 'SLOT_CONTENT' }]+ })+ editor.graph.createNode('TEXT', body.id, { name: 'Default', text: 'Default' })+ const item = editor.graph.createNode('COMPONENT', pageId, { name: 'Item' })+ const instance = editor.graph.createInstance(card.id, pageId)+ if (!instance) throw new Error('No instance')+ const free = editor.graph.createNode('RECTANGLE', pageId, { name: 'Free' })+ const slot = editor.graph.getChildren(instance.id).find((child) => slotPropertyId(child))+ const title = editor.graph.getChildren(instance.id).find((child) => child.name === 'Title')+ if (!slot || !title) throw new Error('Missing instance layers')+ return { editor, pageId, card, item, instance, free, slot, title }+}++const names = (editor: ReturnType<typeof createEditor>, node: SceneNode) =>+ editor.graph.getChildren(node.id).map((child) => child.name)++describe('editing instance slots', () => {+ test('moving a layer into an untouched slot claims it, and one undo restores both', () => {+ const { editor, pageId, instance, free, slot } = setup()+ // As the canvas does: reparent on drop, then record the move.+ editor.undo.runBatch('Move', () => {+ editor.reparentNodes([free.id], slot.id)+ editor.commitMoveWithReparent(new Map([[free.id, { x: 0, y: 0, parentId: pageId }]]))+ })++ expect(names(editor, slot)).toEqual(['Default', 'Free'])+ expect(ownsSlotContent(editor.graph, slot)).toBe(true)+ expect(instance.componentPropertyAssignments).toEqual({ 'card:body': '' })++ editor.undo.undo()+ const restored = editor.graph.getChildren(instance.id).find((child) => slotPropertyId(child))+ if (!restored) throw new Error('Missing slot after undo')+ expect(names(editor, restored)).toEqual(['Default'])+ expect(editor.graph.getNode(free.id)?.parentId).toBe(pageId)+ expect(editor.graph.getNode(instance.id)?.componentPropertyAssignments).toEqual({})+ })++ test('the rest of an instance refuses layers', () => {+ const { editor, pageId, instance, free, title } = setup()+ expect(editor.reparentNodes([free.id], instance.id)).toBe(false)+ expect(editor.graph.getNode(free.id)?.parentId).toBe(pageId)+ expect(editor.acceptsChildren(instance.id)).toBe(false)+ expect(editor.acceptingParent(title.id)).toBe(pageId)+ })++ test('paste with the instance selected lands beside it, and with the slot selected inside it', async () => {+ const { editor, pageId, instance, free, slot } = setup()+ editor.select([free.id])+ const payload = await editor.prepareCopy()+ if (!payload.snapshot) throw new Error('Missing snapshot')+ editor.select([instance.id])+ await editor.pasteSnapshot(payload.snapshot)+ expect(editor.graph.getChildren(pageId).filter((node) => node.name === 'Free')).toHaveLength(2)+ editor.select([slot.id])+ await editor.pasteSnapshot(payload.snapshot)+ expect(names(editor, slot)).toEqual(['Default', 'Free'])+ })++ test('reset, delete contents, and add instance are single undo steps', () => {+ const { editor, item, instance, slot } = setup()+ editor.clearSlot(slot.id)+ expect(names(editor, slot)).toEqual([])++ const added = editor.addInstanceToSlot(slot.id, item.id)+ expect(added && editor.graph.getNode(added)?.componentId).toBe(item.id)+ expect(names(editor, slot)).toEqual(['Item'])++ editor.resetSlot(slot.id)+ const current = () => {+ const frame = editor.graph.getChildren(instance.id).find((child) => slotPropertyId(child))+ if (!frame) throw new Error('Missing slot')+ return frame+ }+ expect(names(editor, current())).toEqual(['Default'])+ expect(editor.graph.getNode(instance.id)?.componentPropertyAssignments).toEqual({})++ editor.undo.undo()+ expect(names(editor, current())).toEqual(['Item'])+ editor.undo.undo()+ expect(names(editor, current())).toEqual([])+ })+ test('layers in the rest of an instance cannot be grouped or wrapped', () => {+ const { editor, instance, title } = setup()+ editor.select([title.id])+ editor.groupSelected()+ editor.wrapInAutoLayout()+ expect(editor.graph.getNode(title.id)?.parentId).toBe(instance.id)+ })++ test('undoing an added instance restores the selection', () => {+ const { editor, item, slot, free } = setup()+ editor.select([free.id])+ const added = editor.addInstanceToSlot(slot.id, item.id)+ expect([...editor.state.selectedIds]).toEqual([added])+ editor.undo.undo()+ expect([...editor.state.selectedIds]).toEqual([free.id])+ editor.undo.redo()+ expect([...editor.state.selectedIds]).toEqual([added])+ })+ test('delete leaves the rest of an instance alone and claims a slot in one undo step', () => {+ const { editor, instance, slot, title } = setup()+ editor.select([title.id])+ editor.deleteSelected()+ expect(editor.graph.getNode(title.id)?.parentId).toBe(instance.id)++ const [content] = editor.graph.getChildren(slot.id)+ editor.select([content.id])+ editor.deleteSelected()+ expect(editor.graph.getChildren(slot.id)).toEqual([])+ expect(editor.graph.getNode(instance.id)?.componentPropertyAssignments).toEqual({+ 'card:body': ''+ })+ editor.undo.undo()+ const restored = editor.graph.getChildren(instance.id).find((child) => slotPropertyId(child))+ expect(restored && names(editor, restored)).toEqual(['Default'])+ expect(editor.graph.getNode(instance.id)?.componentPropertyAssignments).toEqual({})+ })+})diff --git a/packages/core/tests/figma-api/slots.test.ts b/packages/core/tests/figma-api/slots.test.tsnew file mode 100644index 000000000..627c621da--- /dev/null+++ b/packages/core/tests/figma-api/slots.test.ts@@ -0,0 +1,156 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { SceneGraph } from '@open-pencil/scene-graph'++// Defaults, names, read-back values, and limit reports were recorded by running the same+// script against a component in live Figma through figma-use.++function setup() {+ const api = new FigmaAPI(new SceneGraph())+ const component = api.createComponent()+ component.name = 'Card'+ return { api, component }+}++describe('slots', () => {+ test('createSlot appends a 100×100 frame named Slot bound to a new SLOT property', () => {+ const { component } = setup()+ const slot = component.createSlot()++ expect(slot.type).toBe('SLOT')+ expect(slot.name).toBe('Slot')+ expect([slot.width, slot.height]).toEqual([100, 100])+ expect(slot.parent?.id).toBe(component.id)+ const [key] = Object.keys(component.componentPropertyDefinitions)+ expect(key).toStartWith('Slot#')+ expect(component.componentPropertyDefinitions[key]).toMatchObject({+ type: 'SLOT',+ preferredValues: []+ })+ expect(slot.componentPropertyReferences).toEqual({ slotContentId: key })++ expect(component.createSlot().name).toBe('Slot 2')+ })++ test('instances show the slot, report broken limits, and reset to the component content', () => {+ const { api, component } = setup()+ const slot = component.createSlot()+ slot.appendChild(Object.assign(api.createText(), { name: 'Default' }))+ const [key] = Object.keys(component.componentPropertyDefinitions)+ component.editComponentProperty(key, { slotSettings: { minChildren: 2, maxChildren: 3 } })+ expect(component.componentPropertyDefinitions[key].slotSettings).toEqual({+ stretchChildOnInsert: false,+ displayEmptyByDefault: false,+ minChildren: 2,+ maxChildren: 3,+ allowPreferredValuesOnly: false+ })++ const instance = component.createInstance()+ const instanceSlot = instance.children.find((child) => child.type === 'SLOT')+ if (!instanceSlot) throw new Error('Missing instance slot')+ expect(instanceSlot.children.map((child) => child.name)).toEqual(['Default'])+ expect(instanceSlot.limitViolations).toEqual(['BELOW_MIN'])+ // A main component's slot reports nothing.+ expect(slot.limitViolations).toEqual([])++ instanceSlot.appendChild(Object.assign(api.createFrame(), { name: 'Inner' }))+ instanceSlot.resetSlot()+ const reset = instance.children.find((child) => child.type === 'SLOT')+ expect(reset?.children.map((child) => child.name)).toEqual(['Default'])+ })++ // Recorded in live Figma: an instance's own layers and its slot frames refuse removal;+ // slot content can be removed, which makes the slot the instance's own.+ test('remove() only takes layers out of the slots of an instance', () => {+ const { api, component } = setup()+ component.appendChild(Object.assign(api.createFrame(), { name: 'Locked' }))+ component.createSlot().appendChild(Object.assign(api.createRectangle(), { name: 'Default' }))+ const instance = component.createInstance()+ const locked = instance.children.find((child) => child.name === 'Locked')+ const slot = instance.children.find((child) => child.type === 'SLOT')+ if (!locked || !slot) throw new Error('Missing instance layers')++ expect(() => locked.remove()).toThrow('in remove: Removing this node is not allowed')+ expect(() => slot.remove()).toThrow('in remove: Removing this node is not allowed')+ slot.children[0]?.remove()+ expect(slot.children).toEqual([])+ expect(Object.values(instance.componentProperties)).toHaveLength(1)+ })++ // Recorded in live Figma: resetting a main component's slot neither throws nor changes it.+ test('resetSlot on a main component slot keeps its content', () => {+ const { api, component } = setup()+ const slot = component.createSlot()+ slot.appendChild(Object.assign(api.createText(), { name: 'Main' }))+ slot.resetSlot()+ expect(slot.children.map((child) => child.name)).toEqual(['Main'])+ expect(Object.keys(component.componentPropertyDefinitions)).toHaveLength(1)+ })++ test('addComponentProperty takes a SLOT description and settings, unset counts reading null', () => {+ const { component } = setup()+ const key = component.addComponentProperty('Added', 'SLOT', '', {+ description: 'desc',+ slotSettings: { maxChildren: 1 }+ })+ expect(component.componentPropertyDefinitions[key]).toMatchObject({+ type: 'SLOT',+ description: 'desc',+ slotSettings: { minChildren: null, maxChildren: 1, allowPreferredValuesOnly: false }+ })+ expect(() =>+ component.addComponentProperty('Label', 'TEXT', 'x', { slotSettings: { maxChildren: 1 } })+ ).toThrow("slotSettings is only supported for 'SLOT' properties")+ })++ // Figma returns the copy as a SLOT without references; the typings promise a FrameNode,+ // and OpenPencil, whose slots are frames bound to a property, returns that frame. Figma+ // also moves the copy to the page, so it reads null references; OpenPencil's clone stays+ // beside the original, inside the component, where it binds nothing.+ test('a cloned slot is a plain frame bound to nothing', () => {+ const { component } = setup()+ const copy = component.createSlot().clone()+ expect(copy.type).toBe('FRAME')+ expect(copy.componentPropertyReferences).toEqual({})+ expect(Object.keys(component.componentPropertyDefinitions)).toHaveLength(1)+ })++ test('createSlot is only for components', () => {+ const { api, component } = setup()+ // Only components declare createSlot; a script can still call it on another node.+ const { createSlot } = component+ expect(() => createSlot.call(api.createFrame())).toThrow(+ 'createSlot() can only be called on components'+ )+ })+})++describe('swapping an instance', () => {+ /** An outer component holding a Card instance named `innerName`, whose slot has a layer. */+ function outerWithFilledSlot(innerName: string) {+ const { api, component: card } = setup()+ card.createSlot()+ const outer = (name: string, nestedName: string) => {+ const component = api.createComponent()+ component.name = name+ component.appendChild(Object.assign(card.createInstance(), { name: nestedName }))+ return component+ }+ const instance = outer('Outer A', 'Card').createInstance()+ const nestedSlot = () =>+ instance.children[0]?.children.find((child) => child.type === 'SLOT')+ nestedSlot()?.appendChild(Object.assign(api.createText(), { name: 'Filled' }))+ return { instance, nestedSlot, same: outer('Outer B', 'Card'), other: outer('Outer C', innerName) }+ }++ // Recorded in live Figma: nested slot content follows a nested instance of the same name.+ test('keeps a nested instance’s slot content when the new component nests one of the same name', () => {+ const { instance, nestedSlot, same, other } = outerWithFilledSlot('Other name')+ instance.swapComponent(same)+ expect(nestedSlot()?.children.map((child) => child.name)).toEqual(['Filled'])+ instance.swapComponent(other)+ expect(nestedSlot()?.children.map((child) => child.name)).toEqual([])+ })+})diff --git a/packages/docs/development/roadmap.md b/packages/docs/development/roadmap.mdindex 9aa6c646e..a37658399 100644--- a/packages/docs/development/roadmap.md+++ b/packages/docs/development/roadmap.md@@ -184,9 +184,9 @@ Figma's design documentation groups features into these areas:| Vectors / vector networks | ✅ | ✅ | ◐ | ✅ | ✅ | Vector edit support exists; Figma Draw tools are not fully replicated. || Boolean operations | ✅ | ✅ | ◐ | ✅ | ✅ | Figma `BOOLEAN_OPERATION` nodes import/export as boolean operations; inspector editing remains limited. || Components | ✅ | ✅ | ◐ | ✅ | ✅ | Component metadata, descriptions, links, and publish fields mostly round-trip. |-| Component sets / variants | ✅ | ✅ | ◐ | ✅ | ✅ | Multidimensional variant definitions and common instance properties are editable; slots and broader Figma-specific property parity remain incomplete. |+| Component sets / variants | ✅ | ✅ | ◐ | ✅ | ✅ | Multidimensional variant definitions and common instance properties are editable; broader Figma-specific property parity remains incomplete. || Instances / overrides | ✅ | ✅ | ◐ | ✅ | ✅ | Component-property refs and typed assignments are modeled and editable; raw symbol overrides and derived data remain preserved for fidelity. |-| Slots | ✅ | ✅ | — | ✅ | ◐ | Slot properties, settings, and instance slot content import, render, and round-trip; the editor cannot create or fill slots yet. |+| Slots | ✅ | ✅ | ✅ | ✅ | ✅ | Slot properties, settings, and instance slot content import, render, and round-trip. The editor creates, configures, and removes slots on main components and fills them in instances; scripts do the same through `createSlot()`, `resetSlot()`, and `limitViolations`. || Connectors | ◐ | ◐ | — | ◐ | ◐ | Type exists, but Figma connector semantics are weak. || Shape-with-text / FigJam shapes | ◐ | ◐ | — | ◐ | ◐ | Type exists, but not a full FigJam feature implementation. || Slices | ◐ | — | ◐ | ◐ | ✅ | Slice-like export regions exist via tooling, not as true Figma slice nodes. |diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.mdindex e93887185..61c7e237d 100644--- a/packages/docs/programmable/cli/scripting.md+++ b/packages/docs/programmable/cli/scripting.md@@ -165,6 +165,7 @@ Common node properties are readable/writable through the proxy, including:- `figma.getNodeByIdAsync(id)` and `instance.getMainComponentAsync()` resolve to the same nodes as `figma.getNodeById(id)` and `instance.mainComponent`, for scripts written for Figma's dynamic-page mode- `figma.notify(message)` logs a warning in headless mode- `instance.swapComponent(component)` points an instance at another component+- `component.createSlot()` adds a slot frame and its `SLOT` property; slot frames read `type: 'SLOT'`, `resetSlot()` brings back an instance slot's component content, and `limitViolations` lists the limits an instance slot breaks. `addComponentProperty` and `editComponentProperty` take a `description` and, for slots, `slotSettings`- `figma.viewport`## Not yet Figma-compatiblediff --git a/packages/scene-graph/src/components/properties.ts b/packages/scene-graph/src/components/properties.tsindex 79bfbba0c..4ed51a2a4 100644--- a/packages/scene-graph/src/components/properties.ts+++ b/packages/scene-graph/src/components/properties.ts@@ -1,6 +1,7 @@import type { SceneGraph } from '../index'import { getInstanceOverride, setInstanceOverride } from '../instance-overrides'import { findInstanceAncestor } from '../instances'+import { instanceMainComponent } from '../instances/main-component'import type {ComponentPropertyDefinition,ComponentPropertyReferenceField,@@ -14,8 +15,8 @@ export interface ComponentPropertyTarget {}export function componentPropertyOwners(graph: SceneGraph, instance: SceneNode): SceneNode[] {- if (instance.type !== 'INSTANCE' || !instance.componentId) return []- const component = graph.getNode(instance.componentId)+ if (instance.type !== 'INSTANCE') return []+ const component = instanceMainComponent(graph, instance)if (!component) return []const parent = component.parentId ? graph.getNode(component.parentId) : nullreturn parent?.type === 'COMPONENT_SET' ? [parent, component] : [component]diff --git a/packages/scene-graph/src/components/slots.ts b/packages/scene-graph/src/components/slots.tsdeleted file mode 100644index 1a364d006..000000000--- a/packages/scene-graph/src/components/slots.ts+++ /dev/null@@ -1,104 +0,0 @@-import type { SceneGraph } from '../index'-import type { SceneNode } from '../types'--/** The slot property a frame holds the content of, if it is a slot. */-export function slotPropertyId(node: SceneNode): string | undefined {- return node.componentPropertyReferences.find((reference) => reference.field === 'SLOT_CONTENT')- ?.propertyId-}--/**- * Whether this slot frame's children belong to its instance rather than its component: the- * nearest enclosing instance assigns the slot. Such content is never synced from the component.- */-export function ownsSlotContent(- graph: SceneGraph,- node: SceneNode,- propertyId = slotPropertyId(node)-): boolean {- if (!propertyId) return false- let owner = node.parentId ? graph.nodes.get(node.parentId) : undefined- while (owner && owner.type !== 'INSTANCE')- owner = owner.parentId ? graph.nodes.get(owner.parentId) : undefined- return !!owner && Object.hasOwn(owner.componentPropertyAssignments, propertyId)-}--/** The name of a slot property as its component (or the component's set) defines it. */-function slotName(graph: SceneGraph, componentId: string | null, propertyId: string) {- const component = componentId ? graph.nodes.get(componentId) : undefined- const set = component?.parentId ? graph.nodes.get(component.parentId) : undefined- return [component, set]- .flatMap((node) => node?.componentPropertyDefinitions ?? [])- .find((definition) => definition.id === propertyId && definition.type === 'SLOT')?.name-}--/** An instance's slot frames, without entering nested instances, whose slots are their own. */-function slotFrames(graph: SceneGraph, instance: SceneNode): SceneNode[] {- const frames: SceneNode[] = []- const visit = (node: SceneNode): void => {- for (const childId of node.childIds) {- const child = graph.nodes.get(childId)- if (!child) continue- if (slotPropertyId(child)) frames.push(child)- else if (child.type !== 'INSTANCE') visit(child)- }- }- visit(instance)- return frames-}--/** Owned slot content parked under its instance while the instance's component changes. */-export interface ParkedSlotContent {- /** Content layer ids by slot name, in layer order. */- content: Map<string, string[]>- /** The slot assignments the content was parked from. */- propertyIds: string[]-}--/**- * Park an instance's own slot content directly under the instance, by slot name, so the- * instance's component can be replaced. Figma keeps that content when a variant switch or- * swap lands on a component with a slot of the same name.- */-export function detachOwnedSlotContent(graph: SceneGraph, instance: SceneNode): ParkedSlotContent {- const parked: ParkedSlotContent = { content: new Map(), propertyIds: [] }- for (const frame of slotFrames(graph, instance)) {- const propertyId = slotPropertyId(frame)- if (!propertyId || !Object.hasOwn(instance.componentPropertyAssignments, propertyId)) continue- parked.propertyIds.push(propertyId)- const name = slotName(graph, instance.componentId, propertyId)- if (!name || parked.content.has(name)) continue- const content = [...frame.childIds]- for (const id of content) graph.reorderChild(id, instance.id, instance.childIds.length)- parked.content.set(name, content)- }- return parked-}--/** Move parked content into the new component's slots of the same name and reassign them. */-export function restoreOwnedSlotContent(- graph: SceneGraph,- instance: SceneNode,- parked: ParkedSlotContent-): void {- if (!parked.propertyIds.length) return- const assignments = Object.fromEntries(- Object.entries(instance.componentPropertyAssignments).filter(- ([id]) => !parked.propertyIds.includes(id)- )- )- const placed = new Set<string>()- for (const frame of slotFrames(graph, instance)) {- const propertyId = slotPropertyId(frame)- const name = propertyId && slotName(graph, instance.componentId, propertyId)- const content = name ? parked.content.get(name) : undefined- if (!propertyId || !name || !content || placed.has(name)) continue- for (const id of Array.from(frame.childIds)) graph.deleteNode(id)- for (const [index, id] of content.entries()) graph.reorderChild(id, frame.id, index)- assignments[propertyId] = ''- placed.add(name)- }- for (const [name, content] of parked.content)- if (!placed.has(name)) for (const id of content) graph.deleteNode(id)- graph.updateNode(instance.id, { componentPropertyAssignments: assignments })-}diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex e69410bc8..799e8033a 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -12,7 +12,11 @@ export * from './transfer'export * from './instance-overrides'export * from './images'export * from './components/properties'-export * from './components/slots'+export * from './slots/frames'+export { instanceMainComponent } from './instances/main-component'+export * from './slots/content'+export * from './slots/authoring'+export * from './slots/limits'export * from './copy'export { createDefaultNode } from './node-defaults'export {diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.tsindex b3cf21168..2dad1e9ab 100644--- a/packages/scene-graph/src/instances.ts+++ b/packages/scene-graph/src/instances.ts@@ -1,5 +1,4 @@import type { SceneGraph, SceneNode } from './'-import { detachOwnedSlotContent, restoreOwnedSlotContent } from './components/slots'import type { NodeCloneMode } from './copy'import {clearInstanceOverrides,@@ -19,6 +18,7 @@ import {syncChildren,updateSyncedProps} from './instances/sync'+import { detachOwnedSlotContent, restoreOwnedSlotContent } from './slots/frames'export type { NodeCloneMode } from './copy'export {diff --git a/packages/scene-graph/src/instances/main-component.ts b/packages/scene-graph/src/instances/main-component.tsnew file mode 100644index 000000000..1b155fd2b--- /dev/null+++ b/packages/scene-graph/src/instances/main-component.ts@@ -0,0 +1,19 @@+import type { SceneGraph } from '../index'+import type { SceneNode } from '../types'++/**+ * The main component an instance shows. An instance nested in another instance points at the+ * instance it was cloned from, so follow those links to the component.+ */+export function instanceMainComponent(+ graph: SceneGraph,+ instance: SceneNode+): SceneNode | undefined {+ const seen = new Set<string>()+ let current = instance.componentId ? graph.getNode(instance.componentId) : undefined+ while (current?.type === 'INSTANCE' && current.componentId && !seen.has(current.id)) {+ seen.add(current.id)+ current = graph.getNode(current.componentId)+ }+ return current?.type === 'COMPONENT' ? current : undefined+}diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.tsindex c20fbafc1..bc467ce35 100644--- a/packages/scene-graph/src/instances/sync.ts+++ b/packages/scene-graph/src/instances/sync.ts@@ -2,7 +2,6 @@import { isEqual } from 'es-toolkit/predicate'import type { ComponentPropertyReferenceField, SceneGraph, SceneNode } from '../'-import { ownsSlotContent, slotPropertyId } from '../components/slots'import { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from '../copy'import type { NodeCloneMode } from '../copy'import {@@ -12,6 +11,7 @@ import {type InstanceOverrideState} from '../instance-overrides'import { scaleNodeChanges } from '../scaling/node'+import { ownsSlotContent, slotPropertyId } from '../slots/frames'import { scaleVariableBindingUnits } from '../variables/units'import { INSTANCE_SYNC_FIELDS } from './fields'@@ -411,7 +411,12 @@ export function syncChildren(const componentScale =(compChild.componentScale * instParent.componentScale) / compParent.componentScaleconst source = sourceInTargetCoordinates(compChild, componentScale)- const updates: Partial<SceneNode> = { componentScale }+ // Which properties a layer serves is the component's to say; a slot or exposed layer+ // created on the component becomes one in every instance.+ const updates: Partial<SceneNode> = {+ componentScale,+ componentPropertyReferences: structuredClone(compChild.componentPropertyReferences)+ }syncBindingFields(instChild, source, updates, protectedField)for (const key of INSTANCE_SYNC_FIELDS) {if (key === 'boundVariables') continuediff --git a/packages/scene-graph/src/slots/authoring.ts b/packages/scene-graph/src/slots/authoring.tsnew file mode 100644index 000000000..04ae3599d--- /dev/null+++ b/packages/scene-graph/src/slots/authoring.ts@@ -0,0 +1,101 @@+import type { SceneGraph } from '../index'+import type { ComponentPropertyDefinition, SceneNode, SlotSettings } from '../types'+import { slotPropertyId } from './frames'++/** The settings a new slot starts with: no limits, any layer allowed. */+export const DEFAULT_SLOT_SETTINGS: SlotSettings = {+ allowPreferredValuesOnly: false,+ displayEmptyByDefault: false,+ stretchChildOnInsert: false+}++/**+ * The main component a layer belongs to, which defines the slots inside it. Layers of an+ * instance are not authored there, so a layer under an instance has none.+ */+export function slotOwner(graph: SceneGraph, node: SceneNode): SceneNode | undefined {+ let current = node.parentId ? graph.getNode(node.parentId) : undefined+ while (current && current.type !== 'CANVAS') {+ if (current.type === 'COMPONENT') return current+ if (current.type === 'INSTANCE') return undefined+ current = current.parentId ? graph.getNode(current.parentId) : undefined+ }+ return undefined+}++/** Whether a frame inside a main component can become a slot. */+export function canCreateSlot(graph: SceneGraph, node: SceneNode): boolean {+ return node.type === 'FRAME' && !slotPropertyId(node) && !!slotOwner(graph, node)+}++function uniqueSlotName(owner: SceneNode, base: string): string {+ const taken = new Set(owner.componentPropertyDefinitions.map((definition) => definition.name))+ if (!taken.has(base)) return base+ let index = 2+ while (taken.has(`${base} ${index}`)) index+++ return `${base} ${index}`+}++/**+ * Make a frame of a main component a slot: define a SLOT property, named after the frame, on+ * the component and bind the frame's children to it. Instances pick up the slot on their next+ * sync.+ */+export function createSlotProperty(+ graph: SceneGraph,+ frameId: string,+ id: string+): ComponentPropertyDefinition | null {+ const frame = graph.getNode(frameId)+ const owner = frame && canCreateSlot(graph, frame) ? slotOwner(graph, frame) : undefined+ if (!frame || !owner) return null+ const definition: ComponentPropertyDefinition = {+ id,+ name: uniqueSlotName(owner, frame.name.trim() || 'Slot'),+ type: 'SLOT',+ defaultValue: '',+ preferredValues: [],+ slotSettings: { ...DEFAULT_SLOT_SETTINGS }+ }+ graph.updateNode(owner.id, {+ componentPropertyDefinitions: [...owner.componentPropertyDefinitions, definition]+ })+ graph.updateNode(frame.id, {+ componentPropertyReferences: [+ ...frame.componentPropertyReferences,+ { propertyId: id, field: 'SLOT_CONTENT' }+ ]+ })+ return definition+}++/** What a slot's settings panel can change. */+export type SlotPropertyPatch = Partial<+ Pick<ComponentPropertyDefinition, 'name' | 'description' | 'preferredValues'>+> & { slotSettings?: Partial<SlotSettings> }++/** Change a slot property's name, description, preferred components, or limits. */+export function updateSlotProperty(+ graph: SceneGraph,+ ownerId: string,+ propertyId: string,+ patch: SlotPropertyPatch+): boolean {+ const owner = graph.getNode(ownerId)+ const current = owner?.componentPropertyDefinitions.find(+ (definition) => definition.id === propertyId && definition.type === 'SLOT'+ )+ if (!owner || !current) return false+ const { slotSettings, ...fields } = patch+ const next: ComponentPropertyDefinition = {+ ...current,+ ...fields,+ slotSettings: { ...DEFAULT_SLOT_SETTINGS, ...current.slotSettings, ...slotSettings }+ }+ graph.updateNode(owner.id, {+ componentPropertyDefinitions: owner.componentPropertyDefinitions.map((definition) =>+ definition.id === propertyId ? next : definition+ )+ })+ return true+}diff --git a/packages/scene-graph/src/slots/content.ts b/packages/scene-graph/src/slots/content.tsnew file mode 100644index 000000000..0594c0c85--- /dev/null+++ b/packages/scene-graph/src/slots/content.ts@@ -0,0 +1,124 @@+import type { SceneGraph } from '../index'+import { getInstanceOverride, setInstanceOverride } from '../instance-overrides'+import { cloneChildrenWithMapping } from '../instances/sync'+import type { SceneNode } from '../types'+import { ownsSlotContent, slotPropertyId } from './frames'++/**+ * Where layers may be added, moved, or removed under a parent:+ * - `free`: outside any instance, or inside a component definition;+ * - `slot`: inside a slot of an instance, whose content the instance owns or can claim;+ * - `locked`: anywhere else inside an instance, whose layers come from its component.+ */+export type SlotScope =+ | { kind: 'free' }+ | { kind: 'slot'; frame: SceneNode; instance: SceneNode; propertyId: string }+ | { kind: 'locked'; instance: SceneNode }++function parentOf(graph: SceneGraph, node: SceneNode): SceneNode | undefined {+ return node.parentId ? graph.nodes.get(node.parentId) : undefined+}++function nearestInstance(graph: SceneGraph, node: SceneNode): SceneNode | undefined {+ let current = parentOf(graph, node)+ while (current && current.type !== 'INSTANCE') current = parentOf(graph, current)+ return current+}++export function slotScope(graph: SceneGraph, parentId: string): SlotScope {+ let current = graph.nodes.get(parentId)+ while (current) {+ const propertyId = slotPropertyId(current)+ if (propertyId) {+ const instance = nearestInstance(graph, current)+ return instance ? { kind: 'slot', frame: current, instance, propertyId } : { kind: 'free' }+ }+ if (current.type === 'INSTANCE') return { kind: 'locked', instance: current }+ current = parentOf(graph, current)+ }+ return { kind: 'free' }+}++/** Every layer below `node`; `enterInstances` also walks the layers of nested instances. */+function descendants(graph: SceneGraph, node: SceneNode, enterInstances: boolean): SceneNode[] {+ const result: SceneNode[] = []+ const visit = (parent: SceneNode): void => {+ for (const childId of parent.childIds) {+ const child = graph.nodes.get(childId)+ if (!child) continue+ result.push(child)+ if (enterInstances || child.type !== 'INSTANCE') visit(child)+ }+ }+ visit(node)+ return result+}++/**+ * Make the instance own its slot's content, as Figma does on the first edit: the layers+ * stay where they are, but stop following the component. Overrides the instance held for+ * them become their own values, or move to the nested instance they belong to.+ */+export function claimSlotContent(+ graph: SceneGraph,+ scope: Extract<SlotScope, { kind: 'slot' }>+): void {+ const { frame, instance, propertyId } = scope+ if (ownsSlotContent(graph, frame, propertyId)) return+ const overrides = instance.instanceOverrides+ for (const node of descendants(graph, frame, false)) {+ overrides.descendants.delete(node.id)+ if (node.type !== 'INSTANCE') {+ graph.updateNode(node.id, { componentId: null })+ continue+ }+ // A nested instance keeps the overrides its former owner applied inside it.+ for (const inner of descendants(graph, node, true)) {+ const fields = overrides.descendants.get(inner.id)+ if (!fields) continue+ for (const [field, value] of fields)+ if (field !== 'sourceComponentId')+ setInstanceOverride(node.instanceOverrides, node.id, inner.id, field, value)+ overrides.descendants.delete(inner.id)+ }+ graph.updateNode(node.id, { instanceOverrides: node.instanceOverrides })+ }+ graph.updateNode(instance.id, {+ instanceOverrides: overrides,+ componentPropertyAssignments: { ...instance.componentPropertyAssignments, [propertyId]: '' }+ })+}++/** The component layer an instance layer was cloned from. */+function componentSource(instance: SceneNode, node: SceneNode): string | null {+ const mapped = getInstanceOverride(+ instance.instanceOverrides,+ instance.id,+ node.id,+ 'sourceComponentId'+ )+ return typeof mapped === 'string' ? mapped : node.componentId+}++/** Return the slot to its component's content: the instance stops owning it. */+export function resetSlotContent(+ graph: SceneGraph,+ scope: Extract<SlotScope, { kind: 'slot' }>+): void {+ const { frame, instance, propertyId } = scope+ for (const childId of Array.from(frame.childIds)) graph.deleteNode(childId)+ const assignments = { ...instance.componentPropertyAssignments }+ Reflect.deleteProperty(assignments, propertyId)+ graph.updateNode(instance.id, { componentPropertyAssignments: assignments })+ const source = componentSource(instance, frame)+ if (source && graph.nodes.has(source)) cloneChildrenWithMapping(graph, source, frame.id)+}++/** Remove everything from the slot; the instance keeps owning it, now empty. */+export function clearSlotContent(+ graph: SceneGraph,+ scope: Extract<SlotScope, { kind: 'slot' }>+): void {+ claimSlotContent(graph, scope)+ for (const childId of Array.from(scope.frame.childIds)) graph.deleteNode(childId)+}diff --git a/packages/scene-graph/src/slots/frames.ts b/packages/scene-graph/src/slots/frames.tsnew file mode 100644index 000000000..86c8bf5d1--- /dev/null+++ b/packages/scene-graph/src/slots/frames.ts@@ -0,0 +1,160 @@+import type { SceneGraph } from '../index'+import { instanceMainComponent } from '../instances/main-component'+import type { SceneNode } from '../types'++/** The slot property a frame holds the content of, if it is a slot. */+export function slotPropertyId(node: SceneNode): string | undefined {+ return node.componentPropertyReferences.find((reference) => reference.field === 'SLOT_CONTENT')+ ?.propertyId+}++/**+ * Whether this slot frame's children belong to its instance rather than its component: the+ * nearest enclosing instance assigns the slot. Such content is never synced from the component.+ */+export function ownsSlotContent(+ graph: SceneGraph,+ node: SceneNode,+ propertyId = slotPropertyId(node)+): boolean {+ if (!propertyId) return false+ let owner = node.parentId ? graph.nodes.get(node.parentId) : undefined+ while (owner && owner.type !== 'INSTANCE')+ owner = owner.parentId ? graph.nodes.get(owner.parentId) : undefined+ return !!owner && Object.hasOwn(owner.componentPropertyAssignments, propertyId)+}++/** The name of a slot property as the instance's component (or the component's set) defines it. */+function slotName(graph: SceneGraph, instance: SceneNode, propertyId: string) {+ const component = instanceMainComponent(graph, instance)+ const set = component?.parentId ? graph.nodes.get(component.parentId) : undefined+ return [component, set]+ .flatMap((node) => node?.componentPropertyDefinitions ?? [])+ .find((definition) => definition.id === propertyId && definition.type === 'SLOT')?.name+}++/** An instance's slot frames, without entering nested instances, whose slots are their own. */+export function instanceSlotFrames(graph: SceneGraph, instance: SceneNode): SceneNode[] {+ const frames: SceneNode[] = []+ const visit = (node: SceneNode): void => {+ for (const childId of node.childIds) {+ const child = graph.nodes.get(childId)+ if (!child) continue+ if (slotPropertyId(child)) frames.push(child)+ else if (child.type !== 'INSTANCE') visit(child)+ }+ }+ visit(instance)+ return frames+}++/** One slot's owned content, parked while the instance it belongs to is rebuilt. */+interface ParkedSlot {+ /** Names of the nested instances leading to the slot's owner; empty for the instance itself. */+ path: string[]+ /** The slot property's name, which the replacement must share. */+ name: string+ /** Content layer ids, in layer order. */+ content: string[]+}++/** Owned slot content parked under an instance while its component changes. */+export interface ParkedSlotContent {+ slots: ParkedSlot[]+ /** The instance's own slot assignments the content was parked from. */+ propertyIds: string[]+}++/** Instances directly inside this one: not inside another nested instance or a slot. */+function nestedInstances(graph: SceneGraph, owner: SceneNode): SceneNode[] {+ const found: SceneNode[] = []+ const visit = (node: SceneNode): void => {+ for (const childId of node.childIds) {+ const child = graph.nodes.get(childId)+ if (!child || slotPropertyId(child)) continue+ if (child.type === 'INSTANCE') found.push(child)+ else visit(child)+ }+ }+ visit(owner)+ return found+}++/** The nested instance a name path leads to from `root`, matched by layer name as Figma does. */+function instanceAtPath(+ graph: SceneGraph,+ root: SceneNode,+ path: readonly string[]+): SceneNode | undefined {+ let current: SceneNode | undefined = root+ for (const name of path) {+ current = current && nestedInstances(graph, current).find((node) => node.name === name)+ }+ return current+}++/**+ * Park the slot content an instance and the instances nested in it own, by slot name and the+ * nested instance's name path, directly under the instance, so its component can be replaced.+ * Figma keeps that content when a variant switch or swap leads to slots of the same names.+ */+export function detachOwnedSlotContent(graph: SceneGraph, instance: SceneNode): ParkedSlotContent {+ const parked: ParkedSlotContent = { slots: [], propertyIds: [] }+ const visit = (owner: SceneNode, path: string[]): void => {+ for (const nested of nestedInstances(graph, owner)) visit(nested, [...path, nested.name])+ for (const frame of instanceSlotFrames(graph, owner)) {+ const propertyId = slotPropertyId(frame)+ if (!propertyId || !Object.hasOwn(owner.componentPropertyAssignments, propertyId)) continue+ if (owner.id === instance.id) parked.propertyIds.push(propertyId)+ const name = slotName(graph, owner, propertyId)+ const key = [...path, name].join('\u0000')+ if (!name || parked.slots.some((slot) => [...slot.path, slot.name].join('\u0000') === key))+ continue+ const content = [...frame.childIds]+ for (const id of content) graph.reorderChild(id, instance.id, instance.childIds.length)+ parked.slots.push({ path, name, content })+ }+ }+ visit(instance, [])+ return parked+}++/** Move parked content into the slots of the same names and paths, and reassign them. */+export function restoreOwnedSlotContent(+ graph: SceneGraph,+ instance: SceneNode,+ parked: ParkedSlotContent+): void {+ if (parked.slots.length === 0 && parked.propertyIds.length === 0) return+ graph.updateNode(instance.id, {+ componentPropertyAssignments: Object.fromEntries(+ Object.entries(instance.componentPropertyAssignments).filter(+ ([id]) => !parked.propertyIds.includes(id)+ )+ )+ })+ for (const slot of parked.slots) {+ const owner = instanceAtPath(graph, instance, slot.path)+ const frame =+ owner &&+ instanceSlotFrames(graph, owner).find((candidate) => {+ const propertyId = slotPropertyId(candidate)+ return !!propertyId && slotName(graph, owner, propertyId) === slot.name+ })+ const propertyId = frame && slotPropertyId(frame)+ if (+ !owner ||+ !frame ||+ !propertyId ||+ Object.hasOwn(owner.componentPropertyAssignments, propertyId)+ ) {+ for (const id of slot.content) graph.deleteNode(id)+ continue+ }+ for (const id of Array.from(frame.childIds)) graph.deleteNode(id)+ for (const [index, id] of slot.content.entries()) graph.reorderChild(id, frame.id, index)+ graph.updateNode(owner.id, {+ componentPropertyAssignments: { ...owner.componentPropertyAssignments, [propertyId]: '' }+ })+ }+}diff --git a/packages/scene-graph/src/slots/limits.ts b/packages/scene-graph/src/slots/limits.tsnew file mode 100644index 000000000..5aced8127--- /dev/null+++ b/packages/scene-graph/src/slots/limits.ts@@ -0,0 +1,49 @@+import type { SceneGraph } from '../index'+import type { ComponentPropertyDefinition, SceneNode } from '../types'++/** A limit a slot's content breaks, named as Figma's `SlotNode.limitViolations` names them. */+export type SlotLimitViolation = 'BELOW_MIN' | 'ABOVE_MAX' | 'HAS_NON_PREFERRED'++/** Whether a component is among a slot's preferred values, by id, key, or library key. */+export function isPreferredComponent(+ component: SceneNode | undefined,+ preferredValues: readonly string[] = []+): boolean {+ if (!component) return false+ return [component.id, component.componentKey, component.sourceLibraryKey].some(+ (value) => !!value && preferredValues.includes(value)+ )+}++/** Content layers a preferred-only slot does not allow: anything but preferred instances. */+export function nonPreferredLayers(+ graph: SceneGraph,+ definition: ComponentPropertyDefinition,+ content: readonly SceneNode[]+): SceneNode[] {+ if (!definition.slotSettings?.allowPreferredValuesOnly) return []+ return content.filter(+ (node) =>+ node.type !== 'INSTANCE' ||+ !isPreferredComponent(+ node.componentId ? graph.getNode(node.componentId) : undefined,+ definition.preferredValues+ )+ )+}++/** The limits a slot's content breaks; below-minimum and above-maximum exclude each other. */+export function slotLimitViolations(+ graph: SceneGraph,+ definition: ComponentPropertyDefinition,+ content: readonly SceneNode[]+): SlotLimitViolation[] {+ const settings = definition.slotSettings+ const violations: SlotLimitViolation[] = []+ if (settings?.minChildren !== undefined && content.length < settings.minChildren)+ violations.push('BELOW_MIN')+ else if (settings?.maxChildren !== undefined && content.length > settings.maxChildren)+ violations.push('ABOVE_MAX')+ if (nonPreferredLayers(graph, definition, content).length) violations.push('HAS_NON_PREFERRED')+ return violations+}diff --git a/packages/scene-graph/tests/components/properties.test.ts b/packages/scene-graph/tests/components/properties.test.tsindex 759cff1fd..3a80ce852 100644--- a/packages/scene-graph/tests/components/properties.test.ts+++ b/packages/scene-graph/tests/components/properties.test.ts@@ -164,3 +164,32 @@ describe('component properties', () => {expect(graph.getNode(instance.id)?.componentPropertyAssignments).toEqual({})})})++describe('nested instances', () => {+ test('read and apply the properties of the component they show', () => {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const button = graph.createNode('COMPONENT', pageId, {+ name: 'Button',+ componentPropertyDefinitions: [+ { id: 'button:label', name: 'Label', type: 'TEXT', defaultValue: 'OK' }+ ]+ })+ graph.createNode('TEXT', button.id, {+ name: 'Label',+ text: 'OK',+ componentPropertyReferences: [{ propertyId: 'button:label', field: 'TEXT' }]+ })+ const toolbar = graph.createNode('COMPONENT', pageId, { name: 'Toolbar' })+ graph.createInstance(button.id, toolbar.id)+ const instance = graph.createInstance(toolbar.id, pageId)+ const [nested] = graph.getChildren(instance?.id ?? '')+ if (nested.type !== 'INSTANCE') throw new Error('Missing nested instance')++ expect(componentPropertyOwners(graph, nested).map((owner) => owner.id)).toEqual([button.id])+ expect(componentPropertyDefinitions(graph, nested).map(({ name }) => name)).toEqual(['Label'])+ const [label] = componentPropertyDefinitions(graph, nested)+ applyComponentPropertyValue(graph, nested.id, label, 'Save')+ expect(graph.getChildren(nested.id)[0]?.text).toBe('Save')+ })+})diff --git a/packages/scene-graph/tests/components/slots.test.ts b/packages/scene-graph/tests/slots/content.test.tssimilarity index 56%rename from packages/scene-graph/tests/components/slots.test.tsrename to packages/scene-graph/tests/slots/content.test.tsindex 82c9b1d31..565dea1e9 100644--- a/packages/scene-graph/tests/components/slots.test.ts+++ b/packages/scene-graph/tests/slots/content.test.ts@@ -1,6 +1,15 @@import { describe, expect, test } from 'bun:test'-import { SceneGraph, slotPropertyId, type SceneNode } from '@open-pencil/scene-graph'+import {+ claimSlotContent,+ clearSlotContent,+ ownsSlotContent,+ resetSlotContent,+ SceneGraph,+ slotPropertyId,+ slotScope,+ type SceneNode+} from '@open-pencil/scene-graph'/** A component set with a Small and a Large variant, each with a `Content` slot. */function panel(graph: SceneGraph, page: SceneNode) {@@ -86,3 +95,60 @@ describe('instance slot content', () => {expect([...graph.getAllNodes()].filter((node) => node.name === 'Mine')).toEqual([])})})++describe('slot scope', () => {+ function setup() {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const { small } = panel(graph, page)+ const instance = graph.createInstance(small.id, page.id)+ if (!instance) throw new Error('No instance')+ const [slot] = graph.getChildren(instance.id)+ const componentSlot = graph.getChildren(small.id)[0]+ return { graph, page, small, instance, slot, componentSlot }+ }+ const slotOf = (graph: SceneGraph, id: string) => {+ const scope = slotScope(graph, id)+ if (scope.kind !== 'slot') throw new Error(`Expected a slot, got ${scope.kind}`)+ return scope+ }++ test('classifies pages, component slots, instance slots, and the rest of an instance', () => {+ const { graph, page, instance, slot, componentSlot } = setup()+ const nested = graph.createNode('FRAME', slot.id, { name: 'Group' })+ expect(slotScope(graph, page.id).kind).toBe('free')+ expect(slotScope(graph, componentSlot.id).kind).toBe('free')+ expect(slotScope(graph, instance.id).kind).toBe('locked')+ expect(slotOf(graph, slot.id).frame.id).toBe(slot.id)+ expect(slotOf(graph, nested.id).frame.id).toBe(slot.id)+ })++ test('claiming keeps the content but stops it following the component', () => {+ const { graph, small, instance, slot } = setup()+ const [copied] = graph.getChildren(slot.id)+ expect(copied.componentId).not.toBeNull()++ claimSlotContent(graph, slotOf(graph, slot.id))++ expect(ownsSlotContent(graph, slot)).toBe(true)+ expect(graph.getChildren(slot.id).map((child) => child.name)).toEqual(['Default'])+ expect(copied.componentId).toBeNull()+ const defaultText = graph.getChildren(graph.getChildren(small.id)[0].id)[0]+ graph.updateNode(defaultText.id, { name: 'Edited default' })+ graph.syncInstances(small.id)+ expect(graph.getChildren(slot.id).map((child) => child.name)).toEqual(['Default'])+ expect(instance.componentPropertyAssignments).toEqual({ 'small:content': '' })+ })++ test('reset brings back the component content, and clear empties an owned slot', () => {+ const { graph, instance, slot } = setup()+ clearSlotContent(graph, slotOf(graph, slot.id))+ expect(graph.getChildren(slot.id)).toEqual([])+ expect(ownsSlotContent(graph, slot)).toBe(true)++ resetSlotContent(graph, slotOf(graph, slot.id))+ expect(graph.getChildren(slot.id).map((child) => child.name)).toEqual(['Default'])+ expect(instance.componentPropertyAssignments).toEqual({})+ expect(graph.getChildren(slot.id)[0].componentId).not.toBeNull()+ })+})diff --git a/packages/vue/src/controls/component-props/authoring.ts b/packages/vue/src/controls/component-props/authoring.tsindex 14c08bfb9..20977249f 100644--- a/packages/vue/src/controls/component-props/authoring.ts+++ b/packages/vue/src/controls/component-props/authoring.ts@@ -51,9 +51,26 @@ export function useVariantAuthoring() {return componentSetId ? editor.getComponentSetVariantConflicts(componentSetId) : []})- function addProperty(name: string, initialValue: string) {+ /**+ * Add a variant property, by default named Property 1, Property 2, … with the value Default,+ * as Figma does; returns its id so the caller can start renaming it.+ */+ function addProperty(name?: string, initialValue = 'Default'): string | undefined {const componentSetId = componentSet.value?.id- if (componentSetId) editor.addPropertyDefinition(componentSetId, name, 'VARIANT', initialValue)+ if (!componentSetId) return undefined+ return editor.addPropertyDefinition(+ componentSetId,+ name ?? nextPropertyName(),+ 'VARIANT',+ initialValue+ )+ }++ function nextPropertyName(): string {+ const taken = new Set(definitions.value.map((definition) => definition.name))+ let index = 1+ while (taken.has(`Property ${index}`)) index+++ return `Property ${index}`}function renameProperty(propertyId: string, name: string) {diff --git a/packages/vue/src/controls/component-props/index.ts b/packages/vue/src/controls/component-props/index.tsindex 5b6914aa1..deb12d631 100644--- a/packages/vue/src/controls/component-props/index.ts+++ b/packages/vue/src/controls/component-props/index.ts@@ -1,3 +1,4 @@export * from './authoring'export * from './model'+export * from './slots'export * from './use'diff --git a/packages/vue/src/controls/component-props/model.ts b/packages/vue/src/controls/component-props/model.tsindex 8b75f082a..f027dca37 100644--- a/packages/vue/src/controls/component-props/model.ts+++ b/packages/vue/src/controls/component-props/model.ts@@ -12,6 +12,8 @@ export interface ComponentPropertyOption {label: stringmissing?: booleandisabled?: boolean+ /** A swap choice the property's definition recommends. */+ preferred?: boolean}export interface ComponentPropertyControl {@@ -56,7 +58,6 @@ export function instanceSwapOptions((left, right) =>Number(right.preferred) - Number(left.preferred) || left.label.localeCompare(right.label))- .map(({ value: optionValue, label }) => ({ value: optionValue, label }))if (value && !options.some((option) => option.value === value)) {options.push({ value, label: value, missing: true })}diff --git a/packages/vue/src/controls/component-props/slots.ts b/packages/vue/src/controls/component-props/slots.tsnew file mode 100644index 000000000..4dd90525e--- /dev/null+++ b/packages/vue/src/controls/component-props/slots.ts@@ -0,0 +1,264 @@+import {+ canCreateSlot,+ instanceSlotFrames,+ isPreferredComponent,+ nonPreferredLayers,+ ownsSlotContent,+ slotOwner,+ slotPropertyId+} from '@open-pencil/scene-graph'+import type {+ ComponentPropertyDefinition,+ SceneGraph,+ SceneNode,+ SlotPropertyPatch+} from '@open-pencil/scene-graph'++import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'++/** One configured limit of a slot and whether the instance's content meets it. */+export type SlotLimit =+ | { kind: 'minimum'; count: number; met: boolean }+ | { kind: 'maximum'; count: number; met: boolean }+ | { kind: 'preferred'; met: boolean; offending: number }++/** A component the Add instances list can insert into a slot. */+export interface SlotInstanceOption {+ id: string+ name: string+ preferred: boolean+ /** The page or library the component comes from. */+ source: string+}++export interface SlotPropertyControl {+ id: string+ name: string+ /** The instance's frame that holds this slot's content. */+ frameId: string+ /** Whether the instance owns the content instead of following its component. */+ modified: boolean+ itemCount: number+ limits: SlotLimit[]+ preferredOnly: boolean+ /** Content layers that break the preferred-only limit. */+ offendingIds: string[]+}++/** A slot's limits, measured against the content the instance shows. */+export function slotLimits(+ graph: SceneGraph,+ definition: ComponentPropertyDefinition,+ content: readonly SceneNode[]+): { limits: SlotLimit[]; offendingIds: string[] } {+ const settings = definition.slotSettings+ const limits: SlotLimit[] = []+ let offendingIds: string[] = []+ if (!settings) return { limits, offendingIds }+ if (settings.minChildren !== undefined)+ limits.push({+ kind: 'minimum',+ count: settings.minChildren,+ met: content.length >= settings.minChildren+ })+ if (settings.maxChildren !== undefined)+ limits.push({+ kind: 'maximum',+ count: settings.maxChildren,+ met: content.length <= settings.maxChildren+ })+ if (settings.allowPreferredValuesOnly) {+ offendingIds = nonPreferredLayers(graph, definition, content).map((node) => node.id)+ limits.push({+ kind: 'preferred',+ met: offendingIds.length === 0,+ offending: offendingIds.length+ })+ }+ return { limits, offendingIds }+}++function pageName(graph: SceneGraph, node: SceneNode): string {+ let current: SceneNode | undefined = node+ while (current && current.type !== 'CANVAS')+ current = current.parentId ? graph.getNode(current.parentId) : undefined+ return current?.name ?? ''+}++/** Components a slot can take, its preferred ones first. */+export function slotInstanceOptions(+ graph: SceneGraph,+ definition: ComponentPropertyDefinition+): SlotInstanceOption[] {+ return [...graph.getAllNodes()]+ .filter((node) => node.type === 'COMPONENT')+ .map((node) => ({+ id: node.id,+ name: node.name,+ preferred: isPreferredComponent(node, definition.preferredValues),+ source: pageName(graph, node)+ }))+ .sort(+ (left, right) =>+ Number(right.preferred) - Number(left.preferred) || left.name.localeCompare(right.name)+ )+}++/** Slot properties of the single selected instance, and the actions on their content. */+export function useSlotProperties() {+ const editor = useEditor()+ const instance = useSceneComputed(() => {+ const nodes = editor.getSelectedNodes()+ return nodes.length === 1 && nodes[0].type === 'INSTANCE' ? nodes[0] : undefined+ })+ const definitions = useSceneComputed(() =>+ instance.value+ ? editor+ .getInstanceComponentPropertyDefinitions(instance.value.id)+ .filter((definition) => definition.type === 'SLOT')+ : []+ )+ const slots = useSceneComputed<SlotPropertyControl[]>(() => {+ const owner = instance.value+ if (!owner) return []+ const frames = instanceSlotFrames(editor.graph, owner)+ return definitions.value.flatMap((definition) => {+ const frame = frames.find((candidate) => slotPropertyId(candidate) === definition.id)+ if (!frame) return []+ const content = editor.graph.getChildren(frame.id)+ const { limits, offendingIds } = slotLimits(editor.graph, definition, content)+ return [+ {+ id: definition.id,+ name: definition.name,+ frameId: frame.id,+ modified: ownsSlotContent(editor.graph, frame, definition.id),+ itemCount: content.length,+ limits,+ preferredOnly: definition.slotSettings?.allowPreferredValuesOnly ?? false,+ offendingIds+ }+ ]+ })+ })++ function options(propertyId: string): SlotInstanceOption[] {+ const definition = definitions.value.find((item) => item.id === propertyId)+ return definition ? slotInstanceOptions(editor.graph, definition) : []+ }++ return {+ slots,+ options,+ add: (frameId: string, componentId: string) => editor.addInstanceToSlot(frameId, componentId),+ reset: (frameId: string) => editor.resetSlot(frameId),+ clear: (frameId: string) => editor.clearSlot(frameId),+ selectLayers: (ids: string[]) => editor.select(ids)+ }+}++/** A slot property as its main component defines it. */+export interface SlotDefinitionControl {+ id: string+ name: string+ description: string+ minChildren?: number+ maxChildren?: number+ preferredOnly: boolean+ /** Components the slot prefers, resolved from the definition's preferred values. */+ preferred: SlotInstanceOption[]+}++/** The value a preferred-components list stores for a component: its key, else its id. */+function preferredValue(component: SceneNode): string {+ return component.componentKey ?? component.id+}++/**+ * Slot properties of the selected main component or slot frame, with the actions that+ * create, configure, and remove them.+ */+export function useSlotAuthoring() {+ const editor = useEditor()+ const target = useSceneComputed(() => {+ const nodes = editor.getSelectedNodes()+ if (nodes.length !== 1) return undefined+ const [node] = nodes+ if (node.type === 'COMPONENT') return { owner: node, frame: undefined, propertyId: undefined }+ const owner = slotOwner(editor.graph, node)+ if (!owner) return undefined+ const propertyId = slotPropertyId(node)+ if (!propertyId && !canCreateSlot(editor.graph, node)) return undefined+ return { owner, frame: node, propertyId }+ })+ const slots = useSceneComputed<SlotDefinitionControl[]>(() => {+ const current = target.value+ if (!current) return []+ return current.owner.componentPropertyDefinitions+ .filter((definition) => definition.type === 'SLOT')+ .filter((definition) => !current.frame || definition.id === current.propertyId)+ .map((definition) => {+ const values = new Set(definition.preferredValues)+ return {+ id: definition.id,+ name: definition.name,+ description: definition.description ?? '',+ minChildren: definition.slotSettings?.minChildren,+ maxChildren: definition.slotSettings?.maxChildren,+ preferredOnly: definition.slotSettings?.allowPreferredValuesOnly ?? false,+ preferred: slotInstanceOptions(editor.graph, definition).filter(+ (option) => option.preferred && values.size > 0+ )+ }+ })+ })+ /** Whether the selection is a frame that can become a slot. */+ const canCreate = useSceneComputed(() => !!target.value?.frame && !target.value.propertyId)+ const active = useSceneComputed(() => slots.value.length > 0 || canCreate.value)++ function update(propertyId: string, patch: SlotPropertyPatch) {+ const owner = target.value?.owner+ if (owner) editor.updateSlot(owner.id, propertyId, patch)+ }++ function definition(propertyId: string): ComponentPropertyDefinition | undefined {+ return target.value?.owner.componentPropertyDefinitions.find((item) => item.id === propertyId)+ }++ /** Components that can be marked preferred, the slot's current choices first. */+ function options(propertyId: string): SlotInstanceOption[] {+ const found = definition(propertyId)+ return found ? slotInstanceOptions(editor.graph, found) : []+ }++ function setPreferred(propertyId: string, componentId: string, preferred: boolean) {+ const found = definition(propertyId)+ const component = editor.graph.getNode(componentId)+ if (!found || !component) return+ const keys = new Set([component.id, component.componentKey, component.sourceLibraryKey])+ const rest = (found.preferredValues ?? []).filter((value) => !keys.has(value))+ update(propertyId, {+ preferredValues: preferred ? [...rest, preferredValue(component)] : rest+ })+ }++ return {+ active,+ canCreate,+ slots,+ options,+ create: () => editor.createSlot(),+ rename: (propertyId: string, name: string) => update(propertyId, { name }),+ describe: (propertyId: string, description: string) => update(propertyId, { description }),+ setLimits: (propertyId: string, limits: { minChildren?: number; maxChildren?: number }) =>+ update(propertyId, { slotSettings: limits }),+ setPreferredOnly: (propertyId: string, value: boolean) =>+ update(propertyId, { slotSettings: { allowPreferredValuesOnly: value } }),+ setPreferred,+ remove: (propertyId: string) => {+ const owner = target.value?.owner+ if (owner) editor.removeSlot(owner.id, propertyId)+ }+ }+}diff --git a/packages/vue/src/controls/component-props/use.ts b/packages/vue/src/controls/component-props/use.tsindex bd08a8f70..eb8d56a29 100644--- a/packages/vue/src/controls/component-props/use.ts+++ b/packages/vue/src/controls/component-props/use.ts@@ -54,7 +54,12 @@ export function useComponentProperties() {const definitionSets = useSceneComputed(() =>instances.value.map((instance) => editor.getInstanceComponentPropertyDefinitions(instance.id)))- const definitions = computed(() => compatibleComponentPropertyDefinitions(definitionSets.value))+ // Slots render as their own rows (useSlotProperties), not as value controls.+ const definitions = computed(() =>+ compatibleComponentPropertyDefinitions(definitionSets.value).filter(+ (definition) => definition.type !== 'SLOT'+ )+ )const active = computed(() => allSelectedAreInstances.value && definitions.value.length > 0)const controls = useSceneComputed<ComponentPropertyControl[]>(() => {if (!active.value || instances.value.length === 0) return []diff --git a/packages/vue/src/editor/commands/registry.ts b/packages/vue/src/editor/commands/registry.tsindex d3b73e24f..70283ae61 100644--- a/packages/vue/src/editor/commands/registry.ts+++ b/packages/vue/src/editor/commands/registry.ts@@ -33,6 +33,7 @@ export const EDITOR_COMMAND_METADATA = {'selection.detachInstance': { shortcut: 'MOD+ALT+B', keybinding: '$mod+Alt+KeyB' },'selection.goToMainComponent': {},'selection.createInstance': {},+ 'selection.createSlot': { contextTestId: 'context-create-slot' },'selection.wrapInAutoLayout': { shortcut: 'SHIFT+A', keybinding: 'Shift+KeyA' },'selection.toggleMask': {shortcut: 'MOD+ALT+M',diff --git a/packages/vue/src/editor/commands/selection.ts b/packages/vue/src/editor/commands/selection.tsindex 022409a8f..6b0dd8b62 100644--- a/packages/vue/src/editor/commands/selection.ts+++ b/packages/vue/src/editor/commands/selection.ts@@ -132,6 +132,14 @@ export function createSelectionCommands({enabled: capabilities.canGoToMainComponent,run: () => void editor.goToMainComponent()},+ 'selection.createSlot': {+ id: 'selection.createSlot',+ get label() {+ return t.value.createSlot+ },+ enabled: capabilities.canCreateSlot,+ run: () => void editor.createSlot()+ },'selection.wrapInAutoLayout': {id: 'selection.wrapInAutoLayout',get label() {diff --git a/packages/vue/src/editor/commands/types.ts b/packages/vue/src/editor/commands/types.tsindex 8c79c80de..60b328f72 100644--- a/packages/vue/src/editor/commands/types.ts+++ b/packages/vue/src/editor/commands/types.ts@@ -15,6 +15,7 @@ export type EditorCommandId =| 'selection.createInstance'| 'selection.detachInstance'| 'selection.goToMainComponent'+ | 'selection.createSlot'| 'selection.wrapInAutoLayout'| 'selection.toggleMask'| 'selection.bringForward'diff --git a/packages/vue/src/editor/menu-model/canvas.ts b/packages/vue/src/editor/menu-model/canvas.tsindex 1563cc3eb..3175fb291 100644--- a/packages/vue/src/editor/menu-model/canvas.ts+++ b/packages/vue/src/editor/menu-model/canvas.ts@@ -69,7 +69,8 @@ function componentItems({ commandMenuItem, selection }: CanvasMenuOptions): Menureturn [selection.isComponent.value? commandMenuItem('selection.createInstance')- : commandMenuItem('selection.createComponent')+ : commandMenuItem('selection.createComponent'),+ ...(selection.canCreateSlot.value ? [commandMenuItem('selection.createSlot')] : [])]}diff --git a/packages/vue/src/editor/selection-capabilities/use.ts b/packages/vue/src/editor/selection-capabilities/use.tsindex e8df44799..d10a36595 100644--- a/packages/vue/src/editor/selection-capabilities/use.ts+++ b/packages/vue/src/editor/selection-capabilities/use.ts@@ -69,6 +69,7 @@ export function useSelectionCapabilities() {}),canGoToMainComponent: computed(() => selection.isInstance.value),canCreateInstance: computed(() => selectedNode.value?.type === 'COMPONENT'),+ canCreateSlot: selection.canCreateSlot,canMoveToPage: useSceneComputed(() => hasSelection.value && editor.graph.getPages().length > 1),canSetOpacity: computed(() => hasSelection.value),canSelectAll: useSceneComputed(diff --git a/packages/vue/src/editor/selection-state/use.ts b/packages/vue/src/editor/selection-state/use.tsindex a895063d9..c356c5a4f 100644--- a/packages/vue/src/editor/selection-state/use.ts+++ b/packages/vue/src/editor/selection-state/use.ts@@ -1,5 +1,7 @@import { computed } from 'vue'+import { canCreateSlot as canBecomeSlot, slotOwner, slotPropertyId } from '@open-pencil/scene-graph'+import { useEditor } from '#vue/editor/context'import { useSelectedNodeState } from '#vue/editor/selection-state/nodes'import { useSceneComputed } from '#vue/internal/scene-computed/use'@@ -35,6 +37,16 @@ export function useSelectionState() {return true})+ // A frame of a main component becomes a slot; other sibling layers there are wrapped in one.+ const canCreateSlot = useSceneComputed(() => {+ const nodes = editor.getSelectedNodes()+ const first = nodes.at(0)+ if (!first || nodes.some((node) => node.parentId !== first.parentId || slotPropertyId(node)))+ return false+ if (nodes.length === 1 && canBecomeSlot(editor.graph, first)) return true+ return !!slotOwner(editor.graph, first)+ })+return {editor,selectedIds,@@ -45,6 +57,7 @@ export function useSelectionState() {isInstance,isComponent,isGroup,- canCreateComponentSet+ canCreateComponentSet,+ canCreateSlot}}diff --git a/packages/vue/src/i18n/locales/de/commands.json b/packages/vue/src/i18n/locales/de/commands.jsonindex 4ca8bb997..5e1bb852f 100644--- a/packages/vue/src/i18n/locales/de/commands.json+++ b/packages/vue/src/i18n/locales/de/commands.json@@ -7,6 +7,7 @@"group": "Gruppieren","ungroup": "Gruppierung aufheben","createComponent": "Komponente erstellen",+ "createSlot": "Slot erstellen","createComponentSet": "Komponentensatz erstellen","createInstance": "Instanz erstellen","detachInstance": "Instanz lösen",diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex a9dfce2ad..536617ac6 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -151,6 +151,10 @@"auto": "Automatisch","columns": "Spalten","rows": "Zeilen",+ "addGridColumn": "Spalte hinzufügen",+ "addGridRow": "Zeile hinzufügen",+ "removeGridColumn": "Spalte entfernen",+ "removeGridRow": "Zeile entfernen","sizingFixed": "Fest","sizingHug": "An Inhalt anpassen","sizingFill": "Füllen",@@ -183,6 +187,58 @@"add": "Hinzufügen","variants": "Varianten","componentProperties": "Komponenteneigenschaften",+ "slotDefault": "Standard",+ "slotModified": "Geändert",+ "slotItemCount": {+ "one": "{count} Element",+ "many": "{count} Elemente"+ },+ "addInstances": "Instanzen hinzufügen",+ "searchInstances": "Komponenten suchen",+ "preferredInstances": "Bevorzugt",+ "allInstances": "Alle Komponenten",+ "noInstancesFound": "Keine Komponenten gefunden",+ "notPreferredInstance": "Nicht bevorzugt",+ "slotLimits": "Slot-Grenzen",+ "slotLimitCount": {+ "one": "{count} Grenze",+ "many": "{count} Grenzen"+ },+ "slotLimitIssueCount": {+ "one": "{count} Problem",+ "many": "{count} Probleme"+ },+ "slotMinimumLayers": {+ "one": "Mindestens {count} Ebene",+ "many": "Mindestens {count} Ebenen"+ },+ "slotMaximumLayers": {+ "one": "Höchstens {count} Ebene",+ "many": "Höchstens {count} Ebenen"+ },+ "slotPreferredOnly": "Nur bevorzugte Instanzen",+ "slotNonPreferredFound": {+ "one": "{count} Ebene ist nicht bevorzugt",+ "many": "{count} Ebenen sind nicht bevorzugt"+ },+ "selectLayers": "Ebenen auswählen",+ "resetSlot": "Slot zurücksetzen",+ "deleteSlotContents": "Inhalt löschen",+ "slotActions": "Aktionen für {name}",+ "slots": "Slots",+ "createSlot": "Slot erstellen",+ "removeSlot": "Slot entfernen",+ "slotSettings": "Slot-Einstellungen",+ "slotName": "Slot-Name",+ "slotDescription": "Beschreibung",+ "slotMinimum": "Mindestanzahl Ebenen",+ "slotMaximum": "Höchstanzahl Ebenen",+ "slotNoLimit": "Keine Grenze",+ "addPreferredInstances": "Bevorzugte Instanzen hinzufügen",+ "removePreferredInstance": "Aus bevorzugten entfernen",+ "searchStyles": "Stile suchen",+ "noStylesFound": "Keine Stile gefunden",+ "noComponentsFound": "Keine Komponenten gefunden","gapAuto": "Automatischer Abstand","horizontalGap": "Horizontaler Abstand","verticalGap": "Vertikaler Abstand",@@ -264,11 +320,9 @@"assetVariantSummary": "{count} Varianten · {names}","duplicateVariantValues": "Doppelte Variantenwerte","variantPropertyName": "Eigenschaftsname",- "variantPropertyValue": "Anfangswert","addVariantProperty": "Varianteneigenschaft hinzufügen","addVariant": "Variante hinzufügen","duplicateVariant": "Variante duplizieren",- "removeVariant": "Variante entfernen","removeVariantProperty": "Varianteneigenschaft entfernen","moveVariantPropertyUp": "Varianteneigenschaft nach oben verschieben","moveVariantPropertyDown": "Varianteneigenschaft nach unten verschieben",diff --git a/packages/vue/src/i18n/locales/es/commands.json b/packages/vue/src/i18n/locales/es/commands.jsonindex 6e04f0938..b2b4539e7 100644--- a/packages/vue/src/i18n/locales/es/commands.json+++ b/packages/vue/src/i18n/locales/es/commands.json@@ -7,6 +7,7 @@"group": "Agrupar","ungroup": "Desagrupar","createComponent": "Crear componente",+ "createSlot": "Crear slot","createComponentSet": "Crear conjunto de componentes","createInstance": "Crear instancia","detachInstance": "Separar instancia",diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex 5a4feadc5..fea4df837 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -165,6 +165,10 @@"auto": "Auto","columns": "Columnas","rows": "Filas",+ "addGridColumn": "Añadir columna",+ "addGridRow": "Añadir fila",+ "removeGridColumn": "Quitar columna",+ "removeGridRow": "Quitar fila","gap": "Espaciado","sizingFixed": "Fijo","sizingHug": "Ajustar al contenido",@@ -200,6 +204,58 @@"add": "Añadir","variants": "Variantes","componentProperties": "Propiedades del componente",+ "slotDefault": "Predeterminado",+ "slotModified": "Modificado",+ "slotItemCount": {+ "one": "{count} elemento",+ "many": "{count} elementos"+ },+ "addInstances": "Añadir instancias",+ "searchInstances": "Buscar componentes",+ "preferredInstances": "Preferidos",+ "allInstances": "Todos los componentes",+ "noInstancesFound": "No se encontraron componentes",+ "notPreferredInstance": "No preferido",+ "slotLimits": "Límites del slot",+ "slotLimitCount": {+ "one": "{count} límite",+ "many": "{count} límites"+ },+ "slotLimitIssueCount": {+ "one": "{count} problema",+ "many": "{count} problemas"+ },+ "slotMinimumLayers": {+ "one": "Al menos {count} capa",+ "many": "Al menos {count} capas"+ },+ "slotMaximumLayers": {+ "one": "Como máximo {count} capa",+ "many": "Como máximo {count} capas"+ },+ "slotPreferredOnly": "Solo instancias preferidas",+ "slotNonPreferredFound": {+ "one": "{count} capa no es preferida",+ "many": "{count} capas no son preferidas"+ },+ "selectLayers": "Seleccionar capas",+ "resetSlot": "Restablecer slot",+ "deleteSlotContents": "Eliminar contenido",+ "slotActions": "Acciones de {name}",+ "slots": "Slots",+ "createSlot": "Crear slot",+ "removeSlot": "Quitar slot",+ "slotSettings": "Ajustes del slot",+ "slotName": "Nombre del slot",+ "slotDescription": "Descripción",+ "slotMinimum": "Mínimo de capas",+ "slotMaximum": "Máximo de capas",+ "slotNoLimit": "Sin límite",+ "addPreferredInstances": "Añadir instancias preferidas",+ "removePreferredInstance": "Quitar de preferidas",+ "searchStyles": "Buscar estilos",+ "noStylesFound": "No se encontraron estilos",+ "noComponentsFound": "No se encontraron componentes","gapAuto": "Espaciado auto","horizontalGap": "Espaciado horizontal","verticalGap": "Espaciado vertical",@@ -281,11 +337,9 @@"assetVariantSummary": "{count} variantes · {names}","duplicateVariantValues": "Valores de variante duplicados","variantPropertyName": "Nombre de la propiedad",- "variantPropertyValue": "Valor inicial","addVariantProperty": "Agregar propiedad de variante","addVariant": "Agregar variante","duplicateVariant": "Duplicar variante",- "removeVariant": "Eliminar variante","removeVariantProperty": "Eliminar propiedad de variante","moveVariantPropertyUp": "Mover propiedad variante hacia arriba","moveVariantPropertyDown": "Mover propiedad variante hacia abajo",diff --git a/packages/vue/src/i18n/locales/fr/commands.json b/packages/vue/src/i18n/locales/fr/commands.jsonindex 0ffe13fa4..2f3ed8e41 100644--- a/packages/vue/src/i18n/locales/fr/commands.json+++ b/packages/vue/src/i18n/locales/fr/commands.json@@ -7,6 +7,7 @@"group": "Grouper","ungroup": "Dégrouper","createComponent": "Créer un composant",+ "createSlot": "Créer un slot","createComponentSet": "Créer un jeu de composants","createInstance": "Créer une instance","detachInstance": "Détacher l'instance",diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex 07a6593fb..005e9ecf5 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -151,6 +151,10 @@"auto": "Auto","columns": "Colonnes","rows": "Lignes",+ "addGridColumn": "Ajouter une colonne",+ "addGridRow": "Ajouter une ligne",+ "removeGridColumn": "Supprimer la colonne",+ "removeGridRow": "Supprimer la ligne","sizingFixed": "Fixe","sizingHug": "Ajuster au contenu","sizingFill": "Remplir",@@ -183,6 +187,58 @@"add": "Ajouter","variants": "Variantes","componentProperties": "Propriétés du composant",+ "slotDefault": "Par défaut",+ "slotModified": "Modifié",+ "slotItemCount": {+ "one": "{count} élément",+ "many": "{count} éléments"+ },+ "addInstances": "Ajouter des instances",+ "searchInstances": "Rechercher des composants",+ "preferredInstances": "Préférés",+ "allInstances": "Tous les composants",+ "noInstancesFound": "Aucun composant trouvé",+ "notPreferredInstance": "Non préféré",+ "slotLimits": "Limites du slot",+ "slotLimitCount": {+ "one": "{count} limite",+ "many": "{count} limites"+ },+ "slotLimitIssueCount": {+ "one": "{count} problème",+ "many": "{count} problèmes"+ },+ "slotMinimumLayers": {+ "one": "Au moins {count} calque",+ "many": "Au moins {count} calques"+ },+ "slotMaximumLayers": {+ "one": "Au plus {count} calque",+ "many": "Au plus {count} calques"+ },+ "slotPreferredOnly": "Instances préférées uniquement",+ "slotNonPreferredFound": {+ "one": "{count} calque n’est pas préféré",+ "many": "{count} calques ne sont pas préférés"+ },+ "selectLayers": "Sélectionner les calques",+ "resetSlot": "Réinitialiser le slot",+ "deleteSlotContents": "Supprimer le contenu",+ "slotActions": "Actions de {name}",+ "slots": "Slots",+ "createSlot": "Créer un slot",+ "removeSlot": "Supprimer le slot",+ "slotSettings": "Réglages du slot",+ "slotName": "Nom du slot",+ "slotDescription": "Description",+ "slotMinimum": "Calques minimum",+ "slotMaximum": "Calques maximum",+ "slotNoLimit": "Sans limite",+ "addPreferredInstances": "Ajouter des instances préférées",+ "removePreferredInstance": "Retirer des préférées",+ "searchStyles": "Rechercher des styles",+ "noStylesFound": "Aucun style trouvé",+ "noComponentsFound": "Aucun composant trouvé","gapAuto": "Espacement auto","horizontalGap": "Espacement horizontal","verticalGap": "Espacement vertical",@@ -264,11 +320,9 @@"assetVariantSummary": "{count} variantes · {names}","duplicateVariantValues": "Valeurs de variante en double","variantPropertyName": "Nom de la propriété",- "variantPropertyValue": "Valeur initiale","addVariantProperty": "Ajouter une propriété de variante","addVariant": "Ajouter une variante","duplicateVariant": "Variante en double",- "removeVariant": "Supprimer la variante","removeVariantProperty": "Supprimer la propriété de variante","moveVariantPropertyUp": "Déplacer la propriété de variante vers le haut","moveVariantPropertyDown": "Déplacer la propriété de variante vers le bas",diff --git a/packages/vue/src/i18n/locales/it/commands.json b/packages/vue/src/i18n/locales/it/commands.jsonindex 2a8f305a4..a886df13f 100644--- a/packages/vue/src/i18n/locales/it/commands.json+++ b/packages/vue/src/i18n/locales/it/commands.json@@ -7,6 +7,7 @@"group": "Raggruppa","ungroup": "Separa","createComponent": "Crea componente",+ "createSlot": "Crea slot","createComponentSet": "Crea set di componenti","createInstance": "Crea istanza","detachInstance": "Scollega istanza",diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex c1bd89022..429ca0b59 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -151,6 +151,10 @@"auto": "Auto","columns": "Colonne","rows": "Righe",+ "addGridColumn": "Aggiungi colonna",+ "addGridRow": "Aggiungi riga",+ "removeGridColumn": "Rimuovi colonna",+ "removeGridRow": "Rimuovi riga","sizingFixed": "Fisso","sizingHug": "Adatta al contenuto","sizingFill": "Riempi",@@ -183,6 +187,58 @@"add": "Aggiungi","variants": "Varianti","componentProperties": "Proprietà del componente",+ "slotDefault": "Predefinito",+ "slotModified": "Modificato",+ "slotItemCount": {+ "one": "{count} elemento",+ "many": "{count} elementi"+ },+ "addInstances": "Aggiungi istanze",+ "searchInstances": "Cerca componenti",+ "preferredInstances": "Preferiti",+ "allInstances": "Tutti i componenti",+ "noInstancesFound": "Nessun componente trovato",+ "notPreferredInstance": "Non preferito",+ "slotLimits": "Limiti dello slot",+ "slotLimitCount": {+ "one": "{count} limite",+ "many": "{count} limiti"+ },+ "slotLimitIssueCount": {+ "one": "{count} problema",+ "many": "{count} problemi"+ },+ "slotMinimumLayers": {+ "one": "Almeno {count} livello",+ "many": "Almeno {count} livelli"+ },+ "slotMaximumLayers": {+ "one": "Al massimo {count} livello",+ "many": "Al massimo {count} livelli"+ },+ "slotPreferredOnly": "Solo istanze preferite",+ "slotNonPreferredFound": {+ "one": "{count} livello non è preferito",+ "many": "{count} livelli non sono preferiti"+ },+ "selectLayers": "Seleziona livelli",+ "resetSlot": "Ripristina slot",+ "deleteSlotContents": "Elimina contenuto",+ "slotActions": "Azioni di {name}",+ "slots": "Slot",+ "createSlot": "Crea slot",+ "removeSlot": "Rimuovi slot",+ "slotSettings": "Impostazioni dello slot",+ "slotName": "Nome dello slot",+ "slotDescription": "Descrizione",+ "slotMinimum": "Livelli minimi",+ "slotMaximum": "Livelli massimi",+ "slotNoLimit": "Nessun limite",+ "addPreferredInstances": "Aggiungi istanze preferite",+ "removePreferredInstance": "Rimuovi dalle preferite",+ "searchStyles": "Cerca stili",+ "noStylesFound": "Nessuno stile trovato",+ "noComponentsFound": "Nessun componente trovato","gapAuto": "Spaziatura auto","horizontalGap": "Spaziatura orizzontale","verticalGap": "Spaziatura verticale",@@ -264,11 +320,9 @@"assetVariantSummary": "{count} varianti · {names}","duplicateVariantValues": "Valori variante duplicati","variantPropertyName": "Nome della proprietà",- "variantPropertyValue": "Valore iniziale","addVariantProperty": "Aggiungi proprietà variante","addVariant": "Aggiungi variante","duplicateVariant": "Duplica variante",- "removeVariant": "Rimuovi variante","removeVariantProperty": "Rimuovi la proprietà della variante","moveVariantPropertyUp": "Sposta la proprietà della variante verso l'alto","moveVariantPropertyDown": "Sposta la proprietà della variante verso il basso",diff --git a/packages/vue/src/i18n/locales/ja/commands.json b/packages/vue/src/i18n/locales/ja/commands.jsonindex fe3f58c18..b908ca159 100644--- a/packages/vue/src/i18n/locales/ja/commands.json+++ b/packages/vue/src/i18n/locales/ja/commands.json@@ -7,6 +7,7 @@"group": "グループ化","ungroup": "グループ解除","createComponent": "コンポーネントを作成",+ "createSlot": "スロットを作成","createComponentSet": "コンポーネントセットを作成","createInstance": "インスタンスを作成","detachInstance": "インスタンスの切り離し",diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex 81ff8bfd0..9b2dc8dc3 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -165,6 +165,10 @@"auto": "自動","columns": "列","rows": "行",+ "addGridColumn": "列を追加",+ "addGridRow": "行を追加",+ "removeGridColumn": "列を削除",+ "removeGridRow": "行を削除","gap": "間隔","sizingFixed": "固定","sizingHug": "コンテンツに合わせる",@@ -200,6 +204,52 @@"add": "追加","variants": "バリアント","componentProperties": "コンポーネントのプロパティ",+ "slotDefault": "デフォルト",+ "slotModified": "変更済み",+ "slotItemCount": {+ "many": "{count} 個の項目"+ },+ "addInstances": "インスタンスを追加",+ "searchInstances": "コンポーネントを検索",+ "preferredInstances": "優先",+ "allInstances": "すべてのコンポーネント",+ "noInstancesFound": "コンポーネントが見つかりません",+ "notPreferredInstance": "優先ではありません",+ "slotLimits": "スロットの制限",+ "slotLimitCount": {+ "many": "{count} 件の制限"+ },+ "slotLimitIssueCount": {+ "many": "{count} 件の問題"+ },+ "slotMinimumLayers": {+ "many": "{count} レイヤー以上"+ },+ "slotMaximumLayers": {+ "many": "{count} レイヤー以下"+ },+ "slotPreferredOnly": "優先インスタンスのみ",+ "slotNonPreferredFound": {+ "many": "{count} 個のレイヤーが優先ではありません"+ },+ "selectLayers": "レイヤーを選択",+ "resetSlot": "スロットをリセット",+ "deleteSlotContents": "内容を削除",+ "slotActions": "{name} の操作",+ "slots": "スロット",+ "createSlot": "スロットを作成",+ "removeSlot": "スロットを削除",+ "slotSettings": "スロットの設定",+ "slotName": "スロット名",+ "slotDescription": "説明",+ "slotMinimum": "最小レイヤー数",+ "slotMaximum": "最大レイヤー数",+ "slotNoLimit": "制限なし",+ "addPreferredInstances": "優先インスタンスを追加",+ "removePreferredInstance": "優先から削除",+ "searchStyles": "スタイルを検索",+ "noStylesFound": "スタイルが見つかりません",+ "noComponentsFound": "コンポーネントが見つかりません","gapAuto": "間隔自動","horizontalGap": "水平方向の間隔","verticalGap": "垂直方向の間隔",@@ -281,11 +331,9 @@"assetVariantSummary": "{count} 個のバリアント · {names}","duplicateVariantValues": "重複したバリアント値","variantPropertyName": "プロパティ名",- "variantPropertyValue": "初期値","addVariantProperty": "バリアントプロパティを追加","addVariant": "バリアントを追加","duplicateVariant": "バリアントを複製",- "removeVariant": "バリアントを削除","removeVariantProperty": "バリアントプロパティを削除","moveVariantPropertyUp": "バリアントプロパティを上へ移動","moveVariantPropertyDown": "バリアントプロパティを下へ移動",diff --git a/packages/vue/src/i18n/locales/pl/commands.json b/packages/vue/src/i18n/locales/pl/commands.jsonindex 8b9be67bd..a733c8029 100644--- a/packages/vue/src/i18n/locales/pl/commands.json+++ b/packages/vue/src/i18n/locales/pl/commands.json@@ -7,6 +7,7 @@"group": "Grupuj","ungroup": "Rozgrupuj","createComponent": "Utwórz komponent",+ "createSlot": "Utwórz slot","createComponentSet": "Utwórz zestaw komponentów","createInstance": "Utwórz instancję","detachInstance": "Odłącz instancję",diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex bff88ba2a..c4e647930 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -151,6 +151,10 @@"auto": "Auto","columns": "Kolumny","rows": "Wiersze",+ "addGridColumn": "Dodaj kolumnę",+ "addGridRow": "Dodaj wiersz",+ "removeGridColumn": "Usuń kolumnę",+ "removeGridRow": "Usuń wiersz","sizingFixed": "Stały","sizingHug": "Dopasuj do zawartości","sizingFill": "Wypełnij",@@ -183,6 +187,64 @@"add": "Dodaj","variants": "Warianty","componentProperties": "Właściwości komponentu",+ "slotDefault": "Domyślna",+ "slotModified": "Zmieniona",+ "slotItemCount": {+ "one": "{count} element",+ "few": "{count} elementy",+ "many": "{count} elementów"+ },+ "addInstances": "Dodaj instancje",+ "searchInstances": "Szukaj komponentów",+ "preferredInstances": "Preferowane",+ "allInstances": "Wszystkie komponenty",+ "noInstancesFound": "Nie znaleziono komponentów",+ "notPreferredInstance": "Niepreferowany",+ "slotLimits": "Limity slotu",+ "slotLimitCount": {+ "one": "{count} limit",+ "few": "{count} limity",+ "many": "{count} limitów"+ },+ "slotLimitIssueCount": {+ "one": "{count} problem",+ "few": "{count} problemy",+ "many": "{count} problemów"+ },+ "slotMinimumLayers": {+ "one": "Co najmniej {count} warstwa",+ "few": "Co najmniej {count} warstwy",+ "many": "Co najmniej {count} warstw"+ },+ "slotMaximumLayers": {+ "one": "Najwyżej {count} warstwa",+ "few": "Najwyżej {count} warstwy",+ "many": "Najwyżej {count} warstw"+ },+ "slotPreferredOnly": "Tylko preferowane instancje",+ "slotNonPreferredFound": {+ "one": "{count} warstwa nie jest preferowana",+ "few": "{count} warstwy nie są preferowane",+ "many": "{count} warstw nie jest preferowanych"+ },+ "selectLayers": "Zaznacz warstwy",+ "resetSlot": "Resetuj slot",+ "deleteSlotContents": "Usuń zawartość",+ "slotActions": "Akcje: {name}",+ "slots": "Sloty",+ "createSlot": "Utwórz slot",+ "removeSlot": "Usuń slot",+ "slotSettings": "Ustawienia slotu",+ "slotName": "Nazwa slotu",+ "slotDescription": "Opis",+ "slotMinimum": "Minimalna liczba warstw",+ "slotMaximum": "Maksymalna liczba warstw",+ "slotNoLimit": "Bez limitu",+ "addPreferredInstances": "Dodaj preferowane instancje",+ "removePreferredInstance": "Usuń z preferowanych",+ "searchStyles": "Szukaj stylów",+ "noStylesFound": "Nie znaleziono stylów",+ "noComponentsFound": "Nie znaleziono komponentów","gapAuto": "Automatyczny odstep","horizontalGap": "Odstep poziomy","verticalGap": "Odstep pionowy",@@ -264,11 +326,9 @@"assetVariantSummary": "{count} wariantów · {names}","duplicateVariantValues": "Zduplikowane wartości wariantu","variantPropertyName": "Nazwa właściwości",- "variantPropertyValue": "Wartość początkowa","addVariantProperty": "Dodaj właściwość wariantu","addVariant": "Dodaj wariant","duplicateVariant": "Duplikuj wariant",- "removeVariant": "Usuń wariant","removeVariantProperty": "Usuń właściwość wariantu","moveVariantPropertyUp": "Przesuń właściwość wariantu w górę","moveVariantPropertyDown": "Przesuń właściwość wariantu w dół",diff --git a/packages/vue/src/i18n/locales/ru/commands.json b/packages/vue/src/i18n/locales/ru/commands.jsonindex db6dc341b..74f8ab294 100644--- a/packages/vue/src/i18n/locales/ru/commands.json+++ b/packages/vue/src/i18n/locales/ru/commands.json@@ -7,6 +7,7 @@"group": "Сгруппировать","ungroup": "Разгруппировать","createComponent": "Создать компонент",+ "createSlot": "Создать слот","createComponentSet": "Создать набор компонентов","createInstance": "Создать экземпляр","detachInstance": "Отвязать экземпляр",diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex 541bfc9cf..b9ac1db31 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -151,6 +151,10 @@"auto": "Авто","columns": "Столбцы","rows": "Строки",+ "addGridColumn": "Добавить столбец",+ "addGridRow": "Добавить строку",+ "removeGridColumn": "Удалить столбец",+ "removeGridRow": "Удалить строку","sizingFixed": "Фиксированный","sizingHug": "По содержимому","sizingFill": "Заполнить",@@ -183,6 +187,64 @@"add": "Добавить","variants": "Варианты","componentProperties": "Свойства компонента",+ "slotDefault": "По умолчанию",+ "slotModified": "Изменён",+ "slotItemCount": {+ "one": "{count} элемент",+ "few": "{count} элемента",+ "many": "{count} элементов"+ },+ "addInstances": "Добавить экземпляры",+ "searchInstances": "Поиск компонентов",+ "preferredInstances": "Предпочтительные",+ "allInstances": "Все компоненты",+ "noInstancesFound": "Компоненты не найдены",+ "notPreferredInstance": "Не предпочтительный",+ "slotLimits": "Ограничения слота",+ "slotLimitCount": {+ "one": "{count} ограничение",+ "few": "{count} ограничения",+ "many": "{count} ограничений"+ },+ "slotLimitIssueCount": {+ "one": "{count} проблема",+ "few": "{count} проблемы",+ "many": "{count} проблем"+ },+ "slotMinimumLayers": {+ "one": "Не меньше {count} слоя",+ "few": "Не меньше {count} слоёв",+ "many": "Не меньше {count} слоёв"+ },+ "slotMaximumLayers": {+ "one": "Не больше {count} слоя",+ "few": "Не больше {count} слоёв",+ "many": "Не больше {count} слоёв"+ },+ "slotPreferredOnly": "Только предпочтительные экземпляры",+ "slotNonPreferredFound": {+ "one": "{count} слой не предпочтителен",+ "few": "{count} слоя не предпочтительны",+ "many": "{count} слоёв не предпочтительны"+ },+ "selectLayers": "Выделить слои",+ "resetSlot": "Сбросить слот",+ "deleteSlotContents": "Удалить содержимое",+ "slotActions": "Действия: {name}",+ "slots": "Слоты",+ "createSlot": "Создать слот",+ "removeSlot": "Удалить слот",+ "slotSettings": "Настройки слота",+ "slotName": "Название слота",+ "slotDescription": "Описание",+ "slotMinimum": "Минимум слоёв",+ "slotMaximum": "Максимум слоёв",+ "slotNoLimit": "Без ограничения",+ "addPreferredInstances": "Добавить предпочтительные экземпляры",+ "removePreferredInstance": "Убрать из предпочтительных",+ "searchStyles": "Поиск стилей",+ "noStylesFound": "Стили не найдены",+ "noComponentsFound": "Компоненты не найдены","gapAuto": "Авто отступ","horizontalGap": "Горизонтальный отступ","verticalGap": "Вертикальный отступ",@@ -264,11 +326,9 @@"assetVariantSummary": "{count} вариантов · {names}","duplicateVariantValues": "Повторяющиеся значения вариантов","variantPropertyName": "Имя свойства",- "variantPropertyValue": "Начальное значение","addVariantProperty": "Добавить свойство варианта","addVariant": "Добавить вариант","duplicateVariant": "Дублировать вариант",- "removeVariant": "Удалить вариант","removeVariantProperty": "Удалить свойство варианта","moveVariantPropertyUp": "Переместить свойство варианта вверх","moveVariantPropertyDown": "Переместить свойство варианта вниз",diff --git a/packages/vue/src/i18n/locales/zh-cn/commands.json b/packages/vue/src/i18n/locales/zh-cn/commands.jsonindex 7c3713e7b..859e0a998 100644--- a/packages/vue/src/i18n/locales/zh-cn/commands.json+++ b/packages/vue/src/i18n/locales/zh-cn/commands.json@@ -7,6 +7,7 @@"group": "编组","ungroup": "取消编组","createComponent": "创建组件",+ "createSlot": "创建插槽","createComponentSet": "创建组件集","createInstance": "创建实例","detachInstance": "分离实例",diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex c1106aab0..b3f21867b 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -151,6 +151,10 @@"auto": "自动","columns": "列","rows": "行",+ "addGridColumn": "添加列",+ "addGridRow": "添加行",+ "removeGridColumn": "移除列",+ "removeGridRow": "移除行","sizingFixed": "固定","sizingHug": "适应内容","sizingFill": "填充",@@ -183,6 +187,52 @@"add": "添加","variants": "变体","componentProperties": "组件属性",+ "slotDefault": "默认",+ "slotModified": "已修改",+ "slotItemCount": {+ "many": "{count} 项"+ },+ "addInstances": "添加实例",+ "searchInstances": "搜索组件",+ "preferredInstances": "首选",+ "allInstances": "所有组件",+ "noInstancesFound": "未找到组件",+ "notPreferredInstance": "非首选",+ "slotLimits": "插槽限制",+ "slotLimitCount": {+ "many": "{count} 项限制"+ },+ "slotLimitIssueCount": {+ "many": "{count} 个问题"+ },+ "slotMinimumLayers": {+ "many": "至少 {count} 个图层"+ },+ "slotMaximumLayers": {+ "many": "最多 {count} 个图层"+ },+ "slotPreferredOnly": "仅限首选实例",+ "slotNonPreferredFound": {+ "many": "{count} 个图层不是首选"+ },+ "selectLayers": "选择图层",+ "resetSlot": "重置插槽",+ "deleteSlotContents": "删除内容",+ "slotActions": "{name} 操作",+ "slots": "插槽",+ "createSlot": "创建插槽",+ "removeSlot": "移除插槽",+ "slotSettings": "插槽设置",+ "slotName": "插槽名称",+ "slotDescription": "描述",+ "slotMinimum": "最少图层数",+ "slotMaximum": "最多图层数",+ "slotNoLimit": "无限制",+ "addPreferredInstances": "添加首选实例",+ "removePreferredInstance": "从首选中移除",+ "searchStyles": "搜索样式",+ "noStylesFound": "未找到样式",+ "noComponentsFound": "未找到组件","gapAuto": "自动间距","horizontalGap": "水平间距","verticalGap": "垂直间距",@@ -264,11 +314,9 @@"assetVariantSummary": "{count} 个变体 · {names}","duplicateVariantValues": "重复的变体值","variantPropertyName": "属性名称",- "variantPropertyValue": "初始值","addVariantProperty": "添加变体属性","addVariant": "添加变体","duplicateVariant": "复制变体",- "removeVariant": "删除变体","removeVariantProperty": "删除变体属性","moveVariantPropertyUp": "向上移动变体属性","moveVariantPropertyDown": "向下移动变体属性",diff --git a/packages/vue/src/i18n/messages/commands.ts b/packages/vue/src/i18n/messages/commands.tsindex 60f4a1e46..204b7ff5a 100644--- a/packages/vue/src/i18n/messages/commands.ts+++ b/packages/vue/src/i18n/messages/commands.ts@@ -12,6 +12,7 @@ export const commandMessageDefaults = {frameSelection: 'Frame selection',ungroup: 'Ungroup',createComponent: 'Create component',+ createSlot: 'Create slot',createComponentSet: 'Create component set',createInstance: 'Create instance',detachInstance: 'Detach instance',diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex 9e229f373..2d78cb42e 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -1,4 +1,4 @@-import { params } from '@nanostores/i18n'+import { count, params } from '@nanostores/i18n'import { i18n } from '#vue/i18n/create'@@ -77,11 +77,9 @@ export const panelMessageDefaults = {assetVariantSummary: params('{count} variants · {names}'),duplicateVariantValues: 'Duplicate variant values',variantPropertyName: 'Property name',- variantPropertyValue: 'Initial value',addVariantProperty: 'Add variant property',addVariant: 'Add variant',duplicateVariant: 'Duplicate variant',- removeVariant: 'Remove variant',removeVariantProperty: 'Remove variant property',moveVariantPropertyUp: 'Move variant property up',moveVariantPropertyDown: 'Move variant property down',@@ -161,6 +159,43 @@ export const panelMessageDefaults = {variables: 'Variables',variants: 'Variants',componentProperties: 'Component properties',+ slotDefault: 'Default',+ slotModified: 'Modified',+ slotItemCount: count({ one: '{count} item', many: '{count} items' }),+ addInstances: 'Add instances',+ searchInstances: 'Search components',+ preferredInstances: 'Preferred',+ allInstances: 'All components',+ noInstancesFound: 'No components found',+ notPreferredInstance: 'Not preferred',+ slotLimits: 'Slot limits',+ slotLimitCount: count({ one: '{count} limit', many: '{count} limits' }),+ slotLimitIssueCount: count({ one: '{count} issue', many: '{count} issues' }),+ slotMinimumLayers: count({ one: 'At least {count} layer', many: 'At least {count} layers' }),+ slotMaximumLayers: count({ one: 'At most {count} layer', many: 'At most {count} layers' }),+ slotPreferredOnly: 'Preferred instances only',+ slotNonPreferredFound: count({+ one: '{count} layer is not preferred',+ many: '{count} layers are not preferred'+ }),+ selectLayers: 'Select layers',+ resetSlot: 'Reset slot',+ deleteSlotContents: 'Delete contents',+ slotActions: params('{name} actions'),+ slots: 'Slots',+ createSlot: 'Create slot',+ removeSlot: 'Remove slot',+ slotSettings: 'Slot settings',+ slotName: 'Slot name',+ slotDescription: 'Description',+ slotMinimum: 'Minimum layers',+ slotMaximum: 'Maximum layers',+ slotNoLimit: 'No limit',+ addPreferredInstances: 'Add preferred instances',+ removePreferredInstance: 'Remove from preferred',+ searchStyles: 'Search styles',+ noStylesFound: 'No styles found',+ noComponentsFound: 'No components found',constraints: 'Constraints',horizontalConstraint: 'Horizontal constraint',verticalConstraint: 'Vertical constraint',@@ -281,8 +316,8 @@ export const panelMessageDefaults = {gridStyle: 'Grid style',missingStyle: params('Missing style ({id})'),layersCount: params('{count} layers'),- goToMainComponent: 'Go to Main Component',- detachInstance: 'Detach Instance',+ goToMainComponent: 'Go to main component',+ detachInstance: 'Detach instance',gap: 'Gap',@@ -320,6 +355,10 @@ export const panelMessageDefaults = {auto: 'Auto',columns: 'Columns',rows: 'Rows',+ addGridColumn: 'Add column',+ addGridRow: 'Add row',+ removeGridColumn: 'Remove column',+ removeGridRow: 'Remove row',sizingFixed: 'Fixed',sizingHug: 'Hug',sizingFill: 'Fill',diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex d3ccbd714..d283971d7 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -241,12 +241,20 @@ export {compatibleComponentPropertyDefinitions,instanceSwapOptions,mergedComponentPropertyValue,+ slotInstanceOptions,+ slotLimits,useComponentProperties,+ useSlotAuthoring,+ useSlotProperties,useVariantAuthoring} from '#vue/controls/component-props'export type {ComponentPropertyControl,ComponentPropertyOption,+ SlotDefinitionControl,+ SlotInstanceOption,+ SlotLimit,+ SlotPropertyControl,VariantDefinitionControl} from '#vue/controls/component-props'export type { CornerGeometryKey, CornerRadiusKey } from '#vue/controls/appearance/types'diff --git a/packages/vue/src/primitives/LayerTree/context.ts b/packages/vue/src/primitives/LayerTree/context.tsindex 18c73bcac..b166640ee 100644--- a/packages/vue/src/primitives/LayerTree/context.ts+++ b/packages/vue/src/primitives/LayerTree/context.ts@@ -7,6 +7,8 @@ export interface LayerNode {name: stringtype: stringlayoutMode: string+ /** Whether the layer is a slot frame holding a slot property's content. */+ slot?: booleanvisible: booleanlocked: booleanchildren?: LayerNode[]diff --git a/packages/vue/src/primitives/LayerTree/model.ts b/packages/vue/src/primitives/LayerTree/model.tsindex ecf3a5fbd..af003c9f7 100644--- a/packages/vue/src/primitives/LayerTree/model.ts+++ b/packages/vue/src/primitives/LayerTree/model.ts@@ -1,3 +1,4 @@+import { slotPropertyId } from '@open-pencil/scene-graph'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import type { LayerNode, LayerRow, LayerSelectionMode } from '#vue/primitives/LayerTree/context'@@ -8,6 +9,7 @@ function nodeToLayerNode(node: SceneNode): LayerNode {name: node.name,type: node.type,layoutMode: node.layoutMode,+ slot: !!slotPropertyId(node),visible: node.visible,locked: node.locked}@@ -56,12 +58,14 @@ export function patchLayerNode(target: LayerNode, source: SceneNode): boolean {target.name !== source.name ||target.type !== source.type ||target.layoutMode !== source.layoutMode ||+ target.slot !== !!slotPropertyId(source) ||target.visible !== source.visible ||target.locked !== source.lockedif (!changed) return falsetarget.name = source.nametarget.type = source.typetarget.layoutMode = source.layoutMode+ target.slot = !!slotPropertyId(source)target.visible = source.visibletarget.locked = source.lockedreturn truediff --git a/packages/vue/src/primitives/LayerTree/useLayerDrag.ts b/packages/vue/src/primitives/LayerTree/useLayerDrag.tsindex 1646d5894..e6aa39638 100644--- a/packages/vue/src/primitives/LayerTree/useLayerDrag.ts+++ b/packages/vue/src/primitives/LayerTree/useLayerDrag.ts@@ -42,10 +42,20 @@ export function useLayerDrag(const isContainer = editor.graph.isContainer(data.id)const mode: ItemMode = data.hasChildren ? 'expanded' : 'standard'+ const parentId = editor.graph.getNode(data.id)?.parentId ?? editor.state.currentPageId+ // Inside an instance only slots take layers; the rest of it comes from its component.+ const acceptsChildren = isContainer && editor.acceptsChildren(data.id)+ const acceptsSiblings = editor.acceptsChildren(parentId)+ const block: Array<'make-child' | 'reorder-above' | 'reorder-below' | 'reparent'> = [+ 'reparent',+ ...(acceptsChildren ? [] : (['make-child'] as const)),+ ...(acceptsSiblings ? [] : (['reorder-above', 'reorder-below'] as const))+ ]const cleanup = combine(draggable({element,+ canDrag: () => acceptsSiblings,getInitialData: () => ({ id: data.id }),onDragStart: () => {draggingId.value = data.id@@ -65,7 +75,7 @@ export function useLayerDrag(indentPerLevel,currentLevel: data.level,mode,- block: isContainer ? ['reparent'] : ['make-child', 'reparent']+ block}),canDrop: ({ source }) => source.data.id !== data.id,diff --git a/packages/vue/src/shared/input/drop-target.ts b/packages/vue/src/shared/input/drop-target.tsindex 8f2de53cb..a14183ea4 100644--- a/packages/vue/src/shared/input/drop-target.ts+++ b/packages/vue/src/shared/input/drop-target.ts@@ -19,6 +19,11 @@ export function findMoveDropTarget(cx: number, cy: number, editor: Editor): Scen) {dropTarget = null}+ // Only an instance's slots take layers; anywhere else in it drops into its parent.+ if (dropTarget) {+ const accepting = editor.graph.getNode(editor.acceptingParent(dropTarget.id))+ dropTarget = accepting && accepting.type !== 'CANVAS' ? accepting : null+ }return dropTarget}@@ -32,7 +37,7 @@ export function reparentOutsideNodes(editor: Editor) {const outsideY = node.y + node.height < 0 || node.y > parent.heightif (outsideX || outsideY) {const grandparentId = parent.parentId ?? editor.state.currentPageId- editor.graph.reparentNode(id, grandparentId)+ editor.reparentNodes([id], editor.acceptingParent(grandparentId))}}}diff --git a/packages/vue/src/shared/input/move.ts b/packages/vue/src/shared/input/move.tsindex c6b2e68a7..8e43874aa 100644--- a/packages/vue/src/shared/input/move.ts+++ b/packages/vue/src/shared/input/move.ts@@ -159,38 +159,47 @@ export function handleMoveUp(d: DragMove, editor: Editor) {editor.setDropTarget(null)return}- for (const id of d.originals.keys()) {- editor.reorderInAutoLayout(id, indicator.parentId, indicator.index)- }+ // Claiming a slot records its own step; the batch makes it one undo with the reorder.+ editor.undo.runBatch('Reorder', () => {+ for (const id of d.originals.keys()) {+ editor.reorderInAutoLayout(id, indicator.parentId, indicator.index)+ }+ })editor.setDropTarget(null)return}const moved = hasMoved(d, editor)- if (moved) {- restoreOriginalPositions(d, editor)- applyFinalPositions(d, editor)- const dropId = editor.state.dropTargetId- if (dropId) {- editor.reparentNodes([...editor.state.selectedIds], dropId)- } else {- reparentOutsideNodes(editor)- }+ if (d.duplicated && !moved) {+ const previousSelection = d.duplicatedPreviousSelection ?? new Set<string>()+ for (const id of [...d.originals.keys()].toReversed()) editor.graph.deleteNode(id)+ editor.select([...previousSelection])+ editor.requestRender()+ editor.setDropTarget(null)+ return}- if (d.duplicated) {- const previousSelection = d.duplicatedPreviousSelection ?? new Set<string>()- if (!moved) {- for (const id of [...d.originals.keys()].toReversed()) editor.graph.deleteNode(id)- editor.select([...previousSelection])- editor.requestRender()- editor.setDropTarget(null)- return+ // The batch keeps a slot claim in the same undo step; it carries the edit's own name.+ editor.undo.runBatch(d.duplicated ? 'Duplicate' : 'Move', () => {+ if (moved) {+ restoreOriginalPositions(d, editor)+ applyFinalPositions(d, editor)+ const dropId = editor.state.dropTargetId+ if (dropId) {+ editor.reparentNodes([...editor.state.selectedIds], dropId)+ } else {+ reparentOutsideNodes(editor)+ }}- editor.commitDuplicateMove([...d.originals.keys()], previousSelection)- } else if (moved) {- editor.commitMoveWithReparent(d.originals)- }+ if (d.duplicated) {+ editor.commitDuplicateMove(+ [...d.originals.keys()],+ d.duplicatedPreviousSelection ?? new Set<string>()+ )+ } else if (moved) {+ editor.commitMoveWithReparent(d.originals)+ }+ })editor.setDropTarget(null)}diff --git a/packages/vue/tests/controls/component-props/slots.test.ts b/packages/vue/tests/controls/component-props/slots.test.tsnew file mode 100644index 000000000..ad2c92024--- /dev/null+++ b/packages/vue/tests/controls/component-props/slots.test.ts@@ -0,0 +1,68 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph, instanceSlotFrames } from '@open-pencil/scene-graph'+import type { ComponentPropertyDefinition } from '@open-pencil/scene-graph'+import { slotInstanceOptions, slotLimits } from '@open-pencil/vue'++function card() {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const item = graph.createNode('COMPONENT', pageId, { name: 'Item', componentKey: 'item-key' })+ const other = graph.createNode('COMPONENT', pageId, { name: 'Avatar' })+ const definition: ComponentPropertyDefinition = {+ id: 'card:body',+ name: 'Body',+ type: 'SLOT',+ defaultValue: '',+ preferredValues: ['item-key'],+ slotSettings: { minChildren: 1, maxChildren: 2, allowPreferredValuesOnly: true }+ }+ const component = graph.createNode('COMPONENT', pageId, {+ name: 'Card',+ componentPropertyDefinitions: [definition]+ })+ const body = graph.createNode('FRAME', component.id, {+ name: 'Body',+ componentPropertyReferences: [{ propertyId: definition.id, field: 'SLOT_CONTENT' }]+ })+ graph.createNode('TEXT', body.id, { name: 'Default' })+ return { graph, item, other, definition, component }+}++describe('slot property model', () => {+ test('finds the instance frame that holds a slot', () => {+ const { graph, component } = card()+ const instance = graph.createInstance(component.id, graph.getPages()[0].id)+ if (!instance) throw new Error('No instance')+ expect(instanceSlotFrames(graph, instance).map((frame) => frame.name)).toEqual(['Body'])+ })++ test('measures limits against the content and names offending layers', () => {+ const { graph, item, definition, component } = card()+ const body = graph.getChildren(component.id)[0]+ const preferred = graph.createInstance(item.id, body.id)+ if (!preferred) throw new Error('No instance')+ const content = graph.getChildren(body.id)+ const [text] = content+ expect(slotLimits(graph, definition, content)).toEqual({+ limits: [+ { kind: 'minimum', count: 1, met: true },+ { kind: 'maximum', count: 2, met: true },+ { kind: 'preferred', met: false, offending: 1 }+ ],+ offendingIds: [text.id]+ })+ expect(slotLimits(graph, definition, []).limits[0]).toMatchObject({ met: false })+ })++ test('lists components with preferred ones first', () => {+ const { graph, definition } = card()+ expect(+ slotInstanceOptions(graph, definition).map(({ name, preferred }) => [name, preferred])+ ).toEqual([+ ['Item', true],+ ['Avatar', false],+ ['Card', false]+ ])+ })+})diff --git a/src/app.css b/src/app.cssindex 05c10cfa5..6298d0141 100644--- a/src/app.css+++ b/src/app.css@@ -63,6 +63,7 @@--color-muted: #a6a6a6;--color-input: #1e1e1e;--color-component: #9747ff;+ --color-slot: #f24bbc;--color-warning-bg: rgb(245 158 11 / 0.1);--color-warning-border: rgb(245 158 11 / 0.3);--color-warning-text: #fde68a;@@ -109,6 +110,7 @@ html[data-theme='light'] {--color-muted: #6b7280;--color-input: #ffffff;--color-component: #7c3aed;+ --color-slot: #db2777;--color-warning-bg: rgb(245 158 11 / 0.14);--color-warning-border: rgb(245 158 11 / 0.32);--color-warning-text: #92400e;diff --git a/src/app/editor/icons.ts b/src/app/editor/icons.tsindex 606bed6dc..74b561e41 100644--- a/src/app/editor/icons.ts+++ b/src/app/editor/icons.ts@@ -13,6 +13,7 @@ import IconMousePointer from '~icons/lucide/mouse-pointer'import IconPenTool from '~icons/lucide/pen-tool'import IconRows from '~icons/lucide/rows-3'import IconSquare from '~icons/lucide/square'+import IconSlot from '~icons/lucide/square-dashed'import IconStar from '~icons/lucide/star'import IconTriangle from '~icons/lucide/triangle'import IconType from '~icons/lucide/type'@@ -57,7 +58,8 @@ export const COMPONENT_TYPES = new Set(['COMPONENT', 'COMPONENT_SET', 'INSTANCE'export { IconFrame, IconSquare }-export function nodeIcon(node: { type: string; layoutMode: string }) {+export function nodeIcon(node: { type: string; layoutMode: string; slot?: boolean }) {+ if (node.slot) return IconSlotif (node.type === 'FRAME' && node.layoutMode !== 'NONE')return AUTO_LAYOUT_ICONS[node.layoutMode] ?? IconFramereturn NODE_ICONS[node.type] ?? IconSquarediff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.tsindex 2b2398577..8feecb6b9 100644--- a/src/app/shell/keyboard/registry.ts+++ b/src/app/shell/keyboard/registry.ts@@ -69,8 +69,9 @@ function originatedInOverlay(event: KeyboardEvent) {.some((target) => target instanceof Element && target.matches(EDITOR_SHORTCUT_OVERLAY_SELECTOR))}+/** A popover, menu, or dialog that is open; one fading out after closing no longer counts. */function hasOpenDismissableLayer() {- return document.querySelector('[data-dismissable-layer]') !== null+ return document.querySelector('[data-dismissable-layer]:not([data-state="closed"])') !== null}function shouldIgnoreShortcut(event: KeyboardEvent, options: KeyboardShortcutOptions) {diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.tsindex bd19c2c1d..252088011 100644--- a/src/app/shell/menu/schema.ts+++ b/src/app/shell/menu/schema.ts@@ -331,6 +331,11 @@ export const APP_MENU_SCHEMA = [label: 'Create Instance',command: 'selection.createInstance'},+ {+ id: 'selection.createSlot',+ label: 'Create Slot',+ command: 'selection.createSlot'+ },{id: 'selection.goToMainComponent',label: 'Go to Main Component',diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vueindex 3cb8e89e8..c0d4cd3a5 100644--- a/src/components/DesignPanel.vue+++ b/src/components/DesignPanel.vue@@ -12,6 +12,7 @@ import PanelHeader from '@/components/ui/panel/PanelHeader.vue'import AppearanceSection from './properties/AppearanceSection.vue'import ComponentPropertiesSection from './properties/component-properties/ComponentPropertiesSection.vue'import InstanceUpdateAction from './properties/component-properties/instance-update/InstanceUpdateAction.vue'+import SlotAuthoringSection from './properties/component-properties/slot/SlotAuthoringSection.vue'import VariantAuthoringSection from './properties/component-properties/VariantAuthoringSection.vue'import ConstraintsSection from './properties/constraints/ConstraintsSection.vue'import EffectsSection from './properties/EffectsSection.vue'@@ -160,6 +161,8 @@ const { panels } = useI18n()"/>+ <SlotAuthoringSection />+<FramePresetSelect v-if="node.type === 'FRAME'" /><PositionSection />diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vueindex 77645bf95..9b0aa93df 100644--- a/src/components/EditorCanvas.vue+++ b/src/components/EditorCanvas.vue@@ -38,6 +38,8 @@ import { appRuntimeConfig } from '@/app/runtime/config'import IssueMarkerTooltip from '@/components/design-check/IssueMarkerTooltip.vue'import PreparationOverlay from '@/components/preparation/canvas/Overlay.vue'import FollowFrame from '@/components/presence/FollowFrame.vue'+import { motionStyles } from '@/theme/motion/styles'+import { floatingSurface } from '@/theme/overlay'import CanvasMenu from './canvas/CanvasMenu.vue'import CanvasLabelEditor from './canvas/labels/CanvasLabelEditor.vue'@@ -256,7 +258,7 @@ const cursor = computed(() =>:side-offset="AUTO_LAYOUT_PADDING_EDITOR_OFFSET_Y":align-offset="AUTO_LAYOUT_PADDING_EDITOR_OFFSET_X":collision-padding="8"- class="z-50 w-20 rounded-md bg-panel p-1 shadow-lg"+ :class="['z-50 w-20 p-1', floatingSurface, motionStyles.floating]"data-test-id="auto-layout-padding-editor"@keydown.escape.prevent="cancelAutoLayoutPaddingEdit"@open-auto-focus.preventdiff --git a/src/components/LayerTree/LayerTreeNodeRow.vue b/src/components/LayerTree/LayerTreeNodeRow.vueindex 699ec50a0..aff09cd77 100644--- a/src/components/LayerTree/LayerTreeNodeRow.vue+++ b/src/components/LayerTree/LayerTreeNodeRow.vue@@ -45,6 +45,7 @@ const styles = computed(() =>dragging: chrome.draggingId === node.id,visible: node.visible,component: COMPONENT_TYPES.has(node.type),+ slot: node.slot,childDropTarget:chrome.instructionTargetId === node.id && chrome.instruction?.type === 'make-child'})diff --git a/src/components/LayerTree/examples/States.vue b/src/components/LayerTree/examples/States.vueindex 6670db138..43f4b0538 100644--- a/src/components/LayerTree/examples/States.vue+++ b/src/components/LayerTree/examples/States.vue@@ -101,6 +101,12 @@ const states: Array<{},{ label: 'Hidden', node: node('Hidden', { visible: false }), selected: false, chrome: chrome() },{ label: 'Locked', node: node('Locked', { locked: true }), selected: false, chrome: chrome() },+ {+ label: 'Slot',+ node: node('Slot', { type: 'FRAME', layoutMode: 'VERTICAL', slot: true }),+ selected: false,+ chrome: chrome()+ },{label: 'Component',node: node('Component', { type: 'COMPONENT' }),diff --git a/src/components/MobileHud/MobileFileMenu.vue b/src/components/MobileHud/MobileFileMenu.vueindex 161f58e8b..91fba08a5 100644--- a/src/components/MobileHud/MobileFileMenu.vue+++ b/src/components/MobileHud/MobileFileMenu.vue@@ -16,7 +16,7 @@ import { menu, useMenuUI } from '@/components/ui/menu/menu'const menuMessages = useMenuMessages()const hud = useMobileHudContext()const menuCls = useMenuUI({- content: 'w-48 rounded-xl p-1.5 shadow-xl',+ content: 'w-48 p-1.5',item: 'w-full gap-2.5 rounded-lg border-none bg-transparent px-2.5 py-2 active:bg-hover'})</script>diff --git a/src/components/PagesPanel.vue b/src/components/PagesPanel.vueindex 82fbc6658..f3869f63e 100644--- a/src/components/PagesPanel.vue+++ b/src/components/PagesPanel.vue@@ -34,7 +34,7 @@ const pageInput = templateRef<HTMLInputElement>('pageInput')const rename = useInlineRename((id, name) => pageActions.value?.rename(id, name))const { panels, pages: pageMessages } = useI18n()const menuCls = useMenuUI({- content: 'min-w-36 shadow-[0_8px_30px_rgb(0_0_0/0.4)]',+ content: 'min-w-36',item: 'justify-start gap-2'})const pageListStyles = tv(pageListTheme)diff --git a/src/components/canvas/CanvasMenu.vue b/src/components/canvas/CanvasMenu.vueindex f5c3e5563..3dcea7c9d 100644--- a/src/components/canvas/CanvasMenu.vue+++ b/src/components/canvas/CanvasMenu.vue@@ -51,8 +51,7 @@ function removeSelectedGuide() {}const menuCls = useMenuUI({- content:- 'min-w-56 max-w-80 shadow-[0_8px_30px_rgb(0_0_0/0.4)] animate-in fade-in zoom-in-95 motion-reduce:animate-none',+ content: 'min-w-56 max-w-80',separator: 'my-1'})const componentMenu = menu({ tone: 'component' })@@ -71,7 +70,9 @@ function contextCommandTestId(id: EditorCommandId | undefined): string | undefin</script><template>- <ContextMenuContent :class="cls.menu" :side-offset="2" align="start">+ <!-- Closing hands focus back to the canvas; when that lands just after a quick reopen, it+ must not close the new menu. Clicks outside and Escape still close it. -->+ <ContextMenuContent :class="cls.menu" :side-offset="2" align="start" @close-auto-focus.prevent><template v-if="selectedGuide"><ContextMenuItem data-property="guide" :class="cls.item" @select="removeSelectedGuide"><span>{{ t.removeGuide }}</span>diff --git a/src/components/design-check/IssueGroup.vue b/src/components/design-check/IssueGroup.vueindex 5c12d58be..47a8c4ac3 100644--- a/src/components/design-check/IssueGroup.vue+++ b/src/components/design-check/IssueGroup.vue@@ -13,12 +13,12 @@ import { useDesignCheckMessages } from '@open-pencil/vue'import AppButton from '@/components/ui/button/AppButton.vue'import IconButton from '@/components/ui/button/IconButton.vue'import AppCollapsible from '@/components/ui/collapsible/AppCollapsible.vue'+import SeverityIcon from '@/components/ui/feedback/SeverityIcon.vue'import { menuItem, useMenuUI } from '@/components/ui/menu/menu'import Tip from '@/components/ui/overlay/Tip.vue'import { designCheck } from '@/theme/design-check'import IssueRow from './IssueRow.vue'-import SeverityIcon from './SeverityIcon.vue'import type { IssueGroupView, IssueRowView } from './types'/** Rows rendered before a group asks to show the rest. */diff --git a/src/components/design-check/IssueMarkerTooltip.vue b/src/components/design-check/IssueMarkerTooltip.vueindex bb783a4af..6c8567ea7 100644--- a/src/components/design-check/IssueMarkerTooltip.vue+++ b/src/components/design-check/IssueMarkerTooltip.vue@@ -15,10 +15,9 @@ import { useEditorStore } from '@/app/editor/active-store'import { issueDetail, ruleTitle } from '@/app/editor/design-check/format'import { compareIssueSeverity, type DesignIssue } from '@/app/editor/design-check/issues'import { nodeIcon } from '@/app/editor/icons'+import SeverityIcon from '@/components/ui/feedback/SeverityIcon.vue'import { issueTooltip } from '@/theme/design-check'-import SeverityIcon from './SeverityIcon.vue'-/** Issues listed before the tooltip summarizes the rest. */const MAX_ITEMS = 4diff --git a/src/components/design-check/LayerIssueMark.vue b/src/components/design-check/LayerIssueMark.vueindex 8775e6fde..76066dba8 100644--- a/src/components/design-check/LayerIssueMark.vue+++ b/src/components/design-check/LayerIssueMark.vue@@ -4,11 +4,10 @@ import { computed } from 'vue'import { useDesignCheckMessages } from '@open-pencil/vue'import type { LayerIssueMark } from '@/app/editor/design-check/layers'+import SeverityIcon from '@/components/ui/feedback/SeverityIcon.vue'import Tip from '@/components/ui/overlay/Tip.vue'import { layerIssueMark } from '@/theme/design-check'-import SeverityIcon from './SeverityIcon.vue'-/** A layer's own issues show as their severity icon; issues inside it as a dot. */const { mark } = defineProps<{ mark: LayerIssueMark }>()diff --git a/src/components/design-check/SeverityFilters.vue b/src/components/design-check/SeverityFilters.vueindex a9f33fe3f..94a7100c5 100644--- a/src/components/design-check/SeverityFilters.vue+++ b/src/components/design-check/SeverityFilters.vue@@ -9,11 +9,10 @@ import {type DesignIssueCounts,type DesignIssueSeverity} from '@/app/editor/design-check/issues'+import SeverityIcon from '@/components/ui/feedback/SeverityIcon.vue'import Tip from '@/components/ui/overlay/Tip.vue'import { designCheck } from '@/theme/design-check'-import SeverityIcon from './SeverityIcon.vue'-const { counts } = defineProps<{ counts: DesignIssueCounts }>()/** Severities whose issues are listed; toggling one hides or shows its issues. */const visible = defineModel<DesignIssueSeverity[]>({ required: true })diff --git a/src/components/properties/VariablesSection.vue b/src/components/properties/VariablesSection.vueindex 247314d0e..1400b15ed 100644--- a/src/components/properties/VariablesSection.vue+++ b/src/components/properties/VariablesSection.vue@@ -26,7 +26,7 @@ const { panels } = useI18n()<PanelSection :label="panels.variables" :empty="!hasVariables"><template #actions><IconButton :label="panels.openVariables" @click="emit('openDialog')">- <icon-lucide-settings-2 class="size-3.5" />+ <icon-lucide-square-arrow-out-up-right class="size-3.5" /></IconButton></template><div v-if="hasVariables" class="mt-1 text-[11px] text-muted">diff --git a/src/components/properties/binding/VariableBindingPicker.vue b/src/components/properties/binding/VariableBindingPicker.vueindex 84d59afc2..1cdd2434a 100644--- a/src/components/properties/binding/VariableBindingPicker.vue+++ b/src/components/properties/binding/VariableBindingPicker.vue@@ -6,6 +6,7 @@ export interface VariableBindingPickerProps {searchPlaceholder: stringemptyLabel: stringdetachLabel: string+ closeLabel?: stringcreateLabel?: stringcreateNamePlaceholder?: stringcreateSubmitLabel?: string@@ -17,29 +18,20 @@ export interface VariableBindingPickerProps {</script><script setup lang="ts">-import {- ComboboxAnchor,- ComboboxContent,- ComboboxInput,- ComboboxItem,- ComboboxItemIndicator,- ComboboxPortal,- ComboboxTrigger,- ComboboxViewport-} from 'reka-ui'import { computed, nextTick, ref, watch } from 'vue'-import { BindableValuePicker, useBindableValue, useRetainedPopup } from '@open-pencil/vue'+import { useBindableValue, useI18n } from '@open-pencil/vue'import { BindingTrigger, useBindingFieldUI } from '@/components/ui/binding'import AppButton from '@/components/ui/button/AppButton.vue'-import Tip from '@/components/ui/overlay/Tip.vue'+import AppPicker, { type AppPickerItem } from '@/components/ui/select/AppPicker.vue'const {triggerLabel,searchPlaceholder,emptyLabel,detachLabel,+ closeLabel,createLabel,createNamePlaceholder = 'Variable name',createSubmitLabel = 'Create',@@ -50,7 +42,7 @@ const {} = defineProps<VariableBindingPickerProps>()const binding = useBindableValue<unknown>()-const { portalActive } = useRetainedPopup(binding.open)+const { common } = useI18n()const creating = ref(false)const createName = ref('')const createInput = ref<HTMLInputElement | null>(null)@@ -66,9 +58,13 @@ const styles = computed(() =>ui))-function updateSearch(value: unknown) {- if (typeof value === 'string') binding.actions.setSearchTerm(value)-}+const open = computed({+ get: () => binding.open.value,+ set: (value: boolean) => (value ? binding.actions.openPicker() : binding.actions.closePicker())+})+const items = computed<AppPickerItem[]>(() =>+ binding.variables.value.map((variable) => ({ value: variable.id, label: variable.name }))+)function startCreate() {creating.value = true@@ -90,122 +86,86 @@ function detach() {binding.actions.closePicker()}-watch(binding.open, (open) => {- if (open) return- creating.value = false- binding.actions.setSearchTerm('')+watch(binding.open, (isOpen) => {+ if (!isOpen) creating.value = false})defineOptions({ inheritAttrs: false })</script><template>- <BindableValuePicker v-slot="picker">- <ComboboxAnchor class="inline-flex shrink-0 items-center" data-slot="anchor">- <Tip :label="triggerLabel">- <ComboboxTrigger as-child>- <BindingTrigger- :label="triggerLabel"- :state="picker.state"- :open="picker.open"- :disabled="disabled"- :derived="derived"- :ui="ui"- />- </ComboboxTrigger>- </Tip>- </ComboboxAnchor>-- <ComboboxPortal v-if="portalActive">- <ComboboxContent- v-if="picker.open"- position="popper"- side="bottom"- align="end"- :side-offset="8"- :collision-padding="8"- :class="styles.pickerContent"- data-slot="content"- >- <ComboboxInput- :model-value="picker.searchTerm"- :placeholder="searchPlaceholder"- :class="styles.pickerSearch"- autocomplete="off"- autocorrect="off"- autocapitalize="off"- :spellcheck="false"- data-slot="search"- @update:model-value="updateSearch"+ <span class="inline-flex shrink-0 items-center" data-slot="anchor">+ <AppPicker+ v-model:open="open"+ :heading="triggerLabel"+ :items="items"+ :selected="binding.variable.value?.id"+ density="compact"+ :search-placeholder="searchPlaceholder"+ :empty-label="emptyLabel"+ :close-label="closeLabel ?? common.close"+ :tooltip="triggerLabel"+ @select="binding.actions.bind($event)"+ >+ <template #trigger>+ <BindingTrigger+ :label="triggerLabel"+ :state="binding.state.value"+ :open="binding.open.value"+ :disabled="disabled"+ :derived="derived"+ :ui="ui"/>- <ComboboxViewport :class="styles.pickerViewport" data-slot="viewport">- <div v-if="picker.variables.length === 0" :class="styles.pickerEmpty" data-slot="empty">- {{ emptyLabel }}- </div>- <ComboboxItem- v-for="variable in picker.variables"- :key="variable.id"- :value="variable"- :text-value="variable.name"- :class="styles.pickerItem"- data-slot="item"- >- <icon-lucide-diamond :class="styles.pickerItemIcon" data-slot="itemIcon" />- <span :class="styles.pickerItemLabel" data-slot="itemLabel">{{ variable.name }}</span>- <ComboboxItemIndicator :class="styles.pickerItemIndicator" data-slot="itemIndicator">- <icon-lucide-check class="size-3" />- </ComboboxItemIndicator>- </ComboboxItem>- </ComboboxViewport>-- <div :class="styles.pickerFooter" data-slot="footer">- <AppButton- v-if="picker.state !== 'unbound'"- size="xs"- class="w-full justify-start"- data-slot="action"- @click="detach"- >- <template #leading><icon-lucide-unlink class="size-3" /></template>- {{ detachLabel }}- </AppButton>-- <form- v-if="creating"- :class="styles.createForm"- data-slot="createForm"- @submit.prevent="submitCreate"- @keydown.esc.prevent.stop="creating = false"- >- <input- ref="createInput"- v-model="createName"- :placeholder="createNamePlaceholder"- :class="styles.createInput"- data-slot="createInput"- />- <AppButton- size="xs"- variant="soft"- :disabled="!canCreate"- data-slot="createSubmit"- type="submit"- >- {{ createSubmitLabel }}- </AppButton>- </form>+ </template>+ <template #leading>+ <icon-lucide-diamond class="size-3.5 text-component" />+ </template>+ <template #footer>+ <AppButton+ v-if="binding.state.value !== 'unbound'"+ size="xs"+ class="w-full justify-start"+ data-slot="action"+ @click="detach"+ >+ <template #leading><icon-lucide-unlink class="size-3" /></template>+ {{ detachLabel }}+ </AppButton>+ <form+ v-if="creating"+ :class="styles.createForm"+ data-slot="createForm"+ @submit.prevent="submitCreate"+ @keydown.esc.prevent.stop="creating = false"+ >+ <input+ ref="createInput"+ v-model="createName"+ :placeholder="createNamePlaceholder"+ :class="styles.createInput"+ data-slot="createInput"+ /><AppButton- v-else-if="createLabel"size="xs"- class="w-full justify-start"- data-slot="action"- @click="startCreate"+ variant="soft"+ :disabled="!canCreate"+ data-slot="createSubmit"+ type="submit">- <template #leading><icon-lucide-plus class="size-3" /></template>- <span class="min-w-0 flex-1 truncate">{{ createLabel }}</span>+ {{ createSubmitLabel }}</AppButton>- </div>- </ComboboxContent>- </ComboboxPortal>- </BindableValuePicker>+ </form>+ <AppButton+ v-else-if="createLabel"+ size="xs"+ class="w-full justify-start"+ data-slot="action"+ @click="startCreate"+ >+ <template #leading><icon-lucide-plus class="size-3" /></template>+ <span class="min-w-0 flex-1 truncate text-left">{{ createLabel }}</span>+ </AppButton>+ </template>+ </AppPicker>+ </span></template>diff --git a/src/components/properties/component-properties/ComponentPropertiesSection.vue b/src/components/properties/component-properties/ComponentPropertiesSection.vueindex 34922df53..663f6ef2e 100644--- a/src/components/properties/component-properties/ComponentPropertiesSection.vue+++ b/src/components/properties/component-properties/ComponentPropertiesSection.vue@@ -1,17 +1,26 @@<script setup lang="ts">import { computed } from 'vue'-import { MIXED, useComponentProperties, useI18n } from '@open-pencil/vue'+import { MIXED, useComponentProperties, useI18n, useSlotProperties } from '@open-pencil/vue'+import AssetThumbnail from '@/components/assets-panel/AssetThumbnail.vue'import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'import PanelSection from '@/components/ui/panel/PanelSection.vue'+import type { AppPickerItem } from '@/components/ui/select/AppPicker.vue'+import AppPickerField from '@/components/ui/select/AppPickerField.vue'import AppSelect from '@/components/ui/select/AppSelect.vue'import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'import ComponentPropertyTextField from './ComponentPropertyTextField.vue'+import SlotPropertyRow from './slot/SlotPropertyRow.vue'const { active, controls, setValue, setTextValue, flush } = useComponentProperties()-const { panels } = useI18n()+const slotProperties = useSlotProperties()+const slots = slotProperties.slots+const visible = computed(() => active.value || slots.value.length > 0)+/** Thumbnail edge in the Add instances list, matching the picker's 32px tile. */+const SLOT_THUMBNAIL_SIZE = 32+const { panels, common } = useI18n()const componentSectionUI = { title: 'text-component' }function selectOptions(control: (typeof controls.value)[number]) {@@ -28,19 +37,34 @@ function updateSelect(propertyId: string, value: string) {if (value !== 'MIXED') setValue(propertyId, value)}+/** Swap choices with the definition's preferred components first, as Figma lists them. */+function swapItems(control: (typeof controls.value)[number]): AppPickerItem[] {+ const anyPreferred = control.options.some((option) => option.preferred)+ const groupOf = (preferred: boolean | undefined) => {+ if (!anyPreferred) return undefined+ return preferred ? panels.value.preferredInstances : panels.value.allInstances+ }+ return control.options.map((option) => ({+ value: option.value,+ label: option.label,+ disabled: option.disabled,+ group: groupOf(option.preferred)+ }))+}+function booleanValue(control: (typeof controls.value)[number]) {return control.value !== MIXED && control.value === 'true'}const sectionLabel = computed(() =>- controls.value.every((control) => control.type === 'VARIANT')+ slots.value.length === 0 && controls.value.every((control) => control.type === 'VARIANT')? panels.value.variants: panels.value.componentProperties)</script><template>- <PanelSection v-if="active" :label="sectionLabel" :ui="componentSectionUI">+ <PanelSection v-if="visible" :label="sectionLabel" :ui="componentSectionUI"><div class="flex flex-col gap-1.5"><PanelFieldGroup v-for="control in controls" :key="control.id" :label="control.name"><ComponentPropertyTextField@@ -60,6 +84,18 @@ const sectionLabel = computed(() =>@update:model-value="setValue(control.id, String($event))"/></div>+ <AppPickerField+ v-else-if="control.type === 'INSTANCE_SWAP'"+ :model-value="control.value === MIXED ? '' : control.value"+ :items="swapItems(control)"+ :label="control.name"+ :placeholder="control.value === MIXED ? panels.mixed : undefined"+ :search-placeholder="panels.searchInstances"+ :empty-label="panels.noComponentsFound"+ :close-label="common.close"+ :data-property="control.id"+ @update:model-value="setValue(control.id, $event)"+ /><AppSelectv-else:label="control.name"@@ -69,6 +105,24 @@ const sectionLabel = computed(() =>@update:model-value="updateSelect(control.id, $event)"/></PanelFieldGroup>+ <SlotPropertyRow+ v-for="slot in slots"+ :key="slot.id"+ :name="slot.name"+ :modified="slot.modified"+ :item-count="slot.itemCount"+ :limits="slot.limits"+ :options="slotProperties.options(slot.id)"+ :preferred-only="slot.preferredOnly"+ @add="slotProperties.add(slot.frameId, $event)"+ @reset="slotProperties.reset(slot.frameId)"+ @delete-contents="slotProperties.clear(slot.frameId)"+ @select-layers="slotProperties.selectLayers(slot.offendingIds)"+ >+ <template #thumbnail="{ id }">+ <AssetThumbnail :node-id="id" alt="" :size="SLOT_THUMBNAIL_SIZE" />+ </template>+ </SlotPropertyRow></div></PanelSection></template>diff --git a/src/components/properties/component-properties/VariantAuthoringSection.vue b/src/components/properties/component-properties/VariantAuthoringSection.vueindex fe9743e54..a51605e0d 100644--- a/src/components/properties/component-properties/VariantAuthoringSection.vue+++ b/src/components/properties/component-properties/VariantAuthoringSection.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { computed, reactive, ref, watch } from 'vue'+import { computed, nextTick, reactive, ref, watch } from 'vue'import { useI18n, useVariantAuthoring } from '@open-pencil/vue'@@ -22,15 +22,12 @@ const {reorderValues,setVariantValue,addVariant,- duplicateVariant,- removeVariant+ duplicateVariant} = useVariantAuthoring()const { panels } = useI18n()const propertyNames = reactive<Record<string, string>>({})const propertyValues = reactive<Record<string, string>>({})const selectedValues = reactive<Record<string, string>>({})-const newPropertyName = ref('')-const newPropertyValue = ref('')const mutationConflictIds = ref<string[]>([])const conflictIds = computed(() =>@@ -124,13 +121,20 @@ function commitSelectedValue(propertyId: string) {}}-function createProperty() {- const name = newPropertyName.value.trim()- const value = newPropertyValue.value.trim()- if (!name || !value) return- addProperty(name, value)- newPropertyName.value = ''- newPropertyValue.value = ''+/** Add Property N and put the cursor in its name, so typing renames it right away. */+async function createProperty() {+ const id = addProperty()+ if (!id) return+ await nextTick()+ nameInputs.get(id)?.select()+}++/** Name fields of the listed properties, so a new one can be selected for typing. */+type SelectableInput = { select(): void }+const nameInputs = new Map<string, SelectableInput>()+function nameInputRef(id: string, input: SelectableInput | null) {+ if (input) nameInputs.set(id, input)+ else nameInputs.delete(id)}</script>@@ -138,14 +142,11 @@ function createProperty() {<PanelSection v-if="active" :label="panels.variants" :empty="definitions.length === 0"><template #actions><IconButton- :label="variant ? panels.duplicateVariant : panels.addVariant"- @click="variant ? duplicateVariant() : addVariant()"+ :label="variant ? panels.duplicateVariant : panels.addVariantProperty"+ @click="variant ? duplicateVariant() : createProperty()"><icon-lucide-plus class="size-3.5" /></IconButton>- <IconButton v-if="variant" :label="panels.removeVariant" @click="removeVariant">- <icon-lucide-trash-2 class="size-3.5" />- </IconButton></template><div v-if="variant" class="flex flex-col gap-1.5">@@ -183,6 +184,7 @@ function createProperty() {><div class="flex items-center gap-1"><AppInput+ :ref="(input) => nameInputRef(definition.id, input as SelectableInput | null)"v-model="propertyNames[definition.id]"size="sm"tone="panel"@@ -205,7 +207,7 @@ function createProperty() {<icon-lucide-chevron-down class="size-3.5" /></IconButton><IconButton :label="panels.removeVariantProperty" @click="removeProperty(definition.id)">- <icon-lucide-trash-2 class="size-3.5" />+ <icon-lucide-minus class="size-3.5" /></IconButton></div><div@@ -248,31 +250,15 @@ function createProperty() {<p v-else class="py-1 text-[10px] text-muted">{{ panels.noVariantProperties }}</p>- <form class="mt-2 flex flex-col gap-1.5" @submit.prevent="createProperty">- <div class="grid grid-cols-2 gap-1">- <AppInput- v-model="newPropertyName"- size="sm"- tone="panel"- :placeholder="panels.variantPropertyName"- :aria-label="panels.variantPropertyName"- />- <AppInput- v-model="newPropertyValue"- size="sm"- tone="panel"- :placeholder="panels.variantPropertyValue"- :aria-label="panels.variantPropertyValue"- />- </div>- <AppButton- type="submit"- size="xs"- variant="soft"- :disabled="!newPropertyName.trim() || !newPropertyValue.trim()"- >- {{ panels.addVariantProperty }}- </AppButton>- </form>+ <AppButton+ v-if="!variant"+ size="xs"+ variant="soft"+ class="mt-2 self-start"+ @click="addVariant()"+ >+ <icon-lucide-plus class="size-3.5" />+ {{ panels.addVariant }}+ </AppButton></PanelSection></template>diff --git a/src/components/properties/component-properties/slot/AddInstancesPopover.vue b/src/components/properties/component-properties/slot/AddInstancesPopover.vuenew file mode 100644index 000000000..e9f06619b--- /dev/null+++ b/src/components/properties/component-properties/slot/AddInstancesPopover.vue@@ -0,0 +1,60 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue'+import type { SlotInstanceOption } from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'+import AppPicker, { type AppPickerItem } from '@/components/ui/select/AppPicker.vue'++/**+ * Slots that allow only preferred instances list just those; otherwise every component is+ * offered, preferred ones first.+ */+const { options, preferredOnly = false } = defineProps<{+ options: SlotInstanceOption[]+ preferredOnly?: boolean+}>()+const emit = defineEmits<{ add: [id: string] }>()+defineSlots<{ thumbnail?(props: { id: string }): unknown }>()+const { panels, common } = useI18n()++const items = computed<AppPickerItem[]>(() => {+ const toItem = (option: SlotInstanceOption, group?: string): AppPickerItem => ({+ value: option.id,+ label: option.name,+ description: option.source,+ group+ })+ const preferred = options.filter((option) => option.preferred)+ if (preferredOnly) return preferred.map((option) => toItem(option))+ return [+ ...preferred.map((option) => toItem(option, panels.value.preferredInstances)),+ ...options+ .filter((option) => !option.preferred)+ .map((option) => toItem(option, panels.value.allInstances))+ ]+})+</script>++<template>+ <AppPicker+ :heading="panels.addInstances"+ :items="items"+ :search-placeholder="panels.searchInstances"+ :empty-label="panels.noInstancesFound"+ :close-label="common.close"+ @select="emit('add', $event)"+ >+ <template #trigger>+ <IconButton :label="panels.addInstances" data-property="slot-add-instances">+ <icon-lucide-plus class="size-3.5" />+ </IconButton>+ </template>+ <template #leading="{ item }">+ <slot name="thumbnail" :id="item.value">+ <icon-lucide-component class="size-3.5" />+ </slot>+ </template>+ </AppPicker>+</template>diff --git a/src/components/properties/component-properties/slot/SlotAuthoringSection.vue b/src/components/properties/component-properties/slot/SlotAuthoringSection.vuenew file mode 100644index 000000000..3b779f1ad--- /dev/null+++ b/src/components/properties/component-properties/slot/SlotAuthoringSection.vue@@ -0,0 +1,90 @@+<script setup lang="ts">+import { reactive, watch } from 'vue'++import { useI18n, useSlotAuthoring } from '@open-pencil/vue'++import AssetThumbnail from '@/components/assets-panel/AssetThumbnail.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import AppInput from '@/components/ui/input/AppInput.vue'+import PanelSection from '@/components/ui/panel/PanelSection.vue'++import SlotSettingsPopover from './SlotSettingsPopover.vue'++/** Slots of the selected main component or slot frame, and Create slot for a plain frame. */+const authoring = useSlotAuthoring()+const { active, canCreate, slots } = authoring+const { panels } = useI18n()+const names = reactive<Record<string, string>>({})+/** Thumbnail edge in the preferred components picker, matching its 32px tile. */+const THUMBNAIL_SIZE = 32++watch(+ slots,+ (items) => {+ for (const slot of items) names[slot.id] = slot.name+ },+ { immediate: true }+)++function commitName(propertyId: string) {+ const name = names[propertyId]?.trim()+ const slot = slots.value.find((item) => item.id === propertyId)+ if (!slot) return+ if (name && name !== slot.name) authoring.rename(propertyId, name)+ else names[propertyId] = slot.name+}++function blurInput(event: KeyboardEvent) {+ const target = event.currentTarget+ if (target instanceof HTMLInputElement) target.blur()+}+</script>++<template>+ <PanelSection v-if="active" :label="panels.slots">+ <div class="flex flex-col gap-1.5">+ <AppButton+ v-if="canCreate"+ variant="soft"+ class="self-start"+ data-property="create-slot"+ @click="authoring.create()"+ >+ <icon-lucide-square-dashed class="size-3.5 text-slot" />+ {{ panels.createSlot }}+ </AppButton>+ <div+ v-for="slot in slots"+ :key="slot.id"+ class="flex items-center gap-1"+ :data-property="`slot-definition-${slot.name}`"+ >+ <AppInput+ v-model="names[slot.id]"+ size="sm"+ tone="panel"+ class="flex-1"+ :aria-label="panels.slotName"+ @change="commitName(slot.id)"+ @enter="blurInput"+ />+ <SlotSettingsPopover+ :slot="slot"+ :options="authoring.options(slot.id)"+ @describe="authoring.describe(slot.id, $event)"+ @set-limits="authoring.setLimits(slot.id, $event)"+ @set-preferred-only="authoring.setPreferredOnly(slot.id, $event)"+ @set-preferred="(id, preferred) => authoring.setPreferred(slot.id, id, preferred)"+ >+ <template #thumbnail="{ id }">+ <AssetThumbnail :node-id="id" alt="" :size="THUMBNAIL_SIZE" />+ </template>+ </SlotSettingsPopover>+ <IconButton :label="panels.removeSlot" @click="authoring.remove(slot.id)">+ <icon-lucide-minus class="size-3.5" />+ </IconButton>+ </div>+ </div>+ </PanelSection>+</template>diff --git a/src/components/properties/component-properties/slot/SlotLimitsPopover.vue b/src/components/properties/component-properties/slot/SlotLimitsPopover.vuenew file mode 100644index 000000000..c5c505fdc--- /dev/null+++ b/src/components/properties/component-properties/slot/SlotLimitsPopover.vue@@ -0,0 +1,88 @@+<script setup lang="ts">+import { PopoverClose, PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'+import { computed } from 'vue'++import { useI18n, useRetainedPopup } from '@open-pencil/vue'+import type { SlotLimit } from '@open-pencil/vue'++import AppButton from '@/components/ui/button/AppButton.vue'+import SeverityIcon from '@/components/ui/feedback/SeverityIcon.vue'+import { usePopoverUI } from '@/components/ui/overlay/popover'++const { limits } = defineProps<{ limits: SlotLimit[] }>()+const emit = defineEmits<{ selectLayers: [] }>()+const { panels, common } = useI18n()+const { open: popupOpen, portalActive } = useRetainedPopup()+const issues = computed(() => limits.filter((limit) => !limit.met).length)+const styles = usePopoverUI({+ content: 'w-64 max-w-[calc(100vw-1rem)]',+ header: 'flex items-center gap-1.5 border-b border-border px-3 py-2',+ body: 'flex flex-col gap-2.5 p-3'+})++function label(limit: SlotLimit): string {+ if (limit.kind === 'minimum') return panels.value.slotMinimumLayers(limit.count)+ if (limit.kind === 'maximum') return panels.value.slotMaximumLayers(limit.count)+ return panels.value.slotPreferredOnly+}+</script>++<template>+ <PopoverRoot v-model:open="popupOpen">+ <PopoverTrigger+ :data-issues="issues > 0 || undefined"+ data-property="slot-limits"+ class="flex h-5 shrink-0 cursor-pointer items-center gap-1 rounded bg-panel-field px-1.5 text-[10px] text-muted outline-none hover:bg-hover hover:text-surface focus-visible:ring-1 focus-visible:ring-panel-focus data-issues:bg-issue-warning/15 data-issues:text-issue-warning"+ >+ <SeverityIcon v-if="issues" severity="warning" />+ <icon-lucide-check v-else class="size-3 text-success" />+ {{ panels.slotLimitCount(limits.length) }}+ </PopoverTrigger>+ <PopoverPortal v-if="portalActive">+ <PopoverContent+ side="left"+ align="start"+ :side-offset="8"+ :aria-label="panels.slotLimits"+ :class="styles.content"+ >+ <div :class="styles.header">+ <h3 class="text-xs font-semibold text-surface">{{ panels.slotLimits }}</h3>+ <span v-if="issues" class="text-[11px] text-muted">+ {{ panels.slotLimitIssueCount(issues) }}+ </span>+ <PopoverClose as-child>+ <AppButton :aria-label="common.close" class="ml-auto">+ <icon-lucide-x class="size-3.5" />+ </AppButton>+ </PopoverClose>+ </div>+ <ul :class="styles.body">+ <li+ v-for="limit in limits"+ :key="limit.kind"+ class="grid grid-cols-[14px_minmax(0,1fr)] gap-x-2 text-xs text-surface"+ >+ <icon-lucide-check v-if="limit.met" class="mt-px size-3.5 text-success" />+ <SeverityIcon v-else severity="warning" class="mt-px size-3.5" />+ <span>{{ label(limit) }}</span>+ <template v-if="limit.kind === 'preferred' && !limit.met">+ <span />+ <span class="text-[11px] text-muted">+ {{ panels.slotNonPreferredFound(limit.offending) }}+ </span>+ <span />+ <AppButton+ variant="soft"+ class="mt-1 justify-self-start"+ @click="emit('selectLayers')"+ >+ {{ panels.selectLayers }}+ </AppButton>+ </template>+ </li>+ </ul>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+</template>diff --git a/src/components/properties/component-properties/slot/SlotProperty.stories.ts b/src/components/properties/component-properties/slot/SlotProperty.stories.tsnew file mode 100644index 000000000..535eac8d9--- /dev/null+++ b/src/components/properties/component-properties/slot/SlotProperty.stories.ts@@ -0,0 +1,75 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, waitFor, within } from 'storybook/test'++import SlotSettings from './examples/Settings.vue'+import SlotPropertyStates from './examples/States.vue'++const meta = {+ title: 'Editor/Properties/Slot Property',+ component: SlotPropertyStates,+ tags: ['autodocs'],+ parameters: {+ docs: {+ description: {+ component:+ 'Slot properties of a selected instance: default and modified content, item counts, slot limits, and Add instances.'+ }+ }+ }+} satisfies Meta<typeof SlotPropertyStates>++export default meta+type Story = StoryObj<typeof meta>++export const Rows: Story = {}++/** The row of the named slot and the document body its popovers open in. */+function slotRow(canvasElement: HTMLElement, name: string) {+ const row = within(canvasElement).getByText(name).closest('[data-panel-field-group]')+ if (!(row instanceof HTMLElement)) throw new Error(`Missing ${name} slot`)+ return { row: within(row), page: within(canvasElement.ownerDocument.body) }+}++export const LimitsPopover: Story = {+ play: async ({ canvasElement }) => {+ const { row, page } = slotRow(canvasElement, 'Items')+ await userEvent.click(row.getByText('3 limits'))+ await waitFor(() => expect(page.getByText('At most 3 layers')).toBeVisible())+ await waitFor(() => expect(page.getByText('1 layer is not preferred')).toBeVisible())+ }+}++export const AddInstances: Story = {+ play: async ({ canvasElement }) => {+ const { row, page } = slotRow(canvasElement, 'Body')+ await userEvent.click(row.getByRole('button', { name: 'Add instances' }))+ await waitFor(() => expect(page.getByText('Preferred')).toBeVisible())+ await waitFor(() => expect(page.getByText('Avatar')).toBeVisible())+ }+}++export const AddPreferredOnly: Story = {+ play: async ({ canvasElement }) => {+ const { row, page } = slotRow(canvasElement, 'Items')+ await userEvent.click(row.getByRole('button', { name: 'Add instances' }))+ await waitFor(() => expect(page.getByText('List item')).toBeVisible())+ await expect(page.queryByText('Avatar')).toBeNull()+ }+}++export const Settings: Story = {+ render: () => ({ components: { SlotSettings }, template: '<SlotSettings />' }),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const page = within(canvasElement.ownerDocument.body)+ await userEvent.click(canvas.getByRole('button', { name: 'Slot settings' }))+ const maximum = await page.findByLabelText('Maximum layers')+ await userEvent.clear(maximum)+ await userEvent.type(maximum, '5')+ await userEvent.tab()+ await expect(canvas.getByText('limits: 1..5')).toBeVisible()+ await userEvent.click(page.getByRole('button', { name: 'Add preferred instances' }))+ await userEvent.click(await page.findByRole('option', { name: /Divider/ }))+ await expect(canvas.getByText('prefer divider')).toBeVisible()+ }+}diff --git a/src/components/properties/component-properties/slot/SlotPropertyRow.vue b/src/components/properties/component-properties/slot/SlotPropertyRow.vuenew file mode 100644index 000000000..609073781--- /dev/null+++ b/src/components/properties/component-properties/slot/SlotPropertyRow.vue@@ -0,0 +1,102 @@+<script setup lang="ts">+import {+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuRoot,+ DropdownMenuTrigger+} from 'reka-ui'++import { useI18n } from '@open-pencil/vue'+import type { SlotInstanceOption, SlotLimit } from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'+import { menuItem, useMenuUI } from '@/components/ui/menu/menu'+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'+import { panelFieldBase } from '@/theme/panel/field'++import AddInstancesPopover from './AddInstancesPopover.vue'+import SlotLimitsPopover from './SlotLimitsPopover.vue'++/** One slot property of a selected instance: its state, limits, and content actions. */+const {+ name,+ modified,+ itemCount,+ limits = [],+ options,+ preferredOnly = false+} = defineProps<{+ name: string+ /** Whether the instance owns this slot's content instead of following its component. */+ modified: boolean+ itemCount: number+ limits?: SlotLimit[]+ options: SlotInstanceOption[]+ preferredOnly?: boolean+}>()+const emit = defineEmits<{+ add: [id: string]+ reset: []+ deleteContents: []+ selectLayers: []+}>()+defineSlots<{ thumbnail?(props: { id: string }): unknown }>()+const { panels } = useI18n()+const menu = useMenuUI({ content: 'min-w-40' })+const item = menuItem({ justify: 'start' })+</script>++<template>+ <PanelFieldGroup :label="name">+ <div class="flex items-center gap-1" :data-property="`slot-${name}`">+ <div+ :class="[panelFieldBase, 'flex flex-1 items-center gap-1.5 px-2 text-xs']"+ :data-modified="modified || undefined"+ >+ <icon-lucide-square-dashed class="size-3.5 shrink-0 text-slot" />+ <span class="truncate" :class="modified ? 'text-surface' : 'text-muted'">+ {{ modified ? panels.slotModified : panels.slotDefault }}+ </span>+ <span class="ml-auto shrink-0 text-[11px] text-muted">+ {{ panels.slotItemCount(itemCount) }}+ </span>+ </div>+ <AddInstancesPopover+ :options="options"+ :preferred-only="preferredOnly"+ @add="emit('add', $event)"+ >+ <template v-if="$slots.thumbnail" #thumbnail="{ id }">+ <slot name="thumbnail" :id="id" />+ </template>+ </AddInstancesPopover>+ <DropdownMenuRoot>+ <DropdownMenuTrigger as-child>+ <IconButton :label="panels.slotActions({ name })">+ <icon-lucide-ellipsis class="size-3.5" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent side="bottom" align="end" :side-offset="4" :class="menu.content">+ <DropdownMenuItem :class="item" :disabled="!modified" @select="emit('reset')">+ <icon-lucide-rotate-ccw :class="menu.icon" />+ {{ panels.resetSlot }}+ </DropdownMenuItem>+ <DropdownMenuItem+ :class="item"+ :disabled="itemCount === 0"+ @select="emit('deleteContents')"+ >+ <icon-lucide-trash-2 :class="menu.icon" />+ {{ panels.deleteSlotContents }}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ </div>+ <div v-if="limits.length" class="flex">+ <SlotLimitsPopover :limits="limits" @select-layers="emit('selectLayers')" />+ </div>+ </PanelFieldGroup>+</template>diff --git a/src/components/properties/component-properties/slot/SlotSettingsPopover.vue b/src/components/properties/component-properties/slot/SlotSettingsPopover.vuenew file mode 100644index 000000000..eb49568fb--- /dev/null+++ b/src/components/properties/component-properties/slot/SlotSettingsPopover.vue@@ -0,0 +1,184 @@+<script setup lang="ts">+import { PopoverClose, PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'+import { computed, ref, watch } from 'vue'++import { useI18n, useRetainedPopup } from '@open-pencil/vue'+import type { SlotDefinitionControl, SlotInstanceOption } from '@open-pencil/vue'++import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import AppInput from '@/components/ui/input/AppInput.vue'+import AppTextarea from '@/components/ui/input/AppTextarea.vue'+import { usePopoverUI } from '@/components/ui/overlay/popover'+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'+import AppPicker, { type AppPickerItem } from '@/components/ui/select/AppPicker.vue'+import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'++/** A main component's slot settings: description, layer limits, and preferred components. */+const { slot, options } = defineProps<{+ slot: SlotDefinitionControl+ options: SlotInstanceOption[]+}>()+const emit = defineEmits<{+ describe: [description: string]+ setLimits: [limits: { minChildren?: number; maxChildren?: number }]+ setPreferredOnly: [value: boolean]+ setPreferred: [componentId: string, preferred: boolean]+}>()+defineSlots<{ thumbnail?(props: { id: string }): unknown }>()+const { panels, common } = useI18n()+const { open: popupOpen, portalActive } = useRetainedPopup()+const styles = usePopoverUI({+ content: 'w-64 max-w-[calc(100vw-1rem)]',+ header: 'flex items-center gap-1.5 border-b border-border px-3 py-2',+ body: 'flex flex-col gap-3 p-3'+})++const description = ref(slot.description)+const minimum = ref<string | number>(slot.minChildren ?? '')+const maximum = ref<string | number>(slot.maxChildren ?? '')+watch(+ () => slot,+ (current) => {+ description.value = current.description+ minimum.value = current.minChildren ?? ''+ maximum.value = current.maxChildren ?? ''+ }+)++/** A limit field's value: a whole number of layers, or none when left empty. */+function limit(value: string | number): number | undefined {+ const parsed = typeof value === 'number' ? value : Number.parseInt(value, 10)+ return Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : undefined+}++function commitLimits() {+ emit('setLimits', { minChildren: limit(minimum.value), maxChildren: limit(maximum.value) })+}++function commitDescription() {+ const next = description.value.trim()+ description.value = next+ if (next !== slot.description) emit('describe', next)+}++const candidates = computed<AppPickerItem[]>(() =>+ options+ .filter((option) => !option.preferred)+ .map((option) => ({ value: option.id, label: option.name, description: option.source }))+)+</script>++<template>+ <PopoverRoot v-model:open="popupOpen">+ <PopoverTrigger as-child>+ <IconButton :label="panels.slotSettings" data-property="slot-settings">+ <icon-lucide-sliders-horizontal class="size-3.5" />+ </IconButton>+ </PopoverTrigger>+ <PopoverPortal v-if="portalActive">+ <PopoverContent+ side="left"+ align="start"+ :side-offset="8"+ :aria-label="panels.slotSettings"+ :class="styles.content"+ @focus-outside.prevent+ >+ <div :class="styles.header">+ <icon-lucide-square-dashed class="size-3.5 text-slot" />+ <h3 class="truncate text-xs font-semibold text-surface">{{ slot.name }}</h3>+ <PopoverClose as-child>+ <AppButton :aria-label="common.close" class="ml-auto">+ <icon-lucide-x class="size-3.5" />+ </AppButton>+ </PopoverClose>+ </div>+ <div :class="styles.body">+ <PanelFieldGroup :label="panels.slotDescription">+ <AppTextarea+ v-model="description"+ :rows="2"+ :aria-label="panels.slotDescription"+ @blur="commitDescription"+ />+ </PanelFieldGroup>+ <div class="grid grid-cols-2 gap-2">+ <PanelFieldGroup :label="panels.slotMinimum">+ <AppInput+ v-model="minimum"+ type="number"+ size="sm"+ tone="panel"+ :min="0"+ :placeholder="panels.slotNoLimit"+ :aria-label="panels.slotMinimum"+ data-property="slot-minimum"+ @change="commitLimits"+ />+ </PanelFieldGroup>+ <PanelFieldGroup :label="panels.slotMaximum">+ <AppInput+ v-model="maximum"+ type="number"+ size="sm"+ tone="panel"+ :min="0"+ :placeholder="panels.slotNoLimit"+ :aria-label="panels.slotMaximum"+ data-property="slot-maximum"+ @change="commitLimits"+ />+ </PanelFieldGroup>+ </div>+ <PanelFieldGroup :label="panels.preferredInstances">+ <ul class="flex flex-col gap-0.5">+ <li+ v-for="option in slot.preferred"+ :key="option.id"+ class="flex h-7 items-center gap-1.5 rounded px-1 text-xs text-surface hover:bg-hover"+ >+ <icon-lucide-diamond class="size-3.5 shrink-0 text-component" />+ <span class="min-w-0 flex-1 truncate">{{ option.name }}</span>+ <IconButton+ :label="panels.removePreferredInstance"+ @click="emit('setPreferred', option.id, false)"+ >+ <icon-lucide-minus class="size-3.5" />+ </IconButton>+ </li>+ </ul>+ <AppPicker+ :heading="panels.addPreferredInstances"+ :items="candidates"+ :search-placeholder="panels.searchInstances"+ :empty-label="panels.noInstancesFound"+ :close-label="common.close"+ @select="emit('setPreferred', $event, true)"+ >+ <template #trigger>+ <AppButton variant="soft" class="self-start" data-property="slot-add-preferred">+ <icon-lucide-plus class="size-3.5" />+ {{ panels.addPreferredInstances }}+ </AppButton>+ </template>+ <template #leading="{ item }">+ <slot name="thumbnail" :id="item.value">+ <icon-lucide-component class="size-3.5" />+ </slot>+ </template>+ </AppPicker>+ </PanelFieldGroup>+ <label class="flex items-center justify-between gap-2 text-xs text-surface">+ {{ panels.slotPreferredOnly }}+ <AppSwitch+ :model-value="slot.preferredOnly"+ :label="panels.slotPreferredOnly"+ @update:model-value="emit('setPreferredOnly', $event)"+ />+ </label>+ </div>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+</template>diff --git a/src/components/properties/component-properties/slot/examples/Settings.vue b/src/components/properties/component-properties/slot/examples/Settings.vuenew file mode 100644index 000000000..f6d6ac949--- /dev/null+++ b/src/components/properties/component-properties/slot/examples/Settings.vue@@ -0,0 +1,61 @@+<script setup lang="ts">+import { ref } from 'vue'++import type { SlotDefinitionControl, SlotInstanceOption } from '@open-pencil/vue'++import PanelSection from '@/components/ui/panel/PanelSection.vue'++import SlotSettingsPopover from '../SlotSettingsPopover.vue'++const options = ref<SlotInstanceOption[]>([+ { id: 'item', name: 'List item', preferred: true, source: 'This file' },+ { id: 'divider', name: 'Divider', preferred: false, source: 'This file' },+ { id: 'button', name: 'Button', preferred: false, source: 'Design system' }+])+const slot = ref<SlotDefinitionControl>({+ id: 'items',+ name: 'Items',+ description: 'Put list items here',+ minChildren: 1,+ maxChildren: 3,+ preferredOnly: true,+ preferred: options.value.filter((option) => option.preferred)+})+const log = ref<string[]>([])+const record = (entry: string) => {+ log.value = [entry, ...log.value].slice(0, 4)+}++function setPreferred(id: string, preferred: boolean) {+ options.value = options.value.map((option) =>+ option.id === id ? { ...option, preferred } : option+ )+ slot.value = { ...slot.value, preferred: options.value.filter((option) => option.preferred) }+ record(`${preferred ? 'prefer' : 'unprefer'} ${id}`)+}+</script>++<template>+ <div class="flex gap-6">+ <div class="w-[240px] overflow-hidden rounded-lg border border-border bg-panel">+ <PanelSection label="Slots">+ <div class="flex items-center gap-1">+ <span class="flex-1 truncate text-xs text-surface">{{ slot.name }}</span>+ <SlotSettingsPopover+ :slot="slot"+ :options="options"+ @describe="record(`describe: ${$event}`)"+ @set-limits="+ record(`limits: ${$event.minChildren ?? '-'}..${$event.maxChildren ?? '-'}`)+ "+ @set-preferred-only="record(`preferred only: ${$event}`)"+ @set-preferred="setPreferred"+ />+ </div>+ </PanelSection>+ </div>+ <ul class="text-xs text-muted" aria-label="Events">+ <li v-for="entry in log" :key="entry">{{ entry }}</li>+ </ul>+ </div>+</template>diff --git a/src/components/properties/component-properties/slot/examples/States.vue b/src/components/properties/component-properties/slot/examples/States.vuenew file mode 100644index 000000000..c9f69dbc1--- /dev/null+++ b/src/components/properties/component-properties/slot/examples/States.vue@@ -0,0 +1,86 @@+<script setup lang="ts">+import { ref } from 'vue'++import type { SlotInstanceOption, SlotLimit } from '@open-pencil/vue'++import ComponentPropertyTextField from '@/components/properties/component-properties/ComponentPropertyTextField.vue'+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'+import PanelSection from '@/components/ui/panel/PanelSection.vue'++import SlotPropertyRow from '../SlotPropertyRow.vue'++const options: SlotInstanceOption[] = [+ { id: 'item', name: 'List item', preferred: true, source: 'This file' },+ { id: 'item-icon', name: 'List item / With icon', preferred: true, source: 'This file' },+ { id: 'divider', name: 'Divider', preferred: false, source: 'This file' },+ { id: 'button', name: 'Button', preferred: false, source: 'Design system' },+ { id: 'avatar', name: 'Avatar', preferred: false, source: 'Design system' }+]+const brokenLimits: SlotLimit[] = [+ { kind: 'minimum', count: 1, met: true },+ { kind: 'maximum', count: 3, met: false },+ { kind: 'preferred', met: false, offending: 1 }+]+const title = ref('Settings')+const log = ref<string[]>([])+const record = (entry: string) => {+ log.value = [entry, ...log.value].slice(0, 4)+}+</script>++<template>+ <div class="flex gap-6">+ <div class="w-[240px] overflow-hidden rounded-lg border border-border bg-panel">+ <PanelSection label="Component properties" :ui="{ title: 'text-component' }">+ <div class="flex flex-col gap-1.5">+ <PanelFieldGroup label="Title">+ <ComponentPropertyTextField :value="title" label="Title" @update="title = $event" />+ </PanelFieldGroup>+ <SlotPropertyRow+ name="Header"+ :modified="false"+ :item-count="2"+ :options="options"+ @add="record(`Header: add ${$event}`)"+ />+ <SlotPropertyRow+ name="Body"+ :modified="true"+ :item-count="3"+ :options="options"+ @add="record(`Body: add ${$event}`)"+ @reset="record('Body: reset')"+ @delete-contents="record('Body: delete contents')"+ />+ <SlotPropertyRow+ name="Items"+ :modified="true"+ :item-count="5"+ :limits="brokenLimits"+ :options="options"+ preferred-only+ @add="record(`Items: add ${$event}`)"+ @select-layers="record('Items: select layers')"+ />+ <SlotPropertyRow+ name="Actions"+ :modified="true"+ :item-count="1"+ :limits="[{ kind: 'maximum', count: 2, met: true }]"+ :options="options"+ />+ <SlotPropertyRow+ name="Footer"+ :modified="true"+ :item-count="0"+ :limits="[{ kind: 'minimum', count: 1, met: false }]"+ :options="options"+ />+ </div>+ </PanelSection>+ </div>+ <ol aria-label="Events" class="w-48 text-[11px] text-muted">+ <li v-for="(entry, index) in log" :key="index">{{ entry }}</li>+ </ol>+ </div>+</template>diff --git a/src/components/properties/layout/grid/GridControls.vue b/src/components/properties/layout/grid/GridControls.vueindex 1e9784d04..f961c4eb7 100644--- a/src/components/properties/layout/grid/GridControls.vue+++ b/src/components/properties/layout/grid/GridControls.vue@@ -26,7 +26,10 @@ function defaultTrackValue(sizing: GridTrackSizing): number {<label class="text-[11px] text-muted">{{ trackProp === 'gridTemplateColumns' ? panels.columns : panels.rows }}</label>- <IconButton @click="ctx.addTrack(trackProp)">+ <IconButton+ :label="trackProp === 'gridTemplateColumns' ? panels.addGridColumn : panels.addGridRow"+ @click="ctx.addTrack(trackProp)"+ ><icon-lucide-plus class="size-3.5" /></IconButton></div>@@ -52,8 +55,14 @@ function defaultTrackValue(sizing: GridTrackSizing): number {})"/>- <IconButton v-if="ctx.node[trackProp].length > 1" @click="ctx.removeTrack(trackProp, i)">- <icon-lucide-x class="size-3.5" />+ <IconButton+ v-if="ctx.node[trackProp].length > 1"+ :label="+ trackProp === 'gridTemplateColumns' ? panels.removeGridColumn : panels.removeGridRow+ "+ @click="ctx.removeTrack(trackProp, i)"+ >+ <icon-lucide-minus class="size-3.5" /></IconButton></div></div>diff --git a/src/components/properties/shared-style/SharedStyleField.vue b/src/components/properties/shared-style/SharedStyleField.vueindex ae15314c1..258c17330 100644--- a/src/components/properties/shared-style/SharedStyleField.vue+++ b/src/components/properties/shared-style/SharedStyleField.vue@@ -1,22 +1,27 @@<script setup lang="ts">import type { SharedStyleKind } from '@open-pencil/scene-graph'+import { useI18n } from '@open-pencil/vue'import { useSharedStylePicker } from '@/components/properties/shared-style/useSharedStylePicker'import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'import PanelGrid from '@/components/ui/panel/PanelGrid.vue'-import AppSelect from '@/components/ui/select/AppSelect.vue'+import AppPickerField from '@/components/ui/select/AppPickerField.vue'const { kind, label } = defineProps<{ kind: SharedStyleKind; label: string }>()const { visible, value, options, update } = useSharedStylePicker(kind)+const { panels, common } = useI18n()</script><template><PanelGrid v-if="visible" class="mb-1.5"><PanelFieldGroup :label="label">- <AppSelect+ <AppPickerField:model-value="value"- :options="options"+ :items="options":label="label"+ :search-placeholder="panels.searchStyles"+ :empty-label="panels.noStylesFound"+ :close-label="common.close":data-property="`${kind}-style`"@update:model-value="update"/>diff --git a/src/components/ui/binding/ui.ts b/src/components/ui/binding/ui.tsindex 21bf94767..740dad7a3 100644--- a/src/components/ui/binding/ui.ts+++ b/src/components/ui/binding/ui.ts@@ -22,15 +22,6 @@ export function useBindingFieldUI(options: BindingFieldUIOptions = {}, ui?: Bindpill: styles.pill({ class: ui?.pill }),pillLabel: styles.pillLabel({ class: ui?.pillLabel }),trigger: styles.trigger({ class: ui?.trigger }),- pickerContent: styles.pickerContent({ class: ui?.pickerContent }),- pickerSearch: styles.pickerSearch({ class: ui?.pickerSearch }),- pickerViewport: styles.pickerViewport({ class: ui?.pickerViewport }),- pickerItem: styles.pickerItem({ class: ui?.pickerItem }),- pickerItemIcon: styles.pickerItemIcon({ class: ui?.pickerItemIcon }),- pickerItemLabel: styles.pickerItemLabel({ class: ui?.pickerItemLabel }),- pickerItemIndicator: styles.pickerItemIndicator({ class: ui?.pickerItemIndicator }),- pickerEmpty: styles.pickerEmpty({ class: ui?.pickerEmpty }),- pickerFooter: styles.pickerFooter({ class: ui?.pickerFooter }),createForm: styles.createForm({ class: ui?.createForm }),createInput: styles.createInput({ class: ui?.createInput })}diff --git a/src/components/ui/button/IconButton.vue b/src/components/ui/button/IconButton.vueindex b05fc107e..26bf524bd 100644--- a/src/components/ui/button/IconButton.vue+++ b/src/components/ui/button/IconButton.vue@@ -16,7 +16,8 @@ const {} = defineProps<{active?: booleandisabled?: boolean- label?: string+ /** Accessible name and tooltip; every icon-only button needs one. */+ label: stringside?: 'top' | 'bottom' | 'left' | 'right'size?: ControlSizetype?: 'button' | 'submit' | 'reset'@@ -37,7 +38,7 @@ const cls = computed(() =></script><template>- <Tip as-child :label="label" :side="side" :disabled="disabled || !label">+ <Tip as-child :label="label" :side="side" :disabled="disabled"><buttonv-bind="buttonAttrs"data-slot="icon-button"diff --git a/src/components/design-check/SeverityIcon.vue b/src/components/ui/feedback/SeverityIcon.vuesimilarity index 82%rename from src/components/design-check/SeverityIcon.vuerename to src/components/ui/feedback/SeverityIcon.vueindex 6a9e6355e..228db1cd4 100644--- a/src/components/design-check/SeverityIcon.vue+++ b/src/components/ui/feedback/SeverityIcon.vue@@ -1,6 +1,7 @@<script setup lang="ts">-import type { DesignIssueSeverity } from '@/app/editor/design-check/issues'-import { severityIcon } from '@/theme/design-check'+import type { DesignIssueSeverity } from '@open-pencil/core/canvas'++import { severityIcon } from '@/theme/feedback/severity'const { severity, class: className } = defineProps<{severity: DesignIssueSeveritydiff --git a/src/components/ui/menu/menu.ts b/src/components/ui/menu/menu.tsindex 5b3980887..36f741288 100644--- a/src/components/ui/menu/menu.ts+++ b/src/components/ui/menu/menu.ts@@ -1,8 +1,11 @@import { tv } from 'tailwind-variants'+import { motionStyles } from '@/theme/motion/styles'+import { floatingSurface } from '@/theme/overlay'+export const menu = tv({slots: {- content: 'z-50 rounded-xl bg-panel p-1 shadow-[0_8px_30px_rgb(0_0_0/0.4)]',+ content: ['z-50 p-1', floatingSurface, motionStyles.floating],item: 'flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-[11px] outline-none select-none data-[disabled]:cursor-default data-[disabled]:text-muted/50 data-[highlighted]:bg-hover',separator: 'mx-1 my-1 h-px bg-border',label: 'px-2 pt-1.5 pb-1 text-[11px] text-muted select-none',diff --git a/src/components/ui/overlay/popover.ts b/src/components/ui/overlay/popover.tsindex 3a6891baa..8fad95354 100644--- a/src/components/ui/overlay/popover.ts+++ b/src/components/ui/overlay/popover.ts@@ -1,8 +1,11 @@import { tv } from 'tailwind-variants'+import { motionStyles } from '@/theme/motion/styles'+import { floatingSurface } from '@/theme/overlay'+export const popover = tv({slots: {- content: 'z-[100] rounded-xl bg-panel shadow-[0_8px_30px_rgb(0_0_0/0.4)]',+ content: ['z-[100]', floatingSurface, motionStyles.floating],header: '',body: '',footer: ''diff --git a/src/components/ui/overlay/tooltip.ts b/src/components/ui/overlay/tooltip.tsindex 901b79b96..e137e47f2 100644--- a/src/components/ui/overlay/tooltip.ts+++ b/src/components/ui/overlay/tooltip.ts@@ -1,9 +1,10 @@import { tv } from 'tailwind-variants'+import { tooltipSurface } from '@/theme/overlay'+export const tooltip = tv({slots: {- content:- 'z-50 rounded-md bg-panel px-2 py-1 text-[11px] text-surface shadow-[0_8px_30px_rgb(0_0_0/0.4)]'+ content: ['z-50 px-2 py-1 text-[11px]', tooltipSurface]}})diff --git a/src/components/ui/select/AppPicker.stories.ts b/src/components/ui/select/AppPicker.stories.tsnew file mode 100644index 000000000..654d9fa06--- /dev/null+++ b/src/components/ui/select/AppPicker.stories.ts@@ -0,0 +1,61 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, waitFor, within } from 'storybook/test'++import Picker from './examples/Picker.vue'++const meta = {+ title: 'Design System/Picker',+ component: Picker,+ tags: ['autodocs'],+ parameters: {+ docs: {+ description: {+ component:+ 'A searchable, grouped list that opens beside the properties panel. Comfortable rows carry a thumbnail and a description; compact rows suit plain names such as variables.'+ }+ }+ }+} satisfies Meta<typeof Picker>++export default meta+type Story = StoryObj<typeof meta>++export const Default: Story = {}++/** Open the components picker and wait for its search field to take focus. */+async function openComponents(canvasElement: HTMLElement) {+ const canvas = within(canvasElement)+ const page = within(canvasElement.ownerDocument.body)+ await userEvent.click(canvas.getByRole('button', { name: 'Add instances' }))+ const search = await page.findByPlaceholderText('Search components')+ await waitFor(() => expect(search).toHaveFocus())+ return { canvas, page }+}++export const Components: Story = {+ play: async ({ canvasElement }) => {+ const { page } = await openComponents(canvasElement)+ await expect(page.getAllByText('Design system')).toHaveLength(2)+ }+}++export const KeyboardSearch: Story = {+ play: async ({ canvasElement }) => {+ const { canvas, page } = await openComponents(canvasElement)+ await userEvent.keyboard('butt')+ await expect(page.queryByText('Divider')).toBeNull()+ await userEvent.keyboard('{ArrowDown}{Enter}')+ await waitFor(() => expect(canvas.getByText(/^Chosen:/)).toHaveTextContent('Chosen: button'))+ }+}++export const CompactWithFooter: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const page = within(canvasElement.ownerDocument.body)+ await userEvent.click(canvas.getByRole('button', { name: 'Apply variable' }))+ await waitFor(() =>+ expect(page.getByRole('button', { name: /Create number variable/ })).toBeVisible()+ )+ }+}diff --git a/src/components/ui/select/AppPicker.vue b/src/components/ui/select/AppPicker.vuenew file mode 100644index 000000000..29fec26ba--- /dev/null+++ b/src/components/ui/select/AppPicker.vue@@ -0,0 +1,205 @@+<script lang="ts">+import type { VNode } from 'vue'++import type { ComponentUI } from '@/components/ui/types'+import type { AppPickerTheme } from '@/theme/select/picker'++export interface AppPickerItem {+ value: string+ label: string+ description?: string+ /** Items keep their order; groups appear in the order their first item does. */+ group?: string+ disabled?: boolean+}++export interface AppPickerProps {+ /** Header text of the open list, also its accessible name. */+ heading: string+ items: AppPickerItem[]+ searchPlaceholder: string+ emptyLabel: string+ closeLabel: string+ /** The current choice, marked with a check. */+ selected?: string+ /** Tooltip on the trigger; wraps the popover trigger so both reach the same element. */+ tooltip?: string+ density?: 'compact' | 'comfortable'+ side?: 'left' | 'right' | 'top' | 'bottom'+ align?: 'start' | 'center' | 'end'+ ui?: ComponentUI<AppPickerTheme>+}++export interface AppPickerSlots {+ /** The control that opens the picker; rendered as the popover trigger. */+ trigger(): VNode[]+ /** Thumbnail or icon before an item's label. */+ leading?(props: { item: AppPickerItem }): VNode[]+ /** Actions below the list, such as creating a new choice. */+ footer?(props: { close: () => void }): VNode[]+}+</script>++<script setup lang="ts">+import Fuse from 'fuse.js'+import {+ ListboxContent,+ ListboxFilter,+ ListboxGroup,+ ListboxGroupLabel,+ ListboxItem,+ ListboxRoot,+ PopoverClose,+ PopoverContent,+ PopoverPortal,+ PopoverRoot,+ PopoverTrigger,+ type AcceptableValue+} from 'reka-ui'+import { tv } from 'tailwind-variants'+import { computed, ref, watch } from 'vue'++import { useRetainedPopup } from '@open-pencil/vue'++import AppButton from '@/components/ui/button/AppButton.vue'+import Tip from '@/components/ui/overlay/Tip.vue'+import theme from '@/theme/select/picker'++const {+ heading,+ items,+ searchPlaceholder,+ emptyLabel,+ closeLabel,+ selected,+ tooltip,+ density = 'comfortable',+ side = 'left',+ align = 'start',+ ui+} = defineProps<AppPickerProps>()+const emit = defineEmits<{ select: [value: string] }>()+const slots = defineSlots<AppPickerSlots>()+const open = defineModel<boolean>('open', { default: false })+const { portalActive } = useRetainedPopup(open, () => close())+const query = ref('')+// However the list closes, by the user or from outside through v-model, it reopens unfiltered.+watch(open, (isOpen) => {+ if (!isOpen) query.value = ''+})+const styles = computed(() => tv(theme)({ density }))++const index = computed(+ () =>+ new Fuse(items, {+ keys: ['label', 'description', 'group'],+ threshold: 0.2,+ ignoreLocation: true+ })+)+const matches = computed(() => {+ const term = query.value.trim()+ return term ? index.value.search(term).map((result) => result.item) : items+})+const groups = computed(() => {+ const byGroup = new Map<string, AppPickerItem[]>()+ for (const item of matches.value) {+ const key = item.group ?? ''+ byGroup.set(key, [...(byGroup.get(key) ?? []), item])+ }+ return [...byGroup.entries()]+})++function close() {+ open.value = false+}++function select(value: AcceptableValue) {+ if (typeof value !== 'string') return+ close()+ emit('select', value)+}+</script>++<template>+ <PopoverRoot v-model:open="open">+ <Tip as-child :label="tooltip" :disabled="!tooltip">+ <PopoverTrigger as-child>+ <slot name="trigger" />+ </PopoverTrigger>+ </Tip>+ <PopoverPortal v-if="portalActive">+ <PopoverContent+ :side="side"+ :align="align"+ :side-offset="8"+ :aria-label="heading"+ :class="styles.content({ class: ui?.content })"+ @open-auto-focus.prevent+ >+ <div :class="styles.header({ class: ui?.header })">+ <h3 :class="styles.title({ class: ui?.title })">{{ heading }}</h3>+ <PopoverClose as-child>+ <AppButton :aria-label="closeLabel" class="ml-auto">+ <icon-lucide-x class="size-3.5" />+ </AppButton>+ </PopoverClose>+ </div>+ <ListboxRoot+ class="flex min-h-0 flex-col"+ highlight-on-hover+ :aria-label="heading"+ @update:model-value="select"+ >+ <div :class="styles.search({ class: ui?.search })">+ <icon-lucide-search :class="styles.searchIcon({ class: ui?.searchIcon })" />+ <ListboxFilter+ v-model="query"+ auto-focus+ :placeholder="searchPlaceholder"+ :aria-label="searchPlaceholder"+ :class="styles.input({ class: ui?.input })"+ />+ </div>+ <ListboxContent :class="styles.list({ class: ui?.list })">+ <p v-if="groups.length === 0" :class="styles.empty({ class: ui?.empty })">+ {{ emptyLabel }}+ </p>+ <ListboxGroup v-for="[group, entries] in groups" :key="group">+ <ListboxGroupLabel v-if="group" :class="styles.groupLabel({ class: ui?.groupLabel })">+ {{ group }}+ </ListboxGroupLabel>+ <ListboxItem+ v-for="item in entries"+ :key="item.value"+ :value="item.value"+ :disabled="item.disabled"+ :class="styles.item({ class: ui?.item })"+ >+ <span v-if="slots.leading" :class="styles.leading({ class: ui?.leading })">+ <slot name="leading" :item="item" />+ </span>+ <span :class="styles.text({ class: ui?.text })">+ <span :class="styles.label({ class: ui?.label })">{{ item.label }}</span>+ <span+ v-if="item.description && density === 'comfortable'"+ :class="styles.description({ class: ui?.description })"+ >+ {{ item.description }}+ </span>+ </span>+ <icon-lucide-check+ v-if="item.value === selected"+ :class="styles.check({ class: ui?.check })"+ />+ </ListboxItem>+ </ListboxGroup>+ </ListboxContent>+ </ListboxRoot>+ <div v-if="slots.footer" :class="styles.footer({ class: ui?.footer })">+ <slot name="footer" :close="close" />+ </div>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+</template>diff --git a/src/components/ui/select/AppPickerField.vue b/src/components/ui/select/AppPickerField.vuenew file mode 100644index 000000000..e294f2d5a--- /dev/null+++ b/src/components/ui/select/AppPickerField.vue@@ -0,0 +1,53 @@+<script setup lang="ts">+import { tv } from 'tailwind-variants'+import { computed } from 'vue'++import AppPicker, { type AppPickerItem } from '@/components/ui/select/AppPicker.vue'+import theme from '@/theme/select/app'++/** A select-looking field whose choices open in the searchable picker. */+const { label, items, searchPlaceholder, emptyLabel, closeLabel, placeholder } = defineProps<{+ label: string+ items: AppPickerItem[]+ searchPlaceholder: string+ emptyLabel: string+ closeLabel: string+ /** Shown when the value matches no item, such as a mixed selection. */+ placeholder?: string+}>()+const value = defineModel<string>({ required: true })+defineSlots<{ leading?(props: { item: AppPickerItem }): unknown }>()+defineOptions({ inheritAttrs: false })+const styles = tv(theme)()+const current = computed(() => items.find((item) => item.value === value.value))+</script>++<template>+ <AppPicker+ :heading="label"+ :items="items"+ :selected="value"+ density="compact"+ :search-placeholder="searchPlaceholder"+ :empty-label="emptyLabel"+ :close-label="closeLabel"+ @select="value = $event"+ >+ <template #trigger>+ <button+ type="button"+ role="combobox"+ aria-haspopup="listbox"+ v-bind="$attrs"+ :aria-label="label"+ :class="styles.trigger()"+ >+ <span :class="styles.value()">{{ current?.label ?? placeholder ?? value }}</span>+ <icon-lucide-chevron-down class="ml-1 size-3 shrink-0 text-muted" />+ </button>+ </template>+ <template v-if="$slots.leading" #leading="{ item }">+ <slot name="leading" :item="item" />+ </template>+ </AppPicker>+</template>diff --git a/src/components/ui/select/examples/Picker.vue b/src/components/ui/select/examples/Picker.vuenew file mode 100644index 000000000..efd557d5b--- /dev/null+++ b/src/components/ui/select/examples/Picker.vue@@ -0,0 +1,74 @@+<script setup lang="ts">+import { ref } from 'vue'+import IconComponent from '~icons/lucide/component'+import IconDiamond from '~icons/lucide/diamond'+import IconPlus from '~icons/lucide/plus'++import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import AppPicker, { type AppPickerItem } from '@/components/ui/select/AppPicker.vue'++const components: AppPickerItem[] = [+ { value: 'item', label: 'List item', description: 'This file', group: 'Preferred' },+ {+ value: 'item-icon',+ label: 'List item / With icon',+ description: 'This file',+ group: 'Preferred'+ },+ { value: 'divider', label: 'Divider', description: 'This file', group: 'All components' },+ { value: 'button', label: 'Button', description: 'Design system', group: 'All components' },+ { value: 'avatar', label: 'Avatar', description: 'Design system', group: 'All components' }+]+const variables: AppPickerItem[] = [+ { value: 'space/sm', label: 'Space/sm', group: 'Spacing' },+ { value: 'space/md', label: 'Space/md', group: 'Spacing' },+ { value: 'space/lg', label: 'Space/lg', group: 'Spacing' },+ { value: 'radius/md', label: 'Radius/md', group: 'Radius', disabled: true }+]+const chosen = ref('')+</script>++<template>+ <div class="flex w-[240px] flex-col gap-2 rounded-lg border border-border bg-panel p-3">+ <div class="flex items-center justify-between text-xs text-surface">+ Components+ <AppPicker+ heading="Add instances"+ :items="components"+ search-placeholder="Search components"+ empty-label="No components found"+ close-label="Close"+ @select="chosen = $event"+ >+ <template #trigger>+ <IconButton label="Add instances"><IconPlus class="size-3.5" /></IconButton>+ </template>+ <template #leading><IconComponent class="size-3.5" /></template>+ </AppPicker>+ </div>+ <div class="flex items-center justify-between text-xs text-surface">+ Variables+ <AppPicker+ heading="Apply variable"+ :items="variables"+ density="compact"+ search-placeholder="Search variables"+ empty-label="No variables found"+ close-label="Close"+ @select="chosen = $event"+ >+ <template #trigger>+ <IconButton label="Apply variable"><IconDiamond class="size-3.5" /></IconButton>+ </template>+ <template #leading><IconDiamond class="size-3.5 text-component" /></template>+ <template #footer="{ close }">+ <AppButton class="w-full justify-start" @click="close()">+ <IconPlus class="size-3.5" /> Create number variable+ </AppButton>+ </template>+ </AppPicker>+ </div>+ <p class="text-[11px] text-muted">Chosen: {{ chosen || '—' }}</p>+ </div>+</template>diff --git a/src/components/ui/select/select.ts b/src/components/ui/select/select.tsindex 0dbe6ec7d..5388be8b6 100644--- a/src/components/ui/select/select.ts+++ b/src/components/ui/select/select.ts@@ -4,8 +4,6 @@ import type { ComponentUI } from '@/components/ui/types'import theme from '@/theme/select/select'export interface SelectContentVariants {- radius?: keyof typeof theme.variants.radius- elevation?: keyof typeof theme.variants.elevationpadding?: keyof typeof theme.variants.padding}diff --git a/src/theme/binding/field.ts b/src/theme/binding/field.tsindex 11c4c3ae2..2211abe62 100644--- a/src/theme/binding/field.ts+++ b/src/theme/binding/field.ts@@ -5,18 +5,6 @@ const bindingFieldTheme = {pillLabel: 'min-w-0 flex-1 truncate text-[11px] font-medium',trigger:'flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border border-transparent bg-transparent text-muted outline-none transition-colors hover:text-surface focus-visible:border-panel-focus data-[open]:bg-hover data-[open]:text-component disabled:opacity-0 data-[disabled]:opacity-0',- pickerContent:- 'z-[100] w-56 overflow-hidden rounded-lg border border-border bg-panel text-surface shadow-xl',- pickerSearch:- 'h-6 w-full border-0 border-b border-border bg-transparent px-2 text-[11px] text-surface outline-none placeholder:text-muted focus:border-panel-focus',- pickerViewport: 'max-h-48 overflow-y-auto p-1',- pickerItem:- 'flex h-6 cursor-pointer items-center gap-2 rounded px-2 text-[11px] text-surface outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[highlighted]:bg-hover',- pickerItemIcon: 'size-3 shrink-0 text-component',- pickerItemLabel: 'min-w-0 flex-1 truncate',- pickerItemIndicator: 'flex size-3 shrink-0 items-center justify-center text-component',- pickerEmpty: 'px-2 py-3 text-center text-[11px] text-muted',- pickerFooter: 'border-t border-border p-1',createForm: 'flex items-center gap-1.5 p-1',createInput:'h-6 min-w-0 flex-1 rounded border border-transparent bg-panel-field px-2 text-[11px] text-surface outline-none placeholder:text-muted focus:border-panel-focus'diff --git a/src/theme/chat/history.ts b/src/theme/chat/history.tsindex 006e68078..52dd55041 100644--- a/src/theme/chat/history.ts+++ b/src/theme/chat/history.ts@@ -1,5 +1,8 @@import { tv } from 'tailwind-variants'+import { motionStyles } from '@/theme/motion/styles'+import { floatingSurface } from '@/theme/overlay'+export const chatHistoryTheme = tv({slots: {root: 'shrink-0 border-b border-border',@@ -8,8 +11,7 @@ export const chatHistoryTheme = tv({'flex min-w-0 flex-1 items-center gap-1 rounded px-1.5 py-1 text-left text-xs text-surface hover:bg-hover disabled:opacity-50',title: 'min-w-0 flex-1 truncate',icon: 'size-3.5 shrink-0',- content:- 'z-50 w-80 max-w-[calc(100vw-1rem)] rounded-lg border border-border bg-panel p-2 text-surface shadow-lg',+ content: ['z-50 w-80 max-w-[calc(100vw-1rem)] p-2', floatingSurface, motionStyles.floating],input:'w-full rounded border border-border bg-input px-2 py-1.5 text-xs outline-none focus:border-accent',scope: 'my-2 flex gap-1',diff --git a/src/theme/collaboration/presence-avatars.ts b/src/theme/collaboration/presence-avatars.tsindex 60df7dc44..b15fb8ce6 100644--- a/src/theme/collaboration/presence-avatars.ts+++ b/src/theme/collaboration/presence-avatars.ts@@ -1,5 +1,8 @@import { tv } from 'tailwind-variants'+import { motionStyles } from '@/theme/motion/styles'+import { floatingSurface } from '@/theme/overlay'+/** The avatar stack in the toolbar: you, collaborators with their agent counts, then "+N". */export const presenceAvatars = tv({slots: {@@ -13,7 +16,7 @@ export const presenceAvatars = tv({live: 'absolute -top-0.5 -right-0.5 size-2 rounded-full border border-panel bg-[var(--color-success-bg)]',overflow:'relative flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full border-2 border-panel bg-hover text-[9px] font-semibold text-surface outline-none focus-visible:ring-2 focus-visible:ring-accent',- card: 'z-50 w-60 rounded-xl bg-panel p-2 shadow-[0_8px_30px_rgb(0_0_0/0.4)]',+ card: ['z-50 w-60 p-2', floatingSurface, motionStyles.floating],leave: 'mt-2 w-full'}})diff --git a/src/theme/design-check.ts b/src/theme/design-check.tsindex 4c9cf4e48..3442b623f 100644--- a/src/theme/design-check.ts+++ b/src/theme/design-check.ts@@ -1,5 +1,8 @@import { tv } from 'tailwind-variants'+import { motionStyles } from '@/theme/motion/styles'+import { floatingSurface } from '@/theme/overlay'+export const designCheck = tv({slots: {root: 'flex min-h-0 flex-1 flex-col',@@ -39,17 +42,6 @@ export const designCheck = tv({}})-export const severityIcon = tv({- base: 'size-3 shrink-0',- variants: {- severity: {- error: 'text-issue-error',- warning: 'text-issue-warning',- info: 'text-issue-info'- }- }-})-/** The Layers panel mark: a severity icon on a layer, a dot on a collapsed layer holding issues. */export const layerIssueMark = tv({slots: {@@ -78,8 +70,11 @@ export const pageIssueBadge = tv({export const issueTooltip = tv({slots: {- content:- 'pointer-events-none z-50 w-64 rounded-lg bg-panel py-1.5 text-[11px] text-surface shadow-[0_0_0_1px_var(--color-border),0_8px_30px_rgb(0_0_0/0.35)]',+ content: [+ 'pointer-events-none z-50 w-64 py-1.5 text-[11px]',+ floatingSurface,+ motionStyles.popup+ ],header: 'flex items-center gap-1.5 px-2.5 pt-0.5 pb-1 font-semibold',headerIcon: 'size-3 shrink-0 text-muted',headerText: 'min-w-0 truncate',diff --git a/src/theme/feedback/severity.ts b/src/theme/feedback/severity.tsnew file mode 100644index 000000000..3d5251deb--- /dev/null+++ b/src/theme/feedback/severity.ts@@ -0,0 +1,13 @@+import { tv } from 'tailwind-variants'++/** The icon colour of a problem's severity, shared by the design check and property limits. */+export const severityIcon = tv({+ base: 'size-3 shrink-0',+ variants: {+ severity: {+ error: 'text-issue-error',+ warning: 'text-issue-warning',+ info: 'text-issue-info'+ }+ }+})diff --git a/src/theme/layer-tree.ts b/src/theme/layer-tree.tsindex 61ff1e515..bb254d6f4 100644--- a/src/theme/layer-tree.ts+++ b/src/theme/layer-tree.ts@@ -38,6 +38,10 @@ const layerTreeTheme = {true: { icon: 'text-component opacity-100' },false: { icon: 'opacity-70' }},+ slot: {+ true: { icon: 'text-slot opacity-100', label: 'text-slot' },+ false: {}+ },expanded: {true: { disclosure: 'rotate-90' },false: { disclosure: 'rotate-0' }@@ -86,6 +90,7 @@ const layerTreeTheme = {dragging: false,visible: true,component: false,+ slot: false,expanded: false,actionsVisible: true,actionActive: false,diff --git a/src/theme/mobile/presence-popover.ts b/src/theme/mobile/presence-popover.tsindex 4ce27df5f..d4b32093b 100644--- a/src/theme/mobile/presence-popover.ts+++ b/src/theme/mobile/presence-popover.ts@@ -1,9 +1,12 @@import { tv } from 'tailwind-variants'+import { motionStyles } from '@/theme/motion/styles'+import { floatingSurface } from '@/theme/overlay'+export const presencePopover = tv({slots: {dot: 'size-2 rounded-full bg-green-500',- content: 'z-50 w-56 rounded-xl bg-panel p-3 shadow-[0_8px_30px_rgb(0_0_0/0.4)]',+ content: ['z-50 w-56 p-3', floatingSurface, motionStyles.floating],peerRow:'flex cursor-pointer items-center gap-2 rounded-md px-0.5 py-0.5 outline-none select-none active:bg-hover focus-visible:ring-1 focus-visible:ring-accent'}diff --git a/src/theme/motion/styles.ts b/src/theme/motion/styles.tsindex 9853b1b1c..74c3e5b86 100644--- a/src/theme/motion/styles.ts+++ b/src/theme/motion/styles.ts@@ -2,6 +2,12 @@ export const motionStyles = {overlay:'data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:duration-180 data-[state=open]:ease-out data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:duration-120 data-[state=closed]:ease-in motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none',popup: 'animate-in fade-in zoom-in-95 motion-reduce:animate-none',+ /**+ * Popovers, menus, selects, and pickers grow in from the side they open on and close at once:+ * a fading-out modal menu would still block the canvas and shortcuts until it unmounts.+ */+ floating:+ 'animate-in fade-in-0 zoom-in-95 duration-150 ease-out data-[side=bottom]:slide-in-from-top-1 data-[side=top]:slide-in-from-bottom-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 motion-reduce:animate-none',spinner: 'animate-spin motion-reduce:animate-none',pulse: 'animate-pulse motion-reduce:animate-none'} as constdiff --git a/src/theme/overlay.ts b/src/theme/overlay.tsnew file mode 100644index 000000000..d73035d89--- /dev/null+++ b/src/theme/overlay.ts@@ -0,0 +1,10 @@+/**+ * The surface of everything that floats above the editor: popovers, menus, lists, pickers,+ * and cards. The ring, unlike a border, outlines it in both themes without changing its size.+ */+export const floatingSurface =+ 'rounded-xl bg-panel text-surface shadow-[0_0_0_1px_var(--color-border),0_8px_30px_rgb(0_0_0/0.4)]'++/** A one-line tooltip: the same edge and shadow on a compact shape. */+export const tooltipSurface =+ 'rounded-md bg-panel text-surface shadow-[0_0_0_1px_var(--color-border),0_8px_30px_rgb(0_0_0/0.4)]'diff --git a/src/theme/select/combobox.ts b/src/theme/select/combobox.tsindex 94f47e9e9..8347bbc82 100644--- a/src/theme/select/combobox.ts+++ b/src/theme/select/combobox.ts@@ -1,3 +1,5 @@+import { motionStyles } from '../motion/styles'+import { floatingSurface } from '../overlay'import { panelFieldBase } from '../panel/field'const appComboboxTheme = {@@ -8,8 +10,11 @@ const appComboboxTheme = {],value: 'min-w-0 flex-1 truncate text-left text-[11px] text-surface',chevron: 'ml-1 size-3 shrink-0 text-muted',- content:- 'z-[110] max-h-72 min-w-[var(--reka-combobox-trigger-width)] overflow-hidden rounded-md bg-panel text-[11px] shadow-[0_8px_30px_rgb(0_0_0/0.4)]',+ content: [+ 'z-[110] max-h-72 min-w-[var(--reka-combobox-trigger-width)] overflow-hidden text-[11px]',+ floatingSurface,+ motionStyles.floating+ ],search: 'relative m-1 flex h-7 items-center rounded-md border border-border bg-input',input:'h-full min-w-0 flex-1 bg-transparent pr-2 pl-7 text-[11px] text-surface outline-none placeholder:text-muted',diff --git a/src/theme/select/grouped.ts b/src/theme/select/grouped.tsindex 3d2e95b1b..0ed21dcd4 100644--- a/src/theme/select/grouped.ts+++ b/src/theme/select/grouped.ts@@ -11,8 +11,6 @@ const appGroupedSelectTheme = {},variants: selectTheme.variants,defaultVariants: {- radius: 'lg' as const,- elevation: 'lg' as const,padding: 'md' as const}}diff --git a/src/theme/select/picker.ts b/src/theme/select/picker.tsnew file mode 100644index 000000000..2adf53a53--- /dev/null+++ b/src/theme/select/picker.ts@@ -0,0 +1,43 @@+import { motionStyles } from '../motion/styles'+import { floatingSurface } from '../overlay'+import { panelFieldBase } from '../panel/field'++/** A searchable list of choices that opens beside the properties panel, as Figma's pickers do. */+const appPickerTheme = {+ slots: {+ content: [+ 'z-[100] flex max-h-96 w-64 max-w-[calc(100vw-1rem)] flex-col overflow-hidden',+ floatingSurface,+ motionStyles.floating+ ],+ header: 'flex items-center gap-1.5 border-b border-border px-3 py-2',+ title: 'text-xs font-semibold text-surface',+ search: [panelFieldBase, 'relative m-2 flex h-7 shrink-0 items-center'],+ searchIcon: 'pointer-events-none absolute left-2 size-3.5 text-muted',+ input:+ 'h-full min-w-0 flex-1 bg-transparent pr-2 pl-7 text-xs text-surface outline-none placeholder:text-muted',+ list: 'flex min-h-0 flex-col gap-2 overflow-y-auto px-2 pb-2',+ groupLabel: 'px-1 pb-1 text-[10px] font-medium tracking-wide text-muted uppercase',+ item: 'flex w-full cursor-pointer items-center gap-2 rounded px-1 py-1 text-left outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[highlighted]:bg-hover',+ leading:+ 'flex size-8 shrink-0 items-center justify-center overflow-hidden rounded border border-border bg-panel-secondary text-muted',+ text: 'min-w-0 flex-1',+ label: 'block truncate text-xs text-surface',+ description: 'block truncate text-[10px] text-muted',+ check: 'size-3 shrink-0 text-accent',+ empty: 'px-1 py-2 text-[11px] text-muted',+ footer: 'border-t border-border p-1'+ },+ variants: {+ density: {+ /** One line per choice, for plain names such as variables or styles. */+ compact: { leading: 'size-5 border-0 bg-transparent', item: 'min-h-7' },+ /** A thumbnail and a description line, for components and assets. */+ comfortable: {}+ }+ },+ defaultVariants: { density: 'comfortable' as const }+}++export type AppPickerTheme = typeof appPickerTheme+export default appPickerThemediff --git a/src/theme/select/select.ts b/src/theme/select/select.tsindex f35a997d3..bf88156d4 100644--- a/src/theme/select/select.ts+++ b/src/theme/select/select.ts@@ -1,23 +1,20 @@+import { motionStyles } from '../motion/styles'+import { floatingSurface } from '../overlay'import { panelFieldBase } from '../panel/field'export default {slots: {trigger: [panelFieldBase, 'flex items-center justify-between text-[11px]'],value: 'min-w-0 flex-1 truncate text-left',- content:- 'z-[110] min-w-[var(--reka-select-trigger-width)] overflow-hidden rounded-xl bg-panel text-[11px] shadow-[0_8px_30px_rgb(0_0_0/0.4)]',+ content: [+ 'z-[110] min-w-[var(--reka-select-trigger-width)] overflow-hidden text-[11px]',+ floatingSurface,+ motionStyles.floating+ ],viewport: '',item: 'relative flex h-6 cursor-pointer items-center text-surface outline-none select-none data-[disabled]:pointer-events-none data-[highlighted]:bg-hover data-[disabled]:opacity-50'},variants: {- radius: {- md: { content: 'rounded-md' },- lg: { content: 'rounded-xl' }- },- elevation: {- lg: { content: 'shadow-[0_8px_30px_rgb(0_0_0/0.4)]' },- xl: { content: 'shadow-[0_8px_30px_rgb(0_0_0/0.4)]' }- },padding: {none: { content: '' },sm: { content: 'p-0.5' },@@ -25,8 +22,6 @@ export default {}},defaultVariants: {- radius: 'md' as const,- elevation: 'lg' as const,padding: 'sm' as const}}diff --git a/tests/e2e/canvas/slot-overlays.spec.ts b/tests/e2e/canvas/slot-overlays.spec.tsnew file mode 100644index 000000000..33abbe371--- /dev/null+++ b/tests/e2e/canvas/slot-overlays.spec.ts@@ -0,0 +1,84 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'++const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')++async function expectCanvas(name: string) {+ editor.canvas.assertNoErrors()+ const buffer = await editor.canvas.screenshotCanvasRegion()+ expect(buffer).toMatchSnapshot(`${name}.png`, { maxDiffPixelRatio: 0, threshold: 0 })+}++/** A card with a filled Body slot and an empty Footer slot; returns its instance. */+async function createSlottedCard(): Promise<string> {+ return editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const graph = store.graph+ const pageId = store.state.currentPageId+ const white = [+ { type: 'SOLID' as const, color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }+ ]+ const card = graph.createNode('COMPONENT', pageId, {+ name: 'Card',+ x: 120,+ y: 120,+ width: 260,+ height: 220,+ fills: white,+ layoutMode: 'VERTICAL',+ itemSpacing: 12,+ paddingLeft: 16,+ paddingRight: 16,+ paddingTop: 16,+ paddingBottom: 16,+ componentPropertyDefinitions: [+ { id: 'card:body', name: 'Body', type: 'SLOT', defaultValue: '' },+ { id: 'card:footer', name: 'Footer', type: 'SLOT', defaultValue: '' }+ ]+ })+ const slot = (name: string, propertyId: string, height: number) =>+ graph.createNode('FRAME', card.id, {+ name,+ width: 228,+ height,+ layoutAlignSelf: 'STRETCH',+ fills: [],+ componentPropertyReferences: [{ propertyId, field: 'SLOT_CONTENT' }]+ })+ const body = slot('Body', 'card:body', 96)+ graph.createNode('RECTANGLE', body.id, {+ name: 'Placeholder',+ width: 120,+ height: 48,+ fills: [+ { type: 'SOLID', color: { r: 0.85, g: 0.88, b: 0.93, a: 1 }, visible: true, opacity: 1 }+ ]+ })+ slot('Footer', 'card:footer', 64)+ const instance = graph.createInstance(card.id, pageId, { x: 440, y: 120 })+ if (!instance) throw new Error('Instance not created')+ store.select([instance.id])+ store.requestRender()+ return instance.id+ })+}++test('selected instance outlines its slots and tints empty ones', async () => {+ await createSlottedCard()+ await editor.canvas.waitForRender()+ await expectCanvas('slot-outlines-instance-selected')+})++test('selected slot frame and its hovered content render in slot pink', async () => {+ const instanceId = await createSlottedCard()+ await editor.page.evaluate((id) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const [body] = store.graph.getChildren(id)+ store.select([body.id])+ store.state.hoveredNodeId = store.graph.getChildren(body.id)[0]?.id ?? null+ store.requestRender()+ }, instanceId)+ await editor.canvas.waitForRender()+ await expectCanvas('slot-frame-selected')+})diff --git a/tests/e2e/canvas/slot-overlays.spec.ts-snapshots/slot-frame-selected-openpencil-darwin.png b/tests/e2e/canvas/slot-overlays.spec.ts-snapshots/slot-frame-selected-openpencil-darwin.pngnew file mode 100644index 000000000..9a0c0fddbBinary files /dev/null and b/tests/e2e/canvas/slot-overlays.spec.ts-snapshots/slot-frame-selected-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/slot-overlays.spec.ts-snapshots/slot-outlines-instance-selected-openpencil-darwin.png b/tests/e2e/canvas/slot-overlays.spec.ts-snapshots/slot-outlines-instance-selected-openpencil-darwin.pngnew file mode 100644index 000000000..71764e6d0Binary files /dev/null and b/tests/e2e/canvas/slot-overlays.spec.ts-snapshots/slot-outlines-instance-selected-openpencil-darwin.png differdiff --git a/tests/e2e/components.spec.ts b/tests/e2e/components.spec.tsindex 6626561dc..d758664aa 100644--- a/tests/e2e/components.spec.ts+++ b/tests/e2e/components.spec.ts@@ -105,12 +105,12 @@ test('instance shows INSTANCE type in design panel', async () => {await expect(editor.page.getByRole('img', { name: 'INSTANCE' })).toBeVisible()})-test('instance has "Go to Main Component" button', async () => {- await expect(editor.page.getByRole('button', { name: 'Go to Main Component' })).toBeVisible()+test('instance has "Go to main component" button', async () => {+ await expect(editor.page.getByRole('button', { name: 'Go to main component' })).toBeVisible()})test('instance has "Detach" button', async () => {- await expect(editor.page.getByRole('button', { name: 'Detach Instance' })).toBeVisible()+ await expect(editor.page.getByRole('button', { name: 'Detach instance' })).toBeVisible()})test('modifying component propagates to instance', async () => {diff --git a/tests/e2e/components/variant-authoring.spec.ts b/tests/e2e/components/variant-authoring.spec.tsindex a561cea77..5716f7ba8 100644--- a/tests/e2e/components/variant-authoring.spec.ts+++ b/tests/e2e/components/variant-authoring.spec.ts@@ -66,9 +66,13 @@ test('authors multiple variant dimensions and reports duplicate combinations', aawait propertyRows.nth(1).getByRole('textbox', { name: 'Property name' }).blur()await canvas.waitForRender()- await section.getByRole('textbox', { name: 'Property name' }).last().fill('State')- await section.getByRole('textbox', { name: 'Initial value' }).fill('Enabled')+ // The header + adds Property 1 with the value Default and selects its name for typing.await section.getByRole('button', { name: 'Add variant property' }).click()+ const added = propertyRows.nth(2).getByRole('textbox', { name: 'Property name' })+ await expect(added).toHaveValue('Property 1')+ await expect(added).toBeFocused()+ await page.keyboard.type('State')+ await added.blur()await canvas.waitForRender()const definitions = await page.evaluate((componentSetId) => {@@ -88,7 +92,7 @@ test('authors multiple variant dimensions and reports duplicate combinations', aconst variantSection = propertySection(page, 'Variants')await expect(variantSection.getByRole('textbox', { name: 'Type' })).toHaveValue('Primary')await expect(variantSection.getByRole('textbox', { name: 'Size' })).toHaveValue('Large')- await expect(variantSection.getByRole('textbox', { name: 'State' })).toHaveValue('Enabled')+ await expect(variantSection.getByRole('textbox', { name: 'State' })).toHaveValue('Default')await variantSection.getByRole('textbox', { name: 'Size' }).fill('Small')await variantSection.getByRole('textbox', { name: 'Size' }).blur()await expect(variantSection.getByRole('alert')).toContainText('Duplicate variant values')@@ -103,9 +107,9 @@ test('authors multiple variant dimensions and reports duplicate combinations', a: null}, ids.primaryLargeId)expect(state).toEqual({- name: 'Type=Primary, Size=Large, State=Enabled',- values: { Type: 'Primary', Size: 'Large', State: 'Enabled' },- undoLabel: 'Add property'+ name: 'Type=Primary, Size=Large, State=Default',+ values: { Type: 'Primary', Size: 'Large', State: 'Default' },+ undoLabel: 'Rename property'})await variantSection.getByRole('textbox', { name: 'Size' }).fill('Medium')diff --git a/tests/e2e/context-menu/basic.spec.ts b/tests/e2e/context-menu/basic.spec.tsindex 83d588b85..8e5b0e078 100644--- a/tests/e2e/context-menu/basic.spec.ts+++ b/tests/e2e/context-menu/basic.spec.ts@@ -34,6 +34,12 @@ function contextMenu() {return editor.page.locator('[role="menu"]')}+/** Close the menu and wait until it is gone, so the next test's keys reach the canvas. */+async function closeMenu() {+ await editor.page.keyboard.press('Escape')+ await expect(contextMenu()).toHaveCount(0)+}+function contextItem(testId: string) {return editor.page.getByTestId(testId)}@@ -46,7 +52,7 @@ test('right-click on empty canvas shows context menu without selection items disconst copyItem = contextItem('context-copy')await expect(copyItem).toBeVisible()- await editor.page.keyboard.press('Escape')+ await closeMenu()})test('draw shape and right-click selects it', async () => {@@ -54,7 +60,7 @@ test('draw shape and right-click selects it', async () => {await editor.canvas.waitForRender()// Deselect first- await editor.page.keyboard.press('Escape')+ await closeMenu()await editor.canvas.waitForRender()// Right-click the shape@@ -62,7 +68,7 @@ test('draw shape and right-click selects it', async () => {expect(await getSelectedCount()).toBe(1)await expect(contextMenu()).toBeVisible()- await editor.page.keyboard.press('Escape')+ await closeMenu()})test('context menu shows expected items', async () => {@@ -84,7 +90,7 @@ test('context menu shows expected items', async () => {await expect(contextItem('context-outline-stroke')).toBeVisible()await expect(contextItem('context-boolean-union')).toHaveCount(0)- await editor.page.keyboard.press('Escape')+ await closeMenu()})test('duplicate via context menu works', async () => {@@ -225,7 +231,7 @@ test('outline stroke is disabled for fill-only shapes', async () => {const item = contextItem('context-outline-stroke')await expect(item).toBeVisible()await expect(item).toHaveAttribute('data-disabled', '')- await editor.page.keyboard.press('Escape')+ await closeMenu()})test('Copy/Paste as submenu exists', async () => {@@ -242,5 +248,5 @@ test('Copy/Paste as submenu exists', async () => {await expect(contextItem('context-copy-as-svg')).toBeVisible()await expect(contextItem('context-copy-as-jsx')).toBeVisible()- await editor.page.keyboard.press('Escape')+ await closeMenu()})diff --git a/tests/e2e/keyboard/shortcuts.spec.ts b/tests/e2e/keyboard/shortcuts.spec.tsindex 34742d7bf..015227a65 100644--- a/tests/e2e/keyboard/shortcuts.spec.ts+++ b/tests/e2e/keyboard/shortcuts.spec.ts@@ -157,6 +157,8 @@ test.describe('selection shortcuts', () => {await expect(dialog).toBeVisible()await dialog.getByLabel('Rename to').fill('Layer $n')await dialog.getByRole('button', { name: 'Rename', exact: true }).click()+ // The next test's keys must reach the canvas, not the closing dialog.+ await expect(dialog).toBeHidden()const renamed = (await getPageChildren()).filter((node) => ids.includes(node.id))expect(renamed.map((node) => node.name)).toEqual(['Layer 1', 'Layer 2'])})diff --git a/tests/e2e/properties/component-properties.spec.ts-snapshots/component-properties-controls-openpencil-darwin.png b/tests/e2e/properties/component-properties.spec.ts-snapshots/component-properties-controls-openpencil-darwin.pngindex 02fc14159..3afd57f52 100644Binary files a/tests/e2e/properties/component-properties.spec.ts-snapshots/component-properties-controls-openpencil-darwin.png and b/tests/e2e/properties/component-properties.spec.ts-snapshots/component-properties-controls-openpencil-darwin.png differdiff --git a/tests/e2e/properties/panel.spec.ts b/tests/e2e/properties/panel.spec.tsindex 0df47c5f9..8b71d86b0 100644--- a/tests/e2e/properties/panel.spec.ts+++ b/tests/e2e/properties/panel.spec.ts@@ -41,34 +41,29 @@ test('appearance fields share control height and show variable actions', async (await applyVariable.hover()await expect(applyVariable).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)')+ // The shared picker opens beside the panel, to the left of its trigger, like Figma's.await applyVariable.click()- const search = editor.page.locator('input[data-slot="search"]')- const picker = editor.page.locator('[data-slot=content]').filter({ has: search })+ const picker = editor.page.getByRole('dialog', { name: 'Apply variable' })await expect(picker).toBeVisible()+ await expect(picker).toHaveAttribute('data-side', 'left')const triggerBox = expectDefined(await applyVariable.boundingBox(), 'variable trigger bounds')const pickerBox = expectDefined(await picker.boundingBox(), 'variable picker bounds')- await expect(picker).toHaveAttribute('data-side', 'bottom')- expect(pickerBox.y).toBeGreaterThanOrEqual(triggerBox.y + triggerBox.height)- expect(Math.abs(pickerBox.x + pickerBox.width - (triggerBox.x + triggerBox.width))).toBeLessThan(- 4- )- await search.press('Escape')+ expect(pickerBox.x + pickerBox.width).toBeLessThanOrEqual(triggerBox.x)+ await editor.page.keyboard.press('Escape')+ await expect(picker).toBeHidden()- // Move the anchor near the bottom without changing its actual panel layout.+ // Near the bottom of the window it shifts up to stay fully visible.const viewport = editor.page.viewportSize()if (!viewport) throw new Error('Viewport unavailable')- await editor.page.setViewportSize({- width: viewport.width,- height: Math.ceil(triggerBox.y + triggerBox.height + 24)- })+ const height = Math.ceil(triggerBox.y + triggerBox.height + 24)+ await editor.page.setViewportSize({ width: viewport.width, height })try {await applyVariable.click()- await expect(picker).toHaveAttribute('data-side', 'top')- const flipped = expectDefined(await picker.boundingBox(), 'flipped picker bounds')- const anchor = expectDefined(await applyVariable.boundingBox(), 'edge trigger bounds')- expect(flipped.y).toBeGreaterThanOrEqual(8)- expect(flipped.y + flipped.height).toBeLessThanOrEqual(anchor.y)- await search.press('Escape')+ await expect(picker).toBeVisible()+ const shifted = expectDefined(await picker.boundingBox(), 'shifted picker bounds')+ expect(shifted.y).toBeGreaterThanOrEqual(0)+ expect(shifted.y + shifted.height).toBeLessThanOrEqual(height)+ await editor.page.keyboard.press('Escape')} finally {await editor.page.setViewportSize(viewport)}diff --git a/tests/e2e/properties/stroke-geometry.spec.ts b/tests/e2e/properties/stroke-geometry.spec.tsindex 80d4533cc..e43249e68 100644--- a/tests/e2e/properties/stroke-geometry.spec.ts+++ b/tests/e2e/properties/stroke-geometry.spec.ts@@ -81,6 +81,8 @@ test('updates cap, join, and miter state from compact controls', async () => {])await page.keyboard.press('Escape')+ // Undo goes to the canvas only once the settings popover is gone.+ await expect(page.getByRole('dialog', { name: 'Stroke settings' })).toHaveCount(0)await canvas.pressKey('Meta+z')await canvas.waitForRender()expect((await selectedStrokeGeometry())[0]?.miterLimit).toBe(4)@@ -103,6 +105,8 @@ test('applies mixed multi-selection joins in one undo step', async () => {expect((await selectedStrokeGeometry()).map((value) => value?.join)).toEqual(['ROUND', 'ROUND'])await page.keyboard.press('Escape')+ // Undo goes to the canvas only once the settings popover is gone.+ await expect(page.getByRole('dialog', { name: 'Stroke settings' })).toHaveCount(0)await canvas.pressKey('Meta+z')await canvas.waitForRender()expect((await selectedStrokeGeometry()).map((value) => value?.join)).toEqual(['MITER', 'MITER'])diff --git a/tests/engine/vue/controls/component-properties.test.ts b/tests/engine/vue/controls/component-properties.test.tsindex d7e1bc905..27c75a06e 100644--- a/tests/engine/vue/controls/component-properties.test.ts+++ b/tests/engine/vue/controls/component-properties.test.ts@@ -49,8 +49,8 @@ describe('component property control model', () => {'missing-id')).toEqual([- { value: preferred.id, label: 'Preferred' },- { value: secondary.id, label: 'Secondary' },+ { value: preferred.id, label: 'Preferred', preferred: true },+ { value: secondary.id, label: 'Secondary', preferred: false },{ value: 'missing-id', label: 'missing-id', missing: true }])})diff --git a/tests/engine/vue/editor/menu-model/canvas.test.ts b/tests/engine/vue/editor/menu-model/canvas.test.tsindex c4cbc9f96..c4d39ec05 100644--- a/tests/engine/vue/editor/menu-model/canvas.test.ts+++ b/tests/engine/vue/editor/menu-model/canvas.test.ts@@ -14,6 +14,7 @@ function selection(overrides: Partial<CanvasMenuOptions['selection']> = {}) {isComponent: ref(false),isInstance: ref(false),canCreateComponentSet: ref(false),+ canCreateSlot: ref(false),...overrides} as CanvasMenuOptions['selection']}@@ -74,6 +75,16 @@ describe('buildCanvasContextMenu', () => {).toContain('selection.detachInstance')})+ test('offers Create slot for layers of a main component', () => {+ const ids = itemIds(+ buildCanvasContextMenu(+ options({ selection: selection({ canCreateSlot: computed(() => true) }) })+ )+ )+ expect(ids).toContain('selection.createSlot')+ expect(itemIds(buildCanvasContextMenu(options()))).not.toContain('selection.createSlot')+ })+test('does not emit empty leading or repeated separators', () => {const ids = itemIds(buildCanvasContextMenu(options({ otherPages: [] })))expect(ids[0]).not.toBe('---')diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex 21c9e76b4..93daa39d7 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -40,6 +40,7 @@ de:panels.positionde:panels.radialGradientde:panels.radiusde:panels.textCaseOriginal+de:panels.slotsde:settings.mcpde:storage.bucketde:storage.providerAmazonS3@@ -75,6 +76,7 @@ es:panels.localLibrarieses:panels.radialGradientes:panels.textCaseOriginales:panels.variables+es:panels.slotses:rendering.experimentales:settings.generales:settings.mcp@@ -133,6 +135,8 @@ fr:panels.radialGradientfr:panels.rotationfr:panels.saturationfr:panels.variables+fr:panels.slots+fr:panels.slotDescriptionfr:settings.animationsfr:settings.diagnosticsfr:settings.mcp