@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
@@ -0,0 +1,241 @@
1
+ import type {
2
+ SceneNode,
3
+ TextListType,
4
+ TextParagraphSpacingField,
5
+ TextParagraphStyle
6
+ } from '../types'
7
+
8
+ /** The style of a paragraph with no entry: not in a list. */
9
+ export const PLAIN_PARAGRAPH: Readonly<TextParagraphStyle> = Object.freeze({
10
+ listType: 'NONE',
11
+ indentation: 0
12
+ })
13
+
14
+ /** Figma nests list items at most this deep. */
15
+ export const MAX_LIST_INDENTATION = 5
16
+
17
+ /** A paragraph's characters: `start` to `end`, not counting the newline that ends it. */
18
+ export interface TextParagraphRange {
19
+ start: number
20
+ end: number
21
+ }
22
+
23
+ /** The paragraphs of `text`: one per line ending at a newline, and one after the last. */
24
+ export function textParagraphRanges(text: string): TextParagraphRange[] {
25
+ const ranges: TextParagraphRange[] = []
26
+ let start = 0
27
+ for (let index = text.indexOf('\n'); index !== -1; index = text.indexOf('\n', start)) {
28
+ ranges.push({ start, end: index })
29
+ start = index + 1
30
+ }
31
+ ranges.push({ start, end: text.length })
32
+ return ranges
33
+ }
34
+
35
+ /** The paragraph holding character `index`; a newline belongs to the paragraph it ends. */
36
+ export function paragraphIndexAt(text: string, index: number): number {
37
+ let paragraph = 0
38
+ const end = Math.min(index, text.length)
39
+ for (let at = text.indexOf('\n'); at !== -1 && at < end; at = text.indexOf('\n', at + 1)) {
40
+ paragraph++
41
+ }
42
+ return paragraph
43
+ }
44
+
45
+ export function paragraphStyleAt(
46
+ paragraphs: readonly TextParagraphStyle[],
47
+ paragraph: number
48
+ ): TextParagraphStyle {
49
+ return paragraphs[paragraph] ?? PLAIN_PARAGRAPH
50
+ }
51
+
52
+ export const TEXT_PARAGRAPH_SPACING_FIELDS: readonly TextParagraphSpacingField[] = [
53
+ 'listSpacing',
54
+ 'paragraphSpacing',
55
+ 'paragraphIndent'
56
+ ]
57
+
58
+ /** A paragraph's spacing: its own value, or the text's when it sets none. */
59
+ export function paragraphSpacingAt(
60
+ node: Pick<SceneNode, 'textParagraphs' | TextParagraphSpacingField>,
61
+ paragraph: number,
62
+ field: TextParagraphSpacingField
63
+ ): number {
64
+ return paragraphStyleAt(node.textParagraphs, paragraph)[field] ?? node[field]
65
+ }
66
+
67
+ /** Whether a paragraph sets any spacing of its own. */
68
+ export function hasParagraphSpacing(style: TextParagraphStyle): boolean {
69
+ return TEXT_PARAGRAPH_SPACING_FIELDS.some((field) => style[field] !== undefined)
70
+ }
71
+
72
+ /** A paragraph style with its own `field` set, or following the text again for `undefined`. */
73
+ export function withParagraphSpacing(
74
+ style: TextParagraphStyle,
75
+ field: TextParagraphSpacingField,
76
+ value: number | undefined
77
+ ): TextParagraphStyle {
78
+ const { [field]: _previous, ...rest } = style
79
+ return value === undefined ? rest : { ...rest, [field]: value }
80
+ }
81
+
82
+ /** Every paragraph's `field`, or `null` when they differ. */
83
+ export function sharedParagraphSpacing(
84
+ node: Pick<SceneNode, 'text' | 'textParagraphs' | TextParagraphSpacingField>,
85
+ field: TextParagraphSpacingField,
86
+ first = 0,
87
+ last = paragraphCount(node.text) - 1
88
+ ): number | null {
89
+ const value = paragraphSpacingAt(node, first, field)
90
+ for (let index = first + 1; index <= last; index++) {
91
+ if (paragraphSpacingAt(node, index, field) !== value) return null
92
+ }
93
+ return value
94
+ }
95
+
96
+ /** Paragraph styles with no paragraph setting its own `field`, as setting the text's does. */
97
+ export function paragraphStylesWithoutSpacing(
98
+ paragraphs: readonly TextParagraphStyle[],
99
+ field: TextParagraphSpacingField
100
+ ): TextParagraphStyle[] {
101
+ return trimParagraphStyles(
102
+ paragraphs.map((style) => withParagraphSpacing(style, field, undefined)),
103
+ paragraphs.length
104
+ )
105
+ }
106
+
107
+ /** Whether any paragraph of the node is a list item. */
108
+ export function hasTextList(node: Pick<SceneNode, 'textParagraphs'>): boolean {
109
+ return node.textParagraphs.some((paragraph) => paragraph.listType !== 'NONE')
110
+ }
111
+
112
+ /**
113
+ * Paragraph styles for `count` paragraphs, without the plain paragraphs at the end, so text
114
+ * without lists, indentation, or paragraph spacing of its own keeps none.
115
+ */
116
+ export function trimParagraphStyles(
117
+ paragraphs: readonly TextParagraphStyle[],
118
+ count: number
119
+ ): TextParagraphStyle[] {
120
+ const styles = paragraphs.slice(0, count).map((paragraph) => ({ ...paragraph }))
121
+ while (styles.length > 0) {
122
+ const last = styles[styles.length - 1]
123
+ if (last.listType !== 'NONE' || last.indentation !== 0 || hasParagraphSpacing(last)) break
124
+ styles.pop()
125
+ }
126
+ return styles
127
+ }
128
+
129
+ /** How many paragraphs `text` has: one more than its newlines. */
130
+ export function paragraphCount(text: string): number {
131
+ let count = 1
132
+ for (let at = text.indexOf('\n'); at !== -1; at = text.indexOf('\n', at + 1)) count++
133
+ return count
134
+ }
135
+
136
+ /**
137
+ * Paragraph styles after replacing `text[start, end)` with `inserted`, as Figma keeps them: the
138
+ * paragraph the edit starts in keeps its style, paragraphs a deleted newline joins to it are
139
+ * dropped, and paragraphs an inserted newline starts take its style.
140
+ */
141
+ export function paragraphStylesAfterEdit(
142
+ paragraphs: readonly TextParagraphStyle[],
143
+ text: string,
144
+ start: number,
145
+ end: number,
146
+ inserted: string
147
+ ): TextParagraphStyle[] {
148
+ if (paragraphs.length === 0) return []
149
+ const first = paragraphIndexAt(text, start)
150
+ const last = paragraphIndexAt(text, end)
151
+ const style = paragraphStyleAt(paragraphs, first)
152
+ const added = paragraphCount(inserted) - 1
153
+ const next = [
154
+ ...Array.from({ length: first }, (_, index) => paragraphStyleAt(paragraphs, index)),
155
+ ...Array.from({ length: added + 1 }, () => style),
156
+ ...paragraphs.slice(last + 1)
157
+ ]
158
+ return trimParagraphStyles(next, paragraphCount(text) - (last - first) + added)
159
+ }
160
+
161
+ /**
162
+ * Paragraph styles with every paragraph that `text[start, end)` touches changed by `change`,
163
+ * as a range setter changes whole paragraphs.
164
+ */
165
+ export function paragraphStylesInRange(
166
+ paragraphs: readonly TextParagraphStyle[],
167
+ text: string,
168
+ start: number,
169
+ end: number,
170
+ change: (style: TextParagraphStyle) => TextParagraphStyle
171
+ ): TextParagraphStyle[] {
172
+ const count = paragraphCount(text)
173
+ const first = paragraphIndexAt(text, start)
174
+ // An empty range still names the paragraph it sits in; a range ending right after a
175
+ // newline does not reach into the next paragraph.
176
+ const last = end > start ? paragraphIndexAt(text, end - 1) : first
177
+ const next = Array.from({ length: count }, (_, index) => {
178
+ const style = paragraphStyleAt(paragraphs, index)
179
+ return index >= first && index <= last ? change(style) : style
180
+ })
181
+ return trimParagraphStyles(next, count)
182
+ }
183
+
184
+ /**
185
+ * A paragraph style with its list type set. A list item is nested at least one level, and a
186
+ * paragraph leaving a list keeps no indentation.
187
+ */
188
+ export function withListType(
189
+ style: TextParagraphStyle,
190
+ listType: TextListType
191
+ ): TextParagraphStyle {
192
+ if (listType === 'NONE') return { ...style, listType, indentation: 0 }
193
+ return { ...style, listType, indentation: clampListIndentation(style.indentation) }
194
+ }
195
+
196
+ /** A paragraph style with its nesting set, kept in the range a list item allows. */
197
+ export function withIndentation(
198
+ style: TextParagraphStyle,
199
+ indentation: number
200
+ ): TextParagraphStyle {
201
+ if (style.listType === 'NONE') {
202
+ return {
203
+ ...style,
204
+ indentation: Math.max(0, Math.min(MAX_LIST_INDENTATION, Math.round(indentation)))
205
+ }
206
+ }
207
+ return { ...style, indentation: clampListIndentation(indentation) }
208
+ }
209
+
210
+ function clampListIndentation(indentation: number): number {
211
+ return Math.max(1, Math.min(MAX_LIST_INDENTATION, Math.round(indentation)))
212
+ }
213
+
214
+ /**
215
+ * Paragraph styles after `before` became `after` through one edit, found as the text between
216
+ * their common start and end, for editors that replace the text rather than report the edit.
217
+ */
218
+ export function paragraphStylesAfterTextChange(
219
+ paragraphs: readonly TextParagraphStyle[],
220
+ before: string,
221
+ after: string
222
+ ): TextParagraphStyle[] {
223
+ if (paragraphs.length === 0 || before === after) return paragraphs.map((style) => ({ ...style }))
224
+ let prefix = 0
225
+ const shorter = Math.min(before.length, after.length)
226
+ while (prefix < shorter && before[prefix] === after[prefix]) prefix++
227
+ let suffix = 0
228
+ while (
229
+ suffix < shorter - prefix &&
230
+ before[before.length - 1 - suffix] === after[after.length - 1 - suffix]
231
+ ) {
232
+ suffix++
233
+ }
234
+ return paragraphStylesAfterEdit(
235
+ paragraphs,
236
+ before,
237
+ prefix,
238
+ before.length - suffix,
239
+ after.slice(prefix, after.length - suffix)
240
+ )
241
+ }
@@ -1,40 +1,21 @@
1
- import type { SceneNode } from './types'
1
+ import { isEqual } from 'es-toolkit/predicate'
2
+
3
+ import { TEXT_SHAPING_FIELDS, TEXT_LAYOUT_FIELDS } from '../fields/text'
4
+ import type { SceneNode } from '../types'
2
5
 
