@open-pencil/scene-graph 0.15.0 → 0.16.0-beta.1

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 (232) 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 +596 -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} +573 -521
  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 +2021 -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/fields/text.js +36 -0
  34. package/dist/chunks/fields/text.js.map +1 -0
  35. package/dist/chunks/group-bounds.js +104 -0
  36. package/dist/chunks/group-bounds.js.map +1 -0
  37. package/dist/chunks/icons/glyph.js +147 -0
  38. package/dist/chunks/icons/glyph.js.map +1 -0
  39. package/dist/chunks/index.js +1712 -662
  40. package/dist/chunks/index.js.map +1 -1
  41. package/dist/color.d.ts +72 -0
  42. package/dist/color.d.ts.map +1 -0
  43. package/dist/color.js +3 -0
  44. package/dist/constants.d.ts +2 -2
  45. package/dist/constants.js +2 -2
  46. package/dist/constants2.d.ts +3 -1
  47. package/dist/constants2.d.ts.map +1 -1
  48. package/dist/coordinate.d.ts +2 -448
  49. package/dist/coordinate.js +2 -2
  50. package/dist/copy.d.ts +1 -1
  51. package/dist/copy.js +1 -1
  52. package/dist/css.d.ts +39 -0
  53. package/dist/css.d.ts.map +1 -0
  54. package/dist/css.js +3 -0
  55. package/dist/geometry.d.ts +1 -1
  56. package/dist/geometry.js +1 -1
  57. package/dist/gradient.d.ts +51 -0
  58. package/dist/gradient.d.ts.map +1 -0
  59. package/dist/gradient.js +132 -0
  60. package/dist/gradient.js.map +1 -0
  61. package/dist/guides.d.ts +2 -2
  62. package/dist/guides.js +39 -0
  63. package/dist/guides.js.map +1 -0
  64. package/dist/hit-test.d.ts +2 -9
  65. package/dist/hit-test.js +154 -18
  66. package/dist/hit-test.js.map +1 -1
  67. package/dist/index.d.ts +4 -8
  68. package/dist/index.js +20 -5
  69. package/dist/instances.d.ts +2 -2
  70. package/dist/instances.js +2 -2
  71. package/dist/layout.d.ts +2 -0
  72. package/dist/layout.js +4 -0
  73. package/dist/node-defaults.d.ts +2 -8
  74. package/dist/node-defaults.js +2 -2
  75. package/dist/order-keys.d.ts +39 -0
  76. package/dist/order-keys.d.ts.map +1 -0
  77. package/dist/order-keys.js +136 -0
  78. package/dist/order-keys.js.map +1 -0
  79. package/dist/parse-path.d.ts +7 -1
  80. package/dist/parse-path.d.ts.map +1 -1
  81. package/dist/parse-path.js +6 -2
  82. package/dist/parse-path.js.map +1 -1
  83. package/dist/polygon.d.ts +53 -0
  84. package/dist/polygon.d.ts.map +1 -0
  85. package/dist/polygon.js +205 -0
  86. package/dist/polygon.js.map +1 -0
  87. package/dist/preview.d.ts +1 -1
  88. package/dist/random.d.ts +7 -0
  89. package/dist/random.d.ts.map +1 -0
  90. package/dist/random.js +2 -0
  91. package/dist/resize.d.ts +11 -2
  92. package/dist/resize.d.ts.map +1 -1
  93. package/dist/resize.js +2 -184
  94. package/dist/snap.d.ts +1 -1
  95. package/dist/text-direction.d.ts +13 -0
  96. package/dist/text-direction.d.ts.map +1 -0
  97. package/dist/text-direction.js +31 -0
  98. package/dist/text-direction.js.map +1 -0
  99. package/dist/text-picture.d.ts +1 -1
  100. package/dist/text-picture.d.ts.map +1 -1
  101. package/dist/text.d.ts +2 -0
  102. package/dist/text.js +3 -0
  103. package/dist/types.d.ts +2063 -13
  104. package/dist/types.d.ts.map +1 -1
  105. package/dist/types.js +2 -1
  106. package/dist/types2.d.ts +2 -2
  107. package/dist/undo.d.ts +2 -2
  108. package/dist/undo.js +2 -2
  109. package/dist/undo2.d.ts +29 -1
  110. package/dist/undo2.d.ts.map +1 -1
  111. package/dist/variables.d.ts +2 -29
  112. package/dist/variables.js +2 -2
  113. package/dist/variant-properties.d.ts +9 -1
  114. package/dist/variant-properties.d.ts.map +1 -1
  115. package/dist/variant-properties.js +36 -1
  116. package/dist/variant-properties.js.map +1 -1
  117. package/dist/vector-network.d.ts +1 -1
  118. package/dist/vector-network.js +1 -1
  119. package/package.json +60 -9
  120. package/src/behaviours/kinds.ts +185 -0
  121. package/src/behaviours/layers.ts +51 -0
  122. package/src/behaviours/model.ts +192 -0
  123. package/src/behaviours/schema.ts +58 -0
  124. package/src/behaviours/spec.ts +223 -0
  125. package/src/buffered-events.ts +64 -0
  126. package/src/color/contrast.ts +31 -0
  127. package/src/color/index.ts +88 -0
  128. package/src/color/management.ts +210 -0
  129. package/src/color/normalize.ts +7 -0
  130. package/src/color/okhcl.ts +201 -0
  131. package/src/comments/document.ts +51 -0
  132. package/src/comments/list.ts +52 -0
  133. package/src/comments/merge.ts +63 -0
  134. package/src/comments/threads.ts +156 -0
  135. package/src/components/exposure.ts +61 -0
  136. package/src/components/properties.ts +18 -15
  137. package/src/components/variants.ts +53 -0
  138. package/src/constants.ts +2 -0
  139. package/src/coordinate.ts +100 -43
  140. package/src/copy.ts +13 -5
  141. package/src/css/grid.ts +70 -0
  142. package/src/css/index.ts +9 -0
  143. package/src/css/layout.ts +53 -0
  144. package/src/css/shadows.ts +68 -0
  145. package/src/css/values.ts +42 -0
  146. package/src/export-format.ts +12 -0
  147. package/src/fields/geometry.ts +11 -0
  148. package/src/fields/text.ts +35 -0
  149. package/src/gradient.ts +166 -0
  150. package/src/group-bounds.ts +131 -0
  151. package/src/guides.ts +39 -0
  152. package/src/hit-test.ts +219 -25
  153. package/src/icons/glyph.ts +128 -0
  154. package/src/icons/model.ts +54 -0
  155. package/src/icons/schema.ts +18 -0
  156. package/src/index.ts +344 -56
  157. package/src/instance-overrides.ts +27 -0
  158. package/src/instances/copies.ts +239 -0
  159. package/src/instances/cycles.ts +73 -0
  160. package/src/instances/fields.ts +143 -0
  161. package/src/instances/main-component.ts +19 -0
  162. package/src/instances/placement.ts +29 -0
  163. package/src/instances/source-walk.ts +41 -0
  164. package/src/instances/sync.ts +599 -0
  165. package/src/instances.ts +122 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +1 -1
  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/slots/authoring.ts +101 -0
  187. package/src/slots/content.ts +124 -0
  188. package/src/slots/frames.ts +160 -0
  189. package/src/slots/limits.ts +49 -0
  190. package/src/text/direction.ts +55 -0
  191. package/src/text/index.ts +2 -0
  192. package/src/text/lists.ts +138 -0
  193. package/src/text/paragraphs.ts +241 -0
  194. package/src/{text-picture.ts → text/picture.ts} +21 -29
  195. package/src/transfer/apply.ts +84 -0
  196. package/src/transfer/history.ts +49 -0
  197. package/src/transfer/identity.ts +16 -0
  198. package/src/transfer/index.ts +6 -0
  199. package/src/transfer/nodes.ts +108 -0
  200. package/src/transfer/plan.ts +107 -0
  201. package/src/transfer/references.ts +9 -0
  202. package/src/transfer/remove.ts +39 -0
  203. package/src/transfer/validation.ts +54 -0
  204. package/src/transfer/variables.ts +82 -0
  205. package/src/types.ts +221 -11
  206. package/src/undo.ts +54 -2
  207. package/src/variables/bindings.ts +186 -0
  208. package/src/variables/fields.ts +43 -0
  209. package/src/variables/token.ts +14 -0
  210. package/src/variables/units.ts +15 -0
  211. package/src/variables.ts +118 -69
  212. package/src/variant-properties.ts +50 -0
  213. package/dist/chunks/components/properties.js.map +0 -1
  214. package/dist/chunks/export-scale.js +0 -19
  215. package/dist/chunks/export-scale.js.map +0 -1
  216. package/dist/coordinate.d.ts.map +0 -1
  217. package/dist/coordinate2.d.ts +0 -2
  218. package/dist/guides2.d.ts +0 -11
  219. package/dist/guides2.d.ts.map +0 -1
  220. package/dist/hit-test.d.ts.map +0 -1
  221. package/dist/layout-guides.d.ts +0 -2
  222. package/dist/layout-guides.js +0 -2
  223. package/dist/layout-guides2.d.ts +0 -16
  224. package/dist/layout-guides2.d.ts.map +0 -1
  225. package/dist/node-defaults.d.ts.map +0 -1
  226. package/dist/preview2.d.ts +0 -12
  227. package/dist/preview2.d.ts.map +0 -1
  228. package/dist/resize.js.map +0 -1
  229. package/dist/variables.d.ts.map +0 -1
  230. package/dist/vector-network2.d.ts +0 -32
  231. package/dist/vector-network2.d.ts.map +0 -1
  232. 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,
