@pairdraw/scene-graph 0.19.0 → 0.19.2
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/behaviours/index.d.ts +2 -2
- package/dist/behaviours/index.js +2 -2
- package/dist/behaviours/spec.d.ts +6 -1
- package/dist/behaviours/spec.d.ts.map +1 -1
- package/dist/behaviours/spec.js +62 -5
- package/dist/behaviours/spec.js.map +1 -1
- package/dist/canvas-layout.js +66 -0
- package/dist/canvas-layout.js.map +1 -0
- package/dist/coordinate.js +1 -1
- package/dist/css/index.d.ts +2 -2
- package/dist/css/index.js +2 -2
- package/dist/css/text.d.ts +6 -1
- package/dist/css/text.d.ts.map +1 -1
- package/dist/css/text.js +20 -1
- package/dist/css/text.js.map +1 -1
- package/dist/generated/index.d.ts +2 -2
- package/dist/generated/index.js +2 -2
- package/dist/generated/shape-with-text.d.ts +7 -2
- package/dist/generated/shape-with-text.d.ts.map +1 -1
- package/dist/generated/shape-with-text.js +20 -3
- package/dist/generated/shape-with-text.js.map +1 -1
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +11 -5
- package/dist/graph.js.map +1 -1
- package/dist/group-bounds.d.ts +4 -1
- package/dist/group-bounds.d.ts.map +1 -1
- package/dist/group-bounds.js +11 -1
- package/dist/group-bounds.js.map +1 -1
- package/dist/hit-test.d.ts.map +1 -1
- package/dist/hit-test.js +47 -24
- package/dist/hit-test.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/node-defaults.d.ts +21 -1
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +22 -14
- package/dist/node-defaults.js.map +1 -1
- package/dist/resize.d.ts.map +1 -1
- package/dist/resize.js +3 -6
- package/dist/resize.js.map +1 -1
- package/dist/scaling/node.d.ts.map +1 -1
- package/dist/scaling/node.js +23 -3
- package/dist/scaling/node.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/text/path.js +11 -0
- package/dist/text/path.js.map +1 -0
- package/dist/text/picture.d.ts.map +1 -1
- package/dist/text/picture.js +5 -5
- package/dist/text/picture.js.map +1 -1
- package/dist/transfer/copied.d.ts +14 -0
- package/dist/transfer/copied.d.ts.map +1 -0
- package/dist/transfer/copied.js +52 -0
- package/dist/transfer/copied.js.map +1 -0
- package/dist/transfer/index.d.ts +2 -1
- package/dist/transfer/index.js +2 -1
- package/dist/transfer/nodes.js +7 -0
- package/dist/transfer/nodes.js.map +1 -1
- package/dist/types.d.ts +3 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/undo.d.ts +6 -0
- package/dist/undo.d.ts.map +1 -1
- package/dist/undo.js +13 -0
- package/dist/undo.js.map +1 -1
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js.map +1 -1
- package/package.json +1 -1
- package/src/behaviours/spec.ts +94 -4
- package/src/canvas-layout.ts +76 -0
- package/src/css/index.ts +6 -1
- package/src/css/text.ts +24 -0
- package/src/generated/shape-with-text.ts +28 -2
- package/src/graph.ts +14 -4
- package/src/group-bounds.ts +13 -0
- package/src/hit-test.ts +95 -39
- package/src/node-defaults.ts +22 -13
- package/src/resize.ts +3 -14
- package/src/scaling/node.ts +27 -3
- package/src/shared-styles.ts +8 -0
- package/src/text/path.ts +14 -0
- package/src/text/picture.ts +5 -2
- package/src/transfer/copied.ts +72 -0
- package/src/transfer/index.ts +1 -0
- package/src/transfer/nodes.ts +10 -0
- package/src/types.ts +2 -1
- package/src/undo.ts +11 -0
- package/src/variables/index.ts +1 -4
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 { getAxisAlignedBoundsAt, getNodeLocalMatrix, getWorldMatrix } from './coordinate'\nimport { geometryBlobPolylines } from './geometry'\nimport type { SceneGraph } from './graph'\nimport { drawnChildIds } from './layout/draw-order'\nimport Matrix, { type Mat3 } from './matrix'\nimport type { Rect, Vector } from './primitives'\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 * How far from a zero-width or zero-height layer, in canvas units, a point still lands on it, so\n * a flat line or an empty box stays clickable; matches a connector line's slop (`connectors/hit.ts`).\n */\nconst DEGENERATE_AXIS_SLOP = 4\n\nfunction hasVisibleFillOrStroke(node: SceneNode): boolean {\n return node.fills.some((f) => f.visible) || node.strokes.some((s) => s.visible)\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/**\n * Where the point lies in the node's own coordinates: its offset from the position when nothing\n * above it is turned, else through the inverse world matrix. Null when that cannot be inverted.\n */\nfunction localPoint(\n px: number,\n py: number,\n node: SceneNode,\n graph: SceneGraph,\n transformCache: Map<string, boolean>\n): Vector | null {\n if (!hasTransformedAncestor(node, graph, transformCache)) {\n const absolute = graph.getAbsolutePosition(node.id)\n return { x: px - absolute.x, y: py - absolute.y }\n }\n const inv = Matrix.invert(getWorldMatrix(node, graph))\n if (!inv) return null\n const [x, y] = Matrix.mapPoints(inv, [px, py])\n return { x, y }\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 const local = localPoint(px, py, node, graph, transformCache)\n if (!local) return false\n const padX = node.width > 0 ? pad : Math.max(pad, DEGENERATE_AXIS_SLOP)\n const padY = node.height > 0 ? pad : Math.max(pad, DEGENERATE_AXIS_SLOP)\n return (\n local.x >= -padX &&\n local.x <= node.width + padX &&\n local.y >= -padY &&\n local.y <= node.height + padY\n )\n}\n\n/** Whether a rounded rectangle of `width` × `height` holds the point. */\nfunction roundedRectContains(\n point: Vector,\n width: number,\n height: number,\n radius: number\n): boolean {\n if (point.x < 0 || point.y < 0 || point.x > width || point.y > height) return false\n const r = Math.max(0, Math.min(radius, width / 2, height / 2))\n const cx = Math.min(Math.max(point.x, r), width - r)\n const cy = Math.min(Math.max(point.y, r), height - r)\n return Math.hypot(point.x - cx, point.y - cy) <= r\n}\n\n/** Whether the point is inside a closed polyline, by the even-odd rule. */\nfunction insidePolyline(polyline: readonly Vector[], x: number, y: number): boolean {\n let inside = false\n for (let i = 0, j = polyline.length - 1; i < polyline.length; j = i++) {\n const a = polyline[i]\n const b = polyline[j]\n if (a.y > y === b.y > y) continue\n if (x < ((b.x - a.x) * (y - a.y)) / (b.y - a.y) + a.x) inside = !inside\n }\n return inside\n}\n\n/**\n * Whether a mask lets the point through, by the outline it draws: an ellipse's curve, a rounded\n * rectangle's corners, or a vector's filled path. Other shapes clip by their box.\n */\nfunction maskContainsPoint(\n px: number,\n py: number,\n mask: SceneNode,\n graph: SceneGraph,\n transformCache: Map<string, boolean>\n): boolean {\n const outlined =\n (mask.type === 'ELLIPSE' && mask.width > 0 && mask.height > 0) ||\n (mask.type === 'RECTANGLE' && mask.cornerRadius > 0) ||\n (mask.type === 'VECTOR' && mask.fillGeometry.length > 0)\n if (!outlined) return containsPoint(px, py, mask, graph, transformCache)\n const local = localPoint(px, py, mask, graph, transformCache)\n if (!local) return false\n if (mask.type === 'ELLIPSE') {\n const rx = mask.width / 2\n const ry = mask.height / 2\n const dx = (local.x - rx) / rx\n const dy = (local.y - ry) / ry\n return dx * dx + dy * dy <= 1\n }\n if (mask.type === 'RECTANGLE') {\n return roundedRectContains(local, mask.width, mask.height, mask.cornerRadius)\n }\n return geometryBlobPolylines(mask.fillGeometry).some((points) =>\n insidePolyline(points, local.x, local.y)\n )\n}\n\nfunction isVisibleMask(node: SceneNode | undefined): node is SceneNode {\n return node !== undefined && node.visible && node.isMask\n}\n\n/**\n * The masks that clip each child, by index, as the renderer groups them (`core/canvas/masks.ts`):\n * a run of visible masks clips the layers after it up to the next visible mask. Empty when the\n * container has no visible mask.\n */\nfunction clippingMasks(graph: SceneGraph, childIds: readonly string[]): SceneNode[][] {\n const children = childIds.map((childId) => graph.nodes.get(childId))\n if (!children.some(isVisibleMask)) return []\n const result: SceneNode[][] = []\n let run: SceneNode[] = []\n let previousWasMask = false\n for (const child of children) {\n if (isVisibleMask(child)) {\n run = previousWasMask ? [...run, child] : [child]\n previousWasMask = true\n result.push([])\n continue\n }\n previousWasMask = false\n result.push(run)\n }\n return result\n}\n\nfunction hitTestOpaqueContainer(\n graph: SceneGraph,\n px: number,\n py: number,\n child: SceneNode,\n childId: string,\n deep: boolean,\n transformCache: Map<string, boolean>,\n pad: number,\n locked = false\n): SceneNode | null {\n if (!containsPoint(px, py, child, graph, transformCache)) return null\n const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad, locked)\n if (childHit) return child\n if (hasVisibleFillOrStroke(child)) return child\n return null\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 childId: string,\n deep: boolean,\n transformCache: Map<string, boolean>,\n pad: number,\n locked = false\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, transformCache, pad)) return null\n const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad, locked)\n if (childHit) return standIn(child, childHit, deep)\n return containsPoint(px, py, child, graph, transformCache) ? child : null\n }\n\n const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad, locked)\n if (childHit) return standIn(child, childHit, true)\n\n if (\n containsPoint(px, py, child, graph, transformCache) &&\n (hasVisibleFillOrStroke(child) || ownsItsEmptyArea(graph, child))\n )\n return child\n return null\n}\n\n/** Whether the masks that clip a layer leave the point outside every one of their outlines. */\nfunction isMaskedOut(\n px: number,\n py: number,\n masks: readonly SceneNode[] | undefined,\n graph: SceneGraph,\n transformCache: Map<string, boolean>\n): boolean {\n if (!masks) return false\n return (\n masks.length > 0 &&\n !masks.some((mask) => maskContainsPoint(px, py, mask, graph, transformCache))\n )\n}\n\n/**\n * The topmost layer under the point among a container's children. `pad`, in canvas units, grows\n * each leaf layer's box, as Figma takes a click a few screen pixels outside a shape.\n */\n/**\n * Whether a layer under the point can take the click. A locked layer and everything in it are\n * invisible to a press and to hover, as in Figma: a click falls through to what lies under it, and\n * a drag from it draws a marquee.\n */\nfunction takesClick(\n graph: SceneGraph,\n px: number,\n py: number,\n child: SceneNode | undefined,\n mask: readonly SceneNode[] | undefined,\n locked: boolean,\n transformCache: Map<string, boolean>\n): child is SceneNode {\n if (!child || child.internalOnly || !child.visible || (child.locked && !locked)) return false\n return !isMaskedOut(px, py, mask, graph, transformCache)\n}\n\nfunction hitTestChildren(\n graph: SceneGraph,\n px: number,\n py: number,\n parentId: string,\n deep = false,\n transformCache = new Map<string, boolean>(),\n pad = 0,\n locked = false\n): SceneNode | null {\n const parent = graph.nodes.get(parentId)\n if (!parent) return null\n\n if (parent.clipsContent) {\n if (!containsPoint(px, py, parent, graph, transformCache)) return null\n }\n\n // Front to back, as the layers are drawn: a reversed auto layout puts the first child on top.\n const drawn = drawnChildIds(parent)\n const masks = clippingMasks(graph, drawn)\n for (let i = drawn.length - 1; i >= 0; i--) {\n const childId = drawn[i]\n const child = graph.nodes.get(childId)\n if (!takesClick(graph, px, py, child, masks[i], locked, transformCache)) continue\n if (CONTAINER_TYPES.has(child.type)) {\n if (OPAQUE_CONTAINER_TYPES.has(child.type) && !deep) {\n const hit = hitTestOpaqueContainer(\n graph,\n px,\n py,\n child,\n childId,\n deep,\n transformCache,\n pad,\n locked\n )\n if (hit) return hit\n continue\n }\n\n const hit = hitTestTransparentContainer(\n graph,\n px,\n py,\n child,\n childId,\n deep,\n transformCache,\n pad,\n locked\n )\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 (containsPoint(px, py, child, graph, transformCache, pad)) return child\n }\n\n return null\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, 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, true, new Map(), 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.\n */\nfunction opensByItself(graph: SceneGraph, node: SceneNode): 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 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 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) && !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, and a\n * selected container itself, so a click inside it selects the layer under the point, as in Figma.\n * A selected group or boolean stays closed: clicking inside it keeps it selected.\n */\nfunction openedBySelection(\n graph: SceneGraph,\n selectedIds: ReadonlySet<string>,\n scopeId: string\n): Set<string> {\n const ancestors = new Set<string>()\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 )\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 function hitTestSelectable(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId: string,\n selectedIds: ReadonlySet<string>,\n pad = 0,\n /** Whether locked layers are hit, as a right-click hits them; see `hitTestAtPoint`. */\n locked = false\n): SceneNode | null {\n const deepest = hitTestChildren(graph, px, py, scopeId, true, new Map(), pad, locked)\n if (!deepest) {\n const scope = graph.nodes.get(scopeId)\n return scope ? frameChildAt(graph, scope, px, py, 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)\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)) return node\n }\n const last = chain.at(-1)\n if (!last) return null\n const frame = frameChildAt(graph, last, px, py, locked)\n if (frame) return frame\n if (ownsItsEmptyArea(graph, last)) return last\n return opened.has(last.id) && !opensByItself(graph, last) ? 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): boolean {\n const node = graph.nodes.get(nodeId)\n return node !== undefined && opensByItself(graph, node)\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, 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\nfunction rectsTouch(a: Rect, b: Rect): boolean {\n return a.x + a.width > b.x && a.x < b.x + b.width && a.y + a.height > b.y && a.y < b.y + b.height\n}\n\nfunction rectOverlap(a: Rect, b: Rect): Rect | null {\n if (!rectsTouch(a, b)) return null\n const x = Math.max(a.x, b.x)\n const y = Math.max(a.y, b.y)\n return {\n x,\n y,\n width: Math.min(a.x + a.width, b.x + b.width) - x,\n height: Math.min(a.y + a.height, b.y + b.height) - y\n }\n}\n\n/**\n * Whether a deep marquee touching a container, but none of its layers, selects it: where a deep\n * click there would select it (a group's box, a painted container, the empty area a top-level frame\n * with auto layout owns), except a board or section whose empty area a press treats as background.\n */\nfunction selectsByOwnArea(graph: SceneGraph, node: SceneNode): boolean {\n if (node.type === 'GROUP' || ownsItsEmptyArea(graph, node)) return true\n return hasVisibleFillOrStroke(node) && !opensByItself(graph, node)\n}\n\n/**\n * Collects the deepest layers among `parent`'s children that touch `rect`. Each child's world\n * matrix is composed from its parent's, so a walk over a large page climbs no ancestor chains.\n */\nfunction collectDeepestInRect(\n graph: SceneGraph,\n parent: SceneNode,\n parentWorld: Mat3,\n rect: Rect,\n hits: SceneNode[]\n) {\n // A clipping container draws nothing outside itself, so its layers meet only that part of the rect.\n const area =\n parent.clipsContent && parent.type !== 'CANVAS'\n ? rectOverlap(rect, getAxisAlignedBoundsAt(parent, parentWorld))\n : rect\n if (!area) return\n for (const childId of parent.childIds) {\n const child = graph.nodes.get(childId)\n if (!child || child.internalOnly || !child.visible || child.locked) continue\n const world = Matrix.multiply(parentWorld, getNodeLocalMatrix(child))\n const touches = rectsTouch(area, getAxisAlignedBoundsAt(child, world))\n if (!CONTAINER_TYPES.has(child.type) || child.childIds.length === 0) {\n if (touches) hits.push(child)\n continue\n }\n const before = hits.length\n collectDeepestInRect(graph, child, world, area, hits)\n if (hits.length === before && touches && selectsByOwnArea(graph, child)) hits.push(child)\n }\n}\n\n/**\n * The deepest layers a deep (⌘) marquee over `rect` selects, as in Figma, by the rules a deep click\n * follows: it looks into frames, groups, sections, components, component sets, and instances, keeps\n * a boolean's operands inside it, and skips hidden, locked, and internal layers with their contents.\n * A container is selected itself only where the rect touches its own area and none of its layers.\n * Layers are compared by their axis-aligned canvas bounds, as a plain marquee compares them.\n */\nexport function hitTestDeepInRect(graph: SceneGraph, rect: Rect, scopeId: string): SceneNode[] {\n const scope = graph.nodes.get(scopeId)\n if (!scope) return []\n const hits: SceneNode[] = []\n collectDeepestInRect(graph, scope, getWorldMatrix(scope, graph), rect, hits)\n return hits\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":";;;;;;AASA,MAAM,kCAAkB,IAAI,IAAc;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,yCAAyB,IAAI,IAAc,CAAC,aAAa,UAAU,CAAC;;;;;AAK1E,MAAM,uBAAuB;AAE7B,SAAS,uBAAuB,MAA0B;CACxD,OAAO,KAAK,MAAM,MAAM,MAAM,EAAE,OAAO,KAAK,KAAK,QAAQ,MAAM,MAAM,EAAE,OAAO;AAChF;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,IA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,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 { getAxisAlignedBoundsAt, getNodeLocalMatrix, getWorldMatrix } from './coordinate'\nimport { geometryBlobPolylines } from './geometry'\nimport type { SceneGraph } from './graph'\nimport { drawnChildIds } from './layout/draw-order'\nimport Matrix, { type Mat3 } from './matrix'\nimport type { Rect, Vector } from './primitives'\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 * How far from a zero-width or zero-height layer, in canvas units, a point still lands on it, so\n * a flat line or an empty box stays clickable; matches a connector line's slop (`connectors/hit.ts`).\n */\nconst DEGENERATE_AXIS_SLOP = 4\n\n/**\n * Whether a paint shows, so its container's empty area counts when a click reaches past\n * containers: a paint at 0% opacity, or a gradient whose stops are all transparent, does not,\n * while 1% does, and the layer's own opacity does not matter.\n */\nfunction isHitPaint(paint: SceneNode['fills'][number]): boolean {\n if (!paint.visible || !(paint.opacity > 0)) return false\n if (paint.type === 'SOLID') return paint.color.a > 0\n if (\n paint.type === 'GRADIENT_LINEAR' ||\n paint.type === 'GRADIENT_RADIAL' ||\n paint.type === 'GRADIENT_ANGULAR' ||\n paint.type === 'GRADIENT_DIAMOND'\n )\n return (paint.gradientStops ?? []).some((stop) => stop.color.a > 0)\n return true\n}\n\nfunction showsPaint(node: SceneNode): boolean {\n return node.fills.some(isHitPaint) || node.strokes.some(isHitPaint)\n}\n\n/**\n * Whether a container's empty area takes the click. Figma counts it only where a paint shows,\n * except a main component's, which always counts, and an instance's when the click is a plain one.\n */\nfunction takesEmptyArea(graph: SceneGraph, node: SceneNode, instanceBodies: boolean): boolean {\n if (node.type === 'COMPONENT' || showsPaint(node) || ownsItsEmptyArea(graph, node)) return true\n return instanceBodies && node.type === 'INSTANCE'\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/**\n * Where the point lies in the node's own coordinates: its offset from the position when nothing\n * above it is turned, else through the inverse world matrix. Null when that cannot be inverted.\n */\nfunction localPoint(\n px: number,\n py: number,\n node: SceneNode,\n graph: SceneGraph,\n transformCache: Map<string, boolean>\n): Vector | null {\n if (!hasTransformedAncestor(node, graph, transformCache)) {\n const absolute = graph.getAbsolutePosition(node.id)\n return { x: px - absolute.x, y: py - absolute.y }\n }\n const inv = Matrix.invert(getWorldMatrix(node, graph))\n if (!inv) return null\n const [x, y] = Matrix.mapPoints(inv, [px, py])\n return { x, y }\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 const local = localPoint(px, py, node, graph, transformCache)\n if (!local) return false\n const padX = node.width > 0 ? pad : Math.max(pad, DEGENERATE_AXIS_SLOP)\n const padY = node.height > 0 ? pad : Math.max(pad, DEGENERATE_AXIS_SLOP)\n return (\n local.x >= -padX &&\n local.x <= node.width + padX &&\n local.y >= -padY &&\n local.y <= node.height + padY\n )\n}\n\n/** Whether a rounded rectangle of `width` × `height` holds the point. */\nfunction roundedRectContains(\n point: Vector,\n width: number,\n height: number,\n radius: number\n): boolean {\n if (point.x < 0 || point.y < 0 || point.x > width || point.y > height) return false\n const r = Math.max(0, Math.min(radius, width / 2, height / 2))\n const cx = Math.min(Math.max(point.x, r), width - r)\n const cy = Math.min(Math.max(point.y, r), height - r)\n return Math.hypot(point.x - cx, point.y - cy) <= r\n}\n\n/** Whether the point is inside a closed polyline, by the even-odd rule. */\nfunction insidePolyline(polyline: readonly Vector[], x: number, y: number): boolean {\n let inside = false\n for (let i = 0, j = polyline.length - 1; i < polyline.length; j = i++) {\n const a = polyline[i]\n const b = polyline[j]\n if (a.y > y === b.y > y) continue\n if (x < ((b.x - a.x) * (y - a.y)) / (b.y - a.y) + a.x) inside = !inside\n }\n return inside\n}\n\n/**\n * Whether a mask lets the point through, by the outline it draws: an ellipse's curve, a rounded\n * rectangle's corners, or a vector's filled path. Other shapes clip by their box.\n */\nfunction maskContainsPoint(\n px: number,\n py: number,\n mask: SceneNode,\n graph: SceneGraph,\n transformCache: Map<string, boolean>\n): boolean {\n const outlined =\n (mask.type === 'ELLIPSE' && mask.width > 0 && mask.height > 0) ||\n (mask.type === 'RECTANGLE' && mask.cornerRadius > 0) ||\n (mask.type === 'VECTOR' && mask.fillGeometry.length > 0)\n if (!outlined) return containsPoint(px, py, mask, graph, transformCache)\n const local = localPoint(px, py, mask, graph, transformCache)\n if (!local) return false\n if (mask.type === 'ELLIPSE') {\n const rx = mask.width / 2\n const ry = mask.height / 2\n const dx = (local.x - rx) / rx\n const dy = (local.y - ry) / ry\n return dx * dx + dy * dy <= 1\n }\n if (mask.type === 'RECTANGLE') {\n return roundedRectContains(local, mask.width, mask.height, mask.cornerRadius)\n }\n return geometryBlobPolylines(mask.fillGeometry).some((points) =>\n insidePolyline(points, local.x, local.y)\n )\n}\n\nfunction isVisibleMask(node: SceneNode | undefined): node is SceneNode {\n return node !== undefined && node.visible && node.isMask\n}\n\n/**\n * The masks that clip each child, by index, as the renderer groups them (`core/canvas/masks.ts`):\n * a run of visible masks clips the layers after it up to the next visible mask. Empty when the\n * container has no visible mask.\n */\nfunction clippingMasks(graph: SceneGraph, childIds: readonly string[]): SceneNode[][] {\n const children = childIds.map((childId) => graph.nodes.get(childId))\n if (!children.some(isVisibleMask)) return []\n const result: SceneNode[][] = []\n let run: SceneNode[] = []\n let previousWasMask = false\n for (const child of children) {\n if (isVisibleMask(child)) {\n run = previousWasMask ? [...run, child] : [child]\n previousWasMask = true\n result.push([])\n continue\n }\n previousWasMask = false\n result.push(run)\n }\n return result\n}\n\n/**\n * What a click inside a container reports. `opaque` is an instance or component whose body takes\n * the click without looking through it; every other container looks through to its children first.\n */\nfunction hitTestContainer(\n graph: SceneGraph,\n px: number,\n py: number,\n child: SceneNode,\n childId: string,\n deep: boolean,\n transformCache: Map<string, boolean>,\n pad: number,\n locked = false,\n instanceBodies = false,\n opaque = false\n): SceneNode | null {\n if (opaque) {\n if (!containsPoint(px, py, child, graph, transformCache)) return null\n const childHit = hitTestChildren(\n graph,\n px,\n py,\n childId,\n deep,\n transformCache,\n pad,\n locked,\n instanceBodies\n )\n if (childHit) return child\n if (takesEmptyArea(graph, child, instanceBodies)) return child\n return null\n }\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, transformCache, pad)) return null\n const childHit = hitTestChildren(\n graph,\n px,\n py,\n childId,\n deep,\n transformCache,\n pad,\n locked,\n instanceBodies\n )\n if (childHit) return standIn(child, childHit, deep)\n return containsPoint(px, py, child, graph, transformCache) ? child : null\n }\n\n const childHit = hitTestChildren(\n graph,\n px,\n py,\n childId,\n deep,\n transformCache,\n pad,\n locked,\n instanceBodies\n )\n if (childHit) return standIn(child, childHit, true)\n\n if (\n containsPoint(px, py, child, graph, transformCache) &&\n takesEmptyArea(graph, child, instanceBodies)\n )\n return child\n return null\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\n/** Whether the masks that clip a layer leave the point outside every one of their outlines. */\nfunction isMaskedOut(\n px: number,\n py: number,\n masks: readonly SceneNode[] | undefined,\n graph: SceneGraph,\n transformCache: Map<string, boolean>\n): boolean {\n if (!masks) return false\n return (\n masks.length > 0 &&\n !masks.some((mask) => maskContainsPoint(px, py, mask, graph, transformCache))\n )\n}\n\n/**\n * The topmost layer under the point among a container's children. `pad`, in canvas units, grows\n * each leaf layer's box, as Figma takes a click a few screen pixels outside a shape.\n */\n/**\n * Whether a layer under the point can take the click. A locked layer and everything in it are\n * invisible to a press and to hover, as in Figma: a click falls through to what lies under it, and\n * a drag from it draws a marquee.\n */\nfunction takesClick(\n graph: SceneGraph,\n px: number,\n py: number,\n child: SceneNode | undefined,\n mask: readonly SceneNode[] | undefined,\n locked: boolean,\n transformCache: Map<string, boolean>\n): child is SceneNode {\n if (!child || child.internalOnly || !child.visible || (child.locked && !locked)) return false\n return !isMaskedOut(px, py, mask, graph, transformCache)\n}\n\nfunction hitTestChildren(\n graph: SceneGraph,\n px: number,\n py: number,\n parentId: string,\n deep = false,\n transformCache = new Map<string, boolean>(),\n pad = 0,\n locked = false,\n instanceBodies = false\n): SceneNode | null {\n const parent = graph.nodes.get(parentId)\n if (!parent) return null\n\n if (parent.clipsContent) {\n if (!containsPoint(px, py, parent, graph, transformCache)) return null\n }\n\n // Front to back, as the layers are drawn: a reversed auto layout puts the first child on top.\n const drawn = drawnChildIds(parent)\n const masks = clippingMasks(graph, drawn)\n for (let i = drawn.length - 1; i >= 0; i--) {\n const childId = drawn[i]\n const child = graph.nodes.get(childId)\n if (!takesClick(graph, px, py, child, masks[i], locked, transformCache)) continue\n if (CONTAINER_TYPES.has(child.type)) {\n if (OPAQUE_CONTAINER_TYPES.has(child.type) && !deep) {\n const hit = hitTestContainer(\n graph,\n px,\n py,\n child,\n childId,\n deep,\n transformCache,\n pad,\n locked,\n instanceBodies,\n true\n )\n if (hit) return hit\n continue\n }\n\n const hit = hitTestContainer(\n graph,\n px,\n py,\n child,\n childId,\n deep,\n transformCache,\n pad,\n locked,\n instanceBodies\n )\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 (containsPoint(px, py, child, graph, transformCache, pad)) return child\n }\n\n return null\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, false, new Map(), 0, false, true)\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, true, new Map(), 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.\n */\nfunction opensByItself(graph: SceneGraph, node: SceneNode): 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 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 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) && !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, and a\n * selected container itself, so a click inside it selects the layer under the point, as in Figma.\n * A selected group or boolean stays closed: clicking inside it keeps it selected.\n */\nfunction openedBySelection(\n graph: SceneGraph,\n selectedIds: ReadonlySet<string>,\n scopeId: string\n): Set<string> {\n const ancestors = new Set<string>()\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 )\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 function hitTestSelectable(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId: string,\n selectedIds: ReadonlySet<string>,\n pad = 0,\n /** Whether locked layers are hit, as a right-click hits them; see `hitTestAtPoint`. */\n locked = false\n): SceneNode | null {\n const deepest = hitTestChildren(graph, px, py, scopeId, true, new Map(), pad, locked, true)\n if (!deepest) {\n const scope = graph.nodes.get(scopeId)\n return scope ? frameChildAt(graph, scope, px, py, 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)\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)) return node\n }\n const last = chain.at(-1)\n if (!last) return null\n const frame = frameChildAt(graph, last, px, py, locked)\n if (frame) return frame\n if (ownsItsEmptyArea(graph, last)) return last\n return opened.has(last.id) && !opensByItself(graph, last) ? 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): boolean {\n const node = graph.nodes.get(nodeId)\n return node !== undefined && opensByItself(graph, node)\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, true, new Map(), 0, false, false)\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\nfunction rectsTouch(a: Rect, b: Rect): boolean {\n return a.x + a.width > b.x && a.x < b.x + b.width && a.y + a.height > b.y && a.y < b.y + b.height\n}\n\nfunction rectOverlap(a: Rect, b: Rect): Rect | null {\n if (!rectsTouch(a, b)) return null\n const x = Math.max(a.x, b.x)\n const y = Math.max(a.y, b.y)\n return {\n x,\n y,\n width: Math.min(a.x + a.width, b.x + b.width) - x,\n height: Math.min(a.y + a.height, b.y + b.height) - y\n }\n}\n\n/**\n * Whether a deep marquee touching a container, but none of its layers, selects it: where a deep\n * click there would select it (a group's box, a painted container, the empty area a top-level frame\n * with auto layout owns), except a board or section whose empty area a press treats as background.\n */\nfunction selectsByOwnArea(graph: SceneGraph, node: SceneNode): boolean {\n if (node.type === 'GROUP' || ownsItsEmptyArea(graph, node)) return true\n return showsPaint(node) && !opensByItself(graph, node)\n}\n\n/**\n * Collects the deepest layers among `parent`'s children that touch `rect`. Each child's world\n * matrix is composed from its parent's, so a walk over a large page climbs no ancestor chains.\n */\nfunction collectDeepestInRect(\n graph: SceneGraph,\n parent: SceneNode,\n parentWorld: Mat3,\n rect: Rect,\n hits: SceneNode[]\n) {\n // A clipping container draws nothing outside itself, so its layers meet only that part of the rect.\n const area =\n parent.clipsContent && parent.type !== 'CANVAS'\n ? rectOverlap(rect, getAxisAlignedBoundsAt(parent, parentWorld))\n : rect\n if (!area) return\n for (const childId of parent.childIds) {\n const child = graph.nodes.get(childId)\n if (!child || child.internalOnly || !child.visible || child.locked) continue\n const world = Matrix.multiply(parentWorld, getNodeLocalMatrix(child))\n const touches = rectsTouch(area, getAxisAlignedBoundsAt(child, world))\n if (!CONTAINER_TYPES.has(child.type) || child.childIds.length === 0) {\n if (touches) hits.push(child)\n continue\n }\n const before = hits.length\n collectDeepestInRect(graph, child, world, area, hits)\n if (hits.length === before && touches && selectsByOwnArea(graph, child)) hits.push(child)\n }\n}\n\n/**\n * The deepest layers a deep (⌘) marquee over `rect` selects, as in Figma, by the rules a deep click\n * follows: it looks into frames, groups, sections, components, component sets, and instances, keeps\n * a boolean's operands inside it, and skips hidden, locked, and internal layers with their contents.\n * A container is selected itself only where the rect touches its own area and none of its layers.\n * Layers are compared by their axis-aligned canvas bounds, as a plain marquee compares them.\n */\nexport function hitTestDeepInRect(graph: SceneGraph, rect: Rect, scopeId: string): SceneNode[] {\n const scope = graph.nodes.get(scopeId)\n if (!scope) return []\n const hits: SceneNode[] = []\n collectDeepestInRect(graph, scope, getWorldMatrix(scope, graph), rect, hits)\n return hits\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":";;;;;;AASA,MAAM,kCAAkB,IAAI,IAAc;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,yCAAyB,IAAI,IAAc,CAAC,aAAa,UAAU,CAAC;;;;;AAK1E,MAAM,uBAAuB;;;;;;AAO7B,SAAS,WAAW,OAA4C;CAC9D,IAAI,CAAC,MAAM,WAAW,EAAE,MAAM,UAAU,IAAI,OAAO;CACnD,IAAI,MAAM,SAAS,SAAS,OAAO,MA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AM,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/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, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseType, NumericNodeProperty, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ShaderEffect, ShadowEffect, 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, BooleanOperation, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, CommentReply, CommentThread, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, Effect, EnabledLibraryBinding, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseType, NumericNodeProperty, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ShaderEffect, ShadowEffect, 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, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseType, NumericNodeProperty, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraph, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ShaderEffect, ShadowEffect, 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, BooleanOperation, CODE_SYNTAX_PLATFORMS, CharacterStyleOverride, CodeSyntaxPlatform, CommentReply, CommentThread, CommittedGraphEventError, ComponentPropertyDefinition, ComponentPropertyReference, ComponentPropertyReferenceField, ComponentPropertyType, ConnectorControlPoint, ConnectorEndpoint, ConnectorLabelPosition, ConnectorLineType, ConnectorMagnet, ConstraintType, DerivedTextGlyph, DocumentColorSpace, DocumentKind, Effect, EnabledLibraryBinding, ExportSetting, FigmaLayoutMetadata, FigmaSourcePayload, Fill, FillType, FontFeature, FontVariation, GeometryPath, GradientStop, GradientTransform, GridPosition, GridTrack, GridTrackSizing, HandleMirroring, HyperlinkTarget, ImageFilters, ImageScaleMode, LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, LayoutDirection, LayoutGrid, LayoutMode, LayoutSizing, LayoutWrap, LeadingTrim, LibraryAssetIdentity, LibraryAssetSource, MODE_ATTRIBUTE_PATTERN, MaskType, MeshGradientPoint, NodeChangeObserver, NodeType, NoiseType, NumericNodeProperty, PatternAlignment, PatternTileType, PluginDataEntry, PluginRelaunchDataEntry, PrototypeAction, PrototypeActionType, PrototypeBackAction, PrototypeCloseAction, PrototypeNavigationType, PrototypeNodeAction, PrototypeOverlayPositionType, PrototypeReaction, PrototypeTransition, PrototypeTransitionType, PrototypeTrigger, PrototypeTriggerType, SceneGraph, SceneGraphEventHandlers, SceneGraphEvents, SceneNode, ShaderEffect, ShadowEffect, 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 };
|
package/dist/node-defaults.d.ts
CHANGED
|
@@ -18,6 +18,26 @@ declare function defaultNodeName(type: NodeType): string;
|
|
|
18
18
|
* the type's own name while they hold nothing.
|
|
19
19
|
*/
|
|
20
20
|
declare function textLayerName(type: NodeType, text: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* The fields auto layout sets on the frame that holds it, with the value each holds when no frame
|
|
23
|
+
* lays anything out. A page holds layers; it is not one, so none of these apply to it and a page
|
|
24
|
+
* that took them would place its layers by a container nobody can see.
|
|
25
|
+
*/
|
|
26
|
+
declare const FRAME_LAYOUT_DEFAULTS: {
|
|
27
|
+
readonly layoutMode: "NONE";
|
|
28
|
+
readonly layoutDirection: "AUTO";
|
|
29
|
+
readonly layoutWrap: "NO_WRAP";
|
|
30
|
+
readonly primaryAxisAlign: "MIN";
|
|
31
|
+
readonly counterAxisAlign: "MIN";
|
|
32
|
+
readonly primaryAxisSizing: "FIXED";
|
|
33
|
+
readonly counterAxisSizing: "FIXED";
|
|
34
|
+
readonly itemSpacing: 0;
|
|
35
|
+
readonly counterAxisSpacing: 0;
|
|
36
|
+
readonly paddingTop: 0;
|
|
37
|
+
readonly paddingRight: 0;
|
|
38
|
+
readonly paddingBottom: 0;
|
|
39
|
+
readonly paddingLeft: 0;
|
|
40
|
+
};
|
|
21
41
|
declare function createDefaultNode(generateId: () => string, type: NodeType, overrides?: Partial<SceneNode>): SceneNode;
|
|
22
42
|
/** Containers whose bounds follow their children and that set no coordinate space, as in Figma. */
|
|
23
43
|
declare const FITTED_CONTAINER_TYPES: ReadonlySet<NodeType>;
|
|
@@ -25,5 +45,5 @@ declare const FITTED_CONTAINER_TYPES: ReadonlySet<NodeType>;
|
|
|
25
45
|
declare const SIDE_STROKE_TYPES: ReadonlySet<NodeType>;
|
|
26
46
|
declare const CONTAINER_TYPES: Set<NodeType>;
|
|
27
47
|
//#endregion
|
|
28
|
-
export { CONTAINER_TYPES, FITTED_CONTAINER_TYPES, SIDE_STROKE_TYPES, createDefaultNode, createDefaultSourceMetadata, defaultNodeName, defaultStrokeAlign, newStrokeGeometry, textLayerName };
|
|
48
|
+
export { CONTAINER_TYPES, FITTED_CONTAINER_TYPES, FRAME_LAYOUT_DEFAULTS, SIDE_STROKE_TYPES, createDefaultNode, createDefaultSourceMetadata, defaultNodeName, defaultStrokeAlign, newStrokeGeometry, textLayerName };
|
|
29
49
|
//# sourceMappingURL=node-defaults.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-defaults.d.ts","names":[],"sources":["../src/node-defaults.ts"],"mappings":";;iBAWgB,+BAA+B;;iBA4B/B,mBAAmB,MAAM,WAAW;;;;;iBASpC,kBACd,MAAM,KAAK,yDACV,KAAK;;;;;iBASQ,gBAAgB,MAAM;;;;;iBAStB,cAAc,MAAM,UAAU
|
|
1
|
+
{"version":3,"file":"node-defaults.d.ts","names":[],"sources":["../src/node-defaults.ts"],"mappings":";;iBAWgB,+BAA+B;;iBA4B/B,mBAAmB,MAAM,WAAW;;;;;iBASpC,kBACd,MAAM,KAAK,yDACV,KAAK;;;;;iBASQ,gBAAgB,MAAM;;;;;iBAStB,cAAc,MAAM,UAAU;;;;;;cAajC;;;;;;;;;;;;;;;iBAgBG,kBACd,0BACA,MAAM,UACN,YAAW,QAAQ,aAClB;;cAwKU,wBAAwB,YAAY;;cAMpC,mBAAmB,YAAY;cAQ/B,iBAAe,IAAA"}
|
package/dist/node-defaults.js
CHANGED
|
@@ -53,6 +53,26 @@ function defaultNodeName(type) {
|
|
|
53
53
|
function textLayerName(type, text) {
|
|
54
54
|
return text.split(/\r\n|\r|\n/).map((line) => line.trim()).filter((line) => line !== "").join(" ") || defaultNodeName(type);
|
|
55
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* The fields auto layout sets on the frame that holds it, with the value each holds when no frame
|
|
58
|
+
* lays anything out. A page holds layers; it is not one, so none of these apply to it and a page
|
|
59
|
+
* that took them would place its layers by a container nobody can see.
|
|
60
|
+
*/
|
|
61
|
+
const FRAME_LAYOUT_DEFAULTS = {
|
|
62
|
+
layoutMode: "NONE",
|
|
63
|
+
layoutDirection: "AUTO",
|
|
64
|
+
layoutWrap: "NO_WRAP",
|
|
65
|
+
primaryAxisAlign: "MIN",
|
|
66
|
+
counterAxisAlign: "MIN",
|
|
67
|
+
primaryAxisSizing: "FIXED",
|
|
68
|
+
counterAxisSizing: "FIXED",
|
|
69
|
+
itemSpacing: 0,
|
|
70
|
+
counterAxisSpacing: 0,
|
|
71
|
+
paddingTop: 0,
|
|
72
|
+
paddingRight: 0,
|
|
73
|
+
paddingBottom: 0,
|
|
74
|
+
paddingLeft: 0
|
|
75
|
+
};
|
|
56
76
|
function createDefaultNode(generateId, type, overrides = {}) {
|
|
57
77
|
const node = {
|
|
58
78
|
id: generateId(),
|
|
@@ -106,19 +126,7 @@ function createDefaultNode(generateId, type, overrides = {}) {
|
|
|
106
126
|
leadingTrim: "NONE",
|
|
107
127
|
lineHeight: null,
|
|
108
128
|
letterSpacing: NO_LETTER_SPACING,
|
|
109
|
-
|
|
110
|
-
layoutDirection: "AUTO",
|
|
111
|
-
layoutWrap: "NO_WRAP",
|
|
112
|
-
primaryAxisAlign: "MIN",
|
|
113
|
-
counterAxisAlign: "MIN",
|
|
114
|
-
primaryAxisSizing: "FIXED",
|
|
115
|
-
counterAxisSizing: "FIXED",
|
|
116
|
-
itemSpacing: 0,
|
|
117
|
-
counterAxisSpacing: 0,
|
|
118
|
-
paddingTop: 0,
|
|
119
|
-
paddingRight: 0,
|
|
120
|
-
paddingBottom: 0,
|
|
121
|
-
paddingLeft: 0,
|
|
129
|
+
...FRAME_LAYOUT_DEFAULTS,
|
|
122
130
|
blendMode: "PASS_THROUGH",
|
|
123
131
|
layoutPositioning: "AUTO",
|
|
124
132
|
layoutGrow: 0,
|
|
@@ -256,6 +264,6 @@ const CONTAINER_TYPES = /* @__PURE__ */ new Set([
|
|
|
256
264
|
"INSTANCE"
|
|
257
265
|
]);
|
|
258
266
|
//#endregion
|
|
259
|
-
export { CONTAINER_TYPES, FITTED_CONTAINER_TYPES, SIDE_STROKE_TYPES, createDefaultNode, createDefaultSourceMetadata, defaultNodeName, defaultStrokeAlign, newStrokeGeometry, textLayerName };
|
|
267
|
+
export { CONTAINER_TYPES, FITTED_CONTAINER_TYPES, FRAME_LAYOUT_DEFAULTS, SIDE_STROKE_TYPES, createDefaultNode, createDefaultSourceMetadata, defaultNodeName, defaultStrokeAlign, newStrokeGeometry, textLayerName };
|
|
260
268
|
|
|
261
269
|
//# sourceMappingURL=node-defaults.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-defaults.js","names":[],"sources":["../src/node-defaults.ts"],"sourcesContent":["import {\n BLACK,\n DEFAULT_FONT_FAMILY,\n DEFAULT_STROKE_MITER_LIMIT,\n DEFAULT_STROKE_WEIGHT\n} from './constants'\nimport { normalizeEffects } from './effects'\nimport { createInstanceOverrideState } from './instances/overrides'\nimport { NO_LETTER_SPACING } from './text/lengths'\nimport type { NodeType, SceneNode, SourceMetadata } from './types'\n\nexport function createDefaultSourceMetadata(): SourceMetadata {\n return {\n format: null,\n id: null,\n orderKey: null,\n editedFields: [],\n fig: {\n rawSize: null,\n rawTransform: null,\n rawNodeFields: {},\n layout: null,\n symbolOverrides: [],\n componentPropAssignments: [],\n derivedSymbolData: [],\n derivedSymbolDataLayoutVersion: null,\n uniformScaleFactor: null\n }\n }\n}\n\n/**\n * Every SceneNode field. Nodes start with all of them, so setting any field later keeps the\n * shape every node shares; a key added after creation turns a JavaScriptCore object into a\n * slower, larger dictionary.\n */\ntype CompleteNodeFields = SceneNode & Record<keyof SceneNode, unknown>\n\n/** Where Figma aligns a new node's strokes: centered on lines and vectors, outside text, else inside. */\nexport function defaultStrokeAlign(type: NodeType): SceneNode['strokeAlign'] {\n if (type === 'LINE' || type === 'VECTOR') return 'CENTER'\n return type === 'TEXT' ? 'OUTSIDE' : 'INSIDE'\n}\n\n/**\n * Weight and alignment a stroke added to `node` takes: its first stroke's, or what the node keeps\n * with none. Adding a stroke from the panel and from the plugin API both go through here.\n */\nexport function newStrokeGeometry(\n node: Pick<SceneNode, 'strokes' | 'strokeWeight' | 'strokeAlign'>\n): Pick<SceneNode['strokes'][number], 'weight' | 'align'> {\n const first = node.strokes.at(0)\n return { weight: first?.weight ?? node.strokeWeight, align: first?.align ?? node.strokeAlign }\n}\n\n/**\n * The name a layer of `type` carries when nothing names it, as Figma writes a type's name: words\n * of a compound type apart, so a shape with text is a \"Shape with text\".\n */\nexport function defaultNodeName(type: NodeType): string {\n const words = type.toLowerCase().replaceAll('_', ' ')\n return words.charAt(0).toUpperCase() + words.slice(1)\n}\n\n/**\n * The name Figma gives a layer that follows its text: the characters trimmed, on one line, and\n * the type's own name while they hold nothing.\n */\nexport function textLayerName(type: NodeType, text: string): string {\n const lines = text\n .split(/\\r\\n|\\r|\\n/)\n .map((line) => line.trim())\n .filter((line) => line !== '')\n return lines.join(' ') || defaultNodeName(type)\n}\n\nexport function createDefaultNode(\n generateId: () => string,\n type: NodeType,\n overrides: Partial<SceneNode> = {}\n): SceneNode {\n const node = {\n id: generateId(),\n type,\n name: type.charAt(0) + type.slice(1).toLowerCase(),\n parentId: null,\n childIds: [],\n x: 0,\n y: 0,\n width: 100,\n height: 100,\n rotation: 0,\n source: createDefaultSourceMetadata(),\n derivedLayout: null,\n fills:\n type === 'TEXT' ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }] : [],\n strokes: [],\n effects: [],\n layoutGrids: [],\n guides: [],\n fillStyleId: null,\n strokeStyleId: null,\n textStyleId: null,\n effectStyleId: null,\n gridStyleId: null,\n sharedStyleType: null,\n opacity: 1,\n cornerRadius: 0,\n topLeftRadius: 0,\n topRightRadius: 0,\n bottomRightRadius: 0,\n bottomLeftRadius: 0,\n independentCorners: false,\n cornerSmoothing: 0,\n visible: true,\n locked: false,\n clipsContent: false,\n text: '',\n fontSize: 14,\n fontFamily: DEFAULT_FONT_FAMILY,\n fontWeight: 400,\n italic: false,\n fontStyle: null,\n textAlignHorizontal: 'LEFT',\n textDirection: 'AUTO',\n textLanguage: null,\n leadingTrim: 'NONE',\n lineHeight: null,\n letterSpacing: NO_LETTER_SPACING,\n layoutMode: 'NONE',\n layoutDirection: 'AUTO',\n layoutWrap: 'NO_WRAP',\n primaryAxisAlign: 'MIN',\n counterAxisAlign: 'MIN',\n primaryAxisSizing: 'FIXED',\n counterAxisSizing: 'FIXED',\n itemSpacing: 0,\n counterAxisSpacing: 0,\n paddingTop: 0,\n paddingRight: 0,\n paddingBottom: 0,\n paddingLeft: 0,\n blendMode: 'PASS_THROUGH',\n layoutPositioning: 'AUTO',\n layoutGrow: 0,\n layoutAlignSelf: 'AUTO',\n vectorNetwork: null,\n handleMirroring: 'NONE',\n fillGeometry: [],\n strokeGeometry: [],\n arcData: null,\n textAlignVertical: 'TOP',\n textAutoResize: 'NONE',\n textCase: 'ORIGINAL',\n textDecoration: 'NONE',\n textDecorationStyle: 'SOLID',\n textDecorationThickness: null,\n textDecorationFills: [],\n textDecorationSkipInk: true,\n textUnderlineOffset: null,\n maxLines: null,\n textParagraphs: [],\n listSpacing: 0,\n paragraphSpacing: 0,\n paragraphIndent: 0,\n hangingList: false,\n styleRuns: [],\n fontVariations: [],\n opticalSizeFromFontSize: true,\n fontFeatures: [],\n horizontalConstraint: 'MIN',\n verticalConstraint: 'MIN',\n strokeCap: 'NONE',\n strokeJoin: 'MITER',\n dashPattern: [],\n borderTopWeight: 0,\n borderRightWeight: 0,\n borderBottomWeight: 0,\n borderLeftWeight: 0,\n independentStrokeWeights: false,\n strokeWeight: DEFAULT_STROKE_WEIGHT,\n strokeAlign: defaultStrokeAlign(type),\n strokeMiterLimit: DEFAULT_STROKE_MITER_LIMIT,\n minWidth: null,\n maxWidth: null,\n minHeight: null,\n maxHeight: null,\n targetAspectRatio: null,\n connectorStart: null,\n connectorEnd: null,\n connectorLineType: 'ELBOWED',\n connectorStartCap: 'ROUND',\n connectorEndCap: 'ARROW_LINES',\n connectorControlPoints: [],\n connectorCurveHandles: null,\n connectorLabelPosition: null,\n isMask: false,\n maskType: 'ALPHA',\n maskIsOutline: false,\n gridTemplateColumns: [],\n gridTemplateRows: [],\n gridColumnGap: 0,\n gridRowGap: 0,\n gridPosition: null,\n counterAxisAlignContent: 'AUTO',\n itemReverseZIndex: false,\n strokesIncludedInLayout: false,\n expanded: true,\n textTruncation: 'DISABLED',\n autoRename: true,\n pointCount: 5,\n starInnerRadius: 0.38,\n shapeWithTextType: 'SQUARE',\n shapeUserHeight: 0,\n shapeTruncates: false,\n componentId: null,\n instanceOverrides: createInstanceOverrideState(),\n componentPropertyDefinitions: [],\n componentPropertyReferences: [],\n componentPropertyAssignments: {},\n componentPropertyValues: {},\n componentKey: null,\n sourceLibraryKey: null,\n publishId: null,\n overrideKey: null,\n sharedSymbolVersion: null,\n publishedVersion: null,\n librarySource: null,\n isPublishable: false,\n isSymbolPublishable: false,\n isExposedInstance: false,\n symbolDescription: '',\n symbolLinks: [],\n variantPropSpecs: [],\n boundVariables: {},\n variableBindingScales: {},\n variableAssignmentScales: {},\n componentScale: 1,\n variableModes: {},\n exportSettings: [],\n status: null,\n pluginData: [],\n pluginRelaunchData: [],\n prototypeReactions: [],\n internalOnly: false,\n flipX: false,\n flipY: false,\n textPicture: null,\n derivedTextGlyphs: null,\n derivedTextHeight: null,\n textPathData: null,\n textPathBox: null,\n booleanOperation: undefined,\n ...overrides\n } satisfies CompleteNodeFields\n node.effects = normalizeEffects(node.effects)\n return node\n}\n\n/** Containers whose bounds follow their children and that set no coordinate space, as in Figma. */\nexport const FITTED_CONTAINER_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'GROUP',\n 'BOOLEAN_OPERATION'\n])\n\n/** Layers whose stroke can take a weight per side, as Figma's `strokeTopWeight` and its siblings. */\nexport const SIDE_STROKE_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'RECTANGLE',\n 'FRAME',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n\nexport const CONTAINER_TYPES = new Set<NodeType>([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GA,MAAa,yCAAgD,IAAI,IAAc,CAC7E,SACA,mBACF,CAAC;;AAGD,MAAa,oCAA2C,IAAI,IAAc;CACxE;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,kCAAkB,IAAI,IAAc;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"node-defaults.js","names":[],"sources":["../src/node-defaults.ts"],"sourcesContent":["import {\n BLACK,\n DEFAULT_FONT_FAMILY,\n DEFAULT_STROKE_MITER_LIMIT,\n DEFAULT_STROKE_WEIGHT\n} from './constants'\nimport { normalizeEffects } from './effects'\nimport { createInstanceOverrideState } from './instances/overrides'\nimport { NO_LETTER_SPACING } from './text/lengths'\nimport type { NodeType, SceneNode, SourceMetadata } from './types'\n\nexport function createDefaultSourceMetadata(): SourceMetadata {\n return {\n format: null,\n id: null,\n orderKey: null,\n editedFields: [],\n fig: {\n rawSize: null,\n rawTransform: null,\n rawNodeFields: {},\n layout: null,\n symbolOverrides: [],\n componentPropAssignments: [],\n derivedSymbolData: [],\n derivedSymbolDataLayoutVersion: null,\n uniformScaleFactor: null\n }\n }\n}\n\n/**\n * Every SceneNode field. Nodes start with all of them, so setting any field later keeps the\n * shape every node shares; a key added after creation turns a JavaScriptCore object into a\n * slower, larger dictionary.\n */\ntype CompleteNodeFields = SceneNode & Record<keyof SceneNode, unknown>\n\n/** Where Figma aligns a new node's strokes: centered on lines and vectors, outside text, else inside. */\nexport function defaultStrokeAlign(type: NodeType): SceneNode['strokeAlign'] {\n if (type === 'LINE' || type === 'VECTOR') return 'CENTER'\n return type === 'TEXT' ? 'OUTSIDE' : 'INSIDE'\n}\n\n/**\n * Weight and alignment a stroke added to `node` takes: its first stroke's, or what the node keeps\n * with none. Adding a stroke from the panel and from the plugin API both go through here.\n */\nexport function newStrokeGeometry(\n node: Pick<SceneNode, 'strokes' | 'strokeWeight' | 'strokeAlign'>\n): Pick<SceneNode['strokes'][number], 'weight' | 'align'> {\n const first = node.strokes.at(0)\n return { weight: first?.weight ?? node.strokeWeight, align: first?.align ?? node.strokeAlign }\n}\n\n/**\n * The name a layer of `type` carries when nothing names it, as Figma writes a type's name: words\n * of a compound type apart, so a shape with text is a \"Shape with text\".\n */\nexport function defaultNodeName(type: NodeType): string {\n const words = type.toLowerCase().replaceAll('_', ' ')\n return words.charAt(0).toUpperCase() + words.slice(1)\n}\n\n/**\n * The name Figma gives a layer that follows its text: the characters trimmed, on one line, and\n * the type's own name while they hold nothing.\n */\nexport function textLayerName(type: NodeType, text: string): string {\n const lines = text\n .split(/\\r\\n|\\r|\\n/)\n .map((line) => line.trim())\n .filter((line) => line !== '')\n return lines.join(' ') || defaultNodeName(type)\n}\n\n/**\n * The fields auto layout sets on the frame that holds it, with the value each holds when no frame\n * lays anything out. A page holds layers; it is not one, so none of these apply to it and a page\n * that took them would place its layers by a container nobody can see.\n */\nexport const FRAME_LAYOUT_DEFAULTS = {\n layoutMode: 'NONE',\n layoutDirection: 'AUTO',\n layoutWrap: 'NO_WRAP',\n primaryAxisAlign: 'MIN',\n counterAxisAlign: 'MIN',\n primaryAxisSizing: 'FIXED',\n counterAxisSizing: 'FIXED',\n itemSpacing: 0,\n counterAxisSpacing: 0,\n paddingTop: 0,\n paddingRight: 0,\n paddingBottom: 0,\n paddingLeft: 0\n} as const satisfies Partial<SceneNode>\n\nexport function createDefaultNode(\n generateId: () => string,\n type: NodeType,\n overrides: Partial<SceneNode> = {}\n): SceneNode {\n const node = {\n id: generateId(),\n type,\n name: type.charAt(0) + type.slice(1).toLowerCase(),\n parentId: null,\n childIds: [],\n x: 0,\n y: 0,\n width: 100,\n height: 100,\n rotation: 0,\n source: createDefaultSourceMetadata(),\n derivedLayout: null,\n fills:\n type === 'TEXT' ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }] : [],\n strokes: [],\n effects: [],\n layoutGrids: [],\n guides: [],\n fillStyleId: null,\n strokeStyleId: null,\n textStyleId: null,\n effectStyleId: null,\n gridStyleId: null,\n sharedStyleType: null,\n opacity: 1,\n cornerRadius: 0,\n topLeftRadius: 0,\n topRightRadius: 0,\n bottomRightRadius: 0,\n bottomLeftRadius: 0,\n independentCorners: false,\n cornerSmoothing: 0,\n visible: true,\n locked: false,\n clipsContent: false,\n text: '',\n fontSize: 14,\n fontFamily: DEFAULT_FONT_FAMILY,\n fontWeight: 400,\n italic: false,\n fontStyle: null,\n textAlignHorizontal: 'LEFT',\n textDirection: 'AUTO',\n textLanguage: null,\n leadingTrim: 'NONE',\n lineHeight: null,\n letterSpacing: NO_LETTER_SPACING,\n ...FRAME_LAYOUT_DEFAULTS,\n blendMode: 'PASS_THROUGH',\n layoutPositioning: 'AUTO',\n layoutGrow: 0,\n layoutAlignSelf: 'AUTO',\n vectorNetwork: null,\n handleMirroring: 'NONE',\n fillGeometry: [],\n strokeGeometry: [],\n arcData: null,\n textAlignVertical: 'TOP',\n textAutoResize: 'NONE',\n textCase: 'ORIGINAL',\n textDecoration: 'NONE',\n textDecorationStyle: 'SOLID',\n textDecorationThickness: null,\n textDecorationFills: [],\n textDecorationSkipInk: true,\n textUnderlineOffset: null,\n maxLines: null,\n textParagraphs: [],\n listSpacing: 0,\n paragraphSpacing: 0,\n paragraphIndent: 0,\n hangingList: false,\n styleRuns: [],\n fontVariations: [],\n opticalSizeFromFontSize: true,\n fontFeatures: [],\n horizontalConstraint: 'MIN',\n verticalConstraint: 'MIN',\n strokeCap: 'NONE',\n strokeJoin: 'MITER',\n dashPattern: [],\n borderTopWeight: 0,\n borderRightWeight: 0,\n borderBottomWeight: 0,\n borderLeftWeight: 0,\n independentStrokeWeights: false,\n strokeWeight: DEFAULT_STROKE_WEIGHT,\n strokeAlign: defaultStrokeAlign(type),\n strokeMiterLimit: DEFAULT_STROKE_MITER_LIMIT,\n minWidth: null,\n maxWidth: null,\n minHeight: null,\n maxHeight: null,\n targetAspectRatio: null,\n connectorStart: null,\n connectorEnd: null,\n connectorLineType: 'ELBOWED',\n connectorStartCap: 'ROUND',\n connectorEndCap: 'ARROW_LINES',\n connectorControlPoints: [],\n connectorCurveHandles: null,\n connectorLabelPosition: null,\n isMask: false,\n maskType: 'ALPHA',\n maskIsOutline: false,\n gridTemplateColumns: [],\n gridTemplateRows: [],\n gridColumnGap: 0,\n gridRowGap: 0,\n gridPosition: null,\n counterAxisAlignContent: 'AUTO',\n itemReverseZIndex: false,\n strokesIncludedInLayout: false,\n expanded: true,\n textTruncation: 'DISABLED',\n autoRename: true,\n pointCount: 5,\n starInnerRadius: 0.38,\n shapeWithTextType: 'SQUARE',\n shapeUserHeight: 0,\n shapeTruncates: false,\n componentId: null,\n instanceOverrides: createInstanceOverrideState(),\n componentPropertyDefinitions: [],\n componentPropertyReferences: [],\n componentPropertyAssignments: {},\n componentPropertyValues: {},\n componentKey: null,\n sourceLibraryKey: null,\n publishId: null,\n overrideKey: null,\n sharedSymbolVersion: null,\n publishedVersion: null,\n librarySource: null,\n isPublishable: false,\n isSymbolPublishable: false,\n isExposedInstance: false,\n symbolDescription: '',\n symbolLinks: [],\n variantPropSpecs: [],\n boundVariables: {},\n variableBindingScales: {},\n variableAssignmentScales: {},\n componentScale: 1,\n variableModes: {},\n exportSettings: [],\n status: null,\n pluginData: [],\n pluginRelaunchData: [],\n prototypeReactions: [],\n internalOnly: false,\n flipX: false,\n flipY: false,\n textPicture: null,\n derivedTextGlyphs: null,\n derivedTextHeight: null,\n textPathData: null,\n textPathBox: null,\n booleanOperation: undefined,\n ...overrides\n } satisfies CompleteNodeFields\n node.effects = normalizeEffects(node.effects)\n return node\n}\n\n/** Containers whose bounds follow their children and that set no coordinate space, as in Figma. */\nexport const FITTED_CONTAINER_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'GROUP',\n 'BOOLEAN_OPERATION'\n])\n\n/** Layers whose stroke can take a weight per side, as Figma's `strokeTopWeight` and its siblings. */\nexport const SIDE_STROKE_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'RECTANGLE',\n 'F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nB,mBAAmB;EACnB,cAAc;EACd,aAAa;EACb,kBAAkB,KAAA;EAClB,GAAG;CACL;CACA,KAAK,UAAU,iBAAiB,KAAK,OAAO;CAC5C,OAAO;AACT;;AAGA,MAAa,yCAAgD,IAAI,IAAc,CAC7E,SACA,mBACF,CAAC;;AAGD,MAAa,oCAA2C,IAAI,IAAc;CACxE;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,kCAAkB,IAAI,IAAc;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
|
package/dist/resize.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resize.d.ts","names":[],"sources":["../src/resize.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"resize.d.ts","names":[],"sources":["../src/resize.ts"],"mappings":";;;;;;;;;KAmBY,iBAAiB,KAC3B;UAiBQ;EACR,QAAQ,aAAa;;;KAeX,kBAAkB;EAAS;EAAkB;;;iBAyDzC,iBACd,QAAQ,MACR,MAAM,KAAK,2BACX,YAAY,gBACZ,UAAU,iBACT;KAwBE,mBACH,OAAO,MACP,cAAc,KAAK,2BACnB,aAAa,KAAK,2BAClB,YAAY,gBACZ,UAAU,gBACV,gCACG;;;;;cAuCQ,sBAAoB;;;;;;cAOpB,4BAA0B;iBAEvB,gBACd,OAAO,MACP,cAAc,KAAK,2BACnB,aAAa,KAAK,4BACjB;iBAIa,4BACd,eAAe,sBACf,uBACA,wBACA,eACA,iBACC;;iBA8Ba,qBAAqB,MAAM,YAAY;;;;;;;iBAoDvC,sBACd,MAAM,KACJ,kJAUF,mBACA,oBACA,eACA,iBACC,QAAQ;;;;;;;;iBA0CK,qBACd,MAAM,WACN,eACA,iBACC,KAAK,QAAQ;KAkBX,iBAAiB,KAAK;;iBAGX,sBACd,MAAM,gBACN,YACA,aACC,KAAK,QAAQ;iBAmBA,yBACd,OAAO,aACP,iBACC,YAAY;;;;;iBAwBC,YACd,MAAM,KAAK,+BACX,SAAS,KAAK,+BACd,kBACA,mBACC,QAAQ,KAAK;iBASA,gCACd,OAAO,aACP,gBACA,YAAY,KAAK,2BACjB,WAAW,KAAK,2BAChB,WAAW,oBAAoB,kBAC9B,YAAY,QAAQ"}
|
package/dist/resize.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { cloneVectorNetwork } from "./vector-network.js";
|
|
2
2
|
import { copyDerivedGlyphs, copyGeometryPaths, copyStroke, copyStrokes, scaleGeometryPaths } from "./copy.js";
|
|
3
3
|
import { enforcedAspectRatio } from "./layout/aspect-ratio.js";
|
|
4
|
+
import { followsPath } from "./text/path.js";
|
|
4
5
|
//#region src/resize.ts
|
|
5
6
|
const CONSTRAINT_CONTAINER_TYPES = /* @__PURE__ */ new Set([
|
|
6
7
|
"FRAME",
|
|
@@ -226,7 +227,7 @@ function scaledGeometryChanges(orig, origWidth, origHeight, width, height) {
|
|
|
226
227
|
const outlineOnly = orig.type === "TEXT" || orig.type === "VECTOR" && !hasPath(orig);
|
|
227
228
|
if (orig.strokeGeometry.length > 0) changes.strokeGeometry = outlineOnly ? scaleGeometryPaths(orig.strokeGeometry, sx, sy) : [];
|
|
228
229
|
Object.assign(changes, scaledPathTextChanges(orig, sx, sy));
|
|
229
|
-
if (orig.strokes.length > 0 &&
|
|
230
|
+
if (orig.strokes.length > 0 && followsPath(orig)) changes.strokes = scaleStrokes(orig.strokes, sx, sy);
|
|
230
231
|
return changes;
|
|
231
232
|
}
|
|
232
233
|
/**
|
|
@@ -249,13 +250,9 @@ function shapeGeometryChanges(node, width, height) {
|
|
|
249
250
|
if (changes.strokeGeometry) geometry.strokeGeometry = changes.strokeGeometry;
|
|
250
251
|
return geometry;
|
|
251
252
|
}
|
|
252
|
-
function isScaledPathText(orig) {
|
|
253
|
-
const glyphs = orig.derivedTextGlyphs ?? [];
|
|
254
|
-
return glyphs.length > 0 && (!!orig.textPathData || !!orig.textPathBox || glyphs.some((glyph) => (glyph.rotation ?? 0) !== 0));
|
|
255
|
-
}
|
|
256
253
|
/** The baked glyphs and layout box of path text, scaled with the layer; nothing for other text. */
|
|
257
254
|
function scaledPathTextChanges(orig, sx, sy) {
|
|
258
|
-
if (!
|
|
255
|
+
if (!followsPath(orig)) return {};
|
|
259
256
|
const changes = { derivedTextGlyphs: scaleDerivedGlyphs(orig.derivedTextGlyphs, sx, sy) };
|
|
260
257
|
if (orig.textPathBox) changes.textPathBox = {
|
|
261
258
|
x: orig.textPathBox.x * sx,
|
package/dist/resize.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resize.js","names":[],"sources":["../src/resize.ts"],"sourcesContent":["import {\n copyDerivedGlyphs,\n copyGeometryPaths,\n copyStroke,\n copyStrokes,\n scaleGeometryPaths\n} from './copy'\nimport { enforcedAspectRatio } from './layout/aspect-ratio'\nimport type { Rect } from './primitives'\nimport type { ConstraintType, DerivedTextGlyph, SceneNode, Stroke, VectorNetwork } from './types'\nimport { cloneVectorNetwork } from './vector-network'\n\n/**\n * Drag-start state a live resize re-scales from. Path text needs more than the\n * layout rect: its OUTSIDE stroke silhouettes and glyph outlines are baked\n * geometry that must scale with the node, and textPathBox is the layout box the\n * glyphs were reflowed against.\n */\nexport type ResizeSnapshot = Pick<\n SceneNode,\n | 'type'\n | 'x'\n | 'y'\n | 'width'\n | 'height'\n | 'flipX'\n | 'flipY'\n | 'vectorNetwork'\n | 'fillGeometry'\n | 'strokeGeometry'\n | 'derivedTextGlyphs'\n | 'strokes'\n | 'textPathData'\n | 'textPathBox'\n>\n\ninterface ResizeGraph {\n getNode(id: string): SceneNode | undefined\n}\n\nconst CONSTRAINT_CONTAINER_TYPES = new Set([\n 'FRAME',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE',\n 'GROUP',\n 'BOOLEAN_OPERATION'\n])\n\ntype AxisPlacement = { position: number; size: number; flipped?: boolean }\n\n/** A child's box after its parent resizes, and the axes on which it turned over. */\nexport type ConstrainedRect = Rect & { flipsX?: boolean; flipsY?: boolean }\n\n/**\n * Where a constraint places a child on one axis when its parent goes from `parentBefore` to\n * `parentAfter`, as Figma does: Right and Left & right move or grow it by the change in the\n * parent's size rounded to whole pixels, Center by the change in its rounded half, and Scale by\n * the exact ratio. The child's own box is never rounded, so a resize to the same size changes\n * nothing. Left & right that would leave no size keeps the axis as it was; past zero, the child\n * turns over and its box runs back from the edge it was pinned to, as the layer is mirrored in\n * Figma. `scaleStep` snaps a scaled position to that fraction of a pixel.\n */\nfunction constrainedAxis(\n position: number,\n size: number,\n parentBefore: number,\n parentAfter: number,\n constraint: ConstraintType,\n scaleStep = 0,\n allowFlips = true\n): AxisPlacement {\n const delta = Math.round(parentAfter) - Math.round(parentBefore)\n if (constraint === 'MAX') return { position: position + delta, size }\n if (constraint === 'CENTER') {\n return { position: position + Math.round(parentAfter / 2) - Math.round(parentBefore / 2), size }\n }\n if (constraint === 'STRETCH') {\n const stretched = size + delta\n if (!allowFlips) return { position, size: Math.abs(stretched) }\n if (stretched === 0) return { position, size }\n if (stretched > 0) return { position, size: stretched }\n return { position: position + stretched, size: -stretched, flipped: true }\n }\n if (constraint === 'SCALE' && parentBefore > 0) {\n const scale = parentAfter / parentBefore\n const scaled = position * scale\n return {\n position: scaleStep > 0 ? Math.round(scaled / scaleStep) * scaleStep : scaled,\n size: size * scale\n }\n }\n return { position, size }\n}\n\nconst FLEXIBLE_CONSTRAINTS: ReadonlySet<ConstraintType> = new Set(['STRETCH', 'SCALE'])\n\n/** The axis at `size`, keeping the edge or centre its constraint pins where it was placed. */\nfunction resizedInPlace(\n placed: AxisPlacement,\n size: number,\n constraint: ConstraintType\n): AxisPlacement {\n if (constraint === 'MAX') return { position: placed.position + placed.size - size, size }\n if (constraint === 'CENTER') return { position: placed.position + (placed.size - size) / 2, size }\n return { position: placed.position, size }\n}\n\n/** Keep a placed box's constrained edges or center when its content determines its size. */\nexport function resizedChildRect(\n placed: Rect,\n size: Pick<Rect, 'width' | 'height'>,\n horizontal: ConstraintType,\n vertical: ConstraintType\n): Rect {\n const x = resizedInPlace({ position: placed.x, size: placed.width }, size.width, horizontal)\n const y = resizedInPlace({ position: placed.y, size: placed.height }, size.height, vertical)\n return { x: x.position, y: y.position, width: x.size, height: y.size }\n}\n\n/**\n * A locked aspect ratio holds when exactly one axis follows the parent, as in Figma: that axis\n * sizes the other. With both axes following the parent, or neither, the ratio gives way.\n */\nfunction keepLockedRatio(\n x: AxisPlacement,\n y: AxisPlacement,\n horizontal: ConstraintType,\n vertical: ConstraintType,\n aspectRatio: number | null\n): { x: AxisPlacement; y: AxisPlacement } {\n const flexibleX = FLEXIBLE_CONSTRAINTS.has(horizontal)\n if (aspectRatio === null || flexibleX === FLEXIBLE_CONSTRAINTS.has(vertical)) return { x, y }\n return flexibleX\n ? { x, y: resizedInPlace(y, x.size / aspectRatio, vertical) }\n : { x: resizedInPlace(x, y.size * aspectRatio, horizontal), y }\n}\n\ntype ChildRectPlacer = (\n child: Rect,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>,\n horizontal: ConstraintType,\n vertical: ConstraintType,\n aspectRatio?: number | null\n) => ConstrainedRect\n\n/** Places a child by its constraints, snapping a scaled position to `scaleStep` when it is set. */\nfunction childRectPlacer(scaleStep: number, allowFlips = true): ChildRectPlacer {\n return (child, parentBefore, parentAfter, horizontal, vertical, aspectRatio = null) => {\n const { x, y } = keepLockedRatio(\n constrainedAxis(\n child.x,\n child.width,\n parentBefore.width,\n parentAfter.width,\n horizontal,\n scaleStep,\n allowFlips\n ),\n constrainedAxis(\n child.y,\n child.height,\n parentBefore.height,\n parentAfter.height,\n vertical,\n scaleStep,\n allowFlips\n ),\n horizontal,\n vertical,\n aspectRatio\n )\n const rect: ConstrainedRect = { x: x.position, y: y.position, width: x.size, height: y.size }\n if (x.flipped) rect.flipsX = true\n if (y.flipped) rect.flipsY = true\n return rect\n }\n}\n\n/**\n * A child's box after its parent is resized, by a handle or `resize()`, keeping a locked aspect\n * ratio as Figma does.\n */\nexport const constrainedChildRect = childRectPlacer(0)\n\n/**\n * Where a child goes when layout resizes its parent, as Figma places a layer that ignores auto\n * layout when its Hug frame grows (measured on desktop 126): as `constrainedChildRect`, except\n * that a scaled position lands on 1/128 of a pixel.\n */\nexport const layoutConstrainedChildRect = childRectPlacer(1 / 128, false)\n\nexport function scaledChildRect(\n child: Rect,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>\n): Rect {\n return constrainedChildRect(child, parentBefore, parentAfter, 'SCALE', 'SCALE')\n}\n\nexport function scaleVectorNetworkForResize(\n vectorNetwork: VectorNetwork | null,\n originalWidth: number,\n originalHeight: number,\n width: number,\n height: number\n): VectorNetwork | null {\n if (!vectorNetwork || (originalWidth <= 0 && originalHeight <= 0)) return null\n\n // A flat side, as a straight line's, has nothing to scale along it.\n const scaleX = originalWidth > 0 ? width / originalWidth : 1\n const scaleY = originalHeight > 0 ? height / originalHeight : 1\n if (scaleX === 1 && scaleY === 1) return null\n\n return {\n vertices: vectorNetwork.vertices.map((vertex) => ({\n ...vertex,\n x: vertex.x * scaleX,\n y: vertex.y * scaleY\n })),\n segments: vectorNetwork.segments.map((segment) => ({\n ...segment,\n tangentStart: {\n x: segment.tangentStart.x * scaleX,\n y: segment.tangentStart.y * scaleY\n },\n tangentEnd: {\n x: segment.tangentEnd.x * scaleX,\n y: segment.tangentEnd.y * scaleY\n }\n })),\n regions: vectorNetwork.regions\n }\n}\n\n/** Snapshot one node's resize-relevant state (rect + geometry that must scale with it). */\nexport function createResizeSnapshot(node: SceneNode): ResizeSnapshot {\n return {\n type: node.type,\n x: node.x,\n y: node.y,\n width: node.width,\n height: node.height,\n flipX: node.flipX,\n flipY: node.flipY,\n vectorNetwork: node.vectorNetwork ? cloneVectorNetwork(node.vectorNetwork) : null,\n fillGeometry: copyGeometryPaths(node.fillGeometry),\n strokeGeometry: copyGeometryPaths(node.strokeGeometry),\n derivedTextGlyphs: copyDerivedGlyphs(node.derivedTextGlyphs),\n strokes: copyStrokes(node.strokes),\n textPathData: node.textPathData ? structuredClone(node.textPathData) : null,\n textPathBox: node.textPathBox ? { ...node.textPathBox } : null\n }\n}\n\nfunction scaleDerivedGlyphs(\n glyphs: DerivedTextGlyph[] | null,\n sx: number,\n sy: number\n): DerivedTextGlyph[] | null {\n if (!glyphs?.length) return glyphs\n return glyphs.map((g) => ({\n ...g,\n x: g.x * sx,\n y: g.y * sy,\n scaleX: (g.scaleX ?? 1) * sx,\n scaleY: (g.scaleY ?? 1) * sy,\n commandsBlob: new Uint8Array(g.commandsBlob)\n }))\n}\n\nfunction hasPath(orig: Pick<ResizeSnapshot, 'vectorNetwork'>): boolean {\n return (orig.vectorNetwork?.segments.length ?? 0) > 0\n}\n\nfunction scaleStrokes(strokes: Stroke[], sx: number, sy: number): Stroke[] {\n if (strokes.length === 0) return strokes\n // Weight is a scalar; average scale is the usual 2D → 1D compromise.\n const weightScale = (Math.abs(sx) + Math.abs(sy)) / 2\n return strokes.map((s) => ({ ...copyStroke(s), weight: s.weight * weightScale }))\n}\n\n/**\n * All geometry that must track a width/height change. Historically only\n * vectorNetwork + fillGeometry were updated — path-text strokeGeometry and\n * glyphs stayed at the pre-resize size, so shrinking a sticker made the white\n * OUTSIDE outlines look massively thick (DomeSticker resize bug).\n */\nexport function scaledGeometryChanges(\n orig: Pick<\n ResizeSnapshot,\n | 'type'\n | 'vectorNetwork'\n | 'fillGeometry'\n | 'strokeGeometry'\n | 'derivedTextGlyphs'\n | 'strokes'\n | 'textPathData'\n | 'textPathBox'\n >,\n origWidth: number,\n origHeight: number,\n width: number,\n height: number\n): Partial<SceneNode> {\n if (origWidth <= 0 || origHeight <= 0) return {}\n const sx = width / origWidth\n const sy = height / origHeight\n if (sx === 1 && sy === 1) return {}\n\n const changes: Partial<SceneNode> = {}\n const resizedVN = scaleVectorNetworkForResize(\n orig.vectorNetwork,\n origWidth,\n origHeight,\n width,\n height\n )\n if (resizedVN) changes.vectorNetwork = resizedVN\n\n if (orig.fillGeometry.length > 0) {\n changes.fillGeometry = scaleGeometryPaths(orig.fillGeometry, sx, sy)\n }\n // A stroke keeps its weight through a resize, as in Figma, so a saved stroke outline goes where\n // the stroke can be drawn again at its weight: from a path, or from a shape's own outline.\n // Text and a vector with only its outline keep scaling the outline, which is all they have.\n const outlineOnly = orig.type === 'TEXT' || (orig.type === 'VECTOR' && !hasPath(orig))\n if (orig.strokeGeometry.length > 0) {\n changes.strokeGeometry = outlineOnly ? scaleGeometryPaths(orig.strokeGeometry, sx, sy) : []\n }\n Object.assign(changes, scaledPathTextChanges(orig, sx, sy))\n // Glyphs scaled as a picture take their strokes along; any other stroke keeps its weight, as\n // Figma reports it, even where only a scaled outline can draw it.\n if (orig.strokes.length > 0 && isScaledPathText(orig)) {\n changes.strokes = scaleStrokes(orig.strokes, sx, sy)\n }\n return changes\n}\n\n/**\n * The saved outlines a size change invalidates on a layer drawn from its live box: its fill\n * outline follows the box, and its saved stroke outline goes, so the stroke is drawn again at its\n * weight through the live shape. A vector and text draw from outlines of their own, which scaling\n * keeps. Without this, a layer that came from a `.fig` with frame outlines keeps drawing the old\n * box after layout, the Plugin API or an instance sync resizes it.\n */\nexport function shapeGeometryChanges(\n node: SceneNode,\n width: number,\n height: number\n): Pick<Partial<SceneNode>, 'fillGeometry' | 'strokeGeometry'> {\n if (node.type === 'VECTOR' || node.type === 'TEXT') return {}\n if (node.fillGeometry.length === 0 && node.strokeGeometry.length === 0) return {}\n // A box with no extent has no outline to scale from; the live shape draws both again.\n if (node.width <= 0 || node.height <= 0) return { fillGeometry: [], strokeGeometry: [] }\n const changes = scaledGeometryChanges(\n createResizeSnapshot(node),\n node.width,\n node.height,\n width,\n height\n )\n const geometry: Pick<Partial<SceneNode>, 'fillGeometry' | 'strokeGeometry'> = {}\n if (changes.fillGeometry) geometry.fillGeometry = changes.fillGeometry\n if (changes.strokeGeometry) geometry.strokeGeometry = changes.strokeGeometry\n return geometry\n}\n\ntype PathTextFields = Pick<SceneNode, 'derivedTextGlyphs' | 'textPathData' | 'textPathBox'>\n\n// Path text scales with its path, including baked path text that kept only rotated glyphs;\n// other text reflows in the new box, so its glyphs are dropped.\nfunction isScaledPathText(orig: PathTextFields): boolean {\n const glyphs = orig.derivedTextGlyphs ?? []\n return (\n glyphs.length > 0 &&\n (!!orig.textPathData ||\n !!orig.textPathBox ||\n glyphs.some((glyph) => (glyph.rotation ?? 0) !== 0))\n )\n}\n\n/** The baked glyphs and layout box of path text, scaled with the layer; nothing for other text. */\nexport function scaledPathTextChanges(\n orig: PathTextFields,\n sx: number,\n sy: number\n): Pick<Partial<SceneNode>, 'derivedTextGlyphs' | 'textPathBox'> {\n if (!isScaledPathText(orig)) return {}\n const changes: Pick<Partial<SceneNode>, 'derivedTextGlyphs' | 'textPathBox'> = {\n derivedTextGlyphs: scaleDerivedGlyphs(orig.derivedTextGlyphs, sx, sy)\n }\n // Keep the layout/selection box in sync with the scaled glyphs. reflow\n // overrides this when it applies; this covers the fallback where reflow\n // returns null (no path data) so the box doesn't carry a stale size.\n if (orig.textPathBox) {\n changes.textPathBox = {\n x: orig.textPathBox.x * sx,\n y: orig.textPathBox.y * sy,\n width: orig.textPathBox.width * sx,\n height: orig.textPathBox.height * sy\n }\n }\n return changes\n}\n\nexport function collectResizeDescendants(\n graph: ResizeGraph,\n rootId: string\n): Map<string, ResizeSnapshot> | null {\n const root = graph.getNode(rootId)\n if (!root || !CONSTRAINT_CONTAINER_TYPES.has(root.type)) return null\n const snapshots = new Map<string, ResizeSnapshot>()\n\n const collect = (parentId: string) => {\n const parent = graph.getNode(parentId)\n if (!parent) return\n for (const childId of parent.childIds) {\n const child = graph.getNode(childId)\n if (!child) continue\n snapshots.set(childId, createResizeSnapshot(child))\n collect(childId)\n }\n }\n\n collect(rootId)\n return snapshots.size > 0 ? snapshots : null\n}\n\n/**\n * The flips a child takes when its constraints place it from `from`, written only where they\n * differ from the ones it has now, so a drag that crosses back undoes its own turn.\n */\nexport function flipChanges(\n from: Pick<SceneNode, 'flipX' | 'flipY'>,\n current: Pick<SceneNode, 'flipX' | 'flipY'>,\n flipsX = false,\n flipsY = false\n): Partial<Pick<SceneNode, 'flipX' | 'flipY'>> {\n const changes: Partial<Pick<SceneNode, 'flipX' | 'flipY'>> = {}\n const flipX = from.flipX !== flipsX\n const flipY = from.flipY !== flipsY\n if (flipX !== current.flipX) changes.flipX = flipX\n if (flipY !== current.flipY) changes.flipY = flipY\n return changes\n}\n\nexport function computeConstrainedResizeChanges(\n graph: ResizeGraph,\n rootId: string,\n rootBefore: Pick<Rect, 'width' | 'height'>,\n rootAfter: Pick<Rect, 'width' | 'height'>,\n originals: ReadonlyMap<string, ResizeSnapshot>\n): Map<string, Partial<SceneNode>> {\n const changes = new Map<string, Partial<SceneNode>>()\n\n const compute = (\n parentId: string,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>\n ) => {\n const parent = graph.getNode(parentId)\n if (!parent) return\n const scalesChildren = parent.type === 'GROUP' || parent.type === 'BOOLEAN_OPERATION'\n for (const childId of parent.childIds) {\n const original = originals.get(childId)\n const child = graph.getNode(childId)\n if (!original || !child) continue\n const isInFlow = parent.layoutMode !== 'NONE' && child.layoutPositioning !== 'ABSOLUTE'\n if (isInFlow) {\n compute(childId, original, child)\n continue\n }\n const rect: ConstrainedRect = scalesChildren\n ? scaledChildRect(original, parentBefore, parentAfter)\n : constrainedChildRect(\n original,\n parentBefore,\n parentAfter,\n child.horizontalConstraint,\n child.verticalConstraint,\n enforcedAspectRatio(child)\n )\n const { flipsX, flipsY, ...box } = rect\n const childChanges: Partial<SceneNode> = {\n ...box,\n ...flipChanges(original, child, flipsX, flipsY),\n ...scaledGeometryChanges(original, original.width, original.height, box.width, box.height)\n }\n changes.set(childId, childChanges)\n // The final pass sees layout containers after Yoga has resolved HUG/FILL sizing.\n compute(childId, original, child.layoutMode === 'NONE' ? box : child)\n }\n }\n\n compute(rootId, root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C3B;GAEJ,MAAM,eAAmC;IACvC,GAAG;IACH,GAAG,YAAY,UAAU,OAAO,QAAQ,MAAM;IAC9C,GAAG,sBAAsB,UAAU,SAAS,OAAO,SAAS,QAAQ,IAAI,OAAO,IAAI,MAAM;GAC3F;GACA,QAAQ,IAAI,SAAS,YAAY;GAEjC,QAAQ,SAAS,UAAU,MAAM,eAAe,SAAS,MAAM,KAAK;EACtE;CACF;CAEA,QAAQ,QAAQ,YAAY,SAAS;CACrC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"resize.js","names":[],"sources":["../src/resize.ts"],"sourcesContent":["import {\n copyDerivedGlyphs,\n copyGeometryPaths,\n copyStroke,\n copyStrokes,\n scaleGeometryPaths\n} from './copy'\nimport { enforcedAspectRatio } from './layout/aspect-ratio'\nimport type { Rect } from './primitives'\nimport { followsPath } from './text/path'\nimport type { ConstraintType, DerivedTextGlyph, SceneNode, Stroke, VectorNetwork } from './types'\nimport { cloneVectorNetwork } from './vector-network'\n\n/**\n * Drag-start state a live resize re-scales from. Path text needs more than the\n * layout rect: its OUTSIDE stroke silhouettes and glyph outlines are baked\n * geometry that must scale with the node, and textPathBox is the layout box the\n * glyphs were reflowed against.\n */\nexport type ResizeSnapshot = Pick<\n SceneNode,\n | 'type'\n | 'x'\n | 'y'\n | 'width'\n | 'height'\n | 'flipX'\n | 'flipY'\n | 'vectorNetwork'\n | 'fillGeometry'\n | 'strokeGeometry'\n | 'derivedTextGlyphs'\n | 'strokes'\n | 'textPathData'\n | 'textPathBox'\n>\n\ninterface ResizeGraph {\n getNode(id: string): SceneNode | undefined\n}\n\nconst CONSTRAINT_CONTAINER_TYPES = new Set([\n 'FRAME',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE',\n 'GROUP',\n 'BOOLEAN_OPERATION'\n])\n\ntype AxisPlacement = { position: number; size: number; flipped?: boolean }\n\n/** A child's box after its parent resizes, and the axes on which it turned over. */\nexport type ConstrainedRect = Rect & { flipsX?: boolean; flipsY?: boolean }\n\n/**\n * Where a constraint places a child on one axis when its parent goes from `parentBefore` to\n * `parentAfter`, as Figma does: Right and Left & right move or grow it by the change in the\n * parent's size rounded to whole pixels, Center by the change in its rounded half, and Scale by\n * the exact ratio. The child's own box is never rounded, so a resize to the same size changes\n * nothing. Left & right that would leave no size keeps the axis as it was; past zero, the child\n * turns over and its box runs back from the edge it was pinned to, as the layer is mirrored in\n * Figma. `scaleStep` snaps a scaled position to that fraction of a pixel.\n */\nfunction constrainedAxis(\n position: number,\n size: number,\n parentBefore: number,\n parentAfter: number,\n constraint: ConstraintType,\n scaleStep = 0,\n allowFlips = true\n): AxisPlacement {\n const delta = Math.round(parentAfter) - Math.round(parentBefore)\n if (constraint === 'MAX') return { position: position + delta, size }\n if (constraint === 'CENTER') {\n return { position: position + Math.round(parentAfter / 2) - Math.round(parentBefore / 2), size }\n }\n if (constraint === 'STRETCH') {\n const stretched = size + delta\n if (!allowFlips) return { position, size: Math.abs(stretched) }\n if (stretched === 0) return { position, size }\n if (stretched > 0) return { position, size: stretched }\n return { position: position + stretched, size: -stretched, flipped: true }\n }\n if (constraint === 'SCALE' && parentBefore > 0) {\n const scale = parentAfter / parentBefore\n const scaled = position * scale\n return {\n position: scaleStep > 0 ? Math.round(scaled / scaleStep) * scaleStep : scaled,\n size: size * scale\n }\n }\n return { position, size }\n}\n\nconst FLEXIBLE_CONSTRAINTS: ReadonlySet<ConstraintType> = new Set(['STRETCH', 'SCALE'])\n\n/** The axis at `size`, keeping the edge or centre its constraint pins where it was placed. */\nfunction resizedInPlace(\n placed: AxisPlacement,\n size: number,\n constraint: ConstraintType\n): AxisPlacement {\n if (constraint === 'MAX') return { position: placed.position + placed.size - size, size }\n if (constraint === 'CENTER') return { position: placed.position + (placed.size - size) / 2, size }\n return { position: placed.position, size }\n}\n\n/** Keep a placed box's constrained edges or center when its content determines its size. */\nexport function resizedChildRect(\n placed: Rect,\n size: Pick<Rect, 'width' | 'height'>,\n horizontal: ConstraintType,\n vertical: ConstraintType\n): Rect {\n const x = resizedInPlace({ position: placed.x, size: placed.width }, size.width, horizontal)\n const y = resizedInPlace({ position: placed.y, size: placed.height }, size.height, vertical)\n return { x: x.position, y: y.position, width: x.size, height: y.size }\n}\n\n/**\n * A locked aspect ratio holds when exactly one axis follows the parent, as in Figma: that axis\n * sizes the other. With both axes following the parent, or neither, the ratio gives way.\n */\nfunction keepLockedRatio(\n x: AxisPlacement,\n y: AxisPlacement,\n horizontal: ConstraintType,\n vertical: ConstraintType,\n aspectRatio: number | null\n): { x: AxisPlacement; y: AxisPlacement } {\n const flexibleX = FLEXIBLE_CONSTRAINTS.has(horizontal)\n if (aspectRatio === null || flexibleX === FLEXIBLE_CONSTRAINTS.has(vertical)) return { x, y }\n return flexibleX\n ? { x, y: resizedInPlace(y, x.size / aspectRatio, vertical) }\n : { x: resizedInPlace(x, y.size * aspectRatio, horizontal), y }\n}\n\ntype ChildRectPlacer = (\n child: Rect,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>,\n horizontal: ConstraintType,\n vertical: ConstraintType,\n aspectRatio?: number | null\n) => ConstrainedRect\n\n/** Places a child by its constraints, snapping a scaled position to `scaleStep` when it is set. */\nfunction childRectPlacer(scaleStep: number, allowFlips = true): ChildRectPlacer {\n return (child, parentBefore, parentAfter, horizontal, vertical, aspectRatio = null) => {\n const { x, y } = keepLockedRatio(\n constrainedAxis(\n child.x,\n child.width,\n parentBefore.width,\n parentAfter.width,\n horizontal,\n scaleStep,\n allowFlips\n ),\n constrainedAxis(\n child.y,\n child.height,\n parentBefore.height,\n parentAfter.height,\n vertical,\n scaleStep,\n allowFlips\n ),\n horizontal,\n vertical,\n aspectRatio\n )\n const rect: ConstrainedRect = { x: x.position, y: y.position, width: x.size, height: y.size }\n if (x.flipped) rect.flipsX = true\n if (y.flipped) rect.flipsY = true\n return rect\n }\n}\n\n/**\n * A child's box after its parent is resized, by a handle or `resize()`, keeping a locked aspect\n * ratio as Figma does.\n */\nexport const constrainedChildRect = childRectPlacer(0)\n\n/**\n * Where a child goes when layout resizes its parent, as Figma places a layer that ignores auto\n * layout when its Hug frame grows (measured on desktop 126): as `constrainedChildRect`, except\n * that a scaled position lands on 1/128 of a pixel.\n */\nexport const layoutConstrainedChildRect = childRectPlacer(1 / 128, false)\n\nexport function scaledChildRect(\n child: Rect,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>\n): Rect {\n return constrainedChildRect(child, parentBefore, parentAfter, 'SCALE', 'SCALE')\n}\n\nexport function scaleVectorNetworkForResize(\n vectorNetwork: VectorNetwork | null,\n originalWidth: number,\n originalHeight: number,\n width: number,\n height: number\n): VectorNetwork | null {\n if (!vectorNetwork || (originalWidth <= 0 && originalHeight <= 0)) return null\n\n // A flat side, as a straight line's, has nothing to scale along it.\n const scaleX = originalWidth > 0 ? width / originalWidth : 1\n const scaleY = originalHeight > 0 ? height / originalHeight : 1\n if (scaleX === 1 && scaleY === 1) return null\n\n return {\n vertices: vectorNetwork.vertices.map((vertex) => ({\n ...vertex,\n x: vertex.x * scaleX,\n y: vertex.y * scaleY\n })),\n segments: vectorNetwork.segments.map((segment) => ({\n ...segment,\n tangentStart: {\n x: segment.tangentStart.x * scaleX,\n y: segment.tangentStart.y * scaleY\n },\n tangentEnd: {\n x: segment.tangentEnd.x * scaleX,\n y: segment.tangentEnd.y * scaleY\n }\n })),\n regions: vectorNetwork.regions\n }\n}\n\n/** Snapshot one node's resize-relevant state (rect + geometry that must scale with it). */\nexport function createResizeSnapshot(node: SceneNode): ResizeSnapshot {\n return {\n type: node.type,\n x: node.x,\n y: node.y,\n width: node.width,\n height: node.height,\n flipX: node.flipX,\n flipY: node.flipY,\n vectorNetwork: node.vectorNetwork ? cloneVectorNetwork(node.vectorNetwork) : null,\n fillGeometry: copyGeometryPaths(node.fillGeometry),\n strokeGeometry: copyGeometryPaths(node.strokeGeometry),\n derivedTextGlyphs: copyDerivedGlyphs(node.derivedTextGlyphs),\n strokes: copyStrokes(node.strokes),\n textPathData: node.textPathData ? structuredClone(node.textPathData) : null,\n textPathBox: node.textPathBox ? { ...node.textPathBox } : null\n }\n}\n\nfunction scaleDerivedGlyphs(\n glyphs: DerivedTextGlyph[] | null,\n sx: number,\n sy: number\n): DerivedTextGlyph[] | null {\n if (!glyphs?.length) return glyphs\n return glyphs.map((g) => ({\n ...g,\n x: g.x * sx,\n y: g.y * sy,\n scaleX: (g.scaleX ?? 1) * sx,\n scaleY: (g.scaleY ?? 1) * sy,\n commandsBlob: new Uint8Array(g.commandsBlob)\n }))\n}\n\nfunction hasPath(orig: Pick<ResizeSnapshot, 'vectorNetwork'>): boolean {\n return (orig.vectorNetwork?.segments.length ?? 0) > 0\n}\n\nfunction scaleStrokes(strokes: Stroke[], sx: number, sy: number): Stroke[] {\n if (strokes.length === 0) return strokes\n // Weight is a scalar; average scale is the usual 2D → 1D compromise.\n const weightScale = (Math.abs(sx) + Math.abs(sy)) / 2\n return strokes.map((s) => ({ ...copyStroke(s), weight: s.weight * weightScale }))\n}\n\n/**\n * All geometry that must track a width/height change. Historically only\n * vectorNetwork + fillGeometry were updated — path-text strokeGeometry and\n * glyphs stayed at the pre-resize size, so shrinking a sticker made the white\n * OUTSIDE outlines look massively thick (DomeSticker resize bug).\n */\nexport function scaledGeometryChanges(\n orig: Pick<\n ResizeSnapshot,\n | 'type'\n | 'vectorNetwork'\n | 'fillGeometry'\n | 'strokeGeometry'\n | 'derivedTextGlyphs'\n | 'strokes'\n | 'textPathData'\n | 'textPathBox'\n >,\n origWidth: number,\n origHeight: number,\n width: number,\n height: number\n): Partial<SceneNode> {\n if (origWidth <= 0 || origHeight <= 0) return {}\n const sx = width / origWidth\n const sy = height / origHeight\n if (sx === 1 && sy === 1) return {}\n\n const changes: Partial<SceneNode> = {}\n const resizedVN = scaleVectorNetworkForResize(\n orig.vectorNetwork,\n origWidth,\n origHeight,\n width,\n height\n )\n if (resizedVN) changes.vectorNetwork = resizedVN\n\n if (orig.fillGeometry.length > 0) {\n changes.fillGeometry = scaleGeometryPaths(orig.fillGeometry, sx, sy)\n }\n // A stroke keeps its weight through a resize, as in Figma, so a saved stroke outline goes where\n // the stroke can be drawn again at its weight: from a path, or from a shape's own outline.\n // Text and a vector with only its outline keep scaling the outline, which is all they have.\n const outlineOnly = orig.type === 'TEXT' || (orig.type === 'VECTOR' && !hasPath(orig))\n if (orig.strokeGeometry.length > 0) {\n changes.strokeGeometry = outlineOnly ? scaleGeometryPaths(orig.strokeGeometry, sx, sy) : []\n }\n Object.assign(changes, scaledPathTextChanges(orig, sx, sy))\n // Glyphs scaled as a picture take their strokes along; any other stroke keeps its weight, as\n // Figma reports it, even where only a scaled outline can draw it.\n if (orig.strokes.length > 0 && followsPath(orig)) {\n changes.strokes = scaleStrokes(orig.strokes, sx, sy)\n }\n return changes\n}\n\n/**\n * The saved outlines a size change invalidates on a layer drawn from its live box: its fill\n * outline follows the box, and its saved stroke outline goes, so the stroke is drawn again at its\n * weight through the live shape. A vector and text draw from outlines of their own, which scaling\n * keeps. Without this, a layer that came from a `.fig` with frame outlines keeps drawing the old\n * box after layout, the Plugin API or an instance sync resizes it.\n */\nexport function shapeGeometryChanges(\n node: SceneNode,\n width: number,\n height: number\n): Pick<Partial<SceneNode>, 'fillGeometry' | 'strokeGeometry'> {\n if (node.type === 'VECTOR' || node.type === 'TEXT') return {}\n if (node.fillGeometry.length === 0 && node.strokeGeometry.length === 0) return {}\n // A box with no extent has no outline to scale from; the live shape draws both again.\n if (node.width <= 0 || node.height <= 0) return { fillGeometry: [], strokeGeometry: [] }\n const changes = scaledGeometryChanges(\n createResizeSnapshot(node),\n node.width,\n node.height,\n width,\n height\n )\n const geometry: Pick<Partial<SceneNode>, 'fillGeometry' | 'strokeGeometry'> = {}\n if (changes.fillGeometry) geometry.fillGeometry = changes.fillGeometry\n if (changes.strokeGeometry) geometry.strokeGeometry = changes.strokeGeometry\n return geometry\n}\n\ntype PathTextFields = Pick<SceneNode, 'derivedTextGlyphs' | 'textPathData' | 'textPathBox'>\n\n/** The baked glyphs and layout box of path text, scaled with the layer; nothing for other text. */\nexport function scaledPathTextChanges(\n orig: PathTextFields,\n sx: number,\n sy: number\n): Pick<Partial<SceneNode>, 'derivedTextGlyphs' | 'textPathBox'> {\n if (!followsPath(orig)) return {}\n const changes: Pick<Partial<SceneNode>, 'derivedTextGlyphs' | 'textPathBox'> = {\n derivedTextGlyphs: scaleDerivedGlyphs(orig.derivedTextGlyphs, sx, sy)\n }\n // Keep the layout/selection box in sync with the scaled glyphs. reflow\n // overrides this when it applies; this covers the fallback where reflow\n // returns null (no path data) so the box doesn't carry a stale size.\n if (orig.textPathBox) {\n changes.textPathBox = {\n x: orig.textPathBox.x * sx,\n y: orig.textPathBox.y * sy,\n width: orig.textPathBox.width * sx,\n height: orig.textPathBox.height * sy\n }\n }\n return changes\n}\n\nexport function collectResizeDescendants(\n graph: ResizeGraph,\n rootId: string\n): Map<string, ResizeSnapshot> | null {\n const root = graph.getNode(rootId)\n if (!root || !CONSTRAINT_CONTAINER_TYPES.has(root.type)) return null\n const snapshots = new Map<string, ResizeSnapshot>()\n\n const collect = (parentId: string) => {\n const parent = graph.getNode(parentId)\n if (!parent) return\n for (const childId of parent.childIds) {\n const child = graph.getNode(childId)\n if (!child) continue\n snapshots.set(childId, createResizeSnapshot(child))\n collect(childId)\n }\n }\n\n collect(rootId)\n return snapshots.size > 0 ? snapshots : null\n}\n\n/**\n * The flips a child takes when its constraints place it from `from`, written only where they\n * differ from the ones it has now, so a drag that crosses back undoes its own turn.\n */\nexport function flipChanges(\n from: Pick<SceneNode, 'flipX' | 'flipY'>,\n current: Pick<SceneNode, 'flipX' | 'flipY'>,\n flipsX = false,\n flipsY = false\n): Partial<Pick<SceneNode, 'flipX' | 'flipY'>> {\n const changes: Partial<Pick<SceneNode, 'flipX' | 'flipY'>> = {}\n const flipX = from.flipX !== flipsX\n const flipY = from.flipY !== flipsY\n if (flipX !== current.flipX) changes.flipX = flipX\n if (flipY !== current.flipY) changes.flipY = flipY\n return changes\n}\n\nexport function computeConstrainedResizeChanges(\n graph: ResizeGraph,\n rootId: string,\n rootBefore: Pick<Rect, 'width' | 'height'>,\n rootAfter: Pick<Rect, 'width' | 'height'>,\n originals: ReadonlyMap<string, ResizeSnapshot>\n): Map<string, Partial<SceneNode>> {\n const changes = new Map<string, Partial<SceneNode>>()\n\n const compute = (\n parentId: string,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>\n ) => {\n const parent = graph.getNode(parentId)\n if (!parent) return\n const scalesChildren = parent.type === 'GROUP' || parent.type === 'BOOLEAN_OPERATION'\n for (const childId of parent.childIds) {\n const original = originals.get(childId)\n const child = graph.getNode(childId)\n if (!original || !child) continue\n const isInFlow = parent.layoutMode !== 'NONE' && child.layoutPositioning !== 'ABSOLUTE'\n if (isInFlow) {\n compute(childId, original, child)\n continue\n }\n const rect: ConstrainedRect = scalesChildren\n ? scaledChildRect(original, parentBefore, parentAfter)\n : constrainedChildRect(\n original,\n parentBefore,\n parentAfter,\n child.horizontalConstraint,\n child.verticalConstraint,\n enforcedAspectRatio(child)\n )\n const { flipsX, flipsY, ...box } = rect\n const childChanges: Partial<SceneNode> = {\n ...box,\n ...flipChanges(original, child, flipsX, flipsY),\n ...scaledGeometryChanges(original, original.width, original.height, box.width, box.height)\n }\n changes.set(childId, childChanges)\n // The final pass sees layout containers after Yoga has resolved HUG/FILL sizing.\n compute(childId, original, child.layoutMode === 'NONE' ? box : child)\n }\n }\n\n compute(rootId, rootBefore, rootAfter)\n return changes\n}\n"],"mappings":";;;;;AAyCA,MAAM,6CAA6B,IAAI,IAAI;CACzC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;AAgBD,SAAS,gBACP,UACA,MACA,cACA,aACA,YACA,YAAY,GACZ,aAAa,MACE;CACf,MAAM,QAAQ,KAAK,MAAM,WAAW,IAAI,KAAK,MAAM,YAAY;CAC/D,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src/scaling/node.ts"],"mappings":";;iBAyIgB,iBACd,MAAM,WACN,eACA,yBACC,QAAQ"}
|
package/dist/scaling/node.js
CHANGED
|
@@ -1,9 +1,28 @@
|
|
|
1
1
|
import { scaledTextLength } from "../text/lengths.js";
|
|
2
2
|
import { cloneVectorNetwork } from "../vector-network.js";
|
|
3
|
-
import { scaleGeometryPaths } from "../copy.js";
|
|
4
|
-
import {
|
|
3
|
+
import { copyDerivedGlyphs, scaleGeometryPaths } from "../copy.js";
|
|
4
|
+
import { followsPath } from "../text/path.js";
|
|
5
5
|
import { TEXT_PARAGRAPH_SPACING_FIELDS } from "../text/paragraphs.js";
|
|
6
6
|
//#region src/scaling/node.ts
|
|
7
|
+
function scaledPathText(node, scale) {
|
|
8
|
+
if (!node.textPathData && !followsPath(node)) return {};
|
|
9
|
+
const box = node.textPathBox;
|
|
10
|
+
return {
|
|
11
|
+
derivedTextGlyphs: copyDerivedGlyphs(node.derivedTextGlyphs)?.map((glyph) => ({
|
|
12
|
+
...glyph,
|
|
13
|
+
x: glyph.x * scale,
|
|
14
|
+
y: glyph.y * scale,
|
|
15
|
+
fontSize: glyph.fontSize * scale,
|
|
16
|
+
...glyph.advance === void 0 ? {} : { advance: glyph.advance * scale }
|
|
17
|
+
})) ?? null,
|
|
18
|
+
textPathBox: box && {
|
|
19
|
+
x: box.x * scale,
|
|
20
|
+
y: box.y * scale,
|
|
21
|
+
width: box.width * scale,
|
|
22
|
+
height: box.height * scale
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
7
26
|
function scaledOptional(value, scale) {
|
|
8
27
|
return value == null ? null : value * scale;
|
|
9
28
|
}
|
|
@@ -119,6 +138,7 @@ function scaleNodeChanges(node, scale, scalePosition) {
|
|
|
119
138
|
paragraphSpacing: node.paragraphSpacing * scale,
|
|
120
139
|
paragraphIndent: node.paragraphIndent * scale,
|
|
121
140
|
textParagraphs: scaledParagraphStyles(node.textParagraphs, scale),
|
|
141
|
+
derivedTextHeight: scaledOptional(node.derivedTextHeight, scale),
|
|
122
142
|
itemSpacing: node.itemSpacing * scale,
|
|
123
143
|
counterAxisSpacing: node.counterAxisSpacing * scale,
|
|
124
144
|
paddingTop: node.paddingTop * scale,
|
|
@@ -143,7 +163,7 @@ function scaleNodeChanges(node, scale, scalePosition) {
|
|
|
143
163
|
vectorNetwork: scaledVectorNetwork(node, scale),
|
|
144
164
|
fillGeometry: scaleGeometryPaths(node.fillGeometry, scale, scale),
|
|
145
165
|
strokeGeometry: scaleGeometryPaths(node.strokeGeometry, scale, scale),
|
|
146
|
-
...
|
|
166
|
+
...scaledPathText(node, scale)
|
|
147
167
|
};
|
|
148
168
|
}
|
|
149
169
|
//#endregion
|