@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
@@ -0,0 +1,196 @@
1
+ import type { SceneGraph } from '../index'
2
+ import type { LayoutSizing, SceneNode, TextAutoResize } from '../types'
3
+
4
+ /**
5
+ * How a node sizes along one screen axis, as Figma's `layoutSizingHorizontal` and
6
+ * `layoutSizingVertical` report it. Fill is stored on the child, the way Figma stores it:
7
+ * along the parent's primary axis as `layoutGrow`, across it as `layoutAlignSelf: 'STRETCH'`.
8
+ * A grid lays its children out like a horizontal stack. Hug is stored on the node itself:
9
+ * `primaryAxisSizing` and `counterAxisSizing` for an auto-layout frame, `textAutoResize`
10
+ * for text.
11
+ */
12
+ export type LayoutSizingAxis = 'HORIZONTAL' | 'VERTICAL'
13
+
14
+ type AutoLayoutMode = Exclude<SceneNode['layoutMode'], 'NONE'>
15
+
16
+ function primaryAxis(mode: AutoLayoutMode): LayoutSizingAxis {
17
+ return mode === 'VERTICAL' ? 'VERTICAL' : 'HORIZONTAL'
18
+ }
19
+
20
+ /** The auto-layout parent that sizes a node's fill, or `undefined` when nothing does. */
21
+ function fillingParent(parent: SceneNode | undefined, node: SceneNode): SceneNode | undefined {
22
+ if (!parent || parent.layoutMode === 'NONE' || node.layoutPositioning === 'ABSOLUTE')
23
+ return undefined
24
+ return parent
25
+ }
26
+
27
+ function graphParent(graph: SceneGraph, node: SceneNode): SceneNode | undefined {
28
+ return node.parentId ? graph.getNode(node.parentId) : undefined
29
+ }
30
+
31
+ function fills(parent: SceneNode, node: SceneNode, axis: LayoutSizingAxis): boolean {
32
+ if (parent.layoutMode === 'NONE') return false
33
+ if (axis === primaryAxis(parent.layoutMode)) return node.layoutGrow > 0
34
+ if (node.layoutAlignSelf === 'STRETCH') return true
35
+ return (
36
+ node.layoutAlignSelf === 'AUTO' &&
37
+ parent.layoutMode !== 'GRID' &&
38
+ parent.counterAxisAlign === 'STRETCH'
39
+ )
40
+ }
41
+
42
+ function ownSizingField(
43
+ node: SceneNode,
44
+ axis: LayoutSizingAxis
45
+ ): 'primaryAxisSizing' | 'counterAxisSizing' | undefined {
46
+ if (node.layoutMode === 'NONE') return undefined
47
+ return axis === primaryAxis(node.layoutMode) ? 'primaryAxisSizing' : 'counterAxisSizing'
48
+ }
49
+
50
+ function textHugs(autoResize: TextAutoResize, axis: LayoutSizingAxis): boolean {
51
+ if (autoResize === 'WIDTH_AND_HEIGHT') return true
52
+ return axis === 'VERTICAL' && autoResize === 'HEIGHT'
53
+ }
54
+
55
+ function hugs(node: SceneNode, axis: LayoutSizingAxis): boolean {
56
+ if (node.type === 'TEXT') return textHugs(node.textAutoResize, axis)
57
+ const field = ownSizingField(node, axis)
58
+ return field !== undefined && node[field] === 'HUG'
59
+ }
60
+
61
+ /** The node's sizing along `axis`: fill from its parent, else its own hug, else fixed. */
62
+ export function layoutSizing(
63
+ graph: SceneGraph,
64
+ node: SceneNode,
65
+ axis: LayoutSizingAxis
66
+ ): LayoutSizing {
67
+ return layoutSizingInParent(graphParent(graph, node), node, axis)
68
+ }
69
+
70
+ /** `layoutSizing` for code that holds the parent rather than the graph. */
71
+ export function layoutSizingInParent(
72
+ parentNode: SceneNode | undefined,
73
+ node: SceneNode,
74
+ axis: LayoutSizingAxis
75
+ ): LayoutSizing {
76
+ const parent = fillingParent(parentNode, node)
77
+ if (parent && fills(parent, node, axis)) return 'FILL'
78
+ // Figma reports text outside auto-layout as fixed, though it still resizes to its content.
79
+ if (hugs(node, axis) && (parent || node.layoutMode !== 'NONE')) return 'HUG'
80
+ return 'FIXED'
81
+ }
82
+
83
+ /** The sizings this node accepts on either axis, in Figma's order. */
84
+ export function layoutSizingOptions(graph: SceneGraph, node: SceneNode): LayoutSizing[] {
85
+ return (['FIXED', 'HUG', 'FILL'] as const).filter(
86
+ (value) => layoutSizingError(graph, node, value) === undefined
87
+ )
88
+ }
89
+
90
+ /** Figma's reason for refusing `value` on this node, or `undefined` when it applies. */
91
+ export function layoutSizingError(
92
+ graph: SceneGraph,
93
+ node: SceneNode,
94
+ value: LayoutSizing
95
+ ): string | undefined {
96
+ const parent = graphParent(graph, node)
97
+ const inAutoLayout = parent !== undefined && parent.layoutMode !== 'NONE'
98
+ if (!inAutoLayout && node.layoutMode === 'NONE') {
99
+ return 'node must be an auto-layout frame or a child of an auto-layout frame'
100
+ }
101
+ if (value === 'FILL') {
102
+ if (!inAutoLayout) return 'FILL can only be set on children of auto-layout frames'
103
+ if (node.layoutPositioning === 'ABSOLUTE') {
104
+ return 'FILL cannot be set on absolute positioned auto-layout children'
105
+ }
106
+ }
107
+ if (value === 'HUG' && node.layoutMode === 'NONE' && node.type !== 'TEXT') {
108
+ return 'HUG can only be set on auto-layout frames or text children of auto-layout frames'
109
+ }
110
+ return undefined
111
+ }
112
+
113
+ /** The text auto-resize that hugs the content along the axes given. */
114
+ export function textAutoResizeFor(hugsWidth: boolean, hugsHeight: boolean): TextAutoResize {
115
+ if (hugsWidth && hugsHeight) return 'WIDTH_AND_HEIGHT'
116
+ return hugsHeight ? 'HEIGHT' : 'NONE'
117
+ }
118
+
119
+ function textSizingUpdates(
120
+ graph: SceneGraph,
121
+ node: SceneNode,
122
+ axis: LayoutSizingAxis,
123
+ value: LayoutSizing
124
+ ): Partial<SceneNode> {
125
+ const other: LayoutSizingAxis = axis === 'HORIZONTAL' ? 'VERTICAL' : 'HORIZONTAL'
126
+ const hugsAxis = value === 'HUG'
127
+ const hugsOther = layoutSizing(graph, node, other) === 'HUG'
128
+ const autoResize =
129
+ axis === 'HORIZONTAL'
130
+ ? textAutoResizeFor(hugsAxis, hugsOther)
131
+ : textAutoResizeFor(hugsOther, hugsAxis)
132
+ // Truncated text keeps truncating when it stops hugging.
133
+ if (autoResize === 'NONE' && node.textAutoResize === 'TRUNCATE') return {}
134
+ return autoResize === node.textAutoResize ? {} : { textAutoResize: autoResize }
135
+ }
136
+
137
+ /**
138
+ * The fields that set the node's sizing along `axis` to `value`, as Figma's setter writes
139
+ * them. A value Figma refuses yields no updates; `layoutSizingError` says why.
140
+ */
141
+ export function layoutSizingUpdates(
142
+ graph: SceneGraph,
143
+ node: SceneNode,
144
+ axis: LayoutSizingAxis,
145
+ value: LayoutSizing
146
+ ): Partial<SceneNode> {
147
+ if (layoutSizingError(graph, node, value) !== undefined) return {}
148
+ const updates: Partial<SceneNode> = {}
149
+ const parent = fillingParent(graphParent(graph, node), node)
150
+ if (parent && parent.layoutMode !== 'NONE') {
151
+ const fill = value === 'FILL'
152
+ if (axis === primaryAxis(parent.layoutMode)) {
153
+ if (fill !== node.layoutGrow > 0) updates.layoutGrow = fill ? 1 : 0
154
+ } else if (fill && node.layoutAlignSelf !== 'STRETCH') {
155
+ updates.layoutAlignSelf = 'STRETCH'
156
+ } else if (!fill && fills(parent, node, axis)) {
157
+ // A flex parent set to stretch its children stretches this one too unless it opts out.
158
+ const inheritsStretch = parent.layoutMode !== 'GRID' && parent.counterAxisAlign === 'STRETCH'
159
+ updates.layoutAlignSelf = inheritsStretch ? 'MIN' : 'AUTO'
160
+ }
161
+ }
162
+ const field = ownSizingField(node, axis)
163
+ if (field) {
164
+ const own = value === 'HUG' ? 'HUG' : 'FIXED'
165
+ if (node[field] !== own) updates[field] = own
166
+ }
167
+ if (node.type === 'TEXT') Object.assign(updates, textSizingUpdates(graph, node, axis, value))
168
+ return updates
169
+ }
170
+
171
+ /**
172
+ * The fields that make a child fill `axis` of a parent laid out as `parentLayout`, for a node
173
+ * an importer builds before it joins the graph. Under a parent without auto layout, such as a
174
+ * staging parent the node leaves when placed, both are set, so it fills whichever axis its
175
+ * eventual parent stacks along.
176
+ */
177
+ export function fillSizingFields(
178
+ parentLayout: SceneNode['layoutMode'],
179
+ axis: LayoutSizingAxis
180
+ ): Partial<Pick<SceneNode, 'layoutGrow' | 'layoutAlignSelf'>> {
181
+ if (parentLayout === 'NONE') return { layoutGrow: 1, layoutAlignSelf: 'STRETCH' }
182
+ return axis === primaryAxis(parentLayout) ? { layoutGrow: 1 } : { layoutAlignSelf: 'STRETCH' }
183
+ }
184
+
185
+ /** An auto-layout frame's own sizing when it hugs or fixes its width and height. */
186
+ export function autoLayoutSizingFields(
187
+ direction: AutoLayoutMode,
188
+ width: 'FIXED' | 'HUG',
189
+ height: 'FIXED' | 'HUG'
190
+ ): Pick<SceneNode, 'primaryAxisSizing' | 'counterAxisSizing'> {
191
+ const horizontal = primaryAxis(direction) === 'HORIZONTAL'
192
+ return {
193
+ primaryAxisSizing: horizontal ? width : height,
194
+ counterAxisSizing: horizontal ? height : width
195
+ }
196
+ }
@@ -1,3 +1,5 @@
1
+ import { uniq } from 'es-toolkit/array'
2
+
1
3
  import type { SceneGraph } from './index'