@@ -98,7 +113,10 @@ function hitTestTransparentContainer(
98
113
  return childHit
99
114
  }
100
115
 
101
- if (containsPoint(px, py, child, graph, transformCache) && hasVisibleFillOrStroke(child))
116
+ if (
117
+ containsPoint(px, py, child, graph, transformCache) &&
118
+ (hasVisibleFillOrStroke(child) || ownsItsEmptyArea(graph, child))
119
+ )
102
120
  return child
103
121
  return null
104
122
  }
@@ -160,46 +178,222 @@ export function hitTestDeep(
160
178
  return hitTestChildren(graph, px, py, scope, true)
161
179
  }
162
180
 
163
- function hitTestFrameChildren(
181
+ /**
182
+ * A container a click looks into by itself, as in Figma: a top-level frame (on the page or in a
183
+ * section) or a section that holds layers, and a component set.
184
+ */
185
+ function opensByItself(graph: SceneGraph, node: SceneNode): boolean {
186
+ if (node.type === 'COMPONENT_SET') return true
187
+ if (node.childIds.length === 0) return false
188
+ if (node.type === 'SECTION') return true
189
+ return node.type === 'FRAME' && isTopLevel(graph, node)
190
+ }
191
+
192
+ /**
193
+ * The topmost frame among a container's children whose bounds hold the point, filled or not: in
194
+ * Figma a click on the empty area of a frame inside an open container, or of an empty frame on the
195
+ * page or in a section, selects that frame, while a deep (⌘) click looks through it.
196
+ */
197
+ function frameChildAt(
198
+ graph: SceneGraph,
199
+ container: SceneNode,
200
+ px: number,
201
+ py: number
202
+ ): SceneNode | null {
203
+ const transformCache = new Map<string, boolean>()
204
+ for (let i = container.childIds.length - 1; i >= 0; i--) {
205
+ const child = graph.nodes.get(container.childIds[i])
206
+ if (!child || child.internalOnly || !child.visible || child.type !== 'FRAME') continue
207
+ // A board, such as a top-level frame in a section, keeps its empty area as background.
208
+ if (opensByItself(graph, child) && !ownsItsEmptyArea(graph, child)) continue
209
+ if (containsPoint(px, py, child, graph, transformCache)) return child
210
+ }
211
+ return null
212
+ }
213
+
214
+ /**
215
+ * The containers the selection opens: every ancestor of a selected layer inside the scope, and a
216
+ * selected container itself, so a click inside it selects the layer under the point, as in Figma.
217
+ * A selected group or boolean stays closed: clicking inside it keeps it selected.
218
+ */
219
+ function openedBySelection(
220
+ graph: SceneGraph,
221
+ selectedIds: ReadonlySet<string>,
222
+ scopeId: string
223
+ ): Set<string> {
224
+ const ancestors = new Set<string>()
225
+ for (const id of selectedIds) {
226
+ const node = graph.nodes.get(id)
227
+ if (
228
+ node &&
229
+ node.childIds.length > 0 &&
230
+ node.type !== 'GROUP' &&
231
+ node.type !== 'BOOLEAN_OPERATION'
232
+ )
233
+ ancestors.add(id)
234
+ let parentId = node?.parentId
235
+ while (parentId && parentId !== scopeId && !ancestors.has(parentId)) {
236
+ ancestors.add(parentId)
237
+ parentId = graph.nodes.get(parentId)?.parentId
238
+ }
239
+ }
240
+ return ancestors
241
+ }
242
+
243
+ /**
244
+ * The layer a click selects, as in Figma. It walks from the scope down to the deepest layer under
245
+ * the point and stops at the first layer that is not open. Top-level frames and sections with
246
+ * layers and component sets are open, and so is every ancestor of the selection, so clicks reach
247
+ * the siblings of selected layers. Where every layer under the point is open, a container opened
248
+ * by the selection is selected, so is a top-level frame with auto layout, and a plain top-level
249
+ * frame or a section is not.
250
+ */
251
+ export function hitTestSelectable(
164
252
  graph: SceneGraph,
165
253
  px: number,
166
254
  py: number,
167
- parentId: string,
168
- offsetX: number,
169
- offsetY: number,
170
- excludeIds: Set<string>
255
+ scopeId: string,
256
+ selectedIds: ReadonlySet<string>
171
257
  ): SceneNode | null {
172
- const parent = graph.nodes.get(parentId)
173
- if (!parent) return null
258
+ const deepest = hitTestChildren(graph, px, py, scopeId, true)
259
+ if (!deepest) {
260
+ const scope = graph.nodes.get(scopeId)
261
+ return scope ? frameChildAt(graph, scope, px, py) : null
262
+ }
174
263
 
175
- let best: SceneNode | null = null
264
+ const chain: SceneNode[] = []
265
+ for (let node: SceneNode | undefined = deepest; node && node.id !== scopeId;) {
266
+ chain.unshift(node)
267
+ node = node.parentId ? graph.nodes.get(node.parentId) : undefined
268
+ }
176
269
 
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
270
+ const opened = openedBySelection(graph, selectedIds, scopeId)
271
+
272
+ for (const node of chain) {
273
+ // A locked layer stands in for everything inside it.
274
+ if (node.locked) return node
275
+ if (!opened.has(node.id) && !opensByItself(graph, node)) return node
276
+ }
277
+ const last = chain.at(-1)
278
+ if (!last) return null
279
+ const frame = frameChildAt(graph, last, px, py)
280
+ if (frame) return frame
281
+ if (ownsItsEmptyArea(graph, last)) return last
282
+ return opened.has(last.id) && !opensByItself(graph, last) ? last : null
283
+ }
181
284
 
182
- const ax = offsetX + child.x
183
- const ay = offsetY + child.y
285
+ /** Whether a click looks into this container rather than selecting it; see `hitTestSelectable`. */
286
+ export function isOpenContainer(graph: SceneGraph, nodeId: string): boolean {
287
+ const node = graph.nodes.get(nodeId)
288
+ return node !== undefined && opensByItself(graph, node)
289
+ }
290
+
291
+ /**
292
+ * The innermost open container under the point when every layer there is open: a marquee starting
293
+ * here selects that container's layers, as in Figma.
294
+ */
295
+ export function hitTestOpenContainer(
296
+ graph: SceneGraph,
297
+ px: number,
298
+ py: number,
299
+ scopeId: string
300
+ ): SceneNode | null {
301
+ const deepest = hitTestChildren(graph, px, py, scopeId, true)
302
+ for (let node: SceneNode | undefined = deepest ?? undefined; node && node.id !== scopeId;) {
303
+ if (!opensByItself(graph, node) || ownsItsEmptyArea(graph, node)) return null
304
+ node = node.parentId ? graph.nodes.get(node.parentId) : undefined
305
+ }
306
+ return deepest
307
+ }
184
308
 
185
- if (!CONTAINER_TYPES.has(child.type)) continue
186
- if (px < ax || px > ax + child.width || py < ay || py > ay + child.height) continue
309
+ /** Whether the point lies inside the node's rotated and flipped bounds. */
310
+ export function isPointInNode(graph: SceneGraph, nodeId: string, px: number, py: number): boolean {
311
+ const node = graph.nodes.get(nodeId)
312
+ return node !== undefined && containsPoint(px, py, node, graph, new Map())
313
+ }
314
+
315
+ /** Which layers take a drop, and which are only looked through, as in Figma. */
316
+ interface DropRules {
317
+ takes: (node: SceneNode) => boolean
318
+ passThrough: ReadonlySet<NodeType>
319
+ }
187
320
 
188
- best = child
321
+ const LAYER_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'COMPONENT', 'INSTANCE'])
322
+ const COMPONENT_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'INSTANCE'])
189
323
 
