@pairdraw/core 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/canvas/outline-stroke.d.ts.map +1 -1
- package/dist/canvas/outline-stroke.js.map +1 -1
- package/dist/canvas/overlays/prototype.d.ts +2 -5
- package/dist/canvas/overlays/prototype.d.ts.map +1 -1
- package/dist/canvas/overlays/prototype.js +3 -19
- package/dist/canvas/overlays/prototype.js.map +1 -1
- package/dist/canvas/renderer/fonts.js +2 -1
- package/dist/canvas/renderer/fonts.js.map +1 -1
- package/dist/canvas/renderer.d.ts +4 -0
- package/dist/canvas/renderer.d.ts.map +1 -1
- package/dist/canvas/renderer.js +4 -0
- package/dist/canvas/renderer.js.map +1 -1
- package/dist/canvas/rulers.js +1 -1
- package/dist/canvas/rulers.js.map +1 -1
- package/dist/canvas/scene.d.ts.map +1 -1
- package/dist/canvas/scene.js +61 -37
- package/dist/canvas/scene.js.map +1 -1
- package/dist/canvas/text/font-families.d.ts +4 -3
- package/dist/canvas/text/font-families.d.ts.map +1 -1
- package/dist/canvas/text/font-families.js +8 -7
- package/dist/canvas/text/font-families.js.map +1 -1
- package/dist/canvas/text/index.d.ts.map +1 -1
- package/dist/canvas/text/index.js +1 -1
- package/dist/canvas/text/index.js.map +1 -1
- package/dist/canvas/text/paragraph/index.js +2 -2
- package/dist/canvas/text/paragraph/index.js.map +1 -1
- package/dist/canvas/text/placed.js +2 -2
- package/dist/canvas/text/placed.js.map +1 -1
- package/dist/canvas/text/renderer.d.ts +2 -0
- package/dist/canvas/text/renderer.d.ts.map +1 -1
- package/dist/clipboard/pairdraw.d.ts.map +1 -1
- package/dist/clipboard/pairdraw.js +53 -7
- package/dist/clipboard/pairdraw.js.map +1 -1
- package/dist/design-jsx/preview/picture.js +6 -1
- package/dist/design-jsx/preview/picture.js.map +1 -1
- package/dist/design-jsx/renderer.d.ts.map +1 -1
- package/dist/editor/alignment.d.ts.map +1 -1
- package/dist/editor/alignment.js +35 -27
- package/dist/editor/alignment.js.map +1 -1
- package/dist/editor/bridges/undo.d.ts +1 -1
- package/dist/editor/clipboard/detach.d.ts.map +1 -1
- package/dist/editor/clipboard/detach.js +3 -3
- package/dist/editor/clipboard/detach.js.map +1 -1
- package/dist/editor/clipboard/paste/properties.d.ts.map +1 -1
- package/dist/editor/clipboard/paste/properties.js +3 -1
- package/dist/editor/clipboard/paste/properties.js.map +1 -1
- package/dist/editor/create.d.ts +1 -1
- package/dist/editor/structure.d.ts.map +1 -1
- package/dist/editor/structure.js +3 -1
- package/dist/editor/structure.js.map +1 -1
- package/dist/editor/viewport.js +2 -2
- package/dist/editor/viewport.js.map +1 -1
- package/dist/figma-api/index.d.ts +43 -8
- package/dist/figma-api/index.d.ts.map +1 -1
- package/dist/figma-api/index.js +48 -6
- package/dist/figma-api/index.js.map +1 -1
- package/dist/figma-api/serialization.js +10 -0
- package/dist/figma-api/serialization.js.map +1 -1
- package/dist/figma-api/text/bindings.d.ts.map +1 -1
- package/dist/figma-api/text/bindings.js +20 -8
- package/dist/figma-api/text/bindings.js.map +1 -1
- package/dist/figma-api/text/index.js +1 -1
- package/dist/geometry/connectors.js +2 -14
- package/dist/geometry/connectors.js.map +1 -1
- package/dist/geometry/index.d.ts +2 -2
- package/dist/geometry/scene.d.ts +3 -1
- package/dist/geometry/scene.d.ts.map +1 -1
- package/dist/geometry/scene.js +16 -1
- package/dist/geometry/scene.js.map +1 -1
- package/dist/geometry/types.d.ts +7 -1
- package/dist/geometry/types.d.ts.map +1 -1
- package/dist/io/formats/drawio/export.d.ts.map +1 -1
- package/dist/io/formats/drawio/export.js +10 -0
- package/dist/io/formats/drawio/export.js.map +1 -1
- package/dist/io/formats/drawio/index.d.ts.map +1 -1
- package/dist/io/formats/drawio/index.js +32 -1
- package/dist/io/formats/drawio/index.js.map +1 -1
- package/dist/io/formats/drawio/shapes.d.ts +10 -5
- package/dist/io/formats/drawio/shapes.d.ts.map +1 -1
- package/dist/io/formats/drawio/shapes.js +10 -6
- package/dist/io/formats/drawio/shapes.js.map +1 -1
- package/dist/io/formats/drawio/warnings.d.ts +11 -0
- package/dist/io/formats/drawio/warnings.d.ts.map +1 -0
- package/dist/io/formats/drawio/warnings.js +23 -0
- package/dist/io/formats/drawio/warnings.js.map +1 -0
- package/dist/io/formats/pdf/dom.d.ts +10 -1
- package/dist/io/formats/pdf/dom.d.ts.map +1 -1
- package/dist/io/formats/pdf/dom.js +31 -1
- package/dist/io/formats/pdf/dom.js.map +1 -1
- package/dist/io/formats/pdf/export.js +3 -2
- package/dist/io/formats/pdf/export.js.map +1 -1
- package/dist/io/formats/raster/headless.d.ts +2 -2
- package/dist/io/formats/raster/headless.d.ts.map +1 -1
- package/dist/io/formats/raster/headless.js +2 -2
- package/dist/io/formats/raster/headless.js.map +1 -1
- package/dist/io/formats/raster/render.d.ts +1 -1
- package/dist/io/formats/raster/render.d.ts.map +1 -1
- package/dist/io/formats/raster/render.js +2 -2
- package/dist/io/formats/raster/render.js.map +1 -1
- package/dist/io/formats.d.ts.map +1 -1
- package/dist/io/formats.js +6 -6
- package/dist/io/formats.js.map +1 -1
- package/dist/io/registry.d.ts +2 -0
- package/dist/io/registry.d.ts.map +1 -1
- package/dist/io/registry.js +5 -0
- package/dist/io/registry.js.map +1 -1
- package/dist/io/types.d.ts +2 -0
- package/dist/io/types.d.ts.map +1 -1
- package/dist/library/snapshot.d.ts.map +1 -1
- package/dist/library/snapshot.js +1 -0
- package/dist/library/snapshot.js.map +1 -1
- package/dist/lint/linter.d.ts.map +1 -1
- package/dist/lint/linter.js +11 -2
- package/dist/lint/linter.js.map +1 -1
- package/dist/rpc/variables-command.d.ts.map +1 -1
- package/dist/rpc/variables-command.js +4 -2
- package/dist/rpc/variables-command.js.map +1 -1
- package/dist/text/character-style.d.ts.map +1 -1
- package/dist/text/character-style.js +2 -1
- package/dist/text/character-style.js.map +1 -1
- package/dist/text/coverage.d.ts.map +1 -1
- package/dist/text/coverage.js +6 -3
- package/dist/text/coverage.js.map +1 -1
- package/dist/text/fallbacks.d.ts +8 -2
- package/dist/text/fallbacks.d.ts.map +1 -1
- package/dist/text/fallbacks.js +73 -7
- package/dist/text/fallbacks.js.map +1 -1
- package/dist/text/font/manager.d.ts +14 -6
- package/dist/text/font/manager.d.ts.map +1 -1
- package/dist/text/font/manager.js +40 -14
- package/dist/text/font/manager.js.map +1 -1
- package/dist/text/index.d.ts +2 -2
- package/dist/text/index.js +3 -3
- package/dist/text/outlines.js +1 -1
- package/dist/text/outlines.js.map +1 -1
- package/dist/text/path/caret.d.ts +2 -4
- package/dist/text/path/caret.d.ts.map +1 -1
- package/dist/text/path/caret.js.map +1 -1
- package/dist/text/prepare.d.ts +5 -1
- package/dist/text/prepare.d.ts.map +1 -1
- package/dist/text/prepare.js +19 -2
- package/dist/text/prepare.js.map +1 -1
- package/dist/text/web-font/assets.d.ts.map +1 -1
- package/dist/text/web-font/assets.js +13 -21
- package/dist/text/web-font/assets.js.map +1 -1
- package/dist/text/web-font/resolver.d.ts.map +1 -1
- package/dist/text/web-font/resolver.js +4 -1
- package/dist/text/web-font/resolver.js.map +1 -1
- package/dist/tools/create/components.d.ts +2 -1
- package/dist/tools/create/components.d.ts.map +1 -1
- package/dist/tools/create/components.js +27 -1
- package/dist/tools/create/components.js.map +1 -1
- package/dist/tools/create/icons.d.ts.map +1 -1
- package/dist/tools/create/icons.js +11 -5
- package/dist/tools/create/icons.js.map +1 -1
- package/dist/tools/create/vector.d.ts.map +1 -1
- package/dist/tools/create/vector.js +9 -6
- package/dist/tools/create/vector.js.map +1 -1
- package/dist/tools/create.d.ts +2 -2
- package/dist/tools/create.js +2 -2
- package/dist/tools/modify/effects.d.ts.map +1 -1
- package/dist/tools/modify/effects.js +5 -3
- package/dist/tools/modify/effects.js.map +1 -1
- package/dist/tools/modify/matching.d.ts.map +1 -1
- package/dist/tools/modify/matching.js +9 -6
- package/dist/tools/modify/matching.js.map +1 -1
- package/dist/tools/modify/paint.d.ts.map +1 -1
- package/dist/tools/modify/paint.js +7 -5
- package/dist/tools/modify/paint.js.map +1 -1
- package/dist/tools/modify/text.d.ts.map +1 -1
- package/dist/tools/modify/text.js +28 -8
- package/dist/tools/modify/text.js.map +1 -1
- package/dist/tools/read/libraries.d.ts.map +1 -1
- package/dist/tools/read/libraries.js +20 -8
- package/dist/tools/read/libraries.js.map +1 -1
- package/dist/tools/read/pages.d.ts.map +1 -1
- package/dist/tools/read/pages.js.map +1 -1
- package/dist/tools/registry/extended.d.ts.map +1 -1
- package/dist/tools/registry/extended.js +2 -1
- package/dist/tools/registry/extended.js.map +1 -1
- package/dist/tools/schema.d.ts +24 -5
- package/dist/tools/schema.d.ts.map +1 -1
- package/dist/tools/schema.js +80 -6
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/structure/batch.d.ts.map +1 -1
- package/dist/tools/structure/batch.js +4 -3
- package/dist/tools/structure/batch.js.map +1 -1
- package/dist/tools/variables/values.d.ts.map +1 -1
- package/dist/tools/variables/values.js +4 -2
- package/dist/tools/variables/values.js.map +1 -1
- package/dist/tools/vector/export.d.ts.map +1 -1
- package/dist/tools/vector/export.js +5 -2
- package/dist/tools/vector/export.js.map +1 -1
- package/package.json +9 -9
- package/src/canvas/outline-stroke.ts +2 -6
- package/src/canvas/overlays/prototype.ts +5 -27
- package/src/canvas/renderer/fonts.ts +2 -1
- package/src/canvas/renderer.ts +4 -0
- package/src/canvas/rulers.ts +1 -1
- package/src/canvas/scene.ts +92 -63
- package/src/canvas/text/font-families.ts +8 -7
- package/src/canvas/text/index.ts +3 -1
- package/src/canvas/text/paragraph/index.ts +2 -2
- package/src/canvas/text/placed.ts +2 -2
- package/src/canvas/text/renderer.ts +2 -0
- package/src/clipboard/pairdraw.ts +51 -7
- package/src/design-jsx/preview/picture.ts +8 -2
- package/src/editor/alignment.ts +33 -29
- package/src/editor/clipboard/detach.ts +9 -3
- package/src/editor/clipboard/paste/properties.ts +3 -1
- package/src/editor/structure.ts +3 -1
- package/src/editor/viewport.ts +2 -2
- package/src/figma-api/index.ts +90 -9
- package/src/figma-api/serialization.ts +14 -0
- package/src/figma-api/text/bindings.ts +26 -8
- package/src/geometry/connectors.ts +2 -12
- package/src/geometry/index.ts +1 -1
- package/src/geometry/scene.ts +19 -0
- package/src/geometry/types.ts +8 -0
- package/src/io/formats/drawio/export.ts +11 -0
- package/src/io/formats/drawio/index.ts +36 -1
- package/src/io/formats/drawio/shapes.ts +13 -9
- package/src/io/formats/drawio/warnings.ts +27 -0
- package/src/io/formats/pdf/dom.ts +29 -0
- package/src/io/formats/pdf/export.ts +3 -2
- package/src/io/formats/raster/headless.ts +10 -3
- package/src/io/formats/raster/render.ts +4 -2
- package/src/io/formats.ts +8 -10
- package/src/io/registry.ts +12 -0
- package/src/io/types.ts +2 -0
- package/src/library/snapshot.ts +1 -0
- package/src/lint/linter.ts +12 -2
- package/src/rpc/variables-command.ts +6 -5
- package/src/text/character-style.ts +8 -4
- package/src/text/coverage.ts +17 -2
- package/src/text/fallbacks.ts +81 -7
- package/src/text/font/manager.ts +50 -17
- package/src/text/outlines.ts +1 -1
- package/src/text/path/caret.ts +3 -4
- package/src/text/prepare.ts +34 -2
- package/src/text/web-font/assets.ts +11 -15
- package/src/text/web-font/resolver.ts +7 -1
- package/src/tools/create/components.ts +33 -0
- package/src/tools/create/icons.ts +13 -5
- package/src/tools/create/vector.ts +16 -6
- package/src/tools/create.ts +1 -0
- package/src/tools/modify/effects.ts +11 -4
- package/src/tools/modify/matching.ts +10 -6
- package/src/tools/modify/paint.ts +13 -5
- package/src/tools/modify/text.ts +53 -20
- package/src/tools/read/libraries.ts +35 -11
- package/src/tools/read/pages.ts +1 -0
- package/src/tools/registry/extended.ts +2 -0
- package/src/tools/schema.ts +109 -5
- package/src/tools/structure/batch.ts +10 -5
- package/src/tools/variables/values.ts +6 -3
- package/src/tools/vector/export.ts +5 -1
package/dist/editor/alignment.js
CHANGED
|
@@ -2,7 +2,7 @@ import { createArrangeActions } from "./alignment/arrange.js";
|
|
|
2
2
|
import { createFlipRotateActions } from "./alignment/flip-rotate.js";
|
|
3
3
|
import { packPositions, tidyPositions } from "./alignment/tidy.js";
|
|
4
4
|
import { collectNodePositions, commitPositionChange } from "./history/position.js";
|
|
5
|
-
import { getAbsolutePositionFull, getWorldMatrix } from "@pairdraw/scene-graph/coordinate";
|
|
5
|
+
import { getAbsolutePositionFull, getAxisAlignedWorldBounds, getWorldMatrix } from "@pairdraw/scene-graph/coordinate";
|
|
6
6
|
import { computeAbsoluteBounds } from "@pairdraw/scene-graph/geometry";
|
|
7
7
|
import { sumBy } from "es-toolkit";
|
|
8
8
|
import Matrix from "@pairdraw/scene-graph/matrix";
|
|
@@ -14,36 +14,44 @@ function computeAlignTarget(min, max, size, align) {
|
|
|
14
14
|
}
|
|
15
15
|
function alignSingleNode(ctx, node, axis, align) {
|
|
16
16
|
const parent = node.parentId ? ctx.graph.getNode(node.parentId) : void 0;
|
|
17
|
-
const
|
|
18
|
-
const ph = parent?.height ?? 0;
|
|
19
|
-
if (axis === "horizontal") ctx.graph.updateNode(node.id, { x: computeAlignTarget(0, pw, node.width, align) });
|
|
20
|
-
else ctx.graph.updateNode(node.id, { y: computeAlignTarget(0, ph, node.height, align) });
|
|
21
|
-
}
|
|
22
|
-
function alignMultipleNodes(ctx, nodes, axis, align) {
|
|
23
|
-
const absPositions = /* @__PURE__ */ new Map();
|
|
24
|
-
for (const n of nodes) absPositions.set(n.id, ctx.graph.getAbsolutePosition(n.id));
|
|
25
|
-
const getPos = (id) => absPositions.get(id) ?? {
|
|
17
|
+
const target = parent ? getAxisAlignedWorldBounds(parent, ctx.graph) : {
|
|
26
18
|
x: 0,
|
|
27
|
-
y: 0
|
|
19
|
+
y: 0,
|
|
20
|
+
width: 0,
|
|
21
|
+
height: 0
|
|
28
22
|
};
|
|
29
|
-
const
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
23
|
+
const box = getAxisAlignedWorldBounds(node, ctx.graph);
|
|
24
|
+
const localDelta = parentLocalDelta(ctx, node, axis === "horizontal" ? {
|
|
25
|
+
x: computeAlignTarget(target.x, target.x + target.width, box.width, align) - box.x,
|
|
26
|
+
y: 0
|
|
27
|
+
} : {
|
|
28
|
+
x: 0,
|
|
29
|
+
y: computeAlignTarget(target.y, target.y + target.height, box.height, align) - box.y
|
|
30
|
+
});
|
|
31
|
+
if (!localDelta) return;
|
|
32
|
+
ctx.graph.updateNode(node.id, {
|
|
33
|
+
x: node.x + localDelta.x,
|
|
34
|
+
y: node.y + localDelta.y
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function alignMultipleNodes(ctx, nodes, axis, align) {
|
|
38
|
+
const boxes = new Map(nodes.map((n) => [n.id, getAxisAlignedWorldBounds(n, ctx.graph)]));
|
|
39
|
+
const b = computeAbsoluteBounds(nodes, ctx.graph);
|
|
34
40
|
for (const n of nodes) {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
41
|
+
const box = boxes.get(n.id);
|
|
42
|
+
if (!box) continue;
|
|
43
|
+
const localDelta = parentLocalDelta(ctx, n, axis === "horizontal" ? {
|
|
44
|
+
x: computeAlignTarget(b.x, b.x + b.width, box.width, align) - box.x,
|
|
38
45
|
y: 0
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
46
|
+
} : {
|
|
47
|
+
x: 0,
|
|
48
|
+
y: computeAlignTarget(b.y, b.y + b.height, box.height, align) - box.y
|
|
49
|
+
});
|
|
50
|
+
if (!localDelta) continue;
|
|
51
|
+
ctx.graph.updateNode(n.id, {
|
|
52
|
+
x: n.x + localDelta.x,
|
|
53
|
+
y: n.y + localDelta.y
|
|
54
|
+
});
|
|
47
55
|
}
|
|
48
56
|
}
|
|
49
57
|
function canPositionNode(ctx, node) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"alignment.js","names":[],"sources":["../../src/editor/alignment.ts"],"sourcesContent":["import { sumBy } from 'es-toolkit'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { getAbsolutePositionFull, getWorldMatrix } from '@pairdraw/scene-graph/coordinate'\nimport { computeAbsoluteBounds } from '@pairdraw/scene-graph/geometry'\nimport Matrix from '@pairdraw/scene-graph/matrix'\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\n\nimport { createArrangeActions } from '#core/editor/alignment/arrange'\nimport { createFlipRotateActions } from '#core/editor/alignment/flip-rotate'\nimport { packPositions, tidyPositions, type PlacedBox } from '#core/editor/alignment/tidy'\n\nimport { collectNodePositions, commitPositionChange } from './history/position'\nimport type { EditorContext } from './types'\n\nfunction computeAlignTarget(\n min: number,\n max: number,\n size: number,\n align: 'min' | 'center' | 'max'\n): number {\n if (align === 'min') return min\n if (align === 'center') return (min + max) / 2 - size / 2\n return max - size\n}\n\nfunction alignSingleNode(\n ctx: EditorContext,\n node: SceneNode,\n axis: 'horizontal' | 'vertical',\n align: 'min' | 'center' | 'max'\n) {\n const parent = node.parentId ? ctx.graph.getNode(node.parentId) : undefined\n const pw = parent?.width ?? 0\n const ph = parent?.height ?? 0\n\n if (axis === 'horizontal') {\n ctx.graph.updateNode(node.id, { x: computeAlignTarget(0, pw, node.width, align) })\n } else {\n ctx.graph.updateNode(node.id, { y: computeAlignTarget(0, ph, node.height, align) })\n }\n}\n\nfunction alignMultipleNodes(\n ctx: EditorContext,\n nodes: SceneNode[],\n axis: 'horizontal' | 'vertical',\n align: 'min' | 'center' | 'max'\n) {\n const absPositions = new Map<string, Vector>()\n for (const n of nodes) absPositions.set(n.id, ctx.graph.getAbsolutePosition(n.id))\n\n const getPos = (id: string) => absPositions.get(id) ?? { x: 0, y: 0 }\n const b = computeAbsoluteBounds(nodes, getPos)\n const minX = b.x\n const minY = b.y\n const maxX = b.x + b.width\n const maxY = b.y + b.height\n\n for (const n of nodes) {\n const abs = absPositions.get(n.id)\n if (!abs) continue\n const parentAbs = n.parentId ? ctx.graph.getAbsolutePosition(n.parentId) : { x: 0, y: 0 }\n\n if (axis === 'horizontal') {\n const target = computeAlignTarget(minX, maxX, n.width, align)\n ctx.graph.updateNode(n.id, { x: target - parentAbs.x })\n } else {\n const target = computeAlignTarget(minY, maxY, n.height, align)\n ctx.graph.updateNode(n.id, { y: target - parentAbs.y })\n }\n }\n}\n\nfunction canPositionNode(ctx: EditorContext, node: SceneNode): boolean {\n const parent = node.parentId ? ctx.graph.getNode(node.parentId) : undefined\n return !parent || parent.layoutMode === 'NONE' || node.layoutPositioning === 'ABSOLUTE'\n}\n\nfunction parentLocalDelta(ctx: EditorContext, node: SceneNode, worldDelta: Vector): Vector | null {\n const parent = node.parentId ? ctx.graph.getNode(node.parentId) : undefined\n if (!parent) return worldDelta\n const inverse = Matrix.invert(getWorldMatrix(parent, ctx.graph))\n if (!inverse) return null\n const origin = Matrix.mapPoint(inverse, { x: 0, y: 0 })\n const target = Matrix.mapPoint(inverse, worldDelta)\n return { x: target.x - origin.x, y: target.y - origin.y }\n}\n\nfunction distributeMultipleNodes(\n ctx: EditorContext,\n nodes: SceneNode[],\n axis: 'horizontal' | 'vertical'\n) {\n const bounds = new Map(nodes.map((node) => [node.id, getAbsolutePositionFull(node, ctx.graph)]))\n const coordinate = axis === 'horizontal' ? 'boundX' : 'boundY'\n const size = axis === 'horizontal' ? 'width' : 'height'\n const sorted = [...nodes].sort((a, b) => {\n const delta = (bounds.get(a.id)?.[coordinate] ?? 0) - (bounds.get(b.id)?.[coordinate] ?? 0)\n return delta || a.id.localeCompare(b.id)\n })\n const first = sorted[0]\n const last = sorted.at(-1)\n if (!last) return\n\n const start = bounds.get(first.id)?.[coordinate] ?? 0\n const end = (bounds.get(last.id)?.[coordinate] ?? 0) + (bounds.get(last.id)?.[size] ?? 0)\n const totalSize = sumBy(sorted, (node) => bounds.get(node.id)?.[size] ?? 0)\n const gap = (end - start - totalSize) / (sorted.length - 1)\n let cursor = start\n\n for (const node of sorted) {\n const nodeBounds = bounds.get(node.id)\n if (!nodeBounds) continue\n const distance = cursor - nodeBounds[coordinate]\n const localDelta = parentLocalDelta(\n ctx,\n node,\n axis === 'horizontal' ? { x: distance, y: 0 } : { x: 0, y: distance }\n )\n if (!localDelta) continue\n ctx.graph.updateNode(node.id, { x: node.x + localDelta.x, y: node.y + localDelta.y })\n cursor += nodeBounds[size] + gap\n }\n}\n\ntype Axis = 'horizontal' | 'vertical'\n\n/** The layers as one row or column, or null when they are not, as Figma's Spacing field reads them. */\nexport interface SelectionSpacing {\n axis: Axis\n /** The gaps between neighbours, in order along the axis. */\n gaps: number[]\n}\n\nfunction axisSpans(ctx: EditorContext, nodes: SceneNode[], axis: Axis) {\n const start = axis === 'horizontal' ? 'boundX' : 'boundY'\n const crossStart = axis === 'horizontal' ? 'boundY' : 'boundX'\n const size = axis === 'horizontal' ? 'width' : 'height'\n const crossSize = axis === 'horizontal' ? 'height' : 'width'\n return nodes\n .map((node) => {\n const bounds = getAbsolutePositionFull(node, ctx.graph)\n return {\n node,\n min: bounds[start],\n max: bounds[start] + bounds[size],\n crossMin: bounds[crossStart],\n crossMax: bounds[crossStart] + bounds[crossSize]\n }\n })\n .sort((a, b) => a.min - b.min || a.node.id.localeCompare(b.node.id))\n}\n\n/**\n * Layers form a row when none overlap along it and each overlaps its neighbour across it; layers\n * apart on both axes, like a grid or a diagonal, have no spacing in Figma.\n */\nfunction rowAlong(ctx: EditorContext, nodes: SceneNode[], axis: Axis) {\n const spans = axisSpans(ctx, nodes, axis)\n for (let index = 1; index < spans.length; index++) {\n const previous = spans[index - 1]\n const current = spans[index]\n if (current.min < previous.max) return null\n if (current.crossMin > previous.crossMax || current.crossMax < previous.crossMin) return null\n }\n return spans\n}\n\nexport function createAlignmentActions(ctx: EditorContext) {\n function positionableNodes(nodeIds: readonly string[]) {\n const nodes = nodeIds\n .map((id) => ctx.graph.getNode(id))\n .filter((node): node is SceneNode => node != null)\n return nodes.length >= 2 && nodes.every((node) => canPositionNode(ctx, node)) ? nodes : null\n }\n\n function selectionSpacing(nodeIds: readonly string[]): SelectionSpacing | null {\n const nodes = positionableNodes(nodeIds)\n if (!nodes) return null\n for (const axis of ['horizontal', 'vertical'] as const) {\n const spans = rowAlong(ctx, nodes, axis)\n if (spans)\n return { axis, gaps: spans.slice(1).map((span, index) => span.min - spans[index].max) }\n }\n return null\n }\n\n /** Spaces the row or column evenly by `gap`, keeping its first layer in place, as Figma does. */\n function setSelectionSpacing(nodeIds: readonly string[], gap: number) {\n const spacing = selectionSpacing(nodeIds)\n const nodes = positionableNodes(nodeIds)\n if (!spacing || !nodes) return\n const spans = rowAlong(ctx, nodes, spacing.axis)\n if (!spans) return\n const originals = collectNodePositions(\n ctx,\n nodes.map((node) => node.id)\n )\n let cursor = spans[0].max + gap\n for (const span of spans.slice(1)) {\n const distance = cursor - span.min\n const delta = parentLocalDelta(\n ctx,\n span.node,\n spacing.axis === 'horizontal' ? { x: distance, y: 0 } : { x: 0, y: distance }\n )\n if (delta)\n ctx.graph.updateNode(span.node.id, {\n x: span.node.x + delta.x,\n y: span.node.y + delta.y\n })\n cursor += span.max - span.min + gap\n }\n commitPositionChange(ctx, 'Change spacing', originals)\n ctx.requestRender()\n }\n\n function canDistributeNodes(nodeIds: string[]): boolean {\n const nodes = nodeIds\n .map((id) => ctx.graph.getNode(id))\n .filter((node): node is SceneNode => node != null)\n return nodes.length >= 3 && nodes.every((node) => canPositionNode(ctx, node))\n }\n\n function alignNodes(\n nodeIds: string[],\n axis: 'horizontal' | 'vertical',\n align: 'min' | 'center' | 'max'\n ) {\n if (nodeIds.length === 0) return\n\n const nodes = nodeIds\n .map((id) => ctx.graph.getNode(id))\n .filter((n): n is SceneNode => n != null)\n if (nodes.length === 0) return\n\n const originals = collectNodePositions(\n ctx,\n nodes.map((node) => node.id)\n )\n\n if (nodes.length === 1) {\n alignSingleNode(ctx, nodes[0], axis, align)\n } else {\n alignMultipleNodes(ctx, nodes, axis, align)\n }\n\n commitPositionChange(ctx, 'Align', originals)\n ctx.requestRender()\n }\n\n function distributeNodes(nodeIds: string[], axis: 'horizontal' | 'vertical') {\n const nodes = nodeIds\n .map((id) => ctx.graph.getNode(id))\n .filter((node): node is SceneNode => node != null)\n if (!canDistributeNodes(nodeIds)) return\n\n const originals = collectNodePositions(\n ctx,\n nodes.map((node) => node.id)\n )\n distributeMultipleNodes(ctx, nodes, axis)\n commitPositionChange(ctx, 'Distribute', originals)\n ctx.requestRender()\n }\n\n /** Whether layers can be tidied or packed: two or more that can move freely. */\n function canArrangeNodes(nodeIds: string[]): boolean {\n return positionableNodes(nodeIds) !== null\n }\n\n /** Moves each layer so its box on the page starts where `plan` puts it, as one undo step. */\n function placeBoxes(\n nodeIds: string[],\n label: string,\n plan: (boxes: PlacedBox[]) => Map<string, Vector>\n ) {\n const chosen = positionableNodes(nodeIds)\n if (!chosen) return\n // A layer inside another chosen layer moves with it, rather than being placed twice.\n const ids = new Set(chosen.map((node) => node.id))\n const nodes = chosen.filter(\n (node) =>\n !node.parentId || !ctx.graph.closest(node.parentId, (ancestor) => ids.has(ancestor.id))\n )\n const boxes = nodes.map((node) => {\n const bounds = getAbsolutePositionFull(node, ctx.graph)\n return {\n id: node.id,\n x: bounds.boundX,\n y: bounds.boundY,\n width: bounds.width,\n height: bounds.height\n }\n })\n const targets = plan(boxes)\n const originals = collectNodePositions(\n ctx,\n nodes.map((node) => node.id)\n )\n for (const [index, node] of nodes.entries()) {\n const box = boxes[index]\n const target = targets.get(node.id)\n if (!target) continue\n const delta = parentLocalDelta(ctx, node, { x: target.x - box.x, y: target.y - box.y })\n if (delta) ctx.graph.updateNode(node.id, { x: node.x + delta.x, y: node.y + delta.y })\n }\n commitPositionChange(ctx, label, originals)\n ctx.requestRender()\n }\n\n /** Figma's Tidy Up: lines layers up in rows and columns with even spacing. */\n function tidyNodes(nodeIds: string[]) {\n placeBoxes(nodeIds, 'Tidy up', tidyPositions)\n }\n\n /** Figma's Pack Horizontal and Pack Vertical: layers edge to edge, with no gap. */\n function packNodes(nodeIds: string[], axis: Axis) {\n placeBoxes(nodeIds, 'Pack', (boxes) => packPositions(boxes, axis))\n }\n\n const { flipNodes, rotateNodes } = createFlipRotateActions(ctx)\n const arrange = createArrangeActions(ctx)\n\n /** Whether ELK's layouts take these layers: ones that can be tidied, sharing a parent. */\n function canAutoArrangeNodes(nodeIds: string[]): boolean {\n return canArrangeNodes(nodeIds) && arrange.canAutoArrangeNodes(nodeIds)\n }\n\n return {\n alignNodes,\n arrangeNodes: arrange.arrangeNodes,\n canArrangeNodes,\n canAutoArrangeNodes,\n canDistributeNodes,\n distributeNodes,\n selectionSpacing,\n setSelectionSpacing,\n flipNodes,\n packNodes,\n rotateNodes,\n tidyNodes\n }\n}\n"],"mappings":";;;;;;;;;AAeA,SAAS,mBACP,KACA,KACA,MACA,OACQ;CACR,IAAI,UAAU,OAAO,OAAO;CAC5B,IAAI,UAAU,UAAU,QAAQ,MAAM,OAAO,IAAI,OAAO;CACxD,OAAO,MAAM;AACf;AAEA,SAAS,gBACP,KACA,MACA,MACA,OACA;CACA,MAAM,SAAS,KAAK,WAAW,IAAI,MAAM,QAAQ,KAAK,QAAQ,IAAI,KAAA;CAClE,MAAM,KAAK,QAAQ,SAAS;CAC5B,MAAM,KAAK,QAAQ,UAAU;CAE7B,IAAI,SAAS,cACX,IAAI,MAAM,WAAW,KAAK,IAAI,EAAE,GAAG,mBAAmB,GAAG,IAAI,KAAK,OAAO,KAAK,EAAE,CAAC;MAEjF,IAAI,MAAM,WAAW,KAAK,IAAI,EAAE,GAAG,mBAAmB,GAAG,IAAI,KAAK,QAAQ,KAAK,EAAE,CAAC;AAEtF;AAEA,SAAS,mBACP,KACA,OACA,MACA,OACA;CACA,MAAM,+BAAe,IAAI,IAAoB;CAC7C,KAAK,MAAM,KAAK,OAAO,aAAa,IAAI,EAAE,IAAI,IAAI,MAAM,oBAAoB,EAAE,EAAE,CAAC;CAEjF,MAAM,UAAU,OAAe,aAAa,IAAI,EAAE,KAAK;EAAE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I,KAAK;GACtD,OAAO;IACL,IAAI,KAAK;IACT,GAAG,OAAO;IACV,GAAG,OAAO;IACV,OAAO,OAAO;IACd,QAAQ,OAAO;GACjB;EACF,CAAC;EACD,MAAM,UAAU,KAAK,KAAK;EAC1B,MAAM,YAAY,qBAChB,KACA,MAAM,KAAK,SAAS,KAAK,EAAE,CAC7B;EACA,KAAK,MAAM,CAAC,OAAO,SAAS,MAAM,QAAQ,GAAG;GAC3C,MAAM,MAAM,MAAM;GAClB,MAAM,SAAS,QAAQ,IAAI,KAAK,EAAE;GAClC,IAAI,CAAC,QAAQ;GACb,MAAM,QAAQ,iBAAiB,KAAK,MAAM;IAAE,GAAG,OAAO,IAAI,IAAI;IAAG,GAAG,OAAO,IAAI,IAAI;GAAE,CAAC;GACtF,IAAI,OAAO,IAAI,MAAM,WAAW,KAAK,IAAI;IAAE,GAAG,KAAK,IAAI,MAAM;IAAG,GAAG,KAAK,IAAI,MAAM;GAAE,CAAC;EACvF;EACA,qBAAqB,KAAK,OAAO,SAAS;EAC1C,IAAI,cAAc;CACpB;;CAGA,SAAS,UAAU,SAAmB;EACpC,WAAW,SAAS,WAAW,aAAa;CAC9C;;CAGA,SAAS,UAAU,SAAmB,MAAY;EAChD,WAAW,SAAS,SAAS,UAAU,cAAc,OAAO,IAAI,CAAC;CACnE;CAEA,MAAM,EAAE,WAAW,gBAAgB,wBAAwB,GAAG;CAC9D,MAAM,UAAU,qBAAqB,GAAG;;CAGxC,SAAS,oBAAoB,SAA4B;EACvD,OAAO,gBAAgB,OAAO,KAAK,QAAQ,oBAAoB,OAAO;CACxE;CAEA,OAAO;EACL;EACA,cAAc,QAAQ;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"alignment.js","names":[],"sources":["../../src/editor/alignment.ts"],"sourcesContent":["import { sumBy } from 'es-toolkit'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport {\n getAbsolutePositionFull,\n getAxisAlignedWorldBounds,\n getWorldMatrix\n} from '@pairdraw/scene-graph/coordinate'\nimport { computeAbsoluteBounds } from '@pairdraw/scene-graph/geometry'\nimport Matrix from '@pairdraw/scene-graph/matrix'\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\n\nimport { createArrangeActions } from '#core/editor/alignment/arrange'\nimport { createFlipRotateActions } from '#core/editor/alignment/flip-rotate'\nimport { packPositions, tidyPositions, type PlacedBox } from '#core/editor/alignment/tidy'\n\nimport { collectNodePositions, commitPositionChange } from './history/position'\nimport type { EditorContext } from './types'\n\nfunction computeAlignTarget(\n min: number,\n max: number,\n size: number,\n align: 'min' | 'center' | 'max'\n): number {\n if (align === 'min') return min\n if (align === 'center') return (min + max) / 2 - size / 2\n return max - size\n}\n\nfunction alignSingleNode(\n ctx: EditorContext,\n node: SceneNode,\n axis: 'horizontal' | 'vertical',\n align: 'min' | 'center' | 'max'\n) {\n // The layer's drawn box against the parent's, so a rotated layer's visible edge lands on the\n // target as it does when several layers align together.\n const parent = node.parentId ? ctx.graph.getNode(node.parentId) : undefined\n const target = parent\n ? getAxisAlignedWorldBounds(parent, ctx.graph)\n : { x: 0, y: 0, width: 0, height: 0 }\n const box = getAxisAlignedWorldBounds(node, ctx.graph)\n const worldDelta =\n axis === 'horizontal'\n ? { x: computeAlignTarget(target.x, target.x + target.width, box.width, align) - box.x, y: 0 }\n : {\n x: 0,\n y: computeAlignTarget(target.y, target.y + target.height, box.height, align) - box.y\n }\n const localDelta = parentLocalDelta(ctx, node, worldDelta)\n if (!localDelta) return\n ctx.graph.updateNode(node.id, { x: node.x + localDelta.x, y: node.y + localDelta.y })\n}\n\nfunction alignMultipleNodes(\n ctx: EditorContext,\n nodes: SceneNode[],\n axis: 'horizontal' | 'vertical',\n align: 'min' | 'center' | 'max'\n) {\n // Each layer's drawn box, so a rotated layer's visible edge lands on the target.\n const boxes = new Map(nodes.map((n) => [n.id, getAxisAlignedWorldBounds(n, ctx.graph)]))\n const b = computeAbsoluteBounds(nodes, ctx.graph)\n\n for (const n of nodes) {\n const box = boxes.get(n.id)\n if (!box) continue\n const worldDelta =\n axis === 'horizontal'\n ? { x: computeAlignTarget(b.x, b.x + b.width, box.width, align) - box.x, y: 0 }\n : { x: 0, y: computeAlignTarget(b.y, b.y + b.height, box.height, align) - box.y }\n const localDelta = parentLocalDelta(ctx, n, worldDelta)\n if (!localDelta) continue\n ctx.graph.updateNode(n.id, { x: n.x + localDelta.x, y: n.y + localDelta.y })\n }\n}\n\nfunction canPositionNode(ctx: EditorContext, node: SceneNode): boolean {\n const parent = node.parentId ? ctx.graph.getNode(node.parentId) : undefined\n return !parent || parent.layoutMode === 'NONE' || node.layoutPositioning === 'ABSOLUTE'\n}\n\nfunction parentLocalDelta(ctx: EditorContext, node: SceneNode, worldDelta: Vector): Vector | null {\n const parent = node.parentId ? ctx.graph.getNode(node.parentId) : undefined\n if (!parent) return worldDelta\n const inverse = Matrix.invert(getWorldMatrix(parent, ctx.graph))\n if (!inverse) return null\n const origin = Matrix.mapPoint(inverse, { x: 0, y: 0 })\n const target = Matrix.mapPoint(inverse, worldDelta)\n return { x: target.x - origin.x, y: target.y - origin.y }\n}\n\nfunction distributeMultipleNodes(\n ctx: EditorContext,\n nodes: SceneNode[],\n axis: 'horizontal' | 'vertical'\n) {\n const bounds = new Map(nodes.map((node) => [node.id, getAbsolutePositionFull(node, ctx.graph)]))\n const coordinate = axis === 'horizontal' ? 'boundX' : 'boundY'\n const size = axis === 'horizontal' ? 'width' : 'height'\n const sorted = [...nodes].sort((a, b) => {\n const delta = (bounds.get(a.id)?.[coordinate] ?? 0) - (bounds.get(b.id)?.[coordinate] ?? 0)\n return delta || a.id.localeCompare(b.id)\n })\n const first = sorted[0]\n const last = sorted.at(-1)\n if (!last) return\n\n const start = bounds.get(first.id)?.[coordinate] ?? 0\n const end = (bounds.get(last.id)?.[coordinate] ?? 0) + (bounds.get(last.id)?.[size] ?? 0)\n const totalSize = sumBy(sorted, (node) => bounds.get(node.id)?.[size] ?? 0)\n const gap = (end - start - totalSize) / (sorted.length - 1)\n let cursor = start\n\n for (const node of sorted) {\n const nodeBounds = bounds.get(node.id)\n if (!nodeBounds) continue\n const distance = cursor - nodeBounds[coordinate]\n const localDelta = parentLocalDelta(\n ctx,\n node,\n axis === 'horizontal' ? { x: distance, y: 0 } : { x: 0, y: distance }\n )\n if (!localDelta) continue\n ctx.graph.updateNode(node.id, { x: node.x + localDelta.x, y: node.y + localDelta.y })\n cursor += nodeBounds[size] + gap\n }\n}\n\ntype Axis = 'horizontal' | 'vertical'\n\n/** The layers as one row or column, or null when they are not, as Figma's Spacing field reads them. */\nexport interface SelectionSpacing {\n axis: Axis\n /** The gaps between neighbours, in order along the axis. */\n gaps: number[]\n}\n\nfunction axisSpans(ctx: EditorContext, nodes: SceneNode[], axis: Axis) {\n const start = axis === 'horizontal' ? 'boundX' : 'boundY'\n const crossStart = axis === 'horizontal' ? 'boundY' : 'boundX'\n const size = axis === 'horizontal' ? 'width' : 'height'\n const crossSize = axis === 'horizontal' ? 'height' : 'width'\n return nodes\n .map((node) => {\n const bounds = getAbsolutePositionFull(node, ctx.graph)\n return {\n node,\n min: bounds[start],\n max: bounds[start] + bounds[size],\n crossMin: bounds[crossStart],\n crossMax: bounds[crossStart] + bounds[crossSize]\n }\n })\n .sort((a, b) => a.min - b.min || a.node.id.localeCompare(b.node.id))\n}\n\n/**\n * Layers form a row when none overlap along it and each overlaps its neighbour across it; layers\n * apart on both axes, like a grid or a diagonal, have no spacing in Figma.\n */\nfunction rowAlong(ctx: EditorContext, nodes: SceneNode[], axis: Axis) {\n const spans = axisSpans(ctx, nodes, axis)\n for (let index = 1; index < spans.length; index++) {\n const previous = spans[index - 1]\n const current = spans[index]\n if (current.min < previous.max) return null\n if (current.crossMin > previous.crossMax || current.crossMax < previous.crossMin) return null\n }\n return spans\n}\n\nexport function createAlignmentActions(ctx: EditorContext) {\n function positionableNodes(nodeIds: readonly string[]) {\n const nodes = nodeIds\n .map((id) => ctx.graph.getNode(id))\n .filter((node): node is SceneNode => node != null)\n return nodes.length >= 2 && nodes.every((node) => canPositionNode(ctx, node)) ? nodes : null\n }\n\n function selectionSpacing(nodeIds: readonly string[]): SelectionSpacing | null {\n const nodes = positionableNodes(nodeIds)\n if (!nodes) return null\n for (const axis of ['horizontal', 'vertical'] as const) {\n const spans = rowAlong(ctx, nodes, axis)\n if (spans)\n return { axis, gaps: spans.slice(1).map((span, index) => span.min - spans[index].max) }\n }\n return null\n }\n\n /** Spaces the row or column evenly by `gap`, keeping its first layer in place, as Figma does. */\n function setSelectionSpacing(nodeIds: readonly string[], gap: number) {\n const spacing = selectionSpacing(nodeIds)\n const nodes = positionableNodes(nodeIds)\n if (!spacing || !nodes) return\n const spans = rowAlong(ctx, nodes, spacing.axis)\n if (!spans) return\n const originals = collectNodePositions(\n ctx,\n nodes.map((node) => node.id)\n )\n let cursor = spans[0].max + gap\n for (const span of spans.slice(1)) {\n const distance = cursor - span.min\n const delta = parentLocalDelta(\n ctx,\n span.node,\n spacing.axis === 'horizontal' ? { x: distance, y: 0 } : { x: 0, y: distance }\n )\n if (delta)\n ctx.graph.updateNode(span.node.id, {\n x: span.node.x + delta.x,\n y: span.node.y + delta.y\n })\n cursor += span.max - span.min + gap\n }\n commitPositionChange(ctx, 'Change spacing', originals)\n ctx.requestRender()\n }\n\n function canDistributeNodes(nodeIds: string[]): boolean {\n const nodes = nodeIds\n .map((id) => ctx.graph.getNode(id))\n .filter((node): node is SceneNode => node != null)\n return nodes.length >= 3 && nodes.every((node) => canPositionNode(ctx, node))\n }\n\n function alignNodes(\n nodeIds: string[],\n axis: 'horizontal' | 'vertical',\n align: 'min' | 'center' | 'max'\n ) {\n if (nodeIds.length === 0) return\n\n const nodes = nodeIds\n .map((id) => ctx.graph.getNode(id))\n .filter((n): n is SceneNode => n != null)\n if (nodes.length === 0) return\n\n const originals = collectNodePositions(\n ctx,\n nodes.map((node) => node.id)\n )\n\n if (nodes.length === 1) {\n alignSingleNode(ctx, nodes[0], axis, align)\n } else {\n alignMultipleNodes(ctx, nodes, axis, align)\n }\n\n commitPositionChange(ctx, 'Align', originals)\n ctx.requestRender()\n }\n\n function distributeNodes(nodeIds: string[], axis: 'horizontal' | 'vertical') {\n const nodes = nodeIds\n .map((id) => ctx.graph.getNode(id))\n .filter((node): node is SceneNode => node != null)\n if (!canDistributeNodes(nodeIds)) return\n\n const originals = collectNodePositions(\n ctx,\n nodes.map((node) => node.id)\n )\n distributeMultipleNodes(ctx, nodes, axis)\n commitPositionChange(ctx, 'Distribute', originals)\n ctx.requestRender()\n }\n\n /** Whether layers can be tidied or packed: two or more that can move freely. */\n function canArrangeNodes(nodeIds: string[]): boolean {\n return positionableNodes(nodeIds) !== null\n }\n\n /** Moves each layer so its box on the page starts where `plan` puts it, as one undo step. */\n function placeBoxes(\n nodeIds: string[],\n label: string,\n plan: (boxes: PlacedBox[]) => Map<string, Vector>\n ) {\n const chosen = positionableNodes(nodeIds)\n if (!chosen) return\n // A layer inside another chosen layer moves with it, rather than being placed twice.\n const ids = new Set(chosen.map((node) => node.id))\n const nodes = chosen.filter(\n (node) =>\n !node.parentId || !ctx.graph.closest(node.parentId, (ancestor) => ids.has(ancestor.id))\n )\n const boxes = nodes.map((node) => {\n const bounds = getAbsolutePositionFull(node, ctx.graph)\n return {\n id: node.id,\n x: bounds.boundX,\n y: bounds.boundY,\n width: bounds.width,\n height: bounds.height\n }\n })\n const targets = plan(boxes)\n const originals = collectNodePositions(\n ctx,\n nodes.map((node) => node.id)\n )\n for (const [index, node] of nodes.entries()) {\n const box = boxes[index]\n const target = targets.get(node.id)\n if (!target) continue\n const delta = parentLocalDelta(ctx, node, { x: target.x - box.x, y: target.y - box.y })\n if (delta) ctx.graph.updateNode(node.id, { x: node.x + delta.x, y: node.y + delta.y })\n }\n commitPositionChange(ctx, label, originals)\n ctx.requestRender()\n }\n\n /** Figma's Tidy Up: lines layers up in rows and columns with even spacing. */\n function tidyNodes(nodeIds: string[]) {\n placeBoxes(nodeIds, 'Tidy up', tidyPositions)\n }\n\n /** Figma's Pack Horizontal and Pack Vertical: layers edge to edge, with no gap. */\n function packNodes(nodeIds: string[], axis: Axis) {\n placeBoxes(nodeIds, 'Pack', (boxes) => packPositions(boxes, axis))\n }\n\n const { flipNodes, rotateNodes } = createFlipRotateActions(ctx)\n const arrange = createArrangeActions(ctx)\n\n /** Whether ELK's layouts take these layers: ones that can be tidied, sharing a parent. */\n function canAutoArrangeNodes(nodeIds: string[]): boolean {\n return canArrangeNodes(nodeIds) && arrange.canAutoArrangeNodes(nodeIds)\n }\n\n return {\n alignNodes,\n arrangeNodes: arrange.arrangeNodes,\n canArrangeNodes,\n canAutoArrangeNodes,\n canDistributeNodes,\n distributeNodes,\n selectionSpacing,\n setSelectionSpacing,\n flipNodes,\n packNodes,\n rotateNodes,\n tidyNodes\n }\n}\n"],"mappings":";;;;;;;;;AAmBA,SAAS,mBACP,KACA,KACA,MACA,OACQ;CACR,IAAI,UAAU,OAAO,OAAO;CAC5B,IAAI,UAAU,UAAU,QAAQ,MAAM,OAAO,IAAI,OAAO;CACxD,OAAO,MAAM;AACf;AAEA,SAAS,gBACP,KACA,MACA,MACA,OACA;CAGA,MAAM,SAAS,KAAK,WAAW,IAAI,MAAM,QAAQ,KAAK,QAAQ,IAAI,KAAA;CAClE,MAAM,SAAS,SACX,0BAA0B,QAAQ,IAAI,KAAK,IAC3C;EAAE,GAAG;EAAG,GAAG;EAAG,OAAO;EAAG,QAAQ;CAAE;CACtC,MAAM,MAAM,0BAA0B,MAAM,IAAI,KAAK;CAQrD,MAAM,aAAa,iBAAiB,KAAK,MANvC,SAAS,eACL;EAAE,GAAG,mBAAmB,OAAO,GAAG,OAAO,IAAI,OAAO,OAAO,IAAI,OAAO,KAAK,IAAI,IAAI;EAAG,GAAG;CAAE,IAC3F;EACE,GAAG;EACH,GAAG,mBAAmB,OAAO,GAAG,OAAO,IAAI,OAAO,QAAQ,IAAI,QAAQ,KAAK,IAAI,IAAI;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EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
@@ -15,7 +15,7 @@ declare function createUndoBridge(undoActions: UndoActions, selection: Selection
|
|
|
15
15
|
commitMove: (originals: Map<string, import("@pairdraw/scene-graph/primitives").Vector>) => void;
|
|
16
16
|
commitMoveWithReparent: (originals: Map<string, MovePlace>) => void;
|
|
17
17
|
commitDuplicateMove: (rootIds: string[], previousSelection: Set<string>) => void;
|
|
18
|
-
commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<import("@pairdraw/scene-graph").SceneNode, "
|
|
18
|
+
commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<import("@pairdraw/scene-graph").SceneNode, "vectorNetwork" | "fillGeometry" | "strokeGeometry" | "derivedTextGlyphs" | "strokes" | "textPathData" | "textPathBox">>) => void;
|
|
19
19
|
commitGroupResize: (nodeId: string, origRect: import("@pairdraw/scene-graph/primitives").Rect, origChildren: Map<string, import("@pairdraw/scene-graph/resize").ResizeSnapshot>) => void;
|
|
20
20
|
commitRotation: (nodeId: string, origRotation: number) => void;
|
|
21
21
|
commitNodeUpdate: (nodeId: string, previous: Partial<import("@pairdraw/scene-graph").SceneNode>, label?: string) => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"detach.d.ts","names":[],"sources":["../../../src/editor/clipboard/detach.ts"],"mappings":";;;;;;iBAagB,0BACd,OAAO,YACP,MAAM,YACL,QAAQ;;;;;
|
|
1
|
+
{"version":3,"file":"detach.d.ts","names":[],"sources":["../../../src/editor/clipboard/detach.ts"],"mappings":";;;;;;iBAagB,0BACd,OAAO,YACP,MAAM,YACL,QAAQ;;;;;iBA6BK,oBAAoB,MAAM,WAAW,WAAW,QAAQ"}
|
|
@@ -17,9 +17,9 @@ function resolvedClipboardBindings(graph, node) {
|
|
|
17
17
|
return Object.keys(resolved).length > 0 ? structuredClone(resolved) : void 0;
|
|
18
18
|
}
|
|
19
19
|
function unlinkedRun(run) {
|
|
20
|
-
const { boundVariables, textStyleId, fillStyleId } = run.style;
|
|
21
|
-
if (!boundVariables && !textStyleId && !fillStyleId) return run;
|
|
22
|
-
const { boundVariables: _variables, textStyleId: _text, fillStyleId: _fill, ...style } = run.style;
|
|
20
|
+
const { boundVariables, variableBindingScales, textStyleId, fillStyleId } = run.style;
|
|
21
|
+
if (!boundVariables && !variableBindingScales && !textStyleId && !fillStyleId) return run;
|
|
22
|
+
const { boundVariables: _variables, variableBindingScales: _scales, textStyleId: _text, fillStyleId: _fill, ...style } = run.style;
|
|
23
23
|
return {
|
|
24
24
|
...run,
|
|
25
25
|
style
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"detach.js","names":[],"sources":["../../../src/editor/clipboard/detach.ts"],"sourcesContent":["import type { SceneGraph, SceneNode, StyleRun } from '@pairdraw/scene-graph'\nimport { STYLE_LINK_FIELDS } from '@pairdraw/scene-graph/shared-styles'\nimport {\n resolvedNumericBindings,\n resolvedPaintBindings,\n resolvedRunBindings,\n resolvedValueBindings\n} from '@pairdraw/scene-graph/variables'\n\n/**\n * The values a layer's variable bindings show in the document it is copied from, for the fields\n * whose stored value differs, so pasting it unlinked elsewhere keeps how it looked.\n */\nexport function resolvedClipboardBindings(\n graph: SceneGraph,\n node: SceneNode\n): Partial<SceneNode> | undefined {\n const bindsCharacters = node.styleRuns.some((run) => run.style.boundVariables)\n if (Object.keys(node.boundVariables).length === 0 && !bindsCharacters) return undefined\n const resolved = {\n ...resolvedNumericBindings(graph, node),\n ...resolvedValueBindings(graph, node),\n ...resolvedRunBindings(graph, node),\n ...resolvedPaintBindings(graph, node)\n }\n return Object.keys(resolved).length > 0 ? structuredClone(resolved) : undefined\n}\n\nfunction unlinkedRun(run: StyleRun): StyleRun {\n const { boundVariables, textStyleId, fillStyleId } = run.style\n if (!boundVariables && !textStyleId && !fillStyleId) return run\n const {
|
|
1
|
+
{"version":3,"file":"detach.js","names":[],"sources":["../../../src/editor/clipboard/detach.ts"],"sourcesContent":["import type { SceneGraph, SceneNode, StyleRun } from '@pairdraw/scene-graph'\nimport { STYLE_LINK_FIELDS } from '@pairdraw/scene-graph/shared-styles'\nimport {\n resolvedNumericBindings,\n resolvedPaintBindings,\n resolvedRunBindings,\n resolvedValueBindings\n} from '@pairdraw/scene-graph/variables'\n\n/**\n * The values a layer's variable bindings show in the document it is copied from, for the fields\n * whose stored value differs, so pasting it unlinked elsewhere keeps how it looked.\n */\nexport function resolvedClipboardBindings(\n graph: SceneGraph,\n node: SceneNode\n): Partial<SceneNode> | undefined {\n const bindsCharacters = node.styleRuns.some((run) => run.style.boundVariables)\n if (Object.keys(node.boundVariables).length === 0 && !bindsCharacters) return undefined\n const resolved = {\n ...resolvedNumericBindings(graph, node),\n ...resolvedValueBindings(graph, node),\n ...resolvedRunBindings(graph, node),\n ...resolvedPaintBindings(graph, node)\n }\n return Object.keys(resolved).length > 0 ? structuredClone(resolved) : undefined\n}\n\nfunction unlinkedRun(run: StyleRun): StyleRun {\n const { boundVariables, variableBindingScales, textStyleId, fillStyleId } = run.style\n if (!boundVariables && !variableBindingScales && !textStyleId && !fillStyleId) return run\n const {\n boundVariables: _variables,\n variableBindingScales: _scales,\n textStyleId: _text,\n fillStyleId: _fill,\n ...style\n } = run.style\n return { ...run, style }\n}\n\n/**\n * A copied layer pasted as is: the values it showed, with no variables, modes, or styles,\n * which belong to the document it came from.\n */\nexport function detachClipboardNode(node: SceneNode, resolved?: Partial<SceneNode>): void {\n if (resolved) Object.assign(node, structuredClone(resolved))\n node.boundVariables = {}\n node.variableBindingScales = {}\n node.variableModes = {}\n for (const field of STYLE_LINK_FIELDS) node[field] = null\n node.styleRuns = node.styleRuns.map(unlinkedRun)\n}\n"],"mappings":";;;;;;;AAaA,SAAgB,0BACd,OACA,MACgC;CAChC,MAAM,kBAAkB,KAAK,UAAU,MAAM,QAAQ,IAAI,MAAM,cAAc;CAC7E,IAAI,OAAO,KAAK,KAAK,cAAc,CAAC,CAAC,WAAW,KAAK,CAAC,iBAAiB,OAAO,KAAA;CAC9E,MAAM,WAAW;EACf,GAAG,wBAAwB,OAAO,IAAI;EACtC,GAAG,sBAAsB,OAAO,IAAI;EACpC,GAAG,oBAAoB,OAAO,IAAI;EAClC,GAAG,sBAAsB,OAAO,IAAI;CACtC;CACA,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,IAAI,gBAAgB,QAAQ,IAAI,KAAA;AACxE;AAEA,SAAS,YAAY,KAAyB;CAC5C,MAAM,EAAE,gBAAgB,uBAAuB,aAAa,gBAAgB,IAAI;CAChF,IAAI,CAAC,kBAAkB,CAAC,yBAAyB,CAAC,eAAe,CAAC,aAAa,OAAO;CACtF,MAAM,EACJ,gBAAgB,YAChB,uBAAuB,SACvB,aAAa,OACb,aAAa,OACb,GAAG,UACD,IAAI;CACR,OAAO;EAAE,GAAG;EAAK;CAAM;AACzB;;;;;AAMA,SAAgB,oBAAoB,MAAiB,UAAqC;CACxF,IAAI,UAAU,OAAO,OAAO,MAAM,gBAAgB,QAAQ,CAAC;CAC3D,KAAK,iBAAiB,CAAC;CACvB,KAAK,wBAAwB,CAAC;CAC9B,KAAK,gBAAgB,CAAC;CACtB,KAAK,MAAM,SAAS,mBAAmB,KAAK,SAAS;CACrD,KAAK,YAAY,KAAK,UAAU,IAAI,WAAW;AACjD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"properties.d.ts","names":[],"sources":["../../../../src/editor/clipboard/paste/properties.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"properties.d.ts","names":[],"sources":["../../../../src/editor/clipboard/paste/properties.ts"],"mappings":";;;;;iBAwGgB,sBAAsB,QAAQ;;;;;iBAQ9B,sBACd,QAAQ,WACR,QAAQ,YACP,QAAQ;;;;;iBAoBK,oBAAoB,QAAQ,WAAW,OAAO,aAAa;iBAkC3D,iCACd,KAAK,eACL,qBAAqB,YAAY,SAAS,QAAQ,YAAY,yBAC9D,oBAAoB,sBAAsB;EAuDW,8BAAA,UAAA,sBAAoB;EAe5B,0BAAA,iBAAS"}
|
|
@@ -4,6 +4,7 @@ import { importClipboardDependenciesWithUndo } from "../dependencies.js";
|
|
|
4
4
|
import { loadBoundFonts } from "../../text/bound-fonts.js";
|
|
5
5
|
import { parseFigmaClipboard } from "@pairdraw/fig/clipboard";
|
|
6
6
|
import { materializeFigFragment } from "@pairdraw/fig";
|
|
7
|
+
import { withBoundBindingScales } from "@pairdraw/scene-graph/variables";
|
|
7
8
|
import { STYLE_LINK_FIELDS, sharedStyleRefKey } from "@pairdraw/scene-graph/shared-styles";
|
|
8
9
|
import { omitBy, pick } from "es-toolkit/object";
|
|
9
10
|
import { AUTO_LAYOUT_FIELDS, CORNER_FIELDS, PAINT_FIELDS, STROKE_FIELDS, TEXT_STYLE_FIELDS } from "@pairdraw/scene-graph/fields";
|
|
@@ -70,12 +71,13 @@ function pastedFields(source, target) {
|
|
|
70
71
|
function runsWithout(runs, fields) {
|
|
71
72
|
const overrides = new Set([...fields].flatMap((field) => RUN_OVERRIDES[field] ?? [field]));
|
|
72
73
|
return runs.flatMap((run) => {
|
|
73
|
-
|
|
74
|
+
let style = omitBy(run.style, (_, key) => overrides.has(key));
|
|
74
75
|
if (style.boundVariables) {
|
|
75
76
|
const bound = omitBy(style.boundVariables, (_, key) => fields.has(key));
|
|
76
77
|
if (Object.keys(bound).length > 0) style.boundVariables = bound;
|
|
77
78
|
else delete style.boundVariables;
|
|
78
79
|
}
|
|
80
|
+
style = withBoundBindingScales(style);
|
|
79
81
|
return Object.keys(style).length > 0 ? [{
|
|
80
82
|
...run,
|
|
81
83
|
style
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"properties.js","names":[],"sources":["../../../../src/editor/clipboard/paste/properties.ts"],"sourcesContent":["import { noop } from 'es-toolkit/function'\nimport { omitBy, pick } from 'es-toolkit/object'\n\nimport { materializeFigFragment } from '@pairdraw/fig'\nimport { parseFigmaClipboard } from '@pairdraw/fig/clipboard'\nimport type { SceneGraph, SceneNode, StyleRun } from '@pairdraw/scene-graph'\nimport {\n AUTO_LAYOUT_FIELDS,\n CORNER_FIELDS,\n PAINT_FIELDS,\n STROKE_FIELDS,\n TEXT_STYLE_FIELDS\n} from '@pairdraw/scene-graph/fields'\nimport { STYLE_LINK_FIELDS, sharedStyleRefKey } from '@pairdraw/scene-graph/shared-styles'\n\nimport { parsePairdrawClipboard } from '#core/clipboard'\nimport { importClipboardDependenciesWithUndo } from '#core/editor/clipboard/dependencies'\nimport type { ClipboardSnapshot } from '#core/editor/clipboard/snapshot'\nimport { loadBoundFonts } from '#core/editor/text/bound-fonts'\nimport type { EditorContext } from '#core/editor/types'\nimport { reconcileVariableLayouts } from '#core/layout/variables'\n\n/**\n * Figma's Paste properties: the look of the one copied layer, applied to others. Position, size,\n * rotation, name, constraints, export settings, content, and structure never move.\n */\n\nconst APPEARANCE_FIELDS = [\n ...PAINT_FIELDS,\n ...STROKE_FIELDS,\n sharedStyleRefKey('fill'),\n sharedStyleRefKey('stroke'),\n sharedStyleRefKey('effect')\n] as const\n\n/** Auto layout and layout grids, which move only from one frame to another. */\nconst FRAME_FIELDS = [\n ...AUTO_LAYOUT_FIELDS,\n 'itemReverseZIndex',\n 'layoutGrids',\n sharedStyleRefKey('grid')\n] as const satisfies ReadonlyArray<keyof SceneNode>\n\n/** Text style fields, which move only from one text layer to another. */\nconst TEXT_FIELDS = [...TEXT_STYLE_FIELDS, sharedStyleRefKey('text')] as const\n\nconst NO_APPEARANCE: ReadonlySet<SceneNode['type']> = new Set(['CANVAS', 'SECTION', 'CONNECTOR'])\nconst FRAME_TYPES: ReadonlySet<SceneNode['type']> = new Set(['FRAME', 'COMPONENT', 'INSTANCE'])\n\ntype PastedField =\n | (typeof APPEARANCE_FIELDS)[number]\n | (typeof CORNER_FIELDS)[number]\n | (typeof FRAME_FIELDS)[number]\n | (typeof TEXT_FIELDS)[number]\n\n/** The run overrides that replace a text layer's own value of each pasted field. */\nconst RUN_OVERRIDES: Readonly<Record<string, readonly string[]>> = {\n fills: ['fills', 'fillStyleId'],\n fillStyleId: ['fills', 'fillStyleId'],\n textStyleId: ['textStyleId']\n}\n\nfunction fieldOf(key: string): string {\n return key.split('/')[0] ?? key\n}\n\n/** Fields a text layer's character runs override, which Figma treats as mixed and leaves alone. */\nfunction mixedFields(source: SceneNode): Set<string> {\n const mixed = new Set<string>()\n for (const run of source.styleRuns) {\n for (const key of Object.keys(run.style)) mixed.add(key)\n for (const key of Object.keys(run.style.boundVariables ?? {})) mixed.add(key)\n }\n if (mixed.has('fills') || mixed.has('fillStyleId')) mixed.add('fills').add('fillStyleId')\n return mixed\n}\n\nfunction pastedFields(source: SceneNode, target: SceneNode): PastedField[] {\n const fields: PastedField[] = [...APPEARANCE_FIELDS]\n // A text layer has no corners in Figma.\n if (source.type !== 'TEXT' && target.type !== 'TEXT') fields.push(...CORNER_FIELDS)\n if (FRAME_TYPES.has(source.type) && FRAME_TYPES.has(target.type)) fields.push(...FRAME_FIELDS)\n if (source.type === 'TEXT' && target.type === 'TEXT') fields.push(...TEXT_FIELDS)\n const mixed = source.type === 'TEXT' ? mixedFields(source) : new Set<string>()\n return fields.filter((field) => !mixed.has(field))\n}\n\n/** The target's runs without the overrides the pasted fields replace, so they cover all of it. */\nfunction runsWithout(runs: StyleRun[], fields: ReadonlySet<string>): StyleRun[] {\n const overrides = new Set([...fields].flatMap((field) => RUN_OVERRIDES[field] ?? [field]))\n return runs.flatMap((run) => {\n const style = omitBy(run.style, (_, key) => overrides.has(key))\n if (style.boundVariables) {\n const bound = omitBy(style.boundVariables, (_, key) => fields.has(key))\n if (Object.keys(bound).length > 0) style.boundVariables = bound\n else delete style.boundVariables\n }\n return Object.keys(style).length > 0 ? [{ ...run, style }] : []\n })\n}\n\n/** Whether `source` is a layer whose look can be pasted. */\nexport function hasPastableProperties(source: SceneNode): boolean {\n return !NO_APPEARANCE.has(source.type)\n}\n\n/**\n * What pasting the look of `source` onto `target` changes, or null when the target takes none (a\n * page, a section, a connector). Locked layers take it, as in Figma.\n */\nexport function pastedPropertyChanges(\n source: SceneNode,\n target: SceneNode\n): Partial<SceneNode> | null {\n if (!hasPastableProperties(source) || NO_APPEARANCE.has(target.type)) return null\n const fields = pastedFields(source, target)\n const changes: Partial<SceneNode> = structuredClone(pick(source, fields))\n const replaced = new Set<string>(fields)\n if (target.type === 'TEXT' && target.styleRuns.length > 0)\n changes.styleRuns = runsWithout(target.styleRuns, replaced)\n // Bindings of the fields being replaced go; the copied ones come in.\n const kept = Object.entries(target.boundVariables).filter(([key]) => !replaced.has(fieldOf(key)))\n const brought = Object.entries(source.boundVariables).filter(([key]) =>\n replaced.has(fieldOf(key))\n )\n changes.boundVariables = Object.fromEntries([...kept, ...brought])\n return changes\n}\n\n/**\n * A copied layer from another document, keeping only the style and variable links `graph` can\n * resolve; the copied values stay either way.\n */\nexport function withResolvableLinks(source: SceneNode, graph: SceneGraph): SceneNode {\n const resolved = structuredClone(source)\n for (const field of STYLE_LINK_FIELDS) {\n const id = resolved[field]\n if (id && !graph.getNode(id)) resolved[field] = null\n }\n resolved.boundVariables = Object.fromEntries(\n Object.entries(resolved.boundVariables).filter(([, id]) => graph.variables.has(id))\n )\n return resolved\n}\n\ninterface PastedSource {\n node: SceneNode\n images: ReadonlyMap<string, Uint8Array>\n}\n\n/** The one layer a clipboard payload from another app or tab holds, or null. */\nasync function sourceFromHTML(html: string): Promise<PastedSource | null> {\n const pairdraw = parsePairdrawClipboard(html)\n if (pairdraw) {\n const { nodes, images } = pairdraw\n return nodes.length === 1 ? { node: nodes[0], images } : null\n }\n const figma = await parseFigmaClipboard(html)\n if (!figma) return null\n const fragment = materializeFigFragment(figma.nodes, figma.blobs, {\n missingComponent: 'detach-empty'\n })\n const { rootIds } = fragment\n const node = rootIds.length === 1 ? fragment.graph.getNode(rootIds[0]) : undefined\n return node ? { node, images: fragment.graph.images } : null\n}\n\nexport function createClipboardPropertiesActions(\n ctx: EditorContext,\n updateNodeWithUndo: (id: string, changes: Partial<SceneNode>, label?: string) => void,\n loadFontsForNodes: (nodeIds: string[]) => Promise<unknown>\n) {\n const LABEL = 'Paste properties'\n\n function targets(): SceneNode[] {\n return [...ctx.state.selectedIds].flatMap((id) => {\n const node = ctx.graph.getNode(id)\n return node && !NO_APPEARANCE.has(node.type) ? [node] : []\n })\n }\n\n /** Applies the look of `source` to `targets` in the running batch; returns the changed ids. */\n function apply(\n source: SceneNode,\n images: ReadonlyMap<string, Uint8Array>,\n nodes: SceneNode[]\n ): string[] {\n for (const paint of [...source.fills, ...source.strokes]) {\n const bytes = paint.imageHash ? images.get(paint.imageHash) : undefined\n if (paint.imageHash && bytes && !ctx.graph.images.has(paint.imageHash))\n ctx.graph.images.set(paint.imageHash, bytes)\n }\n return nodes.flatMap((target) => {\n const changes = pastedPropertyChanges(source, target)\n if (!changes) return []\n updateNodeWithUndo(target.id, changes, LABEL)\n return [target.id]\n })\n }\n\n /**\n * Resolves the bindings brought onto `changed` against this document's variables, whose values\n * can differ from the copied ones, now and again on redo after the pasted values return.\n */\n function resolveBindings(changed: string[]) {\n const resolve = () =>\n loadBoundFonts(ctx, reconcileVariableLayouts(ctx.graph, { subtrees: changed }))\n resolve()\n // Undoing the paste puts back every field it set, so this step has nothing of its own to undo.\n ctx.undo.push({ label: LABEL, forward: resolve, inverse: noop })\n }\n\n async function finish(changed: string[]): Promise<number> {\n if (changed.length > 0) {\n await loadFontsForNodes(changed)\n ctx.requestRender()\n }\n return changed.length\n }\n\n /**\n * Paste properties from a copy made in this app: the look of its one layer, with the styles and\n * variables it uses, onto every selected layer in one undo step. Returns how many changed.\n * From another document, a collection or style this one has by name is used, not added again.\n */\n async function pastePropertiesFromSnapshot(snapshot: ClipboardSnapshot): Promise<number> {\n const nodes = targets()\n if (snapshot.nodes.length !== 1 || !hasPastableProperties(snapshot.nodes[0])) return 0\n if (nodes.length === 0) return 0\n const changed = ctx.undo.runBatch(LABEL, () => {\n const dependencies = importClipboardDependenciesWithUndo(ctx, snapshot, { mode: 'import' })\n const [source] = dependencies.nodes\n const pasted = apply(source, snapshot.images, nodes)\n if (dependencies.resolveBindings && pasted.length > 0) resolveBindings(pasted)\n return pasted\n })\n return finish(changed)\n }\n\n /** Paste properties from clipboard HTML, such as a Figma copy; links it cannot resolve drop. */\n async function pastePropertiesFromHTML(html: string): Promise<number> {\n const nodes = targets()\n if (nodes.length === 0) return 0\n const source = await sourceFromHTML(html)\n if (!source || !hasPastableProperties(source.node)) return 0\n const resolved = withResolvableLinks(source.node, ctx.graph)\n const changed = ctx.undo.runBatch(LABEL, () => apply(resolved, source.images, nodes))\n return finish(changed)\n }\n\n return { pastePropertiesFromSnapshot, pastePropertiesFromHTML }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,MAAM,oBAAoB;CACxB,GAAG;CACH,GAAG;CACH,kBAAkB,MAAM;CACxB,kBAAkB,QAAQ;CAC1B,kBAAkB,QAAQ;AAC5B;;AAGA,MAAM,eAAe;CACnB,GAAG;CACH;CACA;CACA,kBAAkB,MAAM;AAC1B;;AAGA,MAAM,cAAc,CAAC,GAAG,mBAAmB,kBAAkB,MAAM,CAAC;AAEpE,MAAM,gCAAgD,IAAI,IAAI;CAAC;CAAU;CAAW;AAAW,CAAC;AAChG,MAAM,8BAA8C,IAAI,IAAI;CAAC;CAAS;CAAa;AAAU,CAAC;;AAS9F,MAAM,gBAA6D;CACjE,OAAO,CAAC,SAAS,aAAa;CAC9B,aAAa,CAAC,SAAS,aAAa;CACpC,aAAa,CAAC,aAAa;AAC7B;AAEA,SAAS,QAAQ,KAAqB;CACpC,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC,MAAM;AAC9B;;AAGA,SAAS,YAAY,QAAgC;CACnD,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,OAAO,OAAO,WAAW;EAClC,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,KAAK,GAAG,MAAM,IAAI,GAAG;EACvD,KAAK,MAAM,OAAO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,IAAI,KAAK,KAAK;GAAE,OAAO;GAAO,SAAS;GAAS,SAAS;EAAK,CAAC;CACjE;CAEA,eAAe,OAAO,SAAoC;EACxD,IAAI,QAAQ,SAAS,GAAG;GACtB,MAAM,kBAAkB,OAAO;GAC/B,IAAI,cAAc;EACpB;EACA,OAAO,QAAQ;CACjB;;;;;;CAOA,eAAe,4BAA4B,UAA8C;EACvF,MAAM,QAAQ,QAAQ;EACtB,IAAI,SAAS,MAAM,WAAW,KAAK,CAAC,sBAAsB,SAAS,MAAM,EAAE,GAAG,OAAO;EACrF,IAAI,MAAM,WAAW,GAAG,OAAO;EAQ/B,OAAO,OAPS,IAAI,KAAK,SAAS,aAAa;GAC7C,MAAM,eAAe,oCAAoC,KAAK,UAAU,EAAE,MAAM,SAAS,CAAC;GAC1F,MAAM,CAAC,UAAU,aAAa;GAC9B,MAAM,SAAS,MAAM,QAAQ,SAAS,QAAQ,KAAK;GACnD,IAAI,aAAa,mBAAmB,OAAO,SAAS,GAAG,gBAAgB,MAAM;GAC7E,OAAO;EACT,CACoB,CAAC;CACvB;;CAGA,eAAe,wBAAwB,MAA+B;EACpE,MAAM,QAAQ,QAAQ;EACtB,IAAI,MAAM,WAAW,GAAG,OAAO;EAC/B,MAAM,SAAS,MAAM,eAAe,IAAI;EACxC,IAAI,CAAC,UAAU,CAAC,sBAAsB,OAAO,IAAI,GAAG,OAAO;EAC3D,MAAM,WAAW,oBAAoB,OAAO,MAAM,IAAI,KAAK;EAE3D,OAAO,OADS,IAAI,KAAK,SAAS,aAAa,MAAM,UAAU,OAAO,QAAQ,KAAK,CAC/D,CAAC;CACvB;CAEA,OAAO;EAAE;EAA6B;CAAwB;AAChE"}
|
|
1
|
+
{"version":3,"file":"properties.js","names":[],"sources":["../../../../src/editor/clipboard/paste/properties.ts"],"sourcesContent":["import { noop } from 'es-toolkit/function'\nimport { omitBy, pick } from 'es-toolkit/object'\n\nimport { materializeFigFragment } from '@pairdraw/fig'\nimport { parseFigmaClipboard } from '@pairdraw/fig/clipboard'\nimport type { SceneGraph, SceneNode, StyleRun } from '@pairdraw/scene-graph'\nimport {\n AUTO_LAYOUT_FIELDS,\n CORNER_FIELDS,\n PAINT_FIELDS,\n STROKE_FIELDS,\n TEXT_STYLE_FIELDS\n} from '@pairdraw/scene-graph/fields'\nimport { STYLE_LINK_FIELDS, sharedStyleRefKey } from '@pairdraw/scene-graph/shared-styles'\nimport { withBoundBindingScales } from '@pairdraw/scene-graph/variables'\n\nimport { parsePairdrawClipboard } from '#core/clipboard'\nimport { importClipboardDependenciesWithUndo } from '#core/editor/clipboard/dependencies'\nimport type { ClipboardSnapshot } from '#core/editor/clipboard/snapshot'\nimport { loadBoundFonts } from '#core/editor/text/bound-fonts'\nimport type { EditorContext } from '#core/editor/types'\nimport { reconcileVariableLayouts } from '#core/layout/variables'\n\n/**\n * Figma's Paste properties: the look of the one copied layer, applied to others. Position, size,\n * rotation, name, constraints, export settings, content, and structure never move.\n */\n\nconst APPEARANCE_FIELDS = [\n ...PAINT_FIELDS,\n ...STROKE_FIELDS,\n sharedStyleRefKey('fill'),\n sharedStyleRefKey('stroke'),\n sharedStyleRefKey('effect')\n] as const\n\n/** Auto layout and layout grids, which move only from one frame to another. */\nconst FRAME_FIELDS = [\n ...AUTO_LAYOUT_FIELDS,\n 'itemReverseZIndex',\n 'layoutGrids',\n sharedStyleRefKey('grid')\n] as const satisfies ReadonlyArray<keyof SceneNode>\n\n/** Text style fields, which move only from one text layer to another. */\nconst TEXT_FIELDS = [...TEXT_STYLE_FIELDS, sharedStyleRefKey('text')] as const\n\nconst NO_APPEARANCE: ReadonlySet<SceneNode['type']> = new Set(['CANVAS', 'SECTION', 'CONNECTOR'])\nconst FRAME_TYPES: ReadonlySet<SceneNode['type']> = new Set(['FRAME', 'COMPONENT', 'INSTANCE'])\n\ntype PastedField =\n | (typeof APPEARANCE_FIELDS)[number]\n | (typeof CORNER_FIELDS)[number]\n | (typeof FRAME_FIELDS)[number]\n | (typeof TEXT_FIELDS)[number]\n\n/** The run overrides that replace a text layer's own value of each pasted field. */\nconst RUN_OVERRIDES: Readonly<Record<string, readonly string[]>> = {\n fills: ['fills', 'fillStyleId'],\n fillStyleId: ['fills', 'fillStyleId'],\n textStyleId: ['textStyleId']\n}\n\nfunction fieldOf(key: string): string {\n return key.split('/')[0] ?? key\n}\n\n/** Fields a text layer's character runs override, which Figma treats as mixed and leaves alone. */\nfunction mixedFields(source: SceneNode): Set<string> {\n const mixed = new Set<string>()\n for (const run of source.styleRuns) {\n for (const key of Object.keys(run.style)) mixed.add(key)\n for (const key of Object.keys(run.style.boundVariables ?? {})) mixed.add(key)\n }\n if (mixed.has('fills') || mixed.has('fillStyleId')) mixed.add('fills').add('fillStyleId')\n return mixed\n}\n\nfunction pastedFields(source: SceneNode, target: SceneNode): PastedField[] {\n const fields: PastedField[] = [...APPEARANCE_FIELDS]\n // A text layer has no corners in Figma.\n if (source.type !== 'TEXT' && target.type !== 'TEXT') fields.push(...CORNER_FIELDS)\n if (FRAME_TYPES.has(source.type) && FRAME_TYPES.has(target.type)) fields.push(...FRAME_FIELDS)\n if (source.type === 'TEXT' && target.type === 'TEXT') fields.push(...TEXT_FIELDS)\n const mixed = source.type === 'TEXT' ? mixedFields(source) : new Set<string>()\n return fields.filter((field) => !mixed.has(field))\n}\n\n/** The target's runs without the overrides the pasted fields replace, so they cover all of it. */\nfunction runsWithout(runs: StyleRun[], fields: ReadonlySet<string>): StyleRun[] {\n const overrides = new Set([...fields].flatMap((field) => RUN_OVERRIDES[field] ?? [field]))\n return runs.flatMap((run) => {\n let style = omitBy(run.style, (_, key) => overrides.has(key))\n if (style.boundVariables) {\n const bound = omitBy(style.boundVariables, (_, key) => fields.has(key))\n if (Object.keys(bound).length > 0) style.boundVariables = bound\n else delete style.boundVariables\n }\n style = withBoundBindingScales(style)\n return Object.keys(style).length > 0 ? [{ ...run, style }] : []\n })\n}\n\n/** Whether `source` is a layer whose look can be pasted. */\nexport function hasPastableProperties(source: SceneNode): boolean {\n return !NO_APPEARANCE.has(source.type)\n}\n\n/**\n * What pasting the look of `source` onto `target` changes, or null when the target takes none (a\n * page, a section, a connector). Locked layers take it, as in Figma.\n */\nexport function pastedPropertyChanges(\n source: SceneNode,\n target: SceneNode\n): Partial<SceneNode> | null {\n if (!hasPastableProperties(source) || NO_APPEARANCE.has(target.type)) return null\n const fields = pastedFields(source, target)\n const changes: Partial<SceneNode> = structuredClone(pick(source, fields))\n const replaced = new Set<string>(fields)\n if (target.type === 'TEXT' && target.styleRuns.length > 0)\n changes.styleRuns = runsWithout(target.styleRuns, replaced)\n // Bindings of the fields being replaced go; the copied ones come in.\n const kept = Object.entries(target.boundVariables).filter(([key]) => !replaced.has(fieldOf(key)))\n const brought = Object.entries(source.boundVariables).filter(([key]) =>\n replaced.has(fieldOf(key))\n )\n changes.boundVariables = Object.fromEntries([...kept, ...brought])\n return changes\n}\n\n/**\n * A copied layer from another document, keeping only the style and variable links `graph` can\n * resolve; the copied values stay either way.\n */\nexport function withResolvableLinks(source: SceneNode, graph: SceneGraph): SceneNode {\n const resolved = structuredClone(source)\n for (const field of STYLE_LINK_FIELDS) {\n const id = resolved[field]\n if (id && !graph.getNode(id)) resolved[field] = null\n }\n resolved.boundVariables = Object.fromEntries(\n Object.entries(resolved.boundVariables).filter(([, id]) => graph.variables.has(id))\n )\n return resolved\n}\n\ninterface PastedSource {\n node: SceneNode\n images: ReadonlyMap<string, Uint8Array>\n}\n\n/** The one layer a clipboard payload from another app or tab holds, or null. */\nasync function sourceFromHTML(html: string): Promise<PastedSource | null> {\n const pairdraw = parsePairdrawClipboard(html)\n if (pairdraw) {\n const { nodes, images } = pairdraw\n return nodes.length === 1 ? { node: nodes[0], images } : null\n }\n const figma = await parseFigmaClipboard(html)\n if (!figma) return null\n const fragment = materializeFigFragment(figma.nodes, figma.blobs, {\n missingComponent: 'detach-empty'\n })\n const { rootIds } = fragment\n const node = rootIds.length === 1 ? fragment.graph.getNode(rootIds[0]) : undefined\n return node ? { node, images: fragment.graph.images } : null\n}\n\nexport function createClipboardPropertiesActions(\n ctx: EditorContext,\n updateNodeWithUndo: (id: string, changes: Partial<SceneNode>, label?: string) => void,\n loadFontsForNodes: (nodeIds: string[]) => Promise<unknown>\n) {\n const LABEL = 'Paste properties'\n\n function targets(): SceneNode[] {\n return [...ctx.state.selectedIds].flatMap((id) => {\n const node = ctx.graph.getNode(id)\n return node && !NO_APPEARANCE.has(node.type) ? [node] : []\n })\n }\n\n /** Applies the look of `source` to `targets` in the running batch; returns the changed ids. */\n function apply(\n source: SceneNode,\n images: ReadonlyMap<string, Uint8Array>,\n nodes: SceneNode[]\n ): string[] {\n for (const paint of [...source.fills, ...source.strokes]) {\n const bytes = paint.imageHash ? images.get(paint.imageHash) : undefined\n if (paint.imageHash && bytes && !ctx.graph.images.has(paint.imageHash))\n ctx.graph.images.set(paint.imageHash, bytes)\n }\n return nodes.flatMap((target) => {\n const changes = pastedPropertyChanges(source, target)\n if (!changes) return []\n updateNodeWithUndo(target.id, changes, LABEL)\n return [target.id]\n })\n }\n\n /**\n * Resolves the bindings brought onto `changed` against this document's variables, whose values\n * can differ from the copied ones, now and again on redo after the pasted values return.\n */\n function resolveBindings(changed: string[]) {\n const resolve = () =>\n loadBoundFonts(ctx, reconcileVariableLayouts(ctx.graph, { subtrees: changed }))\n resolve()\n // Undoing the paste puts back every field it set, so this step has nothing of its own to undo.\n ctx.undo.push({ label: LABEL, forward: resolve, inverse: noop })\n }\n\n async function finish(changed: string[]): Promise<number> {\n if (changed.length > 0) {\n await loadFontsForNodes(changed)\n ctx.requestRender()\n }\n return changed.length\n }\n\n /**\n * Paste properties from a copy made in this app: the look of its one layer, with the styles and\n * variables it uses, onto every selected layer in one undo step. Returns how many changed.\n * From another document, a collection or style this one has by name is used, not added again.\n */\n async function pastePropertiesFromSnapshot(snapshot: ClipboardSnapshot): Promise<number> {\n const nodes = targets()\n if (snapshot.nodes.length !== 1 || !hasPastableProperties(snapshot.nodes[0])) return 0\n if (nodes.length === 0) return 0\n const changed = ctx.undo.runBatch(LABEL, () => {\n const dependencies = importClipboardDependenciesWithUndo(ctx, snapshot, { mode: 'import' })\n const [source] = dependencies.nodes\n const pasted = apply(source, snapshot.images, nodes)\n if (dependencies.resolveBindings && pasted.length > 0) resolveBindings(pasted)\n return pasted\n })\n return finish(changed)\n }\n\n /** Paste properties from clipboard HTML, such as a Figma copy; links it cannot resolve drop. */\n async function pastePropertiesFromHTML(html: string): Promise<number> {\n const nodes = targets()\n if (nodes.length === 0) return 0\n const source = await sourceFromHTML(html)\n if (!source || !hasPastableProperties(source.node)) return 0\n const resolved = withResolvableLinks(source.node, ctx.graph)\n const changed = ctx.undo.runBatch(LABEL, () => apply(resolved, source.images, nodes))\n return finish(changed)\n }\n\n return { pastePropertiesFromSnapshot, pastePropertiesFromHTML }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,oBAAoB;CACxB,GAAG;CACH,GAAG;CACH,kBAAkB,MAAM;CACxB,kBAAkB,QAAQ;CAC1B,kBAAkB,QAAQ;AAC5B;;AAGA,MAAM,eAAe;CACnB,GAAG;CACH;CACA;CACA,kBAAkB,MAAM;AAC1B;;AAGA,MAAM,cAAc,CAAC,GAAG,mBAAmB,kBAAkB,MAAM,CAAC;AAEpE,MAAM,gCAAgD,IAAI,IAAI;CAAC;CAAU;CAAW;AAAW,CAAC;AAChG,MAAM,8BAA8C,IAAI,IAAI;CAAC;CAAS;CAAa;AAAU,CAAC;;AAS9F,MAAM,gBAA6D;CACjE,OAAO,CAAC,SAAS,aAAa;CAC9B,aAAa,CAAC,SAAS,aAAa;CACpC,aAAa,CAAC,aAAa;AAC7B;AAEA,SAAS,QAAQ,KAAqB;CACpC,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC,MAAM;AAC9B;;AAGA,SAAS,YAAY,QAAgC;CACnD,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,OAAO,OAAO,WAAW;EAClC,KAAK,MAAM,OAAO,OAAO,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(originals: Map<string, import("@pairdraw/scene-graph/primitives").Vector>) => void;
|
|
184
184
|
commitMoveWithReparent: (originals: Map<string, MovePlace>) => void;
|
|
185
185
|
commitDuplicateMove: (rootIds: string[], previousSelection: Set<string>) => void;
|
|
186
|
-
commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<SceneNode, "
|
|
186
|
+
commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<SceneNode, "vectorNetwork" | "fillGeometry" | "strokeGeometry" | "derivedTextGlyphs" | "strokes" | "textPathData" | "textPathBox">>) => void;
|
|
187
187
|
commitGroupResize: (nodeId: string, origRect: import("@pairdraw/scene-graph/primitives").Rect, origChildren: Map<string, import("@pairdraw/scene-graph/resize").ResizeSnapshot>) => void;
|
|
188
188
|
commitRotation: (nodeId: string, origRotation: number) => void;
|
|
189
189
|
snapshotPage: (pageId?: string) => PageSnapshot;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"structure.d.ts","names":[],"sources":["../../src/editor/structure.ts"],"mappings":";;;;;;;iBA6BgB,uBAAuB,KAAK;EA8Ed,aAAA;
|
|
1
|
+
{"version":3,"file":"structure.d.ts","names":[],"sources":["../../src/editor/structure.ts"],"mappings":";;;;;;;iBA6BgB,uBAAuB,KAAK;EA8Ed,aAAA;EA2CY,wBAAA,SAAA,2BAAA;EAIP,iBAAA,SAAA;EAkBT,aAAA,YAAM;;;;;;EAvFmB,2BAAA,eAAA,aAAW,WAAa;EAIlC,kBAAA,cAAA;EAIC,kBAAA,eAAA;EAII,sBAAA,eAAA;EAME,wBAAA,eAAA;2CAAA;EA7Dd,gBAAA,mBAAQ;EAuBvB,2BAAA,kEAAiD,eACjD,aAAW,aACb,QAAQ;EAKkB,mBAAA,eAAA;EAIH,gBAAA,eAAA;EAKC,iBAAA,eAAA;;;;;;;;EA/CT,aAAA;EA6JA,kBAAA;EACA,kBAAA;EACI,qBAAA,WAAA"}
|
package/dist/editor/structure.js
CHANGED
|
@@ -84,12 +84,13 @@ function createStructureActions(ctx) {
|
|
|
84
84
|
}).sort((a, b) => a.index - b.index);
|
|
85
85
|
if (origins.length === 0) return;
|
|
86
86
|
const parentIds = new Set(origins.map((origin) => origin.parentId));
|
|
87
|
+
const prevSelection = new Set(ctx.state.selectedIds);
|
|
87
88
|
const move = () => {
|
|
88
89
|
for (const { id } of origins) ctx.graph.reparentNode(id, pageId);
|
|
89
90
|
for (const parentId of parentIds) ctx.runLayoutForNode(parentId);
|
|
91
|
+
ctx.setSelectedIds(/* @__PURE__ */ new Set());
|
|
90
92
|
};
|
|
91
93
|
move();
|
|
92
|
-
ctx.setSelectedIds(/* @__PURE__ */ new Set());
|
|
93
94
|
ctx.undo.push({
|
|
94
95
|
label: "Move to page",
|
|
95
96
|
forward: move,
|
|
@@ -99,6 +100,7 @@ function createStructureActions(ctx) {
|
|
|
99
100
|
ctx.graph.updateNode(id, place);
|
|
100
101
|
}
|
|
101
102
|
for (const parentId of parentIds) ctx.runLayoutForNode(parentId);
|
|
103
|
+
ctx.setSelectedIds(new Set(prevSelection));
|
|
102
104
|
}
|
|
103
105
|
});
|
|
104
106
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"structure.js","names":["wrapSelectionInContainer","wrapSelectionInContainerImpl","wrapInAutoLayout","wrapInAutoLayoutImpl","booleanOperationSelected","booleanOperationSelectedImpl","ungroupSelected","flattenSelected","flattenSelectedImpl","outlineStrokeSelected","outlineStrokeSelectedImpl"],"sources":["../../src/editor/structure.ts"],"sourcesContent":["import { pick } from 'es-toolkit'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { TRANSFORM_FIELDS } from '@pairdraw/scene-graph/fields'\nimport { generatedFrameKind } from '@pairdraw/scene-graph/generated'\nimport { createsComponentCycle } from '@pairdraw/scene-graph/instances'\n\nimport { acceptingParent, acceptsChildren, prepareSlotEdits } from '#core/editor/components/slots'\nimport { fitEnclosingGroupsWithUndo } from '#core/editor/structure/group/bounds'\n\nimport { wrapInAutoLayout as wrapInAutoLayoutImpl } from './structure/auto-layout-wrap'\nimport {\n booleanOperationSelected as booleanOperationSelectedImpl,\n type BooleanOperation\n} from './structure/boolean'\nimport { wrapSelectionInContainer as wrapSelectionInContainerImpl } from './structure/container-wrap'\nimport { flattenSelected as flattenSelectedImpl } from './structure/flatten'\nimport { ungroupSelected as ungroupImpl } from './structure/group/ungroup'\nimport { createLayerTypeActions } from './structure/layer-type'\nimport { outlineStrokeSelected as outlineStrokeSelectedImpl } from './structure/outline-stroke'\nimport {\n defaultNodeName,\n previewRenamedNodes,\n type RenameSelectionOptions\n} from './structure/rename'\nimport { createStructureReorderActions } from './structure/reorder'\nimport { createStructureStateActions } from './structure/state'\nimport type { EditorContext } from './types'\n\nexport function createStructureActions(ctx: EditorContext) {\n const reorderActions = createStructureReorderActions(ctx)\n const stateActions = createStructureStateActions(ctx)\n const layerTypeActions = createLayerTypeActions(ctx)\n\n function isTopLevel(parentId: string | null): boolean {\n return !parentId || parentId === ctx.graph.rootId || parentId === ctx.state.currentPageId\n }\n\n /**\n * Moves layers under a new parent; refuses the locked part of an instance, and a layer that\n * would make a component contain itself, as Figma does.\n */\n function reparentNodes(nodeIds: string[], newParentId: string): boolean {\n const parent = ctx.graph.getNode(newParentId)\n // Sections only go into pages and other sections.\n const movable = nodeIds.filter(\n (id) =>\n (ctx.graph.getNode(id)?.type !== 'SECTION' ||\n !parent ||\n parent.type === 'CANVAS' ||\n parent.type === 'SECTION') &&\n !createsComponentCycle(ctx.graph, id, newParentId)\n )\n if (movable.length === 0) return true\n const parents = new Set([newParentId])\n for (const id of movable) {\n const current = ctx.graph.getNode(id)?.parentId\n if (current && current !== newParentId) parents.add(current)\n }\n if (!prepareSlotEdits(ctx, parents)) return false\n for (const id of movable) ctx.graph.reparentNode(id, newParentId)\n return true\n }\n\n function wrapSelectionInContainer(\n containerType: 'GROUP' | 'FRAME' | 'COMPONENT' | 'COMPONENT_SET',\n selectedNodes: SceneNode[],\n extraProps?: Partial<SceneNode>\n ) {\n return wrapSelectionInContainerImpl(ctx, containerType, selectedNodes, extraProps)\n }\n\n function wrapInAutoLayout(selectedNodes: SceneNode[]) {\n return wrapInAutoLayoutImpl(ctx, selectedNodes)\n }\n\n function groupSelected(selectedNodes: SceneNode[]) {\n return wrapSelectionInContainer('GROUP', selectedNodes)\n }\n\n /** Figma frames a selection without a fill or clipping, unlike a drawn frame. */\n function frameSelection(selectedNodes: SceneNode[]) {\n return wrapSelectionInContainer('FRAME', selectedNodes)\n }\n\n function booleanOperationSelected(selectedNodes: SceneNode[], operation: BooleanOperation) {\n return booleanOperationSelectedImpl(ctx, selectedNodes, operation)\n }\n\n function ungroupSelected(selectedNode: SceneNode | undefined) {\n ungroupImpl(ctx, selectedNode)\n }\n\n function flattenSelected(selectedNodes: SceneNode[]) {\n return flattenSelectedImpl(ctx, selectedNodes)\n }\n\n function outlineTextSelected(selectedNodes: SceneNode[]) {\n if (selectedNodes.length === 0 || selectedNodes.some((node) => node.type !== 'TEXT'))\n return null\n return flattenSelectedImpl(ctx, selectedNodes, { label: 'Outline text' })\n }\n\n function outlineStrokeSelected(selectedNodes: SceneNode[]) {\n return outlineStrokeSelectedImpl(ctx, selectedNodes)\n }\n\n function moveToPage(pageId: string) {\n const targetPage = ctx.graph.getNode(pageId)\n if (targetPage?.type !== 'CANVAS') return\n // Where each layer was, read before any of them moves: put back in this order, each lands at\n // its own index again.\n const origins = [...ctx.state.selectedIds]\n .flatMap((id) => {\n const node = ctx.graph.getNode(id)\n const parent = node?.parentId ? ctx.graph.getNode(node.parentId) : undefined\n if (!node || !parent || parent.id === pageId) return []\n const index = parent.childIds.indexOf(id)\n return [{ id, parentId: parent.id, index, place: pick(node, TRANSFORM_FIELDS) }]\n })\n .sort((a, b) => a.index - b.index)\n if (origins.length === 0) return\n const parentIds = new Set(origins.map((origin) => origin.parentId))\n const move = () => {\n for (const { id } of origins) ctx.graph.reparentNode(id, pageId)\n for (const parentId of parentIds) ctx.runLayoutForNode(parentId)\n }\n move()\n ctx.setSelectedIds(new Set())\n ctx.undo.push({\n label: 'Move to page',\n forward: move,\n inverse: () => {\n for (const { id, parentId, index, place } of origins) {\n ctx.graph.insertChildAt(id, parentId, index)\n ctx.graph.updateNode(id, place)\n }\n for (const parentId of parentIds) ctx.runLayoutForNode(parentId)\n }\n })\n }\n\n function selectedNodes(): SceneNode[] {\n return [...ctx.state.selectedIds]\n .map((id) => ctx.graph.getNode(id))\n .filter((node): node is SceneNode => node != null)\n }\n\n function previewRenameSelected(options: RenameSelectionOptions) {\n return previewRenamedNodes(selectedNodes(), options)\n }\n\n function renameSelected(options: RenameSelectionOptions) {\n const nodes = selectedNodes()\n if (nodes.length === 0) return\n const before = new Map(nodes.map((node) => [node.id, node.name]))\n const preview = previewRenamedNodes(nodes, options)\n if (preview.error) return\n const applyNames = (names: ReadonlyMap<string, string>) => {\n for (const [id, nextName] of names) ctx.graph.updateNode(id, { name: nextName })\n }\n\n applyNames(preview.names)\n ctx.undo.push({\n label: 'Rename selection',\n forward: () => applyNames(preview.names),\n inverse: () => applyNames(before)\n })\n }\n\n function renameNode(id: string, name: string) {\n const node = ctx.graph.getNode(id)\n if (!node) return\n const previous = { name: node.name, autoRename: node.autoRename }\n const next = name.trim() || defaultNodeName(node.type)\n if (next === previous.name) return\n // A layer named by its text, as a sticky note is, keeps the name it is given, as in FigJam.\n const namedByText = generatedFrameKind(node)?.namedByText ?? false\n const renamed = { name: next, autoRename: namedByText ? false : node.autoRename }\n ctx.graph.updateNode(id, renamed)\n ctx.undo.push({\n label: 'Rename',\n forward: () => ctx.graph.updateNode(id, renamed),\n inverse: () => ctx.graph.updateNode(id, previous)\n })\n }\n\n return {\n isTopLevel,\n acceptsChildren: (parentId: string) => acceptsChildren(ctx, parentId),\n acceptingParent: (parentId: string) => acceptingParent(ctx, parentId),\n fitEnclosingGroups: (parentIds: Iterable<string>) => fitEnclosingGroupsWithUndo(ctx, parentIds),\n ...reorderActions,\n reparentNodes,\n wrapSelectionInContainer,\n wrapInAutoLayout,\n groupSelected,\n frameSelection,\n ...layerTypeActions,\n booleanOperationSelected,\n ungroupSelected,\n flattenSelected,\n outlineTextSelected,\n outlineStrokeSelected,\n ...stateActions,\n moveToPage,\n previewRenameSelected,\n renameSelected,\n renameNode\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,SAAgB,uBAAuB,KAAoB;CACzD,MAAM,iBAAiB,8BAA8B,GAAG;CACxD,MAAM,eAAe,4BAA4B,GAAG;CACpD,MAAM,mBAAmB,uBAAuB,GAAG;CAEnD,SAAS,WAAW,UAAkC;EACpD,OAAO,CAAC,YAAY,aAAa,IAAI,MAAM,UAAU,aAAa,IAAI,MAAM;CAC9E;;;;;CAMA,SAAS,cAAc,SAAmB,aAA8B;EACtE,MAAM,SAAS,IAAI,MAAM,QAAQ,WAAW;EAE5C,MAAM,UAAU,QAAQ,QACrB,QACE,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE,SAAS,aAC/B,CAAC,UACD,OAAO,SAAS,YAChB,OAAO,SAAS,cAClB,CAAC,sBAAsB,IAAI,OAAO,IAAI,WAAW,CACrD;EACA,IAAI,QAAQ,WAAW,GAAG,OAAO;EACjC,MAAM,0BAAU,IAAI,IAAI,CAAC,WAAW,CAAC;EACrC,KAAK,MAAM,MAAM,SAAS;GACxB,MAAM,UAAU,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE;GACvC,IAAI,WAAW,YAAY,aAAa,QAAQ,IAAI,OAAO;EAC7D;EACA,IAAI,CAAC,iBAAiB,KAAK,OAAO,GAAG,OAAO;EAC5C,KAAK,MAAM,MAAM,SAAS,IAAI,MAAM,aAAa,IAAI,WAAW;EAChE,OAAO;CACT;CAEA,SAASA,2BACP,eACA,eACA,YACA;EACA,OAAOC,yBAA6B,KAAK,eAAe,eAAe,UAAU;CACnF;CAEA,SAASC,mBAAiB,eAA4B;EACpD,OAAOC,iBAAqB,KAAK,aAAa;CAChD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AO,IAAI,MAAM,QAAQ,EAAE;EACjC,IAAI,CAAC,MAAM;EACX,MAAM,WAAW;GAAE,MAAM,KAAK;GAAM,YAAY,KAAK;EAAW;EAChE,MAAM,OAAO,KAAK,KAAK,KAAK,gBAAgB,KAAK,IAAI;EACrD,IAAI,SAAS,SAAS,MAAM;EAG5B,MAAM,UAAU;GAAE,MAAM;GAAM,YADV,mBAAmB,IAAI,CAAC,EAAE,eAAe,QACL,QAAQ,KAAK;EAAW;EAChF,IAAI,MAAM,WAAW,IAAI,OAAO;EAChC,IAAI,KAAK,KAAK;GACZ,OAAO;GACP,eAAe,IAAI,MAAM,WAAW,IAAI,OAAO;GAC/C,eAAe,IAAI,MAAM,WAAW,IAAI,QAAQ;EAClD,CAAC;CACH;CAEA,OAAO;EACL;EACA,kBAAkB,aAAqB,gBAAgB,KAAK,QAAQ;EACpE,kBAAkB,aAAqB,gBAAgB,KAAK,QAAQ;EACpE,qBAAqB,cAAgC,2BAA2B,KAAK,SAAS;EAC9F,GAAG;EACH;EACA,0BAAA;EACA,kBAAA;EACA;EACA;EACA,GAAG;EACH,0BAAA;EACA,iBAAA;EACA,iBAAA;EACA;EACA,uBAAA;EACA,GAAG;EACH;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"structure.js","names":["wrapSelectionInContainer","wrapSelectionInContainerImpl","wrapInAutoLayout","wrapInAutoLayoutImpl","booleanOperationSelected","booleanOperationSelectedImpl","ungroupSelected","flattenSelected","flattenSelectedImpl","outlineStrokeSelected","outlineStrokeSelectedImpl"],"sources":["../../src/editor/structure.ts"],"sourcesContent":["import { pick } from 'es-toolkit'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { TRANSFORM_FIELDS } from '@pairdraw/scene-graph/fields'\nimport { generatedFrameKind } from '@pairdraw/scene-graph/generated'\nimport { createsComponentCycle } from '@pairdraw/scene-graph/instances'\n\nimport { acceptingParent, acceptsChildren, prepareSlotEdits } from '#core/editor/components/slots'\nimport { fitEnclosingGroupsWithUndo } from '#core/editor/structure/group/bounds'\n\nimport { wrapInAutoLayout as wrapInAutoLayoutImpl } from './structure/auto-layout-wrap'\nimport {\n booleanOperationSelected as booleanOperationSelectedImpl,\n type BooleanOperation\n} from './structure/boolean'\nimport { wrapSelectionInContainer as wrapSelectionInContainerImpl } from './structure/container-wrap'\nimport { flattenSelected as flattenSelectedImpl } from './structure/flatten'\nimport { ungroupSelected as ungroupImpl } from './structure/group/ungroup'\nimport { createLayerTypeActions } from './structure/layer-type'\nimport { outlineStrokeSelected as outlineStrokeSelectedImpl } from './structure/outline-stroke'\nimport {\n defaultNodeName,\n previewRenamedNodes,\n type RenameSelectionOptions\n} from './structure/rename'\nimport { createStructureReorderActions } from './structure/reorder'\nimport { createStructureStateActions } from './structure/state'\nimport type { EditorContext } from './types'\n\nexport function createStructureActions(ctx: EditorContext) {\n const reorderActions = createStructureReorderActions(ctx)\n const stateActions = createStructureStateActions(ctx)\n const layerTypeActions = createLayerTypeActions(ctx)\n\n function isTopLevel(parentId: string | null): boolean {\n return !parentId || parentId === ctx.graph.rootId || parentId === ctx.state.currentPageId\n }\n\n /**\n * Moves layers under a new parent; refuses the locked part of an instance, and a layer that\n * would make a component contain itself, as Figma does.\n */\n function reparentNodes(nodeIds: string[], newParentId: string): boolean {\n const parent = ctx.graph.getNode(newParentId)\n // Sections only go into pages and other sections.\n const movable = nodeIds.filter(\n (id) =>\n (ctx.graph.getNode(id)?.type !== 'SECTION' ||\n !parent ||\n parent.type === 'CANVAS' ||\n parent.type === 'SECTION') &&\n !createsComponentCycle(ctx.graph, id, newParentId)\n )\n if (movable.length === 0) return true\n const parents = new Set([newParentId])\n for (const id of movable) {\n const current = ctx.graph.getNode(id)?.parentId\n if (current && current !== newParentId) parents.add(current)\n }\n if (!prepareSlotEdits(ctx, parents)) return false\n for (const id of movable) ctx.graph.reparentNode(id, newParentId)\n return true\n }\n\n function wrapSelectionInContainer(\n containerType: 'GROUP' | 'FRAME' | 'COMPONENT' | 'COMPONENT_SET',\n selectedNodes: SceneNode[],\n extraProps?: Partial<SceneNode>\n ) {\n return wrapSelectionInContainerImpl(ctx, containerType, selectedNodes, extraProps)\n }\n\n function wrapInAutoLayout(selectedNodes: SceneNode[]) {\n return wrapInAutoLayoutImpl(ctx, selectedNodes)\n }\n\n function groupSelected(selectedNodes: SceneNode[]) {\n return wrapSelectionInContainer('GROUP', selectedNodes)\n }\n\n /** Figma frames a selection without a fill or clipping, unlike a drawn frame. */\n function frameSelection(selectedNodes: SceneNode[]) {\n return wrapSelectionInContainer('FRAME', selectedNodes)\n }\n\n function booleanOperationSelected(selectedNodes: SceneNode[], operation: BooleanOperation) {\n return booleanOperationSelectedImpl(ctx, selectedNodes, operation)\n }\n\n function ungroupSelected(selectedNode: SceneNode | undefined) {\n ungroupImpl(ctx, selectedNode)\n }\n\n function flattenSelected(selectedNodes: SceneNode[]) {\n return flattenSelectedImpl(ctx, selectedNodes)\n }\n\n function outlineTextSelected(selectedNodes: SceneNode[]) {\n if (selectedNodes.length === 0 || selectedNodes.some((node) => node.type !== 'TEXT'))\n return null\n return flattenSelectedImpl(ctx, selectedNodes, { label: 'Outline text' })\n }\n\n function outlineStrokeSelected(selectedNodes: SceneNode[]) {\n return outlineStrokeSelectedImpl(ctx, selectedNodes)\n }\n\n function moveToPage(pageId: string) {\n const targetPage = ctx.graph.getNode(pageId)\n if (targetPage?.type !== 'CANVAS') return\n // Where each layer was, read before any of them moves: put back in this order, each lands at\n // its own index again.\n const origins = [...ctx.state.selectedIds]\n .flatMap((id) => {\n const node = ctx.graph.getNode(id)\n const parent = node?.parentId ? ctx.graph.getNode(node.parentId) : undefined\n if (!node || !parent || parent.id === pageId) return []\n const index = parent.childIds.indexOf(id)\n return [{ id, parentId: parent.id, index, place: pick(node, TRANSFORM_FIELDS) }]\n })\n .sort((a, b) => a.index - b.index)\n if (origins.length === 0) return\n const parentIds = new Set(origins.map((origin) => origin.parentId))\n const prevSelection = new Set(ctx.state.selectedIds)\n const move = () => {\n for (const { id } of origins) ctx.graph.reparentNode(id, pageId)\n for (const parentId of parentIds) ctx.runLayoutForNode(parentId)\n ctx.setSelectedIds(new Set())\n }\n move()\n ctx.undo.push({\n label: 'Move to page',\n forward: move,\n inverse: () => {\n for (const { id, parentId, index, place } of origins) {\n ctx.graph.insertChildAt(id, parentId, index)\n ctx.graph.updateNode(id, place)\n }\n for (const parentId of parentIds) ctx.runLayoutForNode(parentId)\n ctx.setSelectedIds(new Set(prevSelection))\n }\n })\n }\n\n function selectedNodes(): SceneNode[] {\n return [...ctx.state.selectedIds]\n .map((id) => ctx.graph.getNode(id))\n .filter((node): node is SceneNode => node != null)\n }\n\n function previewRenameSelected(options: RenameSelectionOptions) {\n return previewRenamedNodes(selectedNodes(), options)\n }\n\n function renameSelected(options: RenameSelectionOptions) {\n const nodes = selectedNodes()\n if (nodes.length === 0) return\n const before = new Map(nodes.map((node) => [node.id, node.name]))\n const preview = previewRenamedNodes(nodes, options)\n if (preview.error) return\n const applyNames = (names: ReadonlyMap<string, string>) => {\n for (const [id, nextName] of names) ctx.graph.updateNode(id, { name: nextName })\n }\n\n applyNames(preview.names)\n ctx.undo.push({\n label: 'Rename selection',\n forward: () => applyNames(preview.names),\n inverse: () => applyNames(before)\n })\n }\n\n function renameNode(id: string, name: string) {\n const node = ctx.graph.getNode(id)\n if (!node) return\n const previous = { name: node.name, autoRename: node.autoRename }\n const next = name.trim() || defaultNodeName(node.type)\n if (next === previous.name) return\n // A layer named by its text, as a sticky note is, keeps the name it is given, as in FigJam.\n const namedByText = generatedFrameKind(node)?.namedByText ?? false\n const renamed = { name: next, autoRename: namedByText ? false : node.autoRename }\n ctx.graph.updateNode(id, renamed)\n ctx.undo.push({\n label: 'Rename',\n forward: () => ctx.graph.updateNode(id, renamed),\n inverse: () => ctx.graph.updateNode(id, previous)\n })\n }\n\n return {\n isTopLevel,\n acceptsChildren: (parentId: string) => acceptsChildren(ctx, parentId),\n acceptingParent: (parentId: string) => acceptingParent(ctx, parentId),\n fitEnclosingGroups: (parentIds: Iterable<string>) => fitEnclosingGroupsWithUndo(ctx, parentIds),\n ...reorderActions,\n reparentNodes,\n wrapSelectionInContainer,\n wrapInAutoLayout,\n groupSelected,\n frameSelection,\n ...layerTypeActions,\n booleanOperationSelected,\n ungroupSelected,\n flattenSelected,\n outlineTextSelected,\n outlineStrokeSelected,\n ...stateActions,\n moveToPage,\n previewRenameSelected,\n renameSelected,\n renameNode\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,SAAgB,uBAAuB,KAAoB;CACzD,MAAM,iBAAiB,8BAA8B,GAAG;CACxD,MAAM,eAAe,4BAA4B,GAAG;CACpD,MAAM,mBAAmB,uBAAuB,GAAG;CAEnD,SAAS,WAAW,UAAkC;EACpD,OAAO,CAAC,YAAY,aAAa,IAAI,MAAM,UAAU,aAAa,IAAI,MAAM;CAC9E;;;;;CAMA,SAAS,cAAc,SAAmB,aAA8B;EACtE,MAAM,SAAS,IAAI,MAAM,QAAQ,WAAW;EAE5C,MAAM,UAAU,QAAQ,QACrB,QACE,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE,SAAS,aAC/B,CAAC,UACD,OAAO,SAAS,YAChB,OAAO,SAAS,cAClB,CAAC,sBAAsB,IAAI,OAAO,IAAI,WAAW,CACrD;EACA,IAAI,QAAQ,WAAW,GAAG,OAAO;EACjC,MAAM,0BAAU,IAAI,IAAI,CAAC,WAAW,CAAC;EACrC,KAAK,MAAM,MAAM,SAAS;GACxB,MAAM,UAAU,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE;GACvC,IAAI,WAAW,YAAY,aAAa,QAAQ,IAAI,OAAO;EAC7D;EACA,IAAI,CAAC,iBAAiB,KAAK,OAAO,GAAG,OAAO;EAC5C,KAAK,MAAM,MAAM,SAAS,IAAI,MAAM,aAAa,IAAI,WAAW;EAChE,OAAO;CACT;CAEA,SAASA,2BACP,eACA,eACA,YACA;EACA,OAAOC,yBAA6B,KAAK,eAAe,eA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EAEA,WAAW,QAAQ,KAAK;EACxB,IAAI,KAAK,KAAK;GACZ,OAAO;GACP,eAAe,WAAW,QAAQ,KAAK;GACvC,eAAe,WAAW,MAAM;EAClC,CAAC;CACH;CAEA,SAAS,WAAW,IAAY,MAAc;EAC5C,MAAM,OAAO,IAAI,MAAM,QAAQ,EAAE;EACjC,IAAI,CAAC,MAAM;EACX,MAAM,WAAW;GAAE,MAAM,KAAK;GAAM,YAAY,KAAK;EAAW;EAChE,MAAM,OAAO,KAAK,KAAK,KAAK,gBAAgB,KAAK,IAAI;EACrD,IAAI,SAAS,SAAS,MAAM;EAG5B,MAAM,UAAU;GAAE,MAAM;GAAM,YADV,mBAAmB,IAAI,CAAC,EAAE,eAAe,QACL,QAAQ,KAAK;EAAW;EAChF,IAAI,MAAM,WAAW,IAAI,OAAO;EAChC,IAAI,KAAK,KAAK;GACZ,OAAO;GACP,eAAe,IAAI,MAAM,WAAW,IAAI,OAAO;GAC/C,eAAe,IAAI,MAAM,WAAW,IAAI,QAAQ;EAClD,CAAC;CACH;CAEA,OAAO;EACL;EACA,kBAAkB,aAAqB,gBAAgB,KAAK,QAAQ;EACpE,kBAAkB,aAAqB,gBAAgB,KAAK,QAAQ;EACpE,qBAAqB,cAAgC,2BAA2B,KAAK,SAAS;EAC9F,GAAG;EACH;EACA,0BAAA;EACA,kBAAA;EACA;EACA;EACA,GAAG;EACH,0BAAA;EACA,iBAAA;EACA,iBAAA;EACA;EACA,uBAAA;EACA,GAAG;EACH;EACA;EACA;EACA;CACF;AACF"}
|
package/dist/editor/viewport.js
CHANGED
|
@@ -59,7 +59,7 @@ function createViewportActions(ctx) {
|
|
|
59
59
|
const w = maxX - minX + 160;
|
|
60
60
|
const h = maxY - minY + 160;
|
|
61
61
|
const { width: viewW, height: viewH } = ctx.getViewportSize();
|
|
62
|
-
const zoom = Math.min(viewW / w, viewH / h, 1);
|
|
62
|
+
const zoom = Math.max(.02, Math.min(viewW / w, viewH / h, 1));
|
|
63
63
|
ctx.state.zoom = zoom;
|
|
64
64
|
ctx.state.panX = (viewW - w * zoom) / 2 - minX * zoom + padding * zoom;
|
|
65
65
|
ctx.state.panY = (viewH - h * zoom) / 2 - minY * zoom + padding * zoom;
|
|
@@ -122,7 +122,7 @@ function createViewportActions(ctx) {
|
|
|
122
122
|
if (ctx.state.selectedIds.size === 0) return;
|
|
123
123
|
const nodes = [...ctx.state.selectedIds].map((id) => ctx.graph.getNode(id)).filter((n) => n != null);
|
|
124
124
|
if (nodes.length === 0) return;
|
|
125
|
-
const b = computeAbsoluteBounds(nodes,
|
|
125
|
+
const b = computeAbsoluteBounds(nodes, ctx.graph);
|
|
126
126
|
zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height);
|
|
127
127
|
}
|
|
128
128
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"viewport.js","names":[],"sources":["../../src/editor/viewport.ts"],"sourcesContent":["import { getAxisAlignedWorldBounds } from '@pairdraw/scene-graph/coordinate'\nimport { computeBounds, computeAbsoluteBounds } from '@pairdraw/scene-graph/geometry'\n\nimport { ZOOM_DIVISOR, ZOOM_SCALE_MAX, ZOOM_SCALE_MIN } from '#core/constants'\nimport { emitNavigationTrace } from '#core/profiler'\n\nimport type { EditorContext } from './types'\n\n/** Space kept between revealed layers and the viewport edge. */\nconst REVEAL_MARGIN = 48\n\nexport function createViewportActions(ctx: EditorContext) {\n function currentViewport() {\n return { panX: ctx.state.panX, panY: ctx.state.panY, zoom: ctx.state.zoom }\n }\n\n function emitViewportChanged(previous: ReturnType<typeof currentViewport>) {\n const next = currentViewport()\n if (next.panX !== previous.panX || next.panY !== previous.panY || next.zoom !== previous.zoom) {\n emitNavigationTrace('viewport:changed', {\n panX: next.panX,\n panY: next.panY,\n zoom: next.zoom,\n previousPanX: previous.panX,\n previousPanY: previous.panY,\n previousZoom: previous.zoom\n })\n ctx.emitEditorEvent('viewport:changed', next, previous)\n }\n }\n\n function screenToCanvas(sx: number, sy: number) {\n return {\n x: (sx - ctx.state.panX) / ctx.state.zoom,\n y: (sy - ctx.state.panY) / ctx.state.zoom\n }\n }\n\n function setZoomAroundPoint(level: number, centerX: number, centerY: number) {\n const previous = currentViewport()\n const newZoom = Math.max(0.02, Math.min(256, level))\n ctx.state.panX = centerX - (centerX - ctx.state.panX) * (newZoom / ctx.state.zoom)\n ctx.state.panY = centerY - (centerY - ctx.state.panY) * (newZoom / ctx.state.zoom)\n ctx.state.zoom = newZoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function applyZoom(delta: number, centerX: number, centerY: number) {\n const factor = Math.min(\n ZOOM_SCALE_MAX,\n Math.max(ZOOM_SCALE_MIN, Math.exp(-delta / ZOOM_DIVISOR))\n )\n setZoomAroundPoint(ctx.state.zoom * factor, centerX, centerY)\n }\n\n function pan(dx: number, dy: number) {\n const previous = currentViewport()\n ctx.state.panX += dx\n ctx.state.panY += dy\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomToBounds(minX: number, minY: number, maxX: number, maxY: number) {\n const previous = currentViewport()\n const padding = 80\n const w = maxX - minX + padding * 2\n const h = maxY - minY + padding * 2\n\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const zoom = Math.min(viewW / w, viewH / h, 1)\n\n ctx.state.zoom = zoom\n ctx.state.panX = (viewW - w * zoom) / 2 - minX * zoom + padding * zoom\n ctx.state.panY = (viewH - h * zoom) / 2 - minY * zoom + padding * zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n /**\n * Fits the world area to the viewport, edge to edge and at any zoom, as a drag of Figma's zoom\n * tool does; `zoomToBounds` instead leaves a margin and never zooms past 100%. An area with no\n * width or height leaves the view alone.\n */\n function zoomToArea(minX: number, minY: number, maxX: number, maxY: number) {\n const width = maxX - minX\n const height = maxY - minY\n if (!(width > 0) || !(height > 0)) return\n const previous = currentViewport()\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const zoom = Math.max(0.02, Math.min(256, Math.min(viewW / width, viewH / height)))\n ctx.state.zoom = zoom\n ctx.state.panX = viewW / 2 - (minX + width / 2) * zoom\n ctx.state.panY = viewH / 2 - (minY + height / 2) * zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n /** Put the world point (x, y) at the center of the viewport, at `zoom` (the current one by default). */\n function centerOn(x: number, y: number, zoom = ctx.state.zoom) {\n const previous = currentViewport()\n const { width, height } = ctx.getViewportSize()\n const nextZoom = Math.max(0.02, Math.min(256, zoom))\n const panX = width / 2 - x * nextZoom\n const panY = height / 2 - y * nextZoom\n // Remote cursors are finite but unbounded; a point that overflows leaves the view alone.\n if (!Number.isFinite(panX) || !Number.isFinite(panY)) return\n ctx.state.zoom = nextZoom\n ctx.state.panX = panX\n ctx.state.panY = panY\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomToFit() {\n const nodes = ctx.graph.getChildren(ctx.state.currentPageId)\n if (nodes.length === 0) return\n\n const b = computeBounds(nodes)\n zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)\n }\n\n function zoomToLevel(level: number) {\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const centerX = (-ctx.state.panX + viewW / 2) / ctx.state.zoom\n const centerY = (-ctx.state.panY + viewH / 2) / ctx.state.zoom\n\n const previous = currentViewport()\n ctx.state.zoom = Math.max(0.02, Math.min(256, level))\n // Keep the world point at the center of the viewport where it was.\n ctx.state.panX = viewW / 2 - centerX * ctx.state.zoom\n ctx.state.panY = viewH / 2 - centerY * ctx.state.zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomTo100() {\n zoomToLevel(1)\n }\n\n function zoomToSelection() {\n if (ctx.state.selectedIds.size === 0) return\n\n const nodes = [...ctx.state.selectedIds]\n .map((id) => ctx.graph.getNode(id))\n .filter((n): n is NonNullable<typeof n> => n != null)\n if (nodes.length === 0) return\n\n const b = computeAbsoluteBounds(nodes, (id) => ctx.graph.getAbsolutePosition(id))\n zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)\n }\n\n /**\n * Brings layers into view: pans to center them when they fit at the current zoom and are not\n * already visible, and zooms out to fit them only when they do not fit.\n */\n function revealNodes(nodeIds: readonly string[], margin = REVEAL_MARGIN) {\n const nodes = nodeIds.map((id) => ctx.graph.getNode(id)).filter((node) => node !== undefined)\n if (nodes.length === 0) return\n const bounds = computeBounds(nodes.map((node) => getAxisAlignedWorldBounds(node, ctx.graph)))\n const { width, height } = ctx.getViewportSize()\n const { zoom, panX, panY } = ctx.state\n const fits =\n bounds.width * zoom <= width - margin * 2 && bounds.height * zoom <= height - margin * 2\n if (!fits) {\n zoomToBounds(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y + bounds.height)\n return\n }\n const left = bounds.x * zoom + panX\n const top = bounds.y * zoom + panY\n const right = left + bounds.width * zoom\n const bottom = top + bounds.height * zoom\n const visible =\n left >= margin && top >= margin && right <= width - margin && bottom <= height - margin\n if (visible) return\n pan(width / 2 - (left + right) / 2, height / 2 - (top + bottom) / 2)\n }\n\n return {\n revealNodes,\n screenToCanvas,\n setZoomAroundPoint,\n applyZoom,\n pan,\n zoomToBounds,\n zoomToArea,\n centerOn,\n zoomToFit,\n zoomTo100,\n zoomToLevel,\n zoomToSelection\n }\n}\n"],"mappings":";;;;;;AASA,MAAM,gBAAgB;AAEtB,SAAgB,sBAAsB,KAAoB;CACxD,SAAS,kBAAkB;EACzB,OAAO;GAAE,MAAM,IAAI,MAAM;GAAM,MAAM,IAAI,MAAM;GAAM,MAAM,IAAI,MAAM;EAAK;CAC5E;CAEA,SAAS,oBAAoB,UAA8C;EACzE,MAAM,OAAO,gBAAgB;EAC7B,IAAI,KAAK,SAAS,SAAS,QAAQ,KAAK,SAAS,SAAS,QAAQ,KAAK,SAAS,SAAS,MAAM;GAC7F,oBAAoB,oBAAoB;IACtC,MAAM,KAAK;IACX,MAAM,KAAK;IACX,MAAM,KAAK;IACX,cAAc,SAAS;IACvB,cAAc,SAAS;IACvB,cAAc,SAAS;GACzB,CA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AW,GAAG;EACxB,MAAM,SAAS,cAAc,MAAM,KAAK,SAAS,0BAA0B,MAAM,IAAI,KAAK,CAAC,CAAC;EAC5F,MAAM,EAAE,OAAO,WAAW,IAAI,gBAAgB;EAC9C,MAAM,EAAE,MAAM,MAAM,SAAS,IAAI;EAGjC,IAAI,EADF,OAAO,QAAQ,QAAQ,QAAQ,SAAS,KAAK,OAAO,SAAS,QAAQ,SAAS,SAAS,IAC9E;GACT,aAAa,OAAO,GAAG,OAAO,GAAG,OAAO,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,MAAM;GAClF;EACF;EACA,MAAM,OAAO,OAAO,IAAI,OAAO;EAC/B,MAAM,MAAM,OAAO,IAAI,OAAO;EAC9B,MAAM,QAAQ,OAAO,OAAO,QAAQ;EACpC,MAAM,SAAS,MAAM,OAAO,SAAS;EAGrC,IADE,QAAQ,UAAU,OAAO,UAAU,SAAS,QAAQ,UAAU,UAAU,SAAS,QACtE;EACb,IAAI,QAAQ,KAAK,OAAO,SAAS,GAAG,SAAS,KAAK,MAAM,UAAU,CAAC;CACrE;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"viewport.js","names":[],"sources":["../../src/editor/viewport.ts"],"sourcesContent":["import { getAxisAlignedWorldBounds } from '@pairdraw/scene-graph/coordinate'\nimport { computeBounds, computeAbsoluteBounds } from '@pairdraw/scene-graph/geometry'\n\nimport { ZOOM_DIVISOR, ZOOM_SCALE_MAX, ZOOM_SCALE_MIN } from '#core/constants'\nimport { emitNavigationTrace } from '#core/profiler'\n\nimport type { EditorContext } from './types'\n\n/** Space kept between revealed layers and the viewport edge. */\nconst REVEAL_MARGIN = 48\n\nexport function createViewportActions(ctx: EditorContext) {\n function currentViewport() {\n return { panX: ctx.state.panX, panY: ctx.state.panY, zoom: ctx.state.zoom }\n }\n\n function emitViewportChanged(previous: ReturnType<typeof currentViewport>) {\n const next = currentViewport()\n if (next.panX !== previous.panX || next.panY !== previous.panY || next.zoom !== previous.zoom) {\n emitNavigationTrace('viewport:changed', {\n panX: next.panX,\n panY: next.panY,\n zoom: next.zoom,\n previousPanX: previous.panX,\n previousPanY: previous.panY,\n previousZoom: previous.zoom\n })\n ctx.emitEditorEvent('viewport:changed', next, previous)\n }\n }\n\n function screenToCanvas(sx: number, sy: number) {\n return {\n x: (sx - ctx.state.panX) / ctx.state.zoom,\n y: (sy - ctx.state.panY) / ctx.state.zoom\n }\n }\n\n function setZoomAroundPoint(level: number, centerX: number, centerY: number) {\n const previous = currentViewport()\n const newZoom = Math.max(0.02, Math.min(256, level))\n ctx.state.panX = centerX - (centerX - ctx.state.panX) * (newZoom / ctx.state.zoom)\n ctx.state.panY = centerY - (centerY - ctx.state.panY) * (newZoom / ctx.state.zoom)\n ctx.state.zoom = newZoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function applyZoom(delta: number, centerX: number, centerY: number) {\n const factor = Math.min(\n ZOOM_SCALE_MAX,\n Math.max(ZOOM_SCALE_MIN, Math.exp(-delta / ZOOM_DIVISOR))\n )\n setZoomAroundPoint(ctx.state.zoom * factor, centerX, centerY)\n }\n\n function pan(dx: number, dy: number) {\n const previous = currentViewport()\n ctx.state.panX += dx\n ctx.state.panY += dy\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomToBounds(minX: number, minY: number, maxX: number, maxY: number) {\n const previous = currentViewport()\n const padding = 80\n const w = maxX - minX + padding * 2\n const h = maxY - minY + padding * 2\n\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const zoom = Math.max(0.02, Math.min(viewW / w, viewH / h, 1))\n\n ctx.state.zoom = zoom\n ctx.state.panX = (viewW - w * zoom) / 2 - minX * zoom + padding * zoom\n ctx.state.panY = (viewH - h * zoom) / 2 - minY * zoom + padding * zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n /**\n * Fits the world area to the viewport, edge to edge and at any zoom, as a drag of Figma's zoom\n * tool does; `zoomToBounds` instead leaves a margin and never zooms past 100%. An area with no\n * width or height leaves the view alone.\n */\n function zoomToArea(minX: number, minY: number, maxX: number, maxY: number) {\n const width = maxX - minX\n const height = maxY - minY\n if (!(width > 0) || !(height > 0)) return\n const previous = currentViewport()\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const zoom = Math.max(0.02, Math.min(256, Math.min(viewW / width, viewH / height)))\n ctx.state.zoom = zoom\n ctx.state.panX = viewW / 2 - (minX + width / 2) * zoom\n ctx.state.panY = viewH / 2 - (minY + height / 2) * zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n /** Put the world point (x, y) at the center of the viewport, at `zoom` (the current one by default). */\n function centerOn(x: number, y: number, zoom = ctx.state.zoom) {\n const previous = currentViewport()\n const { width, height } = ctx.getViewportSize()\n const nextZoom = Math.max(0.02, Math.min(256, zoom))\n const panX = width / 2 - x * nextZoom\n const panY = height / 2 - y * nextZoom\n // Remote cursors are finite but unbounded; a point that overflows leaves the view alone.\n if (!Number.isFinite(panX) || !Number.isFinite(panY)) return\n ctx.state.zoom = nextZoom\n ctx.state.panX = panX\n ctx.state.panY = panY\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomToFit() {\n const nodes = ctx.graph.getChildren(ctx.state.currentPageId)\n if (nodes.length === 0) return\n\n const b = computeBounds(nodes)\n zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)\n }\n\n function zoomToLevel(level: number) {\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const centerX = (-ctx.state.panX + viewW / 2) / ctx.state.zoom\n const centerY = (-ctx.state.panY + viewH / 2) / ctx.state.zoom\n\n const previous = currentViewport()\n ctx.state.zoom = Math.max(0.02, Math.min(256, level))\n // Keep the world point at the center of the viewport where it was.\n ctx.state.panX = viewW / 2 - centerX * ctx.state.zoom\n ctx.state.panY = viewH / 2 - centerY * ctx.state.zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomTo100() {\n zoomToLevel(1)\n }\n\n function zoomToSelection() {\n if (ctx.state.selectedIds.size === 0) return\n\n const nodes = [...ctx.state.selectedIds]\n .map((id) => ctx.graph.getNode(id))\n .filter((n): n is NonNullable<typeof n> => n != null)\n if (nodes.length === 0) return\n\n const b = computeAbsoluteBounds(nodes, ctx.graph)\n zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)\n }\n\n /**\n * Brings layers into view: pans to center them when they fit at the current zoom and are not\n * already visible, and zooms out to fit them only when they do not fit.\n */\n function revealNodes(nodeIds: readonly string[], margin = REVEAL_MARGIN) {\n const nodes = nodeIds.map((id) => ctx.graph.getNode(id)).filter((node) => node !== undefined)\n if (nodes.length === 0) return\n const bounds = computeBounds(nodes.map((node) => getAxisAlignedWorldBounds(node, ctx.graph)))\n const { width, height } = ctx.getViewportSize()\n const { zoom, panX, panY } = ctx.state\n const fits =\n bounds.width * zoom <= width - margin * 2 && bounds.height * zoom <= height - margin * 2\n if (!fits) {\n zoomToBounds(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y + bounds.height)\n return\n }\n const left = bounds.x * zoom + panX\n const top = bounds.y * zoom + panY\n const right = left + bounds.width * zoom\n const bottom = top + bounds.height * zoom\n const visible =\n left >= margin && top >= margin && right <= width - margin && bottom <= height - margin\n if (visible) return\n pan(width / 2 - (left + right) / 2, height / 2 - (top + bottom) / 2)\n }\n\n return {\n revealNodes,\n screenToCanvas,\n setZoomAroundPoint,\n applyZoom,\n pan,\n zoomToBounds,\n zoomToArea,\n centerOn,\n zoomToFit,\n zoomTo100,\n zoomToLevel,\n zoomToSelection\n }\n}\n"],"mappings":";;;;;;AASA,MAAM,gBAAgB;AAEtB,SAAgB,sBAAsB,KAAoB;CACxD,SAAS,kBAAkB;EACzB,OAAO;GAAE,MAAM,IAAI,MAAM;GAAM,MAAM,IAAI,MAAM;GAAM,MAAM,IAAI,MAAM;EAAK;CAC5E;CAEA,SAAS,oBAAoB,UAA8C;EACzE,MAA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,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM;CACtD;;;;;CAMA,SAAS,YAAY,SAA4B,SAAS,eAAe;EACvE,MAAM,QAAQ,QAAQ,KAAK,OAAO,IAAI,MAAM,QAAQ,EAAE,CAAC,CAAC,CAAC,QAAQ,SAAS,SAAS,KAAA,CAAS;EAC5F,IAAI,MAAM,WAAW,GAAG;EACxB,MAAM,SAAS,cAAc,MAAM,KAAK,SAAS,0BAA0B,MAAM,IAAI,KAAK,CAAC,CAAC;EAC5F,MAAM,EAAE,OAAO,WAAW,IAAI,gBAAgB;EAC9C,MAAM,EAAE,MAAM,MAAM,SAAS,IAAI;EAGjC,IAAI,EADF,OAAO,QAAQ,QAAQ,QAAQ,SAAS,KAAK,OAAO,SAAS,QAAQ,SAAS,SAAS,IAC9E;GACT,aAAa,OAAO,GAAG,OAAO,GAAG,OAAO,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,MAAM;GAClF;EACF;EACA,MAAM,OAAO,OAAO,IAAI,OAAO;EAC/B,MAAM,MAAM,OAAO,IAAI,OAAO;EAC9B,MAAM,QAAQ,OAAO,OAAO,QAAQ;EACpC,MAAM,SAAS,MAAM,OAAO,SAAS;EAGrC,IADE,QAAQ,UAAU,OAAO,UAAU,SAAS,QAAQ,UAAU,UAAU,SAAS,QACtE;EACb,IAAI,QAAQ,KAAK,OAAO,SAAS,GAAG,SAAS,KAAK,MAAM,UAAU,CAAC;CACrE;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
@@ -21,10 +21,45 @@ import { SceneGraph } from "@pairdraw/scene-graph";
|
|
|
21
21
|
import { GroupFitOptions } from "@pairdraw/scene-graph/group-bounds";
|
|
22
22
|
import { Rect, Vector } from "@pairdraw/scene-graph/primitives";
|
|
23
23
|
//#region src/figma-api/index.d.ts
|
|
24
|
+
/** A view of the document: its centre point and its zoom. */
|
|
25
|
+
interface FigmaViewport {
|
|
26
|
+
center: Vector;
|
|
27
|
+
zoom: number;
|
|
28
|
+
}
|
|
24
29
|
/** What a host passes to `FigmaAPI` beyond the document. */
|
|
25
30
|
interface FigmaAPIOptions {
|
|
26
31
|
/** Fetches the HTTP(S) URLs `figma.createImageAsync` loads; the global `fetch` by default. */
|
|
27
32
|
fetch?: ImageFetch;
|
|
33
|
+
/**
|
|
34
|
+
* Runs when a script puts the API on another page, so a host can show that page too. The host
|
|
35
|
+
* owns which page is on screen, and a plugin that switches page expects to see it switched.
|
|
36
|
+
*/
|
|
37
|
+
onPageChange?: (pageId: string) => void | Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Runs when a script moves the viewport, so a host can show the same view. A host owns the
|
|
40
|
+
* viewport on screen, and a plugin that pans or zooms expects to see the result.
|
|
41
|
+
*/
|
|
42
|
+
onViewportChange?: (viewport: FigmaViewport) => void;
|
|
43
|
+
/**
|
|
44
|
+
* The page the host already shows. Seeded here rather than assigned after construction, so a
|
|
45
|
+
* plain tool call does not ask the host to switch to the page it is already on.
|
|
46
|
+
*/
|
|
47
|
+
pageId?: string;
|
|
48
|
+
/**
|
|
49
|
+
* The view the host already shows, seeded for the same reason: a tool that only reads or draws
|
|
50
|
+
* must not move the viewport of whoever is looking at the document.
|
|
51
|
+
*/
|
|
52
|
+
viewport?: FigmaViewport;
|
|
53
|
+
/**
|
|
54
|
+
* Runs when a script sets the page selection, so a host can select those layers too. The host
|
|
55
|
+
* owns which layers are selected on screen, and a plugin that selects expects to see them selected.
|
|
56
|
+
*/
|
|
57
|
+
onSelectionChange?: (ids: readonly string[], pageId: string) => void;
|
|
58
|
+
/**
|
|
59
|
+
* The selection the host already shows, seeded for the same reason as the page and the viewport:
|
|
60
|
+
* a tool that only reads must not reselect what is already selected.
|
|
61
|
+
*/
|
|
62
|
+
selection?: readonly string[];
|
|
28
63
|
}
|
|
29
64
|
declare class FigmaAPI implements NodeProxyHost {
|
|
30
65
|
#private;
|
|
@@ -103,17 +138,17 @@ declare class FigmaAPI implements NodeProxyHost {
|
|
|
103
138
|
flatten(nodes: ReadonlyArray<FigmaNodeProxy>, parent?: FigmaNodeProxy, index?: number): FigmaVectorNode;
|
|
104
139
|
flatten(nodes: ReadonlyArray<BaseNode>, parent?: BaseNode & ChildrenMixin, index?: number): VectorNode;
|
|
105
140
|
private _viewport;
|
|
106
|
-
get viewport(): {
|
|
107
|
-
center: Vector;
|
|
108
|
-
zoom: number;
|
|
141
|
+
get viewport(): FigmaViewport & {
|
|
109
142
|
scrollAndZoomIntoView: (nodes: readonly {
|
|
110
143
|
absoluteBoundingBox: Rect;
|
|
111
144
|
}[]) => void;
|
|
112
145
|
};
|
|
113
|
-
set viewport(v:
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
146
|
+
set viewport(v: FigmaViewport);
|
|
147
|
+
/**
|
|
148
|
+
* Moves the viewport and puts the host on the same view. A tool that scrolls nodes into view
|
|
149
|
+
* does not call this: only a viewport a writer asks for moves the view of whoever is looking.
|
|
150
|
+
*/
|
|
151
|
+
private _showViewport;
|
|
117
152
|
createImage(data: Uint8Array): Image;
|
|
118
153
|
getImageByHash(hash: string): Image | null;
|
|
119
154
|
/** Fetches the image at `src` through the host's `fetch` and stores it as `createImage` does. */
|
|
@@ -149,5 +184,5 @@ declare class FigmaAPI implements NodeProxyHost {
|
|
|
149
184
|
changeBaseline?: (pageId: string) => SceneGraph | null;
|
|
150
185
|
}
|
|
151
186
|
//#endregion
|
|
152
|
-
export { type ExportImageOptions, FigmaAPI, FigmaAPIOptions, type FigmaBooleanOperationNode, type FigmaComponentNode, type FigmaComponentSetNode, type FigmaComposedColor, type FigmaConnectorNode, type FigmaEffect, type FigmaEllipseNode, type FigmaFont, type FigmaFontName, type FigmaFontNameInput, type FigmaFrameNode, type FigmaGroupNode, type FigmaInstanceNode, type FigmaLineNode, FigmaNodeProxy, type FigmaPolygonNode, type FigmaRectangleNode, type FigmaSectionNode, type FigmaShapeWithTextNode, type FigmaSlotNode, type FigmaStarNode, type FigmaTextNode, FigmaVariable, type FigmaVariableAlias, FigmaVariableCollection, type FigmaVariableValue, FigmaVariablesAPI, type FigmaVariationSettings, type FigmaVectorNode, type ImageFetch, ImageTooLargeError, MAX_IMAGE_FETCH_BYTES, flushPendingLayout, getPageBackgrounds, readBoundedImage, setPageBackgrounds };
|
|
187
|
+
export { type ExportImageOptions, FigmaAPI, FigmaAPIOptions, type FigmaBooleanOperationNode, type FigmaComponentNode, type FigmaComponentSetNode, type FigmaComposedColor, type FigmaConnectorNode, type FigmaEffect, type FigmaEllipseNode, type FigmaFont, type FigmaFontName, type FigmaFontNameInput, type FigmaFrameNode, type FigmaGroupNode, type FigmaInstanceNode, type FigmaLineNode, FigmaNodeProxy, type FigmaPolygonNode, type FigmaRectangleNode, type FigmaSectionNode, type FigmaShapeWithTextNode, type FigmaSlotNode, type FigmaStarNode, type FigmaTextNode, FigmaVariable, type FigmaVariableAlias, FigmaVariableCollection, type FigmaVariableValue, FigmaVariablesAPI, type FigmaVariationSettings, type FigmaVectorNode, FigmaViewport, type ImageFetch, ImageTooLargeError, MAX_IMAGE_FETCH_BYTES, flushPendingLayout, getPageBackgrounds, readBoundedImage, setPageBackgrounds };
|
|
153
188
|
//# sourceMappingURL=index.d.ts.map
|