3
6
  /**
4
7
  * Invalidate cached Skia textPicture (Paragraph snapshot). Includes width/height
5
8
  * because wrapping/layout depends on the box.
6
9
  */
7
10
  export const TEXT_PICTURE_KEYS: ReadonlySet<string> = new Set([
8
- 'text',
9
- 'fontSize',
10
- 'fontFamily',
11
- 'fontWeight',
12
- 'italic',
13
- 'textAlignHorizontal',
14
- 'textDirection',
15
- 'textAlignVertical',
16
- 'lineHeight',
17
- 'letterSpacing',
11
+ ...TEXT_SHAPING_FIELDS,
18
12
  'textDecoration',
19
- 'textCase',
20
- 'styleRuns',
21
13
  'fills',
22
14
  'width',
23
15
  'height'
24
16
  ])
25
17
 
26
- export const GLYPH_AFFECTING_KEYS: ReadonlySet<string> = new Set([
27
- 'text',
28
- 'fontSize',
29
- 'fontFamily',
30
- 'fontWeight',
31
- 'italic',
32
- 'textDirection',
33
- 'lineHeight',
34
- 'letterSpacing',
35
- 'textCase',
36
- 'styleRuns'
37
- ])
18
+ export const GLYPH_AFFECTING_KEYS: ReadonlySet<string> = new Set(TEXT_SHAPING_FIELDS)
38
19
 