2
4
 
3
5
  export interface SceneMutationImpact {
@@ -25,30 +27,36 @@ export interface CollectedSceneMutation<T> {
25
27
  impact: SceneMutationImpact
26
28
  }
27
29
 
28
- /** Collects the actual graph nodes and parent containers touched by an operation. */
29
- export async function collectSceneMutation<T>(
30
+ /** Records into `impact` the nodes and parent containers the graph's edits touch, until unbound. */
31
+ export function recordSceneMutations(
30
32
  graph: SceneGraph,
31
- operation: () => T | Promise<T>
32
- ): Promise<CollectedSceneMutation<T>> {
33
- const impact = createSceneMutationImpact()
34
- const unbind = graph.onNodeEvents({
33
+ impact: SceneMutationImpact,
34
+ shouldRecord: () => boolean = () => true
35
+ ): () => void {
36
+ return graph.onNodeEvents({
35
37
  created: (node) => {
38
+ if (!shouldRecord()) return
36
39
  impact.createdNodeIds.add(node.id)
37
40
  impact.changedNodeIds.add(node.id)
38
41
  if (node.parentId) impact.currentParentIds.add(node.parentId)
39
42
  },
40
- updated: (id) => impact.changedNodeIds.add(id),
43
+ updated: (id) => {
44
+ if (shouldRecord()) impact.changedNodeIds.add(id)
45
+ },
41
46
  deleted: (id, parentId) => {
47
+ if (!shouldRecord()) return
42
48
  if (parentId) impact.previousParentIds.add(parentId)
43
49
  impact.deletedNodeIds.add(id)
44
50
  impact.changedNodeIds.add(id)
45
51
  },
46
52
  reparented: (nodeId, oldParentId, newParentId) => {
53
+ if (!shouldRecord()) return
47
54
  impact.changedNodeIds.add(nodeId)
48
55
  if (oldParentId) impact.previousParentIds.add(oldParentId)
49
56
  impact.currentParentIds.add(newParentId)
50
57
  },
51
58
  reordered: (nodeId, parentId, _index, previousParentId) => {
59
+ if (!shouldRecord()) return
52
60
  impact.changedNodeIds.add(nodeId)
53
61
  if (previousParentId && previousParentId !== parentId) {
54
62
  impact.previousParentIds.add(previousParentId)
@@ -56,6 +64,15 @@ export async function collectSceneMutation<T>(
56
64
  impact.currentParentIds.add(parentId)
57
65
  }
58
66
  })
67
+ }
68
+
69
+ /** Collects the actual graph nodes and parent containers touched by an operation. */
70
+ export async function collectSceneMutation<T>(
71
+ graph: SceneGraph,
72
+ operation: () => T | Promise<T>
73
+ ): Promise<CollectedSceneMutation<T>> {
74
+ const impact = createSceneMutationImpact()
75
+ const unbind = recordSceneMutations(graph, impact)
59
76
  try {
60
77
  return { result: await operation(), impact }
61
78
  } finally {
@@ -64,7 +81,5 @@ export async function collectSceneMutation<T>(
64
81
  }
65
82
 
66
83
  export function mutationLayoutScopeIds(impact: SceneMutationImpact): string[] {
67
- return [
68
- ...new Set([...impact.changedNodeIds, ...impact.previousParentIds, ...impact.currentParentIds])
69
- ]
84
+ return uniq([...impact.changedNodeIds, ...impact.previousParentIds, ...impact.currentParentIds])
70
85
  }
@@ -1,4 +1,9 @@
1
- import { BLACK, DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT } from './constants'
1
+ import {
2
+ BLACK,
3
+ DEFAULT_FONT_FAMILY,
4
+ DEFAULT_STROKE_MITER_LIMIT,
5
+ DEFAULT_STROKE_WEIGHT
6
+ } from './constants'
2
7
  import { createInstanceOverrideState } from './instance-overrides'
3
8
  import type { NodeType, SceneNode, SourceMetadata } from './types'
4
9
 
@@ -22,6 +27,30 @@ export function createDefaultSourceMetadata(): SourceMetadata {
22
27
  }
23
28
  }
24
29
 
30
+ /**
31
+ * Every SceneNode field. Nodes start with all of them, so setting any field later keeps the
32
+ * shape every node shares; a key added after creation turns a JavaScriptCore object into a
33
+ * slower, larger dictionary.
34
+ */
35
+ type CompleteNodeFields = SceneNode & Record<keyof SceneNode, unknown>
36
+
37
+ /** Where Figma aligns a new node's strokes: centered on lines and vectors, outside text, else inside. */
38
+ export function defaultStrokeAlign(type: NodeType): SceneNode['strokeAlign'] {
39
+ if (type === 'LINE' || type === 'VECTOR') return 'CENTER'
40
+ return type === 'TEXT' ? 'OUTSIDE' : 'INSIDE'
41
+ }
42
+
43
+ /**
44
+ * Weight and alignment a stroke added to `node` takes: its first stroke's, or what the node keeps
45
+ * with none. Adding a stroke from the panel and from the plugin API both go through here.
46
+ */
47
+ export function newStrokeGeometry(
48
+ node: Pick<SceneNode, 'strokes' | 'strokeWeight' | 'strokeAlign'>
49
+ ): Pick<SceneNode['strokes'][number], 'weight' | 'align'> {
50
+ const first = node.strokes.at(0)
51
+ return { weight: first?.weight ?? node.strokeWeight, align: first?.align ?? node.strokeAlign }
52
+ }
53
+
25
54
  export function createDefaultNode(
26
55
  generateId: () => string,
27
56
  type: NodeType,
@@ -106,6 +135,11 @@ export function createDefaultNode(
106
135
  textDecorationSkipInk: true,
107
136
  textUnderlineOffset: null,
108
137
  maxLines: null,
138
+ textParagraphs: [],
139
+ listSpacing: 0,
140
+ paragraphSpacing: 0,
141
+ paragraphIndent: 0,
142
+ hangingList: false,
109
143
  styleRuns: [],
110
144
  fontVariations: [],
111
145
  fontFeatures: [],
@@ -119,11 +153,14 @@ export function createDefaultNode(
119
153
  borderBottomWeight: 0,
120
154
  borderLeftWeight: 0,
121
155
  independentStrokeWeights: false,
156
+ strokeWeight: DEFAULT_STROKE_WEIGHT,
157
+ strokeAlign: defaultStrokeAlign(type),
122
158
  strokeMiterLimit: DEFAULT_STROKE_MITER_LIMIT,
123
159
  minWidth: null,
124
160
  maxWidth: null,
125
161
  minHeight: null,
126
162
  maxHeight: null,
163
+ targetAspectRatio: null,
127
164
  isMask: false,
128
165
  maskType: 'ALPHA',
129
166
  maskIsOutline: false,
@@ -155,10 +192,14 @@ export function createDefaultNode(
155
192
  librarySource: null,
156
193
  isPublishable: false,
157
194
  isSymbolPublishable: false,
195
+ isExposedInstance: false,
158
196
  symbolDescription: '',
159
197
  symbolLinks: [],
160
198
  variantPropSpecs: [],
161
199
  boundVariables: {},
200
+ variableBindingScales: {},
201
+ variableAssignmentScales: {},
202
+ componentScale: 1,
162
203
  variableModes: {},
163
204
  exportSettings: [],
164
205
  pluginData: [],
@@ -170,10 +211,17 @@ export function createDefaultNode(
170
211
  derivedTextGlyphs: null,
171
212
  textPathData: null,
172
213
  textPathBox: null,
214
+ booleanOperation: undefined,
173
215
  ...overrides
174
- }
216
+ } satisfies CompleteNodeFields
175
217
  }
176
218
 
219
+ /** Containers whose bounds follow their children and that set no coordinate space, as in Figma. */
220
+ export const FITTED_CONTAINER_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([
221
+ 'GROUP',
222
+ 'BOOLEAN_OPERATION'
223
+ ])
224
+
177
225
  export const CONTAINER_TYPES = new Set<NodeType>([
178
226
  'CANVAS',
179
227
  'FRAME',
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Fractional order keys: printable-ASCII strings (`!` to `~`) that order siblings by plain string
3
+ * comparison, as Figma writes `parentIndex.position`. A new key fits between two neighbours
4
+ * without renumbering the others.
5
+ */
6
+
7
+ const ORDER_KEY_MIN = 33 // '!'
8
+ const ORDER_KEY_MAX = 126 // '~'
9
+ const ORDER_KEY_MID = 'O'
10
+ const INDEX_KEY_BASE = ORDER_KEY_MAX - ORDER_KEY_MIN + 1
11
+
12
+ /** The order key for position `index` of a freshly numbered sibling list. */
13
+ export function fractionalPosition(index: number): string {
14
+ const numTildes = Math.floor(index / INDEX_KEY_BASE)
15
+ const lastChar = String.fromCharCode(ORDER_KEY_MIN + (index % INDEX_KEY_BASE))
16
+ return String.fromCharCode(ORDER_KEY_MAX).repeat(numTildes) + lastChar
17
+ }
18
+
19
+ /**
20
+ * The shortest key strictly between `lo` and `hi` (either may be open), or null when the
21
+ * printable alphabet has none. Splits at the first character where they differ when a character
22
+ * fits between; otherwise keeps that character and recurses into the remainder.
23
+ */
24
+ function keyBetween(lo: string | null, hi: string | null): string | null {
25
+ if (lo !== null && hi !== null && lo >= hi) return null
26
+ const low = lo ?? ''
27
+ // An open upper bound shares no prefix, so the empty string ends the scan immediately.
28
+ const high = hi ?? ''
29
+ let i = 0
30
+ while (i < low.length && i < high.length && low[i] === high[i]) i++
31
+ const a = i < low.length ? low.charCodeAt(i) : ORDER_KEY_MIN - 1
32
+ const b = hi !== null && i < hi.length ? hi.charCodeAt(i) : ORDER_KEY_MAX + 1
33
+ if (b - a > 1) return low.slice(0, i) + String.fromCharCode(Math.floor((a + b) / 2))
34
+ // Keep lo's character: anything above the rest of lo then sorts below hi.
35
+ if (i < low.length) {
36
+ return low.slice(0, i + 1) + (keyBetween(low.slice(i + 1), null) ?? ORDER_KEY_MID)
37
+ }
38
+ // lo is a prefix of hi whose next character can't be lowered: keep it and go below the rest.
39
+ const rest = hi?.slice(i + 1) ?? ''
40
+ if (!hi || rest === '') return null
41
+ return hi.slice(0, i + 1) + (keyBetween(null, rest) ?? '')
42
+ }
43
+
44
+ /** A key above `lo` that has room for `suffix` while staying below `hi`, or null. */
45
+ function keyWithSuffix(lo: string | null, hi: string, suffix: string): string | null {
46
+ // A key that is a prefix of hi leaves no room after it; go one level deeper until it is not.
47
+ for (let key = keyBetween(lo, hi); key !== null; key = keyBetween(key, hi)) {
48
+ if (key + suffix < hi) return key + suffix
49
+ if (!hi.startsWith(key)) return null
50
+ }
51
+ return null
52
+ }
53
+
54
+ /**
55
+ * A key above `lo` and below `hi`; either bound may be open.
56
+ *
57
+ * `suffix`, a few random printable characters, is appended where it fits, so two peers that
58
+ * insert at the same spot at once get distinct keys with room between them. The key stays short:
59
+ * it grows by about one character for every five keys inserted into the same gap.
60
+ *
61
+ * Every pair of bounds gets a key. When no printable key sorts between them, because `lo` is not
62
+ * below `hi` or `hi` is `lo` followed only by `!`, the result is the key `orderKeyBetween(lo, null)`
63
+ * gives, which is above `lo` but not below `hi`, and the caller must re-key `hi`.
64
+ */
65
+ export function orderKeyBetween(lo: string | null, hi: string | null, suffix = ''): string {
66
+ const key = keyBetween(lo, hi)
67
+ if (key === null) return (keyBetween(lo, null) ?? ORDER_KEY_MID) + suffix
68
+ if (!suffix) return key
69
+ if (hi === null) return key + suffix
70
+ return keyWithSuffix(lo, hi, suffix) ?? key
71
+ }
72
+
73
+ /** Whether some printable key sorts strictly between `lo` and `hi`. */
74
+ export function hasOrderKeyBetween(lo: string | null, hi: string | null): boolean {
75
+ return keyBetween(lo, hi) !== null
76
+ }
77
+
78
+ /** Indices of the longest strictly increasing run of keys, so a moved layer re-keys alone. */
79
+ function increasingKeyIndices(sourceKeys: ReadonlyArray<string | null | undefined>): Set<number> {
80
+ const tails: number[] = []
81
+ const previous = new Map<number, number>()
82
+ for (let index = 0; index < sourceKeys.length; index++) {
83
+ const key = sourceKeys[index]
84
+ if (!key) continue
85
+ let low = 0
86
+ let high = tails.length
87
+ while (low < high) {
88
+ const mid = (low + high) >> 1
89
+ if ((sourceKeys[tails[mid]] ?? '') < key) low = mid + 1
90
+ else high = mid
91
+ }
92
+ // A key with nothing below it cannot start the run once a sibling has to precede it.
93
+ if (low === 0 && index > 0 && !hasOrderKeyBetween(null, key)) continue
94
+ if (low > 0) previous.set(index, tails[low - 1])
95
+ tails[low] = index
96
+ }
97
+ const kept = new Set<number>()
98
+ for (let index = tails.at(-1); index !== undefined; index = previous.get(index)) kept.add(index)
99
+ return kept
100
+ }
101
+
102
+ export interface SiblingOrderKeyOptions {
103
+ /**
104
+ * Returns a suffix for each key the function makes up, as `orderKeyBetween` takes. Without it,
105
+ * a sibling that needs a key gets its index key when that fits between its neighbours.
106
+ */
107
+ suffix?: () => string
108
+ }
109
+
110
+ /**
111
+ * Order keys for siblings in their current order. The longest increasing run of existing keys
112
+ * is kept; other siblings get the index key when it fits between their neighbours (or a key with
113
+ * a suffix, when `options.suffix` is given), and otherwise a key between them, so no two siblings
114
+ * share a key.
115
+ */
116
+ export function siblingOrderKeys(
117
+ sourceKeys: ReadonlyArray<string | null | undefined>,
118
+ options: SiblingOrderKeyOptions = {}
119
+ ): string[] {
120
+ const keys: string[] = []
121
+ let prev: string | null = null
122
+ let pending: number[] = []
123
+
124
+ const nextKey = (index: number, lo: string | null, upper: string | null): string | null => {
125
+ if (options.suffix) {
126
+ const key = orderKeyBetween(lo, upper, options.suffix())
127
+ return upper === null || key < upper ? key : null
128
+ }
129
+ const candidate = fractionalPosition(index)
130
+ if ((lo === null || candidate > lo) && (upper === null || candidate < upper)) return candidate
131
+ return keyBetween(lo, upper)
132
+ }
133
+
134
+ const fill = (upper: string | null): string[] | null => {
135
+ const filled: string[] = []
136
+ let lo = prev
137
+ for (const index of pending) {
138
+ const key = nextKey(index, lo, upper)
139
+ if (key === null) return null
140
+ filled.push(key)
141
+ lo = key
142
+ }
143
+ return filled
144
+ }
145
+
146
+ const kept = increasingKeyIndices(sourceKeys)
147
+ for (let index = 0; index < sourceKeys.length; index++) {
148
+ const key = sourceKeys[index]
149
+ const filled = key && kept.has(index) ? fill(key) : null
150
+ if (key && filled) {
151
+ pending.forEach((pendingIndex, i) => (keys[pendingIndex] = filled[i]))
152
+ keys[index] = key
153
+ prev = key
154
+ pending = []
155
+ } else {
156
+ pending.push(index)
157
+ }
158
+ }
159
+ const rest = fill(null) ?? []
160
+ pending.forEach((pendingIndex, i) => (keys[pendingIndex] = rest[i]))
161
+ return keys
162
+ }
package/src/parse-path.ts CHANGED
@@ -21,10 +21,18 @@ interface ParseOptions {
21
21
  *
22
22
  * Uses `svgpath` to normalize all commands to absolute M/L/C/Z
23
23
  * (arcs → cubics via `.unarc()`, smooth curves → explicit via `.unshort()`).
24
+ *
25
+ * Only closed subpaths form the fill region unless `includeOpenRegions` is set. SVG fills every
26
+ * subpath as if it were closed, so set it for a filled path to keep holes that an open subpath and
27
+ * a closed one cut together under the path's fill rule.
24
28
  */
25
- export function parseSVGPath(d: string, windingRule: WindingRule = 'NONZERO'): VectorNetwork {
29
+ export function parseSVGPath(
30
+ d: string,
31
+ windingRule: WindingRule = 'NONZERO',
32
+ options: { includeOpenRegions?: boolean } = {}
33
+ ): VectorNetwork {
26
34
  const parsed = parsePath(d, windingRule, {
27
- includeOpenRegions: false,
35
+ includeOpenRegions: options.includeOpenRegions ?? false,
28
36
  strictCommands: false
29
37
  })
30
38
  return parsed.ok ? parsed.network : { vertices: [], segments: [], regions: [] }
@@ -0,0 +1,131 @@
1
+ import * as v from 'valibot'
2
+
3
+ import type { PluginDataEntry } from '../types'
4
+
5
+ /** The plugin id OpenPencil keeps its own state under, on nodes and in `.fig` files. */
6
+ export const OPEN_PENCIL_PLUGIN_ID = 'open-pencil'
7
+
8
+ /**
9
+ * What a field holds:
10
+ * - `content` belongs to the node like its fills do and exists only as plugin data, so it
11
+ * travels with a component copied into a library or another document;
12
+ * - `format` repeats a node or variable field for files that have no slot for it, where the
13
+ * node field is what counts;
14
+ * - `bookkeeping` records where a node or document came from and stays behind.
15
+ */
16
+ export type PluginDataRole = 'content' | 'format' | 'bookkeeping'
17
+
18
+ /** One OpenPencil plugin-data key. */
19
+ export interface PluginDataKey {
20
+ readonly key: string
21
+ readonly role: PluginDataRole
22
+ }
23
+
24
+ /** A plugin-data key and how its string value is read and written. */
25
+ export interface PluginDataField<T> extends PluginDataKey {
26
+ /** The stored value, or `undefined` when it is missing or not a valid value. */
27
+ decode(value: string | null | undefined): T | undefined
28
+ encode(value: T): string
29
+ }
30
+
31
+ /**
32
+ * A value stored as JSON. Invalid JSON and a wrong shape both read as missing: plugin data
33
+ * comes from files anyone can edit, so a bad entry is ignored rather than thrown on.
34
+ */
35
+ export function jsonPluginDataField<T>(
36
+ key: string,
37
+ role: PluginDataRole,
38
+ schema: v.GenericSchema<unknown, T>
39
+ ): PluginDataField<T> {
40
+ const stored = v.pipe(v.string(), v.parseJson(), schema)
41
+ return {
42
+ key,
43
+ role,
44
+ decode(value) {
45
+ const parsed = v.safeParse(stored, value)
46
+ return parsed.success ? parsed.output : undefined
47
+ },
48
+ encode: (value) => JSON.stringify(value)
49
+ }
50
+ }
51
+
52
+ /** A value stored as one of a fixed set of plain strings. */
53
+ export function textPluginDataField<const T extends string>(
54
+ key: string,
55
+ role: PluginDataRole,
56
+ values: readonly T[]
57
+ ): PluginDataField<T> {
58
+ const schema = v.picklist(values)
59
+ return {
60
+ key,
61
+ role,
62
+ decode(value) {
63
+ const parsed = v.safeParse(schema, value)
64
+ return parsed.success ? parsed.output : undefined
65
+ },
66
+ encode: (value) => value
67
+ }
68
+ }
69
+
70
+ export function isPluginDataEntry(entry: PluginDataEntry, field: PluginDataKey): boolean {
71
+ return entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === field.key
72
+ }
73
+
74
+ export function hasPluginData(
75
+ entries: readonly PluginDataEntry[] | undefined,
76
+ field: PluginDataKey
77
+ ): boolean {
78
+ return entries?.some((entry) => isPluginDataEntry(entry, field)) ?? false
79
+ }
80
+
81
+ export function readPluginData<T>(
82
+ entries: readonly PluginDataEntry[] | undefined,
83
+ field: PluginDataField<T>
84
+ ): T | undefined {
85
+ return field.decode(entries?.find((entry) => isPluginDataEntry(entry, field))?.value)
86
+ }
87
+
88
+ /** Every valid value of a field kept as several entries under one key. */
89
+ export function readAllPluginData<T>(
90
+ entries: readonly PluginDataEntry[] | undefined,
91
+ field: PluginDataField<T>
92
+ ): T[] {
93
+ return (entries ?? []).flatMap((entry) => {
94
+ if (!isPluginDataEntry(entry, field)) return []
95
+ const value = field.decode(entry.value)
96
+ return value === undefined ? [] : [value]
97
+ })
98
+ }
99
+
100
+ export function pluginDataEntry<T>(field: PluginDataField<T>, value: T): PluginDataEntry {
101
+ return { pluginId: OPEN_PENCIL_PLUGIN_ID, key: field.key, value: field.encode(value) }
102
+ }
103
+
104
+ /** Entries other than those of `fields`; other plugins' entries are always kept. */
105
+ export function withoutPluginData(
106
+ entries: readonly PluginDataEntry[],
107
+ fields: readonly PluginDataKey[]
108
+ ): PluginDataEntry[] {
109
+ return entries.filter((entry) => !fields.some((field) => isPluginDataEntry(entry, field)))
110
+ }
111
+
112
+ /** Entries with `field` set to `value`, appended last; `undefined` removes the field. */
113
+ export function withPluginData<T>(
114
+ entries: readonly PluginDataEntry[],
115
+ field: PluginDataField<T>,
116
+ value: T | undefined
117
+ ): PluginDataEntry[] {
118
+ return withAllPluginData(entries, field, value === undefined ? [] : [value])
119
+ }
120
+
121
+ /** Entries with every entry of `field` replaced by one per value. */
122
+ export function withAllPluginData<T>(
123
+ entries: readonly PluginDataEntry[],
124
+ field: PluginDataField<T>,
125
+ values: readonly T[]
126
+ ): PluginDataEntry[] {
127
+ return [
128
+ ...withoutPluginData(entries, [field]),
129
+ ...values.map((value) => pluginDataEntry(field, value))
130
+ ]
131
+ }