AI-native design editor. Open-source Figma alternative.
fix: refuse component cycles, re-lay out text on font load, place pastes in rotated frames (#1076)
Danila Poyarkov066a9b29c5d7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex de3df4741..57a9ac545 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -223,6 +223,10 @@- Show when the browser menubar has more menus than fit in the left panel. The clipped side fades out and a chevron scrolls to the hidden menus; before, Arrange and Text could be cut off with no sign the bar scrolls.- List storage documents as soon as storage settings are saved. The home tab kept asking to configure storage until it next refreshed, which happened on window focus or up to a minute later.- Keep a Figma file's exposed nested instances when it is saved from OpenPencil; their properties stopped showing on the outer component's instances in Figma.+- Paste here and Paste to replace land where they should inside a frame that is offset, rotated, or flipped: Paste here centers on the cursor, and Paste to replace starts the replacement at the target's top-left corner, as in Figma, instead of centering it on canvas coordinates read as the frame's own.+- Reflow components and instances opened from a `.fig` file once a layer in them is edited, as Figma does: restyling the label of a Hug button, or changing a layer's size, now resizes the button instead of leaving it at the size the file saved.+- Size auto-width and auto-height text, and the Hug frames around it, with its real font once the face loads; text laid out while its weight, style, or characters were still loading kept a fallback size. The weight control now loads the face before applying it, as the family control does.+- Never let a component contain itself, as in Figma: an instance dragged, dropped or inserted into its own component, or into a component it shows, lands in the nearest frame that can hold it, and the plugin API's `appendChild` and `insertChild` throw Figma's cycle error.- Offer only components that fit in an instance swap's list: one that would contain itself, such as the component the swapped layer sits in, is left out, and a variant is named with its set, as in `Badge / State=Info`.- Undo a change to a property that drives several layers of an instance on all of them, and show an instance's value on a layer linked to that property after the instance was made.- Open S3 storage documents and show their previews on servers that answer a byte-range read with `200` instead of `206`, such as `rclone serve s3`. Previews failed to load, and the browser cached the partial reply as the whole document, so opening it failed with "Invalid fig-kiwi container". Storage requests now skip the browser cache, and a `200` whose `Content-Range` matches the request is accepted.diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.tsindex 674f07ba5..38ee4bd0a 100644--- a/packages/core/src/editor/clipboard.ts+++ b/packages/core/src/editor/clipboard.ts@@ -1,4 +1,4 @@-import { CommittedGraphEventError } from '@open-pencil/scene-graph'+import { CommittedGraphEventError, cycleSafeParent } from '@open-pencil/scene-graph'import type { SceneNode } from '@open-pencil/scene-graph'import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'@@ -14,16 +14,12 @@ import { importClipboardDependencies } from './clipboard/dependencies'import { createClipboardExportActions } from './clipboard/export'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 {- instanceSafeParent,- pastedComponentIds,- resolvePasteTarget-} from './clipboard/paste-target'+import type { PasteHistoryOperation } from './clipboard/paste/replace'+import { replaceTargetsWithCreated, selectedReplacementTargets } from './clipboard/paste/replace'+import { 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'+import { collectSubtrees, restoreSubtree, snapshotSubtree } from './history/subtree'import type { EditorContext } from './types'type PasteOptions = {@@ -192,14 +188,7 @@ export function createClipboardActions(ctx: EditorContext) {if (created.length === 0) return nullif (replacementTargets.length > 0) {- replaceTargetsWithCreated(- ctx,- placementActions.centerNodesAt,- created,- replacementTargets,- prevSelection,- operation- )+ replaceTargetsWithCreated(ctx, created, replacementTargets, prevSelection, operation)} else {placementActions.placeForeignPaste(created, pasteTarget, cursorPos)computeAllLayouts(ctx.graph, ctx.state.currentPageId)@@ -245,7 +234,7 @@ export function createClipboardActions(ctx: EditorContext) {}const requestedTarget = replacementTargets[0]?.parentId ?? resolvePasteTarget(ctx)- const pasteTarget = instanceSafeParent(+ const pasteTarget = cycleSafeParent(ctx.graph,requestedTarget,pastedComponentIds(ctx.graph, [...nodes, ...dependencies])@@ -281,13 +270,7 @@ export function createClipboardActions(ctx: EditorContext) {if (created.length === 0) return createdif (replacementTargets.length > 0) {- replaceTargetsWithCreated(- ctx,- placementActions.centerNodesAt,- created,- replacementTargets,- prevSelection- )+ replaceTargetsWithCreated(ctx, created, replacementTargets, prevSelection)return created}diff --git a/packages/core/src/editor/clipboard/assets.ts b/packages/core/src/editor/clipboard/assets.tsindex 1ca45be0f..5193cc21b 100644--- a/packages/core/src/editor/clipboard/assets.ts+++ b/packages/core/src/editor/clipboard/assets.ts@@ -3,7 +3,7 @@ import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'import Matrix from '@open-pencil/scene-graph/matrix'import { TRANSPARENT } from '#core/constants'-import { resolvePasteTarget } from '#core/editor/clipboard/paste-target'+import { resolvePasteTarget } from '#core/editor/clipboard/paste/target'import type { EditorContext } from '#core/editor/types'import { computeImageHash } from '#core/figma-api'import {diff --git a/packages/core/src/editor/clipboard/history.ts b/packages/core/src/editor/clipboard/history.tsindex 21a77c212..fc8d972af 100644--- a/packages/core/src/editor/clipboard/history.ts+++ b/packages/core/src/editor/clipboard/history.ts@@ -1,9 +1,8 @@import type { SceneNode } from '@open-pencil/scene-graph'+import { restoreSubtree } from '#core/editor/history/subtree'import type { EditorContext } from '#core/editor/types'-import { restoreSubtree } from './subtree-history'-export type DeletedEntry = {id: stringparentId: stringdiff --git a/packages/core/src/editor/clipboard/paste-replace.ts b/packages/core/src/editor/clipboard/paste/replace.tssimilarity index 70%rename from packages/core/src/editor/clipboard/paste-replace.tsrename to packages/core/src/editor/clipboard/paste/replace.tsindex 57bca3901..b77529b6d 100644--- a/packages/core/src/editor/clipboard/paste-replace.ts+++ b/packages/core/src/editor/clipboard/paste/replace.ts@@ -1,21 +1,25 @@+import { isNotNil } from 'es-toolkit/predicate'+import type { SceneNode } from '@open-pencil/scene-graph'-import { computeAbsoluteBounds } from '@open-pencil/scene-graph/geometry'+import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'import { getNodeEditCapability } from '#core/editor/capabilities'+import {+ deleteIds,+ type DeletedEntry,+ recreateSnapshots,+ restoreDeletedEntries+} from '#core/editor/clipboard/history'+import { collectSubtrees, snapshotSubtree } from '#core/editor/history/subtree'import type { EditorContext } from '#core/editor/types'import { computeAllLayouts } from '#core/layout'-import { deleteIds, type DeletedEntry, recreateSnapshots, restoreDeletedEntries } from './history'-import { collectSubtrees, snapshotSubtree } from './subtree-history'-export interface PasteHistoryOperation {capture: () => voidundo: () => voidredo: () => void}-type CenterNodesAt = (nodeIds: string[], cx: number, cy: number) => void-export function selectedReplacementTargets(ctx: EditorContext) {const selected = [...ctx.state.selectedIds].map((id) => ctx.graph.getNode(id))@@ -36,6 +40,9 @@ function reorderCreatedAtReplacementIndex(if (!insertParentId) returnconst insertIndex = deleted[0]?.index ?? 0for (let i = 0; i < created.length; i++) {+ // A paste that could not go into the target's parent, such as an instance of a component+ // the parent is inside, stays in the ancestor it went to.+ if (ctx.graph.getNode(created[i])?.parentId !== insertParentId) continuectx.graph.reorderChild(created[i], insertParentId, insertIndex + i)}}@@ -73,9 +80,21 @@ function pushPasteReplaceUndo(})}+/**+ * Moves the replacement so its box starts where the targets' box did, as Figma does, in the axes+ * of the parent it went into, so an offset, rotated, or flipped frame keeps it in their place.+ */+function alignWithTargets(ctx: EditorContext, created: string[], targets: SceneNode[]) {+ const nodes = created.map((id) => ctx.graph.getNode(id)).filter(isNotNil)+ const parentId = nodes[0]?.parentId ?? ctx.state.currentPageId+ const from = getAxisAlignedBoundsInParent(nodes, parentId, ctx.graph)+ const to = getAxisAlignedBoundsInParent(targets, parentId, ctx.graph)+ for (const node of nodes)+ ctx.graph.updateNode(node.id, { x: node.x + to.x - from.x, y: node.y + to.y - from.y })+}+export function replaceTargetsWithCreated(ctx: EditorContext,- centerNodesAt: CenterNodesAt,created: string[],targets: SceneNode[],prevSelection: Set<string>,@@ -93,12 +112,7 @@ export function replaceTargetsWithCreated(}})- const targetBounds = computeAbsoluteBounds(targets, (id) => ctx.graph.getAbsolutePosition(id))- centerNodesAt(- created,- targetBounds.x + targetBounds.width / 2,- targetBounds.y + targetBounds.height / 2- )+ alignWithTargets(ctx, created, targets)reorderCreatedAtReplacementIndex(ctx, created, deleted)for (const { id } of deleted) ctx.graph.deleteNode(id)computeAllLayouts(ctx.graph, ctx.state.currentPageId)diff --git a/packages/core/src/editor/clipboard/paste-target.ts b/packages/core/src/editor/clipboard/paste/target.tssimilarity index 74%rename from packages/core/src/editor/clipboard/paste-target.tsrename to packages/core/src/editor/clipboard/paste/target.tsindex c7e223b63..d7e547547 100644--- a/packages/core/src/editor/clipboard/paste-target.ts+++ b/packages/core/src/editor/clipboard/paste/target.ts@@ -1,4 +1,4 @@-import { canCreateInstance, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { CONTAINER_TYPES } from '@open-pencil/scene-graph/node-defaults'import { acceptingParent } from '#core/editor/components/slots'@@ -36,18 +36,3 @@ export function pastedComponentIds(graph: SceneGraph, trees: readonly PastedTreefor (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 29bb96b11..4859d637f 100644--- a/packages/core/src/editor/clipboard/placement.ts+++ b/packages/core/src/editor/clipboard/placement.ts@@ -1,8 +1,13 @@import { isNotNil } from 'es-toolkit/predicate'import type { SceneNode } from '@open-pencil/scene-graph'-import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'+import {+ getAxisAlignedBoundsInParent,+ getParentWorldMatrix,+ getWorldMatrix+} from '@open-pencil/scene-graph/coordinate'import { computeBounds } from '@open-pencil/scene-graph/geometry'+import Matrix from '@open-pencil/scene-graph/matrix'import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import { DUPLICATE_FRAME_GAP } from '#core/constants'@@ -98,11 +103,11 @@ export function createClipboardPlacementActions(ctx: EditorContext) {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- })+ centerNodesAtCanvasPoint(+ nodeIds,+ parentId,+ Matrix.mapPoint(getWorldMatrix(over, ctx.graph), { x: over.width / 2, y: over.height / 2 })+ )}/**@@ -152,12 +157,11 @@ export function createClipboardPlacementActions(ctx: EditorContext) {}}- /** Centers layers of `parentId` on a canvas point. */+ /** Centers layers of `parentId` on a canvas point, through the parent's rotation and flips. */function centerNodesAtCanvasPoint(nodeIds: string[], parentId: string, point: Vector) {- const parent = ctx.graph.getNode(parentId)- const origin =- parent && parent.type !== 'CANVAS' ? ctx.graph.getAbsolutePosition(parentId) : { x: 0, y: 0 }- centerNodesAt(nodeIds, point.x - origin.x, point.y - origin.y)+ const toParent = Matrix.invert(getParentWorldMatrix(ctx.graph.getNode(parentId), ctx.graph))+ const local = toParent ? Matrix.mapPoint(toParent, point) : point+ centerNodesAt(nodeIds, local.x, local.y)}return {diff --git a/packages/core/src/editor/components/instances.ts b/packages/core/src/editor/components/instances.tsindex 92ff10d4e..e2cd6819d 100644--- a/packages/core/src/editor/components/instances.ts+++ b/packages/core/src/editor/components/instances.ts@@ -1,4 +1,4 @@-import { cloneInstanceOverrideState } from '@open-pencil/scene-graph'+import { canCreateInstance, cloneInstanceOverrideState } from '@open-pencil/scene-graph'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'@@ -65,6 +65,7 @@ export function createComponentInstanceActions(ctx: EditorContext) {) {const component = ctx.graph.getNode(componentId)if (component?.type !== 'COMPONENT') return null+ if (!canCreateInstance(ctx.graph, componentId, parentId)) return nullif (!prepareSlotEdits(ctx, [parentId])) return nullconst previousSelection = new Set(ctx.state.selectedIds)diff --git a/packages/core/src/editor/components/slots/history.ts b/packages/core/src/editor/components/slots/history.tsindex 32ce242bf..9e67d905d 100644--- a/packages/core/src/editor/components/slots/history.ts+++ b/packages/core/src/editor/components/slots/history.ts@@ -1,6 +1,6 @@import type { SceneNode } from '@open-pencil/scene-graph'-import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'+import { restoreSubtree, snapshotSubtree } from '#core/editor/history/subtree'import type { EditorContext } from '#core/editor/types'/** Put back a recorded subtree in place of the live one, at the same position. */diff --git a/packages/core/src/editor/components/variants/add.ts b/packages/core/src/editor/components/variants/add.tsindex 68bd03c24..65b567c84 100644--- a/packages/core/src/editor/components/variants/add.ts+++ b/packages/core/src/editor/components/variants/add.ts@@ -2,8 +2,8 @@ import { createComponentPropertyId, type SceneNode } from '@open-pencil/scene-grimport { buildVariantName } from '@open-pencil/scene-graph/variant-name'import { assertNodeEditable } from '#core/editor/capabilities'-import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'import { VARIANT_SET_PADDING, variantSetProps } from '#core/editor/components/variant-set'+import { restoreSubtree, snapshotSubtree } from '#core/editor/history/subtree'import { wrapSelectionInContainer } from '#core/editor/structure/container-wrap'import type { EditorContext } from '#core/editor/types'diff --git a/packages/core/src/editor/components/variants/index.ts b/packages/core/src/editor/components/variants/index.tsindex 7614a7dfe..409000d41 100644--- a/packages/core/src/editor/components/variants/index.ts+++ b/packages/core/src/editor/components/variants/index.ts@@ -2,8 +2,8 @@ import type { ComponentPropertyDefinition, ComponentPropertyType } from '@open-pimport { buildVariantName, parseVariantName } from '@open-pencil/scene-graph/variant-name'import { assertNodeEditable } from '#core/editor/capabilities'-import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'import { reapplyInstanceComponentProperties } from '#core/editor/components/properties'+import { restoreSubtree, snapshotSubtree } from '#core/editor/history/subtree'import type { EditorContext } from '#core/editor/types'import { addVariant, appendVariant } from './add'diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex 77af3fbdf..f0760ee1d 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -49,6 +49,7 @@ import { createShapeActions } from './shapes'import { createDefaultEditorState } from './state'import { createStructureActions } from './structure'import { createTextActions } from './text'+import { createPendingTextLayout } from './text/pending-layout'import type {EditorContext,EditorEventName,@@ -82,6 +83,7 @@ export function createEditor(options?: EditorOptions) {let _textEditor: TextEditor | null = nullconst events: Emitter<EditorEvents> = createNanoEvents()const stopFontResolutionEvents = fontResolver.subscribe((event, snapshot) => {+ if (event === 'settled') pendingTextLayout.relayoutReady(_renderer)events.emit('font:resolution-changed', event, snapshot)})@@ -198,6 +200,11 @@ export function createEditor(options?: EditorOptions) {const graphReads = createGraphReadActions(() => _graph)const { runLayoutForNode, runMutationWithLayout } = createLayoutRunner(() => _graph)+ const pendingTextLayout = createPendingTextLayout({+ getGraph: () => _graph,+ runLayoutForNode,+ requestRender+ })const { scheduleComponentSync } = createComponentSyncScheduler(() => _graph, requestRender)const { subscribeToGraph, unsubscribeFromGraph } = createGraphEventSubscription({@@ -297,7 +304,9 @@ export function createEditor(options?: EditorOptions) {uninstallTextMeasurer?.()uninstallTextMeasurer =typeof renderer.measureTextNode === 'function'- ? installTextMeasurer((node, maxWidth) => renderer.measureTextNode(node, maxWidth))+ ? installTextMeasurer((node, maxWidth) =>+ pendingTextLayout.measure(renderer, node, maxWidth)+ ): null}@@ -318,6 +327,7 @@ export function createEditor(options?: EditorOptions) {nodes.cancelNodePreviews()undo.discardBatches()_graph = newGraph+ pendingTextLayout.clear()subscribeToGraph()const previousPageId = state.currentPageIdstate.currentPageId = _graph.getPages()[0]?.id ?? _graph.rootIddiff --git a/packages/core/src/editor/clipboard/subtree-history.ts b/packages/core/src/editor/history/subtree.tssimilarity index 100%rename from packages/core/src/editor/clipboard/subtree-history.tsrename to packages/core/src/editor/history/subtree.tsdiff --git a/packages/core/src/editor/icons.ts b/packages/core/src/editor/icons.tsindex ea5caa68e..81374bb4c 100644--- a/packages/core/src/editor/icons.ts+++ b/packages/core/src/editor/icons.ts@@ -2,7 +2,7 @@ import { readIcon, type SceneNode } from '@open-pencil/scene-graph'import { BLACK } from '@open-pencil/scene-graph/constants'import type { Color } from '@open-pencil/scene-graph/primitives'-import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'+import { restoreSubtree, snapshotSubtree } from '#core/editor/history/subtree'import type { EditorContext } from '#core/editor/types'import { pushCreatedSubtreesUndo } from '#core/editor/undo'import { detachIcon, placeIcon, recolorIcon, swapIcon } from '#core/icons/render'diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex d1ba9f98b..f6e804210 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -28,7 +28,7 @@ export { isEmptyPageChange } from './history/page-change'export type { PageSnapshot } from './history/snapshot'export { graphFromPageChange, graphFromPageSnapshot } from './history/snapshot-graph'export type { ClipboardPayload, ClipboardSnapshot } from './clipboard/copy'-export { resolvePasteTarget } from './clipboard/paste-target'+export { resolvePasteTarget } from './clipboard/paste/target'export { playIslandRoots } from './play/islands'export { resolvePlayState, type InstanceState } from './play/states'export type { PlayState } from './play/actions'diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.tsindex db06f59c6..c07a91f52 100644--- a/packages/core/src/editor/structure.ts+++ b/packages/core/src/editor/structure.ts@@ -1,4 +1,4 @@-import type { SceneNode } from '@open-pencil/scene-graph'+import { createsComponentCycle, type SceneNode } from '@open-pencil/scene-graph'import { acceptingParent, acceptsChildren, prepareSlotEdits } from '#core/editor/components/slots'import { fitEnclosingGroupsWithUndo } from '#core/editor/structure/group-bounds'@@ -31,16 +31,20 @@ export function createStructureActions(ctx: EditorContext) {return !parentId || parentId === ctx.graph.rootId || parentId === ctx.state.currentPageId}- /** Moves layers under a new parent; refuses the locked part of an instance. */+ /**+ * Moves layers under a new parent; refuses the locked part of an instance, and a layer that+ * would make a component contain itself, as Figma does.+ */function reparentNodes(nodeIds: string[], newParentId: string): boolean {const parent = ctx.graph.getNode(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'+ (ctx.graph.getNode(id)?.type !== 'SECTION' ||+ !parent ||+ parent.type === 'CANVAS' ||+ parent.type === 'SECTION') &&+ !createsComponentCycle(ctx.graph, id, newParentId))if (movable.length === 0) return trueconst parents = new Set([newParentId])diff --git a/packages/core/src/editor/structure/boolean.ts b/packages/core/src/editor/structure/boolean.tsindex 7d662133f..1eed13053 100644--- a/packages/core/src/editor/structure/boolean.ts+++ b/packages/core/src/editor/structure/boolean.ts@@ -9,7 +9,7 @@ import {import { copyFills } from '@open-pencil/scene-graph/copy'import { canMakeBooleanSourceNode, groupFitOptions } from '#core/canvas/boolean'-import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'+import { restoreSubtree, snapshotSubtree } from '#core/editor/history/subtree'import { newLayerDefaults } from '#core/editor/shapes/defaults'import type { EditorContext } from '#core/editor/types'diff --git a/packages/core/src/editor/structure/flatten.ts b/packages/core/src/editor/structure/flatten.tsindex f7a540ec8..934bfaf85 100644--- a/packages/core/src/editor/structure/flatten.ts+++ b/packages/core/src/editor/structure/flatten.ts@@ -2,7 +2,7 @@ import type { SceneNode } from '@open-pencil/scene-graph'import { canMakeBooleanSourceNode, hasVisibleStrokeSourceNode } from '#core/canvas/boolean'import { flattenNodesToVectorProps, outlineStrokeNodesToVectorProps } from '#core/canvas/flatten'-import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'+import { restoreSubtree, snapshotSubtree } from '#core/editor/history/subtree'import type { EditorContext } from '#core/editor/types'import { selectedNodesInSharedParent } from './selection'diff --git a/packages/core/src/editor/text/pending-layout.ts b/packages/core/src/editor/text/pending-layout.tsnew file mode 100644index 000000000..45b587e4e--- /dev/null+++ b/packages/core/src/editor/text/pending-layout.ts@@ -0,0 +1,62 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import type { SkiaRenderer } from '#core/canvas/renderer'+import { isNodeFontLoaded } from '#core/canvas/text'++export type PendingLayoutRenderer = Pick<SkiaRenderer, 'measureTextNode' | 'fontsLoaded'> &+ Parameters<typeof isNodeFontLoaded>[0]++interface PendingTextLayoutContext {+ getGraph: () => SceneGraph+ runLayoutForNode: (id: string) => void+ requestRender: () => void+ /** Whether the renderer can measure this layer with its own faces. */+ isReady?: (renderer: PendingLayoutRenderer, node: SceneNode) => boolean+}++function facesLoaded(renderer: PendingLayoutRenderer, node: SceneNode): boolean {+ return renderer.fontsLoaded && isNodeFontLoaded(renderer, node)+}++/**+ * Text measured before its face loaded is laid out with an estimate. Remember those layers and+ * lay them out again once their faces settle, so auto-sized text and the Hug frames around it+ * take their real size without adding an undo step. Layout of the document's own state stays+ * derived.+ */+export function createPendingTextLayout(ctx: PendingTextLayoutContext) {+ /** Layer id → whether it was measured while laying out the document's own state. */+ const pending = new Map<string, boolean>()+ const ready = ctx.isReady ?? facesLoaded++ function measure(renderer: PendingLayoutRenderer, node: SceneNode, maxWidth?: number) {+ const size = renderer.measureTextNode(node, maxWidth)+ if (!size && node.type === 'TEXT' && node.text && !ready(renderer, node)) {+ const graph = ctx.getGraph()+ pending.set(node.id, (pending.get(node.id) ?? true) && graph.isApplyingDerivedLayout)+ }+ return size+ }++ function relayoutReady(renderer: PendingLayoutRenderer | null) {+ if (!renderer || pending.size === 0) return+ const graph = ctx.getGraph()+ const edited: string[] = []+ const derived: string[] = []+ for (const [id, isDerived] of pending) {+ const node = graph.getNode(id)+ if (node && !ready(renderer, node)) continue+ pending.delete(id)+ if (node) (isDerived ? derived : edited).push(id)+ }+ if (edited.length === 0 && derived.length === 0) return+ if (derived.length > 0)+ graph.applyDerivedLayoutDuring(() => {+ for (const id of derived) ctx.runLayoutForNode(id)+ })+ for (const id of edited) ctx.runLayoutForNode(id)+ ctx.requestRender()+ }++ return { measure, relayoutReady, clear: () => pending.clear() }+}diff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.tsindex a8736c1db..ce5f15430 100644--- a/packages/core/src/editor/undo.ts+++ b/packages/core/src/editor/undo.ts@@ -9,7 +9,6 @@ import type { UndoEntry } from '@open-pencil/scene-graph/undo'import { textAutoResizeChanges } from '#core/layout/text-auto-resize'import { assertNodeEditable } from './capabilities'-import { restoreSubtree, snapshotSubtree } from './clipboard/subtree-history'import {capturePageChange as startPageChange,restorePageChange as applyPageChangeToEditor,@@ -21,6 +20,7 @@ import {snapshotPage as createPageSnapshot,type PageSnapshot} from './history/snapshot'+import { restoreSubtree, snapshotSubtree } from './history/subtree'import type { EditorContext } from './types'/** A layer's place for a move: position, parent, and slot among the parent's children. */diff --git a/packages/core/src/editor/vectorize.ts b/packages/core/src/editor/vectorize.tsindex 8f9d23a3a..b6fd75195 100644--- a/packages/core/src/editor/vectorize.ts+++ b/packages/core/src/editor/vectorize.ts@@ -1,7 +1,7 @@import type { SceneNode } from '@open-pencil/scene-graph'import { copyEffects, copyStrokes } from '@open-pencil/scene-graph/copy'-import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'+import { restoreSubtree, snapshotSubtree } from '#core/editor/history/subtree'import type { EditorContext } from '#core/editor/types'import {createVectorFrameChildren,diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex 384ffa8a2..e36b1a82c 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -1,4 +1,8 @@-import { recordInstanceOverride, slotPropertyId } from '@open-pencil/scene-graph'+import {+ createsComponentCycle,+ recordInstanceOverride,+ slotPropertyId+} from '@open-pencil/scene-graph'import type {GroupFitOptions,SceneGraph,@@ -66,6 +70,17 @@ export interface NodeProxyHost {export { MIXED }+/** Figma refuses a move that would make a component contain itself. */+function assertNoComponentCycle(+ graph: SceneGraph,+ parentId: string,+ childId: string,+ method: 'appendChild' | 'insertChild'+): void {+ if (createsComponentCycle(graph, childId, parentId))+ throw new Error(`in ${method}: Cannot move node. Reparenting would create a component cycle`)+}+export class FigmaNodeProxy {[INTERNAL_ID]: string;[INTERNAL_GRAPH]: SceneGraph;@@ -370,6 +385,12 @@ export class FigmaNodeProxy {appendChild(child: FigmaNodeProxy): void {assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])assertNodeEditable(this[INTERNAL_GRAPH], child[INTERNAL_ID])+ assertNoComponentCycle(+ this[INTERNAL_GRAPH],+ this[INTERNAL_ID],+ child[INTERNAL_ID],+ 'appendChild'+ )prepareSlotMove(this[INTERNAL_GRAPH], this[INTERNAL_ID], child[INTERNAL_ID], 'appendChild')this._reparentAndFit(child[INTERNAL_ID])}@@ -394,6 +415,12 @@ export class FigmaNodeProxy {insertChild(index: number, child: FigmaNodeProxy): void {assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])assertNodeEditable(this[INTERNAL_GRAPH], child[INTERNAL_ID])+ assertNoComponentCycle(+ this[INTERNAL_GRAPH],+ this[INTERNAL_ID],+ child[INTERNAL_ID],+ 'insertChild'+ )prepareSlotMove(this[INTERNAL_GRAPH], this[INTERNAL_ID], child[INTERNAL_ID], 'insertChild')this._reparentAndFit(child[INTERNAL_ID])this[INTERNAL_GRAPH].reorderChild(child[INTERNAL_ID], this[INTERNAL_ID], index)diff --git a/packages/core/src/layout/derived.ts b/packages/core/src/layout/derived.tsindex 11b30b187..d9d80cad7 100644--- a/packages/core/src/layout/derived.ts+++ b/packages/core/src/layout/derived.ts@@ -53,10 +53,10 @@ export function markFlowChanged(graph: SceneGraph, parentId: string): void {}/**- * Whether layout still keeps the geometry saved for `frame` and its flow. Any frame stops once a- * layer joins, leaves, or moves in its flow or a flow inside it; a frame read from a .fig file- * also stops once it or a layer in its flow has its layout edited, such as by adding auto layout- * or a gap. Other frames otherwise keep geometry copied with them, as an instance's layers do.+ * Whether layout still keeps the geometry saved for `frame` and its flow. A frame stops once a+ * layer joins, leaves, or moves in its flow or a flow inside it, or once it or a layer in its flow+ * has its layout edited, such as by adding auto layout or a gap or restyling text. That holds for+ * layers read without a source format too, as a .fig file's components and instances are.*/export function keepsSavedLayout(graph: SceneGraph, frame: SceneNode): boolean {const fromFig = frame.source.format === 'fig'@@ -73,8 +73,6 @@ export function keepsSavedLayout(graph: SceneGraph, frame: SceneNode): boolean {stale.add(frame.id)return false}- // Geometry copied with other layers, as an instance's are, stays until their structure changes.- if (!fromFig) return true// A flow inside edited by now resizes this one, but a cancelled preview gives it back.const last = graphState(reflowed, graph, () => new Set<string>())const keeps =diff --git a/packages/core/tests/editor/clipboard/binding-corruption.test.ts b/packages/core/tests/editor/clipboard/binding-corruption.test.tsindex 1d00fed49..63ee6017c 100644--- a/packages/core/tests/editor/clipboard/binding-corruption.test.ts+++ b/packages/core/tests/editor/clipboard/binding-corruption.test.ts@@ -3,7 +3,7 @@ import { describe, expect, test } from 'bun:test'import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'import { SceneGraph } from '@open-pencil/core'-import { collectSubtrees } from '@open-pencil/core/editor/clipboard/subtree-history'+import { collectSubtrees } from '#core/editor/history/subtree'import { createInstanceOverrideState } from '@open-pencil/scene-graph'function pageId(graph: SceneGraph): string {diff --git a/packages/core/tests/editor/clipboard/paste-to-replace.test.ts b/packages/core/tests/editor/clipboard/paste/replace.test.tssimilarity index 73%rename from packages/core/tests/editor/clipboard/paste-to-replace.test.tsrename to packages/core/tests/editor/clipboard/paste/replace.test.tsindex ff8678988..642ba2116 100644--- a/packages/core/tests/editor/clipboard/paste-to-replace.test.ts+++ b/packages/core/tests/editor/clipboard/paste/replace.test.ts@@ -62,8 +62,8 @@ describe('paste to replace', () => {const created = editor.graph.getNode(createdId)expect(created?.name).toBe('Pasted')expect(created?.parentId).toBe(pageId)- expect(created?.x).toBe(110)- expect(created?.y).toBe(110)+ expect(created?.x).toBe(100)+ expect(created?.y).toBe(100)})test('undo and redo preserve replaced and pasted subtrees', async () => {@@ -168,6 +168,54 @@ describe('paste to replace', () => {expect(editor.graph.getNode(frame.id)?.childIds).toEqual([before.id, createdId, after.id])})+ test('starts the replacement where the target started, inside an offset, rotated, or flipped frame', async () => {+ const html = copiedRectangleHTML()+ const editor = createEditor()+ const frame = editor.graph.createNode('FRAME', editor.state.currentPageId, {+ x: 50,+ y: 50,+ width: 300,+ height: 300+ })+ const target = createTarget(editor, frame.id)+ for (const transform of [{}, { rotation: 90 }, { rotation: 0, flipY: true }]) {+ editor.graph.updateNode(frame.id, transform)+ editor.select([target.id])+ await editor.pasteFromHTML(html, undefined, { replaceSelection: true })+ // Figma keeps the target's top-left rather than its centre (desktop 126).+ expect(editor.graph.getNode([...editor.state.selectedIds][0])).toMatchObject({+ parentId: frame.id,+ x: 100,+ y: 100+ })+ editor.undo.undo()+ }+ })++ test('an instance replacing a layer inside its own component stays out of it', async () => {+ const editor = createEditor()+ const page = editor.state.currentPageId+ const card = editor.graph.createNode('COMPONENT', page, { name: 'Card', width: 200, height: 200 })+ const inner = editor.graph.createNode('FRAME', card.id, { name: 'Inner', width: 100, height: 100 })+ const target = createTarget(editor, inner.id)+ const instance = editor.graph.createInstance(card.id, page, { x: 400 })+ if (!instance) throw new Error('Expected an instance')+ editor.select([instance.id])+ const { snapshot } = await editor.prepareCopy()+ if (!snapshot) throw new Error('Missing snapshot')++ editor.select([target.id])+ await editor.pasteSnapshot(snapshot, undefined, { replaceSelection: true })+ const created = editor.graph.getNode([...editor.state.selectedIds][0])+ expect(created).toMatchObject({ type: 'INSTANCE', componentId: card.id, parentId: page })+ expect(inner.childIds).toEqual([])++ editor.undo.undo()+ editor.undo.redo()+ expect(editor.graph.getNode(created?.id ?? '')?.parentId).toBe(page)+ expect(inner.childIds).toEqual([])+ })+test('preserves pasted child subtrees', async () => {const html = copiedFrameHTML()const editor = createEditor()diff --git a/packages/core/tests/editor/clipboard/paste-target.test.ts b/packages/core/tests/editor/clipboard/paste/target.test.tssimilarity index 99%rename from packages/core/tests/editor/clipboard/paste-target.test.tsrename to packages/core/tests/editor/clipboard/paste/target.test.tsindex ed47746c7..5dad71b69 100644--- a/packages/core/tests/editor/clipboard/paste-target.test.ts+++ b/packages/core/tests/editor/clipboard/paste/target.test.ts@@ -6,7 +6,7 @@ import {} from '@open-pencil/core/editor'import { SceneGraph } from '@open-pencil/scene-graph'-import { resolvePasteTarget } from '#core/editor/clipboard/paste-target'+import { resolvePasteTarget } from '#core/editor/clipboard/paste/target'function setup() {const graph = new SceneGraph()diff --git a/packages/core/tests/editor/clipboard/placement.test.ts b/packages/core/tests/editor/clipboard/placement.test.tsindex ea072daf8..c293e7bdf 100644--- a/packages/core/tests/editor/clipboard/placement.test.ts+++ b/packages/core/tests/editor/clipboard/placement.test.ts@@ -2,6 +2,8 @@ import { afterEach, describe, expect, test } from 'bun:test'import { createEditor, type Editor } from '@open-pencil/core/editor'import type { SceneNode } from '@open-pencil/scene-graph'+import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'+import Matrix from '@open-pencil/scene-graph/matrix'// Each case matches Cmd+D or Cmd+V observed in Figma desktop 126.@@ -18,6 +20,15 @@ function node(type: SceneNode['type'], parentId: string, props: Partial<SceneNodreturn editor.graph.createNode(type, parentId, { width: 40, height: 40, ...props })}+/** Where a layer's centre is drawn on the canvas. */+function worldCenter(layer: SceneNode) {+ const center = Matrix.mapPoint(getWorldMatrix(layer, editor.graph), {+ x: layer.width / 2,+ y: layer.height / 2+ })+ return { x: Math.round(center.x), y: Math.round(center.y) }+}+function selected() {const [id] = editor.state.selectedIdsconst found = editor.graph.getNode(id)@@ -161,6 +172,20 @@ describe('paste placement', () => {expect(selected()).toMatchObject({ parentId: target.id, x: 80, y: 80 })})+ test('Paste here centers on the cursor inside a rotated or flipped frame', async () => {+ const page = setup()+ const box = node('RECTANGLE', page, { width: 50, height: 30 })+ const target = node('FRAME', page, { x: 300, y: 100, width: 200, height: 200 })+ const snapshot = await copy(box.id)+ for (const transform of [{ rotation: 90 }, { rotation: 0, flipX: true }]) {+ editor.graph.updateNode(target.id, transform)+ editor.select([target.id])+ await editor.pasteSnapshot(snapshot, { x: 420, y: 160 })+ expect(selected().parentId).toBe(target.id)+ expect(worldCenter(selected())).toEqual({ x: 420, y: 160 })+ }+ })+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 })diff --git a/packages/core/tests/editor/components/cycles.test.ts b/packages/core/tests/editor/components/cycles.test.tsnew file mode 100644index 000000000..9915df051--- /dev/null+++ b/packages/core/tests/editor/components/cycles.test.ts@@ -0,0 +1,47 @@+import { expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { createEditor } from '@open-pencil/core/editor'+import { FigmaAPI } from '@open-pencil/core/figma-api'++/** Button holds an Inner frame; Card shows a Button. */+function setup() {+ const editor = createEditor()+ const page = editor.state.currentPageId+ const button = editor.graph.createNode('COMPONENT', page, { name: 'Button' })+ const inner = editor.graph.createNode('FRAME', button.id, { name: 'Inner' })+ const card = editor.graph.createNode('COMPONENT', page, { name: 'Card' })+ editor.graph.createInstance(button.id, card.id)+ const instance = expectDefined(editor.graph.createInstance(card.id, page))+ return { editor, page, button, inner, card, instance }+}++test('moving a layer where its component would contain itself leaves it in place', () => {+ const { editor, page, button, inner, instance } = setup()+ editor.reparentNodes([instance.id], inner.id)+ expect(instance.parentId).toBe(page)+ expect(button.childIds).toEqual([inner.id])+})++test('placing an instance inside its own component creates nothing', () => {+ const { editor, card, inner } = setup()+ const before = editor.graph.nodes.size+ expect(editor.createInstanceFromComponent(card.id, 0, 0, inner.id)).toBeNull()+ expect(editor.graph.nodes.size).toBe(before)+ expect(editor.undo.canUndo).toBe(false)+})++test('the plugin API rejects a move that creates a component cycle, as Figma does', () => {+ const { editor, inner, instance } = setup()+ const figma = new FigmaAPI(editor.graph)+ const parent = expectDefined(figma.getNodeById(inner.id))+ const child = expectDefined(figma.getNodeById(instance.id))+ // Message recorded in Figma.+ expect(() => parent.appendChild(child)).toThrow(+ 'in appendChild: Cannot move node. Reparenting would create a component cycle'+ )+ expect(() => parent.insertChild(0, child)).toThrow(+ 'in insertChild: Cannot move node. Reparenting would create a component cycle'+ )+})diff --git a/packages/core/tests/editor/text-auto-resize.test.ts b/packages/core/tests/editor/text/auto-resize.test.tssimilarity index 98%rename from packages/core/tests/editor/text-auto-resize.test.tsrename to packages/core/tests/editor/text/auto-resize.test.tsindex a3242db3a..5dd82fc2c 100644--- a/packages/core/tests/editor/text-auto-resize.test.ts+++ b/packages/core/tests/editor/text/auto-resize.test.ts@@ -3,7 +3,7 @@ import { afterEach, describe, expect, test } from 'bun:test'import { createEditor } from '@open-pencil/core/editor'import { setTextMeasurer } from '@open-pencil/core/layout'-import { getNodeOrThrow } from '../helpers/assert'+import { getNodeOrThrow } from '#core-tests/helpers/assert'afterEach(() => {setTextMeasurer(null)diff --git a/packages/core/tests/editor/text/pending-layout.test.ts b/packages/core/tests/editor/text/pending-layout.test.tsnew file mode 100644index 000000000..f92652f02--- /dev/null+++ b/packages/core/tests/editor/text/pending-layout.test.ts@@ -0,0 +1,101 @@+import { afterEach, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import { setTextMeasurer } from '@open-pencil/core/layout'++import {+ createPendingTextLayout,+ type PendingLayoutRenderer+} from '#core/editor/text/pending-layout'+import { createLayoutRunner } from '#core/layout/mutations'++afterEach(() => {+ setTextMeasurer(null)+})++/** A Hug row around auto-width text whose face loads after the first layout. */+function setup() {+ const editor = createEditor()+ const graph = editor.graph+ const frame = graph.createNode('FRAME', editor.state.currentPageId, {+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ paddingLeft: 16,+ paddingRight: 16,+ paddingTop: 12,+ paddingBottom: 12+ })+ const text = graph.createNode('TEXT', frame.id, {+ text: 'Weighted label',+ fontWeight: 900,+ textAutoResize: 'WIDTH_AND_HEIGHT'+ })+ let loaded = false+ const renderer: PendingLayoutRenderer = {+ fontsLoaded: true,+ measureTextNode: () => (loaded ? { width: 234, height: 29 } : null)+ }+ const { runLayoutForNode } = createLayoutRunner(() => graph)+ let renders = 0+ /** Whether each layout the pending text ran was the document's own. */+ const relayouts: boolean[] = []+ const pending = createPendingTextLayout({+ getGraph: () => graph,+ runLayoutForNode: (id) => {+ relayouts.push(graph.isApplyingDerivedLayout)+ runLayoutForNode(id)+ },+ requestRender: () => renders++,+ isReady: () => loaded+ })+ setTextMeasurer((node, maxWidth) => pending.measure(renderer, node, maxWidth))+ const load = () => {+ loaded = true+ pending.relayoutReady(renderer)+ }+ return {+ editor,+ graph,+ frame,+ text,+ renderer,+ pending,+ runLayoutForNode,+ load,+ relayouts,+ renders: () => renders+ }+}++test('text laid out before its face loads takes its size, and its Hug frame follows', () => {+ const { editor, frame, text, runLayoutForNode, load, relayouts, renders } = setup()+ runLayoutForNode(text.id)+ const estimated = text.width+ expect(estimated).not.toBe(234)++ load()+ expect([text.width, text.height]).toEqual([234, 29])+ expect([frame.width, frame.height]).toEqual([266, 53])+ expect(renders()).toBe(1)+ expect(relayouts).toEqual([false])+ expect(editor.undo.canUndo).toBe(false)+})++test('a face that loads keeps the layout of the document’s own state derived', () => {+ const { graph, text, runLayoutForNode, load, relayouts } = setup()+ graph.applyDerivedLayoutDuring(() => runLayoutForNode(text.id))+ load()+ expect(text.width).toBe(234)+ expect(relayouts).toEqual([true])+})++test('layers whose faces are still loading or that were removed are left alone', () => {+ const { graph, text, pending, renderer, runLayoutForNode, renders } = setup()+ runLayoutForNode(text.id)+ pending.relayoutReady(renderer)+ expect(renders()).toBe(0)+ graph.deleteNode(text.id)+ pending.relayoutReady(renderer)+ expect(renders()).toBe(0)+})diff --git a/packages/core/tests/layout/auto-layout/saved-geometry.test.ts b/packages/core/tests/layout/auto-layout/saved-geometry.test.tsindex 2dabaaa03..01429227e 100644--- a/packages/core/tests/layout/auto-layout/saved-geometry.test.ts+++ b/packages/core/tests/layout/auto-layout/saved-geometry.test.ts@@ -179,3 +179,36 @@ test('a layer moved into a frame with saved geometry resizes it, even before itexpect([badge.width, badge.height]).toEqual([34, 21])editor.dispose()})++test('a component read from a .fig file reflows once a layer in it is edited, but not before', () => {+ const editor = createEditor()+ const { graph } = editor+ // A component's layers as a .fig file loads them: saved sizes, but no source format.+ let button: SceneNode | undefined+ let label: SceneNode | undefined+ graph.applyImportedStateDuring(() => {+ button = graph.createNode('COMPONENT', editor.state.currentPageId, {+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ paddingLeft: 20,+ paddingRight: 20,+ width: 244,+ height: 40,+ derivedLayout: { x: 0, y: 0, width: 244, height: 40 }+ })+ label = graph.createNode('RECTANGLE', button.id, {+ x: 20,+ width: 204,+ height: 40,+ derivedLayout: { x: 20, y: 0, width: 204, height: 40 }+ })+ })+ if (!button || !label) throw new Error('Expected the component')+ graph.applyDerivedLayoutDuring(() => editor.runLayoutForNode(button?.id ?? ''))+ expect(button.width).toBe(244)++ editor.updateNodeWithUndo(label.id, { width: 272 })+ expect(button.width).toBe(312)+ editor.dispose()+})diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex f96d49356..3d11644df 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -17,7 +17,7 @@ export * from './components/properties'export * from './components/variants'export * from './slots/frames'export { instanceMainComponent } from './instances/main-component'-export { canCreateInstance } from './instances/cycles'+export { canCreateInstance, createsComponentCycle, cycleSafeParent } from './instances/cycles'export {exposableInstances,exposedInstances,diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.tsindex 1c252f325..8c0a602ef 100644--- a/packages/scene-graph/src/instances.ts+++ b/packages/scene-graph/src/instances.ts@@ -11,6 +11,7 @@ import {groupCopyRemovals,removeLeftoverCopies} from './instances/copies'+import { canCreateInstance } from './instances/cycles'import { INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS } from './instances/fields'import {bindingProtection,@@ -45,15 +46,16 @@ export function createInstance(overrides: Partial<SceneNode> = {}): SceneNode | null {const component = graph.nodes.get(componentId)- if (component?.type !== 'COMPONENT') return null+ if (component?.type !== 'COMPONENT' || !canCreateInstance(graph, componentId, parentId))+ return nullconst props: Partial<SceneNode> = {...copyInstanceComponentProps(component),- name: component.name,- componentId+ name: component.name}- const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides })+ // The component checked above is the one the instance shows, whatever `overrides` holds.+ const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides, componentId })cloneChildrenWithMapping(graph, component.id, instance.id)@@ -117,6 +119,7 @@ export function swapInstanceComponent(const instance = graph.nodes.get(instanceId)const component = graph.nodes.get(componentId)if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return+ if (instance.parentId && !canCreateInstance(graph, componentId, instance.parentId)) returnconst previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : undefinedrecordNestedSwap(graph, instance, componentId)diff --git a/packages/scene-graph/src/instances/cycles.ts b/packages/scene-graph/src/instances/cycles.tsindex a030d8ecf..b16e0ba15 100644--- a/packages/scene-graph/src/instances/cycles.ts+++ b/packages/scene-graph/src/instances/cycles.ts@@ -1,17 +1,8 @@import type { SceneGraph } from '../'import { instanceMainComponent } from './main-component'-/**- * Whether placing this definition's instance under `parentId` would make a component contain- * itself. Both components and instances above the parent count: an instance's layers are its- * component's, so a swap inside one may not bring that component back in.- */-export function canCreateInstance(- graph: SceneGraph,- componentId: string,- parentId: string-): boolean {- if (graph.getNode(componentId)?.type !== 'COMPONENT') return false+/** Components at or above `parentId`, counting the component each enclosing instance shows. */+function enclosingComponents(graph: SceneGraph, parentId: string): Set<string> {const ancestors = new Set<string>()graph.closest(parentId, (node) => {if (node.type === 'COMPONENT') ancestors.add(node.id)@@ -21,6 +12,22 @@ export function canCreateInstance(}return false})+ return ancestors+}++/**+ * Whether moving `nodeId` under `parentId` would make a component contain itself: its layers,+ * followed through instances into their components, reach a component at or above the parent.+ * Both components and instances above the parent count: an instance's layers are its+ * component's, so a swap inside one may not bring that component back in.+ */+export function createsComponentCycle(+ graph: SceneGraph,+ nodeId: string,+ parentId: string+): boolean {+ const ancestors = enclosingComponents(graph, parentId)+ if (ancestors.size === 0) return falseconst visited = new Set<string>()function reachesAncestor(id: string): boolean {if (ancestors.has(id)) return true@@ -32,5 +39,35 @@ export function canCreateInstance(return truereturn node.childIds.some(reachesAncestor)}- return !reachesAncestor(componentId)+ return reachesAncestor(nodeId)+}++/** Whether placing this definition's instance under `parentId` would make a component contain itself. */+export function canCreateInstance(+ graph: SceneGraph,+ componentId: string,+ parentId: string+): boolean {+ if (graph.getNode(componentId)?.type !== 'COMPONENT') return false+ return !createsComponentCycle(graph, componentId, parentId)+}++/**+ * `parentId`, or its nearest ancestor that can hold these layers or instances of these+ * components without a component containing itself. Figma pastes an instance next to its own+ * component, not in it.+ */+export function cycleSafeParent(+ graph: SceneGraph,+ parentId: string,+ nodeIds: readonly string[]+): string {+ const safe = graph.closest(+ parentId,+ (node) =>+ // Climbing out of a variant passes its set, which holds only variants.+ (node.id === parentId || node.type !== 'COMPONENT_SET') &&+ nodeIds.every((id) => !createsComponentCycle(graph, id, node.id))+ )+ return safe?.id ?? parentId}diff --git a/packages/scene-graph/tests/components/cycles.test.ts b/packages/scene-graph/tests/components/cycles.test.tsnew file mode 100644index 000000000..741bf2e3a--- /dev/null+++ b/packages/scene-graph/tests/components/cycles.test.ts@@ -0,0 +1,93 @@+import { describe, expect, test } from 'bun:test'++import {+ canCreateInstance,+ createsComponentCycle,+ cycleSafeParent,+ SceneGraph+} from '@open-pencil/scene-graph'++/** Card holds a Footer with an Action instance of Button, which holds an instance of Icon. */+function setup() {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const icon = graph.createNode('COMPONENT', page, { name: 'Icon' })+ const button = graph.createNode('COMPONENT', page, { name: 'Button' })+ const buttonIcon = graph.createInstance(icon.id, button.id, { name: 'Icon' })+ const card = graph.createNode('COMPONENT', page, { name: 'Card' })+ const footer = graph.createNode('FRAME', card.id, { name: 'Footer' })+ const action = graph.createInstance(button.id, footer.id, { name: 'Action' })+ if (!buttonIcon || !action) throw new Error('instances were not created')+ return { graph, page, icon, button, card, footer, action }+}++describe('instance cycles', () => {+ test('refuses an instance that would contain its own component', () => {+ const { graph, icon, button, card } = setup()+ expect(canCreateInstance(graph, icon.id, card.id)).toBe(true)+ expect(canCreateInstance(graph, card.id, card.id)).toBe(false)+ // Button holds Icon, so Icon cannot hold Button, directly or through a nested layer.+ const frame = graph.createNode('FRAME', icon.id, { name: 'Holder' })+ expect(canCreateInstance(graph, button.id, frame.id)).toBe(false)+ })++ test('counts the component of an instance the new one would sit in', () => {+ const { graph, page, button, card } = setup()+ const outer = graph.createInstance(card.id, page)+ const action = outer && graph.getChildren(outer.id).find((node) => node.name === 'Footer')+ const copy = action && graph.getChildren(action.id).find((node) => node.name === 'Action')+ if (!copy) throw new Error('Expected the Action copy')+ // A layer inside a Button, wherever it is shown, cannot become another Button.+ expect(canCreateInstance(graph, button.id, copy.id)).toBe(false)+ expect(canCreateInstance(graph, card.id, copy.id)).toBe(false)+ })++ test('creating or swapping to an instance that would contain itself does nothing', () => {+ const { graph, icon, button, card, footer, action } = setup()+ const before = graph.nodes.size+ expect(graph.createInstance(card.id, footer.id)).toBeNull()+ expect(graph.createInstance(button.id, icon.id)).toBeNull()+ expect(graph.nodes.size).toBe(before)++ graph.swapInstanceComponent(action.id, card.id)+ expect(action.componentId).toBe(button.id)+ expect(graph.nodes.size).toBe(before)+ })++ test('a layer holding an instance cannot move into that instance’s component', () => {+ const { graph, page, icon, button, card } = setup()+ const holder = graph.createNode('FRAME', page, { name: 'Holder' })+ graph.createInstance(card.id, holder.id)+ const inIcon = graph.createNode('FRAME', icon.id, { name: 'Inside icon' })+ // Card shows a Button, which shows an Icon.+ expect(createsComponentCycle(graph, holder.id, card.id)).toBe(true)+ expect(createsComponentCycle(graph, holder.id, inIcon.id)).toBe(true)+ expect(createsComponentCycle(graph, holder.id, page)).toBe(false)+ expect(createsComponentCycle(graph, inIcon.id, button.id)).toBe(false)+ })++ test('overrides cannot swap in a component that would contain itself', () => {+ const { graph, icon, card, footer } = setup()+ const instance = graph.createInstance(icon.id, footer.id, { componentId: card.id })+ expect(instance?.componentId).toBe(icon.id)+ })++ test('climbing out of a variant passes its set, which holds only variants', () => {+ const { graph, page } = setup()+ const set = graph.createNode('COMPONENT_SET', page, { name: 'States' })+ const variant = graph.createNode('COMPONENT', set.id, { name: 'State=Default' })+ const inner = graph.createNode('FRAME', variant.id, { name: 'Inner' })+ const instance = graph.createInstance(variant.id, page)+ if (!instance) throw new Error('no instance')+ expect(cycleSafeParent(graph, inner.id, [instance.id])).toBe(page)+ expect(cycleSafeParent(graph, set.id, [graph.createNode('COMPONENT', page).id])).toBe(set.id)+ })++ test('the safe parent is the nearest ancestor that can hold every layer', () => {+ const { graph, page, button, card, footer } = setup()+ const outer = graph.createNode('FRAME', page, { name: 'Outer' })+ graph.reparentNode(card.id, outer.id)+ expect(cycleSafeParent(graph, footer.id, [card.id])).toBe(outer.id)+ expect(cycleSafeParent(graph, footer.id, [button.id])).toBe(footer.id)+ })+})diff --git a/packages/scene-graph/tests/components/exposure.test.ts b/packages/scene-graph/tests/components/exposure.test.tsindex a5c264bbe..60c0c2b37 100644--- a/packages/scene-graph/tests/components/exposure.test.ts+++ b/packages/scene-graph/tests/components/exposure.test.ts@@ -1,7 +1,6 @@import { describe, expect, test } from 'bun:test'import {- canCreateInstance,exposableInstances,exposedInstances,SceneGraph@@ -50,25 +49,3 @@ describe('exposed nested instances', () => {expect(exposedInstances(graph, instance).map((node) => node.name)).toEqual(['Action', 'Badge'])})})--describe('instance cycles', () => {- test('refuses an instance that would contain its own component', () => {- const { graph, icon, button, card } = setup()- expect(canCreateInstance(graph, icon.id, card.id)).toBe(true)- expect(canCreateInstance(graph, card.id, card.id)).toBe(false)- // Button holds Icon, so Icon cannot hold Button, directly or through a nested layer.- const frame = graph.createNode('FRAME', icon.id, { name: 'Holder' })- expect(canCreateInstance(graph, button.id, frame.id)).toBe(false)- })-- test('counts the component of an instance the new one would sit in', () => {- const { graph, page, button, card } = setup()- const outer = graph.createInstance(card.id, page)- const action = outer && graph.getChildren(outer.id).find((node) => node.name === 'Footer')- const copy = action && graph.getChildren(action.id).find((node) => node.name === 'Action')- if (!copy) throw new Error('Expected the Action copy')- // A layer inside a Button, wherever it is shown, cannot become another Button.- expect(canCreateInstance(graph, button.id, copy.id)).toBe(false)- expect(canCreateInstance(graph, card.id, copy.id)).toBe(false)- })-})diff --git a/packages/vue/src/canvas/drop/use.ts b/packages/vue/src/canvas/drop/use.tsindex 5065af1f5..080531e8c 100644--- a/packages/vue/src/canvas/drop/use.ts+++ b/packages/vue/src/canvas/drop/use.ts@@ -3,7 +3,7 @@ import { ref, type Ref } from 'vue'import type { Editor } from '@open-pencil/core/editor'-import { findMoveDropTarget } from '#vue/shared/input/drop-target'+import { cycleSafeTarget, findMoveDropTarget } from '#vue/shared/input/drop-target'const RASTER_IMAGE_TYPES = new Set(['image/png',@@ -27,7 +27,9 @@ function componentDropPlacement(componentId: string, cx: number, cy: number, ediconst component = editor.graph.getNode(componentId)if (component?.type !== 'COMPONENT') return null- const target = findMoveDropTarget(cx, cy, editor)+ // An instance never lands inside its own component; Figma puts it in the nearest frame that can hold it.+ const dragged = new Set([componentId])+ const target = cycleSafeTarget(findMoveDropTarget(cx, cy, editor, dragged), [componentId], editor)const parentId = target?.id ?? editor.state.currentPageIdconst parentOffset =parentId === editor.state.currentPageIddiff --git a/packages/vue/src/controls/typography/actions.ts b/packages/vue/src/controls/typography/actions.tsindex 7c368953f..3bd0f366d 100644--- a/packages/vue/src/controls/typography/actions.ts+++ b/packages/vue/src/controls/typography/actions.ts@@ -131,8 +131,11 @@ export function createTypographyActions({const beforePreview = new Map<string, Preview>()/** Applies one change per text layer in one undo step. */- function updateEach(label: string, changes: (node: SceneNode) => Partial<SceneNode>) {- const targets = nodes.value+ function updateEach(+ label: string,+ changes: (node: SceneNode) => Partial<SceneNode>,+ targets = nodes.value+ ) {if (targets.length === 0) returneditor.undo.runBatch(label, () => {for (const target of targets) editor.updateNodeWithUndo(target.id, changes(target), label)@@ -143,23 +146,46 @@ export function createTypographyActions({updateEach(label, () => changes)}- async function setFamily(family: string) {+ /** The newest pending change for each layer and field, by `id:field`. */+ const latestLoadingRequest = new Map<string, symbol>()++ /**+ * Applies a change once its faces have loaded, to the layers selected when it was asked for:+ * the selection may change while the load is pending, and a layer may be deleted.+ */+ async function updateAfterLoading(+ label: string,+ changes: Partial<SceneNode>,+ load: (target: SceneNode) => Promise<unknown> | undefined+ ) {const targets = nodes.valueif (targets.length === 0) return- await Promise.all(- targets.map((target) =>- options.fontLoader?.load(family, FONT_WEIGHT_NAMES[target.fontWeight] ?? 'Regular')- )+ const request = Symbol(label)+ const keys = (target: SceneNode) => Object.keys(changes).map((field) => `${target.id}:${field}`)+ for (const target of targets)+ for (const key of keys(target)) latestLoadingRequest.set(key, request)+ await Promise.all(targets.map(load))+ // A later choice for the same field wins, even when its face loaded first.+ const current = targets.filter((target) =>+ keys(target).every((key) => latestLoadingRequest.get(key) === request))- update('Change font', { fontFamily: family })+ for (const target of current) for (const key of keys(target)) latestLoadingRequest.delete(key)+ const live = current.filter((target) => editor.graph.getNode(target.id))+ updateEach(label, () => changes, live)}+ async function setFamily(family: string) {+ await updateAfterLoading('Change font', { fontFamily: family }, (target) =>+ options.fontLoader?.load(family, FONT_WEIGHT_NAMES[target.fontWeight] ?? 'Regular')+ )+ }++ /** Loads the face first, as for a family, so the text is laid out once with it. */async function setWeight(weight: number) {- const targets = nodes.value- if (targets.length === 0) return- update('Change font weight', { fontWeight: weight })const style = weightToStyle(weight)- await Promise.all(targets.map((target) => options.fontLoader?.load(target.fontFamily, style)))+ await updateAfterLoading('Change font weight', { fontWeight: weight }, (target) =>+ options.fontLoader?.load(target.fontFamily, style)+ )}function setAlign(align: TextAlign) {diff --git a/packages/vue/src/shared/input/drop-target.ts b/packages/vue/src/shared/input/drop-target.tsindex 670d3db47..86e4391ad 100644--- a/packages/vue/src/shared/input/drop-target.ts+++ b/packages/vue/src/shared/input/drop-target.ts@@ -1,5 +1,5 @@import type { Editor } from '@open-pencil/core/editor'-import type { NodeType, SceneNode } from '@open-pencil/scene-graph'+import { cycleSafeParent, type NodeType, type SceneNode } from '@open-pencil/scene-graph'/** Parents a layer stays in while dragged until it lands on another frame. */const ENCLOSING_TYPES = new Set<NodeType>(['GROUP', 'BOOLEAN_OPERATION'])@@ -34,7 +34,21 @@ export function findMoveDropTarget(if (movingSection && dropTarget && dropTarget.type !== 'SECTION') {dropTarget = null}- return acceptingTarget(dropTarget, editor)+ return cycleSafeTarget(acceptingTarget(dropTarget, editor), [...excludeIds], editor)+}++/**+ * The target, or its nearest ancestor these layers can go into without a component containing+ * itself; null is the page.+ */+export function cycleSafeTarget(+ target: SceneNode | null,+ ids: readonly string[],+ editor: Editor+): SceneNode | null {+ if (!target) return null+ const safe = editor.graph.getNode(cycleSafeParent(editor.graph, target.id, ids))+ return safe && safe.type !== 'CANVAS' ? safe : null}function takesDrawnLayer(target: SceneNode, type: NodeType) {diff --git a/packages/vue/tests/controls/typography.test.ts b/packages/vue/tests/controls/typography.test.tsnew file mode 100644index 000000000..5ac84be1a--- /dev/null+++ b/packages/vue/tests/controls/typography.test.ts@@ -0,0 +1,76 @@+import { expect, test } from 'bun:test'+import { computed, shallowRef } from 'vue'++import { createEditor } from '@open-pencil/core/editor'+import type { SceneNode } from '@open-pencil/scene-graph'++import { createTypographyActions } from '#vue/controls/typography/actions'++/** Two text layers, the typography actions over a selection, and a font load that waits. */+function setup() {+ const editor = createEditor()+ const page = editor.state.currentPageId+ const first = editor.graph.createNode('TEXT', page, { name: 'First', text: 'a' })+ const second = editor.graph.createNode('TEXT', page, { name: 'Second', text: 'b' })+ const selection = shallowRef<SceneNode[]>([first])+ let resolveLoading: (() => void) | undefined+ const loading = new Promise<void>((resolve) => {+ resolveLoading = resolve+ })+ const finishLoading = () => resolveLoading?.()+ const actions = createTypographyActions({+ editor,+ nodes: computed(() => selection.value),+ activeFormatting: computed(() => []),+ options: { fontLoader: { load: () => loading } }+ })+ return { editor, first, second, selection, actions, finishLoading }+}++test('a weight waits for its face, then changes the layers selected when it was chosen', async () => {+ const { first, second, selection, actions, finishLoading } = setup()+ const applied = actions.setWeight(700)+ expect(first.fontWeight).toBe(400)+ selection.value = [second]+ finishLoading()+ await applied+ expect(first.fontWeight).toBe(700)+ expect(second.fontWeight).toBe(400)+})++test('a later choice wins over an earlier one whose face loads after it', async () => {+ const editor = createEditor()+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, { text: 'a' })+ const loads = new Map<string, () => void>()+ const actions = createTypographyActions({+ editor,+ nodes: computed(() => [text]),+ activeFormatting: computed(() => []),+ options: {+ fontLoader: {+ load: (family) =>+ new Promise<void>((resolve) => {+ loads.set(family, resolve)+ })+ }+ }+ })+ const slow = actions.setFamily('Roboto')+ const fast = actions.setFamily('Lora')+ loads.get('Lora')?.()+ await fast+ loads.get('Roboto')?.()+ await slow+ expect(text.fontFamily).toBe('Lora')+})++test('a family chosen while loading skips layers deleted in the meantime', async () => {+ const { editor, first, second, selection, actions, finishLoading } = setup()+ selection.value = [first, second]+ const applied = actions.setFamily('Roboto')+ editor.graph.deleteNode(first.id)+ finishLoading()+ await applied+ expect(editor.graph.getNode(second.id)?.fontFamily).toBe('Roboto')+ expect(editor.graph.getNode(first.id)).toBeUndefined()+})diff --git a/src/components/assets-panel/AssetsPanel.vue b/src/components/assets-panel/AssetsPanel.vueindex bca1d6b9c..700f0d0ad 100644--- a/src/components/assets-panel/AssetsPanel.vue+++ b/src/components/assets-panel/AssetsPanel.vue@@ -11,7 +11,7 @@ import {} from 'reka-ui'import { computed, onMounted, ref, shallowRef, watch } from 'vue'-import type { SceneNode } from '@open-pencil/scene-graph'+import { cycleSafeParent, type SceneNode } from '@open-pencil/scene-graph'import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'import { useI18n } from '@open-pencil/vue'@@ -285,7 +285,11 @@ async function insertAsset(asset: LocalAsset) {if (!componentId) returnconst component = editor.graph.getNode(componentId)if (!component) return- const parentId = editor.state.enteredContainerId ?? editor.state.currentPageId+ const parentId = cycleSafeParent(+ editor.graph,+ editor.state.enteredContainerId ?? editor.state.currentPageId,+ [componentId]+ )const point = insertionPoint(component, parentId)editor.createInstanceFromComponent(componentId, point.x, point.y, parentId)editor.requestRender()