AI-native design editor. Open-source Figma alternative.
feat(canvas): match Figma when renaming names, selecting nested layers, and pasting (#1012)
Danila Poyarkov1525583813ef
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6bef5333f..aa300605a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -91,6 +91,7 @@### Changed+- Layers inside components and instances are outlined in purple when hovered or selected, with a purple size label, as in Figma; they were blue.- The properties panel's variable picker groups variables by collection and shows each color variable's swatch, and the variables dialog points a value at another variable with the same picker, detaching it from the picker's footer.- **Add variant** on a component set copies its last variant below it, 20 px apart, with the next free value such as `Variant3`, and grows the set to hold it, as Figma does. It used to place a copy with the same values to the right, which made a duplicate combination.- The `get_selection` tool returns the selected layers with their direct children by default instead of their whole subtrees, and takes a `depth` for more or fewer levels, so agents can start from what the user selected without reading the full tree.@@ -115,8 +116,8 @@- `createInstance()` and `detachInstance()` in the plugin API return the node type they built, so reading `componentProperties`, `setProperties`, or `isExposedInstance` from a new instance no longer needs a cast; `FigmaInstanceNode` is exported alongside the other node types.- Name the tool and list every invalid argument with where it is when AI chat, the CLI, or WebMCP calls a tool wrongly, as MCP clients already saw, as in `Invalid arguments for create_shape:` followed by `× Invalid type: Expected ("FRAME" | …) but received "CIRCLE"` and `→ at type`. Design JSX component properties and gradient stops report their problems the same way. Previously only the first problem was named, without the tool or the argument.- HTML and Tailwind JSX export write variable-bound colors, spacing, radii, borders, sizes, type sizes, and opacity as the tokens they come from, such as `var(--color-primary)` or `bg-primary`, and put layers set to another mode in it with an attribute such as `data-theme="dark"`. Values CSS would not resolve as the canvas draws them stay literal, and standalone HTML includes the stylesheet for the tokens it uses.-- Clicking selects layers as in Figma: inside a top-level frame or section, a click selects the frame's direct child rather than the deepest layer, the empty part of a top-level frame or section that holds layers selects nothing, while the gaps and padding of a top-level auto layout frame select, highlight, and drag it, and a frame inside a top-level frame, or an empty frame, is selected by its empty area even without a fill, which ⌘-click looks through, so every top-level frame shows its name above it, in the selection color while selected or hovered, and clicking or dragging the name selects or moves the frame; once a layer is selected, clicks reach its siblings and cousins. Double-click goes one level deeper, as does another click inside a selected frame, component, or instance, so repeated clicks at one point reach the layer under it; ⌘-click (Ctrl-click on Windows and Linux) selects the deepest layer. A marquee started inside a top-level frame or section selects that container's layers, and from the page it selects a frame or section that holds layers only when fully enclosed.-- Drag, draw, duplicate, and paste follow Figma. A dragged layer lands in the frame under the cursor and leaves its frame as soon as the cursor does; groups and locked frames never take a drop, a component set takes back only its own variants, and a layer inside a group stays in it unless dropped on another frame. Groups and booleans fit their children after a move or nudge, and a group whose last layer leaves is removed. Pressing inside a selected frame, group, or component set drags it rather than the layer under the cursor, and an auto layout child dragged out lands where you drop it. Hold Space while dragging to keep layers in their parents, Shift to move along one axis, or Control to drop into auto layout as an absolute-positioned layer. Locked layers stay put when the rest of the selection moves. Shapes drawn inside a frame, auto layout, or slot go into it, a frame drawn over layers takes in the ones it fully covers, and a section does so when moved or resized too. Wrapped auto layout inserts on the line under the cursor. Duplicates keep their names, and duplicating a main component with ⌘D or Alt-drag creates an instance. ⌘D duplicates in place, placing a lone top-level frame's copy to its right, and ⌘V keeps the copied position, centering an axis that doesn't fit the selected frame; **Paste here** still pastes at the cursor.+- Clicking selects layers as in Figma: inside a top-level frame or section, a click selects the frame's direct child rather than the deepest layer, the empty part of a top-level frame or section that holds layers selects nothing, while the gaps and padding of a top-level auto layout frame select, highlight, and drag it, and a frame inside a top-level frame, or an empty frame, is selected by its empty area even without a fill, which ⌘-click looks through, so every top-level frame shows its name above it, in the selection color while selected or hovered, and clicking or dragging the name selects or moves the frame; once a layer is selected, clicks reach its siblings and cousins. Double-click goes one level deeper, as does another click inside a selected frame, component, or instance, so repeated clicks at one point reach the layer under it; ⌘-click (Ctrl-click on Windows and Linux) selects the deepest layer, which holding ⌘ highlights. Double-clicking a frame's or component's name renames it in place. A layer is never selected together with its own parent or child: Shift-clicking one replaces the other. A marquee started inside a top-level frame or section selects that container's layers, and from the page it selects a frame or section that holds layers only when fully enclosed.+- Drag, draw, duplicate, and paste follow Figma. A dragged layer lands in the frame under the cursor and leaves its frame as soon as the cursor does; groups and locked frames never take a drop, a component set takes back only its own variants, and a layer inside a group stays in it unless dropped on another frame. Groups and booleans fit their children after a move or nudge, and a group whose last layer leaves is removed. Pressing inside a selected frame, group, or component set drags it rather than the layer under the cursor, and an auto layout child dragged out lands where you drop it. Hold Space while dragging to keep layers in their parents, Shift to move along one axis, or Control to drop into auto layout as an absolute-positioned layer. Locked layers stay put when the rest of the selection moves. Shapes drawn inside a frame, auto layout, or slot go into it, a frame drawn over layers takes in the ones it fully covers, and a section does so when moved or resized too. Wrapped auto layout inserts on the line under the cursor. Duplicates keep their names, and duplicating a main component with ⌘D or Alt-drag creates an instance. ⌘D duplicates in place, placing a lone top-level frame's copy to its right, and ⌘V keeps the copied position, in the browser too, centering an axis that doesn't fit the selected frame, and an instance pasted into its own main component, or into a layer inside it, lands over that layer in the component's parent instead of inside it; **Paste here** still pastes at the cursor.- 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.@@ -135,6 +136,7 @@### Fixed+- Renaming a section title on the canvas keeps the title's size, weight, and place. Section titles draw in Inter SemiBold rather than an emboldened regular weight, and labels that are not rotated sit on whole pixels, so they stay crisp.- Reject an argument an AI, MCP, CLI, or WebMCP tool does not take, such as `properties: { y: 500 }` for `update_node` or `font: { family }` for `set_font`, and name it, instead of reporting success without changing anything (#977).- Choose an instance's variant by its variant property in design JSX, such as `<Instance component="Button" State="Pressed" />`, without a warning that the property is unsupported.- Keep memory flat while the AI chat or an MCP client edits a document (#587). Each edit kept two copies of its whole page in the undo history, about 10 MB a call on a 400-layer page, until the 200-step history limit, so long sessions grew until the app ran out of memory; an edit now keeps only the layers it changed, and undoing it leaves the other layers as they are.diff --git a/packages/core/src/canvas/labels/paragraph-cache.ts b/packages/core/src/canvas/labels/paragraph-cache.tsindex d94e46a87..fa28465ca 100644--- a/packages/core/src/canvas/labels/paragraph-cache.ts+++ b/packages/core/src/canvas/labels/paragraph-cache.ts@@ -12,7 +12,7 @@ import { detectTextDirection } from '@open-pencil/scene-graph/text-direction'import { ResourceCache } from '#core/cache/resource'import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'-import { DEFAULT_FONT_FAMILY } from '#core/constants'+import { DEFAULT_FONT_FAMILY, SECTION_TITLE_FONT_FAMILY } from '#core/constants'import { textHasFallbackScript } from '#core/text/coverage'import { weightToStyle } from '#core/text/fonts'import { missingGlyphOccurrences, type MissingGlyphOccurrence } from '#core/text/resolver'@@ -30,6 +30,12 @@ export interface LabelFontOptions {onMissingGlyphs?: (missing: readonly MissingGlyphOccurrence[]) => void}+/** Semibold labels are section titles, drawn in their own face; the rest in Inter. */+function labelFontFamilies(weight: number): string[] {+ const families = resolveParagraphFontFamilies(DEFAULT_FONT_FAMILY, weightToStyle(weight))+ return weight >= 600 ? [SECTION_TITLE_FONT_FAMILY, ...families] : families+}+interface LabelParagraphEntry extends BorrowedLabelParagraph {units: numberlayoutWidth: number@@ -71,9 +77,7 @@ function buildEntry(textAlign: ck.TextAlign.Left,textStyle: {color,- fontFamilies:- fonts.families?.(fontWeight) ??- resolveParagraphFontFamilies(DEFAULT_FONT_FAMILY, weightToStyle(fontWeight)),+ fontFamilies: fonts.families?.(fontWeight) ?? labelFontFamilies(fontWeight),fontSize,fontStyle: { weight: { value: fontWeight } as FontWeight }}diff --git a/packages/core/src/canvas/labels/selection.ts b/packages/core/src/canvas/labels/selection.tsindex 8482a19dd..252f5b350 100644--- a/packages/core/src/canvas/labels/selection.ts+++ b/packages/core/src/canvas/labels/selection.ts@@ -74,7 +74,7 @@ export function drawSingleSelectionSize(sizeFont: NonNullable<SkiaRenderer['sizeFont']>): void {const sizeText = `${Math.round(node.width)} × ${Math.round(node.height)}`- const pillColor = r.outlineColor(node)+ const pillColor = r.outlineColor(node, graph)const transform = frameLabelPlacement(node, graph, overlays.rotationPreview, {x: 0.5,y: 1@@ -90,6 +90,7 @@ export function drawSingleSelectionSize(function drawMultiSelectionSize(r: SkiaRenderer,canvas: Canvas,+ graph: SceneGraph,nodes: SceneNode[],minX: number,minY: number,@@ -102,7 +103,7 @@ function drawMultiSelectionSize(const sx2 = maxX * r.zoom + r.panXconst sy2 = maxY * r.zoom + r.panYconst smx = (sx1 + sx2) / 2- const allComponents = nodes.length > 0 && nodes.every((n) => r.isComponentType(n.type))+ const allComponents = nodes.length > 0 && nodes.every((n) => r.isInComponent(n, graph))const pillColor = allComponents ? r.compColor() : r.selColor()drawSizePill(r, canvas, sizeFont, sizeText, smx, sy2, pillColor)@@ -131,5 +132,5 @@ export function drawSelectionLabels(return}- drawMultiSelectionSize(r, canvas, nodes, minX, minY, maxX, maxY, sizeFont)+ drawMultiSelectionSize(r, canvas, graph, nodes, minX, minY, maxX, maxY, sizeFont)}diff --git a/packages/core/src/canvas/labels/transform.ts b/packages/core/src/canvas/labels/transform.tsindex 73d7facca..b05d8783e 100644--- a/packages/core/src/canvas/labels/transform.ts+++ b/packages/core/src/canvas/labels/transform.ts@@ -62,8 +62,21 @@ function labelWorldMatrix(transform: LabelTransform, zoom: number) {)}+/**+ * Where a label draws on screen. An upright label starts on a whole pixel, so its text is crisp+ * and lines up with the field that renames it, which the page also places on whole pixels.+ */export function labelScreenMatrix(transform: LabelTransform, viewport: ViewportTransform) {- return Matrix.multiply(viewportMatrix(viewport), labelWorldMatrix(transform, viewport.zoom))+ const matrix = Matrix.multiply(+ viewportMatrix(viewport),+ labelWorldMatrix(transform, viewport.zoom)+ )+ const upright = Math.abs(matrix[1]) < 1e-9 && Math.abs(matrix[3]) < 1e-9+ if (!upright) return matrix+ const snapped = [...matrix] as typeof matrix+ snapped[2] = Math.round(matrix[2])+ snapped[5] = Math.round(matrix[5])+ return snapped}export function labelLocalPoint(diff --git a/packages/core/src/canvas/overlays/layout-outlines.ts b/packages/core/src/canvas/overlays/layout-outlines.tsindex bb216004a..25317233c 100644--- a/packages/core/src/canvas/overlays/layout-outlines.ts+++ b/packages/core/src/canvas/overlays/layout-outlines.ts@@ -33,7 +33,7 @@ export function strokeLayoutOutlines(0)r.auxStroke.setStrokeWidth(1 / r.zoom)- r.auxStroke.setColor(r.outlineColor(container))+ r.auxStroke.setColor(r.outlineColor(container, graph))r.auxStroke.setPathEffect(dash)try {for (const node of nodes) {diff --git a/packages/core/src/canvas/overlays/selection.ts b/packages/core/src/canvas/overlays/selection.tsindex d9df86993..6919bd6b2 100644--- a/packages/core/src/canvas/overlays/selection.ts+++ b/packages/core/src/canvas/overlays/selection.ts@@ -39,7 +39,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.outlineColor(node))+ r.auxStroke.setColor(r.outlineColor(node, graph))r.auxStroke.setPathEffect(null)canvas.save()canvas.concat(createSceneGeometry(graph, preview).screenMatrix(node, r))@@ -106,7 +106,7 @@ function drawSingleSelection(// is suppressed (see drawTextEditOverlay) since it can't follow the path.if (editing && !isPathText) return- r.selectionPaint.setColor(r.outlineColor(node))+ r.selectionPaint.setColor(r.outlineColor(node, graph))r.selectionPaint.setStrokeWidth(1 / r.zoom)const rotation = node.rotation@@ -144,7 +144,7 @@ export function drawSelection(const node = graph.getNode(id)if (!node) continue- r.selectionPaint.setColor(r.outlineColor(node))+ r.selectionPaint.setColor(r.outlineColor(node, graph))r.selectionPaint.setStrokeWidth(1 / r.zoom)const rotation = node.rotationdiff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex dff10d30b..9e141ef1c 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -431,10 +431,22 @@ export class SkiaRenderer {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) {+ /**+ * The outline colour for a node: pink for slots, purple for components, instances and every+ * layer inside them, as in Figma, blue otherwise.+ */+ outlineColor(node: SceneNode, graph: SceneGraph) {if (slotPropertyId(node)) return this.slotColor()- return this.isComponentType(node.type) ? this.compColor() : this.selColor()+ return this.isInComponent(node, graph) ? this.compColor() : this.selColor()+ }++ /** A component, instance or set, or a layer inside one; content placed in a slot is not. */+ isInComponent(node: SceneNode, graph: SceneGraph): boolean {+ const owner = graph.closest(+ node.id,+ (layer) => this.isComponentType(layer.type) || slotPropertyId(layer) !== undefined+ )+ return owner !== undefined && !slotPropertyId(owner)}isComponentType(type: string): boolean {diff --git a/packages/core/src/canvas/renderer/fonts.ts b/packages/core/src/canvas/renderer/fonts.tsindex 55e86e5cb..c5e7a03c7 100644--- a/packages/core/src/canvas/renderer/fonts.ts+++ b/packages/core/src/canvas/renderer/fonts.ts@@ -6,7 +6,9 @@ import {DEFAULT_FONT_FAMILY,DEFAULT_FONT_SIZE,LABEL_FONT_SIZE,+ SECTION_TITLE_FONT_FAMILY,SECTION_TITLE_FONT_SIZE,+ SECTION_TITLE_FONT_URL,SIZE_FONT_SIZE} from '#core/constants'import { withTextMeasurer } from '#core/layout/text-measurement'@@ -89,6 +91,12 @@ export function getFontProvider(r: SkiaRenderer) {return r.isDestroyed() || !r.fontProvider ? null : r.fontProvider}+/** Section titles' face, for the canvas and for the field that renames a title in the page. */+function registerSectionTitleFont(r: SkiaRenderer, data: ArrayBuffer) {+ r.fontProvider?.registerFont(data, SECTION_TITLE_FONT_FAMILY)+ fontManager.registerFontInBrowser(SECTION_TITLE_FONT_FAMILY, 'SemiBold', data)+}+export async function loadFonts(r: SkiaRenderer,onFallbackFontsLoaded?: () => void@@ -105,8 +113,12 @@ export async function loadFonts(fontManager.attachProvider(r.ck, r.fontProvider)syncFontGeneration(r)- const fontData = await fontManager.loadFont(DEFAULT_FONT_FAMILY, 'Regular')+ const [fontData, titleData] = await Promise.all([+ fontManager.loadFont(DEFAULT_FONT_FAMILY, 'Regular'),+ fontManager.fetchBundledFont(SECTION_TITLE_FONT_URL).catch(() => null)+ ])if (r.isDestroyed()) return+ if (titleData) registerSectionTitleFont(r, titleData)if (fontData) {const typeface = r.ck.Typeface.MakeFreeTypeFaceFromData(fontData)if (typeface) {diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.tsindex 70f1fd904..286bfc002 100644--- a/packages/core/src/constants.ts+++ b/packages/core/src/constants.ts@@ -89,6 +89,13 @@ export const SECTION_TITLE_HEIGHT = 24export const SECTION_TITLE_PADDING_X = 6export const SECTION_TITLE_RADIUS = 5export const SECTION_TITLE_FONT_SIZE = 11+/**+ * The family section titles draw in: the bundled Inter SemiBold under a name of its own, on the+ * canvas and in the page, so renaming a title shows the same glyphs and document fonts named+ * Inter cannot replace them.+ */+export const SECTION_TITLE_FONT_FAMILY = 'OpenPencil Section Title'+export const SECTION_TITLE_FONT_URL = '/Inter-SemiBold.ttf'export const SECTION_TITLE_GAP = 6export const SECTION_HOVER_STROKE_WIDTH = 2diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.tsindex 449fff585..674f07ba5 100644--- a/packages/core/src/editor/clipboard.ts+++ b/packages/core/src/editor/clipboard.ts@@ -16,7 +16,11 @@ import { createClipboardFontActions } from './clipboard/fonts'import { deleteIds, recreateSnapshots, restoreDeletedEntries } from './clipboard/history'import type { PasteHistoryOperation } from './clipboard/paste-replace'import { replaceTargetsWithCreated, selectedReplacementTargets } from './clipboard/paste-replace'-import { resolvePasteTarget } from './clipboard/paste-target'+import {+ instanceSafeParent,+ pastedComponentIds,+ resolvePasteTarget+} from './clipboard/paste-target'import { createClipboardPlacementActions } from './clipboard/placement'import { collectSubtrees, restoreSubtree, snapshotSubtree } from './clipboard/subtree-history'import { acceptsChildren, prepareSlotEdits } from './components/slots'@@ -197,10 +201,7 @@ export function createClipboardActions(ctx: EditorContext) {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)+ placementActions.placeForeignPaste(created, pasteTarget, cursorPos)computeAllLayouts(ctx.graph, ctx.state.currentPageId)ctx.setSelectedIds(new Set(created))pushCreatedNodesUndo(created, prevSelection, 'Paste', operation)@@ -243,7 +244,12 @@ export function createClipboardActions(ctx: EditorContext) {return node.id}- const pasteTarget = replacementTargets[0]?.parentId ?? resolvePasteTarget(ctx)+ const requestedTarget = replacementTargets[0]?.parentId ?? resolvePasteTarget(ctx)+ const pasteTarget = instanceSafeParent(+ ctx.graph,+ requestedTarget,+ pastedComponentIds(ctx.graph, [...nodes, ...dependencies])+ )if (!prepareSlotEdits(ctx, [pasteTarget])) return createdconst dependencyRootIds: string[] = []for (const dependency of dependencies)@@ -286,7 +292,13 @@ export function createClipboardActions(ctx: EditorContext) {}if (cursorPos) placementActions.centerNodesAtCanvasPoint(created, pasteTarget, cursorPos)- else placementActions.placePasted(created, nodes[0]?.parentId ?? undefined, pasteTarget)+ else+ placementActions.placePasted(+ created,+ nodes[0]?.parentId ?? undefined,+ pasteTarget,+ requestedTarget+ )computeAllLayouts(ctx.graph, ctx.state.currentPageId)ctx.setSelectedIds(new Set(created))diff --git a/packages/core/src/editor/clipboard/paste-target.ts b/packages/core/src/editor/clipboard/paste-target.tsindex ab97a1498..c7e223b63 100644--- a/packages/core/src/editor/clipboard/paste-target.ts+++ b/packages/core/src/editor/clipboard/paste-target.ts@@ -1,3 +1,4 @@+import { canCreateInstance, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'import { CONTAINER_TYPES } from '@open-pencil/scene-graph/node-defaults'import { acceptingParent } from '#core/editor/components/slots'@@ -20,3 +21,33 @@ function pasteTargetCandidate(ctx: Pick<EditorContext, 'graph' | 'state'>): striif (CONTAINER_TYPES.has(node.type) && node.type !== 'CANVAS') return node.idreturn node.parentId ?? ctx.state.currentPageId}++type PastedTree = SceneNode & { children?: PastedTree[] }++/** The document's components that pasted instances point at; copied components are new ones. */+export function pastedComponentIds(graph: SceneGraph, trees: readonly PastedTree[]): string[] {+ const copied = new Set<string>()+ const referenced = new Set<string>()+ const visit = (node: PastedTree) => {+ copied.add(node.id)+ if (node.type === 'INSTANCE' && node.componentId) referenced.add(node.componentId)+ for (const child of node.children ?? []) visit(child)+ }+ for (const tree of trees) visit(tree)+ return [...referenced].filter((id) => !copied.has(id) && graph.getNode(id)?.type === 'COMPONENT')+}++/**+ * `parentId`, or its nearest ancestor that can hold instances of these components without a+ * component containing itself: Figma pastes an instance next to its own main component, not in it.+ */+export function instanceSafeParent(+ graph: SceneGraph,+ parentId: string,+ componentIds: readonly string[]+): string {+ const safe = graph.closest(parentId, (node) =>+ componentIds.every((id) => canCreateInstance(graph, id, node.id))+ )+ return safe?.id ?? parentId+}diff --git a/packages/core/src/editor/clipboard/placement.ts b/packages/core/src/editor/clipboard/placement.tsindex 8e688ad1f..29bb96b11 100644--- a/packages/core/src/editor/clipboard/placement.ts+++ b/packages/core/src/editor/clipboard/placement.ts@@ -61,13 +61,67 @@ export function createClipboardPlacementActions(ctx: EditorContext) {return { x: -panX / zoom, y: -panY / zoom, width: width / zoom, height: height / zoom }}+ /** Centers each axis of the layers that does not fit inside their frame. */+ function fitInside(nodeIds: string[], parentId: string) {+ const parent = ctx.graph.getNode(parentId)+ const items = nodeIds.map((id) => ctx.graph.getNode(id)).filter(isNotNil)+ if (!parent || parent.type === 'CANVAS' || items.length === 0) return+ const box = computeBounds(items)+ const fitsX = box.x >= 0 && box.x + box.width <= parent.width+ const fitsY = box.y >= 0 && box.y + box.height <= parent.height+ translate(+ nodeIds,+ fitsX ? 0 : (parent.width - box.width) / 2 - box.x,+ fitsY ? 0 : (parent.height - box.height) / 2 - box.y+ )+ }++ /**+ * Places layers pasted from another app, whose copied position means nothing here: at the+ * cursor for Paste here, otherwise in the middle of the view and inside the frame they go into.+ */+ function placeForeignPaste(nodeIds: string[], parentId: string, cursor?: Vector) {+ if (cursor) {+ centerNodesAtCanvasPoint(nodeIds, parentId, cursor)+ return+ }+ const view = viewportRect()+ if (view)+ centerNodesAtCanvasPoint(nodeIds, parentId, {+ x: view.x + view.width / 2,+ y: view.y + view.height / 2+ })+ fitInside(nodeIds, parentId)+ }++ /** Centers layers of `parentId` over another layer, wherever that layer sits. */+ function centerOver(nodeIds: string[], parentId: string, overId: string) {+ const over = ctx.graph.getNode(overId)+ if (!over) return+ const at = ctx.graph.getAbsolutePosition(over.id)+ centerNodesAtCanvasPoint(nodeIds, parentId, {+ x: at.x + over.width / 2,+ y: at.y + over.height / 2+ })+ }+/*** Places pasted layers as Figma does. Layers copied out of a frame keep their offset inside the* frame they are pasted into; top-level layers keep their place on the canvas. An axis that* does not fit inside the destination frame is centered in it, and layers that would land out- * of view are centered in the view.+ * of view are centered in the view. A paste that could not go into the selected layer+ * (`requestedId`), such as an instance into its own main component, lands over that layer.*/- function placePasted(nodeIds: string[], sourceParentId: string | undefined, targetId: string) {+ function placePasted(+ nodeIds: string[],+ sourceParentId: string | undefined,+ targetId: string,+ requestedId = targetId+ ) {+ if (requestedId !== targetId) {+ centerOver(nodeIds, targetId, requestedId)+ return+ }const items = nodeIds.map((id) => ctx.graph.getNode(id)).filter(isNotNil)if (items.length === 0) returnconst target = ctx.graph.getNode(targetId)@@ -83,16 +137,7 @@ export function createClipboardPlacementActions(ctx: EditorContext) {translate(nodeIds, from.x - to.x, from.y - to.y)}- if (target && target.type !== 'CANVAS') {- const box = computeBounds(items)- const fitsX = box.x >= 0 && box.x + box.width <= target.width- const fitsY = box.y >= 0 && box.y + box.height <= target.height- translate(- nodeIds,- fitsX ? 0 : (target.width - box.width) / 2 - box.x,- fitsY ? 0 : (target.height - box.height) / 2 - box.y- )- }+ fitInside(nodeIds, targetId)const view = viewportRect()if (!view) return@@ -115,5 +160,11 @@ export function createClipboardPlacementActions(ctx: EditorContext) {centerNodesAt(nodeIds, point.x - origin.x, point.y - origin.y)}- return { centerNodesAt, centerNodesAtCanvasPoint, duplicatePosition, placePasted }+ return {+ centerNodesAt,+ centerNodesAtCanvasPoint,+ duplicatePosition,+ placeForeignPaste,+ placePasted+ }}diff --git a/packages/core/src/editor/selection.ts b/packages/core/src/editor/selection.tsindex 4c1be6875..c3fb111a7 100644--- a/packages/core/src/editor/selection.ts+++ b/packages/core/src/editor/selection.ts@@ -5,17 +5,40 @@ import { createSelectionReadActions } from './selection/read'import type { EditorContext } from './types'export function createSelectionActions(ctx: EditorContext) {+ function nested(a: string, b: string) {+ return ctx.graph.isDescendant(a, b) || ctx.graph.isDescendant(b, a)+ }++ /** The outermost of the layers: one inside another listed layer is dropped. */+ function outermost(ids: string[]): Set<string> {+ const listed = new Set(ids)+ return new Set(+ ids.filter((id) => {+ const parentId = ctx.graph.getNode(id)?.parentId+ return !parentId || !ctx.graph.closest(parentId, (node) => listed.has(node.id))+ })+ )+ }++ /**+ * Figma never selects a layer together with one of its ancestors. A plain selection keeps the+ * outermost layers; adding a layer replaces its selected ancestors and descendants.+ */function select(ids: string[], additive = false) {- if (additive) {- const next = new Set(ctx.state.selectedIds)- for (const id of ids) {- if (next.has(id)) next.delete(id)- else next.add(id)+ if (!additive) {+ ctx.setSelectedIds(outermost(ids))+ return+ }+ let next = new Set(ctx.state.selectedIds)+ for (const id of ids) {+ if (next.has(id)) {+ next.delete(id)+ continue}- ctx.setSelectedIds(next)- } else {- ctx.setSelectedIds(new Set(ids))+ next = new Set([...next].filter((other) => !nested(other, id)))+ next.add(id)}+ ctx.setSelectedIds(next)}function clearSelection() {diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.tsindex 907c84912..de095a589 100644--- a/packages/core/src/text/fonts.ts+++ b/packages/core/src/text/fonts.ts@@ -650,7 +650,8 @@ export class FontManager {}}- private registerFontInBrowser(family: string, style: string, data: ArrayBuffer) {+ /** Makes a face available to the page's own text, such as fields over canvas labels. */+ registerFontInBrowser(family: string, style: string, data: ArrayBuffer) {if (!IS_BROWSER) returnconst weight = styleToWeight(style)const italic = style.toLowerCase().includes('italic') ? 'italic' : 'normal'diff --git a/packages/core/tests/editor/clipboard/placement.test.ts b/packages/core/tests/editor/clipboard/placement.test.tsindex 68c074d1a..ea072daf8 100644--- a/packages/core/tests/editor/clipboard/placement.test.ts+++ b/packages/core/tests/editor/clipboard/placement.test.ts@@ -160,4 +160,35 @@ describe('paste placement', () => {await editor.pasteSnapshot(snapshot, { x: 400, y: 200 })expect(selected()).toMatchObject({ parentId: target.id, x: 80, y: 80 })})++ test('an instance pasted into its own main component lands over it in its parent', async () => {+ const page = setup()+ const card = node('COMPONENT', page, { x: 260, width: 160, height: 100 })+ const instance = editor.graph.createInstance(card.id, page, { x: 460 })+ if (!instance) throw new Error('Expected an instance')+ const snapshot = await copy(instance.id)+ editor.select([card.id])+ await editor.pasteSnapshot(snapshot)+ expect(selected()).toMatchObject({ type: 'INSTANCE', parentId: page, x: 260, y: 0 })++ // Inside a frame in the component, the paste climbs to the component's own parent.+ const frame = node('FRAME', card.id, { x: 10, y: 10, width: 100, height: 60 })+ editor.select([frame.id])+ await editor.pasteSnapshot(snapshot)+ expect(selected()).toMatchObject({ parentId: page, x: 240, y: -10 })+ expect(editor.graph.getChildren(card.id).map((child) => child.id)).toEqual([frame.id])+ })++ test('a paste read back from the Figma clipboard lands inside the selected frame', async () => {+ const page = setup()+ const card = node('RECTANGLE', page, { x: 600, y: 600, width: 240, height: 160 })+ const holder = node('FRAME', page, { x: 1000, y: 1000, width: 400, height: 240 })+ editor.state.panX = -900+ editor.state.panY = -900+ editor.select([card.id])+ const { html } = await editor.prepareCopy()+ editor.select([holder.id])+ await editor.pasteFromHTML(html)+ expect(selected()).toMatchObject({ parentId: holder.id, x: 80, y: 40 })+ })})diff --git a/packages/core/tests/editor/selection/semantics.test.ts b/packages/core/tests/editor/selection/semantics.test.tsindex dfdd80aa4..9573e23bd 100644--- a/packages/core/tests/editor/selection/semantics.test.ts+++ b/packages/core/tests/editor/selection/semantics.test.ts@@ -7,6 +7,31 @@ function renameOptions(replacement: string, match = '', startNumber = 1) {}describe('selection semantics', () => {+ // Figma desktop 126: a layer and its own ancestor are never selected together.+ test('a plain selection keeps the outermost of nested layers', () => {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const frame = editor.graph.createNode('FRAME', pageId, { name: 'Frame' })+ const child = editor.graph.createNode('RECTANGLE', frame.id, { name: 'Child' })+ editor.select([child.id, frame.id])+ expect(editor.state.selectedIds).toEqual(new Set([frame.id]))+ })++ test('adding a layer replaces its selected ancestors and descendants', () => {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const frame = editor.graph.createNode('FRAME', pageId, { name: 'Frame' })+ const child = editor.graph.createNode('RECTANGLE', frame.id, { name: 'Child' })+ const other = editor.graph.createNode('RECTANGLE', pageId, { name: 'Other' })+ editor.select([frame.id, other.id])+ editor.select([child.id], true)+ expect(editor.state.selectedIds).toEqual(new Set([other.id, child.id]))+ editor.select([frame.id], true)+ expect(editor.state.selectedIds).toEqual(new Set([other.id, frame.id]))+ editor.select([frame.id], true)+ expect(editor.state.selectedIds).toEqual(new Set([other.id]))+ })+test('selectInverse selects unselected top-level layers', () => {const editor = createEditor()const pageId = editor.state.currentPageIddiff --git a/packages/docs/user-guide/selection-and-manipulation.md b/packages/docs/user-guide/selection-and-manipulation.mdindex e8235a15d..ae012dba3 100644--- a/packages/docs/user-guide/selection-and-manipulation.md+++ b/packages/docs/user-guide/selection-and-manipulation.md@@ -11,8 +11,9 @@ Select objects to move, resize, rotate, duplicate, and organize them on the canv- **Click** a node to select it (deselects everything else). As in Figma, a click inside a top-level frame selects that frame's direct child, such as a nested frame or a group, rather than the deepest layer; click a top-level frame by its title, anywhere when it is empty, or by its gaps and padding when it has auto layout- **Hover** an auto layout frame to see its direct children outlined with dotted lines; while a single layer is selected, the border of its auto layout parent is dotted- **Double-click** to go one level deeper, or click again inside a selected frame, component, or instance; once a layer is selected, clicks reach its siblings and cousins directly-- <kbd>⌘</kbd> + click (<kbd>Ctrl</kbd> + click on Windows and Linux) selects the deepest layer under the cursor-- <kbd>Shift</kbd> + click to add or remove a node from the current selection+- <kbd>⌘</kbd> + click (<kbd>Ctrl</kbd> + click on Windows and Linux) selects the deepest layer under the cursor; holding <kbd>⌘</kbd> highlights that layer before you click+- <kbd>Shift</kbd> + click to add or remove a node from the current selection. A layer and its own parent or child are never selected together, so Shift-clicking one replaces the other+- **Double-click a frame's or component's name** above it on the canvas to rename it in place- **Marquee drag** — drag on empty canvas to draw a selection rectangle; intersecting nodes are selected on release. Started inside a top-level frame without auto layout or a section, it selects that container's layers; from the page, a frame or section that holds layers is selected only when fully enclosed- <kbd>⌘</kbd><kbd>A</kbd> — select all nodes on the current page- **Click empty canvas** — deselect alldiff --git a/packages/vue/src/canvas/text-edit/input.ts b/packages/vue/src/canvas/text-edit/input.tsindex 10ed18580..e81ed97e5 100644--- a/packages/vue/src/canvas/text-edit/input.ts+++ b/packages/vue/src/canvas/text-edit/input.ts@@ -1,4 +1,4 @@-import type { Editor } from '@open-pencil/core/editor'+import { getNodeEditCapability, type Editor } from '@open-pencil/core/editor'import type { SceneNode } from '@open-pencil/scene-graph'import type { CanvasLabelKind } from '#vue/canvas/labels/edit'@@ -15,6 +15,7 @@ type TextEditInputOptions = {hitTestInScope: HitTesthitTestSectionTitle: (cx: number, cy: number) => SceneNode | nullhitTestComponentLabel: (cx: number, cy: number) => SceneNode | null+ hitTestFrameTitle: (cx: number, cy: number) => SceneNode | nullgetClickCount: () => numberwasSelectedBeforeClickSequence: (id: string) => booleanonEditCanvasLabel?: (kind: CanvasLabelKind, node: SceneNode) => void@@ -28,6 +29,7 @@ export function createTextEditInput(options: TextEditInputOptions) {hitTestInScope,hitTestSectionTitle,hitTestComponentLabel,+ hitTestFrameTitle,getClickCount,wasSelectedBeforeClickSequence,onEditCanvasLabel,@@ -70,6 +72,8 @@ export function createTextEditInput(options: TextEditInputOptions) {function startTextEditingAt(hit: SceneNode, cx: number, cy: number) {editor.select([hit.id])editor.startTextEditing(hit.id)+ // Text the editor refuses, such as path text without its font, stays selected only.+ if (editor.state.editingTextId !== hit.id) returnconst textEd = editor.textEditorif (textEd) {const abs = editor.graph.getAbsolutePosition(hit.id)@@ -91,12 +95,24 @@ export function createTextEditInput(options: TextEditInputOptions) {: null}- function startSectionTitleRename(cx: number, cy: number): boolean {- const sectionTitle = hitTestSectionTitle(cx, cy)- if (sectionTitle?.type !== 'SECTION') return false- editor.select([sectionTitle.id])- onEditCanvasLabel?.('section-title', sectionTitle)- return true+ /**+ * Double-clicking the name above a section, frame or component renames it in place and keeps+ * it selected, as in Figma. A locked layer or a library's read-only component keeps its name.+ */+ function startLabelRename(cx: number, cy: number): boolean {+ const labels: [CanvasLabelKind, SceneNode | null][] = [+ ['section-title', hitTestSectionTitle(cx, cy)],+ ['component-label', hitTestComponentLabel(cx, cy)],+ ['frame-title', hitTestFrameTitle(cx, cy)]+ ]+ for (const [kind, node] of labels) {+ if (!node) continue+ editor.select([node.id])+ if (!node.locked && getNodeEditCapability(editor.graph, node.id).editable)+ onEditCanvasLabel?.(kind, node)+ return true+ }+ return false}function handleContainerDoubleClick(@@ -126,14 +142,13 @@ export function createTextEditInput(options: TextEditInputOptions) {if (editor.state.editingTextId) returnconst { cx, cy } = getCoords(e)- if (startSectionTitleRename(cx, cy)) return+ if (startLabelRename(cx, cy)) returnconst selectedId =editor.state.selectedIds.size === 1 ? [...editor.state.selectedIds][0] : undefinedif (handleContainerDoubleClick(selectedId, cx, cy)) return- const hit =- hitTestSectionTitle(cx, cy) ?? hitTestComponentLabel(cx, cy) ?? hitTestInScope(cx, cy, true)+ const hit = hitTestInScope(cx, cy, true)if (!hit) returnif (hit.type === 'TEXT') {diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.tsindex 6d6d46165..0f46283c3 100644--- a/packages/vue/src/canvas/useCanvasInput.ts+++ b/packages/vue/src/canvas/useCanvasInput.ts@@ -89,6 +89,11 @@ export function useCanvasInput()}+ /** ⌘ or Ctrl held: hover reaches the deepest layer, the one a click would select, as in Figma. */+ function hoverDeep(e?: MouseEvent) {+ return e ? e.metaKey || e.ctrlKey : metaHeld || controlHeld+ }+function refreshMeasurement() {const mode = altHeld && canMeasure() ? (metaHeld || controlHeld ? 'deep' : 'shallow') : 'off'editor.setMeasurementMode(mode)@@ -100,7 +105,7 @@ export function useCanvasInput(pointer.cy,editor,hitFns,- mode === 'deep'+ mode === 'deep' || hoverDeep())editor.setAutoLayoutHover(mode === 'off' ? resolveAutoLayoutHover(pointer.cx, pointer.cy, editor) : null@@ -145,6 +150,7 @@ export function useCanvasInput(hitTestInScope,hitTestSectionTitle,hitTestComponentLabel,+ hitTestFrameTitle,getClickCount,wasSelectedBeforeClickSequence: (id) => selectedIdsBeforeClickSequence.value.has(id),onEditCanvasLabel: canvasLabelEdit.start,@@ -296,7 +302,13 @@ export function useCanvasInput(const guideCursor = guideInput.updateHover(sx, sy)cursorOverride.value =guideCursor ??- updateHoverCursor(cx, cy, editor, hitFns, editor.state.measurementMode === 'deep')+ updateHoverCursor(+ cx,+ cy,+ editor,+ hitFns,+ editor.state.measurementMode === 'deep' || hoverDeep(e)+ )editor.setAutoLayoutHover(editor.state.measurementMode === 'off' ? resolveAutoLayoutHover(cx, cy, editor) : null)diff --git a/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vue b/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vueindex e260bd639..07f579c84 100644--- a/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vue+++ b/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vue@@ -181,7 +181,9 @@ function select(id: string, selection: boolean | LayerSelectionMode) {if (!mode.range) selectionAnchorId = idapplyingSelection = truetry {- editor.select([...next])+ // Adding a layer goes through the editor, which drops its selected ancestors and descendants.+ if (mode.additive && !mode.range) editor.select([id], true)+ else editor.select([...next])} finally {applyingSelection = false}diff --git a/src/app/editor/clipboard/memory.ts b/src/app/editor/clipboard/memory.tsindex 8a1622694..b2a23fc28 100644--- a/src/app/editor/clipboard/memory.ts+++ b/src/app/editor/clipboard/memory.ts@@ -6,8 +6,23 @@ export function setInMemoryClipboardPayload(payload: ClipboardPayload): void {memoryClipboard = payload}+/**+ * What identifies a copy: its Base64 metadata and buffer. Browsers rewrite clipboard HTML when+ * reading it back, changing quotes and escaping, but leave the Base64 alone.+ */+function clipboardPayloadKey(html: string): string | null {+ const meta = /\(figmeta\)(.*?)\(\/figmeta\)/.exec(html)?.[1]+ const buffer = /\(figma\)(.*?)\(\/figma\)/s.exec(html)?.[1]+ return meta && buffer ? `${meta}:${buffer}` : null+}++/** The snapshot of the last copy when `html` is that copy, however the clipboard rewrote it. */export function matchingClipboardSnapshot(html: string) {- return html && html === memoryClipboard.html ? memoryClipboard.snapshot : undefined+ const { snapshot } = memoryClipboard+ if (!html || !snapshot) return undefined+ if (html === memoryClipboard.html) return snapshot+ const key = clipboardPayloadKey(html)+ return key !== null && key === clipboardPayloadKey(memoryClipboard.html) ? snapshot : undefined}export function setInMemoryClipboardHTML(html: string, plainText = ''): void {diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vueindex f5adf0e29..6f7531cf3 100644--- a/src/components/EditorCanvas.vue+++ b/src/components/EditorCanvas.vue@@ -15,7 +15,11 @@ import IconLucidePanelTop from '~icons/lucide/panel-top'import {AUTO_LAYOUT_PADDING_EDITOR_OFFSET_X,- AUTO_LAYOUT_PADDING_EDITOR_OFFSET_Y+ AUTO_LAYOUT_PADDING_EDITOR_OFFSET_Y,+ COMPONENT_LABEL_ICON_GAP,+ COMPONENT_LABEL_ICON_SIZE,+ SECTION_TITLE_GAP,+ SECTION_TITLE_HEIGHT} from '@open-pencil/core/constants'import type { ViewportTransform } from '@open-pencil/core/geometry'import {@@ -176,12 +180,31 @@ const canvasLabelEditNode = computed(() => {const canvasLabelEditAnchor = computed(() => {const node = canvasLabelEditNode.valueif (!node) return null- const abs = store.graph.getAbsolutePosition(node.id)+ const origin = store.graph.getAbsolutePosition(node.id)+ const { zoom, panX, panY } = store.state+ const kind = canvasLabelEdit.value?.kind+ // The canvas starts an upright label on a whole screen pixel; the field starts on the same one.+ const abs = {+ x: (Math.round(origin.x * zoom + panX) - panX) / zoom,+ y: (Math.round(origin.y * zoom + panY) - panY) / zoom+ }+ // A component's name starts after its diamond, which keeps its screen size at any zoom.+ if (kind === 'component-label')+ return { x: abs.x + (COMPONENT_LABEL_ICON_SIZE + COMPONENT_LABEL_ICON_GAP) / zoom, y: abs.y }+ // A section inside another draws its title inside its top-left corner instead of above it.+ const nested = node.parentId && store.graph.closest(node.parentId, (n) => n.type === 'SECTION')+ if (kind === 'section-title' && nested) {+ const inset = SECTION_TITLE_GAP / zoom+ return {+ x: abs.x + inset,+ y: abs.y + inset + (SECTION_TITLE_HEIGHT + SECTION_TITLE_GAP) / zoom+ }+ }return { x: abs.x, y: abs.y }})const canvasLabelEditReference = useCanvasVirtualReference(canvasRef, store, canvasLabelEditAnchor)const canvasLabelEditPresentation = computed(() =>- canvasLabelPresentation(store, canvasLabelEditNode.value ?? null)+ canvasLabelPresentation(store, canvasLabelEditNode.value ?? null, canvasLabelEdit.value?.kind))const paddingEditorAnchor = computed(() => {diff --git a/src/components/canvas/labels/CanvasLabelEditor.vue b/src/components/canvas/labels/CanvasLabelEditor.vueindex 56312cf62..f58003b7d 100644--- a/src/components/canvas/labels/CanvasLabelEditor.vue+++ b/src/components/canvas/labels/CanvasLabelEditor.vue@@ -1,7 +1,14 @@<script setup lang="ts">import type { ReferenceElement } from 'reka-ui'import { PopoverContent, PopoverPortal, PopoverRoot } from 'reka-ui'+import { computed } from 'vue'+import {+ COMPONENT_LABEL_FONT_SIZE,+ COMPONENT_LABEL_GAP,+ LABEL_FONT_SIZE,+ LABEL_OFFSET_Y+} from '@open-pencil/core/constants'import { colorToCSS } from '@open-pencil/scene-graph/color'import type { CanvasLabelEdit } from '@open-pencil/vue'@@ -14,6 +21,27 @@ const { edit, presentation, reference } = defineProps<{reference: ReferenceElement | null}>()+// Figma renames a frame or component name in a field the size of the name itself.+const compact = computed(() => !!edit && edit.kind !== 'section-title')++/** The name field's height in screen pixels, as Figma draws it. */+const NAME_FIELD_HEIGHT = 18+/** Inter's line box, ascent plus descent, as a share of its size, the box the canvas lays out. */+const INTER_LINE_BOX = 1.21++/**+ * How far above the layer the field ends, so its text sits exactly where the canvas drew the+ * name: the canvas puts the name's line box this far above the layer, and the field centers its+ * line box in its height.+ */+const sideOffset = computed(() => {+ if (!compact.value) return 6+ const component = edit?.kind === 'component-label'+ const fontSize = component ? COMPONENT_LABEL_FONT_SIZE : LABEL_FONT_SIZE+ const lineTop = (component ? COMPONENT_LABEL_GAP : LABEL_OFFSET_Y) + fontSize+ return lineTop - (NAME_FIELD_HEIGHT + fontSize * INTER_LINE_BOX) / 2+})+const emit = defineEmits<{update: [value: string]commit: []@@ -29,12 +57,14 @@ const emit = defineEmits<{:reference="reference"side="top"align="start"- :side-offset="6"+ :side-offset="sideOffset"+ :align-offset="compact ? -2 : 0":collision-padding="8":data-label-kind="edit.kind":data-foreground="presentation.foreground":style="{ backgroundColor: colorToCSS(presentation.background) }"- class="z-50 h-6 rounded-[5px] text-black shadow-sm ring-1 ring-accent data-[foreground=light]:text-white"+ class="z-50 text-black ring-1 ring-accent data-[foreground=light]:text-white"+ :class="compact ? 'h-[18px] rounded-[2px]' : 'h-6 rounded-[5px] shadow-sm'"@open-auto-focus.prevent@escape-key-down.prevent="emit('cancel')"@pointer-down-outside="emit('commit')"@@ -42,6 +72,7 @@ const emit = defineEmits<{<InlineLabelEditor:model-value="edit.value"label="Layer name"+ :variant="compact ? 'name' : 'section'"@update:model-value="emit('update', $event)"@commit="emit('commit')"@cancel="emit('cancel')"diff --git a/src/components/canvas/labels/presentation.ts b/src/components/canvas/labels/presentation.tsindex d8b43c7de..75700ded9 100644--- a/src/components/canvas/labels/presentation.ts+++ b/src/components/canvas/labels/presentation.ts@@ -1,6 +1,7 @@import { canvasLabelForeground } from '@open-pencil/core/canvas'import type { Editor } from '@open-pencil/core/editor'import type { Color, SceneNode } from '@open-pencil/scene-graph'+import type { CanvasLabelKind } from '@open-pencil/vue'export interface CanvasLabelPresentation {background: Color@@ -9,10 +10,18 @@ export interface CanvasLabelPresentation {const DEFAULT_LABEL_BACKGROUND: Color = { r: 0.37, g: 0.37, b: 0.37, a: 1 }+/** Figma renames a frame or component name in a white field, a section title on its own fill. */+const NAME_FIELD: CanvasLabelPresentation = {+ background: { r: 1, g: 1, b: 1, a: 1 },+ foreground: 'dark'+}+export function canvasLabelPresentation(editor: Editor,- node: SceneNode | null+ node: SceneNode | null,+ kind: CanvasLabelKind | undefined): CanvasLabelPresentation {+ if (kind && kind !== 'section-title') return NAME_FIELDconst fill = node?.fills[0]const background =node && fill?.visiblediff --git a/src/components/ui/input/InlineLabelEditor.vue b/src/components/ui/input/InlineLabelEditor.vueindex 272c4d861..3539e642c 100644--- a/src/components/ui/input/InlineLabelEditor.vue+++ b/src/components/ui/input/InlineLabelEditor.vue@@ -1,11 +1,38 @@<script setup lang="ts">-import { nextTick, ref, watch } from 'vue'+import { useDevicePixelRatio } from '@vueuse/core'+import { computed, nextTick, ref, watch } from 'vue'-const { modelValue, label } = defineProps<{+import { SECTION_TITLE_FONT_FAMILY } from '@open-pencil/core/constants'++const {+ modelValue,+ label,+ variant = 'section'+} = defineProps<{modelValue: stringlabel: string+ /** The typography of the label it edits: a section title's pill or a frame's plain name. */+ variant?: 'section' | 'name'}>()+// The canvas draws section titles in 11px semibold with 6px padding, names in 11px regular.+const TEXT = {+ section: 'px-1.5 text-[11px] font-semibold leading-6',+ name: 'px-0.5 text-[11px] font-normal leading-[18px]'+}+const { pixelRatio } = useDevicePixelRatio()+// Section titles use the canvas's own title face; names use Inter like the rest of the page.+// The canvas centers a title by its measured paragraph, the page by the font's line box, which+// leaves the page's text one device pixel higher.+const font = computed(() =>+ variant === 'section'+ ? {+ fontFamily: `'${SECTION_TITLE_FONT_FAMILY}', Inter, sans-serif`,+ transform: `translateY(${1 / pixelRatio.value}px)`+ }+ : undefined+)+const emit = defineEmits<{'update:modelValue': [value: string]commit: []@@ -36,14 +63,18 @@ watch(<div class="grid h-full"><spanaria-hidden="true"- class="invisible col-start-1 row-start-1 h-full whitespace-pre px-2 text-xs leading-6"+ class="invisible col-start-1 row-start-1 h-full whitespace-pre"+ :class="TEXT[variant]"+ :style="font">{{ modelValue || ' ' }}</span><inputref="input":value="modelValue":aria-label="label"- class="col-start-1 row-start-1 h-full w-0 min-w-full bg-transparent px-2 text-xs leading-6 outline-none"+ class="col-start-1 row-start-1 h-full w-0 min-w-full bg-transparent outline-none"+ :class="TEXT[variant]"+ :style="font"@input="updateValue"@keydown.enter.prevent="emit('commit')"@keydown.escape.prevent="emit('cancel')"diff --git a/tests/e2e/canvas/component-overlays.spec.ts b/tests/e2e/canvas/component-overlays.spec.tsnew file mode 100644index 000000000..406621c16--- /dev/null+++ b/tests/e2e/canvas/component-overlays.spec.ts@@ -0,0 +1,44 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'++// Figma desktop 126: layers inside a component or an instance outline in the component purple.++const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')++test('layers inside a component and an instance outline in component purple', async () => {+ await 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 fill = (r: number, g: number, b: number) => [+ { type: 'SOLID' as const, color: { r, g, b, a: 1 }, visible: true, opacity: 1 }+ ]+ const card = graph.createNode('COMPONENT', pageId, {+ name: 'Card',+ x: 120,+ y: 120,+ width: 160,+ height: 100,+ fills: fill(1, 1, 1)+ })+ const rect = graph.createNode('RECTANGLE', card.id, {+ name: 'Card Rect',+ x: 20,+ y: 20,+ width: 60,+ height: 40,+ fills: fill(0.6, 0.6, 0.6)+ })+ const instance = graph.createInstance(card.id, pageId, { x: 340, y: 120 })+ store.select([rect.id])+ store.state.hoveredNodeId = instance ? (graph.getChildren(instance.id)[0]?.id ?? null) : null+ store.requestRender()+ })+ await editor.canvas.waitForRender()+ editor.canvas.assertNoErrors()+ const buffer = await editor.canvas.screenshotCanvasRegion(600, 320)+ expect(buffer).toMatchSnapshot('component-descendant-outlines.png', {+ maxDiffPixelRatio: 0,+ threshold: 0+ })+})diff --git a/tests/e2e/canvas/component-overlays.spec.ts-snapshots/component-descendant-outlines-openpencil-darwin.png b/tests/e2e/canvas/component-overlays.spec.ts-snapshots/component-descendant-outlines-openpencil-darwin.pngnew file mode 100644index 000000000..256c4e674Binary files /dev/null and b/tests/e2e/canvas/component-overlays.spec.ts-snapshots/component-descendant-outlines-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-controls-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-controls-openpencil-darwin.pngindex b93c82417..1d42848e5 100644Binary files a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-controls-openpencil-darwin.png and b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-controls-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/frame-overlays.spec.ts-snapshots/nested-frame-rotation-preview-openpencil-darwin.png b/tests/e2e/canvas/frame-overlays.spec.ts-snapshots/nested-frame-rotation-preview-openpencil-darwin.pngindex 77d743ae2..8b11d222e 100644Binary files a/tests/e2e/canvas/frame-overlays.spec.ts-snapshots/nested-frame-rotation-preview-openpencil-darwin.png and b/tests/e2e/canvas/frame-overlays.spec.ts-snapshots/nested-frame-rotation-preview-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-0-5-openpencil-darwin.png b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-0-5-openpencil-darwin.pngindex 78d642fc7..d66d0bdf1 100644Binary files a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-0-5-openpencil-darwin.png and b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-0-5-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-1-openpencil-darwin.png b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-1-openpencil-darwin.pngindex b20e69281..a40ca9672 100644Binary files a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-1-openpencil-darwin.png and b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-1-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-2-openpencil-darwin.png b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-2-openpencil-darwin.pngindex 62beae231..940b1d88c 100644Binary files a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-2-openpencil-darwin.png and b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-2-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-0-5-openpencil-darwin.png b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-0-5-openpencil-darwin.pngindex 94dfd4b5b..d768cbc81 100644Binary files a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-0-5-openpencil-darwin.png and b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-0-5-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-1-openpencil-darwin.png b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-1-openpencil-darwin.pngindex df6063259..2b39197f8 100644Binary files a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-1-openpencil-darwin.png and b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-1-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-2-openpencil-darwin.png b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-2-openpencil-darwin.pngindex 42f026ac0..025190537 100644Binary files a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-2-openpencil-darwin.png and b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/section-pills-hover-2-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/unicode-section-labels-openpencil-darwin.png b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/unicode-section-labels-openpencil-darwin.pngindex 6a1ff44fd..23b2c0f74 100644Binary files a/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/unicode-section-labels-openpencil-darwin.png and b/tests/e2e/canvas/label-anatomy.spec.ts-snapshots/unicode-section-labels-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/labels/section-title-editing.spec.ts b/tests/e2e/canvas/labels/name-editing.spec.tssimilarity index 56%rename from tests/e2e/canvas/labels/section-title-editing.spec.tsrename to tests/e2e/canvas/labels/name-editing.spec.tsindex 92d30a2ab..33c6deb80 100644--- a/tests/e2e/canvas/labels/section-title-editing.spec.ts+++ b/tests/e2e/canvas/labels/name-editing.spec.ts@@ -39,9 +39,9 @@ test('editing section labels preserve dark and light label presentation', asyncawait expect(editorPill).toHaveCSS('height', '24px')await expect(editorPill).toHaveCSS('background-color', item.background)await expect(input).toHaveCSS('color', item.foreground)- const width = await editorPill.evaluate((element) => element.getBoundingClientRect().width)- expect(width).toBeGreaterThan(80)- expect(width).toBeLessThan(100)+ // The canvas title's own type, so the name does not change size when the field opens.+ await expect(input).toHaveCSS('font-size', '11px')+ await expect(input).toHaveCSS('font-weight', '600')await input.press('Escape')await expect(input).toBeHidden()}@@ -85,3 +85,62 @@ test('double-clicking a section title renames it inline', async () => {).toBe('Primitives')})++// Figma desktop 126: the name above a frame or component renames in place and stays selected.+test('double-clicking a frame or component name renames it inline and keeps it selected', async () => {+ const ids = await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ 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 frame = store.graph.createNode('FRAME', pageId, {+ name: 'Card',+ x: 120,+ y: 160,+ width: 200,+ height: 150,+ fills: white+ })+ const component = store.graph.createNode('COMPONENT', pageId, {+ name: 'Button',+ x: 120,+ y: 400,+ width: 160,+ height: 100,+ fills: white+ })+ store.clearSelection()+ store.requestRender()+ return { frame: frame.id, component: component.id }+ })+ await editor.canvas.waitForRender()++ const canvas = editor.page.getByTestId('canvas-element')+ const input = editor.page.getByRole('textbox', { name: 'Layer name' })+ for (const [id, point, from, to] of [+ [ids.frame, { x: 126, y: 147 }, 'Card', 'Pricing card'],+ [ids.component, { x: 144, y: 388 }, 'Button', 'Primary button']+ ] as const) {+ await canvas.dblclick({ position: point })+ await expect(input).toBeVisible()+ await expect(input).toHaveValue(from)+ await expect(input.locator('xpath=../..')).toHaveCSS('background-color', 'rgb(255, 255, 255)')+ await input.fill(to)+ await input.press('Enter')+ await expect(input).toBeHidden()+ await expect+ .poll(() =>+ editor.page.evaluate((nodeId) => {+ const store = window.openPencil?.getStore?.()+ return {+ name: store?.graph.getNode(nodeId)?.name,+ selected: [...(store?.state.selectedIds ?? [])]+ }+ }, id)+ )+ .toEqual({ name: to, selected: [id] })+ }+ editor.canvas.assertNoErrors()+})diff --git a/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-false-false-held-openpencil-darwin.png b/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-false-false-held-openpencil-darwin.pngindex fc69a6c23..8546a4d2c 100644Binary files a/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-false-false-held-openpencil-darwin.png and b/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-false-false-held-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-false-true-held-openpencil-darwin.png b/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-false-true-held-openpencil-darwin.pngindex c4dfec34d..5232309b0 100644Binary files a/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-false-true-held-openpencil-darwin.png and b/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-false-true-held-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-true-false-held-openpencil-darwin.png b/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-true-false-held-openpencil-darwin.pngindex 169e672dc..1d9405423 100644Binary files a/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-true-false-held-openpencil-darwin.png and b/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-true-false-held-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-true-true-held-openpencil-darwin.png b/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-true-true-held-openpencil-darwin.pngindex 4e4d4e905..f038c4988 100644Binary files a/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-true-true-held-openpencil-darwin.png and b/tests/e2e/canvas/nested-transform-interaction.spec.ts-snapshots/nested-transform-true-true-held-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/top-level-frame-click.spec.ts b/tests/e2e/canvas/top-level-frame-click.spec.tsindex 208ef0872..bc0b57778 100644--- a/tests/e2e/canvas/top-level-frame-click.spec.ts+++ b/tests/e2e/canvas/top-level-frame-click.spec.ts@@ -1,194 +1,88 @@import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { clickDepthDriver } from '#tests/helpers/canvas/click-depth-driver'// Matches Figma desktop 126 with the same pointer input: the gaps and padding of a top-level auto// layout frame select, highlight, and drag it, while those of a plain top-level frame are background.const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')-/** A top-level card with auto layout and one without, each holding a title and a button. */-async function createCards() {- return editor.page.evaluate(() => {- const store = window.openPencil?.getStore?.()- if (!store) throw new Error('OpenPencil store not initialized')- const pageId = store.state.currentPageId- const fill = (r: number, g: number, b: number) => [- { type: 'SOLID' as const, color: { r, g, b, a: 1 }, opacity: 1, visible: true }- ]- const card = (name: string, x: number, layoutMode: 'VERTICAL' | 'NONE') => {- const frame = store.graph.createNode('FRAME', pageId, {- name,- x,- y: 100,- width: 200,- height: 240,- fills: fill(1, 1, 1),- layoutMode,- itemSpacing: 24,- paddingTop: 24,- paddingRight: 24,- paddingBottom: 24,- paddingLeft: 24- })- store.graph.createNode('RECTANGLE', frame.id, {- name: `${name} title`,- x: 24,- y: 24,- width: 152,- height: 40,- fills: fill(0.85, 0.85, 0.9)- })- store.graph.createNode('RECTANGLE', frame.id, {- name: `${name} button`,- x: 24,- y: 88,- width: 152,- height: 40,- fills: fill(0.2, 0.4, 1)- })- return frame.id- }- const ids = { auto: card('Auto card', 100, 'VERTICAL'), plain: card('Plain card', 400, 'NONE') }- store.clearSelection()- store.requestRender()- return ids- })-}--/** Canvas coordinates of a point given relative to a node's top-left corner. */-async function at(id: string, dx: number, dy: number) {- return editor.page.evaluate(- ({ id, dx, dy }) => {- const store = window.openPencil?.getStore?.()- if (!store) throw new Error('OpenPencil store not initialized')- const abs = store.graph.getAbsolutePosition(id)- const { zoom, panX, panY } = store.state- return { x: (abs.x + dx) * zoom + panX, y: (abs.y + dy) * zoom + panY }- },- { id, dx, dy }- )-}--async function state() {- return editor.page.evaluate(() => {- const store = window.openPencil?.getStore?.()- if (!store) throw new Error('OpenPencil store not initialized')- return { selected: [...store.state.selectedIds], hovered: store.state.hoveredNodeId }- })-}--async function position(id: string) {- return editor.page.evaluate((nodeId) => {- const node = window.openPencil?.getStore?.().graph.getNode(nodeId)- return node ? { x: node.x, y: node.y } : null- }, id)-}+const scene = clickDepthDriver(() => editor.page)test('hovering and clicking the empty area of a top-level auto layout frame selects it', async () => {- const { auto } = await createCards()+ const { auto } = await scene.cards()await editor.canvas.waitForRender()- const gap = await at(auto, 100, 200)+ const gap = await scene.at(auto, 100, 200)await editor.canvas.hover(gap.x, gap.y)- await expect.poll(async () => (await state()).hovered).toBe(auto)+ await expect.poll(async () => (await scene.state()).hovered).toBe(auto)await editor.canvas.click(gap.x, gap.y)- await expect.poll(async () => (await state()).selected).toEqual([auto])+ await expect.poll(async () => (await scene.state()).selected).toEqual([auto])editor.canvas.assertNoErrors()})test('a click on a layer in a top-level auto layout frame still selects the layer', async () => {- const { auto } = await createCards()+ const { auto } = await scene.cards()await editor.canvas.waitForRender()- const button = await at(auto, 100, 108)- const buttonId = await editor.page.evaluate(- (frameId) => window.openPencil?.getStore?.().graph.getNode(frameId)?.childIds[1],- auto- )+ const button = await scene.at(auto, 100, 108)+ const [, buttonId] = await scene.children(auto)await editor.canvas.click(button.x, button.y)- await expect.poll(async () => (await state()).selected).toEqual([buttonId])+ await expect.poll(async () => (await scene.state()).selected).toEqual([buttonId])editor.canvas.assertNoErrors()})test('dragging the empty area of a top-level auto layout frame moves it', async () => {- const { auto } = await createCards()+ const { auto } = await scene.cards()await editor.canvas.waitForRender()- const gap = await at(auto, 100, 200)+ const gap = await scene.at(auto, 100, 200)await editor.canvas.drag(gap.x, gap.y, gap.x + 60, gap.y + 40)- await expect.poll(() => position(auto)).toEqual({ x: 160, y: 140 })- expect((await state()).selected).toEqual([auto])+ await expect.poll(() => scene.position(auto)).toEqual({ x: 160, y: 140 })+ expect((await scene.state()).selected).toEqual([auto])editor.canvas.assertNoErrors()})test('the empty area of a plain top-level frame stays background', async () => {- const { plain } = await createCards()+ const { plain } = await scene.cards()await editor.canvas.waitForRender()- const gap = await at(plain, 100, 200)+ const gap = await scene.at(plain, 100, 200)await editor.canvas.hover(gap.x, gap.y)- expect((await state()).hovered).toBeNull()+ expect((await scene.state()).hovered).toBeNull()await editor.canvas.click(gap.x, gap.y)- expect((await state()).selected).toEqual([])+ expect((await scene.state()).selected).toEqual([])await editor.canvas.drag(gap.x, gap.y, gap.x + 60, gap.y + 40)- expect(await position(plain)).toEqual({ x: 400, y: 100 })+ expect(await scene.position(plain)).toEqual({ x: 400, y: 100 })editor.canvas.assertNoErrors()})test('repeated clicks at one point reach deeper layers, one level at a time', async () => {- const ids = await editor.page.evaluate(() => {- const store = window.openPencil?.getStore?.()- if (!store) throw new Error('OpenPencil store not initialized')- const fill = (r: number, g: number, b: number) => [- { type: 'SOLID' as const, color: { r, g, b, a: 1 }, opacity: 1, visible: true }- ]- const page = store.state.currentPageId- const board = store.graph.createNode('FRAME', page, {- name: 'Board',- x: 100,- y: 100,- width: 300,- height: 300,- fills: fill(1, 1, 1)- })- const grid = store.graph.createNode('FRAME', board.id, {- name: 'Grid',- x: 20,- y: 20,- width: 260,- height: 260,- fills: fill(0.95, 0.95, 0.95)- })- const cell = store.graph.createNode('FRAME', grid.id, {- name: 'Cell',- x: 40,- y: 40,- width: 80,- height: 80,- fills: fill(0.1, 0.1, 0.1)- })- const label = store.graph.createNode('RECTANGLE', cell.id, {- name: 'Label',- x: 20,- y: 20,- width: 40,- height: 40,- fills: fill(1, 1, 1)- })- store.clearSelection()- store.requestRender()- return { grid: grid.id, cell: cell.id, label: label.id }- })+ const ids = await scene.nestedBoard()await editor.canvas.waitForRender()- const point = await at(ids.label, 20, 20)+ const point = await scene.at(ids.label, 20, 20)for (const expected of [ids.grid, ids.cell, ids.label]) {await editor.canvas.click(point.x, point.y)- await expect.poll(async () => (await state()).selected).toEqual([expected])+ await expect.poll(async () => (await scene.state()).selected).toEqual([expected])// Apart enough not to count as a double-click, which goes one level deeper by itself.await editor.page.waitForTimeout(600)}editor.canvas.assertNoErrors()})++test('holding Cmd hovers the deepest layer, the one a Cmd-click selects', async () => {+ const ids = await scene.nestedBoard()+ await editor.canvas.waitForRender()+ const point = await scene.at(ids.label, 20, 20)++ await editor.canvas.hover(point.x, point.y)+ await expect.poll(async () => (await scene.state()).hovered).toBe(ids.grid)+ await editor.page.keyboard.down('Meta')+ await expect.poll(async () => (await scene.state()).hovered).toBe(ids.label)+ await editor.page.keyboard.up('Meta')+ await expect.poll(async () => (await scene.state()).hovered).toBe(ids.grid)+ editor.canvas.assertNoErrors()+})diff --git a/tests/engine/app/clipboard/memory.test.ts b/tests/engine/app/clipboard/memory.test.tsindex 1e533655b..e3a755426 100644--- a/tests/engine/app/clipboard/memory.test.ts+++ b/tests/engine/app/clipboard/memory.test.ts@@ -6,7 +6,9 @@ import {clearInMemoryClipboardHTML,getInMemoryClipboardHTML,hasInMemoryClipboardHTML,- setInMemoryClipboardHTML+ matchingClipboardSnapshot,+ setInMemoryClipboardHTML,+ setInMemoryClipboardPayload} from '@/app/editor/clipboard/memory'import { pasteClipboardToReplace } from '@/app/editor/clipboard/paste-to-replace'import { executeClipboardCommand, type SystemClipboard } from '@/app/editor/clipboard/system'@@ -32,6 +34,21 @@ const memoryIO: BrowserClipboardIO = {const memoryClipboard = createBrowserSystemClipboard(memoryIO)describe('in-memory clipboard', () => {+ test('recognizes its own copy after the browser rewrites the HTML', async () => {+ const store = createEditorStore()+ const rect = store.graph.createNode('RECTANGLE', store.state.currentPageId, { name: 'Card' })+ store.select([rect.id])+ const payload = await store.prepareCopy()+ setInMemoryClipboardPayload(payload)+ // What Chrome returns from navigator.clipboard.read(): double quotes and escaped markup.+ const rewritten = payload.html+ .replace("charset='utf-8'", 'charset="utf-8"')+ .replaceAll('<!--', '<!--')+ expect(rewritten).not.toBe(payload.html)+ expect(matchingClipboardSnapshot(rewritten)).toBe(payload.snapshot)+ expect(matchingClipboardSnapshot(rewritten.replace('(figma)', '(figma)A'))).toBeUndefined()+ })+test('stores, retrieves, and clears clipboard HTML', () => {expect(hasInMemoryClipboardHTML()).toBe(false)expect(getInMemoryClipboardHTML()).toBe('')diff --git a/tests/helpers/canvas/click-depth-driver.ts b/tests/helpers/canvas/click-depth-driver.tsnew file mode 100644index 000000000..1875adb69--- /dev/null+++ b/tests/helpers/canvas/click-depth-driver.ts@@ -0,0 +1,63 @@+import type { Page } from '@playwright/test'++import type * as ClickDepthScenes from '#tests/helpers/canvas/click-depth'++type SceneName = 'createClickDepthCards' | 'createNestedBoard'++/** Builds click-depth scenes and reads back what pointer input selected, hovered, or moved. */+/** `page` is read on each call, so a spec can create the driver before its page exists. */+export function clickDepthDriver(page: () => Page) {+ function build<Name extends SceneName>(name: Name) {+ return page().evaluate(async (scene) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const fixtureURL = '/tests/helpers/canvas/click-depth.ts'+ const scenes: typeof ClickDepthScenes = await import(fixtureURL)+ const ids = scenes[scene](store.graph, store.state.currentPageId)+ store.clearSelection()+ store.requestRender()+ return ids+ }, name) as Promise<ReturnType<(typeof ClickDepthScenes)[Name]>>+ }++ return {+ cards: () => build('createClickDepthCards'),+ nestedBoard: () => build('createNestedBoard'),++ /** Canvas coordinates of a point given relative to a node's top-left corner. */+ at(id: string, dx: number, dy: number) {+ return page().evaluate(+ ({ id, dx, dy }) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const abs = store.graph.getAbsolutePosition(id)+ const { zoom, panX, panY } = store.state+ return { x: (abs.x + dx) * zoom + panX, y: (abs.y + dy) * zoom + panY }+ },+ { id, dx, dy }+ )+ },++ state() {+ return page().evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ return { selected: [...store.state.selectedIds], hovered: store.state.hoveredNodeId }+ })+ },++ children(id: string) {+ return page().evaluate(+ (nodeId) => window.openPencil?.getStore?.().graph.getNode(nodeId)?.childIds ?? [],+ id+ )+ },++ position(id: string) {+ return page().evaluate((nodeId) => {+ const node = window.openPencil?.getStore?.().graph.getNode(nodeId)+ return node ? { x: node.x, y: node.y } : null+ }, id)+ }+ }+}diff --git a/tests/helpers/canvas/click-depth.ts b/tests/helpers/canvas/click-depth.tsnew file mode 100644index 000000000..d5c5ef573--- /dev/null+++ b/tests/helpers/canvas/click-depth.ts@@ -0,0 +1,82 @@+import type { Fill, SceneGraph } from '@open-pencil/scene-graph'++/** Scenes for click-depth specs, built in the browser on the editor's graph. */++function fill(r: number, g: number, b: number): Fill[] {+ return [{ type: 'SOLID', color: { r, g, b, a: 1 }, opacity: 1, visible: true }]+}++/** A top-level card with auto layout and one without, each holding a title and a button. */+export function createClickDepthCards(graph: SceneGraph, pageId: string) {+ const card = (name: string, x: number, layoutMode: 'VERTICAL' | 'NONE') => {+ const frame = graph.createNode('FRAME', pageId, {+ name,+ x,+ y: 100,+ width: 200,+ height: 240,+ fills: fill(1, 1, 1),+ layoutMode,+ itemSpacing: 24,+ paddingTop: 24,+ paddingRight: 24,+ paddingBottom: 24,+ paddingLeft: 24+ })+ graph.createNode('RECTANGLE', frame.id, {+ name: `${name} title`,+ x: 24,+ y: 24,+ width: 152,+ height: 40,+ fills: fill(0.85, 0.85, 0.9)+ })+ graph.createNode('RECTANGLE', frame.id, {+ name: `${name} button`,+ x: 24,+ y: 88,+ width: 152,+ height: 40,+ fills: fill(0.2, 0.4, 1)+ })+ return frame.id+ }+ return { auto: card('Auto card', 100, 'VERTICAL'), plain: card('Plain card', 400, 'NONE') }+}++/** A top-level board holding a grid, a cell, and a label, one inside the other. */+export function createNestedBoard(graph: SceneGraph, pageId: string) {+ const board = graph.createNode('FRAME', pageId, {+ name: 'Board',+ x: 100,+ y: 100,+ width: 300,+ height: 300,+ fills: fill(1, 1, 1)+ })+ const grid = graph.createNode('FRAME', board.id, {+ name: 'Grid',+ x: 20,+ y: 20,+ width: 260,+ height: 260,+ fills: fill(0.95, 0.95, 0.95)+ })+ const cell = graph.createNode('FRAME', grid.id, {+ name: 'Cell',+ x: 40,+ y: 40,+ width: 80,+ height: 80,+ fills: fill(0.1, 0.1, 0.1)+ })+ const label = graph.createNode('RECTANGLE', cell.id, {+ name: 'Label',+ x: 20,+ y: 20,+ width: 40,+ height: 40,+ fills: fill(1, 1, 1)+ })+ return { grid: grid.id, cell: cell.id, label: label.id }+}