@open-pencil/scene-graph 0.17.0-beta.4 → 0.17.0-beta.5
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/arrays.d.ts +17 -0
- package/dist/arrays.d.ts.map +1 -0
- package/dist/arrays.js +38 -0
- package/dist/arrays.js.map +1 -0
- package/dist/buffered-events.js +1 -1
- package/dist/buffered-events.js.map +1 -1
- package/dist/clipping.d.ts +7 -1
- package/dist/clipping.d.ts.map +1 -1
- package/dist/clipping.js +23 -19
- package/dist/clipping.js.map +1 -1
- package/dist/components/index.d.ts +2 -2
- package/dist/components/index.js +2 -2
- package/dist/components/properties.d.ts +1 -3
- package/dist/components/properties.d.ts.map +1 -1
- package/dist/components/properties.js +2 -9
- package/dist/components/properties.js.map +1 -1
- package/dist/corners.d.ts +22 -0
- package/dist/corners.d.ts.map +1 -0
- package/dist/corners.js +52 -0
- package/dist/corners.js.map +1 -0
- package/dist/css/grid.d.ts +4 -1
- package/dist/css/grid.d.ts.map +1 -1
- package/dist/css/grid.js +16 -7
- package/dist/css/grid.js.map +1 -1
- package/dist/css/index.d.ts +2 -2
- package/dist/css/index.js +2 -2
- package/dist/css/values.d.ts +6 -1
- package/dist/css/values.d.ts.map +1 -1
- package/dist/font-style.d.ts +2 -1
- package/dist/font-style.d.ts.map +1 -1
- package/dist/font-style.js +31 -6
- package/dist/font-style.js.map +1 -1
- package/dist/geometry.d.ts +68 -3
- package/dist/geometry.d.ts.map +1 -1
- package/dist/geometry.js +155 -5
- package/dist/geometry.js.map +1 -1
- package/dist/gradient.d.ts +9 -2
- package/dist/gradient.d.ts.map +1 -1
- package/dist/gradient.js +29 -1
- package/dist/gradient.js.map +1 -1
- package/dist/graph.d.ts +4 -0
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +30 -4
- package/dist/graph.js.map +1 -1
- package/dist/group-bounds.d.ts.map +1 -1
- package/dist/group-bounds.js +4 -3
- package/dist/group-bounds.js.map +1 -1
- package/dist/guides.d.ts +11 -2
- package/dist/guides.d.ts.map +1 -1
- package/dist/guides.js +30 -1
- package/dist/guides.js.map +1 -1
- package/dist/hit-test.d.ts.map +1 -1
- package/dist/hit-test.js +57 -5
- package/dist/hit-test.js.map +1 -1
- package/dist/icons/fit.d.ts +17 -0
- package/dist/icons/fit.d.ts.map +1 -0
- package/dist/icons/fit.js +21 -0
- package/dist/icons/fit.js.map +1 -0
- package/dist/icons/glyph.d.ts.map +1 -1
- package/dist/icons/glyph.js +5 -4
- package/dist/icons/glyph.js.map +1 -1
- package/dist/icons/index.d.ts +2 -1
- package/dist/icons/index.js +2 -1
- package/dist/images.d.ts +14 -4
- package/dist/images.d.ts.map +1 -1
- package/dist/images.js +45 -5
- package/dist/images.js.map +1 -1
- package/dist/instances/assignments.js +39 -6
- package/dist/instances/assignments.js.map +1 -1
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +39 -2
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/kept-overrides.js +2 -2
- package/dist/instances/kept-overrides.js.map +1 -1
- package/dist/instances/matching.js +68 -0
- package/dist/instances/matching.js.map +1 -0
- package/dist/instances/overrides.d.ts +4 -1
- package/dist/instances/overrides.d.ts.map +1 -1
- package/dist/instances/overrides.js +13 -1
- package/dist/instances/overrides.js.map +1 -1
- package/dist/instances/protection.js +67 -0
- package/dist/instances/protection.js.map +1 -0
- package/dist/instances/swap.js +7 -5
- package/dist/instances/swap.js.map +1 -1
- package/dist/instances/sync.js +10 -116
- package/dist/instances/sync.js.map +1 -1
- package/dist/layout/guides.d.ts +17 -1
- package/dist/layout/guides.d.ts.map +1 -1
- package/dist/layout/guides.js +31 -11
- package/dist/layout/guides.js.map +1 -1
- package/dist/layout/index.d.ts +4 -2
- package/dist/layout/index.js +4 -2
- package/dist/layout/limits.d.ts +40 -0
- package/dist/layout/limits.d.ts.map +1 -0
- package/dist/layout/limits.js +54 -0
- package/dist/layout/limits.js.map +1 -0
- package/dist/layout/sizing.d.ts.map +1 -1
- package/dist/layout/sizing.js +0 -1
- package/dist/layout/sizing.js.map +1 -1
- package/dist/layout/spacing.d.ts +10 -0
- package/dist/layout/spacing.d.ts.map +1 -0
- package/dist/layout/spacing.js +12 -0
- package/dist/layout/spacing.js.map +1 -0
- package/dist/masks.d.ts +28 -0
- package/dist/masks.d.ts.map +1 -0
- package/dist/masks.js +53 -0
- package/dist/masks.js.map +1 -0
- package/dist/matrix.d.ts +2 -1
- package/dist/matrix.d.ts.map +1 -1
- package/dist/matrix.js +14 -1
- package/dist/matrix.js.map +1 -1
- package/dist/node-defaults.d.ts +9 -1
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +16 -1
- package/dist/node-defaults.js.map +1 -1
- package/dist/outline/flatten.d.ts.map +1 -1
- package/dist/outline/flatten.js +24 -17
- package/dist/outline/flatten.js.map +1 -1
- package/dist/outline/hit.d.ts +2 -8
- package/dist/outline/hit.d.ts.map +1 -1
- package/dist/outline/hit.js +16 -25
- package/dist/outline/hit.js.map +1 -1
- package/dist/outline/index.d.ts +3 -3
- package/dist/outline/index.js +3 -3
- package/dist/outline/shapes.d.ts +3 -1
- package/dist/outline/shapes.d.ts.map +1 -1
- package/dist/outline/shapes.js +18 -39
- package/dist/outline/shapes.js.map +1 -1
- package/dist/paints/index.d.ts +3 -1
- package/dist/paints/index.js +3 -1
- package/dist/paints/pattern.d.ts +13 -0
- package/dist/paints/pattern.d.ts.map +1 -0
- package/dist/paints/pattern.js +47 -0
- package/dist/paints/pattern.js.map +1 -0
- package/dist/paints/shows.d.ts +11 -0
- package/dist/paints/shows.d.ts.map +1 -0
- package/dist/paints/shows.js +16 -0
- package/dist/paints/shows.js.map +1 -0
- package/dist/paths/arc.d.ts +32 -0
- package/dist/paths/arc.d.ts.map +1 -0
- package/dist/paths/arc.js +49 -0
- package/dist/paths/arc.js.map +1 -0
- package/dist/paths/index.d.ts +5 -0
- package/dist/paths/index.js +5 -0
- package/dist/paths/network.d.ts +43 -0
- package/dist/paths/network.d.ts.map +1 -0
- package/dist/paths/network.js +249 -0
- package/dist/paths/network.js.map +1 -0
- package/dist/paths/sink.d.ts +20 -0
- package/dist/paths/sink.d.ts.map +1 -0
- package/dist/paths/sink.js +32 -0
- package/dist/paths/sink.js.map +1 -0
- package/dist/paths/smooth-corners.d.ts +25 -0
- package/dist/paths/smooth-corners.d.ts.map +1 -0
- package/dist/paths/smooth-corners.js +196 -0
- package/dist/paths/smooth-corners.js.map +1 -0
- package/dist/plugin-data/fields.d.ts +4 -0
- package/dist/plugin-data/fields.d.ts.map +1 -1
- package/dist/plugin-data/fields.js +2 -0
- package/dist/plugin-data/fields.js.map +1 -1
- package/dist/polygon.d.ts +1 -3
- package/dist/polygon.d.ts.map +1 -1
- package/dist/polygon.js +1 -16
- package/dist/polygon.js.map +1 -1
- package/dist/resize.d.ts.map +1 -1
- package/dist/resize.js +5 -5
- package/dist/resize.js.map +1 -1
- package/dist/scaling/node.d.ts.map +1 -1
- package/dist/scaling/node.js +25 -3
- package/dist/scaling/node.js.map +1 -1
- package/dist/text/auto-resize.d.ts +15 -0
- package/dist/text/auto-resize.d.ts.map +1 -0
- package/dist/text/auto-resize.js +23 -0
- package/dist/text/auto-resize.js.map +1 -0
- package/dist/text/index.d.ts +4 -3
- package/dist/text/index.js +4 -3
- package/dist/text/lengths.d.ts +6 -1
- package/dist/text/lengths.d.ts.map +1 -1
- package/dist/text/lengths.js +10 -1
- package/dist/text/lengths.js.map +1 -1
- package/dist/text/overflow.d.ts +14 -5
- package/dist/text/overflow.d.ts.map +1 -1
- package/dist/text/overflow.js +24 -6
- package/dist/text/overflow.js.map +1 -1
- package/dist/text/path.js +10 -0
- package/dist/text/path.js.map +1 -0
- package/dist/text/picture.js +5 -5
- package/dist/text/picture.js.map +1 -1
- package/dist/transfer/dependencies.d.ts.map +1 -1
- package/dist/transfer/dependencies.js +3 -2
- package/dist/transfer/dependencies.js.map +1 -1
- package/dist/transfer/nodes.js +2 -1
- package/dist/transfer/nodes.js.map +1 -1
- package/dist/types.d.ts +21 -8
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/variables/index.d.ts +4 -3
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js +4 -3
- package/dist/variables/index.js.map +1 -1
- package/dist/variables/lookup.d.ts +20 -0
- package/dist/variables/lookup.d.ts.map +1 -0
- package/dist/variables/lookup.js +34 -0
- package/dist/variables/lookup.js.map +1 -0
- package/dist/variables/paints.d.ts +35 -4
- package/dist/variables/paints.d.ts.map +1 -1
- package/dist/variables/paints.js +67 -16
- package/dist/variables/paints.js.map +1 -1
- package/dist/variables/resolution.d.ts +3 -1
- package/dist/variables/resolution.d.ts.map +1 -1
- package/dist/variables/resolution.js +8 -3
- package/dist/variables/resolution.js.map +1 -1
- package/dist/variables/subtree.js +1 -1
- package/dist/variables/subtree.js.map +1 -1
- package/dist/vector-network.d.ts.map +1 -1
- package/dist/vector-network.js +12 -76
- package/dist/vector-network.js.map +1 -1
- package/package.json +25 -1
- package/src/arrays.ts +37 -0
- package/src/buffered-events.ts +2 -1
- package/src/clipping.ts +11 -8
- package/src/components/properties.ts +1 -13
- package/src/corners.ts +93 -0
- package/src/css/grid.ts +21 -7
- package/src/css/index.ts +1 -1
- package/src/font-style.ts +38 -4
- package/src/geometry.ts +219 -6
- package/src/gradient.ts +23 -1
- package/src/graph.ts +22 -4
- package/src/group-bounds.ts +7 -3
- package/src/guides.ts +26 -1
- package/src/hit-test.ts +68 -10
- package/src/icons/fit.ts +24 -0
- package/src/icons/glyph.ts +5 -4
- package/src/icons/index.ts +1 -0
- package/src/images.ts +67 -7
- package/src/instances/assignments.ts +65 -7
- package/src/instances/index.ts +53 -4
- package/src/instances/kept-overrides.ts +2 -5
- package/src/instances/matching.ts +101 -0
- package/src/instances/overrides.ts +18 -0
- package/src/instances/protection.ts +103 -0
- package/src/instances/swap.ts +11 -9
- package/src/instances/sync.ts +11 -184
- package/src/layout/guides.ts +42 -9
- package/src/layout/index.ts +2 -0
- package/src/layout/limits.ts +64 -0
- package/src/layout/sizing.ts +0 -2
- package/src/layout/spacing.ts +11 -0
- package/src/masks.ts +51 -0
- package/src/matrix.ts +15 -2
- package/src/node-defaults.ts +23 -3
- package/src/outline/flatten.ts +30 -18
- package/src/outline/hit.ts +16 -33
- package/src/outline/index.ts +2 -2
- package/src/outline/shapes.ts +19 -36
- package/src/paints/index.ts +2 -0
- package/src/paints/pattern.ts +45 -0
- package/src/paints/shows.ts +13 -0
- package/src/paths/arc.ts +59 -0
- package/src/paths/index.ts +4 -0
- package/src/paths/network.ts +334 -0
- package/src/paths/sink.ts +50 -0
- package/src/paths/smooth-corners.ts +356 -0
- package/src/plugin-data/fields.ts +2 -0
- package/src/polygon.ts +0 -17
- package/src/resize.ts +6 -7
- package/src/scaling/node.ts +29 -3
- package/src/text/auto-resize.ts +25 -0
- package/src/text/index.ts +1 -0
- package/src/text/lengths.ts +11 -0
- package/src/text/overflow.ts +32 -6
- package/src/text/path.ts +13 -0
- package/src/text/picture.ts +5 -5
- package/src/transfer/dependencies.ts +3 -2
- package/src/transfer/nodes.ts +2 -1
- package/src/types.ts +25 -8
- package/src/variables/index.ts +1 -0
- package/src/variables/lookup.ts +31 -0
- package/src/variables/paints.ts +101 -20
- package/src/variables/resolution.ts +14 -2
- package/src/variables/subtree.ts +1 -1
- package/src/vector-network.ts +17 -138
package/dist/hit-test.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import Matrix from "./matrix.js";
|
|
2
|
+
import { clipsChildren } from "./node-defaults.js";
|
|
2
3
|
import { getWorldMatrix } from "./coordinate.js";
|
|
3
4
|
import { hitsConnectorLine } from "./connectors/hit.js";
|
|
4
|
-
import {
|
|
5
|
+
import { asMaskShape, isVisibleMask, maskRuns } from "./masks.js";
|
|
6
|
+
import { paintShows } from "./paints/shows.js";
|
|
7
|
+
import { hitsShape, strokeReach } from "./outline/hit.js";
|
|
5
8
|
//#region src/hit-test.ts
|
|
6
9
|
const CONTAINER_TYPES = /* @__PURE__ */ new Set([
|
|
7
10
|
"CANVAS",
|
|
@@ -13,9 +16,9 @@ const CONTAINER_TYPES = /* @__PURE__ */ new Set([
|
|
|
13
16
|
"INSTANCE"
|
|
14
17
|
]);
|
|
15
18
|
const OPAQUE_CONTAINER_TYPES = /* @__PURE__ */ new Set(["COMPONENT", "INSTANCE"]);
|
|
16
|
-
/** Whether a container's own paints show, so its empty area is drawn (
|
|
19
|
+
/** Whether a container's own paints show, so its empty area is drawn (`paintShows`). */
|
|
17
20
|
function showsPaint(node) {
|
|
18
|
-
return node.fills.some(
|
|
21
|
+
return node.fills.some(paintShows) || node.strokes.some(paintShows);
|
|
19
22
|
}
|
|
20
23
|
function isTopLevel(graph, node) {
|
|
21
24
|
const parent = node.parentId ? graph.nodes.get(node.parentId) : void 0;
|
|
@@ -82,17 +85,66 @@ function hitTestTransparentContainer(graph, px, py, child, walk) {
|
|
|
82
85
|
if (containsPoint(px, py, child, graph, walk.transformCache) && takesEmptyArea(graph, child, walk)) return child;
|
|
83
86
|
return null;
|
|
84
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* The mask run holding each child, asked for from the top child down: the walk steps back through
|
|
90
|
+
* the runs once rather than searching them for every child.
|
|
91
|
+
*/
|
|
92
|
+
function maskRunCursor(graph, childIds) {
|
|
93
|
+
const runs = maskRuns(childIds, (id) => {
|
|
94
|
+
const child = graph.nodes.get(id);
|
|
95
|
+
return child !== void 0 && isVisibleMask(child);
|
|
96
|
+
});
|
|
97
|
+
let runIndex = runs.length - 1;
|
|
98
|
+
return (index) => {
|
|
99
|
+
while (runIndex >= 0 && runs[runIndex].start > index) runIndex--;
|
|
100
|
+
const run = runs.at(runIndex);
|
|
101
|
+
return run && runIndex >= 0 && index >= run.maskedStart ? run : void 0;
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Whether the point lies on what a run's masks draw, or there is no run to hold it to. A container
|
|
106
|
+
* mask draws its own paint and its layers, so a click between its layers is outside it.
|
|
107
|
+
*/
|
|
108
|
+
function insideMasks(graph, px, py, childIds, run, walk) {
|
|
109
|
+
if (!run) return true;
|
|
110
|
+
return childIds.slice(run.start, run.maskedStart).some((id) => {
|
|
111
|
+
const mask = graph.nodes.get(id);
|
|
112
|
+
if (!mask) return false;
|
|
113
|
+
if (!CONTAINER_TYPES.has(mask.type)) return hitsLeaf(graph, px, py, asMaskShape(mask), walk.transformCache, 0);
|
|
114
|
+
if (showsPaint(mask) && containsPoint(px, py, mask, graph, walk.transformCache)) return true;
|
|
115
|
+
const drawn = {
|
|
116
|
+
...walk,
|
|
117
|
+
deep: true,
|
|
118
|
+
pad: 0,
|
|
119
|
+
locked: true
|
|
120
|
+
};
|
|
121
|
+
return hitTestChildren(graph, px, py, mask.id, drawn) !== null;
|
|
122
|
+
});
|
|
123
|
+
}
|
|
85
124
|
/** The topmost layer under the point among a container's children. */
|
|
86
125
|
function hitTestChildren(graph, px, py, parentId, walk) {
|
|
87
126
|
const parent = graph.nodes.get(parentId);
|
|
88
127
|
if (!parent) return null;
|
|
89
128
|
const { transformCache, pad } = walk;
|
|
90
|
-
if (parent
|
|
129
|
+
if (clipsChildren(parent)) {
|
|
91
130
|
if (!containsPoint(px, py, parent, graph, transformCache)) return null;
|
|
92
131
|
}
|
|
132
|
+
const runAt = maskRunCursor(graph, parent.childIds);
|
|
133
|
+
const covered = /* @__PURE__ */ new Map();
|
|
134
|
+
const inside = (run) => {
|
|
135
|
+
if (!run) return true;
|
|
136
|
+
let hit = covered.get(run);
|
|
137
|
+
if (hit === void 0) {
|
|
138
|
+
hit = insideMasks(graph, px, py, parent.childIds, run, walk);
|
|
139
|
+
covered.set(run, hit);
|
|
140
|
+
}
|
|
141
|
+
return hit;
|
|
142
|
+
};
|
|
93
143
|
for (let i = parent.childIds.length - 1; i >= 0; i--) {
|
|
144
|
+
const run = runAt(i);
|
|
94
145
|
const child = graph.nodes.get(parent.childIds[i]);
|
|
95
146
|
if (!child || child.internalOnly || !child.visible || child.locked && !walk.locked) continue;
|
|
147
|
+
if (!inside(run)) continue;
|
|
96
148
|
if (CONTAINER_TYPES.has(child.type)) {
|
|
97
149
|
if (OPAQUE_CONTAINER_TYPES.has(child.type) && !walk.deep) {
|
|
98
150
|
if (containsPoint(px, py, child, graph, transformCache)) return child;
|
|
@@ -244,7 +296,7 @@ function dropRules(options) {
|
|
|
244
296
|
};
|
|
245
297
|
}
|
|
246
298
|
function dropTargetIn(graph, px, py, parent, excludeIds, rules, transformCache) {
|
|
247
|
-
if (parent
|
|
299
|
+
if (clipsChildren(parent) && !containsPoint(px, py, parent, graph, transformCache)) return null;
|
|
248
300
|
for (let i = parent.childIds.length - 1; i >= 0; i--) {
|
|
249
301
|
const childId = parent.childIds[i];
|
|
250
302
|
if (excludeIds.has(childId)) continue;
|
package/dist/hit-test.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hit-test.js","names":[],"sources":["../src/hit-test.ts"],"sourcesContent":["import { hitsConnectorLine } from './connectors/hit'\nimport { getWorldMatrix } from './coordinate'\nimport type { SceneGraph } from './graph'\nimport Matrix from './matrix'\nimport { hitsShape, isHitPaint, strokeReach } from './outline/hit'\nimport type { SceneNode, NodeType } from './types'\n\nconst CONTAINER_TYPES = new Set<NodeType>([\n 'CANVAS',\n 'FRAME',\n 'GROUP',\n 'SECTION',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\nconst OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])\n\n/** Whether a container's own paints show, so its empty area is drawn (see `isHitPaint`). */\nfunction showsPaint(node: SceneNode): boolean {\n return node.fills.some(isHitPaint) || node.strokes.some(isHitPaint)\n}\n\nfunction isTopLevel(graph: SceneGraph, node: SceneNode): boolean {\n const parent = node.parentId ? graph.nodes.get(node.parentId) : undefined\n return parent?.type === 'CANVAS' || parent?.type === 'SECTION'\n}\n\n/**\n * An open container whose empty area still belongs to it, as in Figma: a top-level frame with auto\n * layout is selected, hovered, and dragged by its gaps and padding, while its children stay one\n * click away, with or without a fill. A plain top-level frame's empty area is background, and a\n * nested frame's empty area belongs to it only as a click target (see `frameChildAt`).\n */\nfunction ownsItsEmptyArea(graph: SceneGraph, node: SceneNode): boolean {\n return node.type === 'FRAME' && node.layoutMode !== 'NONE' && isTopLevel(graph, node)\n}\n\nfunction hasTransformedAncestor(\n node: SceneNode,\n graph: SceneGraph,\n cache: Map<string, boolean>\n): boolean {\n const cached = cache.get(node.id)\n if (cached !== undefined) return cached\n const parent = node.parentId ? graph.getNode(node.parentId) : undefined\n const transformed =\n node.rotation !== 0 ||\n node.flipX ||\n node.flipY ||\n (parent ? hasTransformedAncestor(parent, graph, cache) : false)\n cache.set(node.id, transformed)\n return transformed\n}\n\n/** Whether the point lies in the node's box, grown by `pad` canvas units on every side. */\nfunction containsPoint(\n px: number,\n py: number,\n node: SceneNode,\n graph: SceneGraph,\n transformCache: Map<string, boolean>,\n pad = 0\n): boolean {\n if (!hasTransformedAncestor(node, graph, transformCache)) {\n const absolute = graph.getAbsolutePosition(node.id)\n return (\n px >= absolute.x - pad &&\n px <= absolute.x + node.width + pad &&\n py >= absolute.y - pad &&\n py <= absolute.y + node.height + pad\n )\n }\n\n const m = getWorldMatrix(node, graph)\n\n const inv = Matrix.invert(m)\n if (!inv) return false\n\n const [localX, localY] = Matrix.mapPoints(inv, [px, py])\n return (\n localX >= -pad && localX <= node.width + pad && localY >= -pad && localY <= node.height + pad\n )\n}\n\n/**\n * How a walk down the layers takes a click. `deep` reaches past containers to the deepest layer;\n * `pad`, in canvas units, grows each leaf layer's box, as Figma takes a click a few screen pixels\n * outside a shape; `instanceBodies` lets a deep walk take an instance's empty area whatever its\n * fill, as a plain click does, where a ⌘-click counts only a fill that shows.\n */\ninterface HitWalk {\n deep: boolean\n pad: number\n instanceBodies: boolean\n /** Whether locked layers are hit, as by a right-click; see `SelectableHitOptions.locked`. */\n locked: boolean\n transformCache: Map<string, boolean>\n}\n\nfunction walkOf(deep: boolean, pad = 0, instanceBodies = false, locked = false): HitWalk {\n return { deep, pad, instanceBodies, locked, transformCache: new Map() }\n}\n\n/** Whether a container's empty area under the point takes a click reaching past containers. */\nfunction takesEmptyArea(graph: SceneGraph, node: SceneNode, walk: HitWalk): boolean {\n // Figma counts an empty area only where a paint shows, except a main component's, which always\n // counts, and an instance's when the click is a plain one.\n if (node.type === 'COMPONENT' || showsPaint(node) || ownsItsEmptyArea(graph, node)) return true\n return walk.instanceBodies && node.type === 'INSTANCE'\n}\n\n/**\n * What a hit inside a container reports: the container itself when it is locked (a locked layer,\n * where one is hit at all, stands in for everything inside it) or the walk stops at containers.\n */\nfunction standIn(container: SceneNode, hit: SceneNode, deep: boolean): SceneNode {\n return container.locked || !deep ? container : hit\n}\n\nfunction hitTestTransparentContainer(\n graph: SceneGraph,\n px: number,\n py: number,\n child: SceneNode,\n walk: HitWalk\n): SceneNode | null {\n if (child.type === 'GROUP') {\n // A group fits its layers, so a padded click on one at its edge falls just outside it.\n if (!containsPoint(px, py, child, graph, walk.transformCache, walk.pad)) return null\n // A group has no area of its own, as in Figma: between its layers the click falls through to\n // whatever lies under the group.\n const childHit = hitTestChildren(graph, px, py, child.id, walk)\n return childHit ? standIn(child, childHit, walk.deep) : null\n }\n\n const childHit = hitTestChildren(graph, px, py, child.id, walk)\n if (childHit) return standIn(child, childHit, true)\n\n if (\n containsPoint(px, py, child, graph, walk.transformCache) &&\n takesEmptyArea(graph, child, walk)\n )\n return child\n return null\n}\n\n/** The topmost layer under the point among a container's children. */\nfunction hitTestChildren(\n graph: SceneGraph,\n px: number,\n py: number,\n parentId: string,\n walk: HitWalk\n): SceneNode | null {\n const parent = graph.nodes.get(parentId)\n if (!parent) return null\n const { transformCache, pad } = walk\n\n if (parent.clipsContent) {\n if (!containsPoint(px, py, parent, graph, transformCache)) return null\n }\n\n for (let i = parent.childIds.length - 1; i >= 0; i--) {\n const child = graph.nodes.get(parent.childIds[i])\n // A locked layer and everything in it are invisible to a press and to hover, as in Figma: a\n // click falls through to what lies under it, and a drag from it draws a marquee.\n if (!child || child.internalOnly || !child.visible || (child.locked && !walk.locked)) continue\n if (CONTAINER_TYPES.has(child.type)) {\n if (OPAQUE_CONTAINER_TYPES.has(child.type) && !walk.deep) {\n // A plain click takes an instance or component anywhere in its box, with a fill or\n // without, as in Figma.\n if (containsPoint(px, py, child, graph, transformCache)) return child\n continue\n }\n const hit = hitTestTransparentContainer(graph, px, py, child, walk)\n if (hit) return hit\n continue\n }\n\n if (child.type === 'CONNECTOR') {\n if (hitsConnectorLine(graph, child, px, py, pad)) return child\n continue\n }\n if (hitsLeaf(graph, px, py, child, transformCache, pad)) return child\n }\n\n return null\n}\n\n/**\n * Whether a click lands on a leaf layer: on what its paints draw, as Figma tests shapes (see\n * `hitsShape`), or on its box for layers without an outline to test, such as text.\n */\nfunction hitsLeaf(\n graph: SceneGraph,\n px: number,\n py: number,\n node: SceneNode,\n transformCache: Map<string, boolean>,\n pad: number\n): boolean {\n if (!containsPoint(px, py, node, graph, transformCache, pad + strokeReach(node))) return false\n return (\n hitsShape(graph, node, px, py, pad) ?? containsPoint(px, py, node, graph, transformCache, pad)\n )\n}\n\nexport function hitTest(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId?: string\n): SceneNode | null {\n const scope = scopeId ?? graph.rootId\n return hitTestChildren(graph, px, py, scope, walkOf(false))\n}\n\nexport function hitTestDeep(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId?: string,\n pad = 0\n): SceneNode | null {\n const scope = scopeId ?? graph.rootId\n return hitTestChildren(graph, px, py, scope, walkOf(true, pad))\n}\n\n/**\n * A container a click looks into by itself, as in Figma: a top-level frame (on the page or in a\n * section) or a section that holds layers, and a component set. On a FigJam board frames stay\n * closed (`framesOpen` false): a click inside one selects the frame.\n */\nfunction opensByItself(graph: SceneGraph, node: SceneNode, framesOpen = true): boolean {\n if (node.type === 'COMPONENT_SET') return true\n if (node.childIds.length === 0) return false\n if (node.type === 'SECTION') return true\n return framesOpen && node.type === 'FRAME' && isTopLevel(graph, node)\n}\n\n/**\n * The topmost frame among a container's children whose bounds hold the point, filled or not: in\n * Figma a click on the empty area of a frame inside an open container, or of an empty frame on the\n * page or in a section, selects that frame, while a deep (⌘) click looks through it.\n */\nfunction frameChildAt(\n graph: SceneGraph,\n container: SceneNode,\n px: number,\n py: number,\n framesOpen = true,\n locked = false\n): SceneNode | null {\n const transformCache = new Map<string, boolean>()\n for (let i = container.childIds.length - 1; i >= 0; i--) {\n const child = graph.nodes.get(container.childIds[i])\n if (!child || child.internalOnly || !child.visible || child.type !== 'FRAME') continue\n if (child.locked && !locked) continue\n // A board, such as a top-level frame in a section, keeps its empty area as background.\n if (opensByItself(graph, child, framesOpen) && !ownsItsEmptyArea(graph, child)) continue\n if (containsPoint(px, py, child, graph, transformCache)) return child\n }\n return null\n}\n\n/**\n * The containers the selection opens: every ancestor of a selected layer inside the scope, so a\n * click reaches the siblings of selected layers, and a selected container itself, so hover and a\n * read-only click reach the layer under the point. A plain press inside a selected frame still\n * drags the frame, as in Figma, which `pressesSelection` in the Vue input decides. A selected group\n * or boolean stays closed: clicking inside it keeps it selected.\n */\nfunction openedBySelection(\n graph: SceneGraph,\n selectedIds: ReadonlySet<string>,\n scopeId: string,\n framesOpen: boolean,\n enteredId: string | null\n): Set<string> {\n const ancestors = new Set<string>()\n // An entered container is open whatever its kind, so a double-click into a board's frame\n // reaches its layers; its ancestors open with it.\n for (let id = enteredId; id && id !== scopeId && !ancestors.has(id);) {\n ancestors.add(id)\n id = graph.nodes.get(id)?.parentId ?? null\n }\n for (const id of selectedIds) {\n const node = graph.nodes.get(id)\n if (\n node &&\n node.childIds.length > 0 &&\n node.type !== 'GROUP' &&\n node.type !== 'BOOLEAN_OPERATION' &&\n // A board's frame stays closed when selected: a click inside keeps it selected.\n (framesOpen || node.type !== 'FRAME' || !isTopLevel(graph, node))\n )\n ancestors.add(id)\n let parentId = node?.parentId\n while (parentId && parentId !== scopeId && !ancestors.has(parentId)) {\n ancestors.add(parentId)\n parentId = graph.nodes.get(parentId)?.parentId\n }\n }\n return ancestors\n}\n\n/**\n * The layer a click selects, as in Figma. It walks from the scope down to the deepest layer under\n * the point and stops at the first layer that is not open. Top-level frames and sections with\n * layers and component sets are open, and so is every ancestor of the selection, so clicks reach\n * the siblings of selected layers. Where every layer under the point is open, a container opened\n * by the selection is selected, so is a top-level frame with auto layout, and a plain top-level\n * frame or a section is not.\n */\nexport interface SelectableHitOptions {\n /** Canvas units a leaf layer's box grows by, as Figma takes a click a few pixels outside. */\n pad?: number\n /** Whether top-level frames are looked into (a design) or selected whole (a board). */\n framesOpen?: boolean\n /** The container a double-click entered, open along with its ancestors. */\n enteredId?: string | null\n /**\n * Whether locked layers are hit, each standing in for everything inside it: a right-click\n * selects one, as in Figma, while a press and hover pass through it.\n */\n locked?: boolean\n}\n\nexport function hitTestSelectable(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId: string,\n selectedIds: ReadonlySet<string>,\n options: SelectableHitOptions = {}\n): SceneNode | null {\n const { pad = 0, framesOpen = true, enteredId = null, locked = false } = options\n // A plain click: the walk takes an instance's empty area whatever its fill.\n const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true, pad, true, locked))\n if (!deepest) {\n const scope = graph.nodes.get(scopeId)\n return scope ? frameChildAt(graph, scope, px, py, framesOpen, locked) : null\n }\n\n const chain: SceneNode[] = []\n for (let node: SceneNode | undefined = deepest; node && node.id !== scopeId;) {\n chain.unshift(node)\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n\n const opened = openedBySelection(graph, selectedIds, scopeId, framesOpen, enteredId)\n\n for (const node of chain) {\n // A locked layer, hit only with `locked`, stands in for everything inside it.\n if (node.locked) return node\n if (!opened.has(node.id) && !opensByItself(graph, node, framesOpen)) return node\n }\n const last = chain.at(-1)\n if (!last) return null\n const frame = frameChildAt(graph, last, px, py, framesOpen, locked)\n if (frame) return frame\n if (ownsItsEmptyArea(graph, last)) return last\n return opened.has(last.id) && !opensByItself(graph, last, framesOpen) ? last : null\n}\n\n/** Whether a click looks into this container rather than selecting it; see `hitTestSelectable`. */\nexport function isOpenContainer(graph: SceneGraph, nodeId: string, framesOpen = true): boolean {\n const node = graph.nodes.get(nodeId)\n return node !== undefined && opensByItself(graph, node, framesOpen)\n}\n\n/**\n * The innermost open container under the point when every layer there is open: a marquee starting\n * here selects that container's layers, as in Figma.\n */\nexport function hitTestOpenContainer(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId: string\n): SceneNode | null {\n const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true))\n for (let node: SceneNode | undefined = deepest ?? undefined; node && node.id !== scopeId;) {\n if (!opensByItself(graph, node) || ownsItsEmptyArea(graph, node)) return null\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n return deepest\n}\n\n/** Whether the point lies inside the node's rotated and flipped bounds. */\nexport function isPointInNode(graph: SceneGraph, nodeId: string, px: number, py: number): boolean {\n const node = graph.nodes.get(nodeId)\n return node !== undefined && containsPoint(px, py, node, graph, new Map())\n}\n\n/** Which layers take a drop, and which are only looked through, as in Figma. */\ninterface DropRules {\n takes: (node: SceneNode) => boolean\n passThrough: ReadonlySet<NodeType>\n}\n\nconst LAYER_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'COMPONENT', 'INSTANCE'])\nconst COMPONENT_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'INSTANCE'])\n\nfunction dropRules(options: DropTargetOptions): DropRules {\n const { componentSetIds } = options\n if (!componentSetIds) {\n return {\n takes: (node) => LAYER_TARGETS.has(node.type),\n passThrough: new Set(['GROUP', 'COMPONENT_SET'])\n }\n }\n // Components never go into other components, and a set only takes back its own variants.\n return {\n takes: (node) =>\n COMPONENT_TARGETS.has(node.type) ||\n (node.type === 'COMPONENT_SET' && componentSetIds.has(node.id)),\n passThrough: new Set(['GROUP'])\n }\n}\n\nfunction dropTargetIn(\n graph: SceneGraph,\n px: number,\n py: number,\n parent: SceneNode,\n excludeIds: ReadonlySet<string>,\n rules: DropRules,\n transformCache: Map<string, boolean>\n): SceneNode | null {\n // A clipped-away part of a child is not under the cursor.\n if (\n parent.type !== 'CANVAS' &&\n parent.clipsContent &&\n !containsPoint(px, py, parent, graph, transformCache)\n )\n return null\n\n for (let i = parent.childIds.length - 1; i >= 0; i--) {\n const childId = parent.childIds[i]\n if (excludeIds.has(childId)) continue\n const child = graph.nodes.get(childId)\n if (!child || child.internalOnly || !child.visible || child.locked) continue\n const target = rules.takes(child)\n if (!target && !rules.passThrough.has(child.type)) continue\n\n const deeper = dropTargetIn(graph, px, py, child, excludeIds, rules, transformCache)\n if (deeper) return deeper\n if (target && containsPoint(px, py, child, graph, transformCache)) return child\n }\n\n return null\n}\n\nexport interface DropTargetOptions {\n /**\n * Set when the dropped layers are all main components: the component sets they come from.\n * Components then go only into frames, sections, instances, and those sets.\n */\n componentSetIds?: ReadonlySet<string>\n}\n\n/**\n * The topmost unlocked frame, section, component, or instance under the point, in its rotated\n * shape and inside its clipping ancestors. Groups and component sets are looked through but never\n * returned, except that a set takes dropped components; locked layers and their contents are\n * skipped.\n */\nexport function hitTestDropTarget(\n graph: SceneGraph,\n px: number,\n py: number,\n excludeIds: ReadonlySet<string>,\n scopeId?: string,\n options: DropTargetOptions = {}\n): SceneNode | null {\n const scope = graph.nodes.get(scopeId ?? graph.rootId)\n if (!scope) return null\n return dropTargetIn(graph, px, py, scope, excludeIds, dropRules(options), new Map())\n}\n"],"mappings":";;;;;AAOA,MAAM,kCAAkB,IAAI,IAAc;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,yCAAyB,IAAI,IAAc,CAAC,aAAa,UAAU,CAAC;;AAG1E,SAAS,WAAW,MAA0B;CAC5C,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,KAAK,QAAQ,KAAK,UAAU;AACpE;AAEA,SAAS,WAAW,OAAmB,MAA0B;CAC/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,gBAAgB,CAAC,MAAM,WAAW,MAAM,QAAQ;EACpE,MAAM,SAAS,MAAM,MAAM,KAAK;EAChC,IAAI,CAAC,UAAU,CAAC,MAAM,YAAY,IAAI,MAAM,IAAI,GAAG;EAEnD,MAAM,SAAS,aAAa,OAAO,IAAI,IAAI,OAAO,YAAY,OAAO,cAAc;EACnF,IAAI,QAAQ,OAAO;EACnB,IAAI,UAAU,cAAc,IAAI,IAAI,OAAO,OAAO,cAAc,GAAG,OAAO;CAC5E;CAEA,OAAO;AACT;;;;;;;AAgBA,SAAgB,kBACd,OACA,IACA,IACA,YACA,SACA,UAA6B,CAAC,GACZ;CAClB,MAAM,QAAQ,MAAM,MAAM,IAAI,WAAW,MAAM,MAAM;CACrD,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,aAAa,OAAO,IAAI,IAAI,OAAO,YAAY,UAAU,OAAO,mBAAG,IAAI,IAAI,CAAC;AACrF"}
|
|
1
|
+
{"version":3,"file":"hit-test.js","names":[],"sources":["../src/hit-test.ts"],"sourcesContent":["import { hitsConnectorLine } from './connectors/hit'\nimport { getWorldMatrix } from './coordinate'\nimport type { SceneGraph } from './graph'\nimport { asMaskShape, isVisibleMask, maskRuns, type MaskRun } from './masks'\nimport Matrix from './matrix'\nimport { clipsChildren } from './node-defaults'\nimport { hitsShape, strokeReach } from './outline/hit'\nimport { paintShows } from './paints/shows'\nimport type { SceneNode, NodeType } from './types'\n\nconst CONTAINER_TYPES = new Set<NodeType>([\n 'CANVAS',\n 'FRAME',\n 'GROUP',\n 'SECTION',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\nconst OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])\n\n/** Whether a container's own paints show, so its empty area is drawn (`paintShows`). */\nfunction showsPaint(node: SceneNode): boolean {\n return node.fills.some(paintShows) || node.strokes.some(paintShows)\n}\n\nfunction isTopLevel(graph: SceneGraph, node: SceneNode): boolean {\n const parent = node.parentId ? graph.nodes.get(node.parentId) : undefined\n return parent?.type === 'CANVAS' || parent?.type === 'SECTION'\n}\n\n/**\n * An open container whose empty area still belongs to it, as in Figma: a top-level frame with auto\n * layout is selected, hovered, and dragged by its gaps and padding, while its children stay one\n * click away, with or without a fill. A plain top-level frame's empty area is background, and a\n * nested frame's empty area belongs to it only as a click target (see `frameChildAt`).\n */\nfunction ownsItsEmptyArea(graph: SceneGraph, node: SceneNode): boolean {\n return node.type === 'FRAME' && node.layoutMode !== 'NONE' && isTopLevel(graph, node)\n}\n\nfunction hasTransformedAncestor(\n node: SceneNode,\n graph: SceneGraph,\n cache: Map<string, boolean>\n): boolean {\n const cached = cache.get(node.id)\n if (cached !== undefined) return cached\n const parent = node.parentId ? graph.getNode(node.parentId) : undefined\n const transformed =\n node.rotation !== 0 ||\n node.flipX ||\n node.flipY ||\n (parent ? hasTransformedAncestor(parent, graph, cache) : false)\n cache.set(node.id, transformed)\n return transformed\n}\n\n/** Whether the point lies in the node's box, grown by `pad` canvas units on every side. */\nfunction containsPoint(\n px: number,\n py: number,\n node: SceneNode,\n graph: SceneGraph,\n transformCache: Map<string, boolean>,\n pad = 0\n): boolean {\n if (!hasTransformedAncestor(node, graph, transformCache)) {\n const absolute = graph.getAbsolutePosition(node.id)\n return (\n px >= absolute.x - pad &&\n px <= absolute.x + node.width + pad &&\n py >= absolute.y - pad &&\n py <= absolute.y + node.height + pad\n )\n }\n\n const m = getWorldMatrix(node, graph)\n\n const inv = Matrix.invert(m)\n if (!inv) return false\n\n const [localX, localY] = Matrix.mapPoints(inv, [px, py])\n return (\n localX >= -pad && localX <= node.width + pad && localY >= -pad && localY <= node.height + pad\n )\n}\n\n/**\n * How a walk down the layers takes a click. `deep` reaches past containers to the deepest layer;\n * `pad`, in canvas units, grows each leaf layer's box, as Figma takes a click a few screen pixels\n * outside a shape; `instanceBodies` lets a deep walk take an instance's empty area whatever its\n * fill, as a plain click does, where a ⌘-click counts only a fill that shows.\n */\ninterface HitWalk {\n deep: boolean\n pad: number\n instanceBodies: boolean\n /** Whether locked layers are hit, as by a right-click; see `SelectableHitOptions.locked`. */\n locked: boolean\n transformCache: Map<string, boolean>\n}\n\nfunction walkOf(deep: boolean, pad = 0, instanceBodies = false, locked = false): HitWalk {\n return { deep, pad, instanceBodies, locked, transformCache: new Map() }\n}\n\n/** Whether a container's empty area under the point takes a click reaching past containers. */\nfunction takesEmptyArea(graph: SceneGraph, node: SceneNode, walk: HitWalk): boolean {\n // Figma counts an empty area only where a paint shows, except a main component's, which always\n // counts, and an instance's when the click is a plain one.\n if (node.type === 'COMPONENT' || showsPaint(node) || ownsItsEmptyArea(graph, node)) return true\n return walk.instanceBodies && node.type === 'INSTANCE'\n}\n\n/**\n * What a hit inside a container reports: the container itself when it is locked (a locked layer,\n * where one is hit at all, stands in for everything inside it) or the walk stops at containers.\n */\nfunction standIn(container: SceneNode, hit: SceneNode, deep: boolean): SceneNode {\n return container.locked || !deep ? container : hit\n}\n\nfunction hitTestTransparentContainer(\n graph: SceneGraph,\n px: number,\n py: number,\n child: SceneNode,\n walk: HitWalk\n): SceneNode | null {\n if (child.type === 'GROUP') {\n // A group fits its layers, so a padded click on one at its edge falls just outside it.\n if (!containsPoint(px, py, child, graph, walk.transformCache, walk.pad)) return null\n // A group has no area of its own, as in Figma: between its layers the click falls through to\n // whatever lies under the group.\n const childHit = hitTestChildren(graph, px, py, child.id, walk)\n return childHit ? standIn(child, childHit, walk.deep) : null\n }\n\n const childHit = hitTestChildren(graph, px, py, child.id, walk)\n if (childHit) return standIn(child, childHit, true)\n\n if (\n containsPoint(px, py, child, graph, walk.transformCache) &&\n takesEmptyArea(graph, child, walk)\n )\n return child\n return null\n}\n\n/**\n * The mask run holding each child, asked for from the top child down: the walk steps back through\n * the runs once rather than searching them for every child.\n */\nfunction maskRunCursor(\n graph: SceneGraph,\n childIds: readonly string[]\n): (index: number) => MaskRun | undefined {\n const runs = maskRuns(childIds, (id) => {\n const child = graph.nodes.get(id)\n return child !== undefined && isVisibleMask(child)\n })\n let runIndex = runs.length - 1\n return (index) => {\n while (runIndex >= 0 && runs[runIndex].start > index) runIndex--\n const run = runs.at(runIndex)\n return run && runIndex >= 0 && index >= run.maskedStart ? run : undefined\n }\n}\n\n/**\n * Whether the point lies on what a run's masks draw, or there is no run to hold it to. A container\n * mask draws its own paint and its layers, so a click between its layers is outside it.\n */\nfunction insideMasks(\n graph: SceneGraph,\n px: number,\n py: number,\n childIds: readonly string[],\n run: MaskRun | undefined,\n walk: HitWalk\n): boolean {\n if (!run) return true\n return childIds.slice(run.start, run.maskedStart).some((id) => {\n const mask = graph.nodes.get(id)\n if (!mask) return false\n if (!CONTAINER_TYPES.has(mask.type)) {\n return hitsLeaf(graph, px, py, asMaskShape(mask), walk.transformCache, 0)\n }\n if (showsPaint(mask) && containsPoint(px, py, mask, graph, walk.transformCache)) return true\n const drawn: HitWalk = { ...walk, deep: true, pad: 0, locked: true }\n return hitTestChildren(graph, px, py, mask.id, drawn) !== null\n })\n}\n\n/** The topmost layer under the point among a container's children. */\nfunction hitTestChildren(\n graph: SceneGraph,\n px: number,\n py: number,\n parentId: string,\n walk: HitWalk\n): SceneNode | null {\n const parent = graph.nodes.get(parentId)\n if (!parent) return null\n const { transformCache, pad } = walk\n\n if (clipsChildren(parent)) {\n if (!containsPoint(px, py, parent, graph, transformCache)) return null\n }\n\n const runAt = maskRunCursor(graph, parent.childIds)\n // Each run's masks are tested once per query, however many siblings they mask.\n const covered = new Map<MaskRun, boolean>()\n const inside = (run: MaskRun | undefined) => {\n if (!run) return true\n let hit = covered.get(run)\n if (hit === undefined) {\n hit = insideMasks(graph, px, py, parent.childIds, run, walk)\n covered.set(run, hit)\n }\n return hit\n }\n for (let i = parent.childIds.length - 1; i >= 0; i--) {\n const run = runAt(i)\n const child = graph.nodes.get(parent.childIds[i])\n // A locked layer and everything in it are invisible to a press and to hover, as in Figma: a\n // click falls through to what lies under it, and a drag from it draws a marquee.\n if (!child || child.internalOnly || !child.visible || (child.locked && !walk.locked)) continue\n // Where its masks cut a layer away, a click falls through to what lies under it (Figma, live).\n if (!inside(run)) continue\n if (CONTAINER_TYPES.has(child.type)) {\n if (OPAQUE_CONTAINER_TYPES.has(child.type) && !walk.deep) {\n // A plain click takes an instance or component anywhere in its box, with a fill or\n // without, as in Figma.\n if (containsPoint(px, py, child, graph, transformCache)) return child\n continue\n }\n const hit = hitTestTransparentContainer(graph, px, py, child, walk)\n if (hit) return hit\n continue\n }\n\n if (child.type === 'CONNECTOR') {\n if (hitsConnectorLine(graph, child, px, py, pad)) return child\n continue\n }\n if (hitsLeaf(graph, px, py, child, transformCache, pad)) return child\n }\n\n return null\n}\n\n/**\n * Whether a click lands on a leaf layer: on what its paints draw, as Figma tests shapes (see\n * `hitsShape`), or on its box for layers without an outline to test, such as text.\n */\nfunction hitsLeaf(\n graph: SceneGraph,\n px: number,\n py: number,\n node: SceneNode,\n transformCache: Map<string, boolean>,\n pad: number\n): boolean {\n if (!containsPoint(px, py, node, graph, transformCache, pad + strokeReach(node))) return false\n return (\n hitsShape(graph, node, px, py, pad) ?? containsPoint(px, py, node, graph, transformCache, pad)\n )\n}\n\nexport function hitTest(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId?: string\n): SceneNode | null {\n const scope = scopeId ?? graph.rootId\n return hitTestChildren(graph, px, py, scope, walkOf(false))\n}\n\nexport function hitTestDeep(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId?: string,\n pad = 0\n): SceneNode | null {\n const scope = scopeId ?? graph.rootId\n return hitTestChildren(graph, px, py, scope, walkOf(true, pad))\n}\n\n/**\n * A container a click looks into by itself, as in Figma: a top-level frame (on the page or in a\n * section) or a section that holds layers, and a component set. On a FigJam board frames stay\n * closed (`framesOpen` false): a click inside one selects the frame.\n */\nfunction opensByItself(graph: SceneGraph, node: SceneNode, framesOpen = true): boolean {\n if (node.type === 'COMPONENT_SET') return true\n if (node.childIds.length === 0) return false\n if (node.type === 'SECTION') return true\n return framesOpen && node.type === 'FRAME' && isTopLevel(graph, node)\n}\n\n/**\n * The topmost frame among a container's children whose bounds hold the point, filled or not: in\n * Figma a click on the empty area of a frame inside an open container, or of an empty frame on the\n * page or in a section, selects that frame, while a deep (⌘) click looks through it.\n */\nfunction frameChildAt(\n graph: SceneGraph,\n container: SceneNode,\n px: number,\n py: number,\n framesOpen = true,\n locked = false\n): SceneNode | null {\n const transformCache = new Map<string, boolean>()\n for (let i = container.childIds.length - 1; i >= 0; i--) {\n const child = graph.nodes.get(container.childIds[i])\n if (!child || child.internalOnly || !child.visible || child.type !== 'FRAME') continue\n if (child.locked && !locked) continue\n // A board, such as a top-level frame in a section, keeps its empty area as background.\n if (opensByItself(graph, child, framesOpen) && !ownsItsEmptyArea(graph, child)) continue\n if (containsPoint(px, py, child, graph, transformCache)) return child\n }\n return null\n}\n\n/**\n * The containers the selection opens: every ancestor of a selected layer inside the scope, so a\n * click reaches the siblings of selected layers, and a selected container itself, so hover and a\n * read-only click reach the layer under the point. A plain press inside a selected frame still\n * drags the frame, as in Figma, which `pressesSelection` in the Vue input decides. A selected group\n * or boolean stays closed: clicking inside it keeps it selected.\n */\nfunction openedBySelection(\n graph: SceneGraph,\n selectedIds: ReadonlySet<string>,\n scopeId: string,\n framesOpen: boolean,\n enteredId: string | null\n): Set<string> {\n const ancestors = new Set<string>()\n // An entered container is open whatever its kind, so a double-click into a board's frame\n // reaches its layers; its ancestors open with it.\n for (let id = enteredId; id && id !== scopeId && !ancestors.has(id);) {\n ancestors.add(id)\n id = graph.nodes.get(id)?.parentId ?? null\n }\n for (const id of selectedIds) {\n const node = graph.nodes.get(id)\n if (\n node &&\n node.childIds.length > 0 &&\n node.type !== 'GROUP' &&\n node.type !== 'BOOLEAN_OPERATION' &&\n // A board's frame stays closed when selected: a click inside keeps it selected.\n (framesOpen || node.type !== 'FRAME' || !isTopLevel(graph, node))\n )\n ancestors.add(id)\n let parentId = node?.parentId\n while (parentId && parentId !== scopeId && !ancestors.has(parentId)) {\n ancestors.add(parentId)\n parentId = graph.nodes.get(parentId)?.parentId\n }\n }\n return ancestors\n}\n\n/**\n * The layer a click selects, as in Figma. It walks from the scope down to the deepest layer under\n * the point and stops at the first layer that is not open. Top-level frames and sections with\n * layers and component sets are open, and so is every ancestor of the selection, so clicks reach\n * the siblings of selected layers. Where every layer under the point is open, a container opened\n * by the selection is selected, so is a top-level frame with auto layout, and a plain top-level\n * frame or a section is not.\n */\nexport interface SelectableHitOptions {\n /** Canvas units a leaf layer's box grows by, as Figma takes a click a few pixels outside. */\n pad?: number\n /** Whether top-level frames are looked into (a design) or selected whole (a board). */\n framesOpen?: boolean\n /** The container a double-click entered, open along with its ancestors. */\n enteredId?: string | null\n /**\n * Whether locked layers are hit, each standing in for everything inside it: a right-click\n * selects one, as in Figma, while a press and hover pass through it.\n */\n locked?: boolean\n}\n\nexport function hitTestSelectable(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId: string,\n selectedIds: ReadonlySet<string>,\n options: SelectableHitOptions = {}\n): SceneNode | null {\n const { pad = 0, framesOpen = true, enteredId = null, locked = false } = options\n // A plain click: the walk takes an instance's empty area whatever its fill.\n const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true, pad, true, locked))\n if (!deepest) {\n const scope = graph.nodes.get(scopeId)\n return scope ? frameChildAt(graph, scope, px, py, framesOpen, locked) : null\n }\n\n const chain: SceneNode[] = []\n for (let node: SceneNode | undefined = deepest; node && node.id !== scopeId;) {\n chain.unshift(node)\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n\n const opened = openedBySelection(graph, selectedIds, scopeId, framesOpen, enteredId)\n\n for (const node of chain) {\n // A locked layer, hit only with `locked`, stands in for everything inside it.\n if (node.locked) return node\n if (!opened.has(node.id) && !opensByItself(graph, node, framesOpen)) return node\n }\n const last = chain.at(-1)\n if (!last) return null\n const frame = frameChildAt(graph, last, px, py, framesOpen, locked)\n if (frame) return frame\n if (ownsItsEmptyArea(graph, last)) return last\n return opened.has(last.id) && !opensByItself(graph, last, framesOpen) ? last : null\n}\n\n/** Whether a click looks into this container rather than selecting it; see `hitTestSelectable`. */\nexport function isOpenContainer(graph: SceneGraph, nodeId: string, framesOpen = true): boolean {\n const node = graph.nodes.get(nodeId)\n return node !== undefined && opensByItself(graph, node, framesOpen)\n}\n\n/**\n * The innermost open container under the point when every layer there is open: a marquee starting\n * here selects that container's layers, as in Figma.\n */\nexport function hitTestOpenContainer(\n graph: SceneGraph,\n px: number,\n py: number,\n scopeId: string\n): SceneNode | null {\n const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true))\n for (let node: SceneNode | undefined = deepest ?? undefined; node && node.id !== scopeId;) {\n if (!opensByItself(graph, node) || ownsItsEmptyArea(graph, node)) return null\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n return deepest\n}\n\n/** Whether the point lies inside the node's rotated and flipped bounds. */\nexport function isPointInNode(graph: SceneGraph, nodeId: string, px: number, py: number): boolean {\n const node = graph.nodes.get(nodeId)\n return node !== undefined && containsPoint(px, py, node, graph, new Map())\n}\n\n/** Which layers take a drop, and which are only looked through, as in Figma. */\ninterface DropRules {\n takes: (node: SceneNode) => boolean\n passThrough: ReadonlySet<NodeType>\n}\n\nconst LAYER_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'COMPONENT', 'INSTANCE'])\nconst COMPONENT_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'INSTANCE'])\n\nfunction dropRules(options: DropTargetOptions): DropRules {\n const { componentSetIds } = options\n if (!componentSetIds) {\n return {\n takes: (node) => LAYER_TARGETS.has(node.type),\n passThrough: new Set(['GROUP', 'COMPONENT_SET'])\n }\n }\n // Components never go into other components, and a set only takes back its own variants.\n return {\n takes: (node) =>\n COMPONENT_TARGETS.has(node.type) ||\n (node.type === 'COMPONENT_SET' && componentSetIds.has(node.id)),\n passThrough: new Set(['GROUP'])\n }\n}\n\nfunction dropTargetIn(\n graph: SceneGraph,\n px: number,\n py: number,\n parent: SceneNode,\n excludeIds: ReadonlySet<string>,\n rules: DropRules,\n transformCache: Map<string, boolean>\n): SceneNode | null {\n // A clipped-away part of a child is not under the cursor.\n if (clipsChildren(parent) && !containsPoint(px, py, parent, graph, transformCache)) return null\n\n for (let i = parent.childIds.length - 1; i >= 0; i--) {\n const childId = parent.childIds[i]\n if (excludeIds.has(childId)) continue\n const child = graph.nodes.get(childId)\n if (!child || child.internalOnly || !child.visible || child.locked) continue\n const target = rules.takes(child)\n if (!target && !rules.passThrough.has(child.type)) continue\n\n const deeper = dropTargetIn(graph, px, py, child, excludeIds, rules, transformCache)\n if (deeper) return deeper\n if (target && containsPoint(px, py, child, graph, transformCache)) return child\n }\n\n return null\n}\n\nexport interface DropTargetOptions {\n /**\n * Set when the dropped layers are all main components: the component sets they come from.\n * Components then go only into frames, sections, instances, and those sets.\n */\n componentSetIds?: ReadonlySet<string>\n}\n\n/**\n * The topmost unlocked frame, section, component, or instance under the point, in its rotated\n * shape and inside its clipping ancestors. Groups and component sets are looked through but never\n * returned, except that a set takes dropped components; locked layers and their contents are\n * skipped.\n */\nexport function hitTestDropTarget(\n graph: SceneGraph,\n px: number,\n py: number,\n excludeIds: ReadonlySet<string>,\n scopeId?: string,\n options: DropTargetOptions = {}\n): SceneNode | null {\n const scope = graph.nodes.get(scopeId ?? graph.rootId)\n if (!scope) return null\n return dropTargetIn(graph, px, py, scope, excludeIds, dropRules(options), new Map())\n}\n"],"mappings":";;;;;;;;AAUA,MAAM,kCAAkB,IAAI,IAAc;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,yCAAyB,IAAI,IAAc,CAAC,aAAa,UAAU,CAAC;;AAG1E,SAAS,WAAW,MAA0B;CAC5C,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,KAAK,QAAQ,KAAK,UAAU;AACpE;AAEA,SAAS,WAAW,OAAmB,MAA0B;CAC/D,MAAM,SAAS,KAAK,WAAW,MAAM,MAAM,IAAI,KAAK,QAAQ,IAAI,KAAA;CAChE,OAAO,Q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AO;EACrC,IAAI,CAAC,SAAS,MAAM,gBAAgB,CAAC,MAAM,WAAW,MAAM,QAAQ;EACpE,MAAM,SAAS,MAAM,MAAM,KAAK;EAChC,IAAI,CAAC,UAAU,CAAC,MAAM,YAAY,IAAI,MAAM,IAAI,GAAG;EAEnD,MAAM,SAAS,aAAa,OAAO,IAAI,IAAI,OAAO,YAAY,OAAO,cAAc;EACnF,IAAI,QAAQ,OAAO;EACnB,IAAI,UAAU,cAAc,IAAI,IAAI,OAAO,OAAO,cAAc,GAAG,OAAO;CAC5E;CAEA,OAAO;AACT;;;;;;;AAgBA,SAAgB,kBACd,OACA,IACA,IACA,YACA,SACA,UAA6B,CAAC,GACZ;CAClB,MAAM,QAAQ,MAAM,MAAM,IAAI,WAAW,MAAM,MAAM;CACrD,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,aAAa,OAAO,IAAI,IAAI,OAAO,YAAY,UAAU,OAAO,mBAAG,IAAI,IAAI,CAAC;AACrF"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { SceneNode } from "../types.js";
|
|
2
|
+
//#region src/icons/fit.d.ts
|
|
3
|
+
/** What centering an icon's glyph needs of a graph. */
|
|
4
|
+
interface GlyphGraph {
|
|
5
|
+
getNode(id: string): SceneNode | undefined;
|
|
6
|
+
getChildren(id: string): SceneNode[];
|
|
7
|
+
updateNode(id: string, changes: Partial<SceneNode>): void;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Moves a glyph drawn `size` square at its frame's origin to the middle of the frame, as SVG fits
|
|
11
|
+
* a square view box into a box of another shape. An icon is drawn at its frame's shorter side, so
|
|
12
|
+
* it keeps its shape in a frame that is not square, whether placed or swapped.
|
|
13
|
+
*/
|
|
14
|
+
declare function centerGlyph(graph: GlyphGraph, frameId: string, size: number): void;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { centerGlyph };
|
|
17
|
+
//# sourceMappingURL=fit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fit.d.ts","names":[],"sources":["../../src/icons/fit.ts"],"mappings":";;;UAGU;EACR,QAAQ,aAAa;EACrB,YAAY,aAAa;EACzB,WAAW,YAAY,SAAS,QAAQ;;;;;;;iBAQ1B,YAAY,OAAO,YAAY,iBAAiB"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
//#region src/icons/fit.ts
|
|
2
|
+
/**
|
|
3
|
+
* Moves a glyph drawn `size` square at its frame's origin to the middle of the frame, as SVG fits
|
|
4
|
+
* a square view box into a box of another shape. An icon is drawn at its frame's shorter side, so
|
|
5
|
+
* it keeps its shape in a frame that is not square, whether placed or swapped.
|
|
6
|
+
*/
|
|
7
|
+
function centerGlyph(graph, frameId, size) {
|
|
8
|
+
const frame = graph.getNode(frameId);
|
|
9
|
+
if (!frame) return;
|
|
10
|
+
const x = (frame.width - size) / 2;
|
|
11
|
+
const y = (frame.height - size) / 2;
|
|
12
|
+
if (x === 0 && y === 0) return;
|
|
13
|
+
for (const path of graph.getChildren(frameId)) graph.updateNode(path.id, {
|
|
14
|
+
x: path.x + x,
|
|
15
|
+
y: path.y + y
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
export { centerGlyph };
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=fit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fit.js","names":[],"sources":["../../src/icons/fit.ts"],"sourcesContent":["import type { SceneNode } from '../types'\n\n/** What centering an icon's glyph needs of a graph. */\ninterface GlyphGraph {\n getNode(id: string): SceneNode | undefined\n getChildren(id: string): SceneNode[]\n updateNode(id: string, changes: Partial<SceneNode>): void\n}\n\n/**\n * Moves a glyph drawn `size` square at its frame's origin to the middle of the frame, as SVG fits\n * a square view box into a box of another shape. An icon is drawn at its frame's shorter side, so\n * it keeps its shape in a frame that is not square, whether placed or swapped.\n */\nexport function centerGlyph(graph: GlyphGraph, frameId: string, size: number): void {\n const frame = graph.getNode(frameId)\n if (!frame) return\n const x = (frame.width - size) / 2\n const y = (frame.height - size) / 2\n if (x === 0 && y === 0) return\n for (const path of graph.getChildren(frameId)) {\n graph.updateNode(path.id, { x: path.x + x, y: path.y + y })\n }\n}\n"],"mappings":";;;;;;AAcA,SAAgB,YAAY,OAAmB,SAAiB,MAAoB;CAClF,MAAM,QAAQ,MAAM,QAAQ,OAAO;CACnC,IAAI,CAAC,OAAO;CACZ,MAAM,KAAK,MAAM,QAAQ,QAAQ;CACjC,MAAM,KAAK,MAAM,SAAS,QAAQ;CAClC,IAAI,MAAM,KAAK,MAAM,GAAG;CACxB,KAAK,MAAM,QAAQ,MAAM,YAAY,OAAO,GAC1C,MAAM,WAAW,KAAK,IAAI;EAAE,GAAG,KAAK,IAAI;EAAG,GAAG,KAAK,IAAI;CAAE,CAAC;AAE9D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"glyph.d.ts","names":[],"sources":["../../src/icons/glyph.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"glyph.d.ts","names":[],"sources":["../../src/icons/glyph.ts"],"mappings":";;;UAOU;EACR,YAAY,aAAa;;;;;;;;;iBA+FX,UAAU,OAAO,WAAW,OAAO;;;;;iBAsBnC,eAAe,OAAO,WAAW,OAAO"}
|
package/dist/icons/glyph.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { maxOf, minOf } from "../arrays.js";
|
|
1
2
|
import { readIcon, readIconTint } from "./model.js";
|
|
2
3
|
import { omit } from "es-toolkit";
|
|
3
4
|
//#region src/icons/glyph.ts
|
|
@@ -14,10 +15,10 @@ function shape(network) {
|
|
|
14
15
|
const f = Math.fround;
|
|
15
16
|
const xs = network.vertices.map((vertex) => f(vertex.x));
|
|
16
17
|
const ys = network.vertices.map((vertex) => f(vertex.y));
|
|
17
|
-
const minX =
|
|
18
|
-
const minY =
|
|
19
|
-
const sx = 1 / (
|
|
20
|
-
const sy = 1 / (
|
|
18
|
+
const minX = minOf(xs);
|
|
19
|
+
const minY = minOf(ys);
|
|
20
|
+
const sx = 1 / (maxOf(xs) - minX || 1);
|
|
21
|
+
const sy = 1 / (maxOf(ys) - minY || 1);
|
|
21
22
|
return {
|
|
22
23
|
vertices: network.vertices.map((vertex) => [
|
|
23
24
|
round((f(vertex.x) - minX) * sx),
|
package/dist/icons/glyph.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"glyph.js","names":[],"sources":["../../src/icons/glyph.ts"],"sourcesContent":["import { omit } from 'es-toolkit'\n\nimport type { Fill, SceneNode, Stroke, VectorNetwork } from '../types'\nimport { readIcon, readIconTint } from './model'\n\n/** What reading an icon's paths needs of a graph. */\ninterface IconGraph {\n getChildren(id: string): SceneNode[]\n}\n\n/** Digits kept of each proportion, so float noise does not read as an edit. */\nconst PRECISION = 1000\n\nconst round = (value: number) => Math.round(value * PRECISION) / PRECISION\n\n/**\n * A path's points in proportion to their own bounds on each axis. Resizing scales vertices by\n * exact factors, so these proportions survive any resize, while the path boxes around them are\n * rounded to pixels and are left out.\n */\nfunction shape(network: VectorNetwork | null | undefined) {\n if (!network) return null\n // A saved document keeps coordinates as 32-bit floats, so they are read at that precision\n // either way; rounding alone would still split a value that lands on a rounding boundary.\n const f = Math.fround\n const xs = network.vertices.map((vertex) => f(vertex.x))\n const ys = network.vertices.map((vertex) => f(vertex.y))\n const minX =
|
|
1
|
+
{"version":3,"file":"glyph.js","names":[],"sources":["../../src/icons/glyph.ts"],"sourcesContent":["import { omit } from 'es-toolkit'\n\nimport { maxOf, minOf } from '../arrays'\nimport type { Fill, SceneNode, Stroke, VectorNetwork } from '../types'\nimport { readIcon, readIconTint } from './model'\n\n/** What reading an icon's paths needs of a graph. */\ninterface IconGraph {\n getChildren(id: string): SceneNode[]\n}\n\n/** Digits kept of each proportion, so float noise does not read as an edit. */\nconst PRECISION = 1000\n\nconst round = (value: number) => Math.round(value * PRECISION) / PRECISION\n\n/**\n * A path's points in proportion to their own bounds on each axis. Resizing scales vertices by\n * exact factors, so these proportions survive any resize, while the path boxes around them are\n * rounded to pixels and are left out.\n */\nfunction shape(network: VectorNetwork | null | undefined) {\n if (!network) return null\n // A saved document keeps coordinates as 32-bit floats, so they are read at that precision\n // either way; rounding alone would still split a value that lands on a rounding boundary.\n const f = Math.fround\n const xs = network.vertices.map((vertex) => f(vertex.x))\n const ys = network.vertices.map((vertex) => f(vertex.y))\n const minX = minOf(xs)\n const minY = minOf(ys)\n const sx = 1 / (maxOf(xs) - minX || 1)\n const sy = 1 / (maxOf(ys) - minY || 1)\n return {\n vertices: network.vertices.map((vertex) => [\n round((f(vertex.x) - minX) * sx),\n round((f(vertex.y) - minY) * sy),\n vertex.strokeCap ?? null,\n vertex.strokeJoin ?? null\n ]),\n segments: network.segments.map((segment) => [\n segment.start,\n segment.end,\n round(f(segment.tangentStart.x) * sx),\n round(f(segment.tangentStart.y) * sy),\n round(f(segment.tangentEnd.x) * sx),\n round(f(segment.tangentEnd.y) * sy)\n ]),\n regions: network.regions\n }\n}\n\n/**\n * Paint fields that read the same as when they are absent, which saving and loading a document\n * fills in: a normal blend and no dashes.\n */\nconst PAINT_DEFAULTS: Readonly<Record<string, unknown>> = { blendMode: 'NORMAL' }\n\n/**\n * A value described the same however it was stored: keys sorted, defaults and empty lists left\n * out, and numbers rounded, since a saved document keeps them at lower precision.\n */\nfunction canonical(value: unknown): unknown {\n // Stored as 32-bit floats too, so read at that precision before rounding, as coordinates are.\n if (typeof value === 'number') return round(Math.fround(value))\n if (Array.isArray(value)) return value.map(canonical)\n if (typeof value !== 'object' || value === null) return value\n const entries = Object.entries(value)\n .filter(\n ([key, item]) =>\n item !== undefined &&\n PAINT_DEFAULTS[key] !== item &&\n !(Array.isArray(item) && item.length === 0)\n )\n .sort(([a], [b]) => a.localeCompare(b))\n return Object.fromEntries(entries.map(([key, item]) => [key, canonical(item)]))\n}\n\n/**\n * A paint as it looks, leaving out the color when the icon's color sets it, and a stroke's\n * weight, which resizing scales.\n */\nfunction paint(fill: Fill | Stroke, tinted: boolean) {\n const { color, ...rest } = 'weight' in fill ? omit(fill, ['weight']) : fill\n return canonical(tinted ? rest : { ...rest, color })\n}\n\n/** FNV-1a, enough to tell one glyph from another without keeping the whole description. */\nfunction hash(text: string): string {\n let value = 0x811c9dc5\n for (let index = 0; index < text.length; index++) {\n value ^= text.charCodeAt(index)\n value = Math.imul(value, 0x01000193)\n }\n return (value >>> 0).toString(16).padStart(8, '0')\n}\n\n/**\n * A fingerprint of what an icon frame draws: which paths it holds and their shapes, stroke ends,\n * and paints. Resizing the icon, however unevenly, or changing its color leaves it unchanged;\n * editing points, rotating or fading a path, adding or removing one, or changing a color of the\n * icon's own changes it. Moving a whole path or changing its stroke weight does not count, since\n * resizing changes those by rounded amounts too.\n */\nexport function iconGlyph(graph: IconGraph, frame: SceneNode): string {\n const description = graph.getChildren(frame.id).map((path) => {\n const tint = readIconTint(path)\n return {\n type: path.type,\n shape: shape(path.vectorNetwork),\n fills: path.fills.map((fill) => paint(fill, tint.includes('fill'))),\n strokes: path.strokes.map((stroke) => paint(stroke, tint.includes('stroke'))),\n ends: [path.strokeCap, path.strokeJoin],\n // Resizing leaves these alone, so they count, unlike a path's place and stroke weight.\n rotation: round(path.rotation),\n opacity: round(path.opacity),\n visible: path.visible\n }\n })\n return hash(JSON.stringify(description))\n}\n\n/**\n * Whether an icon frame no longer draws the glyph it was placed with: its paths were edited,\n * added, or removed. An icon placed before glyphs were recorded counts as unedited.\n */\nexport function isIconModified(graph: IconGraph, frame: SceneNode): boolean {\n const glyph = readIcon(frame)?.glyph\n return glyph !== undefined && iconGlyph(graph, frame) !== glyph\n}\n"],"mappings":";;;;;AAYA,MAAM,YAAY;AAElB,MAAM,SAAS,UAAkB,KAAK,MAAM,QAAQ,SAAS,IAAI;;;;;;AAOjE,SAAS,MAAM,SAA2C;CACxD,IAAI,CAAC,SAAS,OAAO;CAGrB,MAAM,IAAI,KAAK;CACf,MAAM,KAAK,QA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AO,KAAK,MAAM;AAC5D"}
|
package/dist/icons/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
+
import { centerGlyph } from "./fit.js";
|
|
1
2
|
import { iconGlyph, isIconModified } from "./glyph.js";
|
|
2
3
|
import { ICON_NAME, ICON_PAINTS, Icon, IconOptions, IconPaint, iconOptionsSchema, iconSchema, iconTintSchema } from "./schema.js";
|
|
3
4
|
import { iconLayerName, iconNames, isNamedIcon, isPlacedIconName, readIcon, readIconTint, withIcon, withIconTint } from "./model.js";
|
|
4
|
-
export { ICON_NAME, ICON_PAINTS, Icon, IconOptions, IconPaint, iconGlyph, iconLayerName, iconNames, iconOptionsSchema, iconSchema, iconTintSchema, isIconModified, isNamedIcon, isPlacedIconName, readIcon, readIconTint, withIcon, withIconTint };
|
|
5
|
+
export { ICON_NAME, ICON_PAINTS, Icon, IconOptions, IconPaint, centerGlyph, iconGlyph, iconLayerName, iconNames, iconOptionsSchema, iconSchema, iconTintSchema, isIconModified, isNamedIcon, isPlacedIconName, readIcon, readIconTint, withIcon, withIconTint };
|
package/dist/icons/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ICON_NAME, ICON_PAINTS, iconOptionsSchema, iconSchema, iconTintSchema } from "./schema.js";
|
|
2
|
+
import { centerGlyph } from "./fit.js";
|
|
2
3
|
import { iconLayerName, iconNames, isNamedIcon, isPlacedIconName, readIcon, readIconTint, withIcon, withIconTint } from "./model.js";
|
|
3
4
|
import { iconGlyph, isIconModified } from "./glyph.js";
|
|
4
|
-
export { ICON_NAME, ICON_PAINTS, iconGlyph, iconLayerName, iconNames, iconOptionsSchema, iconSchema, iconTintSchema, isIconModified, isNamedIcon, isPlacedIconName, readIcon, readIconTint, withIcon, withIconTint };
|
|
5
|
+
export { ICON_NAME, ICON_PAINTS, centerGlyph, iconGlyph, iconLayerName, iconNames, iconOptionsSchema, iconSchema, iconTintSchema, isIconModified, isNamedIcon, isPlacedIconName, readIcon, readIconTint, withIcon, withIconTint };
|
package/dist/images.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { Matrix, Size } from "./primitives/index.js";
|
|
2
|
-
import { Fill } from "./types.js";
|
|
2
|
+
import { Fill, SceneNode } from "./types.js";
|
|
3
|
+
import { Mat3 } from "./matrix.js";
|
|
3
4
|
//#region src/images.d.ts
|
|
4
5
|
/**
|
|
5
6
|
* The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,
|
|
6
7
|
* so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may
|
|
7
|
-
* hold images under other names; anything that hands images to Figma still checks.
|
|
8
|
+
* hold images under other names; anything that hands images to Figma still checks. Each array is
|
|
9
|
+
* hashed once, as image bytes are never written into once read or stored.
|
|
8
10
|
*/
|
|
9
11
|
declare function computeImageHash(data: Uint8Array): string;
|
|
10
12
|
type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/avif';
|
|
@@ -51,7 +53,15 @@ declare function imageSize(data: Uint8Array): Size | null;
|
|
|
51
53
|
* centred. Figma starts a crop from it, as the image-space window a crop's transform holds.
|
|
52
54
|
*/
|
|
53
55
|
declare function coverImageTransform(width: number, height: number, imageWidth: number, imageHeight: number): Matrix;
|
|
54
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* Maps `img`'s pixels onto `node` as `fill` places them. `size` is the image's own size when `img`
|
|
58
|
+
* is a downscaled preview, so a tile keeps its size. A crop places the image by its transform;
|
|
59
|
+
* Fill, Fit and Tile ignore it, as Figma does, and turn the image by `imageRotation` first.
|
|
60
|
+
*/
|
|
61
|
+
declare function imageFillMatrix(fill: Fill, node: Pick<SceneNode, 'width' | 'height'>, imgW: number, imgH: number, size?: Size): Mat3;
|
|
62
|
+
/** The image a paint draws: an IMAGE paint's own, or the poster frame of a VIDEO paint. */
|
|
63
|
+
declare function drawnImageHash(paint: Pick<Fill, 'type' | 'imageHash'>): string | undefined;
|
|
64
|
+
/** The images `paints` show, by their hashes: a VIDEO paint shows its poster frame. */
|
|
55
65
|
declare function imagePaintHashes(paints: Iterable<Fill>): string[];
|
|
56
66
|
/**
|
|
57
67
|
* Copies the images `hashes` name from `from` into `to`, each as bytes of its own. An image is
|
|
@@ -59,5 +69,5 @@ declare function imagePaintHashes(paints: Iterable<Fill>): string[];
|
|
|
59
69
|
*/
|
|
60
70
|
declare function copyImages(from: ReadonlyMap<string, Uint8Array>, to: Map<string, Uint8Array>, hashes: Iterable<string>): void;
|
|
61
71
|
//#endregion
|
|
62
|
-
export { DataURL, IMPORTABLE_RASTER_TYPES, ImageHeader, ImageMimeType, computeImageHash, copyImages, coverImageTransform, imageDataURL, imageHeader, imageMimeType, imagePaintHashes, imageSize, isSVGFile, parseDataURL, svgDataURL };
|
|
72
|
+
export { DataURL, IMPORTABLE_RASTER_TYPES, ImageHeader, ImageMimeType, computeImageHash, copyImages, coverImageTransform, drawnImageHash, imageDataURL, imageFillMatrix, imageHeader, imageMimeType, imagePaintHashes, imageSize, isSVGFile, parseDataURL, svgDataURL };
|
|
63
73
|
//# sourceMappingURL=images.d.ts.map
|
package/dist/images.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"images.d.ts","names":[],"sources":["../src/images.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"images.d.ts","names":[],"sources":["../src/images.ts"],"mappings":";;;;;;;;;;iBAkBgB,iBAAiB,MAAM;KAQ3B;;cAYC,yBAAyB;;iBAStB,UAAU;EAAQ;EAAc;;UAM/B,oBAAoB;EACnC,MAAM;;;;;;iBAOQ,YAAY,MAAM,aAAa;;;;;iBAe/B,cAAc,MAAM,aAAa;UAIhC;;EAEf;EACA,OAAO;;;;;;;;iBASO,aAAa,cAAc;;iBAsB3B,aAAa,MAAM;;iBAKnB,WAAW;;iBAKX,UAAU,MAAM,aAAa;;;;;iBAS7B,oBACd,eACA,gBACA,oBACA,sBACC;;;;;;iBAYa,gBACd,MAAM,MACN,MAAM,KAAK,gCACX,cACA,cACA,OAAM,OACL;;iBAsCa,eAAe,OAAO,KAAK;;iBAK3B,iBAAiB,QAAQ,SAAS;;;;;iBAQlC,WACd,MAAM,oBAAoB,aAC1B,IAAI,YAAY,aAChB,QAAQ"}
|
package/dist/images.js
CHANGED
|
@@ -1,15 +1,23 @@
|
|
|
1
|
+
import Matrix from "./matrix.js";
|
|
1
2
|
import { sha1 } from "@noble/hashes/legacy.js";
|
|
2
3
|
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
3
4
|
import { imageSize as imageSize$1 } from "image-size";
|
|
4
5
|
import { fromUint8Array, isValid, toUint8Array } from "js-base64";
|
|
5
6
|
//#region src/images.ts
|
|
7
|
+
/** Hashes already computed, by the bytes hashed: a save would otherwise hash every image again. */
|
|
8
|
+
const imageHashes = /* @__PURE__ */ new WeakMap();
|
|
6
9
|
/**
|
|
7
10
|
* The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,
|
|
8
11
|
* so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may
|
|
9
|
-
* hold images under other names; anything that hands images to Figma still checks.
|
|
12
|
+
* hold images under other names; anything that hands images to Figma still checks. Each array is
|
|
13
|
+
* hashed once, as image bytes are never written into once read or stored.
|
|
10
14
|
*/
|
|
11
15
|
function computeImageHash(data) {
|
|
12
|
-
|
|
16
|
+
const known = imageHashes.get(data);
|
|
17
|
+
if (known) return known;
|
|
18
|
+
const hash = bytesToHex(sha1(data));
|
|
19
|
+
imageHashes.set(data, hash);
|
|
20
|
+
return hash;
|
|
13
21
|
}
|
|
14
22
|
/** The image types documents store, by the name `image-size` gives each format. */
|
|
15
23
|
const IMAGE_MIME_TYPES = {
|
|
@@ -119,9 +127,41 @@ function coverImageTransform(width, height, imageWidth, imageHeight) {
|
|
|
119
127
|
m12: (1 - m11) / 2
|
|
120
128
|
};
|
|
121
129
|
}
|
|
122
|
-
/**
|
|
130
|
+
/**
|
|
131
|
+
* Maps `img`'s pixels onto `node` as `fill` places them. `size` is the image's own size when `img`
|
|
132
|
+
* is a downscaled preview, so a tile keeps its size. A crop places the image by its transform;
|
|
133
|
+
* Fill, Fit and Tile ignore it, as Figma does, and turn the image by `imageRotation` first.
|
|
134
|
+
*/
|
|
135
|
+
function imageFillMatrix(fill, node, imgW, imgH, size = {
|
|
136
|
+
width: imgW,
|
|
137
|
+
height: imgH
|
|
138
|
+
}) {
|
|
139
|
+
const scaleMode = fill.imageScaleMode ?? "FILL";
|
|
140
|
+
if (scaleMode === "CROP" && fill.imageTransform) {
|
|
141
|
+
const t = fill.imageTransform;
|
|
142
|
+
const inverse = Matrix.invert(Matrix.fromAffine(t));
|
|
143
|
+
if (inverse) return Matrix.multiply(Matrix.scaled(node.width, node.height), inverse, Matrix.scaled(1 / imgW, 1 / imgH));
|
|
144
|
+
}
|
|
145
|
+
const radians = (fill.imageRotation ?? 0) * Math.PI / 180;
|
|
146
|
+
const cos = Math.abs(Math.cos(radians));
|
|
147
|
+
const sin = Math.abs(Math.sin(radians));
|
|
148
|
+
const turnedW = size.width * cos + size.height * sin;
|
|
149
|
+
const turnedH = size.width * sin + size.height * cos;
|
|
150
|
+
const turned = Matrix.multiply(Matrix.translated(turnedW / 2, turnedH / 2), Matrix.rotated(radians), Matrix.translated(-size.width / 2, -size.height / 2), Matrix.scaled(size.width / imgW, size.height / imgH));
|
|
151
|
+
if (scaleMode === "TILE") {
|
|
152
|
+
const scale = fill.scale && fill.scale > 0 ? fill.scale : 1;
|
|
153
|
+
return Matrix.multiply(Matrix.scaled(scale, scale), turned);
|
|
154
|
+
}
|
|
155
|
+
const scale = (scaleMode === "FIT" ? Math.min : Math.max)(node.width / turnedW, node.height / turnedH);
|
|
156
|
+
return Matrix.multiply(Matrix.translated((node.width - turnedW * scale) / 2, (node.height - turnedH * scale) / 2), Matrix.scaled(scale, scale), turned);
|
|
157
|
+
}
|
|
158
|
+
/** The image a paint draws: an IMAGE paint's own, or the poster frame of a VIDEO paint. */
|
|
159
|
+
function drawnImageHash(paint) {
|
|
160
|
+
return paint.type === "IMAGE" || paint.type === "VIDEO" ? paint.imageHash : void 0;
|
|
161
|
+
}
|
|
162
|
+
/** The images `paints` show, by their hashes: a VIDEO paint shows its poster frame. */
|
|
123
163
|
function imagePaintHashes(paints) {
|
|
124
|
-
return [...paints].flatMap((paint) => paint
|
|
164
|
+
return [...paints].flatMap((paint) => drawnImageHash(paint) ?? []);
|
|
125
165
|
}
|
|
126
166
|
/**
|
|
127
167
|
* Copies the images `hashes` name from `from` into `to`, each as bytes of its own. An image is
|
|
@@ -134,6 +174,6 @@ function copyImages(from, to, hashes) {
|
|
|
134
174
|
}
|
|
135
175
|
}
|
|
136
176
|
//#endregion
|
|
137
|
-
export { IMPORTABLE_RASTER_TYPES, computeImageHash, copyImages, coverImageTransform, imageDataURL, imageHeader, imageMimeType, imagePaintHashes, imageSize, isSVGFile, parseDataURL, svgDataURL };
|
|
177
|
+
export { IMPORTABLE_RASTER_TYPES, computeImageHash, copyImages, coverImageTransform, drawnImageHash, imageDataURL, imageFillMatrix, imageHeader, imageMimeType, imagePaintHashes, imageSize, isSVGFile, parseDataURL, svgDataURL };
|
|
138
178
|
|
|
139
179
|
//# sourceMappingURL=images.js.map
|
package/dist/images.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"images.js","names":["readImageHeader"],"sources":["../src/images.ts"],"sourcesContent":["import { sha1 } from '@noble/hashes/legacy.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { imageSize as readImageHeader } from 'image-size'\nimport { fromUint8Array, isValid, toUint8Array } from 'js-base64'\n\nimport type { Matrix, Size } from './primitives'\nimport type { Fill } from './types'\n\n/**\n * The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,\n * so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may\n * hold images under other names; anything that hands images to Figma still checks.\n */\nexport function computeImageHash(data: Uint8Array): string {\n return bytesToHex(sha1(data))\n}\n\nexport type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/avif'\n\n/** The image types documents store, by the name `image-size` gives each format. */\nconst IMAGE_MIME_TYPES: Partial<Record<string, ImageMimeType>> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif'\n}\n\n/** The raster types a dropped or pasted file can be imported as an image fill from. */\nexport const IMPORTABLE_RASTER_TYPES: ReadonlySet<string> = new Set([\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/gif',\n 'image/avif'\n])\n\n/** Whether a file is an SVG image, which some systems report without a media type. */\nexport function isSVGFile(file: { name: string; type: string }): boolean {\n return (\n file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))\n )\n}\n\nexport interface ImageHeader extends Size {\n type: ImageMimeType\n}\n\n/**\n * The type and size of a PNG, JPEG, GIF, WebP, or AVIF, read from its header by `image-size`; null for\n * bytes it cannot read and for other formats.\n */\nexport function imageHeader(data: Uint8Array): ImageHeader | null {\n let header: ReturnType<typeof readImageHeader>\n try {\n header = readImageHeader(data)\n } catch {\n return null\n }\n const type = header.type === undefined ? undefined : IMAGE_MIME_TYPES[header.type]\n return type ? { type, width: header.width, height: header.height } : null\n}\n\n/**\n * The media type of encoded image bytes, read from their header, for writing them out as a data\n * URL or file. Bytes it cannot read are reported as PNG, as image fills began.\n */\nexport function imageMimeType(data: Uint8Array): ImageMimeType {\n return imageHeader(data)?.type ?? 'image/png'\n}\n\nexport interface DataURL {\n /** The media type in lowercase, without parameters; `text/plain` when the URL names none. */\n mimeType: string\n bytes: Uint8Array\n}\n\n/**\n * The media type and bytes a `data:` URL carries: a Base64 body decoded, and a percent-encoded\n * one unescaped as UTF-8 text, as SVG and other markup are written. Null for anything else: Base64\n * cut short in transit, and escapes that are not UTF-8, such as a binary image escaped byte by\n * byte, which a reader that must take any data URL, such as `.pen` loading, gets from `fetch`.\n */\nexport function parseDataURL(url: string): DataURL | null {\n const match = /^\\s*data:([^,]*),(.*?)\\s*$/is.exec(url)\n if (!match) return null\n const [, header = '', body = ''] = match\n const params = header.split(';').map((param) => param.trim())\n const base64 = params.length > 1 && params.at(-1)?.toLowerCase() === 'base64'\n const mimeType = params[0]?.toLowerCase() || 'text/plain'\n let text: string\n try {\n // A `%` that starts no escape is a literal percent sign, as in `width=\"100%\"`.\n text = decodeURIComponent(body.replace(/%(?![\\da-f]{2})/gi, '%25'))\n } catch {\n return null\n }\n if (!base64) return { mimeType, bytes: new TextEncoder().encode(text) }\n const compact = text.replace(/\\s+/g, '')\n // Base64 one character past a whole group of four cannot be bytes: it was cut short.\n if (compact.replace(/={1,2}$/, '').length % 4 === 1 || !isValid(compact)) return null\n return { mimeType, bytes: toUint8Array(compact) }\n}\n\n/** Encoded image bytes as a Base64 data URL of the type their header names. */\nexport function imageDataURL(data: Uint8Array): string {\n return `data:${imageMimeType(data)};base64,${fromUint8Array(data)}`\n}\n\n/** SVG markup as a percent-encoded data URL, as CSS `url()` and `<img src>` take one. */\nexport function svgDataURL(svg: string): string {\n return `data:image/svg+xml,${encodeURIComponent(svg)}`\n}\n\n/** An image's size in pixels, read from its header; null for bytes it cannot read. */\nexport function imageSize(data: Uint8Array): Size | null {\n const header = imageHeader(data)\n return header && { width: header.width, height: header.height }\n}\n\n/**\n * The crop that shows an image as Fill does: scaled to cover a `width` × `height` layer and\n * centred. Figma starts a crop from it, as the image-space window a crop's transform holds.\n */\nexport function coverImageTransform(\n width: number,\n height: number,\n imageWidth: number,\n imageHeight: number\n): Matrix {\n const scale = Math.max(width / imageWidth, height / imageHeight)\n const m00 = width / scale / imageWidth\n const m11 = height / scale / imageHeight\n return { m00, m01: 0, m02: (1 - m00) / 2, m10: 0, m11, m12: (1 - m11) / 2 }\n}\n\n/** The images `paints` show, by their hashes. */\nexport function imagePaintHashes(paints: Iterable<Fill>): string[] {\n return [...paints].flatMap((paint) =>\n paint.type === 'IMAGE' && paint.imageHash ? [paint.imageHash] : []\n )\n}\n\n/**\n * Copies the images `hashes` name from `from` into `to`, each as bytes of its own. An image is\n * named by its content, so one `to` already holds stays.\n */\nexport function copyImages(\n from: ReadonlyMap<string, Uint8Array>,\n to: Map<string, Uint8Array>,\n hashes: Iterable<string>\n): void {\n for (const hash of hashes) {\n const bytes = from.get(hash)\n if (bytes && !to.has(hash)) to.set(hash, new Uint8Array(bytes))\n }\n}\n"],"mappings":";;;;;;;;;;AAaA,SAAgB,iBAAiB,MAA0B;CACzD,OAAO,WAAW,KAAK,IAAI,CAAC;AAC9B;;AAKA,MAAM,mBAA2D;CAC/D,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAM;CACN,MAAM;AACR;;AAGA,MAAa,0CAA+C,IAAI,IAAI;CAClE;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,UAAU,MAA+C;CACvE,OACE,KAAK,SAAS,mBAAoB,KAAK,SAAS,MAAM,KAAK,KAAK,YAAY,CAAC,CAAC,SAAS,MAAM;AAEjG;;;;;AAUA,SAAgB,YAAY,MAAsC;CAChE,IAAI;CACJ,IAAI;EACF,SAASA,YAAgB,IAAI;CAC/B,QAAQ;EACN,OAAO;CACT;CACA,MAAM,OAAO,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,iBAAiB,OAAO;CAC7E,OAAO,OAAO;EAAE;EAAM,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,IAAI;AACvE;;;;;AAMA,SAAgB,cAAc,MAAiC;CAC7D,OAAO,YAAY,IAAI,CAAC,EAAE,QAAQ;AACpC;;;;;;;AAcA,SAAgB,aAAa,KAA6B;CACxD,MAAM,QAAQ,+BAA+B,KAAK,GAAG;CACrD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,GAAG,SAAS,IAAI,OAAO,MAAM;CACnC,MAAM,SAAS,OAAO,MAAM,GAAG,CAAC,CAAC,KAAK,UAAU,MAAM,KAAK,CAAC;CAC5D,MAAM,SAAS,OAAO,SAAS,KAAK,OAAO,GAAG,EAAE,CA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K,MAAM,QAAQ,QAAQ;EACzB,MAAM,QAAQ,KAAK,IAAI,IAAI;EAC3B,IAAI,SAAS,CAAC,GAAG,IAAI,IAAI,GAAG,GAAG,IAAI,MAAM,IAAI,WAAW,KAAK,CAAC;CAChE;AACF"}
|
|
1
|
+
{"version":3,"file":"images.js","names":["readImageHeader","MatrixMath"],"sources":["../src/images.ts"],"sourcesContent":["import { sha1 } from '@noble/hashes/legacy.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { imageSize as readImageHeader } from 'image-size'\nimport { fromUint8Array, isValid, toUint8Array } from 'js-base64'\n\nimport MatrixMath, { type Mat3 } from './matrix'\nimport type { Matrix, Size } from './primitives'\nimport type { Fill, SceneNode } from './types'\n\n/** Hashes already computed, by the bytes hashed: a save would otherwise hash every image again. */\nconst imageHashes = new WeakMap<Uint8Array, string>()\n\n/**\n * The name an image's bytes are stored under: the hex SHA-1 of the bytes, as Figma names images,\n * so `.fig` files and the Figma clipboard can carry the name as it is. Documents saved before may\n * hold images under other names; anything that hands images to Figma still checks. Each array is\n * hashed once, as image bytes are never written into once read or stored.\n */\nexport function computeImageHash(data: Uint8Array): string {\n const known = imageHashes.get(data)\n if (known) return known\n const hash = bytesToHex(sha1(data))\n imageHashes.set(data, hash)\n return hash\n}\n\nexport type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/avif'\n\n/** The image types documents store, by the name `image-size` gives each format. */\nconst IMAGE_MIME_TYPES: Partial<Record<string, ImageMimeType>> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif'\n}\n\n/** The raster types a dropped or pasted file can be imported as an image fill from. */\nexport const IMPORTABLE_RASTER_TYPES: ReadonlySet<string> = new Set([\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/gif',\n 'image/avif'\n])\n\n/** Whether a file is an SVG image, which some systems report without a media type. */\nexport function isSVGFile(file: { name: string; type: string }): boolean {\n return (\n file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))\n )\n}\n\nexport interface ImageHeader extends Size {\n type: ImageMimeType\n}\n\n/**\n * The type and size of a PNG, JPEG, GIF, WebP, or AVIF, read from its header by `image-size`; null for\n * bytes it cannot read and for other formats.\n */\nexport function imageHeader(data: Uint8Array): ImageHeader | null {\n let header: ReturnType<typeof readImageHeader>\n try {\n header = readImageHeader(data)\n } catch {\n return null\n }\n const type = header.type === undefined ? undefined : IMAGE_MIME_TYPES[header.type]\n return type ? { type, width: header.width, height: header.height } : null\n}\n\n/**\n * The media type of encoded image bytes, read from their header, for writing them out as a data\n * URL or file. Bytes it cannot read are reported as PNG, as image fills began.\n */\nexport function imageMimeType(data: Uint8Array): ImageMimeType {\n return imageHeader(data)?.type ?? 'image/png'\n}\n\nexport interface DataURL {\n /** The media type in lowercase, without parameters; `text/plain` when the URL names none. */\n mimeType: string\n bytes: Uint8Array\n}\n\n/**\n * The media type and bytes a `data:` URL carries: a Base64 body decoded, and a percent-encoded\n * one unescaped as UTF-8 text, as SVG and other markup are written. Null for anything else: Base64\n * cut short in transit, and escapes that are not UTF-8, such as a binary image escaped byte by\n * byte, which a reader that must take any data URL, such as `.pen` loading, gets from `fetch`.\n */\nexport function parseDataURL(url: string): DataURL | null {\n const match = /^\\s*data:([^,]*),(.*?)\\s*$/is.exec(url)\n if (!match) return null\n const [, header = '', body = ''] = match\n const params = header.split(';').map((param) => param.trim())\n const base64 = params.length > 1 && params.at(-1)?.toLowerCase() === 'base64'\n const mimeType = params[0]?.toLowerCase() || 'text/plain'\n let text: string\n try {\n // A `%` that starts no escape is a literal percent sign, as in `width=\"100%\"`.\n text = decodeURIComponent(body.replace(/%(?![\\da-f]{2})/gi, '%25'))\n } catch {\n return null\n }\n if (!base64) return { mimeType, bytes: new TextEncoder().encode(text) }\n const compact = text.replace(/\\s+/g, '')\n // Base64 one character past a whole group of four cannot be bytes: it was cut short.\n if (compact.replace(/={1,2}$/, '').length % 4 === 1 || !isValid(compact)) return null\n return { mimeType, bytes: toUint8Array(compact) }\n}\n\n/** Encoded image bytes as a Base64 data URL of the type their header names. */\nexport function imageDataURL(data: Uint8Array): string {\n return `data:${imageMimeType(data)};base64,${fromUint8Array(data)}`\n}\n\n/** SVG markup as a percent-encoded data URL, as CSS `url()` and `<img src>` take one. */\nexport function svgDataURL(svg: string): string {\n return `data:image/svg+xml,${encodeURIComponent(svg)}`\n}\n\n/** An image's size in pixels, read from its header; null for bytes it cannot read. */\nexport function imageSize(data: Uint8Array): Size | null {\n const header = imageHeader(data)\n return header && { width: header.width, height: header.height }\n}\n\n/**\n * The crop that shows an image as Fill does: scaled to cover a `width` × `height` layer and\n * centred. Figma starts a crop from it, as the image-space window a crop's transform holds.\n */\nexport function coverImageTransform(\n width: number,\n height: number,\n imageWidth: number,\n imageHeight: number\n): Matrix {\n const scale = Math.max(width / imageWidth, height / imageHeight)\n const m00 = width / scale / imageWidth\n const m11 = height / scale / imageHeight\n return { m00, m01: 0, m02: (1 - m00) / 2, m10: 0, m11, m12: (1 - m11) / 2 }\n}\n\n/**\n * Maps `img`'s pixels onto `node` as `fill` places them. `size` is the image's own size when `img`\n * is a downscaled preview, so a tile keeps its size. A crop places the image by its transform;\n * Fill, Fit and Tile ignore it, as Figma does, and turn the image by `imageRotation` first.\n */\nexport function imageFillMatrix(\n fill: Fill,\n node: Pick<SceneNode, 'width' | 'height'>,\n imgW: number,\n imgH: number,\n size: Size = { width: imgW, height: imgH }\n): Mat3 {\n const scaleMode = fill.imageScaleMode ?? 'FILL'\n if (scaleMode === 'CROP' && fill.imageTransform) {\n const t = fill.imageTransform\n const inverse = MatrixMath.invert(MatrixMath.fromAffine(t))\n if (inverse)\n return MatrixMath.multiply(\n MatrixMath.scaled(node.width, node.height),\n inverse,\n MatrixMath.scaled(1 / imgW, 1 / imgH)\n )\n }\n\n const radians = ((fill.imageRotation ?? 0) * Math.PI) / 180\n const cos = Math.abs(Math.cos(radians))\n const sin = Math.abs(Math.sin(radians))\n const turnedW = size.width * cos + size.height * sin\n const turnedH = size.width * sin + size.height * cos\n const turned = MatrixMath.multiply(\n MatrixMath.translated(turnedW / 2, turnedH / 2),\n MatrixMath.rotated(radians),\n MatrixMath.translated(-size.width / 2, -size.height / 2),\n MatrixMath.scaled(size.width / imgW, size.height / imgH)\n )\n if (scaleMode === 'TILE') {\n const scale = fill.scale && fill.scale > 0 ? fill.scale : 1\n return MatrixMath.multiply(MatrixMath.scaled(scale, scale), turned)\n }\n const fit = scaleMode === 'FIT'\n const scale = (fit ? Math.min : Math.max)(node.width / turnedW, node.height / turnedH)\n return MatrixMath.multiply(\n MatrixMath.translated((node.width - turnedW * scale) / 2, (node.height - turnedH * scale) / 2),\n MatrixMath.scaled(scale, scale),\n turned\n )\n}\n\n/** The image a paint draws: an IMAGE paint's own, or the poster frame of a VIDEO paint. */\nexport function drawnImageHash(paint: Pick<Fill, 'type' | 'imageHash'>): string | undefined {\n return paint.type === 'IMAGE' || paint.type === 'VIDEO' ? paint.imageHash : undefined\n}\n\n/** The images `paints` show, by their hashes: a VIDEO paint shows its poster frame. */\nexport function imagePaintHashes(paints: Iterable<Fill>): string[] {\n return [...paints].flatMap((paint) => drawnImageHash(paint) ?? [])\n}\n\n/**\n * Copies the images `hashes` name from `from` into `to`, each as bytes of its own. An image is\n * named by its content, so one `to` already holds stays.\n */\nexport function copyImages(\n from: ReadonlyMap<string, Uint8Array>,\n to: Map<string, Uint8Array>,\n hashes: Iterable<string>\n): void {\n for (const hash of hashes) {\n const bytes = from.get(hash)\n if (bytes && !to.has(hash)) to.set(hash, new Uint8Array(bytes))\n }\n}\n"],"mappings":";;;;;;;AAUA,MAAM,8BAAc,IAAI,QAA4B;;;;;;;AAQpD,SAAgB,iBAAiB,MAA0B;CACzD,MAAM,QAAQ,YAAY,IAAI,IAAI;CAClC,IAAI,OAAO,OAAO;CAClB,MAAM,OAAO,WAAW,KAAK,IAAI,CAAC;CAClC,YAAY,IAAI,MAAM,I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} from "./overrides.js";
|
|
1
2
|
//#region src/instances/assignments.ts
|
|
2
3
|
/** SLOT_CONTENT is absent because it drives children, which `ownsSlotContent` keeps instead. */
|
|
3
4
|
const PROPERTY_REFERENCE_FIELDS = {
|
|
@@ -25,16 +26,47 @@ function definesProperty(graph, instance, propertyId) {
|
|
|
25
26
|
* that defines it, so the walk stops at an instance of that component even when it assigns
|
|
26
27
|
* nothing; otherwise an outer instance's unrelated property of the same id wins.
|
|
27
28
|
*/
|
|
28
|
-
function
|
|
29
|
+
function findEnclosingAssignment(graph, node, propertyId) {
|
|
29
30
|
let current = node.parentId ? graph.nodes.get(node.parentId) : void 0;
|
|
30
31
|
while (current) {
|
|
31
32
|
if (current.type === "INSTANCE") {
|
|
32
|
-
if (Object.hasOwn(current.componentPropertyAssignments, propertyId)) return
|
|
33
|
+
if (Object.hasOwn(current.componentPropertyAssignments, propertyId)) return {
|
|
34
|
+
instance: current,
|
|
35
|
+
value: current.componentPropertyAssignments[propertyId]
|
|
36
|
+
};
|
|
33
37
|
if (definesProperty(graph, current, propertyId)) return void 0;
|
|
34
38
|
}
|
|
35
39
|
current = current.parentId ? graph.nodes.get(current.parentId) : void 0;
|
|
36
40
|
}
|
|
37
41
|
}
|
|
42
|
+
function enclosingAssignment(graph, node, propertyId) {
|
|
43
|
+
return findEnclosingAssignment(graph, node, propertyId)?.value;
|
|
44
|
+
}
|
|
45
|
+
/** The instances around `node`, nearest first. */
|
|
46
|
+
function enclosingInstances(graph, node) {
|
|
47
|
+
const instances = [];
|
|
48
|
+
if (node.parentId) graph.closest(node.parentId, (ancestor) => {
|
|
49
|
+
if (ancestor.type === "INSTANCE") instances.push(ancestor);
|
|
50
|
+
return false;
|
|
51
|
+
});
|
|
52
|
+
return instances;
|
|
53
|
+
}
|
|
54
|
+
/** The outermost of `instances` that records `field` as an edit of `node`, or -1. */
|
|
55
|
+
function outermostEdit(instances, node, field) {
|
|
56
|
+
return instances.findLastIndex((instance) => instance.instanceOverrides.descendants.get(node.id)?.has(field));
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Whether a text edit of `layer` outranks the assignment that drives it. As in Figma, the edit
|
|
60
|
+
* made in the outer instance wins, and at the same level the assignment does. An assignment is
|
|
61
|
+
* made where an override of it is recorded, or else by the instance that holds it.
|
|
62
|
+
*/
|
|
63
|
+
function textEditOutranks(graph, layer, propertyId, assignment) {
|
|
64
|
+
const instances = enclosingInstances(graph, layer);
|
|
65
|
+
const textLevel = outermostEdit(instances, layer, "text");
|
|
66
|
+
if (textLevel < 0) return false;
|
|
67
|
+
const overridden = outermostEdit(instances, assignment.instance, assignmentOverrideField(propertyId));
|
|
68
|
+
return textLevel > (overridden < 0 ? instances.indexOf(assignment.instance) : overridden);
|
|
69
|
+
}
|
|
38
70
|
function hasEnclosingAssignment(graph, node, propertyId) {
|
|
39
71
|
return enclosingAssignment(graph, node, propertyId) !== void 0;
|
|
40
72
|
}
|
|
@@ -76,10 +108,11 @@ function propertyDrivenFields(graph, instChild, compChild) {
|
|
|
76
108
|
function assignedFieldValues(graph, instChild, compChild) {
|
|
77
109
|
const values = {};
|
|
78
110
|
for (const reference of compChild.componentPropertyReferences) {
|
|
79
|
-
const
|
|
80
|
-
if (
|
|
81
|
-
if (reference.field === "TEXT" && instChild.type === "TEXT")
|
|
82
|
-
|
|
111
|
+
const assignment = findEnclosingAssignment(graph, instChild, reference.propertyId);
|
|
112
|
+
if (!assignment) continue;
|
|
113
|
+
if (reference.field === "TEXT" && instChild.type === "TEXT") {
|
|
114
|
+
if (!textEditOutranks(graph, instChild, reference.propertyId, assignment)) values.text = assignment.value;
|
|
115
|
+
} else if (reference.field === "VISIBLE") values.visible = assignment.value === "true";
|
|
83
116
|
}
|
|
84
117
|
return values;
|
|
85
118
|
}
|