190
- const deeper = hitTestFrameChildren(graph, px, py, childId, ax, ay, excludeIds)
191
- if (deeper) best = deeper
324
+ function dropRules(options: DropTargetOptions): DropRules {
325
+ const { componentSetIds } = options
326
+ if (!componentSetIds) {
327
+ return {
328
+ takes: (node) => LAYER_TARGETS.has(node.type),
329
+ passThrough: new Set(['GROUP', 'COMPONENT_SET'])
330
+ }
192
331
  }
332
+ // Components never go into other components, and a set only takes back its own variants.
333
+ return {
334
+ takes: (node) =>
335
+ COMPONENT_TARGETS.has(node.type) ||
336
+ (node.type === 'COMPONENT_SET' && componentSetIds.has(node.id)),
337
+ passThrough: new Set(['GROUP'])
338
+ }
339
+ }
193
340
 
194
- return best
341
+ function dropTargetIn(
342
+ graph: SceneGraph,
343
+ px: number,
344
+ py: number,
345
+ parent: SceneNode,
346
+ excludeIds: ReadonlySet<string>,
347
+ rules: DropRules,
348
+ transformCache: Map<string, boolean>
349
+ ): SceneNode | null {
350
+ // A clipped-away part of a child is not under the cursor.
351
+ if (
352
+ parent.type !== 'CANVAS' &&
353
+ parent.clipsContent &&
354
+ !containsPoint(px, py, parent, graph, transformCache)
355
+ )
356
+ return null
357
+
358
+ for (let i = parent.childIds.length - 1; i >= 0; i--) {
359
+ const childId = parent.childIds[i]
360
+ if (excludeIds.has(childId)) continue
361
+ const child = graph.nodes.get(childId)
362
+ if (!child || child.internalOnly || !child.visible || child.locked) continue
363
+ const target = rules.takes(child)
364
+ if (!target && !rules.passThrough.has(child.type)) continue
365
+
366
+ const deeper = dropTargetIn(graph, px, py, child, excludeIds, rules, transformCache)
367
+ if (deeper) return deeper
368
+ if (target && containsPoint(px, py, child, graph, transformCache)) return child
369
+ }
370
+
371
+ return null
195
372
  }
