@open-pencil/scene-graph 0.15.1 → 0.16.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/behaviours/kinds.js +273 -0
  4. package/dist/chunks/behaviours/kinds.js.map +1 -0
  5. package/dist/chunks/behaviours/layers.js +607 -0
  6. package/dist/chunks/behaviours/layers.js.map +1 -0
  7. package/dist/chunks/behaviours/spec.js +181 -0
  8. package/dist/chunks/behaviours/spec.js.map +1 -0
  9. package/dist/chunks/buffered-events.js +57 -0
  10. package/dist/chunks/buffered-events.js.map +1 -0
  11. package/dist/chunks/color/contrast.js +57 -0
  12. package/dist/chunks/color/contrast.js.map +1 -0
  13. package/dist/chunks/{components/properties.js → color/index.js} +577 -522
  14. package/dist/chunks/color/index.js.map +1 -0
  15. package/dist/chunks/comments/document.js +32 -0
  16. package/dist/chunks/comments/document.js.map +1 -0
  17. package/dist/chunks/comments/list.js +182 -0
  18. package/dist/chunks/comments/list.js.map +1 -0
  19. package/dist/chunks/comments/merge.js +58 -0
  20. package/dist/chunks/comments/merge.js.map +1 -0
  21. package/dist/chunks/components/exposure.js +2291 -0
  22. package/dist/chunks/components/exposure.js.map +1 -0
  23. package/dist/chunks/components/variants.js +32 -0
  24. package/dist/chunks/components/variants.js.map +1 -0
  25. package/dist/chunks/coordinate.js +93 -55
  26. package/dist/chunks/coordinate.js.map +1 -1
  27. package/dist/chunks/css/grid.js +94 -0
  28. package/dist/chunks/css/grid.js.map +1 -0
  29. package/dist/chunks/css/index.js +160 -0
  30. package/dist/chunks/css/index.js.map +1 -0
  31. package/dist/chunks/fields/geometry.js +14 -0
  32. package/dist/chunks/fields/geometry.js.map +1 -0
  33. package/dist/chunks/group-bounds.js +104 -0
  34. package/dist/chunks/group-bounds.js.map +1 -0
  35. package/dist/chunks/icons/glyph.js +147 -0
  36. package/dist/chunks/icons/glyph.js.map +1 -0
  37. package/dist/chunks/index.js +1724 -663
  38. package/dist/chunks/index.js.map +1 -1
  39. package/dist/color.d.ts +72 -0
  40. package/dist/color.d.ts.map +1 -0
  41. package/dist/color.js +3 -0
  42. package/dist/constants.d.ts +2 -2
  43. package/dist/constants.js +2 -2
  44. package/dist/constants2.d.ts +3 -1
  45. package/dist/constants2.d.ts.map +1 -1
  46. package/dist/coordinate.d.ts +2 -448
  47. package/dist/coordinate.js +2 -2
  48. package/dist/copy.d.ts +1 -1
  49. package/dist/copy.js +1 -1
  50. package/dist/css.d.ts +39 -0
  51. package/dist/css.d.ts.map +1 -0
  52. package/dist/css.js +3 -0
  53. package/dist/geometry.d.ts +1 -1
  54. package/dist/geometry.js +1 -1
  55. package/dist/gradient.d.ts +51 -0
  56. package/dist/gradient.d.ts.map +1 -0
  57. package/dist/gradient.js +132 -0
  58. package/dist/gradient.js.map +1 -0
  59. package/dist/guides.d.ts +2 -2
  60. package/dist/guides.js +39 -0
  61. package/dist/guides.js.map +1 -0
  62. package/dist/hit-test.d.ts +2 -9
  63. package/dist/hit-test.js +176 -34
  64. package/dist/hit-test.js.map +1 -1
  65. package/dist/index.d.ts +4 -8
  66. package/dist/index.js +19 -5
  67. package/dist/instances.d.ts +2 -2
  68. package/dist/instances.js +2 -2
  69. package/dist/layout.d.ts +2 -0
  70. package/dist/layout.js +4 -0
  71. package/dist/node-defaults.d.ts +2 -8
  72. package/dist/node-defaults.js +2 -2
  73. package/dist/order-keys.d.ts +39 -0
  74. package/dist/order-keys.d.ts.map +1 -0
  75. package/dist/order-keys.js +136 -0
  76. package/dist/order-keys.js.map +1 -0
  77. package/dist/parse-path.d.ts +7 -1
  78. package/dist/parse-path.d.ts.map +1 -1
  79. package/dist/parse-path.js +6 -2
  80. package/dist/parse-path.js.map +1 -1
  81. package/dist/polygon.d.ts +53 -0
  82. package/dist/polygon.d.ts.map +1 -0
  83. package/dist/polygon.js +205 -0
  84. package/dist/polygon.js.map +1 -0
  85. package/dist/preview.d.ts +1 -1
  86. package/dist/random.d.ts +7 -0
  87. package/dist/random.d.ts.map +1 -0
  88. package/dist/random.js +2 -0
  89. package/dist/resize.d.ts +11 -2
  90. package/dist/resize.d.ts.map +1 -1
  91. package/dist/resize.js +2 -184
  92. package/dist/snap.d.ts +1 -1
  93. package/dist/text-direction.d.ts +13 -0
  94. package/dist/text-direction.d.ts.map +1 -0
  95. package/dist/text-direction.js +31 -0
  96. package/dist/text-direction.js.map +1 -0
  97. package/dist/text-picture.d.ts +1 -1
  98. package/dist/text-picture.d.ts.map +1 -1
  99. package/dist/text.d.ts +2 -0
  100. package/dist/text.js +3 -0
  101. package/dist/types.d.ts +2121 -15
  102. package/dist/types.d.ts.map +1 -1
  103. package/dist/types.js +2 -1
  104. package/dist/types2.d.ts +2 -2
  105. package/dist/undo.d.ts +2 -2
  106. package/dist/undo.js +2 -2
  107. package/dist/undo2.d.ts +29 -1
  108. package/dist/undo2.d.ts.map +1 -1
  109. package/dist/variables.d.ts +2 -29
  110. package/dist/variables.js +2 -2
  111. package/dist/variant-properties.d.ts +9 -1
  112. package/dist/variant-properties.d.ts.map +1 -1
  113. package/dist/variant-properties.js +36 -1
  114. package/dist/variant-properties.js.map +1 -1
  115. package/dist/vector-network.d.ts +1 -1
  116. package/dist/vector-network.js +1 -1
  117. package/package.json +60 -9
  118. package/src/behaviours/kinds.ts +185 -0
  119. package/src/behaviours/layers.ts +51 -0
  120. package/src/behaviours/model.ts +192 -0
  121. package/src/behaviours/schema.ts +58 -0
  122. package/src/behaviours/spec.ts +223 -0
  123. package/src/buffered-events.ts +64 -0
  124. package/src/color/contrast.ts +31 -0
  125. package/src/color/index.ts +88 -0
  126. package/src/color/management.ts +210 -0
  127. package/src/color/normalize.ts +7 -0
  128. package/src/color/okhcl.ts +201 -0
  129. package/src/comments/document.ts +51 -0
  130. package/src/comments/list.ts +52 -0
  131. package/src/comments/merge.ts +63 -0
  132. package/src/comments/threads.ts +156 -0
  133. package/src/components/exposure.ts +61 -0
  134. package/src/components/properties.ts +18 -15
  135. package/src/components/variants.ts +53 -0
  136. package/src/constants.ts +2 -0
  137. package/src/coordinate.ts +100 -43
  138. package/src/copy.ts +17 -6
  139. package/src/css/grid.ts +70 -0
  140. package/src/css/index.ts +9 -0
  141. package/src/css/layout.ts +53 -0
  142. package/src/css/shadows.ts +68 -0
  143. package/src/css/values.ts +42 -0
  144. package/src/export-format.ts +12 -0
  145. package/src/fields/geometry.ts +11 -0
  146. package/src/fields/text.ts +35 -0
  147. package/src/gradient.ts +166 -0
  148. package/src/group-bounds.ts +131 -0
  149. package/src/guides.ts +39 -0
  150. package/src/hit-test.ts +262 -46
  151. package/src/icons/glyph.ts +128 -0
  152. package/src/icons/model.ts +54 -0
  153. package/src/icons/schema.ts +18 -0
  154. package/src/index.ts +347 -57
  155. package/src/instance-overrides.ts +27 -0
  156. package/src/instances/content-size.ts +58 -0
  157. package/src/instances/copies.ts +239 -0
  158. package/src/instances/cycles.ts +73 -0
  159. package/src/instances/fields.ts +143 -0
  160. package/src/instances/main-component.ts +19 -0
  161. package/src/instances/placement.ts +29 -0
  162. package/src/instances/source-walk.ts +41 -0
  163. package/src/instances/sync.ts +600 -0
  164. package/src/instances/vector-geometry.ts +81 -0
  165. package/src/instances.ts +125 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +41 -12
  168. package/src/layout/index.ts +4 -0
  169. package/src/layout/keywords.ts +73 -0
  170. package/src/layout/sizing.ts +196 -0
  171. package/src/mutation-impact.ts +25 -10
  172. package/src/node-defaults.ts +50 -2
  173. package/src/order-keys.ts +162 -0
  174. package/src/parse-path.ts +10 -2
  175. package/src/plugin-data/field.ts +131 -0
  176. package/src/plugin-data/fields.ts +246 -0
  177. package/src/polygon.ts +211 -0
  178. package/src/preview.ts +1 -1
  179. package/src/random.ts +28 -0
  180. package/src/resize.ts +99 -12
  181. package/src/scaling/index.ts +2 -0
  182. package/src/scaling/node.ts +164 -0
  183. package/src/scaling/tree.ts +50 -0
  184. package/src/shaders/model.ts +98 -0
  185. package/src/shaders/schema.ts +48 -0
  186. package/src/shared-styles.ts +5 -2
  187. package/src/slots/authoring.ts +101 -0
  188. package/src/slots/content.ts +124 -0
  189. package/src/slots/frames.ts +160 -0
  190. package/src/slots/limits.ts +49 -0
  191. package/src/text/direction.ts +55 -0
  192. package/src/text/index.ts +3 -0
  193. package/src/text/lists.ts +138 -0
  194. package/src/text/paragraphs.ts +241 -0
  195. package/src/{text-picture.ts → text/picture.ts} +21 -29
  196. package/src/text/references.ts +50 -0
  197. package/src/transfer/apply.ts +84 -0
  198. package/src/transfer/history.ts +49 -0
  199. package/src/transfer/identity.ts +16 -0
  200. package/src/transfer/index.ts +6 -0
  201. package/src/transfer/nodes.ts +120 -0
  202. package/src/transfer/plan.ts +130 -0
  203. package/src/transfer/references.ts +9 -0
  204. package/src/transfer/remove.ts +39 -0
  205. package/src/transfer/validation.ts +59 -0
  206. package/src/transfer/variables.ts +82 -0
  207. package/src/types.ts +257 -13
  208. package/src/undo.ts +54 -2
  209. package/src/variables/bindings.ts +224 -0
  210. package/src/variables/fields.ts +43 -0
  211. package/src/variables/token.ts +14 -0
  212. package/src/variables/units.ts +15 -0
  213. package/src/variables.ts +118 -69
  214. package/src/variant-properties.ts +50 -0
  215. package/dist/chunks/components/properties.js.map +0 -1
  216. package/dist/chunks/export-scale.js +0 -19
  217. package/dist/chunks/export-scale.js.map +0 -1
  218. package/dist/coordinate.d.ts.map +0 -1
  219. package/dist/coordinate2.d.ts +0 -2
  220. package/dist/guides2.d.ts +0 -11
  221. package/dist/guides2.d.ts.map +0 -1
  222. package/dist/hit-test.d.ts.map +0 -1
  223. package/dist/layout-guides.d.ts +0 -2
  224. package/dist/layout-guides.js +0 -2
  225. package/dist/layout-guides2.d.ts +0 -16
  226. package/dist/layout-guides2.d.ts.map +0 -1
  227. package/dist/node-defaults.d.ts.map +0 -1
  228. package/dist/preview2.d.ts +0 -12
  229. package/dist/preview2.d.ts.map +0 -1
  230. package/dist/resize.js.map +0 -1
  231. package/dist/variables.d.ts.map +0 -1
  232. package/dist/vector-network2.d.ts +0 -32
  233. package/dist/vector-network2.d.ts.map +0 -1
  234. package/src/instance-overrides.test.ts +0 -67