39
20
  /**
40
21
  * Shared by SceneGraph.updateNode and updateNodePreview (drag hot path) so the
@@ -46,16 +27,27 @@ export function textCacheInvalidationChanges(
46
27
  changes: Partial<SceneNode>
47
28
  ): Partial<SceneNode> {
48
29
  const invalidated: Partial<SceneNode> = {}
49
- const keys = Object.keys(changes)
30
+ const keys = Object.keys(changes).filter(
31
+ (key) => !isEqual(node[key as keyof SceneNode], changes[key as keyof SceneNode])
32
+ )
50
33
  if (node.textPicture && keys.some((key) => TEXT_PICTURE_KEYS.has(key)))
51
34
  invalidated.textPicture = null
52
- const glyphsInvalidated = keys.some((key) => GLYPH_AFFECTING_KEYS.has(key))
35
+ const glyphsInvalidated =
36
+ keys.some((key) => GLYPH_AFFECTING_KEYS.has(key)) ||
37
+ TEXT_LAYOUT_FIELDS.some((key) => keys.includes(key))
38
+ if (glyphsInvalidated && !('derivedLayout' in changes)) invalidated.derivedLayout = null
53
39
  // A successful path-text edit supplies reflowed glyphs in `changes`. Every
54
40
  // other mutation path must drop stale baked glyphs and path identity rather
55
41
  // than pair new text/style with old visible outlines.
56
42
  if (node.derivedTextGlyphs && glyphsInvalidated && !changes.derivedTextGlyphs) {
57
- invalidated.derivedTextGlyphs = null
58
- invalidated.textPathData = null
43
+ // Path-text resize supplies transformed glyphs through the resize workflow. A raw box
44
+ // preview keeps them until that workflow commits or an actual shaping edit occurs.
45
+ const onlyPathBoxResize =
46
+ !!node.textPathData && keys.every((key) => key === 'width' || key === 'height')
47
+ if (!onlyPathBoxResize) {
48
+ invalidated.derivedTextGlyphs = null
49
+ invalidated.textPathData = null
50
+ }
59
51
  }
60
52
  return invalidated
61
53
  }
@@ -0,0 +1,50 @@
1
+ import { mapValues } from 'es-toolkit/object'
2
+
3
+ import type { StyleRun } from '../types'
4
+
5
+ /** What a text's runs refer to outside the text: the variables they bind and the styles they use. */
6
+ export interface StyleRunReferences {
7
+ variables: string[]
8
+ styles: string[]
9
+ }
10
+
11
+ /** The variables and styles a text's runs refer to, which copies and transfers carry with it. */
12
+ export function styleRunReferences(runs: readonly StyleRun[]): StyleRunReferences {
13
+ const variables = new Set<string>()
14
+ const styles = new Set<string>()
15
+ for (const { style } of runs) {
16
+ for (const id of Object.values(style.boundVariables ?? {})) if (id) variables.add(id)
17
+ if (style.textStyleId) styles.add(style.textStyleId)
18
+ if (style.fillStyleId) styles.add(style.fillStyleId)
19
+ }
20
+ return { variables: [...variables], styles: [...styles] }
21
+ }
22
+
23
+ /**
24
+ * Runs whose variables, styles, and linked layers are renamed, as a copy into another document
25
+ * renames them. Layers are renamed only when given, since a link may name a layer left behind.
26
+ */
27
+ export function remapStyleRunReferences(
28
+ runs: readonly StyleRun[],
29
+ rename: {
30
+ variable: (id: string) => string
31
+ style: (id: string) => string
32
+ node?: (id: string) => string
33
+ }
34
+ ): StyleRun[] {
35
+ return runs.map((run) => {
36
+ const { boundVariables, textStyleId, fillStyleId, hyperlink } = run.style
37
+ const linksLayer = hyperlink?.type === 'NODE' && rename.node !== undefined
38
+ if (!boundVariables && !textStyleId && !fillStyleId && !linksLayer) return run
39
+ const style = { ...run.style }
40
+ if (hyperlink?.type === 'NODE' && rename.node) {
41
+ style.hyperlink = { type: 'NODE', value: rename.node(hyperlink.value) }
42
+ }
43
+ if (boundVariables) {
44
+ style.boundVariables = mapValues(boundVariables, (id) => (id ? rename.variable(id) : id))
45
+ }
46
+ if (textStyleId) style.textStyleId = rename.style(textStyleId)
47
+ if (fillStyleId) style.fillStyleId = rename.style(fillStyleId)
48
+ return { ...run, style }
49
+ })
50
+ }
@@ -0,0 +1,84 @@
1
+ import { isEqual } from 'es-toolkit/predicate'
2
+
3
+ import type { SceneGraph } from '../index'
4
+ import { variableIdentityReferences } from './identity'
5
+ import type { prepareGraphTransfer } from './plan'
6
+ import { validateTransferReferences } from './validation'
7
+ import { prepareVariableTransfer } from './variables'
8
+
9
+ export type GraphTransferPlan = ReturnType<typeof prepareGraphTransfer>
10
+
11
+ function validate(target: SceneGraph, plan: GraphTransferPlan): void {
12
+ validateTransferReferences(target, plan)
13
+ const reserved = new Set([
14
+ ...target.nodes.keys(),
15
+ ...target.variables.keys(),
16
+ ...target.variableCollections.keys()
17
+ ])
18
+ const claim = (id: string): void => {
19
+ if (reserved.has(id)) throw new Error(`Transfer identity collision ${id}`)
20
+ reserved.add(id)
21
+ }
22
+ prepareVariableTransfer(
23
+ plan.variables,
24
+ plan.collections,
25
+ variableIdentityReferences(plan.variables, plan.collections)
26
+ )
27
+ for (const [id, mode] of plan.activeModes) {
28
+ if (
29
+ !plan.collections
30
+ .find((collection) => collection.id === id)
31
+ ?.modes.some((entry) => entry.modeId === mode)
32
+ )
33
+ throw new Error(`Invalid transferred active mode ${id}:${mode}`)
34
+ }
35
+ for (const collection of plan.collections) claim(collection.id)
36
+ for (const variable of plan.variables) claim(variable.id)
37
+ const parents = new Set(target.nodes.keys())
38
+ for (const node of plan.nodes) {
39
+ claim(node.id)
40
+ if ('id' in node.props || 'parentId' in node.props || 'childIds' in node.props)
41
+ throw new Error('Transfer props cannot override hierarchy identity')
42
+ if (!parents.has(node.parentId)) throw new Error(`Missing transfer parent ${node.parentId}`)
43
+ parents.add(node.id)
44
+ }
45
+ for (const id of [...plan.rootIds, ...plan.dependencyPageIds]) {
46
+ if (!plan.nodes.some((node) => node.id === id)) throw new Error(`Missing transfer root ${id}`)
47
+ }
48
+ for (const node of plan.nodes) {
49
+ if (node.props.componentId && !parents.has(node.props.componentId))
50
+ throw new Error(`Missing transfer component ${node.props.componentId}`)
51
+ }
52
+ for (const [hash, bytes] of plan.images) {
53
+ const existing = target.images.get(hash)
54
+ if (existing && !isEqual(existing, bytes)) throw new Error(`Transfer image collision ${hash}`)
55
+ }
56
+ }
57
+
58
+ /** Revalidate at insertion time. Event-delivery failures after commit are not rollback failures. */
59
+ export function applyGraphTransfer(target: SceneGraph, input: GraphTransferPlan): void {
60
+ const plan = structuredClone(input)
61
+ validate(target, plan)
62
+ const imageIds = [...plan.images.keys()].filter((hash) => !target.images.has(hash))
63
+ target.withBufferedEvents(() => {
64
+ try {
65
+ for (const collection of plan.collections) target.addCollection(collection)
66
+ for (const variable of plan.variables) target.addVariable(variable)
67
+ for (const [id, mode] of plan.activeModes) target.activeMode.set(id, mode)
68
+ for (const [hash, bytes] of plan.images)
69
+ if (!target.images.has(hash)) target.images.set(hash, bytes)
70
+ for (const node of plan.nodes)
71
+ target.createNodeWithId(node.id, node.type, node.parentId, { ...node.props, childIds: [] })
72
+ } catch (error) {
73
+ for (const node of plan.nodes.toReversed())
74
+ if (target.getNode(node.id)) target.deleteNode(node.id)
75
+ for (const variable of plan.variables) target.variables.delete(variable.id)
76
+ for (const collection of plan.collections) {
77
+ target.variableCollections.delete(collection.id)
78
+ target.activeMode.delete(collection.id)
79
+ }
80
+ for (const hash of imageIds) target.images.delete(hash)
81
+ throw error
82
+ }
83
+ })
84
+ }
@@ -0,0 +1,49 @@
1
+ import { cloneNodeProps } from '../copy'
2
+ import type { SceneGraph } from '../index'
3
+ import type { GraphTransferPlan } from './apply'
4
+
5
+ /** Capture post-placement state for redo; this does not authorize deleting shared resources. */
6
+ export function captureTransferredState(
7
+ graph: SceneGraph,
8
+ original: GraphTransferPlan
9
+ ): GraphTransferPlan {
10
+ const requireValue = <T>(value: T | undefined, kind: string, id: string): T => {
11
+ if (value === undefined) throw new Error(`Missing transferred ${kind} ${id}`)
12
+ return value
13
+ }
14
+ return {
15
+ nodeIds: new Map(original.nodeIds),
16
+ rootIds: [...original.rootIds],
17
+ dependencyPageIds: [...original.dependencyPageIds],
18
+ nodes: original.nodes.map((entry) => {
19
+ const node = requireValue(graph.getNode(entry.id), 'node', entry.id)
20
+ if (!node.parentId) throw new Error(`Missing transferred parent ${entry.id}`)
21
+ return {
22
+ id: node.id,
23
+ type: node.type,
24
+ parentId: node.parentId,
25
+ props: cloneNodeProps(node, null)
26
+ }
27
+ }),
28
+ variables: original.variables.map((variable) =>
29
+ structuredClone(requireValue(graph.variables.get(variable.id), 'variable', variable.id))
30
+ ),
31
+ collections: original.collections.map((collection) =>
32
+ structuredClone(
33
+ requireValue(graph.variableCollections.get(collection.id), 'collection', collection.id)
34
+ )
35
+ ),
36
+ activeModes: new Map(
37
+ original.collections.map((collection) => [
38
+ collection.id,
39
+ requireValue(graph.activeMode.get(collection.id), 'active mode', collection.id)
40
+ ])
41
+ ),
42
+ images: new Map(
43
+ [...original.images.keys()].map((hash) => [
44
+ hash,
45
+ requireValue(graph.images.get(hash), 'image', hash).slice()
46
+ ])
47
+ )
48
+ }
49
+ }
@@ -0,0 +1,16 @@
1
+ import type { Variable, VariableCollection } from '../types'
2
+
3
+ export function variableIdentityReferences(
4
+ variables: readonly Variable[],
5
+ collections: readonly VariableCollection[]
6
+ ) {
7
+ return {
8
+ variables: new Map(variables.map((variable) => [variable.id, variable.id])),
9
+ collections: new Map(collections.map((collection) => [collection.id, collection.id])),
10
+ modes: new Map(
11
+ collections.flatMap((collection) =>
12
+ collection.modes.map((mode) => [mode.modeId, mode.modeId] as const)
13
+ )
14
+ )
15
+ }
16
+ }
@@ -0,0 +1,6 @@
1
+ export { removeGraphTransfer } from './remove'
2
+ export { captureTransferredState } from './history'
3
+ export { applyGraphTransfer, type GraphTransferPlan } from './apply'
4
+ export { prepareGraphTransfer, type GraphTransferInput } from './plan'
5
+ export { prepareNodeTransfer, type NodeTransferReferences } from './nodes'
6
+ export { prepareVariableTransfer, type VariableTransferReferences } from './variables'
@@ -0,0 +1,120 @@
1
+ import { cloneNodeProps } from '../copy'
2
+ import { remapInstanceOverrideState } from '../instance-overrides'
3
+ import { remapStyleRunReferences, styleRunReferences } from '../text/references'
4
+ import type { ComponentPropertyType, SceneNode } from '../types'
5
+ import { requireTransferReference as required } from './references'
6
+ import type { VariableTransferReferences } from './variables'
7
+
8
+ export function semanticTransferReferences(node: SceneNode): string[] {
9
+ const runs = styleRunReferences(node.styleRuns)
10
+ return [
11
+ ...(node.componentId ? [node.componentId] : []),
12
+ ...Object.values(node.boundVariables),
13
+ ...runs.variables,
14
+ ...runs.styles,
15
+ ...[
16
+ node.fillStyleId,
17
+ node.strokeStyleId,
18
+ node.textStyleId,
19
+ node.effectStyleId,
20
+ node.gridStyleId
21
+ ].filter((id): id is string => !!id),
22
+ ...node.fillGeometry.flatMap((path) => (path.fillStyleId ? [path.fillStyleId] : [])),
23
+ ...node.strokeGeometry.flatMap((path) => (path.fillStyleId ? [path.fillStyleId] : [])),
24
+ ...Object.entries(node.componentPropertyAssignments).flatMap(([id, value]) => [id, value]),
25
+ ...node.componentPropertyReferences.map((reference) => reference.propertyId),
26
+ ...node.componentPropertyDefinitions.flatMap((definition) => [
27
+ definition.id,
28
+ ...(definition.type === 'INSTANCE_SWAP' && definition.defaultValue
29
+ ? [definition.defaultValue]
30
+ : [])
31
+ ]),
32
+ ...node.instanceOverrides.descendants.keys(),
33
+ ...[
34
+ ...node.instanceOverrides.self,
35
+ ...[...node.instanceOverrides.descendants.values()].flatMap((fields) => [...fields])
36
+ ].flatMap(([field, value]) =>
37
+ typeof value === 'string' &&
38
+ (field === 'componentId' ||
39
+ field === 'sourceComponentId' ||
40
+ field.startsWith('boundVariables/'))
41
+ ? [value]
42
+ : []
43
+ )
44
+ ]
45
+ }
46
+
47
+ export interface NodeTransferReferences extends VariableTransferReferences {
48
+ nodes: ReadonlyMap<string, string>
49
+ styles: ReadonlyMap<string, string>
50
+ properties: ReadonlyMap<string, string>
51
+ propertyTypes: ReadonlyMap<string, ComponentPropertyType>
52
+ }
53
+
54
+ /** Prepare runtime references without rewriting original format identities or ordinary text. */
55
+ export function prepareNodeTransfer(
56
+ source: SceneNode,
57
+ refs: NodeTransferReferences
58
+ ): Partial<SceneNode> {
59
+ const node = (id: string) => required(refs.nodes, id, 'node')
60
+ const variable = (id: string) => required(refs.variables, id, 'variable')
61
+ const property = (id: string) => required(refs.properties, id, 'property')
62
+ const style = (id: string) => required(refs.styles, id, 'style')
63
+ const propertyValue = (id: string, value: string): string => {
64
+ const type = refs.propertyTypes.get(id)
65
+ if (!type) throw new Error(`Missing property transfer type: ${id}`)
66
+ return type === 'INSTANCE_SWAP' && value ? node(value) : value
67
+ }
68
+ const values = (entries: Record<string, string>) =>
69
+ Object.fromEntries(
70
+ Object.entries(entries).map(([id, value]) => [property(id), propertyValue(id, value)])
71
+ )
72
+ const result = cloneNodeProps(source, null)
73
+ result.componentId = source.componentId ? node(source.componentId) : null
74
+ result.instanceOverrides = remapInstanceOverrideState(source.instanceOverrides, {
75
+ node,
76
+ variable
77
+ })
78
+ result.boundVariables = Object.fromEntries(
79
+ Object.entries(source.boundVariables).map(([field, id]) => [field, variable(id)])
80
+ )
81
+ result.variableModes = Object.fromEntries(
82
+ Object.entries(source.variableModes).map(([collection, mode]) => [
83
+ required(refs.collections, collection, 'collection'),
84
+ required(refs.modes, mode, 'mode')
85
+ ])
86
+ )
87
+ for (const field of [
88
+ 'fillStyleId',
89
+ 'strokeStyleId',
90
+ 'textStyleId',
91
+ 'effectStyleId',
92
+ 'gridStyleId'
93
+ ] as const) {
94
+ result[field] = source[field] ? style(source[field]) : null
95
+ }
96
+ if (result.styleRuns) {
97
+ // A link to a layer the transfer leaves behind keeps naming it.
98
+ result.styleRuns = remapStyleRunReferences(result.styleRuns, {
99
+ variable,
100
+ style,
101
+ node: (id) => refs.nodes.get(id) ?? id
102
+ })
103
+ }
104
+ for (const paths of [result.fillGeometry, result.strokeGeometry]) {
105
+ for (const path of paths ?? []) if (path.fillStyleId) path.fillStyleId = style(path.fillStyleId)
106
+ }
107
+ result.componentPropertyDefinitions = source.componentPropertyDefinitions.map((definition) => ({
108
+ ...structuredClone(definition),
109
+ id: property(definition.id),
110
+ defaultValue: propertyValue(definition.id, definition.defaultValue)
111
+ }))
112
+ result.componentPropertyReferences = source.componentPropertyReferences.map((reference) => ({
113
+ ...reference,
114
+ propertyId: property(reference.propertyId)
115
+ }))
116
+ result.componentPropertyAssignments = values(source.componentPropertyAssignments)
117
+ // Variant values are keyed by display names, unlike definition-ID assignments.
118
+ result.componentPropertyValues = { ...source.componentPropertyValues }
119
+ return result
120
+ }