196
373
 
197
- export function hitTestFrame(
374
+ export interface DropTargetOptions {
375
+ /**
376
+ * Set when the dropped layers are all main components: the component sets they come from.
377
+ * Components then go only into frames, sections, instances, and those sets.
378
+ */
379
+ componentSetIds?: ReadonlySet<string>
380
+ }
381
+
382
+ /**
383
+ * The topmost unlocked frame, section, component, or instance under the point, in its rotated
384
+ * shape and inside its clipping ancestors. Groups and component sets are looked through but never
385
+ * returned, except that a set takes dropped components; locked layers and their contents are
386
+ * skipped.
387
+ */
388
+ export function hitTestDropTarget(
198
389
  graph: SceneGraph,
199
390
  px: number,
200
391
  py: number,
201
- excludeIds: Set<string>,
202
- scopeId?: string
392
+ excludeIds: ReadonlySet<string>,
393
+ scopeId?: string,
394
+ options: DropTargetOptions = {}
203
395
  ): SceneNode | null {
204
- return hitTestFrameChildren(graph, px, py, scopeId ?? graph.rootId, 0, 0, excludeIds)
396
+ const scope = graph.nodes.get(scopeId ?? graph.rootId)
397
+ if (!scope) return null
398
+ return dropTargetIn(graph, px, py, scope, excludeIds, dropRules(options), new Map())
205
399
  }
@@ -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))