package/src/hit-test.ts CHANGED
@@ -17,6 +17,21 @@ function hasVisibleFillOrStroke(node: SceneNode): boolean {
17
17
  return node.fills.some((f) => f.visible) || node.strokes.some((s) => s.visible)
18
18
  }
19
19
 
20
+ function isTopLevel(graph: SceneGraph, node: SceneNode): boolean {
21
+ const parent = node.parentId ? graph.nodes.get(node.parentId) : undefined
22
+ return parent?.type === 'CANVAS' || parent?.type === 'SECTION'
23
+ }
24
+
25
+ /**
26
+ * An open container whose empty area still belongs to it, as in Figma: a top-level frame with auto
27
+ * layout is selected, hovered, and dragged by its gaps and padding, while its children stay one
28
+ * click away, with or without a fill. A plain top-level frame's empty area is background, and a
29
+ * nested frame's empty area belongs to it only as a click target (see `frameChildAt`).
30
+ */
31
+ function ownsItsEmptyArea(graph: SceneGraph, node: SceneNode): boolean {
32
+ return node.type === 'FRAME' && node.layoutMode !== 'NONE' && isTopLevel(graph, node)
33
+ }
34
+
20
35
  function hasTransformedAncestor(
21
36
  node: SceneNode,
22
37
  graph: SceneGraph,
@@ -34,20 +49,22 @@ function hasTransformedAncestor(
34
49
  return transformed
35
50
  }
36
51
 
52
+ /** Whether the point lies in the node's box, grown by `pad` canvas units on every side. */
37
53
  function containsPoint(
38
54
  px: number,
39
55
  py: number,
40
56
  node: SceneNode,
41
57
  graph: SceneGraph,
42
- transformCache: Map<string, boolean>
58
+ transformCache: Map<string, boolean>,
59
+ pad = 0
43
60
  ): boolean {
44
61
  if (!hasTransformedAncestor(node, graph, transformCache)) {
45
62
  const absolute = graph.getAbsolutePosition(node.id)
46
63
  return (
47
- px >= absolute.x &&
48
- px <= absolute.x + node.width &&
49
- py >= absolute.y &&
50
- py <= absolute.y + node.height
64
+ px >= absolute.x - pad &&
65
+ px <= absolute.x + node.width + pad &&
66
+ py >= absolute.y - pad &&
67
+ py <= absolute.y + node.height + pad
51
68
  )
52
69
  }
53
70
 
@@ -57,7 +74,9 @@ function containsPoint(
57
74
  if (!inv) return false
58
75
 
59
76
  const [localX, localY] = Matrix.mapPoints(inv, [px, py])
60
- return localX >= 0 && localX <= node.width && localY >= 0 && localY <= node.height
77
+ return (
78
+ localX >= -pad && localX <= node.width + pad && localY >= -pad && localY <= node.height + pad
79
+ )
61
80
  }
62
81
 
63
82
  function hitTestOpaqueContainer(
@@ -67,10 +86,11 @@ function hitTestOpaqueContainer(
67
86
  child: SceneNode,
68
87
  childId: string,
69
88
  deep: boolean,
70
- transformCache: Map<string, boolean>
89
+ transformCache: Map<string, boolean>,
90
+ pad: number
71
91
  ): SceneNode | null {
72
92
  if (!containsPoint(px, py, child, graph, transformCache)) return null
73
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache)
93
+ const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
74
94
  if (childHit) return child
75
95
  if (hasVisibleFillOrStroke(child)) return child
76
96
  return null
@@ -82,34 +102,43 @@ function hitTestTransparentContainer(
82
102
  child: SceneNode,
83
103
  childId: string,
84
104
  deep: boolean,
85
- transformCache: Map<string, boolean>
105
+ transformCache: Map<string, boolean>,
106
+ pad: number
86
107
  ): SceneNode | null {
87
108
  if (child.type === 'GROUP') {
88
- if (!containsPoint(px, py, child, graph, transformCache)) return null
89
-
90
- if (deep) return hitTestChildren(graph, px, py, childId, deep, transformCache) ?? child
91
-
92
- return child
109
+ // A group fits its layers, so a padded click on one at its edge falls just outside it.
110
+ if (!containsPoint(px, py, child, graph, transformCache, pad)) return null
111
+ const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
112
+ if (childHit) return deep ? childHit : child
113
+ return containsPoint(px, py, child, graph, transformCache) ? child : null
93
114
  }
94
115
 
95
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache)
116
+ const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
96
117
  if (childHit) {
97
118
  if (child.locked) return child
98
119
  return childHit
99
120
  }
100
121
 
101
- if (containsPoint(px, py, child, graph, transformCache) && hasVisibleFillOrStroke(child))
122
+ if (
123
+ containsPoint(px, py, child, graph, transformCache) &&
124
+ (hasVisibleFillOrStroke(child) || ownsItsEmptyArea(graph, child))
125
+ )
102
126
  return child
103
127
  return null
104
128
  }
105
129
 
130
+ /**
131
+ * The topmost layer under the point among a container's children. `pad`, in canvas units, grows
132
+ * each leaf layer's box, as Figma takes a click a few screen pixels outside a shape.
133
+ */
106
134
  function hitTestChildren(
107
135
  graph: SceneGraph,
108
136
  px: number,
109
137
  py: number,
110
138
  parentId: string,
111
139
  deep = false,
112
- transformCache = new Map<string, boolean>()
140
+ transformCache = new Map<string, boolean>(),
141
+ pad = 0
113
142
  ): SceneNode | null {
114
143
  const parent = graph.nodes.get(parentId)
115
144
  if (!parent) return null
@@ -124,17 +153,26 @@ function hitTestChildren(
124
153
  if (!child || child.internalOnly || !child.visible) continue
125
154
  if (CONTAINER_TYPES.has(child.type)) {
126
155
  if (OPAQUE_CONTAINER_TYPES.has(child.type) && !deep) {
127
- const hit = hitTestOpaqueContainer(graph, px, py, child, childId, deep, transformCache)
156
+ const hit = hitTestOpaqueContainer(graph, px, py, child, childId, deep, transformCache, pad)
128
157
  if (hit) return hit
129
158
  continue
130
159
  }
131
160
 
132
- const hit = hitTestTransparentContainer(graph, px, py, child, childId, deep, transformCache)
161
+ const hit = hitTestTransparentContainer(
162
+ graph,
163
+ px,
164
+ py,
165
+ child,
166
+ childId,
167
+ deep,
168
+ transformCache,
169
+ pad
170
+ )
133
171
  if (hit) return hit
134
172
  continue
135
173
  }
136
174
 
137
- if (containsPoint(px, py, child, graph, transformCache)) return child
175
+ if (containsPoint(px, py, child, graph, transformCache, pad)) return child
138
176
  }
139
177
 
140
178
  return null
@@ -154,52 +192,230 @@ export function hitTestDeep(
154
192
  graph: SceneGraph,
155
193
  px: number,
156
194
  py: number,
157
- scopeId?: string
195
+ scopeId?: string,
196
+ pad = 0
158
197
  ): SceneNode | null {
159
198
  const scope = scopeId ?? graph.rootId
160
- return hitTestChildren(graph, px, py, scope, true)
199
+ return hitTestChildren(graph, px, py, scope, true, new Map(), pad)
200
+ }
201
+
202
+ /**
203
+ * A container a click looks into by itself, as in Figma: a top-level frame (on the page or in a
204
+ * section) or a section that holds layers, and a component set.
205
+ */
206
+ function opensByItself(graph: SceneGraph, node: SceneNode): boolean {
207
+ if (node.type === 'COMPONENT_SET') return true
208
+ if (node.childIds.length === 0) return false
209
+ if (node.type === 'SECTION') return true
210
+ return node.type === 'FRAME' && isTopLevel(graph, node)
161
211
  }
162
212
 
163
- function hitTestFrameChildren(
213
+ /**
214
+ * The topmost frame among a container's children whose bounds hold the point, filled or not: in
215
+ * Figma a click on the empty area of a frame inside an open container, or of an empty frame on the
216
+ * page or in a section, selects that frame, while a deep (⌘) click looks through it.
217
+ */
218
+ function frameChildAt(
219
+ graph: SceneGraph,
220
+ container: SceneNode,
221
+ px: number,
222
+ py: number
223
+ ): SceneNode | null {
224
+ const transformCache = new Map<string, boolean>()
225
+ for (let i = container.childIds.length - 1; i >= 0; i--) {
226
+ const child = graph.nodes.get(container.childIds[i])
227
+ if (!child || child.internalOnly || !child.visible || child.type !== 'FRAME') continue
228
+ // A board, such as a top-level frame in a section, keeps its empty area as background.
229
+ if (opensByItself(graph, child) && !ownsItsEmptyArea(graph, child)) continue
230
+ if (containsPoint(px, py, child, graph, transformCache)) return child
231
+ }
232
+ return null
233
+ }
234
+
235
+ /**
236
+ * The containers the selection opens: every ancestor of a selected layer inside the scope, and a
237
+ * selected container itself, so a click inside it selects the layer under the point, as in Figma.
238
+ * A selected group or boolean stays closed: clicking inside it keeps it selected.
239
+ */
240
+ function openedBySelection(
241
+ graph: SceneGraph,
242
+ selectedIds: ReadonlySet<string>,
243
+ scopeId: string
244
+ ): Set<string> {
245
+ const ancestors = new Set<string>()
246
+ for (const id of selectedIds) {
247
+ const node = graph.nodes.get(id)
248
+ if (
249
+ node &&
250
+ node.childIds.length > 0 &&
251
+ node.type !== 'GROUP' &&
252
+ node.type !== 'BOOLEAN_OPERATION'
253
+ )
254
+ ancestors.add(id)
255
+ let parentId = node?.parentId
256
+ while (parentId && parentId !== scopeId && !ancestors.has(parentId)) {
257
+ ancestors.add(parentId)
258
+ parentId = graph.nodes.get(parentId)?.parentId
259
+ }
260
+ }
261
+ return ancestors
262
+ }
263
+
264
+ /**
265
+ * The layer a click selects, as in Figma. It walks from the scope down to the deepest layer under
266
+ * the point and stops at the first layer that is not open. Top-level frames and sections with
267
+ * layers and component sets are open, and so is every ancestor of the selection, so clicks reach
268
+ * the siblings of selected layers. Where every layer under the point is open, a container opened
269
+ * by the selection is selected, so is a top-level frame with auto layout, and a plain top-level
270
+ * frame or a section is not.
271
+ */
272
+ export function hitTestSelectable(
164
273
  graph: SceneGraph,
165
274
  px: number,
166
275
  py: number,
167
- parentId: string,
168
- offsetX: number,
169
- offsetY: number,
170
- excludeIds: Set<string>
276
+ scopeId: string,
277
+ selectedIds: ReadonlySet<string>,
278
+ pad = 0
171
279
  ): SceneNode | null {
172
- const parent = graph.nodes.get(parentId)
173
- if (!parent) return null
280
+ const deepest = hitTestChildren(graph, px, py, scopeId, true, new Map(), pad)
281
+ if (!deepest) {
282
+ const scope = graph.nodes.get(scopeId)
283
+ return scope ? frameChildAt(graph, scope, px, py) : null
284
+ }
174
285
 
175
- let best: SceneNode | null = null
286
+ const chain: SceneNode[] = []
287
+ for (let node: SceneNode | undefined = deepest; node && node.id !== scopeId;) {
288
+ chain.unshift(node)
289
+ node = node.parentId ? graph.nodes.get(node.parentId) : undefined
290
+ }
176
291
 
177
- for (const childId of parent.childIds) {
178
- if (excludeIds.has(childId)) continue
179
- const child = graph.nodes.get(childId)
180
- if (!child || child.internalOnly || !child.visible) continue
292
+ const opened = openedBySelection(graph, selectedIds, scopeId)
293
+
294
+ for (const node of chain) {
295
+ // A locked layer stands in for everything inside it.
296
+ if (node.locked) return node
297
+ if (!opened.has(node.id) && !opensByItself(graph, node)) return node
298
+ }
299
+ const last = chain.at(-1)
300
+ if (!last) return null
301
+ const frame = frameChildAt(graph, last, px, py)
302
+ if (frame) return frame
303
+ if (ownsItsEmptyArea(graph, last)) return last
304
+ return opened.has(last.id) && !opensByItself(graph, last) ? last : null
305
+ }
306
+
307
+ /** Whether a click looks into this container rather than selecting it; see `hitTestSelectable`. */
308
+ export function isOpenContainer(graph: SceneGraph, nodeId: string): boolean {
309
+ const node = graph.nodes.get(nodeId)
310
+ return node !== undefined && opensByItself(graph, node)
311
+ }
312
+
313
+ /**
314
+ * The innermost open container under the point when every layer there is open: a marquee starting
315
+ * here selects that container's layers, as in Figma.
316
+ */
317
+ export function hitTestOpenContainer(
318
+ graph: SceneGraph,
319
+ px: number,
320
+ py: number,
321
+ scopeId: string
322
+ ): SceneNode | null {
323
+ const deepest = hitTestChildren(graph, px, py, scopeId, true)
324
+ for (let node: SceneNode | undefined = deepest ?? undefined; node && node.id !== scopeId;) {
325
+ if (!opensByItself(graph, node) || ownsItsEmptyArea(graph, node)) return null
326
+ node = node.parentId ? graph.nodes.get(node.parentId) : undefined
327
+ }
328
+ return deepest
329
+ }
181
330
 
182
- const ax = offsetX + child.x
183
- const ay = offsetY + child.y
331
+ /** Whether the point lies inside the node's rotated and flipped bounds. */
332
+ export function isPointInNode(graph: SceneGraph, nodeId: string, px: number, py: number): boolean {
333
+ const node = graph.nodes.get(nodeId)
334
+ return node !== undefined && containsPoint(px, py, node, graph, new Map())
335
+ }
184
336
 
185
- if (!CONTAINER_TYPES.has(child.type)) continue
186
- if (px < ax || px > ax + child.width || py < ay || py > ay + child.height) continue
337
+ /** Which layers take a drop, and which are only looked through, as in Figma. */
338
+ interface DropRules {
339
+ takes: (node: SceneNode) => boolean
340
+ passThrough: ReadonlySet<NodeType>
341
+ }
187
342
 
188
- best = child
343
+ const LAYER_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'COMPONENT', 'INSTANCE'])
344
+ const COMPONENT_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'INSTANCE'])
189
345
 
190
- const deeper = hitTestFrameChildren(graph, px, py, childId, ax, ay, excludeIds)
191
- if (deeper) best = deeper
346
+ function dropRules(options: DropTargetOptions): DropRules {
347
+ const { componentSetIds } = options
348
+ if (!componentSetIds) {
349
+ return {
350
+ takes: (node) => LAYER_TARGETS.has(node.type),
351
+ passThrough: new Set(['GROUP', 'COMPONENT_SET'])
352
+ }
192
353
  }
354
+ // Components never go into other components, and a set only takes back its own variants.
355
+ return {
356
+ takes: (node) =>
357
+ COMPONENT_TARGETS.has(node.type) ||
358
+ (node.type === 'COMPONENT_SET' && componentSetIds.has(node.id)),
359
+ passThrough: new Set(['GROUP'])
360
+ }
361
+ }
193
362
 
194
- return best
363
+ function dropTargetIn(
364
+ graph: SceneGraph,
365
+ px: number,
366
+ py: number,
367
+ parent: SceneNode,
368
+ excludeIds: ReadonlySet<string>,
369
+ rules: DropRules,
370
+ transformCache: Map<string, boolean>
371
+ ): SceneNode | null {
372
+ // A clipped-away part of a child is not under the cursor.
373
+ if (
374
+ parent.type !== 'CANVAS' &&
375
+ parent.clipsContent &&
376
+ !containsPoint(px, py, parent, graph, transformCache)
377
+ )
378
+ return null
379
+
380
+ for (let i = parent.childIds.length - 1; i >= 0; i--) {
381
+ const childId = parent.childIds[i]
382
+ if (excludeIds.has(childId)) continue
383
+ const child = graph.nodes.get(childId)
384
+ if (!child || child.internalOnly || !child.visible || child.locked) continue
385
+ const target = rules.takes(child)
386
+ if (!target && !rules.passThrough.has(child.type)) continue
387
+
388
+ const deeper = dropTargetIn(graph, px, py, child, excludeIds, rules, transformCache)
389
+ if (deeper) return deeper
390
+ if (target && containsPoint(px, py, child, graph, transformCache)) return child
391
+ }
392
+
393
+ return null
394
+ }
395
+
396
+ export interface DropTargetOptions {
397
+ /**
398
+ * Set when the dropped layers are all main components: the component sets they come from.
399
+ * Components then go only into frames, sections, instances, and those sets.
400
+ */
401
+ componentSetIds?: ReadonlySet<string>
195
402
  }
196
403
 
197
- export function hitTestFrame(
404
+ /**
405
+ * The topmost unlocked frame, section, component, or instance under the point, in its rotated
406
+ * shape and inside its clipping ancestors. Groups and component sets are looked through but never
407
+ * returned, except that a set takes dropped components; locked layers and their contents are
408
+ * skipped.
409
+ */
410
+ export function hitTestDropTarget(
198
411
  graph: SceneGraph,
199
412
  px: number,
200
413
  py: number,
201
- excludeIds: Set<string>,
202
- scopeId?: string
414
+ excludeIds: ReadonlySet<string>,
415
+ scopeId?: string,
416
+ options: DropTargetOptions = {}
203
417
  ): SceneNode | null {
204
- return hitTestFrameChildren(graph, px, py, scopeId ?? graph.rootId, 0, 0, excludeIds)
418
+ const scope = graph.nodes.get(scopeId ?? graph.rootId)
419
+ if (!scope) return null
420
+ return dropTargetIn(graph, px, py, scope, excludeIds, dropRules(options), new Map())
205
421
  }
@@ -0,0 +1,128 @@
1
+ import { omit } from 'es-toolkit'
2
+
3
+ import type { Fill, SceneNode, Stroke, VectorNetwork } from '../types'
4
+ import { readIcon, readIconTint } from './model'
5
+
6
+ /** What reading an icon's paths needs of a graph. */
7
+ interface IconGraph {
8
+ getChildren(id: string): SceneNode[]
9
+ }
10
+
11
+ /** Digits kept of each proportion, so float noise does not read as an edit. */
12
+ const PRECISION = 1000
13
+
14
+ const round = (value: number) => Math.round(value * PRECISION) / PRECISION
15
+
16
+ /**
17
+ * A path's points in proportion to their own bounds on each axis. Resizing scales vertices by
18
+ * exact factors, so these proportions survive any resize, while the path boxes around them are
19
+ * rounded to pixels and are left out.
20
+ */
21
+ function shape(network: VectorNetwork | null | undefined) {
22
+ if (!network) return null
23
+ // A saved document keeps coordinates as 32-bit floats, so they are read at that precision
24
+ // either way; rounding alone would still split a value that lands on a rounding boundary.
25
+ const f = Math.fround
26
+ const xs = network.vertices.map((vertex) => f(vertex.x))
27
+ const ys = network.vertices.map((vertex) => f(vertex.y))
28
+ const minX = Math.min(...xs)
29
+ const minY = Math.min(...ys)
30
+ const sx = 1 / (Math.max(...xs) - minX || 1)
31
+ const sy = 1 / (Math.max(...ys) - minY || 1)
32
+ return {
33
+ vertices: network.vertices.map((vertex) => [
34
+ round((f(vertex.x) - minX) * sx),
35
+ round((f(vertex.y) - minY) * sy),
36
+ vertex.strokeCap ?? null,
37
+ vertex.strokeJoin ?? null
38
+ ]),
39
+ segments: network.segments.map((segment) => [
40
+ segment.start,
41
+ segment.end,
42
+ round(f(segment.tangentStart.x) * sx),
43
+ round(f(segment.tangentStart.y) * sy),
44
+ round(f(segment.tangentEnd.x) * sx),
45
+ round(f(segment.tangentEnd.y) * sy)
46
+ ]),
47
+ regions: network.regions
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Paint fields that read the same as when they are absent, which saving and loading a document
53
+ * fills in: a normal blend and no dashes.
54
+ */
55
+ const PAINT_DEFAULTS: Readonly<Record<string, unknown>> = { blendMode: 'NORMAL' }
56
+
57
+ /**
58
+ * A value described the same however it was stored: keys sorted, defaults and empty lists left
59
+ * out, and numbers rounded, since a saved document keeps them at lower precision.
60
+ */
61
+ function canonical(value: unknown): unknown {
62
+ // Stored as 32-bit floats too, so read at that precision before rounding, as coordinates are.
63
+ if (typeof value === 'number') return round(Math.fround(value))
64
+ if (Array.isArray(value)) return value.map(canonical)
65
+ if (typeof value !== 'object' || value === null) return value
66
+ const entries = Object.entries(value)
67
+ .filter(
68
+ ([key, item]) =>
69
+ item !== undefined &&
70
+ PAINT_DEFAULTS[key] !== item &&
71
+ !(Array.isArray(item) && item.length === 0)
72
+ )
73
+ .sort(([a], [b]) => a.localeCompare(b))
74
+ return Object.fromEntries(entries.map(([key, item]) => [key, canonical(item)]))
75
+ }
76
+
77
+ /**
78
+ * A paint as it looks, leaving out the color when the icon's color sets it, and a stroke's
79
+ * weight, which resizing scales.
80
+ */
81
+ function paint(fill: Fill | Stroke, tinted: boolean) {
82
+ const { color, ...rest } = 'weight' in fill ? omit(fill, ['weight']) : fill
83
+ return canonical(tinted ? rest : { ...rest, color })
84
+ }
85
+
86
+ /** FNV-1a, enough to tell one glyph from another without keeping the whole description. */
87
+ function hash(text: string): string {
88
+ let value = 0x811c9dc5
89
+ for (let index = 0; index < text.length; index++) {
90
+ value ^= text.charCodeAt(index)
91
+ value = Math.imul(value, 0x01000193)
92
+ }
93
+ return (value >>> 0).toString(16).padStart(8, '0')
94
+ }
95
+
96
+ /**
97
+ * A fingerprint of what an icon frame draws: which paths it holds and their shapes, stroke ends,
98
+ * and paints. Resizing the icon, however unevenly, or changing its color leaves it unchanged;
99
+ * editing points, rotating or fading a path, adding or removing one, or changing a color of the
100
+ * icon's own changes it. Moving a whole path or changing its stroke weight does not count, since
101
+ * resizing changes those by rounded amounts too.
102
+ */
103
+ export function iconGlyph(graph: IconGraph, frame: SceneNode): string {
104
+ const description = graph.getChildren(frame.id).map((path) => {
105
+ const tint = readIconTint(path)
106
+ return {
107
+ type: path.type,
108
+ shape: shape(path.vectorNetwork),
109
+ fills: path.fills.map((fill) => paint(fill, tint.includes('fill'))),
110
+ strokes: path.strokes.map((stroke) => paint(stroke, tint.includes('stroke'))),
111
+ ends: [path.strokeCap, path.strokeJoin],
112
+ // Resizing leaves these alone, so they count, unlike a path's place and stroke weight.
113
+ rotation: round(path.rotation),
114
+ opacity: round(path.opacity),
115
+ visible: path.visible
116
+ }
117
+ })
118
+ return hash(JSON.stringify(description))
119
+ }
120
+
121
+ /**
122
+ * Whether an icon frame no longer draws the glyph it was placed with: its paths were edited,
123
+ * added, or removed. An icon placed before glyphs were recorded counts as unedited.
124
+ */
125
+ export function isIconModified(graph: IconGraph, frame: SceneNode): boolean {
126
+ const glyph = readIcon(frame)?.glyph
127
+ return glyph !== undefined && iconGlyph(graph, frame) !== glyph
128
+ }
@@ -0,0 +1,54 @@
1
+ import { readPluginData, withPluginData } from '../plugin-data/field'
2
+ import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'
3
+ import type { SceneNode } from '../types'
4
+ import type { Icon, IconPaint } from './schema'
5
+
6
+ /** The icon a frame draws, or null when it is not an icon or its data is unreadable. */
7
+ export function readIcon(node: SceneNode): Icon | null {
8
+ return readPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.icon) ?? null
9
+ }
10
+
11
+ /** The node's plugin data with the icon set, or removed when null. */
12
+ export function withIcon(node: SceneNode, icon: Icon | null): SceneNode['pluginData'] {
13
+ return withPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.icon, icon ?? undefined)
14
+ }
15
+
16
+ /** The layer name an icon is placed with: its name in the set, such as `cat` for `mdi:cat`. */
17
+ export function iconLayerName(name: string): string {
18
+ return name.slice(name.indexOf(':') + 1)
19
+ }
20
+
21
+ /**
22
+ * Whether `layerName` is the name an icon `name` was placed with, rather than one someone gave
23
+ * it: `cat`, or `Icon / mdi:cat` as icons were named before.
24
+ */
25
+ export function isPlacedIconName(layerName: string, name: string): boolean {
26
+ return layerName === iconLayerName(name) || layerName === `Icon / ${name}`
27
+ }
28
+
29
+ /** The names of the icons among `nodes`, each once, in the order they are first met. */
30
+ export function iconNames(nodes: Iterable<SceneNode>): string[] {
31
+ const names = new Set<string>()
32
+ for (const node of nodes) {
33
+ const icon = readIcon(node)
34
+ if (icon) names.add(icon.name)
35
+ }
36
+ return [...names]
37
+ }
38
+
39
+ /** The paints of an icon path that its icon's color sets; none when it keeps its own colors. */
40
+ export function readIconTint(node: SceneNode): readonly IconPaint[] {
41
+ return readPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.iconTint) ?? []
42
+ }
43
+
44
+ /** The path's plugin data with its tinted paints, or removed when there are none. */
45
+ export function withIconTint(
46
+ node: SceneNode,
47
+ paints: readonly IconPaint[]
48
+ ): SceneNode['pluginData'] {
49
+ return withPluginData(
50
+ node.pluginData,
51
+ OPEN_PENCIL_PLUGIN_DATA.iconTint,
52
+ paints.length > 0 ? [...paints] : undefined
53
+ )
54
+ }
@@ -0,0 +1,18 @@
1
+ import * as v from 'valibot'
2
+
3
+ /** An icon's name in its set, `prefix:name`, as Iconify names icons. */
4
+ export const ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*:[a-z0-9]+(?:[-_][a-z0-9]+)*$/
5
+
6
+ export const iconSchema = v.object({
7
+ name: v.pipe(v.string(), v.regex(ICON_NAME)),
8
+ /** A fingerprint of the glyph as placed, to tell when its paths were edited; see `iconGlyph`. */
9
+ glyph: v.optional(v.string())
10
+ })
11
+
12
+ /** An icon a frame draws. */
13
+ export type Icon = v.InferOutput<typeof iconSchema>
14
+
15
+ export const ICON_PAINTS = ['fill', 'stroke'] as const
16
+ export type IconPaint = (typeof ICON_PAINTS)[number]
17
+
18
+ export const iconTintSchema = v.pipe(v.array(v.picklist(ICON_PAINTS)), v.minLength(1))