@open-pencil/scene-graph 0.17.0-beta.2 → 0.17.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/asset-keys.d.ts +11 -1
- package/dist/asset-keys.d.ts.map +1 -1
- package/dist/asset-keys.js +16 -1
- package/dist/asset-keys.js.map +1 -1
- package/dist/checkpoint.d.ts +3 -3
- package/dist/checkpoint.d.ts.map +1 -1
- package/dist/checkpoint.js +53 -23
- package/dist/checkpoint.js.map +1 -1
- package/dist/components/index.d.ts +2 -2
- package/dist/components/index.js +2 -2
- package/dist/components/properties.d.ts +6 -1
- package/dist/components/properties.d.ts.map +1 -1
- package/dist/components/properties.js +9 -1
- package/dist/components/properties.js.map +1 -1
- package/dist/constants.d.ts +6 -1
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +17 -1
- package/dist/constants.js.map +1 -1
- package/dist/constraints.d.ts +25 -0
- package/dist/constraints.d.ts.map +1 -0
- package/dist/constraints.js +51 -0
- package/dist/constraints.js.map +1 -0
- package/dist/coordinate.d.ts +64 -1
- package/dist/coordinate.d.ts.map +1 -1
- package/dist/coordinate.js +217 -1
- package/dist/coordinate.js.map +1 -1
- package/dist/copy.d.ts.map +1 -1
- package/dist/copy.js +8 -1
- package/dist/copy.js.map +1 -1
- package/dist/css/index.d.ts +3 -2
- package/dist/css/index.js +3 -2
- package/dist/css/text.d.ts +28 -1
- package/dist/css/text.d.ts.map +1 -1
- package/dist/css/text.js +84 -17
- package/dist/css/text.js.map +1 -1
- package/dist/css/transform.d.ts +34 -0
- package/dist/css/transform.d.ts.map +1 -0
- package/dist/css/transform.js +320 -0
- package/dist/css/transform.js.map +1 -0
- package/dist/css/values.d.ts.map +1 -1
- package/dist/css/values.js +11 -1
- package/dist/css/values.js.map +1 -1
- package/dist/figjam/palette.d.ts +1 -1
- package/dist/figjam/palette.js +1 -1
- package/dist/figjam/palette.js.map +1 -1
- package/dist/geometry.d.ts +8 -1
- package/dist/geometry.d.ts.map +1 -1
- package/dist/geometry.js +19 -8
- package/dist/geometry.js.map +1 -1
- package/dist/graph.d.ts +48 -12
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +110 -24
- package/dist/graph.js.map +1 -1
- package/dist/group-bounds.d.ts +14 -4
- package/dist/group-bounds.d.ts.map +1 -1
- package/dist/group-bounds.js +76 -11
- package/dist/group-bounds.js.map +1 -1
- package/dist/hit-test.d.ts +5 -0
- package/dist/hit-test.d.ts.map +1 -1
- package/dist/hit-test.js +18 -12
- package/dist/hit-test.js.map +1 -1
- package/dist/images.d.ts +27 -3
- package/dist/images.d.ts.map +1 -1
- package/dist/images.js +57 -3
- package/dist/images.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +3 -0
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/placement.js +55 -12
- package/dist/instances/placement.js.map +1 -1
- package/dist/instances/swap.js +3 -0
- package/dist/instances/swap.js.map +1 -1
- package/dist/instances/sync.js +34 -13
- package/dist/instances/sync.js.map +1 -1
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +1 -0
- package/dist/node-defaults.js.map +1 -1
- package/dist/order-keys.d.ts +3 -1
- package/dist/order-keys.d.ts.map +1 -1
- package/dist/order-keys.js +6 -1
- package/dist/order-keys.js.map +1 -1
- package/dist/plugin-data/fields.d.ts +2 -0
- package/dist/plugin-data/fields.d.ts.map +1 -1
- package/dist/plugin-data/fields.js +2 -0
- package/dist/plugin-data/fields.js.map +1 -1
- package/dist/resize.d.ts +22 -11
- package/dist/resize.d.ts.map +1 -1
- package/dist/resize.js +227 -93
- package/dist/resize.js.map +1 -1
- package/dist/scaling/index.d.ts +3 -2
- package/dist/scaling/index.js +3 -2
- package/dist/scaling/node.d.ts.map +1 -1
- package/dist/scaling/node.js +5 -1
- package/dist/scaling/node.js.map +1 -1
- package/dist/scaling/snapshot.d.ts +25 -0
- package/dist/scaling/snapshot.d.ts.map +1 -0
- package/dist/scaling/snapshot.js +39 -0
- package/dist/scaling/snapshot.js.map +1 -0
- package/dist/scaling/tree.d.ts +24 -2
- package/dist/scaling/tree.d.ts.map +1 -1
- package/dist/scaling/tree.js +37 -14
- package/dist/scaling/tree.js.map +1 -1
- package/dist/shaders/model.d.ts.map +1 -1
- package/dist/shaders/model.js +2 -1
- package/dist/shaders/model.js.map +1 -1
- package/dist/shared-styles.d.ts +3 -1
- package/dist/shared-styles.d.ts.map +1 -1
- package/dist/shared-styles.js +7 -1
- package/dist/shared-styles.js.map +1 -1
- package/dist/slots/authoring.d.ts +3 -2
- package/dist/slots/authoring.d.ts.map +1 -1
- package/dist/slots/authoring.js +5 -3
- package/dist/slots/authoring.js.map +1 -1
- package/dist/slots/content.d.ts.map +1 -1
- package/dist/slots/content.js +4 -1
- package/dist/slots/content.js.map +1 -1
- package/dist/text/direction.d.ts +3 -1
- package/dist/text/direction.d.ts.map +1 -1
- package/dist/text/direction.js +5 -1
- package/dist/text/direction.js.map +1 -1
- package/dist/transfer/apply.d.ts.map +1 -1
- package/dist/transfer/apply.js +1 -6
- package/dist/transfer/apply.js.map +1 -1
- package/dist/transfer/copied.d.ts +35 -3
- package/dist/transfer/copied.d.ts.map +1 -1
- package/dist/transfer/copied.js +44 -13
- package/dist/transfer/copied.js.map +1 -1
- package/dist/transfer/dependencies.d.ts +38 -0
- package/dist/transfer/dependencies.d.ts.map +1 -0
- package/dist/transfer/dependencies.js +100 -0
- package/dist/transfer/dependencies.js.map +1 -0
- package/dist/transfer/history.js +0 -1
- package/dist/transfer/history.js.map +1 -1
- package/dist/transfer/index.d.ts +5 -3
- package/dist/transfer/index.js +5 -3
- package/dist/transfer/nodes.d.ts.map +1 -1
- package/dist/transfer/nodes.js +7 -14
- package/dist/transfer/nodes.js.map +1 -1
- package/dist/transfer/plan.d.ts +0 -1
- package/dist/transfer/plan.js +3 -5
- package/dist/transfer/plan.js.map +1 -1
- package/dist/transfer/remove.js +5 -2
- package/dist/transfer/remove.js.map +1 -1
- package/dist/transfer/resources.d.ts +21 -0
- package/dist/transfer/resources.d.ts.map +1 -0
- package/dist/transfer/resources.js +38 -0
- package/dist/transfer/resources.js.map +1 -0
- package/dist/transfer/variables.d.ts +8 -1
- package/dist/transfer/variables.d.ts.map +1 -1
- package/dist/transfer/variables.js +24 -1
- package/dist/transfer/variables.js.map +1 -1
- package/dist/types.d.ts +47 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/undo.d.ts +28 -3
- package/dist/undo.d.ts.map +1 -1
- package/dist/undo.js +24 -7
- package/dist/undo.js.map +1 -1
- package/dist/variables/bindings.d.ts +17 -14
- package/dist/variables/bindings.d.ts.map +1 -1
- package/dist/variables/bindings.js +30 -72
- package/dist/variables/bindings.js.map +1 -1
- package/dist/variables/fields.d.ts +1 -1
- package/dist/variables/fields.js +1 -1
- package/dist/variables/fields.js.map +1 -1
- package/dist/variables/formula/check.d.ts +1 -1
- package/dist/variables/formula/index.d.ts +2 -2
- package/dist/variables/formula/index.js +1 -1
- package/dist/variables/formula/index.js.map +1 -1
- package/dist/variables/formula/print.d.ts +1 -1
- package/dist/variables/formula/signatures.js +1 -1
- package/dist/variables/index.d.ts +6 -6
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js +40 -24
- package/dist/variables/index.js.map +1 -1
- package/dist/variables/paints.d.ts +57 -0
- package/dist/variables/paints.d.ts.map +1 -0
- package/dist/variables/paints.js +231 -0
- package/dist/variables/paints.js.map +1 -0
- package/dist/variables/resolution.d.ts +14 -11
- package/dist/variables/resolution.d.ts.map +1 -1
- package/dist/variables/resolution.js +36 -17
- package/dist/variables/resolution.js.map +1 -1
- package/dist/variables/subtree.js +17 -0
- package/dist/variables/subtree.js.map +1 -0
- package/dist/vector-network.d.ts.map +1 -1
- package/dist/vector-network.js +2 -8
- package/dist/vector-network.js.map +1 -1
- package/package.json +8 -1
- package/src/asset-keys.ts +20 -0
- package/src/checkpoint.ts +87 -32
- package/src/components/properties.ts +9 -0
- package/src/constants.ts +17 -0
- package/src/constraints.ts +60 -0
- package/src/coordinate.ts +220 -0
- package/src/copy.ts +9 -4
- package/src/css/index.ts +17 -1
- package/src/css/text.ts +85 -17
- package/src/css/transform.ts +266 -0
- package/src/css/values.ts +8 -0
- package/src/figjam/palette.ts +1 -1
- package/src/geometry.ts +20 -9
- package/src/graph.ts +128 -42
- package/src/group-bounds.ts +84 -17
- package/src/hit-test.ts +30 -14
- package/src/images.ts +71 -3
- package/src/instances/index.ts +4 -0
- package/src/instances/placement.ts +63 -10
- package/src/instances/swap.ts +5 -0
- package/src/instances/sync.ts +48 -21
- package/src/node-defaults.ts +1 -0
- package/src/order-keys.ts +6 -0
- package/src/plugin-data/fields.ts +6 -0
- package/src/resize.ts +267 -119
- package/src/scaling/index.ts +9 -1
- package/src/scaling/node.ts +9 -1
- package/src/scaling/snapshot.ts +51 -0
- package/src/scaling/tree.ts +63 -19
- package/src/shaders/model.ts +2 -3
- package/src/shared-styles.ts +8 -0
- package/src/slots/authoring.ts +5 -3
- package/src/slots/content.ts +4 -1
- package/src/text/direction.ts +5 -0
- package/src/transfer/apply.ts +1 -13
- package/src/transfer/copied.ts +83 -15
- package/src/transfer/dependencies.ts +126 -0
- package/src/transfer/history.ts +0 -6
- package/src/transfer/index.ts +20 -2
- package/src/transfer/nodes.ts +10 -26
- package/src/transfer/plan.ts +3 -11
- package/src/transfer/remove.ts +5 -2
- package/src/transfer/resources.ts +54 -0
- package/src/transfer/variables.ts +34 -0
- package/src/types.ts +55 -1
- package/src/undo.ts +48 -10
- package/src/variables/bindings.ts +44 -91
- package/src/variables/fields.ts +1 -1
- package/src/variables/formula/index.ts +3 -1
- package/src/variables/index.ts +56 -38
- package/src/variables/paints.ts +296 -0
- package/src/variables/resolution.ts +39 -28
- package/src/variables/subtree.ts +15 -0
- package/src/vector-network.ts +4 -2
package/dist/group-bounds.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"group-bounds.js","names":[],"sources":["../src/group-bounds.ts"],"sourcesContent":["import { getAxisAlignedBoundsInParent } from './coordinate'\nimport type { SceneGraph } from './graph'\nimport { FITTED_CONTAINER_TYPES } from './node-defaults'\nimport type { Rect, Vector } from './primitives'\nimport type { SceneNode } from './types'\n\n/** Where a layer sits, with a connector's ends, since a free end is in the parent's axes too. */\ntype Placement = Pick<SceneNode, 'x' | 'y' | 'width' | 'height'> &\n Partial<Pick<SceneNode, 'connectorStart' | 'connectorEnd'>>\n\n/** What `fitEnclosingGroups` changed, so a caller can undo and redo it. */\nexport interface GroupFit {\n before: Map<string, Placement>\n after: Map<string, Placement>\n /** Emptied groups, outermost last, with their index in their parent. */\n removed: Array<{ node: SceneNode; index: number }>\n}\n\nexport interface GroupFitOptions {\n /**\n * The box of a boolean operation's result in its parent's space, which Figma sizes a boolean to,\n * or null to fit its operands. Measuring needs path operations, so the renderer supplies it.\n */\n booleanBounds?: (node: SceneNode) => Rect | null\n}\n\nfunction placement(node: SceneNode): Placement {\n const box = { x: node.x, y: node.y, width: node.width, height: node.height }\n if (node.type !== 'CONNECTOR') return box\n return {\n ...box,\n connectorStart: structuredClone(node.connectorStart),\n connectorEnd: structuredClone(node.connectorEnd)\n }\n}\n\n/** A connector end moved by `dx`, `dy` when it is free, as its point is in the parent's axes. */\nfunction shiftedEnd(\n end: SceneNode['connectorStart'],\n dx: number,\n dy: number\n): SceneNode['connectorStart'] {\n if (end?.nodeId !== null) return end\n return { ...end, position: { x: end.position.x - dx, y: end.position.y - dy } }\n}\n\n/** Groups and booleans holding the parents, innermost first. */\nfunction fittedAncestors(graph: SceneGraph, parentIds: Iterable<string>): SceneNode[] {\n const found = new Map<string, { node: SceneNode; depth: number }>()\n for (const parentId of parentIds) {\n const chain: SceneNode[] = []\n for (let node = graph.getNode(parentId); node && FITTED_CONTAINER_TYPES.has(node.type);) {\n chain.push(node)\n node = node.parentId ? graph.getNode(node.parentId) : undefined\n }\n for (const [index, node] of chain.entries()) {\n found.set(node.id, {\n node,\n depth: Math.max(found.get(node.id)?.depth ?? 0, chain.length - index)\n })\n }\n }\n return [...found.values()].sort((a, b) => b.depth - a.depth).map(({ node }) => node)\n}\n\n/**\n * The layers a group's box covers, bottom to top. Hidden layers do not count, as in Figma. A mask\n * hides the layers above it outside its shape, so they count only through the mask: the box is\n * the layers below it and the masks.\n */\nfunction groupBoundingLayers(children: readonly SceneNode[]): SceneNode[] {\n const shown = children.filter((child) => child.visible)\n const firstMask = shown.findIndex((child) => child.isMask)\n if (firstMask === -1) return shown\n return [...shown.slice(0, firstMask), ...shown.slice(firstMask).filter((c) => c.isMask)]\n}\n\n/**\n * A group's box in its parent's space: around the layers it shows, or, with every layer hidden,\n * empty at `origin`, where Figma leaves it.\n */\nexport function groupBounds(\n graph: SceneGraph,\n children: readonly SceneNode[],\n parentId: string,\n origin: Vector\n): Rect {\n const layers = groupBoundingLayers(children)\n return layers.length > 0\n ? getAxisAlignedBoundsInParent(layers, parentId, graph)\n : { x: origin.x, y: origin.y, width: 0, height: 0 }\n}\n\n/** A child moved back by the group's shift, a connector's free ends with it. */\nfunction shiftedBack(child: SceneNode, dx: number, dy: number): Partial<SceneNode> {\n const moved = { x: child.x - dx, y: child.y - dy }\n if (child.type !== 'CONNECTOR') return moved\n return {\n ...moved,\n connectorStart: shiftedEnd(child.connectorStart, dx, dy),\n connectorEnd: shiftedEnd(child.connectorEnd, dx, dy)\n }\n}\n\n/** Moves the group to its children's bounds, shifting them back so they stay put. */\nfunction fitGroup(\n graph: SceneGraph,\n group: SceneNode,\n children: SceneNode[],\n fit: GroupFit,\n options: GroupFitOptions\n) {\n if (!group.parentId || group.rotation !== 0 || group.flipX || group.flipY) return\n const bounds =\n (group.type === 'BOOLEAN_OPERATION' ? options.booleanBounds?.(group) : null) ??\n groupBounds(graph, children, group.parentId, group)\n const dx = bounds.x - group.x\n const dy = bounds.y - group.y\n if (dx === 0 && dy === 0 && bounds.width === group.width && bounds.height === group.height) {\n return\n }\n for (const node of [group, ...children]) {\n if (!fit.before.has(node.id)) fit.before.set(node.id, placement(node))\n }\n graph.updateNode(group.id, bounds)\n for (const child of children) {\n graph.updateNode(child.id, shiftedBack(child, dx, dy))\n }\n for (const node of [group, ...children]) {\n const current = graph.getNode(node.id)\n if (current) fit.after.set(node.id, placement(current))\n }\n}\n\n/** A group left without layers goes away; an empty boolean stays, as in Figma. */\nfunction removeEmptyGroup(graph: SceneGraph, group: SceneNode, fit: GroupFit) {\n if (group.type !== 'GROUP' || !group.parentId) return\n const index = graph.getNode(group.parentId)?.childIds.indexOf(group.id) ?? -1\n fit.removed.push({ node: structuredClone(group), index })\n graph.deleteNode(group.id)\n}\n\n/**\n * Refits the groups and booleans around these parents to their children, keeping every child where\n * it is on the canvas, and removes groups left empty, as Figma does after a layer inside one moves,\n * resizes, or leaves. Rotated or flipped containers keep their bounds. Returns null when nothing\n * changed.\n */\nexport function fitEnclosingGroups(\n graph: SceneGraph,\n parentIds: Iterable<string>,\n options: GroupFitOptions = {}\n): GroupFit | null {\n const fit: GroupFit = { before: new Map(), after: new Map(), removed: [] }\n for (const group of fittedAncestors(graph, parentIds)) {\n const children = graph.getChildren(group.id)\n if (children.length === 0) removeEmptyGroup(graph, group, fit)\n else fitGroup(graph, group, children, fit, options)\n }\n return fit.before.size === 0 && fit.removed.length === 0 ? null : fit\n}\n\n/** Reapplies a fit after `undoGroupFit`. */\nexport function redoGroupFit(graph: SceneGraph, fit: GroupFit): void {\n for (const [id, value] of fit.after) graph.updateNode(id, value)\n for (const { node } of fit.removed) graph.deleteNode(node.id)\n}\n\n/** Brings back the groups a fit removed and their earlier bounds. */\nexport function undoGroupFit(graph: SceneGraph, fit: GroupFit): void {\n // Outer groups were removed after inner ones, so they come back first.\n for (const { node, index } of fit.removed.toReversed()) {\n const parentId = node.parentId ?? graph.rootId\n graph.createNode(node.type, parentId, { ...structuredClone(node), childIds: [] })\n if (index >= 0) graph.insertChildAt(node.id, parentId, index)\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AE,MAAM,WAAW,IAAI,QAAQ,WAAW,GAAG;EACtD,MAAM,WAAW,KAAK,YAAY,MAAM;EACxC,MAAM,WAAW,KAAK,MAAM,UAAU;GAAE,GAAG,gBAAgB,IAAI;GAAG,UAAU,CAAC;EAAE,CAAC;EAChF,IAAI,SAAS,GAAG,MAAM,cAAc,KAAK,IAAI,UAAU,KAAK;CAC9D;CACA,KAAK,MAAM,CAAC,IAAI,UAAU,IAAI,QAAQ,MAAM,WAAW,IAAI,KAAK;AAClE"}
|
|
1
|
+
{"version":3,"file":"group-bounds.js","names":[],"sources":["../src/group-bounds.ts"],"sourcesContent":["import { getAxisAlignedBoundsInParent, getNodeLocalMatrix } from './coordinate'\nimport type { SceneGraph } from './graph'\nimport Matrix from './matrix'\nimport { FITTED_CONTAINER_TYPES } from './node-defaults'\nimport type { Rect, Vector } from './primitives'\nimport type { SceneNode } from './types'\n\n/**\n * What fitting a group reads: its layers and their parents, as the graph has them or as a resize\n * plans them before writing.\n */\nexport type GroupFitGraph = Pick<SceneGraph, 'getNode' | 'rootId'>\n\n/** Where a layer sits, with a connector's ends, since a free end is in the parent's axes too. */\ntype Placement = Pick<SceneNode, 'x' | 'y' | 'width' | 'height'> &\n Partial<Pick<SceneNode, 'connectorStart' | 'connectorEnd'>>\n\n/** What `fitEnclosingGroups` changed, so a caller can undo and redo it. */\nexport interface GroupFit {\n before: Map<string, Placement>\n after: Map<string, Placement>\n /** Emptied groups, outermost last, with their index in their parent. */\n removed: Array<{ node: SceneNode; index: number }>\n}\n\nexport interface GroupFitOptions {\n /**\n * The box of a boolean operation's result in its parent's space, which Figma sizes a boolean to,\n * or null to fit its operands. Measuring needs path operations, so the renderer supplies it.\n */\n booleanBounds?: (node: SceneNode) => Rect | null\n}\n\nfunction placement(node: SceneNode): Placement {\n const box = { x: node.x, y: node.y, width: node.width, height: node.height }\n if (node.type !== 'CONNECTOR') return box\n return {\n ...box,\n connectorStart: structuredClone(node.connectorStart),\n connectorEnd: structuredClone(node.connectorEnd)\n }\n}\n\n/** A connector end moved by `dx`, `dy` when it is free, as its point is in the parent's axes. */\nfunction shiftedEnd(\n end: SceneNode['connectorStart'],\n dx: number,\n dy: number\n): SceneNode['connectorStart'] {\n if (end?.nodeId !== null) return end\n return { ...end, position: { x: end.position.x - dx, y: end.position.y - dy } }\n}\n\n/** Groups and booleans holding the parents, innermost first. */\nfunction fittedAncestors(graph: SceneGraph, parentIds: Iterable<string>): SceneNode[] {\n const found = new Map<string, { node: SceneNode; depth: number }>()\n for (const parentId of parentIds) {\n const chain: SceneNode[] = []\n for (let node = graph.getNode(parentId); node && FITTED_CONTAINER_TYPES.has(node.type);) {\n chain.push(node)\n node = node.parentId ? graph.getNode(node.parentId) : undefined\n }\n for (const [index, node] of chain.entries()) {\n found.set(node.id, {\n node,\n depth: Math.max(found.get(node.id)?.depth ?? 0, chain.length - index)\n })\n }\n }\n return [...found.values()].sort((a, b) => b.depth - a.depth).map(({ node }) => node)\n}\n\n/**\n * The layers a group's box covers, bottom to top. Hidden layers do not count, as in Figma. A mask\n * hides the layers above it outside its shape, so they count only through the mask: the box is\n * the layers below it and the masks.\n */\nfunction groupBoundingLayers(children: readonly SceneNode[]): SceneNode[] {\n const shown = children.filter((child) => child.visible)\n const firstMask = shown.findIndex((child) => child.isMask)\n if (firstMask === -1) return shown\n return [...shown.slice(0, firstMask), ...shown.slice(firstMask).filter((c) => c.isMask)]\n}\n\n/**\n * A group's box in its parent's space: around the layers it shows, or, with every layer hidden,\n * empty at `origin`, where Figma leaves it.\n */\nexport function groupBounds(\n graph: GroupFitGraph,\n children: readonly SceneNode[],\n parentId: string,\n origin: Vector\n): Rect {\n const layers = groupBoundingLayers(children)\n return layers.length > 0\n ? getAxisAlignedBoundsInParent(layers, parentId, graph)\n : { x: origin.x, y: origin.y, width: 0, height: 0 }\n}\n\n/** A child moved back by the group's shift, a connector's free ends with it. */\nfunction shiftedBack(child: SceneNode, dx: number, dy: number): Partial<SceneNode> {\n const moved = { x: child.x - dx, y: child.y - dy }\n if (child.type !== 'CONNECTOR') return moved\n return {\n ...moved,\n connectorStart: shiftedEnd(child.connectorStart, dx, dy),\n connectorEnd: shiftedEnd(child.connectorEnd, dx, dy)\n }\n}\n\nfunction isTransformed(node: SceneNode): boolean {\n return node.rotation !== 0 || node.flipX || node.flipY\n}\n\n/**\n * The group's new box in its parent's space and how far its children shift in its own frame, so\n * that the group holds its children while they stay put on the canvas. An unrotated group takes\n * their bounds in its parent's space. A rotated or flipped group keeps its angle: it takes their\n * bounds in its own frame, and its position is solved so its frame still maps every child to the\n * same canvas point, as its rotation and flips are unchanged. A rotated or flipped boolean, whose\n * box comes from its result's path, keeps its bounds.\n */\nfunction fittedBox(\n graph: GroupFitGraph,\n group: SceneNode,\n parentId: string,\n children: SceneNode[],\n options: GroupFitOptions\n): { box: Rect; shift: Vector } | null {\n if (!isTransformed(group)) {\n const box =\n (group.type === 'BOOLEAN_OPERATION' ? options.booleanBounds?.(group) : null) ??\n groupBounds(graph, children, parentId, group)\n return { box, shift: { x: box.x - group.x, y: box.y - group.y } }\n }\n if (group.type === 'BOOLEAN_OPERATION') return null\n const local = groupBounds(graph, children, group.id, { x: 0, y: 0 })\n const [px, py] = Matrix.mapPoints(getNodeLocalMatrix(group), [local.x, local.y])\n const sized = { ...group, width: local.width, height: local.height }\n const [qx, qy] = Matrix.mapPoints(getNodeLocalMatrix(sized, { x: 0, y: 0 }), [0, 0])\n return {\n box: { x: px - qx, y: py - qy, width: local.width, height: local.height },\n shift: { x: local.x, y: local.y }\n }\n}\n\nconst FIT_TOLERANCE = 1e-9\n\nfunction unchanged(value: number, previous: number): boolean {\n return Math.abs(value - previous) <= FIT_TOLERANCE * Math.max(1, Math.abs(previous))\n}\n\n/**\n * The changes that fit `group` to `children`: its box in its parent's space, and each child moved\n * back so it stays put on the canvas. Null when the fit changes nothing.\n */\nexport function groupFitChanges(\n graph: GroupFitGraph,\n group: SceneNode,\n children: SceneNode[],\n options: GroupFitOptions = {}\n): Map<string, Partial<SceneNode>> | null {\n if (!group.parentId) return null\n const fitted = fittedBox(graph, group, group.parentId, children, options)\n if (!fitted) return null\n const { box, shift } = fitted\n // A rotated group's frame leaves rounding residue; a fit within it changes nothing.\n if (\n unchanged(shift.x, 0) &&\n unchanged(shift.y, 0) &&\n unchanged(box.width, group.width) &&\n unchanged(box.height, group.height)\n ) {\n return null\n }\n const changes = new Map<string, Partial<SceneNode>>([[group.id, box]])\n for (const child of children) changes.set(child.id, shiftedBack(child, shift.x, shift.y))\n return changes\n}\n\n/** Moves the group to its children's bounds, shifting them back so they stay put. */\nfunction fitGroup(\n graph: SceneGraph,\n group: SceneNode,\n children: SceneNode[],\n fit: GroupFit,\n options: GroupFitOptions\n) {\n const changes = groupFitChanges(graph, group, children, options)\n if (!changes) return\n for (const node of [group, ...children]) {\n if (!fit.before.has(node.id)) fit.before.set(node.id, placement(node))\n }\n for (const [id, change] of changes) graph.updateNode(id, change)\n for (const node of [group, ...children]) {\n const current = graph.getNode(node.id)\n if (current) fit.after.set(node.id, placement(current))\n }\n}\n\n/** A group left without layers goes away; an empty boolean stays, as in Figma. */\nfunction removeEmptyGroup(graph: SceneGraph, group: SceneNode, fit: GroupFit) {\n if (group.type !== 'GROUP' || !group.parentId) return\n const index = graph.getNode(group.parentId)?.childIds.indexOf(group.id) ?? -1\n fit.removed.push({ node: structuredClone(group), index })\n graph.deleteNode(group.id)\n}\n\n/**\n * Refits the groups and booleans around these parents to their children, keeping every child where\n * it is on the canvas, and removes groups left empty, as Figma does after a layer inside one moves,\n * resizes, or leaves. Rotated or flipped groups keep their angle; a rotated or flipped boolean keeps\n * its bounds. Returns null when nothing changed.\n */\nexport function fitEnclosingGroups(\n graph: SceneGraph,\n parentIds: Iterable<string>,\n options: GroupFitOptions = {}\n): GroupFit | null {\n const fit: GroupFit = { before: new Map(), after: new Map(), removed: [] }\n for (const group of fittedAncestors(graph, parentIds)) {\n const children = graph.getChildren(group.id)\n if (children.length === 0) removeEmptyGroup(graph, group, fit)\n else fitGroup(graph, group, children, fit, options)\n }\n return fit.before.size === 0 && fit.removed.length === 0 ? null : fit\n}\n\n/** Reapplies a fit after `undoGroupFit`. */\nexport function redoGroupFit(graph: SceneGraph, fit: GroupFit): void {\n for (const [id, value] of fit.after) graph.updateNode(id, value)\n for (const { node } of fit.removed) graph.deleteNode(node.id)\n}\n\n/** Brings back the groups a fit removed and their earlier bounds. */\nexport function undoGroupFit(graph: SceneGraph, fit: GroupFit): void {\n // Outer groups were removed after inner ones, so they come back first.\n for (const { node, index } of fit.removed.toReversed()) {\n const parentId = node.parentId ?? graph.rootId\n graph.createNode(node.type, parentId, { ...structuredClone(node), childIds: [] })\n if (index >= 0) graph.insertChildAt(node.id, parentId, index)\n }\n for (const [id, value] of fit.before) graph.updateNode(id, value)\n}\n"],"mappings":";;;;AAiCA,SAAS,UAAU,MAA4B;CAC7C,MAAM,MAAM;EAAE,GAAG,KAAK;EAAG,GAAG,KAAK;EAAG,OAAO,KAAK;EAAO,QAAQ,KAAK;CAAO;CAC3E,IAAI,KAAK,SAAS,aAAa,OAAO;CACtC,OAAO;EACL,GAAG;EACH,gBAAgB,gBAAgB,KAAK,cAAc;EACnD,cAAc,gBAAgB,KAAK,YAAY;CACjD;AACF;;AAGA,SAAS,WACP,KACA,IACA,IAC6B;CAC7B,IAAI,KAAK,WAAW,MAAM,OAAO;CACjC,OAAO;EAAE,GAAG;EAAK,UAAU;GAAE,GAAG,IAAI,SAAS,IAAI;GAAI,GAAG,IAAI,SAAS,IAAI;EAAG;CAAE;AAChF;;AAGA,SAAS,gBAAgB,OAAmB,WAA0C;CACpF,MAAM,wBAAQ,IAAI,IAAgD;CAClE,KAAK,MAAM,YAAY,WAAW;EAChC,MAAM,QAAqB,CAAC;EAC5B,KAAK,IAAI,OAAO,MAAM,QAAQ,QAAQ,GAAG,QAAQ,uBAAuB,IAAI,KAAK,IAAI,IAAI;GACvF,MAAM,KAAK,IAAI;GACf,OAAO,KAAK,WAAW,MAAM,QAAQ,K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wBAAQ,IAAI,IAAI;EAAG,uBAAO,IAAI,IAAI;EAAG,SAAS,CAAC;CAAE;CACzE,KAAK,MAAM,SAAS,gBAAgB,OAAO,SAAS,GAAG;EACrD,MAAM,WAAW,MAAM,YAAY,MAAM,EAAE;EAC3C,IAAI,SAAS,WAAW,GAAG,iBAAiB,OAAO,OAAO,GAAG;OACxD,SAAS,OAAO,OAAO,UAAU,KAAK,OAAO;CACpD;CACA,OAAO,IAAI,OAAO,SAAS,KAAK,IAAI,QAAQ,WAAW,IAAI,OAAO;AACpE;;AAGA,SAAgB,aAAa,OAAmB,KAAqB;CACnE,KAAK,MAAM,CAAC,IAAI,UAAU,IAAI,OAAO,MAAM,WAAW,IAAI,KAAK;CAC/D,KAAK,MAAM,EAAE,UAAU,IAAI,SAAS,MAAM,WAAW,KAAK,EAAE;AAC9D;;AAGA,SAAgB,aAAa,OAAmB,KAAqB;CAEnE,KAAK,MAAM,EAAE,MAAM,WAAW,IAAI,QAAQ,WAAW,GAAG;EACtD,MAAM,WAAW,KAAK,YAAY,MAAM;EACxC,MAAM,WAAW,KAAK,MAAM,UAAU;GAAE,GAAG,gBAAgB,IAAI;GAAG,UAAU,CAAC;EAAE,CAAC;EAChF,IAAI,SAAS,GAAG,MAAM,cAAc,KAAK,IAAI,UAAU,KAAK;CAC9D;CACA,KAAK,MAAM,CAAC,IAAI,UAAU,IAAI,QAAQ,MAAM,WAAW,IAAI,KAAK;AAClE"}
|
package/dist/hit-test.d.ts
CHANGED
|
@@ -18,6 +18,11 @@ interface SelectableHitOptions {
|
|
|
18
18
|
framesOpen?: boolean;
|
|
19
19
|
/** The container a double-click entered, open along with its ancestors. */
|
|
20
20
|
enteredId?: string | null;
|
|
21
|
+
/**
|
|
22
|
+
* Whether locked layers are hit, each standing in for everything inside it: a right-click
|
|
23
|
+
* selects one, as in Figma, while a press and hover pass through it.
|
|
24
|
+
*/
|
|
25
|
+
locked?: boolean;
|
|
21
26
|
}
|
|
22
27
|
declare function hitTestSelectable(graph: SceneGraph, px: number, py: number, scopeId: string, selectedIds: ReadonlySet<string>, options?: SelectableHitOptions): SceneNode | null;
|
|
23
28
|
/** Whether a click looks into this container rather than selecting it; see `hitTestSelectable`. */
|
package/dist/hit-test.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hit-test.d.ts","names":[],"sources":["../src/hit-test.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"hit-test.d.ts","names":[],"sources":["../src/hit-test.ts"],"mappings":";;;iBAgNgB,QACd,OAAO,YACP,YACA,YACA,mBACC;iBAKa,YACd,OAAO,YACP,YACA,YACA,kBACA,eACC;;;;;;;;;UA2Fc;;EAEf;;EAEA;;EAEA;;;;;EAKA;;iBAGc,kBACd,OAAO,YACP,YACA,YACA,iBACA,aAAa,qBACb,UAAS,uBACR;;iBA+Ba,gBAAgB,OAAO,YAAY,gBAAgB;;;;;iBASnD,qBACd,OAAO,YACP,YACA,YACA,kBACC;;iBAUa,cAAc,OAAO,YAAY,gBAAgB,YAAY;UAgE5D;;;;;EAKf,kBAAkB;;;;;;;;iBASJ,kBACd,OAAO,YACP,YACA,YACA,YAAY,qBACZ,kBACA,UAAS,oBACR"}
|
package/dist/hit-test.js
CHANGED
|
@@ -50,11 +50,12 @@ function containsPoint(px, py, node, graph, transformCache, pad = 0) {
|
|
|
50
50
|
const [localX, localY] = Matrix.mapPoints(inv, [px, py]);
|
|
51
51
|
return localX >= -pad && localX <= node.width + pad && localY >= -pad && localY <= node.height + pad;
|
|
52
52
|
}
|
|
53
|
-
function walkOf(deep, pad = 0, instanceBodies = false) {
|
|
53
|
+
function walkOf(deep, pad = 0, instanceBodies = false, locked = false) {
|
|
54
54
|
return {
|
|
55
55
|
deep,
|
|
56
56
|
pad,
|
|
57
57
|
instanceBodies,
|
|
58
|
+
locked,
|
|
58
59
|
transformCache: /* @__PURE__ */ new Map()
|
|
59
60
|
};
|
|
60
61
|
}
|
|
@@ -63,17 +64,21 @@ function takesEmptyArea(graph, node, walk) {
|
|
|
63
64
|
if (node.type === "COMPONENT" || showsPaint(node) || ownsItsEmptyArea(graph, node)) return true;
|
|
64
65
|
return walk.instanceBodies && node.type === "INSTANCE";
|
|
65
66
|
}
|
|
67
|
+
/**
|
|
68
|
+
* What a hit inside a container reports: the container itself when it is locked (a locked layer,
|
|
69
|
+
* where one is hit at all, stands in for everything inside it) or the walk stops at containers.
|
|
70
|
+
*/
|
|
71
|
+
function standIn(container, hit, deep) {
|
|
72
|
+
return container.locked || !deep ? container : hit;
|
|
73
|
+
}
|
|
66
74
|
function hitTestTransparentContainer(graph, px, py, child, walk) {
|
|
67
75
|
if (child.type === "GROUP") {
|
|
68
76
|
if (!containsPoint(px, py, child, graph, walk.transformCache, walk.pad)) return null;
|
|
69
77
|
const childHit = hitTestChildren(graph, px, py, child.id, walk);
|
|
70
|
-
return childHit ? walk.deep
|
|
78
|
+
return childHit ? standIn(child, childHit, walk.deep) : null;
|
|
71
79
|
}
|
|
72
80
|
const childHit = hitTestChildren(graph, px, py, child.id, walk);
|
|
73
|
-
if (childHit)
|
|
74
|
-
if (child.locked) return child;
|
|
75
|
-
return childHit;
|
|
76
|
-
}
|
|
81
|
+
if (childHit) return standIn(child, childHit, true);
|
|
77
82
|
if (containsPoint(px, py, child, graph, walk.transformCache) && takesEmptyArea(graph, child, walk)) return child;
|
|
78
83
|
return null;
|
|
79
84
|
}
|
|
@@ -87,7 +92,7 @@ function hitTestChildren(graph, px, py, parentId, walk) {
|
|
|
87
92
|
}
|
|
88
93
|
for (let i = parent.childIds.length - 1; i >= 0; i--) {
|
|
89
94
|
const child = graph.nodes.get(parent.childIds[i]);
|
|
90
|
-
if (!child || child.internalOnly || !child.visible) continue;
|
|
95
|
+
if (!child || child.internalOnly || !child.visible || child.locked && !walk.locked) continue;
|
|
91
96
|
if (CONTAINER_TYPES.has(child.type)) {
|
|
92
97
|
if (OPAQUE_CONTAINER_TYPES.has(child.type) && !walk.deep) {
|
|
93
98
|
if (containsPoint(px, py, child, graph, transformCache)) return child;
|
|
@@ -135,11 +140,12 @@ function opensByItself(graph, node, framesOpen = true) {
|
|
|
135
140
|
* Figma a click on the empty area of a frame inside an open container, or of an empty frame on the
|
|
136
141
|
* page or in a section, selects that frame, while a deep (⌘) click looks through it.
|
|
137
142
|
*/
|
|
138
|
-
function frameChildAt(graph, container, px, py, framesOpen = true) {
|
|
143
|
+
function frameChildAt(graph, container, px, py, framesOpen = true, locked = false) {
|
|
139
144
|
const transformCache = /* @__PURE__ */ new Map();
|
|
140
145
|
for (let i = container.childIds.length - 1; i >= 0; i--) {
|
|
141
146
|
const child = graph.nodes.get(container.childIds[i]);
|
|
142
147
|
if (!child || child.internalOnly || !child.visible || child.type !== "FRAME") continue;
|
|
148
|
+
if (child.locked && !locked) continue;
|
|
143
149
|
if (opensByItself(graph, child, framesOpen) && !ownsItsEmptyArea(graph, child)) continue;
|
|
144
150
|
if (containsPoint(px, py, child, graph, transformCache)) return child;
|
|
145
151
|
}
|
|
@@ -170,11 +176,11 @@ function openedBySelection(graph, selectedIds, scopeId, framesOpen, enteredId) {
|
|
|
170
176
|
return ancestors;
|
|
171
177
|
}
|
|
172
178
|
function hitTestSelectable(graph, px, py, scopeId, selectedIds, options = {}) {
|
|
173
|
-
const { pad = 0, framesOpen = true, enteredId = null } = options;
|
|
174
|
-
const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true, pad, true));
|
|
179
|
+
const { pad = 0, framesOpen = true, enteredId = null, locked = false } = options;
|
|
180
|
+
const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true, pad, true, locked));
|
|
175
181
|
if (!deepest) {
|
|
176
182
|
const scope = graph.nodes.get(scopeId);
|
|
177
|
-
return scope ? frameChildAt(graph, scope, px, py, framesOpen) : null;
|
|
183
|
+
return scope ? frameChildAt(graph, scope, px, py, framesOpen, locked) : null;
|
|
178
184
|
}
|
|
179
185
|
const chain = [];
|
|
180
186
|
for (let node = deepest; node && node.id !== scopeId;) {
|
|
@@ -188,7 +194,7 @@ function hitTestSelectable(graph, px, py, scopeId, selectedIds, options = {}) {
|
|
|
188
194
|
}
|
|
189
195
|
const last = chain.at(-1);
|
|
190
196
|
if (!last) return null;
|
|
191
|
-
const frame = frameChildAt(graph, last, px, py, framesOpen);
|
|
197
|
+
const frame = frameChildAt(graph, last, px, py, framesOpen, locked);
|
|
192
198
|
if (frame) return frame;
|
|
193
199
|
if (ownsItsEmptyArea(graph, last)) return last;
|
|
194
200
|
return opened.has(last.id) && !opensByItself(graph, last, framesOpen) ? last : null;
|
package/dist/hit-test.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hit-test.js","names":[],"sources":["../src/hit-test.ts"],"sourcesContent":["import { hitsConnectorLine } from './connectors/hit'\nimport { getWorldMatrix } from './coordinate'\nimport type { SceneGraph } from './graph'\nimport Matrix from './matrix'\nimport { hitsShape, isHitPaint, strokeReach } from './outline/hit'\nimport type { SceneNode, NodeType } from './types'\n\nconst CONTAINER_TYPES = new Set<NodeType>([\n 'CANVAS',\n 'FRAME',\n 'GROUP',\n 'SECTION',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\nconst OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])\n\n/** Whether a container's own paints show, so its empty area is drawn (see `isHitPaint`). */\nfunction showsPaint(node: SceneNode): boolean {\n return node.fills.some(isHitPaint) || node.strokes.some(isHitPaint)\n}\n\nfunction isTopLevel(graph: SceneGraph, node: SceneNode): boolean {\n const parent = node.parentId ? graph.nodes.get(node.parentId) : undefined\n return parent?.type === 'CANVAS' || parent?.type === 'SECTION'\n}\n\n/**\n * An open container whose empty area still belongs to it, as in Figma: a top-level frame with auto\n * layout is selected, hovered, and dragged by its gaps and padding, while its children stay one\n * click away, with or without a fill. A plain top-level frame's empty area is background, and a\n * nested frame's empty area belongs to it only as a click target (see `frameChildAt`).\n */\nfunction ownsItsEmptyArea(graph: SceneGraph, node: SceneNode): boolean {\n return node.type === 'FRAME' && node.layoutMode !== 'NONE' && isTopLevel(graph, node)\n}\n\nfunction hasTransformedAncestor(\n node: SceneNode,\n graph: SceneGraph,\n cache: Map<string, boolean>\n): boolean {\n const cached = cache.get(node.id)\n if (cached !== undefined) return cached\n const parent = node.parentId ? graph.getNode(node.parentId) : undefined\n const transformed =\n node.rotation !== 0 ||\n node.flipX ||\n node.flipY ||\n (parent ? hasTransformedAncestor(parent, graph, cache) : false)\n cache.set(node.id, transformed)\n return transformed\n}\n\n/** Whether the point lies in the node's box, grown by `pad` canvas units on every side. */\nfunction containsPoint(\n px: number,\n py: number,\n node: SceneNode,\n graph: SceneGraph,\n transformCache: Map<string, boolean>,\n pad = 0\n): boolean {\n if (!hasTransformedAncestor(node, graph, transformCache)) {\n const absolute = graph.getAbsolutePosition(node.id)\n return (\n px >= absolute.x - pad &&\n px <= absolute.x + node.width + pad &&\n py >= absolute.y - pad &&\n py <= absolute.y + node.height + pad\n )\n }\n\n const m = getWorldMatrix(node, graph)\n\n const inv = Matrix.invert(m)\n if (!inv) return false\n\n const [localX, localY] = Matrix.mapPoints(inv, [px, py])\n return (\n localX >= -pad && localX <= node.width + pad && localY >= -pad && localY <= node.height + pad\n )\n}\n\n/**\n * How a walk down the layers takes a click. `deep` reaches past containers to the deepest layer;\n * `pad`, in canvas units, grows each leaf layer's box, as Figma takes a click a few screen pixels\n * outside a shape; `instanceBodies` lets a deep walk take an instance's empty area whatever its\n * fill, as a plain click does, where a ⌘-click counts only a fill that shows.\n */\ninterface HitWalk {\n deep: boolean\n pad: number\n instanceBodies: boolean\n transformCache: Map<string, boolean>\n}\n\nfunction walkOf(deep: boolean, pad = 0, instanceBodies = false): HitWalk {\n return { deep, pad, instanceBodies, transformCache: new Map() }\n}\n\n/** Whether a container's empty area under the point takes a click reaching past containers. */\nfunction takesEmptyArea(graph: SceneGraph, node: SceneNode, walk: HitWalk): boolean {\n // Figma counts an empty area only where a paint shows, except a main component's, which always\n // counts, and an instance's when the click is a plain one.\n if (node.type === 'COMPONENT' || showsPaint(node) || ownsItsEmptyArea(graph, node)) return true\n return walk.instanceBodies && node.type === 'INSTANCE'\n}\n\nfunction hitTestTransparentContainer(\n graph: SceneGraph,\n px: number,\n py: number,\n child: SceneNode,\n walk: HitWalk\n): SceneNode | null {\n if (child.type === 'GROUP') {\n // A group fits its layers, so a padded click on one at its edge falls just outside it.\n if (!containsPoint(px, py, child, graph, walk.transformCache, walk.pad)) return null\n // A group has no area of its own, as in Figma: between its layers the click falls through to\n // whatever lies under the group.\n const childHit = hitTestChildren(graph, px, py, child.id, walk)\n return childHit ? (walk.deep ? childHit : child) : null\n }\n\n const childHit = hitTestChildren(graph, px, py, child.id, walk)\n if (childHit) {\n if (child.locked) return child\n return childHit\n }\n\n if (\n containsPoint(px, py, child, graph, walk.transformCache) &&\n takesEmptyArea(graph, child, walk)\n )\n return child\n return null\n}\n\n/** The topmost layer under the point among a container's children. */\nfunction hitTestChildren(\n graph: SceneGraph,\n px: number,\n py: number,\n parentId: string,\n walk: HitWalk\n): SceneNode | null {\n const parent = graph.nodes.get(parentId)\n if (!parent) return null\n const { transformCache, pad } = walk\n\n if (parent.clipsContent) {\n if (!containsPoint(px, py, parent, graph, transformCache)) return null\n }\n\n for (let i = parent.childIds.length - 1; i >= 0; i--) {\n const child = graph.nodes.get(parent.childIds[i])\n if (!child || child.internalOnly || !child.visible) continue\n if (CONTAINER_TYPES.has(child.type)) {\n if (OPAQUE_CONTAINER_TYPES.has(child.type) && !walk.deep) {\n // A plain click takes an instance or component anywhere in its box, with a fill or\n // without, as in Figma.\n if (containsPoint(px, py, child, graph, transformCache)) return child\n continue\n }\n const hit = hitTestTransparentContainer(graph, px, py, child, walk)\n if (hit) return hit\n continue\n }\n\n if (child.type === 'CONNECTOR') {\n if (hitsConnectorLine(graph, child, px, py, pad)) return child\n continue\n }\n if (hitsLeaf(graph, px, py, child, transformCache, pad)) return child\n }\n\n return null\n}\n\n/**\n * Whether a click lands on a leaf layer: on what its paints draw, as Figma tests shapes (see\n * `hitsShape`), or on its box for layers without an outline to test, such as text.\n */\nfunction hitsLeaf(\n graph: SceneGraph,\n px: number,\n py: number,\n node: SceneNode,\n transformCache: Map<string, boolean>,\n pad: number\n): boolean {\n if (!containsPoint(px, py, node, graph, transformCache, pad + strokeReach(node))) return false\n return (\n hitsShape(graph, node, px, py, pad) ?? containsPoint(px, py, node, graph, transformCache, pad)\n )\n}\n\nexport function hitTest(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId?: string\n): SceneNode | null {\n const scope = scopeId ?? graph.rootId\n return hitTestChildren(graph, px, py, scope, walkOf(false))\n}\n\nexport function hitTestDeep(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId?: string,\n pad = 0\n): SceneNode | null {\n const scope = scopeId ?? graph.rootId\n return hitTestChildren(graph, px, py, scope, walkOf(true, pad))\n}\n\n/**\n * A container a click looks into by itself, as in Figma: a top-level frame (on the page or in a\n * section) or a section that holds layers, and a component set. On a FigJam board frames stay\n * closed (`framesOpen` false): a click inside one selects the frame.\n */\nfunction opensByItself(graph: SceneGraph, node: SceneNode, framesOpen = true): boolean {\n if (node.type === 'COMPONENT_SET') return true\n if (node.childIds.length === 0) return false\n if (node.type === 'SECTION') return true\n return framesOpen && node.type === 'FRAME' && isTopLevel(graph, node)\n}\n\n/**\n * The topmost frame among a container's children whose bounds hold the point, filled or not: in\n * Figma a click on the empty area of a frame inside an open container, or of an empty frame on the\n * page or in a section, selects that frame, while a deep (⌘) click looks through it.\n */\nfunction frameChildAt(\n graph: SceneGraph,\n container: SceneNode,\n px: number,\n py: number,\n framesOpen = true\n): SceneNode | null {\n const transformCache = new Map<string, boolean>()\n for (let i = container.childIds.length - 1; i >= 0; i--) {\n const child = graph.nodes.get(container.childIds[i])\n if (!child || child.internalOnly || !child.visible || child.type !== 'FRAME') continue\n // A board, such as a top-level frame in a section, keeps its empty area as background.\n if (opensByItself(graph, child, framesOpen) && !ownsItsEmptyArea(graph, child)) continue\n if (containsPoint(px, py, child, graph, transformCache)) return child\n }\n return null\n}\n\n/**\n * The containers the selection opens: every ancestor of a selected layer inside the scope, so a\n * click reaches the siblings of selected layers, and a selected container itself, so hover and a\n * read-only click reach the layer under the point. A plain press inside a selected frame still\n * drags the frame, as in Figma, which `pressesSelection` in the Vue input decides. A selected group\n * or boolean stays closed: clicking inside it keeps it selected.\n */\nfunction openedBySelection(\n graph: SceneGraph,\n selectedIds: ReadonlySet<string>,\n scopeId: string,\n framesOpen: boolean,\n enteredId: string | null\n): Set<string> {\n const ancestors = new Set<string>()\n // An entered container is open whatever its kind, so a double-click into a board's frame\n // reaches its layers; its ancestors open with it.\n for (let id = enteredId; id && id !== scopeId && !ancestors.has(id);) {\n ancestors.add(id)\n id = graph.nodes.get(id)?.parentId ?? null\n }\n for (const id of selectedIds) {\n const node = graph.nodes.get(id)\n if (\n node &&\n node.childIds.length > 0 &&\n node.type !== 'GROUP' &&\n node.type !== 'BOOLEAN_OPERATION' &&\n // A board's frame stays closed when selected: a click inside keeps it selected.\n (framesOpen || node.type !== 'FRAME' || !isTopLevel(graph, node))\n )\n ancestors.add(id)\n let parentId = node?.parentId\n while (parentId && parentId !== scopeId && !ancestors.has(parentId)) {\n ancestors.add(parentId)\n parentId = graph.nodes.get(parentId)?.parentId\n }\n }\n return ancestors\n}\n\n/**\n * The layer a click selects, as in Figma. It walks from the scope down to the deepest layer under\n * the point and stops at the first layer that is not open. Top-level frames and sections with\n * layers and component sets are open, and so is every ancestor of the selection, so clicks reach\n * the siblings of selected layers. Where every layer under the point is open, a container opened\n * by the selection is selected, so is a top-level frame with auto layout, and a plain top-level\n * frame or a section is not.\n */\nexport interface SelectableHitOptions {\n /** Canvas units a leaf layer's box grows by, as Figma takes a click a few pixels outside. */\n pad?: number\n /** Whether top-level frames are looked into (a design) or selected whole (a board). */\n framesOpen?: boolean\n /** The container a double-click entered, open along with its ancestors. */\n enteredId?: string | null\n}\n\nexport function hitTestSelectable(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId: string,\n selectedIds: ReadonlySet<string>,\n options: SelectableHitOptions = {}\n): SceneNode | null {\n const { pad = 0, framesOpen = true, enteredId = null } = options\n // A plain click: the walk takes an instance's empty area whatever its fill.\n const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true, pad, true))\n if (!deepest) {\n const scope = graph.nodes.get(scopeId)\n return scope ? frameChildAt(graph, scope, px, py, framesOpen) : null\n }\n\n const chain: SceneNode[] = []\n for (let node: SceneNode | undefined = deepest; node && node.id !== scopeId;) {\n chain.unshift(node)\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n\n const opened = openedBySelection(graph, selectedIds, scopeId, framesOpen, enteredId)\n\n for (const node of chain) {\n // A locked layer stands in for everything inside it.\n if (node.locked) return node\n if (!opened.has(node.id) && !opensByItself(graph, node, framesOpen)) return node\n }\n const last = chain.at(-1)\n if (!last) return null\n const frame = frameChildAt(graph, last, px, py, framesOpen)\n if (frame) return frame\n if (ownsItsEmptyArea(graph, last)) return last\n return opened.has(last.id) && !opensByItself(graph, last, framesOpen) ? last : null\n}\n\n/** Whether a click looks into this container rather than selecting it; see `hitTestSelectable`. */\nexport function isOpenContainer(graph: SceneGraph, nodeId: string, framesOpen = true): boolean {\n const node = graph.nodes.get(nodeId)\n return node !== undefined && opensByItself(graph, node, framesOpen)\n}\n\n/**\n * The innermost open container under the point when every layer there is open: a marquee starting\n * here selects that container's layers, as in Figma.\n */\nexport function hitTestOpenContainer(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId: string\n): SceneNode | null {\n const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true))\n for (let node: SceneNode | undefined = deepest ?? undefined; node && node.id !== scopeId;) {\n if (!opensByItself(graph, node) || ownsItsEmptyArea(graph, node)) return null\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n return deepest\n}\n\n/** Whether the point lies inside the node's rotated and flipped bounds. */\nexport function isPointInNode(graph: SceneGraph, nodeId: string, px: number, py: number): boolean {\n const node = graph.nodes.get(nodeId)\n return node !== undefined && containsPoint(px, py, node, graph, new Map())\n}\n\n/** Which layers take a drop, and which are only looked through, as in Figma. */\ninterface DropRules {\n takes: (node: SceneNode) => boolean\n passThrough: ReadonlySet<NodeType>\n}\n\nconst LAYER_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'COMPONENT', 'INSTANCE'])\nconst COMPONENT_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'INSTANCE'])\n\nfunction dropRules(options: DropTargetOptions): DropRules {\n const { componentSetIds } = options\n if (!componentSetIds) {\n return {\n takes: (node) => LAYER_TARGETS.has(node.type),\n passThrough: new Set(['GROUP', 'COMPONENT_SET'])\n }\n }\n // Components never go into other components, and a set only takes back its own variants.\n return {\n takes: (node) =>\n COMPONENT_TARGETS.has(node.type) ||\n (node.type === 'COMPONENT_SET' && componentSetIds.has(node.id)),\n passThrough: new Set(['GROUP'])\n }\n}\n\nfunction dropTargetIn(\n graph: SceneGraph,\n px: number,\n py: number,\n parent: SceneNode,\n excludeIds: ReadonlySet<string>,\n rules: DropRules,\n transformCache: Map<string, boolean>\n): SceneNode | null {\n // A clipped-away part of a child is not under the cursor.\n if (\n parent.type !== 'CANVAS' &&\n parent.clipsContent &&\n !containsPoint(px, py, parent, graph, transformCache)\n )\n return null\n\n for (let i = parent.childIds.length - 1; i >= 0; i--) {\n const childId = parent.childIds[i]\n if (excludeIds.has(childId)) continue\n const child = graph.nodes.get(childId)\n if (!child || child.internalOnly || !child.visible || child.locked) continue\n const target = rules.takes(child)\n if (!target && !rules.passThrough.has(child.type)) continue\n\n const deeper = dropTargetIn(graph, px, py, child, excludeIds, rules, transformCache)\n if (deeper) return deeper\n if (target && containsPoint(px, py, child, graph, transformCache)) return child\n }\n\n return null\n}\n\nexport interface DropTargetOptions {\n /**\n * Set when the dropped layers are all main components: the component sets they come from.\n * Components then go only into frames, sections, instances, and those sets.\n */\n componentSetIds?: ReadonlySet<string>\n}\n\n/**\n * The topmost unlocked frame, section, component, or instance under the point, in its rotated\n * shape and inside its clipping ancestors. Groups and component sets are looked through but never\n * returned, except that a set takes dropped components; locked layers and their contents are\n * skipped.\n */\nexport function hitTestDropTarget(\n graph: SceneGraph,\n px: number,\n py: number,\n excludeIds: ReadonlySet<string>,\n scopeId?: string,\n options: DropTargetOptions = {}\n): SceneNode | null {\n const scope = graph.nodes.get(scopeId ?? graph.rootId)\n if (!scope) return null\n return dropTargetIn(graph, px, py, scope, excludeIds, dropRules(options), new Map())\n}\n"],"mappings":";;;;;AAOA,MAAM,kCAAkB,IAAI,IAAc;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,yCAAyB,IAAI,IAAc,CAAC,aAAa,UAAU,CAAC;;AAG1E,SAAS,WAAW,MAA0B;CAC5C,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,KAAK,QAAQ,KAAK,UAAU;AACpE;AAEA,SAAS,WAAW,OAAmB,MAA0B;CAC/D,MAAM,SAAS,KAAK,WAAW,MAAM,MAAM,IAAI,KAAK,QAAQ,IAAI,KAAA;CAChE,OAAO,QAAQ,SAAS,YAAY,QAAQ,SAAS;AACvD;;;;;;;AAQA,SAAS,iBAAiB,OAAmB,MAA0B;CACrE,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe,UAAU,WAAW,OAAO,IAAI;AACtF;AAEA,SAAS,uBACP,MACA,OACA,OACS;CACT,MAAM,SAAS,MAAM,IAAI,KAAK,EAAE;CAChC,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,SAAS,KAAK,WAAW,MAAM,QAAQ,KAAK,QAAQ,IAAI,KAAA;CAC9D,MAAM,cACJ,KAAK,aAAa,KAClB,KAAK,SACL,KAAK,UACJ,SAAS,uBAAuB,QAAQ,OAAO,KAAK,IAAI;CAC3D,MAAM,IAAI,KAAK,IAAI,WAAW;CAC9B,OAAO;AACT;;AAGA,SAAS,cACP,IACA,IACA,MACA,OACA,gBACA,MAAM,GAC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IAAI,CAAC,OAAO,CAAC;CAChC;AACF;AAEA,SAAS,aACP,OACA,IACA,IACA,QACA,YACA,OACA,gBACkB;CAElB,IACE,OAAO,SAAS,YAChB,OAAO,gBACP,CAAC,cAAc,IAAI,IAAI,QAAQ,OAAO,cAAc,GAEpD,OAAO;CAET,KAAK,IAAI,IAAI,OAAO,SAAS,SAAS,GAAG,KAAK,GAAG,KAAK;EACpD,MAAM,UAAU,OAAO,SAAS;EAChC,IAAI,WAAW,IAAI,OAAO,GAAG;EAC7B,MAAM,QAAQ,MAAM,MAAM,IAAI,OAAO;EACrC,IAAI,CAAC,SAAS,MAAM,gBAAgB,CAAC,MAAM,WAAW,MAAM,QAAQ;EACpE,MAAM,SAAS,MAAM,MAAM,KAAK;EAChC,IAAI,CAAC,UAAU,CAAC,MAAM,YAAY,IAAI,MAAM,IAAI,GAAG;EAEnD,MAAM,SAAS,aAAa,OAAO,IAAI,IAAI,OAAO,YAAY,OAAO,cAAc;EACnF,IAAI,QAAQ,OAAO;EACnB,IAAI,UAAU,cAAc,IAAI,IAAI,OAAO,OAAO,cAAc,GAAG,OAAO;CAC5E;CAEA,OAAO;AACT;;;;;;;AAgBA,SAAgB,kBACd,OACA,IACA,IACA,YACA,SACA,UAA6B,CAAC,GACZ;CAClB,MAAM,QAAQ,MAAM,MAAM,IAAI,WAAW,MAAM,MAAM;CACrD,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,aAAa,OAAO,IAAI,IAAI,OAAO,YAAY,UAAU,OAAO,mBAAG,IAAI,IAAI,CAAC;AACrF"}
|
|
1
|
+
{"version":3,"file":"hit-test.js","names":[],"sources":["../src/hit-test.ts"],"sourcesContent":["import { hitsConnectorLine } from './connectors/hit'\nimport { getWorldMatrix } from './coordinate'\nimport type { SceneGraph } from './graph'\nimport Matrix from './matrix'\nimport { hitsShape, isHitPaint, strokeReach } from './outline/hit'\nimport type { SceneNode, NodeType } from './types'\n\nconst CONTAINER_TYPES = new Set<NodeType>([\n 'CANVAS',\n 'FRAME',\n 'GROUP',\n 'SECTION',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\nconst OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])\n\n/** Whether a container's own paints show, so its empty area is drawn (see `isHitPaint`). */\nfunction showsPaint(node: SceneNode): boolean {\n return node.fills.some(isHitPaint) || node.strokes.some(isHitPaint)\n}\n\nfunction isTopLevel(graph: SceneGraph, node: SceneNode): boolean {\n const parent = node.parentId ? graph.nodes.get(node.parentId) : undefined\n return parent?.type === 'CANVAS' || parent?.type === 'SECTION'\n}\n\n/**\n * An open container whose empty area still belongs to it, as in Figma: a top-level frame with auto\n * layout is selected, hovered, and dragged by its gaps and padding, while its children stay one\n * click away, with or without a fill. A plain top-level frame's empty area is background, and a\n * nested frame's empty area belongs to it only as a click target (see `frameChildAt`).\n */\nfunction ownsItsEmptyArea(graph: SceneGraph, node: SceneNode): boolean {\n return node.type === 'FRAME' && node.layoutMode !== 'NONE' && isTopLevel(graph, node)\n}\n\nfunction hasTransformedAncestor(\n node: SceneNode,\n graph: SceneGraph,\n cache: Map<string, boolean>\n): boolean {\n const cached = cache.get(node.id)\n if (cached !== undefined) return cached\n const parent = node.parentId ? graph.getNode(node.parentId) : undefined\n const transformed =\n node.rotation !== 0 ||\n node.flipX ||\n node.flipY ||\n (parent ? hasTransformedAncestor(parent, graph, cache) : false)\n cache.set(node.id, transformed)\n return transformed\n}\n\n/** Whether the point lies in the node's box, grown by `pad` canvas units on every side. */\nfunction containsPoint(\n px: number,\n py: number,\n node: SceneNode,\n graph: SceneGraph,\n transformCache: Map<string, boolean>,\n pad = 0\n): boolean {\n if (!hasTransformedAncestor(node, graph, transformCache)) {\n const absolute = graph.getAbsolutePosition(node.id)\n return (\n px >= absolute.x - pad &&\n px <= absolute.x + node.width + pad &&\n py >= absolute.y - pad &&\n py <= absolute.y + node.height + pad\n )\n }\n\n const m = getWorldMatrix(node, graph)\n\n const inv = Matrix.invert(m)\n if (!inv) return false\n\n const [localX, localY] = Matrix.mapPoints(inv, [px, py])\n return (\n localX >= -pad && localX <= node.width + pad && localY >= -pad && localY <= node.height + pad\n )\n}\n\n/**\n * How a walk down the layers takes a click. `deep` reaches past containers to the deepest layer;\n * `pad`, in canvas units, grows each leaf layer's box, as Figma takes a click a few screen pixels\n * outside a shape; `instanceBodies` lets a deep walk take an instance's empty area whatever its\n * fill, as a plain click does, where a ⌘-click counts only a fill that shows.\n */\ninterface HitWalk {\n deep: boolean\n pad: number\n instanceBodies: boolean\n /** Whether locked layers are hit, as by a right-click; see `SelectableHitOptions.locked`. */\n locked: boolean\n transformCache: Map<string, boolean>\n}\n\nfunction walkOf(deep: boolean, pad = 0, instanceBodies = false, locked = false): HitWalk {\n return { deep, pad, instanceBodies, locked, transformCache: new Map() }\n}\n\n/** Whether a container's empty area under the point takes a click reaching past containers. */\nfunction takesEmptyArea(graph: SceneGraph, node: SceneNode, walk: HitWalk): boolean {\n // Figma counts an empty area only where a paint shows, except a main component's, which always\n // counts, and an instance's when the click is a plain one.\n if (node.type === 'COMPONENT' || showsPaint(node) || ownsItsEmptyArea(graph, node)) return true\n return walk.instanceBodies && node.type === 'INSTANCE'\n}\n\n/**\n * What a hit inside a container reports: the container itself when it is locked (a locked layer,\n * where one is hit at all, stands in for everything inside it) or the walk stops at containers.\n */\nfunction standIn(container: SceneNode, hit: SceneNode, deep: boolean): SceneNode {\n return container.locked || !deep ? container : hit\n}\n\nfunction hitTestTransparentContainer(\n graph: SceneGraph,\n px: number,\n py: number,\n child: SceneNode,\n walk: HitWalk\n): SceneNode | null {\n if (child.type === 'GROUP') {\n // A group fits its layers, so a padded click on one at its edge falls just outside it.\n if (!containsPoint(px, py, child, graph, walk.transformCache, walk.pad)) return null\n // A group has no area of its own, as in Figma: between its layers the click falls through to\n // whatever lies under the group.\n const childHit = hitTestChildren(graph, px, py, child.id, walk)\n return childHit ? standIn(child, childHit, walk.deep) : null\n }\n\n const childHit = hitTestChildren(graph, px, py, child.id, walk)\n if (childHit) return standIn(child, childHit, true)\n\n if (\n containsPoint(px, py, child, graph, walk.transformCache) &&\n takesEmptyArea(graph, child, walk)\n )\n return child\n return null\n}\n\n/** The topmost layer under the point among a container's children. */\nfunction hitTestChildren(\n graph: SceneGraph,\n px: number,\n py: number,\n parentId: string,\n walk: HitWalk\n): SceneNode | null {\n const parent = graph.nodes.get(parentId)\n if (!parent) return null\n const { transformCache, pad } = walk\n\n if (parent.clipsContent) {\n if (!containsPoint(px, py, parent, graph, transformCache)) return null\n }\n\n for (let i = parent.childIds.length - 1; i >= 0; i--) {\n const child = graph.nodes.get(parent.childIds[i])\n // A locked layer and everything in it are invisible to a press and to hover, as in Figma: a\n // click falls through to what lies under it, and a drag from it draws a marquee.\n if (!child || child.internalOnly || !child.visible || (child.locked && !walk.locked)) continue\n if (CONTAINER_TYPES.has(child.type)) {\n if (OPAQUE_CONTAINER_TYPES.has(child.type) && !walk.deep) {\n // A plain click takes an instance or component anywhere in its box, with a fill or\n // without, as in Figma.\n if (containsPoint(px, py, child, graph, transformCache)) return child\n continue\n }\n const hit = hitTestTransparentContainer(graph, px, py, child, walk)\n if (hit) return hit\n continue\n }\n\n if (child.type === 'CONNECTOR') {\n if (hitsConnectorLine(graph, child, px, py, pad)) return child\n continue\n }\n if (hitsLeaf(graph, px, py, child, transformCache, pad)) return child\n }\n\n return null\n}\n\n/**\n * Whether a click lands on a leaf layer: on what its paints draw, as Figma tests shapes (see\n * `hitsShape`), or on its box for layers without an outline to test, such as text.\n */\nfunction hitsLeaf(\n graph: SceneGraph,\n px: number,\n py: number,\n node: SceneNode,\n transformCache: Map<string, boolean>,\n pad: number\n): boolean {\n if (!containsPoint(px, py, node, graph, transformCache, pad + strokeReach(node))) return false\n return (\n hitsShape(graph, node, px, py, pad) ?? containsPoint(px, py, node, graph, transformCache, pad)\n )\n}\n\nexport function hitTest(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId?: string\n): SceneNode | null {\n const scope = scopeId ?? graph.rootId\n return hitTestChildren(graph, px, py, scope, walkOf(false))\n}\n\nexport function hitTestDeep(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId?: string,\n pad = 0\n): SceneNode | null {\n const scope = scopeId ?? graph.rootId\n return hitTestChildren(graph, px, py, scope, walkOf(true, pad))\n}\n\n/**\n * A container a click looks into by itself, as in Figma: a top-level frame (on the page or in a\n * section) or a section that holds layers, and a component set. On a FigJam board frames stay\n * closed (`framesOpen` false): a click inside one selects the frame.\n */\nfunction opensByItself(graph: SceneGraph, node: SceneNode, framesOpen = true): boolean {\n if (node.type === 'COMPONENT_SET') return true\n if (node.childIds.length === 0) return false\n if (node.type === 'SECTION') return true\n return framesOpen && node.type === 'FRAME' && isTopLevel(graph, node)\n}\n\n/**\n * The topmost frame among a container's children whose bounds hold the point, filled or not: in\n * Figma a click on the empty area of a frame inside an open container, or of an empty frame on the\n * page or in a section, selects that frame, while a deep (⌘) click looks through it.\n */\nfunction frameChildAt(\n graph: SceneGraph,\n container: SceneNode,\n px: number,\n py: number,\n framesOpen = true,\n locked = false\n): SceneNode | null {\n const transformCache = new Map<string, boolean>()\n for (let i = container.childIds.length - 1; i >= 0; i--) {\n const child = graph.nodes.get(container.childIds[i])\n if (!child || child.internalOnly || !child.visible || child.type !== 'FRAME') continue\n if (child.locked && !locked) continue\n // A board, such as a top-level frame in a section, keeps its empty area as background.\n if (opensByItself(graph, child, framesOpen) && !ownsItsEmptyArea(graph, child)) continue\n if (containsPoint(px, py, child, graph, transformCache)) return child\n }\n return null\n}\n\n/**\n * The containers the selection opens: every ancestor of a selected layer inside the scope, so a\n * click reaches the siblings of selected layers, and a selected container itself, so hover and a\n * read-only click reach the layer under the point. A plain press inside a selected frame still\n * drags the frame, as in Figma, which `pressesSelection` in the Vue input decides. A selected group\n * or boolean stays closed: clicking inside it keeps it selected.\n */\nfunction openedBySelection(\n graph: SceneGraph,\n selectedIds: ReadonlySet<string>,\n scopeId: string,\n framesOpen: boolean,\n enteredId: string | null\n): Set<string> {\n const ancestors = new Set<string>()\n // An entered container is open whatever its kind, so a double-click into a board's frame\n // reaches its layers; its ancestors open with it.\n for (let id = enteredId; id && id !== scopeId && !ancestors.has(id);) {\n ancestors.add(id)\n id = graph.nodes.get(id)?.parentId ?? null\n }\n for (const id of selectedIds) {\n const node = graph.nodes.get(id)\n if (\n node &&\n node.childIds.length > 0 &&\n node.type !== 'GROUP' &&\n node.type !== 'BOOLEAN_OPERATION' &&\n // A board's frame stays closed when selected: a click inside keeps it selected.\n (framesOpen || node.type !== 'FRAME' || !isTopLevel(graph, node))\n )\n ancestors.add(id)\n let parentId = node?.parentId\n while (parentId && parentId !== scopeId && !ancestors.has(parentId)) {\n ancestors.add(parentId)\n parentId = graph.nodes.get(parentId)?.parentId\n }\n }\n return ancestors\n}\n\n/**\n * The layer a click selects, as in Figma. It walks from the scope down to the deepest layer under\n * the point and stops at the first layer that is not open. Top-level frames and sections with\n * layers and component sets are open, and so is every ancestor of the selection, so clicks reach\n * the siblings of selected layers. Where every layer under the point is open, a container opened\n * by the selection is selected, so is a top-level frame with auto layout, and a plain top-level\n * frame or a section is not.\n */\nexport interface SelectableHitOptions {\n /** Canvas units a leaf layer's box grows by, as Figma takes a click a few pixels outside. */\n pad?: number\n /** Whether top-level frames are looked into (a design) or selected whole (a board). */\n framesOpen?: boolean\n /** The container a double-click entered, open along with its ancestors. */\n enteredId?: string | null\n /**\n * Whether locked layers are hit, each standing in for everything inside it: a right-click\n * selects one, as in Figma, while a press and hover pass through it.\n */\n locked?: boolean\n}\n\nexport function hitTestSelectable(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId: string,\n selectedIds: ReadonlySet<string>,\n options: SelectableHitOptions = {}\n): SceneNode | null {\n const { pad = 0, framesOpen = true, enteredId = null, locked = false } = options\n // A plain click: the walk takes an instance's empty area whatever its fill.\n const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true, pad, true, locked))\n if (!deepest) {\n const scope = graph.nodes.get(scopeId)\n return scope ? frameChildAt(graph, scope, px, py, framesOpen, locked) : null\n }\n\n const chain: SceneNode[] = []\n for (let node: SceneNode | undefined = deepest; node && node.id !== scopeId;) {\n chain.unshift(node)\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n\n const opened = openedBySelection(graph, selectedIds, scopeId, framesOpen, enteredId)\n\n for (const node of chain) {\n // A locked layer, hit only with `locked`, stands in for everything inside it.\n if (node.locked) return node\n if (!opened.has(node.id) && !opensByItself(graph, node, framesOpen)) return node\n }\n const last = chain.at(-1)\n if (!last) return null\n const frame = frameChildAt(graph, last, px, py, framesOpen, locked)\n if (frame) return frame\n if (ownsItsEmptyArea(graph, last)) return last\n return opened.has(last.id) && !opensByItself(graph, last, framesOpen) ? last : null\n}\n\n/** Whether a click looks into this container rather than selecting it; see `hitTestSelectable`. */\nexport function isOpenContainer(graph: SceneGraph, nodeId: string, framesOpen = true): boolean {\n const node = graph.nodes.get(nodeId)\n return node !== undefined && opensByItself(graph, node, framesOpen)\n}\n\n/**\n * The innermost open container under the point when every layer there is open: a marquee starting\n * here selects that container's layers, as in Figma.\n */\nexport function hitTestOpenContainer(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId: string\n): SceneNode | null {\n const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true))\n for (let node: SceneNode | undefined = deepest ?? undefined; node && node.id !== scopeId;) {\n if (!opensByItself(graph, node) || ownsItsEmptyArea(graph, node)) return null\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n return deepest\n}\n\n/** Whether the point lies inside the node's rotated and flipped bounds. */\nexport function isPointInNode(graph: SceneGraph, nodeId: string, px: number, py: number): boolean {\n const node = graph.nodes.get(nodeId)\n return node !== undefined && containsPoint(px, py, node, graph, new Map())\n}\n\n/** Which layers take a drop, and which are only looked through, as in Figma. */\ninterface DropRules {\n takes: (node: SceneNode) => boolean\n passThrough: ReadonlySet<NodeType>\n}\n\nconst LAYER_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'COMPONENT', 'INSTANCE'])\nconst COMPONENT_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'INSTANCE'])\n\nfunction dropRules(options: DropTargetOptions): DropRules {\n const { componentSetIds } = options\n if (!componentSetIds) {\n return {\n takes: (node) => LAYER_TARGETS.has(node.type),\n passThrough: new Set(['GROUP', 'COMPONENT_SET'])\n }\n }\n // Components never go into other components, and a set only takes back its own variants.\n return {\n takes: (node) =>\n COMPONENT_TARGETS.has(node.type) ||\n (node.type === 'COMPONENT_SET' && componentSetIds.has(node.id)),\n passThrough: new Set(['GROUP'])\n }\n}\n\nfunction dropTargetIn(\n graph: SceneGraph,\n px: number,\n py: number,\n parent: SceneNode,\n excludeIds: ReadonlySet<string>,\n rules: DropRules,\n transformCache: Map<string, boolean>\n): SceneNode | null {\n // A clipped-away part of a child is not under the cursor.\n if (\n parent.type !== 'CANVAS' &&\n parent.clipsContent &&\n !containsPoint(px, py, parent, graph, transformCache)\n )\n return null\n\n for (let i = parent.childIds.length - 1; i >= 0; i--) {\n const childId = parent.childIds[i]\n if (excludeIds.has(childId)) continue\n const child = graph.nodes.get(childId)\n if (!child || child.internalOnly || !child.visible || child.locked) continue\n const target = rules.takes(child)\n if (!target && !rules.passThrough.has(child.type)) continue\n\n const deeper = dropTargetIn(graph, px, py, child, excludeIds, rules, transformCache)\n if (deeper) return deeper\n if (target && containsPoint(px, py, child, graph, transformCache)) return child\n }\n\n return null\n}\n\nexport interface DropTargetOptions {\n /**\n * Set when the dropped layers are all main components: the component sets they come from.\n * Components then go only into frames, sections, instances, and those sets.\n */\n componentSetIds?: ReadonlySet<string>\n}\n\n/**\n * The topmost unlocked frame, section, component, or instance under the point, in its rotated\n * shape and inside its clipping ancestors. Groups and component sets are looked through but never\n * returned, except that a set takes dropped components; locked layers and their contents are\n * skipped.\n */\nexport function hitTestDropTarget(\n graph: SceneGraph,\n px: number,\n py: number,\n excludeIds: ReadonlySet<string>,\n scopeId?: string,\n options: DropTargetOptions = {}\n): SceneNode | null {\n const scope = graph.nodes.get(scopeId ?? graph.rootId)\n if (!scope) return null\n return dropTargetIn(graph, px, py, scope, excludeIds, dropRules(options), new Map())\n}\n"],"mappings":";;;;;AAOA,MAAM,kCAAkB,IAAI,IAAc;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,yCAAyB,IAAI,IAAc,CAAC,aAAa,UAAU,CAAC;;AAG1E,SAAS,WAAW,MAA0B;CAC5C,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,KAAK,QAAQ,KAAK,UAAU;AACpE;AAEA,SAAS,WAAW,OAAmB,MAA0B;CAC/D,MAAM,SAAS,KAAK,WAAW,MAAM,MAAM,IAAI,KAAK,QAAQ,IAAI,KAAA;CAChE,OAAO,QAAQ,SAAS,YAAY,QAAQ,SAAS;AACvD;;;;;;;AAQA,SAAS,iBAAiB,OAAmB,MAA0B;CACrE,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe,UAAU,WAAW,OAAO,IAAI;AACtF;AAEA,SAAS,uBACP,MACA,OACA,OACS;CACT,MAAM,SAAS,MAAM,IAAI,KAAK,EAAE;CAChC,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,SAAS,KAAK,WAAW,MAAM,QAAQ,KAAK,QAAQ,IAAI,KAAA;CAC9D,MAAM,cACJ,KAAK,aAAa,KAClB,KAAK,SACL,KAAK,UACJ,SAAS,uBAAuB,QAAQ,OAAO,KAAK,IAAI;CAC3D,MAAM,IAAI,KAAK,IAAI,WAAW;CAC9B,OAAO;AACT;;AAGA,SAAS,cACP,IACA,IACA,MACA,OACA,gBACA,MAAM,GACG;CACT,IAAI,CAAC,uBAAuB,MAAM,OAAO,cAAc,GAAG;EACxD,MAAM,WAAW,MAAM,oBAAoB,KAAK,EAAE;EAClD,OACE,MAAM,SAAS,IAAI,OACnB,MAAM,SAAS,IAAI,KAAK,QAAQ,OAChC,MAAM,SAAS,IAAI,OACnB,MAAM,SAAS,IAAI,KA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Aa,IAAI,IAAI,CAAC,OAAO,CAAC;CAChC;AACF;AAEA,SAAS,aACP,OACA,IACA,IACA,QACA,YACA,OACA,gBACkB;CAElB,IACE,OAAO,SAAS,YAChB,OAAO,gBACP,CAAC,cAAc,IAAI,IAAI,QAAQ,OAAO,cAAc,GAEpD,OAAO;CAET,KAAK,IAAI,IAAI,OAAO,SAAS,SAAS,GAAG,KAAK,GAAG,KAAK;EACpD,MAAM,UAAU,OAAO,SAAS;EAChC,IAAI,WAAW,IAAI,OAAO,GAAG;EAC7B,MAAM,QAAQ,MAAM,MAAM,IAAI,OAAO;EACrC,IAAI,CAAC,SAAS,MAAM,gBAAgB,CAAC,MAAM,WAAW,MAAM,QAAQ;EACpE,MAAM,SAAS,MAAM,MAAM,KAAK;EAChC,IAAI,CAAC,UAAU,CAAC,MAAM,YAAY,IAAI,MAAM,IAAI,GAAG;EAEnD,MAAM,SAAS,aAAa,OAAO,IAAI,IAAI,OAAO,YAAY,OAAO,cAAc;EACnF,IAAI,QAAQ,OAAO;EACnB,IAAI,UAAU,cAAc,IAAI,IAAI,OAAO,OAAO,cAAc,GAAG,OAAO;CAC5E;CAEA,OAAO;AACT;;;;;;;AAgBA,SAAgB,kBACd,OACA,IACA,IACA,YACA,SACA,UAA6B,CAAC,GACZ;CAClB,MAAM,QAAQ,MAAM,MAAM,IAAI,WAAW,MAAM,MAAM;CACrD,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,aAAa,OAAO,IAAI,IAAI,OAAO,YAAY,UAAU,OAAO,mBAAG,IAAI,IAAI,CAAC;AACrF"}
|
package/dist/images.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Matrix, Size } from "./primitives/index.js";
|
|
2
|
+
import { Fill } from "./types.js";
|
|
2
3
|
//#region src/images.d.ts
|
|
3
4
|
/**
|
|
4
5
|
* The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,
|
|
@@ -6,7 +7,7 @@ import { Matrix, Size } from "./primitives/index.js";
|
|
|
6
7
|
* hold images under other names; anything that hands images to Figma still checks.
|
|
7
8
|
*/
|
|
8
9
|
declare function computeImageHash(data: Uint8Array): string;
|
|
9
|
-
type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp';
|
|
10
|
+
type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/avif';
|
|
10
11
|
/** The raster types a dropped or pasted file can be imported as an image fill from. */
|
|
11
12
|
declare const IMPORTABLE_RASTER_TYPES: ReadonlySet<string>;
|
|
12
13
|
/** Whether a file is an SVG image, which some systems report without a media type. */
|
|
@@ -18,7 +19,7 @@ interface ImageHeader extends Size {
|
|
|
18
19
|
type: ImageMimeType;
|
|
19
20
|
}
|
|
20
21
|
/**
|
|
21
|
-
* The type and size of a PNG, JPEG, GIF, or
|
|
22
|
+
* The type and size of a PNG, JPEG, GIF, WebP, or AVIF, read from its header by `image-size`; null for
|
|
22
23
|
* bytes it cannot read and for other formats.
|
|
23
24
|
*/
|
|
24
25
|
declare function imageHeader(data: Uint8Array): ImageHeader | null;
|
|
@@ -27,6 +28,22 @@ declare function imageHeader(data: Uint8Array): ImageHeader | null;
|
|
|
27
28
|
* URL or file. Bytes it cannot read are reported as PNG, as image fills began.
|
|
28
29
|
*/
|
|
29
30
|
declare function imageMimeType(data: Uint8Array): ImageMimeType;
|
|
31
|
+
interface DataURL {
|
|
32
|
+
/** The media type in lowercase, without parameters; `text/plain` when the URL names none. */
|
|
33
|
+
mimeType: string;
|
|
34
|
+
bytes: Uint8Array;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The media type and bytes a `data:` URL carries: a Base64 body decoded, and a percent-encoded
|
|
38
|
+
* one unescaped as UTF-8 text, as SVG and other markup are written. Null for anything else: Base64
|
|
39
|
+
* cut short in transit, and escapes that are not UTF-8, such as a binary image escaped byte by
|
|
40
|
+
* byte, which a reader that must take any data URL, such as `.pen` loading, gets from `fetch`.
|
|
41
|
+
*/
|
|
42
|
+
declare function parseDataURL(url: string): DataURL | null;
|
|
43
|
+
/** Encoded image bytes as a Base64 data URL of the type their header names. */
|
|
44
|
+
declare function imageDataURL(data: Uint8Array): string;
|
|
45
|
+
/** SVG markup as a percent-encoded data URL, as CSS `url()` and `<img src>` take one. */
|
|
46
|
+
declare function svgDataURL(svg: string): string;
|
|
30
47
|
/** An image's size in pixels, read from its header; null for bytes it cannot read. */
|
|
31
48
|
declare function imageSize(data: Uint8Array): Size | null;
|
|
32
49
|
/**
|
|
@@ -34,6 +51,13 @@ declare function imageSize(data: Uint8Array): Size | null;
|
|
|
34
51
|
* centred. Figma starts a crop from it, as the image-space window a crop's transform holds.
|
|
35
52
|
*/
|
|
36
53
|
declare function coverImageTransform(width: number, height: number, imageWidth: number, imageHeight: number): Matrix;
|
|
54
|
+
/** The images `paints` show, by their hashes. */
|
|
55
|
+
declare function imagePaintHashes(paints: Iterable<Fill>): string[];
|
|
56
|
+
/**
|
|
57
|
+
* Copies the images `hashes` name from `from` into `to`, each as bytes of its own. An image is
|
|
58
|
+
* named by its content, so one `to` already holds stays.
|
|
59
|
+
*/
|
|
60
|
+
declare function copyImages(from: ReadonlyMap<string, Uint8Array>, to: Map<string, Uint8Array>, hashes: Iterable<string>): void;
|
|
37
61
|
//#endregion
|
|
38
|
-
export { IMPORTABLE_RASTER_TYPES, ImageHeader, ImageMimeType, computeImageHash, coverImageTransform, imageHeader, imageMimeType, imageSize, isSVGFile };
|
|
62
|
+
export { DataURL, IMPORTABLE_RASTER_TYPES, ImageHeader, ImageMimeType, computeImageHash, copyImages, coverImageTransform, imageDataURL, imageHeader, imageMimeType, imagePaintHashes, imageSize, isSVGFile, parseDataURL, svgDataURL };
|
|
39
63
|
//# sourceMappingURL=images.d.ts.map
|
package/dist/images.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"images.d.ts","names":[],"sources":["../src/images.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"images.d.ts","names":[],"sources":["../src/images.ts"],"mappings":";;;;;;;;iBAagB,iBAAiB,MAAM;KAI3B;;cAYC,yBAAyB;;iBAStB,UAAU;EAAQ;EAAc;;UAM/B,oBAAoB;EACnC,MAAM;;;;;;iBAOQ,YAAY,MAAM,aAAa;;;;;iBAe/B,cAAc,MAAM,aAAa;UAIhC;;EAEf;EACA,OAAO;;;;;;;;iBASO,aAAa,cAAc;;iBAsB3B,aAAa,MAAM;;iBAKnB,WAAW;;iBAKX,UAAU,MAAM,aAAa;;;;;iBAS7B,oBACd,eACA,gBACA,oBACA,sBACC;;iBAQa,iBAAiB,QAAQ,SAAS;;;;;iBAUlC,WACd,MAAM,oBAAoB,aAC1B,IAAI,YAAY,aAChB,QAAQ"}
|
package/dist/images.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { sha1 } from "@noble/hashes/legacy.js";
|
|
2
2
|
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
3
3
|
import { imageSize as imageSize$1 } from "image-size";
|
|
4
|
+
import { fromUint8Array, isValid, toUint8Array } from "js-base64";
|
|
4
5
|
//#region src/images.ts
|
|
5
6
|
/**
|
|
6
7
|
* The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,
|
|
@@ -15,7 +16,8 @@ const IMAGE_MIME_TYPES = {
|
|
|
15
16
|
png: "image/png",
|
|
16
17
|
jpg: "image/jpeg",
|
|
17
18
|
gif: "image/gif",
|
|
18
|
-
webp: "image/webp"
|
|
19
|
+
webp: "image/webp",
|
|
20
|
+
avif: "image/avif"
|
|
19
21
|
};
|
|
20
22
|
/** The raster types a dropped or pasted file can be imported as an image fill from. */
|
|
21
23
|
const IMPORTABLE_RASTER_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -30,7 +32,7 @@ function isSVGFile(file) {
|
|
|
30
32
|
return file.type === "image/svg+xml" || file.type === "" && file.name.toLowerCase().endsWith(".svg");
|
|
31
33
|
}
|
|
32
34
|
/**
|
|
33
|
-
* The type and size of a PNG, JPEG, GIF, or
|
|
35
|
+
* The type and size of a PNG, JPEG, GIF, WebP, or AVIF, read from its header by `image-size`; null for
|
|
34
36
|
* bytes it cannot read and for other formats.
|
|
35
37
|
*/
|
|
36
38
|
function imageHeader(data) {
|
|
@@ -54,6 +56,44 @@ function imageHeader(data) {
|
|
|
54
56
|
function imageMimeType(data) {
|
|
55
57
|
return imageHeader(data)?.type ?? "image/png";
|
|
56
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* The media type and bytes a `data:` URL carries: a Base64 body decoded, and a percent-encoded
|
|
61
|
+
* one unescaped as UTF-8 text, as SVG and other markup are written. Null for anything else: Base64
|
|
62
|
+
* cut short in transit, and escapes that are not UTF-8, such as a binary image escaped byte by
|
|
63
|
+
* byte, which a reader that must take any data URL, such as `.pen` loading, gets from `fetch`.
|
|
64
|
+
*/
|
|
65
|
+
function parseDataURL(url) {
|
|
66
|
+
const match = /^\s*data:([^,]*),(.*?)\s*$/is.exec(url);
|
|
67
|
+
if (!match) return null;
|
|
68
|
+
const [, header = "", body = ""] = match;
|
|
69
|
+
const params = header.split(";").map((param) => param.trim());
|
|
70
|
+
const base64 = params.length > 1 && params.at(-1)?.toLowerCase() === "base64";
|
|
71
|
+
const mimeType = params[0]?.toLowerCase() || "text/plain";
|
|
72
|
+
let text;
|
|
73
|
+
try {
|
|
74
|
+
text = decodeURIComponent(body.replace(/%(?![\da-f]{2})/gi, "%25"));
|
|
75
|
+
} catch {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
if (!base64) return {
|
|
79
|
+
mimeType,
|
|
80
|
+
bytes: new TextEncoder().encode(text)
|
|
81
|
+
};
|
|
82
|
+
const compact = text.replace(/\s+/g, "");
|
|
83
|
+
if (compact.replace(/={1,2}$/, "").length % 4 === 1 || !isValid(compact)) return null;
|
|
84
|
+
return {
|
|
85
|
+
mimeType,
|
|
86
|
+
bytes: toUint8Array(compact)
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/** Encoded image bytes as a Base64 data URL of the type their header names. */
|
|
90
|
+
function imageDataURL(data) {
|
|
91
|
+
return `data:${imageMimeType(data)};base64,${fromUint8Array(data)}`;
|
|
92
|
+
}
|
|
93
|
+
/** SVG markup as a percent-encoded data URL, as CSS `url()` and `<img src>` take one. */
|
|
94
|
+
function svgDataURL(svg) {
|
|
95
|
+
return `data:image/svg+xml,${encodeURIComponent(svg)}`;
|
|
96
|
+
}
|
|
57
97
|
/** An image's size in pixels, read from its header; null for bytes it cannot read. */
|
|
58
98
|
function imageSize(data) {
|
|
59
99
|
const header = imageHeader(data);
|
|
@@ -79,7 +119,21 @@ function coverImageTransform(width, height, imageWidth, imageHeight) {
|
|
|
79
119
|
m12: (1 - m11) / 2
|
|
80
120
|
};
|
|
81
121
|
}
|
|
122
|
+
/** The images `paints` show, by their hashes. */
|
|
123
|
+
function imagePaintHashes(paints) {
|
|
124
|
+
return [...paints].flatMap((paint) => paint.type === "IMAGE" && paint.imageHash ? [paint.imageHash] : []);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Copies the images `hashes` name from `from` into `to`, each as bytes of its own. An image is
|
|
128
|
+
* named by its content, so one `to` already holds stays.
|
|
129
|
+
*/
|
|
130
|
+
function copyImages(from, to, hashes) {
|
|
131
|
+
for (const hash of hashes) {
|
|
132
|
+
const bytes = from.get(hash);
|
|
133
|
+
if (bytes && !to.has(hash)) to.set(hash, new Uint8Array(bytes));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
82
136
|
//#endregion
|
|
83
|
-
export { IMPORTABLE_RASTER_TYPES, computeImageHash, coverImageTransform, imageHeader, imageMimeType, imageSize, isSVGFile };
|
|
137
|
+
export { IMPORTABLE_RASTER_TYPES, computeImageHash, copyImages, coverImageTransform, imageDataURL, imageHeader, imageMimeType, imagePaintHashes, imageSize, isSVGFile, parseDataURL, svgDataURL };
|
|
84
138
|
|
|
85
139
|
//# sourceMappingURL=images.js.map
|
package/dist/images.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"images.js","names":["readImageHeader"],"sources":["../src/images.ts"],"sourcesContent":["import { sha1 } from '@noble/hashes/legacy.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { imageSize as readImageHeader } from 'image-size'\n\nimport type { Matrix, Size } from './primitives'\n\n/**\n * The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,\n * so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may\n * hold images under other names; anything that hands images to Figma still checks.\n */\nexport function computeImageHash(data: Uint8Array): string {\n return bytesToHex(sha1(data))\n}\n\nexport type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'\n\n/** The image types documents store, by the name `image-size` gives each format. */\nconst IMAGE_MIME_TYPES: Partial<Record<string, ImageMimeType>> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp'\n}\n\n/** The raster types a dropped or pasted file can be imported as an image fill from. */\nexport const IMPORTABLE_RASTER_TYPES: ReadonlySet<string> = new Set([\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/gif',\n 'image/avif'\n])\n\n/** Whether a file is an SVG image, which some systems report without a media type. */\nexport function isSVGFile(file: { name: string; type: string }): boolean {\n return (\n file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))\n )\n}\n\nexport interface ImageHeader extends Size {\n type: ImageMimeType\n}\n\n/**\n * The type and size of a PNG, JPEG, GIF, or
|
|
1
|
+
{"version":3,"file":"images.js","names":["readImageHeader"],"sources":["../src/images.ts"],"sourcesContent":["import { sha1 } from '@noble/hashes/legacy.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { imageSize as readImageHeader } from 'image-size'\nimport { fromUint8Array, isValid, toUint8Array } from 'js-base64'\n\nimport type { Matrix, Size } from './primitives'\nimport type { Fill } from './types'\n\n/**\n * The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,\n * so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may\n * hold images under other names; anything that hands images to Figma still checks.\n */\nexport function computeImageHash(data: Uint8Array): string {\n return bytesToHex(sha1(data))\n}\n\nexport type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/avif'\n\n/** The image types documents store, by the name `image-size` gives each format. */\nconst IMAGE_MIME_TYPES: Partial<Record<string, ImageMimeType>> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif'\n}\n\n/** The raster types a dropped or pasted file can be imported as an image fill from. */\nexport const IMPORTABLE_RASTER_TYPES: ReadonlySet<string> = new Set([\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/gif',\n 'image/avif'\n])\n\n/** Whether a file is an SVG image, which some systems report without a media type. */\nexport function isSVGFile(file: { name: string; type: string }): boolean {\n return (\n file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))\n )\n}\n\nexport interface ImageHeader extends Size {\n type: ImageMimeType\n}\n\n/**\n * The type and size of a PNG, JPEG, GIF, WebP, or AVIF, read from its header by `image-size`; null for\n * bytes it cannot read and for other formats.\n */\nexport function imageHeader(data: Uint8Array): ImageHeader | null {\n let header: ReturnType<typeof readImageHeader>\n try {\n header = readImageHeader(data)\n } catch {\n return null\n }\n const type = header.type === undefined ? undefined : IMAGE_MIME_TYPES[header.type]\n return type ? { type, width: header.width, height: header.height } : null\n}\n\n/**\n * The media type of encoded image bytes, read from their header, for writing them out as a data\n * URL or file. Bytes it cannot read are reported as PNG, as image fills began.\n */\nexport function imageMimeType(data: Uint8Array): ImageMimeType {\n return imageHeader(data)?.type ?? 'image/png'\n}\n\nexport interface DataURL {\n /** The media type in lowercase, without parameters; `text/plain` when the URL names none. */\n mimeType: string\n bytes: Uint8Array\n}\n\n/**\n * The media type and bytes a `data:` URL carries: a Base64 body decoded, and a percent-encoded\n * one unescaped as UTF-8 text, as SVG and other markup are written. Null for anything else: Base64\n * cut short in transit, and escapes that are not UTF-8, such as a binary image escaped byte by\n * byte, which a reader that must take any data URL, such as `.pen` loading, gets from `fetch`.\n */\nexport function parseDataURL(url: string): DataURL | null {\n const match = /^\\s*data:([^,]*),(.*?)\\s*$/is.exec(url)\n if (!match) return null\n const [, header = '', body = ''] = match\n const params = header.split(';').map((param) => param.trim())\n const base64 = params.length > 1 && params.at(-1)?.toLowerCase() === 'base64'\n const mimeType = params[0]?.toLowerCase() || 'text/plain'\n let text: string\n try {\n // A `%` that starts no escape is a literal percent sign, as in `width=\"100%\"`.\n text = decodeURIComponent(body.replace(/%(?![\\da-f]{2})/gi, '%25'))\n } catch {\n return null\n }\n if (!base64) return { mimeType, bytes: new TextEncoder().encode(text) }\n const compact = text.replace(/\\s+/g, '')\n // Base64 one character past a whole group of four cannot be bytes: it was cut short.\n if (compact.replace(/={1,2}$/, '').length % 4 === 1 || !isValid(compact)) return null\n return { mimeType, bytes: toUint8Array(compact) }\n}\n\n/** Encoded image bytes as a Base64 data URL of the type their header names. */\nexport function imageDataURL(data: Uint8Array): string {\n return `data:${imageMimeType(data)};base64,${fromUint8Array(data)}`\n}\n\n/** SVG markup as a percent-encoded data URL, as CSS `url()` and `<img src>` take one. */\nexport function svgDataURL(svg: string): string {\n return `data:image/svg+xml,${encodeURIComponent(svg)}`\n}\n\n/** An image's size in pixels, read from its header; null for bytes it cannot read. */\nexport function imageSize(data: Uint8Array): Size | null {\n const header = imageHeader(data)\n return header && { width: header.width, height: header.height }\n}\n\n/**\n * The crop that shows an image as Fill does: scaled to cover a `width` × `height` layer and\n * centred. Figma starts a crop from it, as the image-space window a crop's transform holds.\n */\nexport function coverImageTransform(\n width: number,\n height: number,\n imageWidth: number,\n imageHeight: number\n): Matrix {\n const scale = Math.max(width / imageWidth, height / imageHeight)\n const m00 = width / scale / imageWidth\n const m11 = height / scale / imageHeight\n return { m00, m01: 0, m02: (1 - m00) / 2, m10: 0, m11, m12: (1 - m11) / 2 }\n}\n\n/** The images `paints` show, by their hashes. */\nexport function imagePaintHashes(paints: Iterable<Fill>): string[] {\n return [...paints].flatMap((paint) =>\n paint.type === 'IMAGE' && paint.imageHash ? [paint.imageHash] : []\n )\n}\n\n/**\n * Copies the images `hashes` name from `from` into `to`, each as bytes of its own. An image is\n * named by its content, so one `to` already holds stays.\n */\nexport function copyImages(\n from: ReadonlyMap<string, Uint8Array>,\n to: Map<string, Uint8Array>,\n hashes: Iterable<string>\n): void {\n for (const hash of hashes) {\n const bytes = from.get(hash)\n if (bytes && !to.has(hash)) to.set(hash, new Uint8Array(bytes))\n }\n}\n"],"mappings":";;;;;;;;;;AAaA,SAAgB,iBAAiB,MAA0B;CACzD,OAAO,WAAW,KAAK,IAAI,CAAC;AAC9B;;AAKA,MAAM,mBAA2D;CAC/D,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAM;CACN,MAAM;AACR;;AAGA,MAAa,0CAA+C,IAAI,IAAI;CAClE;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,UAAU,MAA+C;CACvE,OACE,KAAK,SAAS,mBAAoB,KAAK,SAAS,MAAM,KAAK,KAAK,YAAY,CAAC,CAAC,SAAS,MAAM;AAEjG;;;;;AAUA,SAAgB,YAAY,MAAsC;CAChE,IAAI;CACJ,IAAI;EACF,SAASA,YAAgB,IAAI;CAC/B,QAAQ;EACN,OAAO;CACT;CACA,MAAM,OAAO,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,iBAAiB,OAAO;CAC7E,OAAO,OAAO;EAAE;EAAM,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,IAAI;AACvE;;;;;AAMA,SAAgB,cAAc,MAAiC;CAC7D,OAAO,YAAY,IAAI,CAAC,EAAE,QAAQ;AACpC;;;;;;;AAcA,SAAgB,aAAa,KAA6B;CACxD,MAAM,QAAQ,+BAA+B,KAAK,GAAG;CACrD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,GAAG,SAAS,IAAI,OAAO,MAAM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,CAAC,SAAS,UAC1B,MAAM,SAAS,WAAW,MAAM,YAAY,CAAC,MAAM,SAAS,IAAI,CAAC,CACnE;AACF;;;;;AAMA,SAAgB,WACd,MACA,IACA,QACM;CACN,KAAK,MAAM,QAAQ,QAAQ;EACzB,MAAM,QAAQ,KAAK,IAAI,IAAI;EAC3B,IAAI,SAAS,CAAC,GAAG,IAAI,IAAI,GAAG,GAAG,IAAI,MAAM,IAAI,WAAW,KAAK,CAAC;CAChE;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CommittedGraphEventError } from "./buffered-events.js";
|
|
2
2
|
import { SceneGraph } from "./graph.js";
|
|
3
|
-
import { ArcData, AxisSizingMode, BlendMode, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, CommentReply, CommentThread, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, Effect, EnabledLibraryBinding, ExportColorProfile, ExportSetting, ExportSize, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, NodeChangeObserver, NodeType, NoiseType, NumericNodeProperty, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, isLibraryCollection, isModeAttributeName } from "./types.js";
|
|
3
|
+
import { ArcData, AxisSizingMode, BlendMode, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, CommentReply, CommentThread, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, DocumentRecordKind, Effect, EnabledLibraryBinding, ExportColorProfile, ExportSetting, ExportSize, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GlassEffectParams, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, NodeChangeObserver, NodeType, NoiseType, NumericNodeProperty, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, ProgressiveBlur, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, isLibraryCollection, isModeAttributeName } from "./types.js";
|
|
4
4
|
import { generateId, setIdSession } from "./ids.js";
|
|
5
|
-
export { ArcData, AxisSizingMode, BlendMode, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, CommentReply, CommentThread, CommittedGraphEventError, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, Effect, EnabledLibraryBinding, ExportColorProfile, ExportSetting, ExportSize, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, NodeChangeObserver, NodeType, NoiseType, NumericNodeProperty, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, SceneGraph, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, generateId, isLibraryCollection, isModeAttributeName, setIdSession };
|
|
5
|
+
export { ArcData, AxisSizingMode, BlendMode, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, CommentReply, CommentThread, CommittedGraphEventError, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, DocumentRecordKind, Effect, EnabledLibraryBinding, ExportColorProfile, ExportSetting, ExportSize, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GlassEffectParams, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, NodeChangeObserver, NodeType, NoiseType, NumericNodeProperty, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, ProgressiveBlur, SceneGraph, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, SharedStyle, SharedStyleKind, SharedStyleType, SlotSettings, SourceLibraryPublication, SourceMetadata, Stroke, StrokeCap, StrokeJoin, StyleRun, SymbolLink, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, TextAlignVertical, TextAutoResize, TextBindableField, TextBoundVariables, TextCase, TextDecoration, TextDecorationStyle, TextDirection, TextLength, TextListType, TextParagraphSpacingField, TextParagraphStyle, TextPathData, TokenExpression, TokenUnit, VARIABLE_FORMULA_OPERATORS, VARIABLE_SCOPES, Variable, VariableAlias, VariableCollection, VariableCollectionMode, VariableColorExpression, VariableFormula, VariableFormulaNode, VariableFormulaOperation, VariableFormulaOperator, VariableLiteral, VariableModeMap, VariableScope, VariableType, VariableUnsupportedExpression, VariableValue, VariantPropSpec, VectorNetwork, VectorRegion, VectorSegment, VectorVertex, WindingRule, generateId, isLibraryCollection, isModeAttributeName, setIdSession };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/instances/index.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/instances/index.ts"],"mappings":";;;;;;;iBA2CgB,2BAA2B,WAAW,YAAY,QAAQ;iBAM1D,eACd,OAAO,YACP,qBACA,kBACA,YAAW,QAAQ,aAClB;iBAoBa,yBACd,OAAO,YACP,oBACA,qBACA,OAAM;UAmCS;;;;;;EAMf;;iBAgBc,sBACd,OAAO,YACP,oBACA,uBACE,aAAoB;iBAwDR,cAAc,OAAO,YAAY;;;;;iBAQjC,sBAAsB,OAAO,YAAY,cAAc;;iBAOvD,aAAa,OAAO,YAAY;iBAsChC,eAAe,OAAO,YAAY;iBAWlC,iBAAiB,OAAO,YAAY,qBAAqB;iBAMzD,aAAa,OAAO,YAAY,sBAAsB;;;;iBActD,oBAAoB,OAAO,YAAY,gBAAgB;iBAMvD,uBACd,OAAO,YACP,gBACA,QAAQ"}
|
package/dist/instances/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { clearInstanceOverrides, getInstanceOverride, hasInstanceOverride as hasInstanceOverride$1, setInstanceOverride } from "./overrides.js";
|
|
2
2
|
import { findInstanceAncestor, instanceMainComponent } from "./main-component.js";
|
|
3
3
|
import { detachOwnedSlotContent, restoreOwnedSlotContent } from "../slots/frames.js";
|
|
4
|
+
import { applyBoundPaintColorsIn, keepCopyBoundPaints } from "../variables/paints.js";
|
|
4
5
|
import { keepOwnContentSize } from "./content-size.js";
|
|
5
6
|
import { createInstanceSyncContext, groupCopyRemovals, removeLeftoverCopies } from "./copies.js";
|
|
6
7
|
import { canCreateInstance, createsComponentCycle, cycleSafeParent } from "./cycles.js";
|
|
@@ -26,6 +27,7 @@ function createInstance(graph, componentId, parentId, overrides = {}) {
|
|
|
26
27
|
componentId
|
|
27
28
|
});
|
|
28
29
|
cloneChildrenWithMapping(graph, component.id, instance.id);
|
|
30
|
+
applyBoundPaintColorsIn(graph, instance.id);
|
|
29
31
|
return instance;
|
|
30
32
|
}
|
|
31
33
|
function populateInstanceChildren(graph, instanceId, componentId, mode = "deep") {
|
|
@@ -65,6 +67,7 @@ function swapInstanceComponent(graph, instanceId, componentId, { keepName = fals
|
|
|
65
67
|
...ownSyncedProps(graph, instance, sourceInTargetCoordinates(component, instance.componentScale)).updates
|
|
66
68
|
};
|
|
67
69
|
if (!keepName && (!previousComponent || instance.name === previousComponent.name)) updates.name = component.name;
|
|
70
|
+
keepCopyBoundPaints(graph, instance, updates);
|
|
68
71
|
const slotContent = detachOwnedSlotContent(graph, instance);
|
|
69
72
|
graph.updateNode(instanceId, updates);
|
|
70
73
|
followComponentLayers(graph, instance, component, parkedContent(slotContent));
|