@pairdraw/scene-graph 0.16.2 → 0.18.0
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/checkpoint.d.ts.map +1 -1
- package/dist/checkpoint.js +8 -3
- package/dist/checkpoint.js.map +1 -1
- package/dist/color/index.d.ts.map +1 -1
- package/dist/color/index.js +3 -3
- package/dist/color/index.js.map +1 -1
- package/dist/color/management.d.ts.map +1 -1
- package/dist/color/management.js +4 -2
- package/dist/color/management.js.map +1 -1
- package/dist/coordinate.d.ts.map +1 -1
- package/dist/coordinate.js +3 -1
- package/dist/coordinate.js.map +1 -1
- package/dist/copy.d.ts.map +1 -1
- package/dist/copy.js +7 -3
- package/dist/copy.js.map +1 -1
- package/dist/css/values.d.ts.map +1 -1
- package/dist/css/values.js +2 -2
- package/dist/css/values.js.map +1 -1
- package/dist/effects.d.ts +16 -0
- package/dist/effects.d.ts.map +1 -0
- package/dist/effects.js +78 -0
- package/dist/effects.js.map +1 -0
- package/dist/geometry.d.ts +14 -7
- package/dist/geometry.d.ts.map +1 -1
- package/dist/geometry.js +130 -26
- package/dist/geometry.js.map +1 -1
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +12 -3
- package/dist/graph.js.map +1 -1
- package/dist/hit-test.d.ts.map +1 -1
- package/dist/hit-test.js +100 -8
- package/dist/hit-test.js.map +1 -1
- package/dist/instances/content-size.js +1 -1
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +4 -1
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/sync.js +4 -3
- package/dist/instances/sync.js.map +1 -1
- package/dist/layout/index.js +1 -1
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +4 -1
- package/dist/node-defaults.js.map +1 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +5 -0
- package/dist/preview.js.map +1 -1
- package/dist/resize.d.ts +4 -1
- package/dist/resize.d.ts.map +1 -1
- package/dist/resize.js +18 -12
- package/dist/resize.js.map +1 -1
- package/dist/scaling/node.d.ts.map +1 -1
- package/dist/scaling/node.js +3 -1
- package/dist/scaling/node.js.map +1 -1
- package/dist/scaling/tree.d.ts.map +1 -1
- package/dist/scaling/tree.js +8 -5
- package/dist/scaling/tree.js.map +1 -1
- package/dist/slots/authoring.js +3 -6
- package/dist/slots/authoring.js.map +1 -1
- package/dist/slots/content.d.ts.map +1 -1
- package/dist/slots/content.js +15 -25
- package/dist/slots/content.js.map +1 -1
- package/dist/slots/frames.js +1 -2
- package/dist/slots/frames.js.map +1 -1
- package/dist/snap.d.ts.map +1 -1
- package/dist/snap.js +12 -4
- package/dist/snap.js.map +1 -1
- package/dist/types.d.ts +5 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/undo.d.ts +2 -1
- package/dist/undo.d.ts.map +1 -1
- package/dist/undo.js +3 -2
- package/dist/undo.js.map +1 -1
- package/dist/variables/bindings.d.ts +2 -1
- package/dist/variables/bindings.d.ts.map +1 -1
- package/dist/variables/bindings.js +6 -2
- package/dist/variables/bindings.js.map +1 -1
- package/dist/variables/index.d.ts +2 -1
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js +37 -7
- package/dist/variables/index.js.map +1 -1
- package/dist/variables/units.d.ts +31 -0
- package/dist/variables/units.d.ts.map +1 -0
- package/dist/variables/units.js +79 -4
- package/dist/variables/units.js.map +1 -1
- package/package.json +6 -1
- package/src/checkpoint.ts +8 -2
- package/src/color/index.ts +4 -6
- package/src/color/management.ts +8 -2
- package/src/coordinate.ts +4 -1
- package/src/copy.ts +8 -3
- package/src/css/values.ts +3 -2
- package/src/effects.ts +76 -0
- package/src/geometry.ts +147 -24
- package/src/graph.ts +13 -3
- package/src/hit-test.ts +138 -16
- package/src/instances/index.ts +5 -1
- package/src/instances/sync.ts +5 -3
- package/src/node-defaults.ts +4 -1
- package/src/preview.ts +4 -0
- package/src/resize.ts +40 -20
- package/src/scaling/node.ts +3 -1
- package/src/scaling/tree.ts +3 -2
- package/src/slots/authoring.ts +7 -7
- package/src/slots/content.ts +13 -19
- package/src/slots/frames.ts +3 -3
- package/src/snap.ts +14 -4
- package/src/types.ts +5 -0
- package/src/undo.ts +3 -2
- package/src/variables/bindings.ts +6 -2
- package/src/variables/index.ts +49 -8
- package/src/variables/units.ts +97 -4
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 | '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\nfunction constrainedAxis(\n position: number,\n size: number,\n parentBefore: number,\n parentAfter: number,\n constraint: ConstraintType\n): { position: number; size: number } {\n const delta = parentAfter - parentBefore\n if (constraint === 'MAX') return { position: position + delta, size }\n if (constraint === 'CENTER') return { position: position + delta / 2, size }\n if (constraint === 'STRETCH') return { position, size: Math.max(1, size + delta) }\n if (constraint === 'SCALE' && parentBefore > 0) {\n const scale = parentAfter / parentBefore\n return { position: position * scale, size: Math.max(1, size * scale) }\n }\n return { position, size }\n}\n\ntype AxisPlacement = { position: number; size: number }\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\n/** A child's box after its parent resizes, keeping a locked aspect ratio as Figma does. */\nexport function constrainedChildRect(\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 = null\n): Rect {\n let x = constrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal)\n let y = constrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical)\n ;({ x, y } = keepLockedRatio(x, y, horizontal, vertical, aspectRatio))\n return {\n x: Math.round(x.position),\n y: Math.round(y.position),\n width: Math.round(x.size),\n height: Math.round(y.size)\n }\n}\n\nfunction layoutConstrainedAxis(\n position: number,\n size: number,\n parentBefore: number,\n parentAfter: number,\n constraint: ConstraintType\n): { position: number; size: number } {\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') return { position, size: Math.abs(size + delta) }\n if (constraint === 'SCALE' && parentBefore > 0) {\n const scale = parentAfter / parentBefore\n return { position: Math.round(position * scale * 128) / 128, size: size * scale }\n }\n return { position, size }\n}\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): Right and Left & right move or grow\n * it by the change in the parent's size rounded to whole pixels, Center by the change in its\n * rounded half, and Scale by the exact ratio, its position to 1/128 of a pixel. Sizes are not\n * rounded, so applying a run of changes one at a time lands where applying them at once does.\n */\nexport function layoutConstrainedChildRect(\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 = null\n): Rect {\n const placed = keepLockedRatio(\n layoutConstrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal),\n layoutConstrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical),\n horizontal,\n vertical,\n aspectRatio\n )\n return {\n x: placed.x.position,\n y: placed.y.position,\n width: placed.x.size,\n height: placed.y.size\n }\n}\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 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 // 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.\n const glyphs = orig.derivedTextGlyphs ?? []\n const pathText =\n !!orig.textPathData || !!orig.textPathBox || glyphs.some((glyph) => (glyph.rotation ?? 0) !== 0)\n if (glyphs.length > 0 && pathText) {\n changes.derivedTextGlyphs = scaleDerivedGlyphs(glyphs, sx, sy)\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 }\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 && glyphs.length > 0 && pathText) {\n changes.strokes = scaleStrokes(orig.strokes, sx, sy)\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\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 = 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 childChanges: Partial<SceneNode> = {\n ...rect,\n ...scaledGeometryChanges(original, original.width, original.height, rect.width, rect.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' ? rect : child)\n }\n }\n\n compute(rootId, rootBefore, rootAfter)\n return changes\n}\n"],"mappings":";;;;AAsCA,MAAM,6CAA6B,IAAI,IAAI;CACzC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,gBACP,UACA,MACA,cACA,aACA,YACoC;CACpC,MAAM,QAAQ,cAAc;CAC5B,IAAI,eAAe,OAAO,OAAO;EAAE,UAAU,WAAW;EAAO;CAAK;CACpE,IAAI,eAAe,UAAU,OAAO;EAAE,UAAU,WAAW,QAAQ;EAAG;CAAK;CAC3E,IAAI,eAAe,WAAW,OAAO;EAAE;EAAU,MAAM,KAAK,IAAI,GAAG,OAAO,KAAK;CAAE;CACjF,IAAI,eAAe,WAAW,eAAe,GAAG;EAC9C,MAAM,QAAQ,cAAc;EAC5B,OAAO;GAAE,UAAU,WAAW;GAAO,MAAM,KAAK,IAAI,GA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AQ,SAAS,UAAU,KAAK;IAChC;GACF;GACA,MAAM,OAAO,iBACT,gBAAgB,UAAU,cAAc,WAAW,IACnD,qBACE,UACA,cACA,aACA,MAAM,sBACN,MAAM,oBACN,oBAAoB,KAAK,CAC3B;GACJ,MAAM,eAAmC;IACvC,GAAG;IACH,GAAG,sBAAsB,UAAU,SAAS,OAAO,SAAS,QAAQ,KAAK,OAAO,KAAK,MAAM;GAC7F;GACA,QAAQ,IAAI,SAAS,YAAY;GAEjC,QAAQ,SAAS,UAAU,MAAM,eAAe,SAAS,OAAO,KAAK;EACvE;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 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 | '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\nfunction constrainedAxis(\n position: number,\n size: number,\n parentBefore: number,\n parentAfter: number,\n constraint: ConstraintType\n): { position: number; size: number } {\n const delta = parentAfter - parentBefore\n if (constraint === 'MAX') return { position: position + delta, size }\n if (constraint === 'CENTER') return { position: position + delta / 2, size }\n if (constraint === 'STRETCH') return { position, size: Math.max(1, size + delta) }\n if (constraint === 'SCALE' && parentBefore > 0) {\n const scale = parentAfter / parentBefore\n return { position: position * scale, size: Math.max(1, size * scale) }\n }\n return { position, size }\n}\n\ntype AxisPlacement = { position: number; size: number }\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\n/** A child's box after its parent resizes, keeping a locked aspect ratio as Figma does. */\nexport function constrainedChildRect(\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 = null\n): Rect {\n let x = constrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal)\n let y = constrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical)\n ;({ x, y } = keepLockedRatio(x, y, horizontal, vertical, aspectRatio))\n return {\n x: Math.round(x.position),\n y: Math.round(y.position),\n width: Math.round(x.size),\n height: Math.round(y.size)\n }\n}\n\nfunction layoutConstrainedAxis(\n position: number,\n size: number,\n parentBefore: number,\n parentAfter: number,\n constraint: ConstraintType\n): { position: number; size: number } {\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') return { position, size: Math.abs(size + delta) }\n if (constraint === 'SCALE' && parentBefore > 0) {\n const scale = parentAfter / parentBefore\n return { position: Math.round(position * scale * 128) / 128, size: size * scale }\n }\n return { position, size }\n}\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): Right and Left & right move or grow\n * it by the change in the parent's size rounded to whole pixels, Center by the change in its\n * rounded half, and Scale by the exact ratio, its position to 1/128 of a pixel. Sizes are not\n * rounded, so applying a run of changes one at a time lands where applying them at once does.\n */\nexport function layoutConstrainedChildRect(\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 = null\n): Rect {\n const placed = keepLockedRatio(\n layoutConstrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal),\n layoutConstrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical),\n horizontal,\n vertical,\n aspectRatio\n )\n return {\n x: placed.x.position,\n y: placed.y.position,\n width: placed.x.size,\n height: placed.y.size\n }\n}\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 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\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\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 = 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 childChanges: Partial<SceneNode> = {\n ...rect,\n ...scaledGeometryChanges(original, original.width, original.height, rect.width, rect.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' ? rect : child)\n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|
+
{"version":3,"file":"node.d.ts","names":[],"sources":["../../src/scaling/node.ts"],"mappings":";;iBAkHgB,iBACd,MAAM,WACN,eACA,yBACC,QAAQ"}
|
package/dist/scaling/node.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { scaledTextLength } from "../text/lengths.js";
|
|
2
2
|
import { cloneVectorNetwork } from "../vector-network.js";
|
|
3
3
|
import { scaleGeometryPaths } from "../copy.js";
|
|
4
|
+
import { scaledPathTextChanges } from "../resize.js";
|
|
4
5
|
import { TEXT_PARAGRAPH_SPACING_FIELDS } from "../text/paragraphs.js";
|
|
5
6
|
//#region src/scaling/node.ts
|
|
6
7
|
function scaledOptional(value, scale) {
|
|
@@ -141,7 +142,8 @@ function scaleNodeChanges(node, scale, scalePosition) {
|
|
|
141
142
|
layoutGrids: scaledLayoutGrids(node.layoutGrids, scale),
|
|
142
143
|
vectorNetwork: scaledVectorNetwork(node, scale),
|
|
143
144
|
fillGeometry: scaleGeometryPaths(node.fillGeometry, scale, scale),
|
|
144
|
-
strokeGeometry: scaleGeometryPaths(node.strokeGeometry, scale, scale)
|
|
145
|
+
strokeGeometry: scaleGeometryPaths(node.strokeGeometry, scale, scale),
|
|
146
|
+
...scaledPathTextChanges(node, scale, scale)
|
|
145
147
|
};
|
|
146
148
|
}
|
|
147
149
|
//#endregion
|
package/dist/scaling/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.js","names":[],"sources":["../../src/scaling/node.ts"],"sourcesContent":["import { scaleGeometryPaths } from '../copy'\nimport { scaledTextLength } from '../text/lengths'\nimport { TEXT_PARAGRAPH_SPACING_FIELDS } from '../text/paragraphs'\nimport {\n type Effect,\n type Fill,\n type GridTrack,\n type LayoutGrid,\n type SceneNode,\n type Stroke,\n type StyleRun,\n type TextParagraphStyle\n} from '../types'\nimport { cloneVectorNetwork } from '../vector-network'\n\nfunction scaledOptional(value: number | null, scale: number): number | null {\n return value == null ? null : value * scale\n}\n\nfunction scaledStrokes(strokes: readonly Stroke[], scale: number): Stroke[] {\n return strokes.map((stroke) => ({\n ...structuredClone(stroke),\n weight: stroke.weight * scale,\n dashPattern: stroke.dashPattern?.map((value) => value * scale)\n }))\n}\n\nfunction scaledEffects(effects: readonly Effect[], scale: number): Effect[] {\n return effects.map((effect) => {\n const copy = structuredClone(effect)\n // A shader effect has no geometry of its own; only a shadow's measures follow the layer.\n if (copy.type === 'SHADER') return copy\n copy.offset = { x: copy.offset.x * scale, y: copy.offset.y * scale }\n copy.radius *= scale\n copy.spread *= scale\n return copy\n })\n}\n\nfunction scaledFills(fills: readonly Fill[], scale: number): Fill[] {\n return fills.map((fill) => ({\n ...structuredClone(fill),\n scale: fill.scale == null ? undefined : fill.scale * scale,\n spacing: fill.spacing == null ? undefined : fill.spacing * scale,\n patternSpacing: fill.patternSpacing\n ? { x: fill.patternSpacing.x * scale, y: fill.patternSpacing.y * scale }\n : undefined,\n noiseSize: fill.noiseSize\n ? { x: fill.noiseSize.x * scale, y: fill.noiseSize.y * scale }\n : undefined\n }))\n}\n\nfunction scaledStyleRuns(styleRuns: readonly StyleRun[], scale: number): StyleRun[] {\n return styleRuns.map((run) => ({\n ...structuredClone(run),\n style: {\n ...structuredClone(run.style),\n fontSize: run.style.fontSize == null ? undefined : run.style.fontSize * scale,\n letterSpacing: run.style.letterSpacing && scaledTextLength(run.style.letterSpacing, scale),\n lineHeight: run.style.lineHeight && scaledTextLength(run.style.lineHeight, scale),\n textDecorationThickness: scaledOptional(run.style.textDecorationThickness ?? null, scale),\n textUnderlineOffset: scaledOptional(run.style.textUnderlineOffset ?? null, scale)\n }\n }))\n}\n\nfunction scaledParagraphStyles(\n paragraphs: readonly TextParagraphStyle[],\n scale: number\n): TextParagraphStyle[] {\n return paragraphs.map((style) => {\n const scaled = { ...style }\n for (const field of TEXT_PARAGRAPH_SPACING_FIELDS) {\n const value = style[field]\n if (value !== undefined) scaled[field] = value * scale\n }\n return scaled\n })\n}\n\nfunction scaledLayoutGrids(grids: readonly LayoutGrid[], scale: number): LayoutGrid[] {\n return grids.map((grid) => ({\n ...structuredClone(grid),\n offset: grid.offset == null ? undefined : grid.offset * scale,\n sectionSize: grid.sectionSize == null ? undefined : grid.sectionSize * scale,\n gutterSize: grid.gutterSize == null ? undefined : grid.gutterSize * scale\n }))\n}\n\nfunction scaledGridTracks(tracks: readonly GridTrack[], scale: number): GridTrack[] {\n return tracks.map((track) => ({\n ...track,\n value: track.sizing === 'FIXED' ? track.value * scale : track.value\n }))\n}\n\nfunction scaledVectorNetwork(node: SceneNode, scale: number): SceneNode['vectorNetwork'] {\n if (!node.vectorNetwork) return null\n const network = cloneVectorNetwork(node.vectorNetwork)\n for (const vertex of network.vertices) {\n vertex.x *= scale\n vertex.y *= scale\n }\n for (const segment of network.segments) {\n segment.tangentStart.x *= scale\n segment.tangentStart.y *= scale\n segment.tangentEnd.x *= scale\n segment.tangentEnd.y *= scale\n }\n return network\n}\n\nexport function scaleNodeChanges(\n node: SceneNode,\n scale: number,\n scalePosition: boolean\n): Partial<SceneNode> {\n return {\n x: scalePosition ? node.x * scale : node.x,\n y: scalePosition ? node.y * scale : node.y,\n width: node.width * scale,\n height: node.height * scale,\n minWidth: scaledOptional(node.minWidth, scale),\n maxWidth: scaledOptional(node.maxWidth, scale),\n minHeight: scaledOptional(node.minHeight, scale),\n maxHeight: scaledOptional(node.maxHeight, scale),\n cornerRadius: node.cornerRadius * scale,\n topLeftRadius: node.topLeftRadius * scale,\n topRightRadius: node.topRightRadius * scale,\n bottomRightRadius: node.bottomRightRadius * scale,\n bottomLeftRadius: node.bottomLeftRadius * scale,\n fontSize: node.fontSize * scale,\n letterSpacing: scaledTextLength(node.letterSpacing, scale),\n lineHeight: node.lineHeight && scaledTextLength(node.lineHeight, scale),\n textDecorationThickness: scaledOptional(node.textDecorationThickness, scale),\n textUnderlineOffset: scaledOptional(node.textUnderlineOffset, scale),\n styleRuns: scaledStyleRuns(node.styleRuns, scale),\n listSpacing: node.listSpacing * scale,\n paragraphSpacing: node.paragraphSpacing * scale,\n paragraphIndent: node.paragraphIndent * scale,\n textParagraphs: scaledParagraphStyles(node.textParagraphs, scale),\n itemSpacing: node.itemSpacing * scale,\n counterAxisSpacing: node.counterAxisSpacing * scale,\n paddingTop: node.paddingTop * scale,\n paddingRight: node.paddingRight * scale,\n paddingBottom: node.paddingBottom * scale,\n paddingLeft: node.paddingLeft * scale,\n gridColumnGap: node.gridColumnGap * scale,\n gridRowGap: node.gridRowGap * scale,\n gridTemplateColumns: scaledGridTracks(node.gridTemplateColumns, scale),\n gridTemplateRows: scaledGridTracks(node.gridTemplateRows, scale),\n strokes: scaledStrokes(node.strokes, scale),\n strokeWeight: node.strokeWeight * scale,\n dashPattern: node.dashPattern.map((value) => value * scale),\n borderTopWeight: node.borderTopWeight * scale,\n borderRightWeight: node.borderRightWeight * scale,\n borderBottomWeight: node.borderBottomWeight * scale,\n borderLeftWeight: node.borderLeftWeight * scale,\n strokeMiterLimit: node.strokeMiterLimit,\n effects: scaledEffects(node.effects, scale),\n fills: scaledFills(node.fills, scale),\n layoutGrids: scaledLayoutGrids(node.layoutGrids, scale),\n vectorNetwork: scaledVectorNetwork(node, scale),\n fillGeometry: scaleGeometryPaths(node.fillGeometry, scale, scale),\n strokeGeometry: scaleGeometryPaths(node.strokeGeometry, scale, scale)\n }\n}\n"],"mappings":";;;;;AAeA,SAAS,eAAe,OAAsB,OAA8B;CAC1E,OAAO,SAAS,OAAO,OAAO,QAAQ;AACxC;AAEA,SAAS,cAAc,SAA4B,OAAyB;CAC1E,OAAO,QAAQ,KAAK,YAAY;EAC9B,GAAG,gBAAgB,MAAM;EACzB,QAAQ,OAAO,SAAS;EACxB,aAAa,OAAO,aAAa,KAAK,UAAU,QAAQ,KAAK;CAC/D,EAAE;AACJ;AAEA,SAAS,cAAc,SAA4B,OAAyB;CAC1E,OAAO,QAAQ,KAAK,WAAW;EAC7B,MAAM,OAAO,gBAAgB,MAAM;EAEnC,IAAI,KAAK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F"}
|
|
1
|
+
{"version":3,"file":"node.js","names":[],"sources":["../../src/scaling/node.ts"],"sourcesContent":["import { scaleGeometryPaths } from '../copy'\nimport { scaledPathTextChanges } from '../resize'\nimport { scaledTextLength } from '../text/lengths'\nimport { TEXT_PARAGRAPH_SPACING_FIELDS } from '../text/paragraphs'\nimport {\n type Effect,\n type Fill,\n type GridTrack,\n type LayoutGrid,\n type SceneNode,\n type Stroke,\n type StyleRun,\n type TextParagraphStyle\n} from '../types'\nimport { cloneVectorNetwork } from '../vector-network'\n\nfunction scaledOptional(value: number | null, scale: number): number | null {\n return value == null ? null : value * scale\n}\n\nfunction scaledStrokes(strokes: readonly Stroke[], scale: number): Stroke[] {\n return strokes.map((stroke) => ({\n ...structuredClone(stroke),\n weight: stroke.weight * scale,\n dashPattern: stroke.dashPattern?.map((value) => value * scale)\n }))\n}\n\nfunction scaledEffects(effects: readonly Effect[], scale: number): Effect[] {\n return effects.map((effect) => {\n const copy = structuredClone(effect)\n // A shader effect has no geometry of its own; only a shadow's measures follow the layer.\n if (copy.type === 'SHADER') return copy\n copy.offset = { x: copy.offset.x * scale, y: copy.offset.y * scale }\n copy.radius *= scale\n copy.spread *= scale\n return copy\n })\n}\n\nfunction scaledFills(fills: readonly Fill[], scale: number): Fill[] {\n return fills.map((fill) => ({\n ...structuredClone(fill),\n scale: fill.scale == null ? undefined : fill.scale * scale,\n spacing: fill.spacing == null ? undefined : fill.spacing * scale,\n patternSpacing: fill.patternSpacing\n ? { x: fill.patternSpacing.x * scale, y: fill.patternSpacing.y * scale }\n : undefined,\n noiseSize: fill.noiseSize\n ? { x: fill.noiseSize.x * scale, y: fill.noiseSize.y * scale }\n : undefined\n }))\n}\n\nfunction scaledStyleRuns(styleRuns: readonly StyleRun[], scale: number): StyleRun[] {\n return styleRuns.map((run) => ({\n ...structuredClone(run),\n style: {\n ...structuredClone(run.style),\n fontSize: run.style.fontSize == null ? undefined : run.style.fontSize * scale,\n letterSpacing: run.style.letterSpacing && scaledTextLength(run.style.letterSpacing, scale),\n lineHeight: run.style.lineHeight && scaledTextLength(run.style.lineHeight, scale),\n textDecorationThickness: scaledOptional(run.style.textDecorationThickness ?? null, scale),\n textUnderlineOffset: scaledOptional(run.style.textUnderlineOffset ?? null, scale)\n }\n }))\n}\n\nfunction scaledParagraphStyles(\n paragraphs: readonly TextParagraphStyle[],\n scale: number\n): TextParagraphStyle[] {\n return paragraphs.map((style) => {\n const scaled = { ...style }\n for (const field of TEXT_PARAGRAPH_SPACING_FIELDS) {\n const value = style[field]\n if (value !== undefined) scaled[field] = value * scale\n }\n return scaled\n })\n}\n\nfunction scaledLayoutGrids(grids: readonly LayoutGrid[], scale: number): LayoutGrid[] {\n return grids.map((grid) => ({\n ...structuredClone(grid),\n offset: grid.offset == null ? undefined : grid.offset * scale,\n sectionSize: grid.sectionSize == null ? undefined : grid.sectionSize * scale,\n gutterSize: grid.gutterSize == null ? undefined : grid.gutterSize * scale\n }))\n}\n\nfunction scaledGridTracks(tracks: readonly GridTrack[], scale: number): GridTrack[] {\n return tracks.map((track) => ({\n ...track,\n value: track.sizing === 'FIXED' ? track.value * scale : track.value\n }))\n}\n\nfunction scaledVectorNetwork(node: SceneNode, scale: number): SceneNode['vectorNetwork'] {\n if (!node.vectorNetwork) return null\n const network = cloneVectorNetwork(node.vectorNetwork)\n for (const vertex of network.vertices) {\n vertex.x *= scale\n vertex.y *= scale\n }\n for (const segment of network.segments) {\n segment.tangentStart.x *= scale\n segment.tangentStart.y *= scale\n segment.tangentEnd.x *= scale\n segment.tangentEnd.y *= scale\n }\n return network\n}\n\nexport function scaleNodeChanges(\n node: SceneNode,\n scale: number,\n scalePosition: boolean\n): Partial<SceneNode> {\n return {\n x: scalePosition ? node.x * scale : node.x,\n y: scalePosition ? node.y * scale : node.y,\n width: node.width * scale,\n height: node.height * scale,\n minWidth: scaledOptional(node.minWidth, scale),\n maxWidth: scaledOptional(node.maxWidth, scale),\n minHeight: scaledOptional(node.minHeight, scale),\n maxHeight: scaledOptional(node.maxHeight, scale),\n cornerRadius: node.cornerRadius * scale,\n topLeftRadius: node.topLeftRadius * scale,\n topRightRadius: node.topRightRadius * scale,\n bottomRightRadius: node.bottomRightRadius * scale,\n bottomLeftRadius: node.bottomLeftRadius * scale,\n fontSize: node.fontSize * scale,\n letterSpacing: scaledTextLength(node.letterSpacing, scale),\n lineHeight: node.lineHeight && scaledTextLength(node.lineHeight, scale),\n textDecorationThickness: scaledOptional(node.textDecorationThickness, scale),\n textUnderlineOffset: scaledOptional(node.textUnderlineOffset, scale),\n styleRuns: scaledStyleRuns(node.styleRuns, scale),\n listSpacing: node.listSpacing * scale,\n paragraphSpacing: node.paragraphSpacing * scale,\n paragraphIndent: node.paragraphIndent * scale,\n textParagraphs: scaledParagraphStyles(node.textParagraphs, scale),\n itemSpacing: node.itemSpacing * scale,\n counterAxisSpacing: node.counterAxisSpacing * scale,\n paddingTop: node.paddingTop * scale,\n paddingRight: node.paddingRight * scale,\n paddingBottom: node.paddingBottom * scale,\n paddingLeft: node.paddingLeft * scale,\n gridColumnGap: node.gridColumnGap * scale,\n gridRowGap: node.gridRowGap * scale,\n gridTemplateColumns: scaledGridTracks(node.gridTemplateColumns, scale),\n gridTemplateRows: scaledGridTracks(node.gridTemplateRows, scale),\n strokes: scaledStrokes(node.strokes, scale),\n strokeWeight: node.strokeWeight * scale,\n dashPattern: node.dashPattern.map((value) => value * scale),\n borderTopWeight: node.borderTopWeight * scale,\n borderRightWeight: node.borderRightWeight * scale,\n borderBottomWeight: node.borderBottomWeight * scale,\n borderLeftWeight: node.borderLeftWeight * scale,\n strokeMiterLimit: node.strokeMiterLimit,\n effects: scaledEffects(node.effects, scale),\n fills: scaledFills(node.fills, scale),\n layoutGrids: scaledLayoutGrids(node.layoutGrids, scale),\n vectorNetwork: scaledVectorNetwork(node, scale),\n fillGeometry: scaleGeometryPaths(node.fillGeometry, scale, scale),\n strokeGeometry: scaleGeometryPaths(node.strokeGeometry, scale, scale),\n ...scaledPathTextChanges(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Y,KAAK,UAAU,QAAQ,KAAK;EAC1D,iBAAiB,KAAK,kBAAkB;EACxC,mBAAmB,KAAK,oBAAoB;EAC5C,oBAAoB,KAAK,qBAAqB;EAC9C,kBAAkB,KAAK,mBAAmB;EAC1C,kBAAkB,KAAK;EACvB,SAAS,cAAc,KAAK,SAAS,KAAK;EAC1C,OAAO,YAAY,KAAK,OAAO,KAAK;EACpC,aAAa,kBAAkB,KAAK,aAAa,KAAK;EACtD,eAAe,oBAAoB,MAAM,KAAK;EAC9C,cAAc,mBAAmB,KAAK,cAAc,OAAO,KAAK;EAChE,gBAAgB,mBAAmB,KAAK,gBAAgB,OAAO,KAAK;EACpE,GAAG,sBAAsB,MAAM,OAAO,KAAK;CAC7C;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tree.d.ts","names":[],"sources":["../../src/scaling/tree.ts"],"mappings":";;;;cAOa;;iBAmBG,aAAa,MAAM,KAAK;;iBAKxB,eAAe,OAAO,YAAY,MAAM,YAAY;;;;;;iBAmBpD,uBACd,OAAO,YACP,gBAAgB,aAChB,gBACA,gBACC,YAAY,QAAQ;;
|
|
1
|
+
{"version":3,"file":"tree.d.ts","names":[],"sources":["../../src/scaling/tree.ts"],"mappings":";;;;cAOa;;iBAmBG,aAAa,MAAM,KAAK;;iBAKxB,eAAe,OAAO,YAAY,MAAM,YAAY;;;;;;iBAmBpD,uBACd,OAAO,YACP,gBAAgB,aAChB,gBACA,gBACC,YAAY,QAAQ;;iBAgBP,oBAAoB;;iBAMpB,gBAAgB,OAAO,YAAY,gBAAgB"}
|
package/dist/scaling/tree.js
CHANGED
|
@@ -45,11 +45,14 @@ function rescaleSubtree(graph, root) {
|
|
|
45
45
|
*/
|
|
46
46
|
function rescaleNodeTreeChanges(graph, nodes, rootId, scale) {
|
|
47
47
|
const changes = /* @__PURE__ */ new Map();
|
|
48
|
-
for (const node of nodes)
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
48
|
+
for (const node of nodes) {
|
|
49
|
+
const scaled = scaleNodeChanges(node, scale, node.id !== rootId);
|
|
50
|
+
changes.set(node.id, {
|
|
51
|
+
...scaled,
|
|
52
|
+
...scaleVariableBindingUnits(node, scale, scaled.styleRuns),
|
|
53
|
+
componentScale: findInstanceAncestor(graph, node.id) ? node.componentScale * scale : node.componentScale
|
|
54
|
+
});
|
|
55
|
+
}
|
|
53
56
|
return changes;
|
|
54
57
|
}
|
|
55
58
|
/** Throws unless `scale` is a factor a layer can be scaled by. */
|
package/dist/scaling/tree.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tree.js","names":[],"sources":["../../src/scaling/tree.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport { findInstanceAncestor } from '../instances'\nimport type { SceneNode } from '../types'\nimport { scaleVariableBindingUnits } from '../variables/units'\nimport { scaleNodeChanges } from './node'\n\n/** The smallest factor a layer scales by, so it never folds away. */\nexport const MIN_RESCALE = 0.01\nconst RESCALABLE_NODE_TYPES = new Set<SceneNode['type']>([\n 'BOOLEAN_OPERATION',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'ELLIPSE',\n 'FRAME',\n 'GROUP',\n 'INSTANCE',\n 'LINE',\n 'POLYGON',\n 'RECTANGLE',\n 'STAR',\n 'STICKY',\n 'TEXT',\n 'VECTOR'\n])\n\n/** Whether a layer scales with its contents, as Figma's Scale tool and `rescale()` allow. */\nexport function isRescalable(node: Pick<SceneNode, 'type'>): boolean {\n return RESCALABLE_NODE_TYPES.has(node.type)\n}\n\n/** A layer and every layer below it, root first, as the graph holds them now. */\nexport function rescaleSubtree(graph: SceneGraph, root: SceneNode): SceneNode[] {\n const nodes: SceneNode[] = [root]\n const collect = (node: SceneNode): void => {\n for (const childId of node.childIds) {\n const child = graph.getNode(childId)\n if (!child) continue\n nodes.push(child)\n collect(child)\n }\n }\n collect(root)\n return nodes\n}\n\n/**\n * What scaling `nodes`, a subtree as `rescaleSubtree` lists it, by `scale` changes in each layer,\n * keeping the root's top-left; read from the given copies, so a preview can scale again from the\n * layers as they were.\n */\nexport function rescaleNodeTreeChanges(\n graph: SceneGraph,\n nodes: readonly SceneNode[],\n rootId: string,\n scale: number\n): Map<string, Partial<SceneNode>> {\n const changes = new Map<string, Partial<SceneNode>>()\n for (const node of nodes) {\n
|
|
1
|
+
{"version":3,"file":"tree.js","names":[],"sources":["../../src/scaling/tree.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport { findInstanceAncestor } from '../instances'\nimport type { SceneNode } from '../types'\nimport { scaleVariableBindingUnits } from '../variables/units'\nimport { scaleNodeChanges } from './node'\n\n/** The smallest factor a layer scales by, so it never folds away. */\nexport const MIN_RESCALE = 0.01\nconst RESCALABLE_NODE_TYPES = new Set<SceneNode['type']>([\n 'BOOLEAN_OPERATION',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'ELLIPSE',\n 'FRAME',\n 'GROUP',\n 'INSTANCE',\n 'LINE',\n 'POLYGON',\n 'RECTANGLE',\n 'STAR',\n 'STICKY',\n 'TEXT',\n 'VECTOR'\n])\n\n/** Whether a layer scales with its contents, as Figma's Scale tool and `rescale()` allow. */\nexport function isRescalable(node: Pick<SceneNode, 'type'>): boolean {\n return RESCALABLE_NODE_TYPES.has(node.type)\n}\n\n/** A layer and every layer below it, root first, as the graph holds them now. */\nexport function rescaleSubtree(graph: SceneGraph, root: SceneNode): SceneNode[] {\n const nodes: SceneNode[] = [root]\n const collect = (node: SceneNode): void => {\n for (const childId of node.childIds) {\n const child = graph.getNode(childId)\n if (!child) continue\n nodes.push(child)\n collect(child)\n }\n }\n collect(root)\n return nodes\n}\n\n/**\n * What scaling `nodes`, a subtree as `rescaleSubtree` lists it, by `scale` changes in each layer,\n * keeping the root's top-left; read from the given copies, so a preview can scale again from the\n * layers as they were.\n */\nexport function rescaleNodeTreeChanges(\n graph: SceneGraph,\n nodes: readonly SceneNode[],\n rootId: string,\n scale: number\n): Map<string, Partial<SceneNode>> {\n const changes = new Map<string, Partial<SceneNode>>()\n for (const node of nodes) {\n const scaled = scaleNodeChanges(node, scale, node.id !== rootId)\n changes.set(node.id, {\n ...scaled,\n ...scaleVariableBindingUnits(node, scale, scaled.styleRuns),\n componentScale: findInstanceAncestor(graph, node.id)\n ? node.componentScale * scale\n : node.componentScale\n })\n }\n return changes\n}\n\n/** Throws unless `scale` is a factor a layer can be scaled by. */\nexport function assertRescaleFactor(scale: number): void {\n if (!Number.isFinite(scale)) throw new TypeError('Scale must be a finite number')\n if (scale < MIN_RESCALE) throw new RangeError(`Scale must be at least ${MIN_RESCALE}`)\n}\n\n/** Scale a node tree from the root node's top-left, matching Figma's Scale tool. */\nexport function rescaleNodeTree(graph: SceneGraph, rootId: string, scale: number): void {\n assertRescaleFactor(scale)\n const root = graph.getNode(rootId)\n if (!root || !isRescalable(root)) throw new Error('rescale() is not supported on this node')\n const nodes = rescaleSubtree(graph, root)\n for (const [id, changes] of rescaleNodeTreeChanges(graph, nodes, rootId, scale)) {\n graph.updateNode(id, changes)\n }\n}\n"],"mappings":";;;;;AAOA,MAAa,cAAc;AAC3B,MAAM,wCAAwB,IAAI,IAAuB;CACvD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,aAAa,MAAwC;CACnE,OAAO,sBAAsB,IAAI,KAAK,IAAI;AAC5C;;AAGA,SAAgB,eAAe,OAAmB,MAA8B;CAC9E,MAAM,QAAqB,CAAC,IAAI;CAChC,MAAM,WAAW,SAA0B;EACzC,KAAK,MAAM,WAAW,KAAK,UAAU;GACnC,MAAM,QAAQ,MAAM,QAAQ,OAAO;GACnC,IAAI,CAAC,OAAO;GACZ,MAAM,KAAK,KAAK;GAChB,QAAQ,KAAK;EACf;CACF;CACA,QAAQ,IAAI;CACZ,OAAO;AACT;;;;;;AAOA,SAAgB,uBACd,OACA,OACA,QACA,OACiC;CACjC,MAAM,0BAAU,IAAI,IAAgC;CACpD,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,SAAS,iBAAiB,MAAM,OAAO,KAAK,OAAO,MAAM;EAC/D,QAAQ,IAAI,KAAK,IAAI;GACnB,GAAG;GACH,GAAG,0BAA0B,MAAM,OAAO,OAAO,SAAS;GAC1D,gBAAgB,qBAAqB,OAAO,KAAK,EAAE,IAC/C,KAAK,iBAAiB,QACtB,KAAK;EACX,CAAC;CACH;CACA,OAAO;AACT;;AAGA,SAAgB,oBAAoB,OAAqB;CACvD,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,MAAM,IAAI,UAAU,+BAA+B;CAChF,IAAI,QAAA,KAAqB,MAAM,IAAI,WAAW,0BAA0B,aAAa;AACvF;;AAGA,SAAgB,gBAAgB,OAAmB,QAAgB,OAAqB;CACtF,oBAAoB,KAAK;CACzB,MAAM,OAAO,MAAM,QAAQ,MAAM;CACjC,IAAI,CAAC,QAAQ,CAAC,aAAa,IAAI,GAAG,MAAM,IAAI,MAAM,yCAAyC;CAC3F,MAAM,QAAQ,eAAe,OAAO,IAAI;CACxC,KAAK,MAAM,CAAC,IAAI,YAAY,uBAAuB,OAAO,OAAO,QAAQ,KAAK,GAC5E,MAAM,WAAW,IAAI,OAAO;AAEhC"}
|
package/dist/slots/authoring.js
CHANGED
|
@@ -12,12 +12,9 @@ const DEFAULT_SLOT_SETTINGS = {
|
|
|
12
12
|
* instance are not authored there, so a layer under an instance has none.
|
|
13
13
|
*/
|
|
14
14
|
function slotOwner(graph, node) {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
if (current.type === "INSTANCE") return void 0;
|
|
19
|
-
current = current.parentId ? graph.getNode(current.parentId) : void 0;
|
|
20
|
-
}
|
|
15
|
+
if (!node.parentId) return void 0;
|
|
16
|
+
const owner = graph.closest(node.parentId, (current) => current.type === "COMPONENT" || current.type === "INSTANCE" || current.type === "CANVAS");
|
|
17
|
+
return owner?.type === "COMPONENT" ? owner : void 0;
|
|
21
18
|
}
|
|
22
19
|
/** Whether a frame inside a main component can become a slot. */
|
|
23
20
|
function canCreateSlot(graph, node) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authoring.js","names":[],"sources":["../../src/slots/authoring.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport { numberedName } from '../naming'\nimport type { ComponentPropertyDefinition, SceneNode, SlotSettings } from '../types'\nimport { slotPropertyId } from './frames'\n\n/** The settings a new slot starts with: no limits, any layer allowed. */\nexport const DEFAULT_SLOT_SETTINGS: SlotSettings = {\n allowPreferredValuesOnly: false,\n displayEmptyByDefault: false,\n stretchChildOnInsert: false\n}\n\n/**\n * The main component a layer belongs to, which defines the slots inside it. Layers of an\n * instance are not authored there, so a layer under an instance has none.\n */\nexport function slotOwner(graph: SceneGraph, node: SceneNode): SceneNode | undefined {\n
|
|
1
|
+
{"version":3,"file":"authoring.js","names":[],"sources":["../../src/slots/authoring.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport { numberedName } from '../naming'\nimport type { ComponentPropertyDefinition, SceneNode, SlotSettings } from '../types'\nimport { slotPropertyId } from './frames'\n\n/** The settings a new slot starts with: no limits, any layer allowed. */\nexport const DEFAULT_SLOT_SETTINGS: SlotSettings = {\n allowPreferredValuesOnly: false,\n displayEmptyByDefault: false,\n stretchChildOnInsert: false\n}\n\n/**\n * The main component a layer belongs to, which defines the slots inside it. Layers of an\n * instance are not authored there, so a layer under an instance has none.\n */\nexport function slotOwner(graph: SceneGraph, node: SceneNode): SceneNode | undefined {\n if (!node.parentId) return undefined\n const owner = graph.closest(\n node.parentId,\n (current) =>\n current.type === 'COMPONENT' || current.type === 'INSTANCE' || current.type === 'CANVAS'\n )\n return owner?.type === 'COMPONENT' ? owner : undefined\n}\n\n/** Whether a frame inside a main component can become a slot. */\nexport function canCreateSlot(graph: SceneGraph, node: SceneNode): boolean {\n return node.type === 'FRAME' && !slotPropertyId(node) && !!slotOwner(graph, node)\n}\n\nfunction uniqueSlotName(owner: SceneNode, base: string): string {\n return numberedName(\n base,\n owner.componentPropertyDefinitions.map((definition) => definition.name)\n )\n}\n\n/**\n * Make a frame of a main component a slot: define a SLOT property, named after the frame, on\n * the component and bind the frame's children to it. Instances pick up the slot on their next\n * sync.\n */\nexport function createSlotProperty(\n graph: SceneGraph,\n frameId: string,\n id: string\n): ComponentPropertyDefinition | null {\n const frame = graph.getNode(frameId)\n const owner = frame && canCreateSlot(graph, frame) ? slotOwner(graph, frame) : undefined\n if (!frame || !owner) return null\n const definition: ComponentPropertyDefinition = {\n id,\n name: uniqueSlotName(owner, frame.name.trim() || 'Slot'),\n type: 'SLOT',\n defaultValue: '',\n preferredValues: [],\n slotSettings: { ...DEFAULT_SLOT_SETTINGS }\n }\n graph.updateNode(owner.id, {\n componentPropertyDefinitions: [...owner.componentPropertyDefinitions, definition]\n })\n graph.updateNode(frame.id, {\n componentPropertyReferences: [\n ...frame.componentPropertyReferences,\n { propertyId: id, field: 'SLOT_CONTENT' }\n ]\n })\n return definition\n}\n\n/** What a slot's settings panel can change. */\nexport type SlotPropertyPatch = Partial<\n Pick<ComponentPropertyDefinition, 'name' | 'description' | 'preferredValues'>\n> & { slotSettings?: Partial<SlotSettings> }\n\n/** Change a slot property's name, description, preferred components, or limits. */\nexport function updateSlotProperty(\n graph: SceneGraph,\n ownerId: string,\n propertyId: string,\n patch: SlotPropertyPatch\n): boolean {\n const owner = graph.getNode(ownerId)\n const current = owner?.componentPropertyDefinitions.find(\n (definition) => definition.id === propertyId && definition.type === 'SLOT'\n )\n if (!owner || !current) return false\n const { slotSettings, ...fields } = patch\n const next: ComponentPropertyDefinition = {\n ...current,\n ...fields,\n slotSettings: { ...DEFAULT_SLOT_SETTINGS, ...current.slotSettings, ...slotSettings }\n }\n graph.updateNode(owner.id, {\n componentPropertyDefinitions: owner.componentPropertyDefinitions.map((definition) =>\n definition.id === propertyId ? next : definition\n )\n })\n return true\n}\n"],"mappings":";;;;AAMA,MAAa,wBAAsC;CACjD,0BAA0B;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,SAAS,MACtE;CACA,IAAI,CAAC,SAAS,CAAC,SAAS,OAAO;CAC/B,MAAM,EAAE,cAAc,GAAG,WAAW;CACpC,MAAM,OAAoC;EACxC,GAAG;EACH,GAAG;EACH,cAAc;GAAE,GAAG;GAAuB,GAAG,QAAQ;GAAc,GAAG;EAAa;CACrF;CACA,MAAM,WAAW,MAAM,IAAI,EACzB,8BAA8B,MAAM,6BAA6B,KAAK,eACpE,WAAW,OAAO,aAAa,OAAO,UACxC,EACF,CAAC;CACD,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"content.d.ts","names":[],"sources":["../../src/slots/content.ts"],"mappings":";;;;;;;;;;KAcY;EACN;;EACA;EAAc,OAAO;EAAW,UAAU;EAAW;;EACrD;EAAgB,OAAO;;
|
|
1
|
+
{"version":3,"file":"content.d.ts","names":[],"sources":["../../src/slots/content.ts"],"mappings":";;;;;;;;;;KAcY;EACN;;EACA;EAAc,OAAO;EAAW,UAAU;EAAW;;EACrD;EAAgB,OAAO;;iBAQb,UAAU,OAAO,YAAY,mBAAmB;;;;;;iBAiChD,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa;;;iBAwCd,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa;;;iBAYd,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa"}
|
package/dist/slots/content.js
CHANGED
|
@@ -3,34 +3,24 @@ import { isGeneratedFrame } from "../generated/index.js";
|
|
|
3
3
|
import { ownsSlotContent, slotPropertyId } from "./frames.js";
|
|
4
4
|
import { cloneChildrenWithMapping } from "../instances/sync.js";
|
|
5
5
|
//#region src/slots/content.ts
|
|
6
|
-
function parentOf(graph, node) {
|
|
7
|
-
return node.parentId ? graph.nodes.get(node.parentId) : void 0;
|
|
8
|
-
}
|
|
9
6
|
function nearestInstance(graph, node) {
|
|
10
|
-
|
|
11
|
-
while (current && current.type !== "INSTANCE") current = parentOf(graph, current);
|
|
12
|
-
return current;
|
|
7
|
+
return node.parentId ? graph.closest(node.parentId, (current) => current.type === "INSTANCE") : void 0;
|
|
13
8
|
}
|
|
14
9
|
function slotScope(graph, parentId) {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
owner: current
|
|
30
|
-
};
|
|
31
|
-
current = parentOf(graph, current);
|
|
32
|
-
}
|
|
33
|
-
return { kind: "free" };
|
|
10
|
+
const owner = graph.closest(parentId, (current) => !!slotPropertyId(current) || current.type === "INSTANCE" || isGeneratedFrame(current));
|
|
11
|
+
if (!owner) return { kind: "free" };
|
|
12
|
+
const propertyId = slotPropertyId(owner);
|
|
13
|
+
if (!propertyId) return {
|
|
14
|
+
kind: "locked",
|
|
15
|
+
owner
|
|
16
|
+
};
|
|
17
|
+
const instance = nearestInstance(graph, owner);
|
|
18
|
+
return instance ? {
|
|
19
|
+
kind: "slot",
|
|
20
|
+
frame: owner,
|
|
21
|
+
instance,
|
|
22
|
+
propertyId
|
|
23
|
+
} : { kind: "free" };
|
|
34
24
|
}
|
|
35
25
|
/** Every layer below `node`; `enterInstances` also walks the layers of nested instances. */
|
|
36
26
|
function descendants(graph, node, enterInstances) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"content.js","names":[],"sources":["../../src/slots/content.ts"],"sourcesContent":["import { isGeneratedFrame } from '../generated'\nimport type { SceneGraph } from '../graph'\nimport { getInstanceOverride, setInstanceOverride } from '../instances/overrides'\nimport { cloneChildrenWithMapping } from '../instances/sync'\nimport type { SceneNode } from '../types'\nimport { ownsSlotContent, slotPropertyId } from './frames'\n\n/**\n * Where layers may be added, moved, or removed under a parent:\n * - `free`: outside any instance, or inside a component definition;\n * - `slot`: inside a slot of an instance, whose content the instance owns or can claim;\n * - `locked`: anywhere else inside an instance, whose layers come from its component, or inside a\n * generated frame such as a sticky note, whose layers come from its template.\n */\nexport type SlotScope =\n | { kind: 'free' }\n | { kind: 'slot'; frame: SceneNode; instance: SceneNode; propertyId: string }\n | { kind: 'locked'; owner: SceneNode }\n\nfunction
|
|
1
|
+
{"version":3,"file":"content.js","names":[],"sources":["../../src/slots/content.ts"],"sourcesContent":["import { isGeneratedFrame } from '../generated'\nimport type { SceneGraph } from '../graph'\nimport { getInstanceOverride, setInstanceOverride } from '../instances/overrides'\nimport { cloneChildrenWithMapping } from '../instances/sync'\nimport type { SceneNode } from '../types'\nimport { ownsSlotContent, slotPropertyId } from './frames'\n\n/**\n * Where layers may be added, moved, or removed under a parent:\n * - `free`: outside any instance, or inside a component definition;\n * - `slot`: inside a slot of an instance, whose content the instance owns or can claim;\n * - `locked`: anywhere else inside an instance, whose layers come from its component, or inside a\n * generated frame such as a sticky note, whose layers come from its template.\n */\nexport type SlotScope =\n | { kind: 'free' }\n | { kind: 'slot'; frame: SceneNode; instance: SceneNode; propertyId: string }\n | { kind: 'locked'; owner: SceneNode }\n\nfunction nearestInstance(graph: SceneGraph, node: SceneNode): SceneNode | undefined {\n return node.parentId\n ? graph.closest(node.parentId, (current) => current.type === 'INSTANCE')\n : undefined\n}\n\nexport function slotScope(graph: SceneGraph, parentId: string): SlotScope {\n const owner = graph.closest(\n parentId,\n (current) =>\n !!slotPropertyId(current) || current.type === 'INSTANCE' || isGeneratedFrame(current)\n )\n if (!owner) return { kind: 'free' }\n const propertyId = slotPropertyId(owner)\n if (!propertyId) return { kind: 'locked', owner }\n const instance = nearestInstance(graph, owner)\n return instance ? { kind: 'slot', frame: owner, instance, propertyId } : { kind: 'free' }\n}\n\n/** Every layer below `node`; `enterInstances` also walks the layers of nested instances. */\nfunction descendants(graph: SceneGraph, node: SceneNode, enterInstances: boolean): SceneNode[] {\n const result: SceneNode[] = []\n const visit = (parent: SceneNode): void => {\n for (const childId of parent.childIds) {\n const child = graph.nodes.get(childId)\n if (!child) continue\n result.push(child)\n if (enterInstances || child.type !== 'INSTANCE') visit(child)\n }\n }\n visit(node)\n return result\n}\n\n/**\n * Make the instance own its slot's content, as Figma does on the first edit: the layers\n * stay where they are, but stop following the component. Overrides the instance held for\n * them become their own values, or move to the nested instance they belong to.\n */\nexport function claimSlotContent(\n graph: SceneGraph,\n scope: Extract<SlotScope, { kind: 'slot' }>\n): void {\n const { frame, instance, propertyId } = scope\n if (ownsSlotContent(graph, frame, propertyId)) return\n const overrides = instance.instanceOverrides\n for (const node of descendants(graph, frame, false)) {\n overrides.descendants.delete(node.id)\n if (node.type !== 'INSTANCE') {\n graph.updateNode(node.id, { componentId: null })\n continue\n }\n // A nested instance keeps the overrides its former owner applied inside it.\n for (const inner of descendants(graph, node, true)) {\n const fields = overrides.descendants.get(inner.id)\n if (!fields) continue\n for (const [field, value] of fields)\n if (field !== 'sourceComponentId')\n setInstanceOverride(node.instanceOverrides, node.id, inner.id, field, value)\n overrides.descendants.delete(inner.id)\n }\n graph.updateNode(node.id, { instanceOverrides: node.instanceOverrides })\n }\n graph.updateNode(instance.id, {\n instanceOverrides: overrides,\n componentPropertyAssignments: { ...instance.componentPropertyAssignments, [propertyId]: '' }\n })\n}\n\n/** The component layer an instance layer was cloned from. */\nfunction componentSource(instance: SceneNode, node: SceneNode): string | null {\n const mapped = getInstanceOverride(\n instance.instanceOverrides,\n instance.id,\n node.id,\n 'sourceComponentId'\n )\n return typeof mapped === 'string' ? mapped : node.componentId\n}\n\n/** Return the slot to its component's content: the instance stops owning it. */\nexport function resetSlotContent(\n graph: SceneGraph,\n scope: Extract<SlotScope, { kind: 'slot' }>\n): void {\n const { frame, instance, propertyId } = scope\n for (const childId of Array.from(frame.childIds)) graph.deleteNode(childId)\n const assignments = { ...instance.componentPropertyAssignments }\n Reflect.deleteProperty(assignments, propertyId)\n graph.updateNode(instance.id, { componentPropertyAssignments: assignments })\n const source = componentSource(instance, frame)\n if (source && graph.nodes.has(source)) cloneChildrenWithMapping(graph, source, frame.id)\n}\n\n/** Remove everything from the slot; the instance keeps owning it, now empty. */\nexport function clearSlotContent(\n graph: SceneGraph,\n scope: Extract<SlotScope, { kind: 'slot' }>\n): void {\n claimSlotContent(graph, scope)\n for (const childId of Array.from(scope.frame.childIds)) graph.deleteNode(childId)\n}\n"],"mappings":";;;;;AAmBA,SAAS,gBAAgB,OAAmB,MAAwC;CAClF,OAAO,KAAK,WACR,MAAM,QAAQ,KAAK,WAAW,YAAY,QAAQ,SAAS,UAAU,IACrE,KAAA;AACN;AAEA,SAAgB,UAAU,OAAmB,UAA6B;CACxE,MAAM,QAAQ,MAAM,QAClB,WACC,YACC,CAAC,CAAC,eAAe,OAAO,KAAK,QAAQ,SAAS,cAAc,iBAAiB,OAAO,CACxF;CACA,IAAI,CAAC,OAAO,OAAO,EAAE,MAAM,OAAO;CAClC,MAAM,aAAa,eAAe,KAAK;CACvC,IAAI,CAAC,YAAY,OAAO;EAAE,MAAM;EAAU;CAAM;CAChD,MAAM,WAAW,gBAAgB,OAAO,KAAK;CAC7C,OAAO,WAAW;EAAE,MAAM;EAAQ,OAAO;EAAO;EAAU;CAAW,IAAI,EAAE,MAAM,OAAO;AAC1F;;AAGA,SAAS,YAAY,OAAmB,MAAiB,gBAAsC;CAC7F,MAAM,SAAsB,CAAC;CAC7B,MAAM,SAAS,WAA4B;EACzC,KAAK,MAAM,WAAW,OAAO,UAAU;GACrC,MAAM,QAAQ,MAAM,MAAM,IAAI,OAAO;GACrC,IAAI,CAAC,OAAO;GACZ,OAAO,KAAK,KAAK;GACjB,IAAI,kBAAkB,MAAM,SAAS,YAAY,MAAM,KAAK;EAC9D;CACF;CACA,MAAM,IAAI;CACV,OAAO;AACT;;;;;;AAOA,SAAgB,iBACd,OACA,OACM;CACN,MAAM,EAAE,OAAO,UAAU,eAAe;CACxC,IAAI,gBAAgB,OAAO,OAAO,UAAU,GAAG;CAC/C,MAAM,YAAY,SAAS;CAC3B,KAAK,MAAM,QAAQ,YAAY,OAAO,OAAO,KAAK,GAAG;EACnD,UAA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AAM,KAAK,MAAM,MAAM,QAAQ,GAAG,MAAM,WAAW,OAAO;AAClF"}
|
package/dist/slots/frames.js
CHANGED
|
@@ -10,8 +10,7 @@ function slotPropertyId(node) {
|
|
|
10
10
|
*/
|
|
11
11
|
function ownsSlotContent(graph, node, propertyId = slotPropertyId(node)) {
|
|
12
12
|
if (!propertyId) return false;
|
|
13
|
-
|
|
14
|
-
while (owner && owner.type !== "INSTANCE") owner = owner.parentId ? graph.nodes.get(owner.parentId) : void 0;
|
|
13
|
+
const owner = node.parentId ? graph.closest(node.parentId, (current) => current.type === "INSTANCE") : void 0;
|
|
15
14
|
return !!owner && Object.hasOwn(owner.componentPropertyAssignments, propertyId);
|
|
16
15
|
}
|
|
17
16
|
/** The name of a slot property as the instance's component (or the component's set) defines it. */
|
package/dist/slots/frames.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"frames.js","names":[],"sources":["../../src/slots/frames.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport { instanceMainComponent } from '../instances/main-component'\nimport type { SceneNode } from '../types'\n\n/** The slot property a frame holds the content of, if it is a slot. */\nexport function slotPropertyId(node: SceneNode): string | undefined {\n return node.componentPropertyReferences.find((reference) => reference.field === 'SLOT_CONTENT')\n ?.propertyId\n}\n\n/**\n * Whether this slot frame's children belong to its instance rather than its component: the\n * nearest enclosing instance assigns the slot. Such content is never synced from the component.\n */\nexport function ownsSlotContent(\n graph: SceneGraph,\n node: SceneNode,\n propertyId = slotPropertyId(node)\n): boolean {\n if (!propertyId) return false\n
|
|
1
|
+
{"version":3,"file":"frames.js","names":[],"sources":["../../src/slots/frames.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport { instanceMainComponent } from '../instances/main-component'\nimport type { SceneNode } from '../types'\n\n/** The slot property a frame holds the content of, if it is a slot. */\nexport function slotPropertyId(node: SceneNode): string | undefined {\n return node.componentPropertyReferences.find((reference) => reference.field === 'SLOT_CONTENT')\n ?.propertyId\n}\n\n/**\n * Whether this slot frame's children belong to its instance rather than its component: the\n * nearest enclosing instance assigns the slot. Such content is never synced from the component.\n */\nexport function ownsSlotContent(\n graph: SceneGraph,\n node: SceneNode,\n propertyId = slotPropertyId(node)\n): boolean {\n if (!propertyId) return false\n const owner = node.parentId\n ? graph.closest(node.parentId, (current) => current.type === 'INSTANCE')\n : undefined\n return !!owner && Object.hasOwn(owner.componentPropertyAssignments, propertyId)\n}\n\n/** The name of a slot property as the instance's component (or the component's set) defines it. */\nfunction slotName(graph: SceneGraph, instance: SceneNode, propertyId: string) {\n const component = instanceMainComponent(graph, instance)\n const set = component?.parentId ? graph.nodes.get(component.parentId) : undefined\n return [component, set]\n .flatMap((node) => node?.componentPropertyDefinitions ?? [])\n .find((definition) => definition.id === propertyId && definition.type === 'SLOT')?.name\n}\n\n/** An instance's slot frames, without entering nested instances, whose slots are their own. */\nexport function instanceSlotFrames(graph: SceneGraph, instance: SceneNode): SceneNode[] {\n const frames: SceneNode[] = []\n const visit = (node: SceneNode): void => {\n for (const childId of node.childIds) {\n const child = graph.nodes.get(childId)\n if (!child) continue\n if (slotPropertyId(child)) frames.push(child)\n else if (child.type !== 'INSTANCE') visit(child)\n }\n }\n visit(instance)\n return frames\n}\n\n/** One slot's owned content, parked while the instance it belongs to is rebuilt. */\ninterface ParkedSlot {\n /** Names of the nested instances leading to the slot's owner; empty for the instance itself. */\n path: string[]\n /** The slot property's name, which the replacement must share. */\n name: string\n /** Content layer ids, in layer order. */\n content: string[]\n}\n\n/** Owned slot content parked under an instance while its component changes. */\nexport interface ParkedSlotContent {\n slots: ParkedSlot[]\n /** The instance's own slot assignments the content was parked from. */\n propertyIds: string[]\n}\n\n/** Instances directly inside this one: not inside another nested instance or a slot. */\nfunction nestedInstances(graph: SceneGraph, owner: SceneNode): SceneNode[] {\n const found: SceneNode[] = []\n const visit = (node: SceneNode): void => {\n for (const childId of node.childIds) {\n const child = graph.nodes.get(childId)\n if (!child || slotPropertyId(child)) continue\n if (child.type === 'INSTANCE') found.push(child)\n else visit(child)\n }\n }\n visit(owner)\n return found\n}\n\n/** The nested instance a name path leads to from `root`, matched by layer name as Figma does. */\nfunction instanceAtPath(\n graph: SceneGraph,\n root: SceneNode,\n path: readonly string[]\n): SceneNode | undefined {\n let current: SceneNode | undefined = root\n for (const name of path) {\n current = current && nestedInstances(graph, current).find((node) => node.name === name)\n }\n return current\n}\n\n/**\n * Park the slot content an instance and the instances nested in it own, by slot name and the\n * nested instance's name path, directly under the instance, so its component can be replaced.\n * Figma keeps that content when a variant switch or swap leads to slots of the same names.\n */\nexport function detachOwnedSlotContent(graph: SceneGraph, instance: SceneNode): ParkedSlotContent {\n const parked: ParkedSlotContent = { slots: [], propertyIds: [] }\n const visit = (owner: SceneNode, path: string[]): void => {\n for (const nested of nestedInstances(graph, owner)) visit(nested, [...path, nested.name])\n for (const frame of instanceSlotFrames(graph, owner)) {\n const propertyId = slotPropertyId(frame)\n if (!propertyId || !Object.hasOwn(owner.componentPropertyAssignments, propertyId)) continue\n if (owner.id === instance.id) parked.propertyIds.push(propertyId)\n const name = slotName(graph, owner, propertyId)\n const key = [...path, name].join('\\u0000')\n if (!name || parked.slots.some((slot) => [...slot.path, slot.name].join('\\u0000') === key))\n continue\n const content = [...frame.childIds]\n for (const id of content) graph.insertChildAt(id, instance.id, instance.childIds.length)\n parked.slots.push({ path, name, content })\n }\n }\n visit(instance, [])\n return parked\n}\n\n/** Move parked content into the slots of the same names and paths, and reassign them. */\nexport function restoreOwnedSlotContent(\n graph: SceneGraph,\n instance: SceneNode,\n parked: ParkedSlotContent\n): void {\n if (parked.slots.length === 0 && parked.propertyIds.length === 0) return\n graph.updateNode(instance.id, {\n componentPropertyAssignments: Object.fromEntries(\n Object.entries(instance.componentPropertyAssignments).filter(\n ([id]) => !parked.propertyIds.includes(id)\n )\n )\n })\n for (const slot of parked.slots) {\n const owner = instanceAtPath(graph, instance, slot.path)\n const frame =\n owner &&\n instanceSlotFrames(graph, owner).find((candidate) => {\n const propertyId = slotPropertyId(candidate)\n return !!propertyId && slotName(graph, owner, propertyId) === slot.name\n })\n const propertyId = frame && slotPropertyId(frame)\n if (\n !owner ||\n !frame ||\n !propertyId ||\n Object.hasOwn(owner.componentPropertyAssignments, propertyId)\n ) {\n for (const id of slot.content) graph.deleteNode(id)\n continue\n }\n for (const id of Array.from(frame.childIds)) graph.deleteNode(id)\n for (const [index, id] of slot.content.entries()) graph.insertChildAt(id, frame.id, index)\n graph.updateNode(owner.id, {\n componentPropertyAssignments: { ...owner.componentPropertyAssignments, [propertyId]: '' }\n })\n }\n}\n"],"mappings":";;;AAKA,SAAgB,eAAe,MAAqC;CAClE,OAAO,KAAK,4BAA4B,MAAM,cAAc,UAAU,UAAU,cAAc,CAAC,EAC3F;AACN;;;;;AAMA,SAAgB,gBACd,OACA,MACA,aAAa,eAAe,IAAI,GACvB;CACT,IAAI,CAAC,YAAY,OAAO;CACxB,MAAM,QAAQ,KAAK,WACf,MAAM,QAAQ,KAAK,WAAW,YAAY,QAAQ,SAAS,UAAU,IACrE,KAAA;CACJ,OAAO,CAAC,CAAC,SAAS,OAAO,OAAO,MAAM,8BAA8B,UAAU;AAChF;;AAGA,SAAS,SAAS,OAAmB,UAAqB,YAAoB;CAC5E,MAAM,YAAY,sBAAsB,OAAO,QAAQ;CAEvD,OAAO,CAAC,WADI,WAAW,WAAW,MAAM,MAAM,IAAI,UAAU,QAAQ,IAAI,KAAA,CAClD,CAAC,CACpB,SAAS,SAAS,MAAM,gCAAgC,CAAC,CAAC,CAAC,CAC3D,MAAM,eAAe,WAAW,OAAO,cAAc,WAAW,SAAS,MAAM,CAAC,EAAE;AACvF;;AAGA,SAAgB,mBAAmB,OAAmB,UAAkC;CACtF,MAAM,SAAsB,CAAC;CAC7B,MAAM,SAAS,SAA0B;EACvC,KAAK,MAAM,WAAW,KAAK,UAAU;GACnC,MAAM,QAAQ,MAAM,MAAM,IAAI,OAAO;GACrC,IAAI,CAAC,OAAO;GACZ,IAAI,eAAe,K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AG,MAAM;IAA+B,aAAa;EAAG,EAC1F,CAAC;CACH;AACF"}
|
package/dist/snap.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snap.d.ts","names":[],"sources":["../src/snap.ts"],"mappings":";;;UAMiB;EACf;EACA;EACA;EACA;;EAEA;;;;;;EAMA;;UAGe;EACf;EACA;EACA,QAAQ;;
|
|
1
|
+
{"version":3,"file":"snap.d.ts","names":[],"sources":["../src/snap.ts"],"mappings":";;;UAMiB;EACf;EACA;EACA;EACA;;EAEA;;;;;;EAMA;;UAGe;EACf;EACA;EACA,QAAQ;;iBAkBM,YACd,WAAW,aACX,cAAc,MACd,UAAU,aACV,qBACC;iBAqFa,uBAAuB,OAAO,cAAc;;UAoB3C;EACf;EACA;EACA;EACA;;;;;;;UAQe;WACN,YAAY;WACZ,YAAY;;UASN;;EAEf;EACA;;;iBA2Bc,eACd,WAAW,aACX,mBAAmB,cAClB;;;;;;iBA4Fa,mBACd,SAAS,gBACT,cAAc,MACd,qBACC;;;;;iBAiDa,qBAAqB,SAAS,gBAAgB,cAAc,OAAO"}
|
package/dist/snap.js
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getNodeWorldBounds } from "./coordinate.js";
|
|
2
2
|
//#region src/snap.ts
|
|
3
3
|
const DEFAULT_SNAP_THRESHOLD = 5;
|
|
4
4
|
function getEdges(node) {
|
|
5
|
-
|
|
5
|
+
const box = getNodeWorldBounds(node);
|
|
6
|
+
return {
|
|
7
|
+
left: box.x,
|
|
8
|
+
right: box.x + box.width,
|
|
9
|
+
top: box.y,
|
|
10
|
+
bottom: box.y + box.height,
|
|
11
|
+
centerX: box.x + box.width / 2,
|
|
12
|
+
centerY: box.y + box.height / 2
|
|
13
|
+
};
|
|
6
14
|
}
|
|
7
15
|
function computeSnap(movingIds, movingBounds, allNodes, threshold = DEFAULT_SNAP_THRESHOLD) {
|
|
8
16
|
const targets = allNodes.filter((n) => !movingIds.has(n.id));
|
|
@@ -39,7 +47,7 @@ function computeSnap(movingIds, movingBounds, allNodes, threshold = DEFAULT_SNAP
|
|
|
39
47
|
guides.length = guides.filter((g) => g.axis === "y").length ? guides.length : guides.length;
|
|
40
48
|
for (let i = guides.length - 1; i >= 0; i--) if (guides[i].axis === "x") guides.splice(i, 1);
|
|
41
49
|
}
|
|
42
|
-
if (
|
|
50
|
+
if (d === bestDx) {
|
|
43
51
|
const minY = Math.min(m.top, t.top);
|
|
44
52
|
const maxY = Math.max(m.bottom, t.bottom);
|
|
45
53
|
guides.push({
|
|
@@ -65,7 +73,7 @@ function computeSnap(movingIds, movingBounds, allNodes, threshold = DEFAULT_SNAP
|
|
|
65
73
|
for (let i = guides.length - 1; i >= 0; i--) if (guides[i].axis === "y") guides.splice(i, 1);
|
|
66
74
|
bestDy = d;
|
|
67
75
|
}
|
|
68
|
-
if (
|
|
76
|
+
if (d === bestDy) {
|
|
69
77
|
const minX = Math.min(m.left, t.left);
|
|
70
78
|
const maxX = Math.max(m.right, t.right);
|
|
71
79
|
guides.push({
|
package/dist/snap.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snap.js","names":[],"sources":["../src/snap.ts"],"sourcesContent":["import { rotatedBBox } from './geometry'\nimport type { Rect } from './primitives'\nimport type { SceneNode } from './types'\n\nconst DEFAULT_SNAP_THRESHOLD = 5\n\nexport interface SnapGuide {\n axis: 'x' | 'y'\n position: number\n from: number\n to: number\n /** Points along the guide that lined up, marked with a cross: a guide through path vertices. */\n marks?: number[]\n /**\n * An equal-spacing indicator instead of an alignment line: the gap between two neighbours, from\n * `from` to `to` on the line at `position`. A gap along x is a horizontal line, so its `axis` is\n * `'y'`, as for any horizontal guide; the renderer caps both ends and labels the gap's size.\n */\n spacing?: boolean\n}\n\nexport interface SnapResult {\n dx: number\n dy: number\n guides: SnapGuide[]\n}\n\nfunction getEdges(node: SceneNode) {\n return rotatedBBox(node.x, node.y, node.width, node.height, node.rotation)\n}\n\n// Pairwise edge/center matching intentionally keeps both axes in one pass.\n// eslint-disable-next-line complexity\nexport function computeSnap(\n movingIds: Set<string>,\n movingBounds: Rect,\n allNodes: SceneNode[],\n threshold = DEFAULT_SNAP_THRESHOLD\n): SnapResult {\n const targets = allNodes.filter((n) => !movingIds.has(n.id))\n if (targets.length === 0) return { dx: 0, dy: 0, guides: [] }\n\n const m = {\n left: movingBounds.x,\n right: movingBounds.x + movingBounds.width,\n centerX: movingBounds.x + movingBounds.width / 2,\n top: movingBounds.y,\n bottom: movingBounds.y + movingBounds.height,\n centerY: movingBounds.y + movingBounds.height / 2\n }\n\n let bestDx = Infinity\n let bestDy = Infinity\n const guides: SnapGuide[] = []\n\n for (const target of targets) {\n const t = getEdges(target)\n\n // X-axis snapping: left-to-left, left-to-right, right-to-left, right-to-right, center-to-center\n const xPairs: [number, number][] = [\n [m.left, t.left],\n [m.left, t.right],\n [m.right, t.left],\n [m.right, t.right],\n [m.centerX, t.centerX]\n ]\n\n for (const [mVal, tVal] of xPairs) {\n const d = tVal - mVal\n if (Math.abs(d) < threshold && Math.abs(d) <= Math.abs(bestDx)) {\n if (Math.abs(d) < Math.abs(bestDx)) {\n bestDx = d\n guides.length = guides.filter((g) => g.axis === 'y').length\n ? guides.length\n : guides.length\n // Remove old x guides if we found a closer snap\n for (let i = guides.length - 1; i >= 0; i--) {\n if (guides[i].axis === 'x') guides.splice(i, 1)\n }\n }\n if (Math.abs(d) === Math.abs(bestDx)) {\n const minY = Math.min(m.top, t.top)\n const maxY = Math.max(m.bottom, t.bottom)\n guides.push({ axis: 'x', position: tVal, from: minY, to: maxY })\n }\n }\n }\n\n // Y-axis snapping\n const yPairs: [number, number][] = [\n [m.top, t.top],\n [m.top, t.bottom],\n [m.bottom, t.top],\n [m.bottom, t.bottom],\n [m.centerY, t.centerY]\n ]\n\n for (const [mVal, tVal] of yPairs) {\n const d = tVal - mVal\n if (Math.abs(d) < threshold && Math.abs(d) <= Math.abs(bestDy)) {\n if (Math.abs(d) < Math.abs(bestDy)) {\n for (let i = guides.length - 1; i >= 0; i--) {\n if (guides[i].axis === 'y') guides.splice(i, 1)\n }\n bestDy = d\n }\n if (Math.abs(d) === Math.abs(bestDy)) {\n const minX = Math.min(m.left, t.left)\n const maxX = Math.max(m.right, t.right)\n guides.push({ axis: 'y', position: tVal, from: minX, to: maxX })\n }\n }\n }\n }\n\n return {\n dx: Math.abs(bestDx) <= threshold ? bestDx : 0,\n dy: Math.abs(bestDy) <= threshold ? bestDy : 0,\n guides\n }\n}\n\nexport function computeSelectionBounds(nodes: SceneNode[]): Rect | null {\n if (nodes.length === 0) return null\n let minX = Infinity\n let minY = Infinity\n let maxX = -Infinity\n let maxY = -Infinity\n for (const n of nodes) {\n const edges = getEdges(n)\n minX = Math.min(minX, edges.left)\n minY = Math.min(minY, edges.top)\n maxX = Math.max(maxX, edges.right)\n maxY = Math.max(maxY, edges.bottom)\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }\n}\n\n/** Gaps this close count as equal, so float noise from world transforms does not hide a match. */\nconst SPACING_MATCH_TOLERANCE = 0.01\n\n/** A layer's extent along one axis (`start`..`end`) and across it (`crossStart`..`crossEnd`). */\nexport interface SpacingSpan {\n start: number\n end: number\n crossStart: number\n crossEnd: number\n}\n\n/**\n * The layers equal spacing measures against, along each axis and sorted by start. Build them once\n * with {@link spacingTargets} and share them between {@link computeSpacingSnap} and\n * {@link computeSpacingGuides}, so one pointer move sorts the layers once.\n */\nexport interface SpacingTargets {\n readonly x: readonly SpacingSpan[]\n readonly y: readonly SpacingSpan[]\n}\n\ninterface SpacingPair {\n before: SpacingSpan\n after: SpacingSpan\n gap: number\n}\n\nexport interface SpacingSnapResult {\n /** The move that makes a gap along x equal to its neighbours', or `null` when none is near. */\n dx: number | null\n dy: number | null\n}\n\ntype Edges = Pick<ReturnType<typeof getEdges>, 'left' | 'right' | 'top' | 'bottom'>\ntype Axis = 'x' | 'y'\n\nfunction spanOf(edges: Edges, axis: Axis): SpacingSpan {\n return axis === 'x'\n ? { start: edges.left, end: edges.right, crossStart: edges.top, crossEnd: edges.bottom }\n : { start: edges.top, end: edges.bottom, crossStart: edges.left, crossEnd: edges.right }\n}\n\nfunction boundsSpan(bounds: Rect, axis: Axis): SpacingSpan {\n const edges = {\n left: bounds.x,\n right: bounds.x + bounds.width,\n top: bounds.y,\n bottom: bounds.y + bounds.height\n }\n return spanOf(edges, axis)\n}\n\nfunction crossOverlaps(a: SpacingSpan, b: SpacingSpan): boolean {\n return a.crossStart < b.crossEnd && a.crossEnd > b.crossStart\n}\n\n/** Every layer except the moving ones, as spans along each axis sorted by start. */\nexport function spacingTargets(\n movingIds: Set<string>,\n allNodes: readonly SceneNode[]\n): SpacingTargets {\n const x: SpacingSpan[] = []\n const y: SpacingSpan[] = []\n for (const node of allNodes) {\n if (movingIds.has(node.id)) continue\n const edges = getEdges(node)\n x.push(spanOf(edges, 'x'))\n y.push(spanOf(edges, 'y'))\n }\n const byStart = (a: SpacingSpan, b: SpacingSpan) => a.start - b.start\n return { x: x.sort(byStart), y: y.sort(byStart) }\n}\n\n/** The layers beside the moving one along an axis: those sharing some of its extent across it. */\nfunction rowOf(moving: SpacingSpan, sorted: readonly SpacingSpan[]): SpacingSpan[] {\n return sorted.filter((span) => crossOverlaps(span, moving))\n}\n\n/**\n * The gaps between neighbours in a row: stretches along the axis that no layer of the row covers,\n * each between the layer reaching furthest into it and the next layer, when the two share some\n * extent across the axis. A layer over another, such as a label on its button, therefore never\n * makes a gap across the button. A gap the moving layer sits in is not a gap between neighbours, so\n * it is left out. The row is sorted by start, so one sweep finds them all.\n */\nfunction neighbourPairs(row: readonly SpacingSpan[], moving: SpacingSpan): SpacingPair[] {\n const pairs: SpacingPair[] = []\n let frontier: SpacingSpan | null = null\n for (const span of row) {\n if (\n frontier &&\n span.start >= frontier.end &&\n crossOverlaps(span, frontier) &&\n !(moving.start < span.start && moving.end > frontier.end)\n ) {\n pairs.push({ before: frontier, after: span, gap: span.start - frontier.end })\n }\n if (!frontier || span.end > frontier.end) frontier = span\n }\n return pairs\n}\n\n/** The nearest layer before the moving one (ending at most `slack` into it), and after it. */\nfunction neighboursOf(\n row: readonly SpacingSpan[],\n moving: SpacingSpan,\n slack: number\n): { before: SpacingSpan | null; after: SpacingSpan | null } {\n let before: SpacingSpan | null = null\n let after: SpacingSpan | null = null\n for (const span of row) {\n if (span.start < moving.start && span.end <= moving.start + slack) {\n if (!before || span.end > before.end) before = span\n }\n if (span.end > moving.end && span.start >= moving.end - slack) {\n if (!after || span.start < after.start) after = span\n }\n }\n return { before, after }\n}\n\nfunction spacingDelta(\n moving: SpacingSpan,\n sorted: readonly SpacingSpan[],\n threshold: number\n): number | null {\n const row = rowOf(moving, sorted)\n const { before, after } = neighboursOf(row, moving, threshold)\n if (!before && !after) return null\n const size = moving.end - moving.start\n const starts: number[] = []\n if (before && after && after.start - before.end - size >= 0) {\n starts.push((before.end + after.start - size) / 2)\n }\n for (const pair of neighbourPairs(row, moving)) {\n if (before) starts.push(before.end + pair.gap)\n if (after) starts.push(after.start - pair.gap - size)\n }\n let best: number | null = null\n for (const start of starts) {\n const delta = start - moving.start\n if (Math.abs(delta) >= threshold) continue\n if (best === null || Math.abs(delta) < Math.abs(best)) best = delta\n }\n return best\n}\n\n/**\n * Figma's equal-spacing snap: on each axis, the move within `threshold` that centres the moving\n * bounds between their two neighbours, or leaves them as far from a neighbour as two other\n * neighbours in the same row are apart. Only layers sharing some extent across the axis count.\n */\nexport function computeSpacingSnap(\n targets: SpacingTargets,\n movingBounds: Rect,\n threshold = DEFAULT_SNAP_THRESHOLD\n): SpacingSnapResult {\n const delta = (axis: Axis) =>\n spacingDelta(boundsSpan(movingBounds, axis), targets[axis], threshold)\n return { dx: delta('x'), dy: delta('y') }\n}\n\nfunction gapGuide(before: SpacingSpan, after: SpacingSpan, axis: Axis): SnapGuide {\n const position =\n (Math.max(before.crossStart, after.crossStart) + Math.min(before.crossEnd, after.crossEnd)) / 2\n return {\n axis: axis === 'x' ? 'y' : 'x',\n position,\n from: before.end,\n to: after.start,\n spacing: true\n }\n}\n\nfunction sameGap(a: number, b: number): boolean {\n return Math.abs(a - b) < SPACING_MATCH_TOLERANCE\n}\n\nfunction axisSpacingGuides(\n movingBounds: Rect,\n sorted: readonly SpacingSpan[],\n axis: Axis\n): SnapGuide[] {\n const moving = boundsSpan(movingBounds, axis)\n const row = rowOf(moving, sorted)\n const { before, after } = neighboursOf(row, moving, SPACING_MATCH_TOLERANCE)\n const pairs = neighbourPairs(row, moving)\n const sides: SpacingPair[] = []\n if (before) sides.push({ before, after: moving, gap: moving.start - before.end })\n if (after) sides.push({ before: moving, after, gap: after.start - moving.end })\n const matched = sides.filter(\n (side) =>\n side.gap > SPACING_MATCH_TOLERANCE &&\n (sides.some((other) => other !== side && sameGap(other.gap, side.gap)) ||\n pairs.some((pair) => sameGap(pair.gap, side.gap)))\n )\n const gaps = matched.map((side) => side.gap)\n const shown = [...matched, ...pairs.filter((pair) => gaps.some((gap) => sameGap(pair.gap, gap)))]\n return shown.map((pair) => gapGuide(pair.before, pair.after, axis))\n}\n\n/**\n * The equal-spacing indicators for bounds where they are: every gap beside them that equals the gap\n * on their other side or a gap between two neighbours in the same row, and those neighbours' gaps.\n */\nexport function computeSpacingGuides(targets: SpacingTargets, movingBounds: Rect): SnapGuide[] {\n return [\n ...axisSpacingGuides(movingBounds, targets.x, 'x'),\n ...axisSpacingGuides(movingBounds, targets.y, 'y')\n ]\n}\n"],"mappings":";;AAIA,MAAM,yBAAyB;AAuB/B,SAAS,SAAS,MAAiB;CACjC,OAAO,YAAY,KAAK,GAAG,KAAK,GAAG,KAAK,OAAO,KAAK,QAAQ,KAAK,QAAQ;AAC3E;AAIA,SAAgB,YACd,WACA,cACA,UACA,YAAY,wBACA;CACZ,MAAM,UAAU,SAAS,QAAQ,MAAM,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;CAC3D,IAAI,QAAQ,WAAW,GAAG,OAAO;EAAE,IAAI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M,QAAQ,OAAO;CAAI,CAAC;CAC9E,MAAM,UAAU,MAAM,QACnB,SACC,KAAK,MAAM,4BACV,MAAM,MAAM,UAAU,UAAU,QAAQ,QAAQ,MAAM,KAAK,KAAK,GAAG,CAAC,KACnE,MAAM,MAAM,SAAS,QAAQ,KAAK,KAAK,KAAK,GAAG,CAAC,EACtD;CACA,MAAM,OAAO,QAAQ,KAAK,SAAS,KAAK,GAAG;CAE3C,OAAO,CADQ,GAAG,SAAS,GAAG,MAAM,QAAQ,SAAS,KAAK,MAAM,QAAQ,QAAQ,KAAK,KAAK,GAAG,CAAC,CAAC,CACpF,CAAC,CAAC,KAAK,SAAS,SAAS,KAAK,QAAQ,KAAK,OAAO,IAAI,CAAC;AACpE;;;;;AAMA,SAAgB,qBAAqB,SAAyB,cAAiC;CAC7F,OAAO,CACL,GAAG,kBAAkB,cAAc,QAAQ,GAAG,GAAG,GACjD,GAAG,kBAAkB,cAAc,QAAQ,GAAG,GAAG,CACnD;AACF"}
|
|
1
|
+
{"version":3,"file":"snap.js","names":[],"sources":["../src/snap.ts"],"sourcesContent":["import { getNodeWorldBounds } from './coordinate'\nimport type { Rect } from './primitives'\nimport type { SceneNode } from './types'\n\nconst DEFAULT_SNAP_THRESHOLD = 5\n\nexport interface SnapGuide {\n axis: 'x' | 'y'\n position: number\n from: number\n to: number\n /** Points along the guide that lined up, marked with a cross: a guide through path vertices. */\n marks?: number[]\n /**\n * An equal-spacing indicator instead of an alignment line: the gap between two neighbours, from\n * `from` to `to` on the line at `position`. A gap along x is a horizontal line, so its `axis` is\n * `'y'`, as for any horizontal guide; the renderer caps both ends and labels the gap's size.\n */\n spacing?: boolean\n}\n\nexport interface SnapResult {\n dx: number\n dy: number\n guides: SnapGuide[]\n}\n\n// A line turns around its start point and other layers around their centre, as they are drawn.\nfunction getEdges(node: SceneNode) {\n const box = getNodeWorldBounds(node)\n return {\n left: box.x,\n right: box.x + box.width,\n top: box.y,\n bottom: box.y + box.height,\n centerX: box.x + box.width / 2,\n centerY: box.y + box.height / 2\n }\n}\n\n// Pairwise edge/center matching intentionally keeps both axes in one pass.\n// eslint-disable-next-line complexity\nexport function computeSnap(\n movingIds: Set<string>,\n movingBounds: Rect,\n allNodes: SceneNode[],\n threshold = DEFAULT_SNAP_THRESHOLD\n): SnapResult {\n const targets = allNodes.filter((n) => !movingIds.has(n.id))\n if (targets.length === 0) return { dx: 0, dy: 0, guides: [] }\n\n const m = {\n left: movingBounds.x,\n right: movingBounds.x + movingBounds.width,\n centerX: movingBounds.x + movingBounds.width / 2,\n top: movingBounds.y,\n bottom: movingBounds.y + movingBounds.height,\n centerY: movingBounds.y + movingBounds.height / 2\n }\n\n let bestDx = Infinity\n let bestDy = Infinity\n const guides: SnapGuide[] = []\n\n for (const target of targets) {\n const t = getEdges(target)\n\n // X-axis snapping: left-to-left, left-to-right, right-to-left, right-to-right, center-to-center\n const xPairs: [number, number][] = [\n [m.left, t.left],\n [m.left, t.right],\n [m.right, t.left],\n [m.right, t.right],\n [m.centerX, t.centerX]\n ]\n\n for (const [mVal, tVal] of xPairs) {\n const d = tVal - mVal\n if (Math.abs(d) < threshold && Math.abs(d) <= Math.abs(bestDx)) {\n if (Math.abs(d) < Math.abs(bestDx)) {\n bestDx = d\n guides.length = guides.filter((g) => g.axis === 'y').length\n ? guides.length\n : guides.length\n // Remove old x guides if we found a closer snap\n for (let i = guides.length - 1; i >= 0; i--) {\n if (guides[i].axis === 'x') guides.splice(i, 1)\n }\n }\n // A tie in the other direction is not applied, so it draws no guide.\n if (d === bestDx) {\n const minY = Math.min(m.top, t.top)\n const maxY = Math.max(m.bottom, t.bottom)\n guides.push({ axis: 'x', position: tVal, from: minY, to: maxY })\n }\n }\n }\n\n // Y-axis snapping\n const yPairs: [number, number][] = [\n [m.top, t.top],\n [m.top, t.bottom],\n [m.bottom, t.top],\n [m.bottom, t.bottom],\n [m.centerY, t.centerY]\n ]\n\n for (const [mVal, tVal] of yPairs) {\n const d = tVal - mVal\n if (Math.abs(d) < threshold && Math.abs(d) <= Math.abs(bestDy)) {\n if (Math.abs(d) < Math.abs(bestDy)) {\n for (let i = guides.length - 1; i >= 0; i--) {\n if (guides[i].axis === 'y') guides.splice(i, 1)\n }\n bestDy = d\n }\n if (d === bestDy) {\n const minX = Math.min(m.left, t.left)\n const maxX = Math.max(m.right, t.right)\n guides.push({ axis: 'y', position: tVal, from: minX, to: maxX })\n }\n }\n }\n }\n\n return {\n dx: Math.abs(bestDx) <= threshold ? bestDx : 0,\n dy: Math.abs(bestDy) <= threshold ? bestDy : 0,\n guides\n }\n}\n\nexport function computeSelectionBounds(nodes: SceneNode[]): Rect | null {\n if (nodes.length === 0) return null\n let minX = Infinity\n let minY = Infinity\n let maxX = -Infinity\n let maxY = -Infinity\n for (const n of nodes) {\n const edges = getEdges(n)\n minX = Math.min(minX, edges.left)\n minY = Math.min(minY, edges.top)\n maxX = Math.max(maxX, edges.right)\n maxY = Math.max(maxY, edges.bottom)\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }\n}\n\n/** Gaps this close count as equal, so float noise from world transforms does not hide a match. */\nconst SPACING_MATCH_TOLERANCE = 0.01\n\n/** A layer's extent along one axis (`start`..`end`) and across it (`crossStart`..`crossEnd`). */\nexport interface SpacingSpan {\n start: number\n end: number\n crossStart: number\n crossEnd: number\n}\n\n/**\n * The layers equal spacing measures against, along each axis and sorted by start. Build them once\n * with {@link spacingTargets} and share them between {@link computeSpacingSnap} and\n * {@link computeSpacingGuides}, so one pointer move sorts the layers once.\n */\nexport interface SpacingTargets {\n readonly x: readonly SpacingSpan[]\n readonly y: readonly SpacingSpan[]\n}\n\ninterface SpacingPair {\n before: SpacingSpan\n after: SpacingSpan\n gap: number\n}\n\nexport interface SpacingSnapResult {\n /** The move that makes a gap along x equal to its neighbours', or `null` when none is near. */\n dx: number | null\n dy: number | null\n}\n\ntype Edges = Pick<ReturnType<typeof getEdges>, 'left' | 'right' | 'top' | 'bottom'>\ntype Axis = 'x' | 'y'\n\nfunction spanOf(edges: Edges, axis: Axis): SpacingSpan {\n return axis === 'x'\n ? { start: edges.left, end: edges.right, crossStart: edges.top, crossEnd: edges.bottom }\n : { start: edges.top, end: edges.bottom, crossStart: edges.left, crossEnd: edges.right }\n}\n\nfunction boundsSpan(bounds: Rect, axis: Axis): SpacingSpan {\n const edges = {\n left: bounds.x,\n right: bounds.x + bounds.width,\n top: bounds.y,\n bottom: bounds.y + bounds.height\n }\n return spanOf(edges, axis)\n}\n\nfunction crossOverlaps(a: SpacingSpan, b: SpacingSpan): boolean {\n return a.crossStart < b.crossEnd && a.crossEnd > b.crossStart\n}\n\n/** Every layer except the moving ones, as spans along each axis sorted by start. */\nexport function spacingTargets(\n movingIds: Set<string>,\n allNodes: readonly SceneNode[]\n): SpacingTargets {\n const x: SpacingSpan[] = []\n const y: SpacingSpan[] = []\n for (const node of allNodes) {\n if (movingIds.has(node.id)) continue\n const edges = getEdges(node)\n x.push(spanOf(edges, 'x'))\n y.push(spanOf(edges, 'y'))\n }\n const byStart = (a: SpacingSpan, b: SpacingSpan) => a.start - b.start\n return { x: x.sort(byStart), y: y.sort(byStart) }\n}\n\n/** The layers beside the moving one along an axis: those sharing some of its extent across it. */\nfunction rowOf(moving: SpacingSpan, sorted: readonly SpacingSpan[]): SpacingSpan[] {\n return sorted.filter((span) => crossOverlaps(span, moving))\n}\n\n/**\n * The gaps between neighbours in a row: stretches along the axis that no layer of the row covers,\n * each between the layer reaching furthest into it and the next layer, when the two share some\n * extent across the axis. A layer over another, such as a label on its button, therefore never\n * makes a gap across the button. A gap the moving layer sits in is not a gap between neighbours, so\n * it is left out. The row is sorted by start, so one sweep finds them all.\n */\nfunction neighbourPairs(row: readonly SpacingSpan[], moving: SpacingSpan): SpacingPair[] {\n const pairs: SpacingPair[] = []\n let frontier: SpacingSpan | null = null\n for (const span of row) {\n if (\n frontier &&\n span.start >= frontier.end &&\n crossOverlaps(span, frontier) &&\n !(moving.start < span.start && moving.end > frontier.end)\n ) {\n pairs.push({ before: frontier, after: span, gap: span.start - frontier.end })\n }\n if (!frontier || span.end > frontier.end) frontier = span\n }\n return pairs\n}\n\n/** The nearest layer before the moving one (ending at most `slack` into it), and after it. */\nfunction neighboursOf(\n row: readonly SpacingSpan[],\n moving: SpacingSpan,\n slack: number\n): { before: SpacingSpan | null; after: SpacingSpan | null } {\n let before: SpacingSpan | null = null\n let after: SpacingSpan | null = null\n for (const span of row) {\n if (span.start < moving.start && span.end <= moving.start + slack) {\n if (!before || span.end > before.end) before = span\n }\n if (span.end > moving.end && span.start >= moving.end - slack) {\n if (!after || span.start < after.start) after = span\n }\n }\n return { before, after }\n}\n\nfunction spacingDelta(\n moving: SpacingSpan,\n sorted: readonly SpacingSpan[],\n threshold: number\n): number | null {\n const row = rowOf(moving, sorted)\n const { before, after } = neighboursOf(row, moving, threshold)\n if (!before && !after) return null\n const size = moving.end - moving.start\n const starts: number[] = []\n if (before && after && after.start - before.end - size >= 0) {\n starts.push((before.end + after.start - size) / 2)\n }\n for (const pair of neighbourPairs(row, moving)) {\n if (before) starts.push(before.end + pair.gap)\n if (after) starts.push(after.start - pair.gap - size)\n }\n let best: number | null = null\n for (const start of starts) {\n const delta = start - moving.start\n if (Math.abs(delta) >= threshold) continue\n if (best === null || Math.abs(delta) < Math.abs(best)) best = delta\n }\n return best\n}\n\n/**\n * Figma's equal-spacing snap: on each axis, the move within `threshold` that centres the moving\n * bounds between their two neighbours, or leaves them as far from a neighbour as two other\n * neighbours in the same row are apart. Only layers sharing some extent across the axis count.\n */\nexport function computeSpacingSnap(\n targets: SpacingTargets,\n movingBounds: Rect,\n threshold = DEFAULT_SNAP_THRESHOLD\n): SpacingSnapResult {\n const delta = (axis: Axis) =>\n spacingDelta(boundsSpan(movingBounds, axis), targets[axis], threshold)\n return { dx: delta('x'), dy: delta('y') }\n}\n\nfunction gapGuide(before: SpacingSpan, after: SpacingSpan, axis: Axis): SnapGuide {\n const position =\n (Math.max(before.crossStart, after.crossStart) + Math.min(before.crossEnd, after.crossEnd)) / 2\n return {\n axis: axis === 'x' ? 'y' : 'x',\n position,\n from: before.end,\n to: after.start,\n spacing: true\n }\n}\n\nfunction sameGap(a: number, b: number): boolean {\n return Math.abs(a - b) < SPACING_MATCH_TOLERANCE\n}\n\nfunction axisSpacingGuides(\n movingBounds: Rect,\n sorted: readonly SpacingSpan[],\n axis: Axis\n): SnapGuide[] {\n const moving = boundsSpan(movingBounds, axis)\n const row = rowOf(moving, sorted)\n const { before, after } = neighboursOf(row, moving, SPACING_MATCH_TOLERANCE)\n const pairs = neighbourPairs(row, moving)\n const sides: SpacingPair[] = []\n if (before) sides.push({ before, after: moving, gap: moving.start - before.end })\n if (after) sides.push({ before: moving, after, gap: after.start - moving.end })\n const matched = sides.filter(\n (side) =>\n side.gap > SPACING_MATCH_TOLERANCE &&\n (sides.some((other) => other !== side && sameGap(other.gap, side.gap)) ||\n pairs.some((pair) => sameGap(pair.gap, side.gap)))\n )\n const gaps = matched.map((side) => side.gap)\n const shown = [...matched, ...pairs.filter((pair) => gaps.some((gap) => sameGap(pair.gap, gap)))]\n return shown.map((pair) => gapGuide(pair.before, pair.after, axis))\n}\n\n/**\n * The equal-spacing indicators for bounds where they are: every gap beside them that equals the gap\n * on their other side or a gap between two neighbours in the same row, and those neighbours' gaps.\n */\nexport function computeSpacingGuides(targets: SpacingTargets, movingBounds: Rect): SnapGuide[] {\n return [\n ...axisSpacingGuides(movingBounds, targets.x, 'x'),\n ...axisSpacingGuides(movingBounds, targets.y, 'y')\n ]\n}\n"],"mappings":";;AAIA,MAAM,yBAAyB;AAwB/B,SAAS,SAAS,MAAiB;CACjC,MAAM,MAAM,mBAAmB,IAAI;CACnC,OAAO;EACL,MAAM,IAAI;EACV,OAAO,IAAI,IAAI,IAAI;EACnB,KAAK,IAAI;EACT,QAAQ,IAAI,IAAI,IAAI;EACpB,SAAS,IAAI,IAAI,IAAI,QAAQ;EAC7B,SAAS,IAAI,IAAI,IAAI,SAAS;CAChC;AACF;AAIA,SAAgB,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,OAAO;CAAI,CAAC;CAChF,IAAI,OAAO,MAAM,KAAK;EAAE,QAAQ;EAAQ;EAAO,KAAK,MAAM,QAAQ,OAAO;CAAI,CAAC;CAC9E,MAAM,UAAU,MAAM,QACnB,SACC,KAAK,MAAM,4BACV,MAAM,MAAM,UAAU,UAAU,QAAQ,QAAQ,MAAM,KAAK,KAAK,GAAG,CAAC,KACnE,MAAM,MAAM,SAAS,QAAQ,KAAK,KAAK,KAAK,GAAG,CAAC,EACtD;CACA,MAAM,OAAO,QAAQ,KAAK,SAAS,KAAK,GAAG;CAE3C,OAAO,CADQ,GAAG,SAAS,GAAG,MAAM,QAAQ,SAAS,KAAK,MAAM,QAAQ,QAAQ,KAAK,KAAK,GAAG,CAAC,CAAC,CACpF,CAAC,CAAC,KAAK,SAAS,SAAS,KAAK,QAAQ,KAAK,OAAO,IAAI,CAAC;AACpE;;;;;AAMA,SAAgB,qBAAqB,SAAyB,cAAiC;CAC7F,OAAO,CACL,GAAG,kBAAkB,cAAc,QAAQ,GAAG,GAAG,GACjD,GAAG,kBAAkB,cAAc,QAAQ,GAAG,GAAG,CACnD;AACF"}
|
package/dist/types.d.ts
CHANGED
|
@@ -299,6 +299,11 @@ interface CharacterStyleOverride {
|
|
|
299
299
|
fillStyleId?: string | null;
|
|
300
300
|
/** The characters' text field bindings, in place of the text's own. */
|
|
301
301
|
boundVariables?: TextBoundVariables;
|
|
302
|
+
/**
|
|
303
|
+
* The scale each number the characters bind resolves with, as a rescale left it; a field without
|
|
304
|
+
* one uses the layer's `variableBindingScales`, as runs did before they kept their own.
|
|
305
|
+
*/
|
|
306
|
+
variableBindingScales?: Partial<Record<TextBindableField, number>>;
|
|
302
307
|
}
|
|
303
308
|
interface StyleRun {
|
|
304
309
|
start: number;
|