@open-pencil/scene-graph 0.15.1 → 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 +1711 -661
  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 +343 -55
  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,164 @@
1
+ import { scaleGeometryPaths } from '../copy'
2
+ import { TEXT_PARAGRAPH_SPACING_FIELDS } from '../text/paragraphs'
3
+ import {
4
+ type Effect,
5
+ type Fill,
6
+ type GridTrack,
7
+ type LayoutGrid,
8
+ type SceneNode,
9
+ type Stroke,
10
+ type StyleRun,
11
+ type TextParagraphStyle
12
+ } from '../types'
13
+ import { cloneVectorNetwork } from '../vector-network'
14
+
15
+ function scaledOptional(value: number | null, scale: number): number | null {
16
+ return value == null ? null : value * scale
17
+ }
18
+
19
+ function scaledStrokes(strokes: readonly Stroke[], scale: number): Stroke[] {
20
+ return strokes.map((stroke) => ({
21
+ ...structuredClone(stroke),
22
+ weight: stroke.weight * scale,
23
+ dashPattern: stroke.dashPattern?.map((value) => value * scale)
24
+ }))
25
+ }
26
+
27
+ function scaledEffects(effects: readonly Effect[], scale: number): Effect[] {
28
+ return effects.map((effect) => ({
29
+ ...structuredClone(effect),
30
+ offset: { x: effect.offset.x * scale, y: effect.offset.y * scale },
31
+ radius: effect.radius * scale,
32
+ spread: effect.spread * scale
33
+ }))
34
+ }
35
+
36
+ function scaledFills(fills: readonly Fill[], scale: number): Fill[] {
37
+ return fills.map((fill) => ({
38
+ ...structuredClone(fill),
39
+ scale: fill.scale == null ? undefined : fill.scale * scale,
40
+ spacing: fill.spacing == null ? undefined : fill.spacing * scale,
41
+ patternSpacing: fill.patternSpacing
42
+ ? { x: fill.patternSpacing.x * scale, y: fill.patternSpacing.y * scale }
43
+ : undefined,
44
+ noiseSize: fill.noiseSize
45
+ ? { x: fill.noiseSize.x * scale, y: fill.noiseSize.y * scale }
46
+ : undefined
47
+ }))
48
+ }
49
+
50
+ function scaledStyleRuns(styleRuns: readonly StyleRun[], scale: number): StyleRun[] {
51
+ return styleRuns.map((run) => ({
52
+ ...structuredClone(run),
53
+ style: {
54
+ ...structuredClone(run.style),
55
+ fontSize: run.style.fontSize == null ? undefined : run.style.fontSize * scale,
56
+ letterSpacing: run.style.letterSpacing == null ? undefined : run.style.letterSpacing * scale,
57
+ lineHeight: scaledOptional(run.style.lineHeight ?? null, scale),
58
+ textDecorationThickness: scaledOptional(run.style.textDecorationThickness ?? null, scale),
59
+ textUnderlineOffset: scaledOptional(run.style.textUnderlineOffset ?? null, scale)
60
+ }
61
+ }))
62
+ }
63
+
64
+ function scaledParagraphStyles(
65
+ paragraphs: readonly TextParagraphStyle[],
66
+ scale: number
67
+ ): TextParagraphStyle[] {
68
+ return paragraphs.map((style) => {
69
+ const scaled = { ...style }
70
+ for (const field of TEXT_PARAGRAPH_SPACING_FIELDS) {
71
+ const value = style[field]
72
+ if (value !== undefined) scaled[field] = value * scale
73
+ }
74
+ return scaled
75
+ })
76
+ }
77
+
78
+ function scaledLayoutGrids(grids: readonly LayoutGrid[], scale: number): LayoutGrid[] {
79
+ return grids.map((grid) => ({
80
+ ...structuredClone(grid),
81
+ offset: grid.offset == null ? undefined : grid.offset * scale,
82
+ sectionSize: grid.sectionSize == null ? undefined : grid.sectionSize * scale,
83
+ gutterSize: grid.gutterSize == null ? undefined : grid.gutterSize * scale
84
+ }))
85
+ }
86
+
87
+ function scaledGridTracks(tracks: readonly GridTrack[], scale: number): GridTrack[] {
88
+ return tracks.map((track) => ({
89
+ ...track,
90
+ value: track.sizing === 'FIXED' ? track.value * scale : track.value
91
+ }))
92
+ }
93
+
94
+ function scaledVectorNetwork(node: SceneNode, scale: number): SceneNode['vectorNetwork'] {
95
+ if (!node.vectorNetwork) return null
96
+ const network = cloneVectorNetwork(node.vectorNetwork)
97
+ for (const vertex of network.vertices) {
98
+ vertex.x *= scale
99
+ vertex.y *= scale
100
+ }
101
+ for (const segment of network.segments) {
102
+ segment.tangentStart.x *= scale
103
+ segment.tangentStart.y *= scale
104
+ segment.tangentEnd.x *= scale
105
+ segment.tangentEnd.y *= scale
106
+ }
107
+ return network
108
+ }
109
+
110
+ export function scaleNodeChanges(
111
+ node: SceneNode,
112
+ scale: number,
113
+ scalePosition: boolean
114
+ ): Partial<SceneNode> {
115
+ return {
116
+ x: scalePosition ? node.x * scale : node.x,
117
+ y: scalePosition ? node.y * scale : node.y,
118
+ width: node.width * scale,
119
+ height: node.height * scale,
120
+ minWidth: scaledOptional(node.minWidth, scale),
121
+ maxWidth: scaledOptional(node.maxWidth, scale),
122
+ minHeight: scaledOptional(node.minHeight, scale),
123
+ maxHeight: scaledOptional(node.maxHeight, scale),
124
+ cornerRadius: node.cornerRadius * scale,
125
+ topLeftRadius: node.topLeftRadius * scale,
126
+ topRightRadius: node.topRightRadius * scale,
127
+ bottomRightRadius: node.bottomRightRadius * scale,
128
+ bottomLeftRadius: node.bottomLeftRadius * scale,
129
+ fontSize: node.fontSize * scale,
130
+ letterSpacing: node.letterSpacing * scale,
131
+ lineHeight: scaledOptional(node.lineHeight, scale),
132
+ textDecorationThickness: scaledOptional(node.textDecorationThickness, scale),
133
+ textUnderlineOffset: scaledOptional(node.textUnderlineOffset, scale),
134
+ styleRuns: scaledStyleRuns(node.styleRuns, scale),
135
+ listSpacing: node.listSpacing * scale,
136
+ paragraphSpacing: node.paragraphSpacing * scale,
137
+ paragraphIndent: node.paragraphIndent * scale,
138
+ textParagraphs: scaledParagraphStyles(node.textParagraphs, scale),
139
+ itemSpacing: node.itemSpacing * scale,
140
+ counterAxisSpacing: node.counterAxisSpacing * scale,
141
+ paddingTop: node.paddingTop * scale,
142
+ paddingRight: node.paddingRight * scale,
143
+ paddingBottom: node.paddingBottom * scale,
144
+ paddingLeft: node.paddingLeft * scale,
145
+ gridColumnGap: node.gridColumnGap * scale,
146
+ gridRowGap: node.gridRowGap * scale,
147
+ gridTemplateColumns: scaledGridTracks(node.gridTemplateColumns, scale),
148
+ gridTemplateRows: scaledGridTracks(node.gridTemplateRows, scale),
149
+ strokes: scaledStrokes(node.strokes, scale),
150
+ strokeWeight: node.strokeWeight * scale,
151
+ dashPattern: node.dashPattern.map((value) => value * scale),
152
+ borderTopWeight: node.borderTopWeight * scale,
153
+ borderRightWeight: node.borderRightWeight * scale,
154
+ borderBottomWeight: node.borderBottomWeight * scale,
155
+ borderLeftWeight: node.borderLeftWeight * scale,
156
+ strokeMiterLimit: node.strokeMiterLimit,
157
+ effects: scaledEffects(node.effects, scale),
158
+ fills: scaledFills(node.fills, scale),
159
+ layoutGrids: scaledLayoutGrids(node.layoutGrids, scale),
160
+ vectorNetwork: scaledVectorNetwork(node, scale),
161
+ fillGeometry: scaleGeometryPaths(node.fillGeometry, scale, scale),
162
+ strokeGeometry: scaleGeometryPaths(node.strokeGeometry, scale, scale)
163
+ }
164
+ }
@@ -0,0 +1,50 @@
1
+ import type { SceneGraph } from '../index'
2
+ import { findInstanceAncestor } from '../instances'
3
+ import type { SceneNode } from '../types'
4
+ import { scaleVariableBindingUnits } from '../variables/units'
5
+ import { scaleNodeChanges } from './node'
6
+
7
+ const MIN_SCALE = 0.01
8
+ const RESCALABLE_NODE_TYPES = new Set<SceneNode['type']>([
9
+ 'BOOLEAN_OPERATION',
10
+ 'COMPONENT',
11
+ 'COMPONENT_SET',
12
+ 'ELLIPSE',
13
+ 'FRAME',
14
+ 'GROUP',
15
+ 'INSTANCE',
16
+ 'LINE',
17
+ 'POLYGON',
18
+ 'RECTANGLE',
19
+ 'STAR',
20
+ 'TEXT',
21
+ 'VECTOR'
22
+ ])
23
+
24
+ /** Scale a node tree from the root node's top-left, matching Figma's Scale tool. */
25
+ export function rescaleNodeTree(graph: SceneGraph, rootId: string, scale: number): void {
26
+ if (!Number.isFinite(scale)) throw new TypeError('Scale must be a finite number')
27
+ if (scale < MIN_SCALE) throw new RangeError(`Scale must be at least ${MIN_SCALE}`)
28
+ const root = graph.getNode(rootId)
29
+ if (!root || !RESCALABLE_NODE_TYPES.has(root.type))
30
+ throw new Error('rescale() is not supported on this node')
31
+ const nodes: SceneNode[] = [root]
32
+ const collect = (node: SceneNode): void => {
33
+ for (const childId of node.childIds) {
34
+ const child = graph.getNode(childId)
35
+ if (!child) continue
36
+ nodes.push(child)
37
+ collect(child)
38
+ }
39
+ }
40
+ collect(root)
41
+ for (const node of nodes) {
42
+ graph.updateNode(node.id, {
43
+ ...scaleNodeChanges(node, scale, node.id !== rootId),
44
+ ...scaleVariableBindingUnits(node, scale),
45
+ componentScale: findInstanceAncestor(graph, node.id)
46
+ ? node.componentScale * scale
47
+ : node.componentScale
48
+ })
49
+ }
50
+ }
@@ -0,0 +1,98 @@
1
+ import { TRANSPARENT } from '../constants'
2
+ import { computeImageHash } from '../images'
3
+ import { readAllPluginData, withAllPluginData } from '../plugin-data/field'
4
+ import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'
5
+ import { randomHex } from '../random'
6
+ import type { Fill, SceneNode } from '../types'
7
+ import type { ShaderPaint, ShaderPreset } from './schema'
8
+
9
+ /** What shader paints read of a node. */
10
+ type ShaderNode = Pick<SceneNode, 'fills' | 'strokes' | 'pluginData'>
11
+
12
+ /** Every shader a node's fills and strokes draw, whether or not a paint still shows it. */
13
+ export function readShaderPaints(node: Pick<SceneNode, 'pluginData'>): ShaderPaint[] {
14
+ return readAllPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.shader)
15
+ }
16
+
17
+ /**
18
+ * The shader a fill or stroke of `node` draws: an image paint whose image is a shader's frame.
19
+ * Null for any other paint, including one whose image was replaced, which then draws as the
20
+ * image it holds.
21
+ */
22
+ export function shaderOfPaint(
23
+ node: Pick<SceneNode, 'pluginData'>,
24
+ paint: Fill
25
+ ): ShaderPaint | null {
26
+ if (paint.type !== 'IMAGE' || !paint.imageHash) return null
27
+ return readShaderPaints(node).find((shader) => shader.image === paint.imageHash) ?? null
28
+ }
29
+
30
+ /** Whether any paint of `node` draws a shader. */
31
+ export function hasShaderPaint(node: ShaderNode): boolean {
32
+ return [...node.fills, ...node.strokes].some((paint) => shaderOfPaint(node, paint) !== null)
33
+ }
34
+
35
+ /**
36
+ * The node's plugin data with `shaders` set by their image, keeping only shaders a fill or
37
+ * stroke of `paints` still shows, so removing or replacing a paint leaves no entry behind.
38
+ */
39
+ export function withShaderPaints(
40
+ node: Pick<SceneNode, 'pluginData'>,
41
+ paints: readonly Fill[],
42
+ shaders: readonly ShaderPaint[] = []
43
+ ): SceneNode['pluginData'] {
44
+ const shown = new Set(
45
+ paints.flatMap((paint) => (paint.type === 'IMAGE' && paint.imageHash ? [paint.imageHash] : []))
46
+ )
47
+ const byImage = new Map(readShaderPaints(node).map((shader) => [shader.image, shader]))
48
+ for (const shader of shaders) byImage.set(shader.image, shader)
49
+ return withAllPluginData(
50
+ node.pluginData,
51
+ OPEN_PENCIL_PLUGIN_DATA.shader,
52
+ [...byImage.values()].filter((shader) => shown.has(shader.image))
53
+ )
54
+ }
55
+
56
+ /**
57
+ * A new paint that draws `preset`, and the shader entry it shows. Its image names a frame not yet
58
+ * rendered, unique to this paint, so no other paint's entry claims it until the frame is drawn.
59
+ */
60
+ export function createShaderPaint(preset: ShaderPreset): {
61
+ paint: Fill
62
+ shader: ShaderPaint
63
+ } {
64
+ const image = randomHex(20)
65
+ return {
66
+ paint: {
67
+ type: 'IMAGE',
68
+ color: TRANSPARENT,
69
+ opacity: 1,
70
+ visible: true,
71
+ imageHash: image,
72
+ imageScaleMode: 'FILL'
73
+ },
74
+ shader: { image, preset: structuredClone(preset) }
75
+ }
76
+ }
77
+
78
+ /** A short key that tells one preset from another, which a rendered frame records. */
79
+ export function shaderPresetKey(preset: ShaderPreset): string {
80
+ return computeImageHash(new TextEncoder().encode(JSON.stringify(preset)))
81
+ }
82
+
83
+ /**
84
+ * Whether a shader's frame was rendered for its preset at the size `node` has now, so undoing a
85
+ * preset change after reopening the document does not keep a frame of the newer preset.
86
+ */
87
+ export function isShaderFrameCurrent(
88
+ shader: ShaderPaint,
89
+ size: { width: number; height: number }
90
+ ): boolean {
91
+ const { frame } = shader
92
+ return (
93
+ frame !== undefined &&
94
+ frame.preset === shaderPresetKey(shader.preset) &&
95
+ Math.round(frame.width) === Math.round(size.width) &&
96
+ Math.round(frame.height) === Math.round(size.height)
97
+ )
98
+ }
@@ -0,0 +1,48 @@
1
+ import * as v from 'valibot'
2
+
3
+ /** One effect of a shader preset, as the `shaders` library names it, with the effects it holds. */
4
+ export interface ShaderComponent {
5
+ type: string
6
+ id?: string
7
+ props?: Record<string, unknown>
8
+ children?: ShaderComponent[]
9
+ }
10
+
11
+ const shaderComponent: v.GenericSchema<unknown, ShaderComponent> = v.object({
12
+ type: v.pipe(v.string(), v.nonEmpty(), v.maxLength(100)),
13
+ id: v.optional(v.string()),
14
+ props: v.optional(v.record(v.string(), v.unknown())),
15
+ children: v.optional(v.array(v.lazy(() => shaderComponent)))
16
+ })
17
+
18
+ /**
19
+ * A shader as the `shaders` library describes it and shaders.com exports it: a tree of effects,
20
+ * drawn first to last.
21
+ */
22
+ export const shaderPresetSchema = v.object({
23
+ components: v.pipe(v.array(shaderComponent), v.minLength(1)),
24
+ structureVersion: v.optional(v.number())
25
+ })
26
+
27
+ export type ShaderPreset = v.InferOutput<typeof shaderPresetSchema>
28
+
29
+ /**
30
+ * A paint that draws a shader. The paint itself is an image fill of the shader's still frame, so
31
+ * every format and renderer that reads images shows it; this entry says which image it is, the
32
+ * preset that draws it, and the layer size and preset the frame was rendered for, which is
33
+ * missing until it is first rendered.
34
+ */
35
+ export const shaderPaintSchema = v.object({
36
+ image: v.pipe(v.string(), v.nonEmpty()),
37
+ preset: shaderPresetSchema,
38
+ frame: v.optional(
39
+ v.object({
40
+ width: v.pipe(v.number(), v.finite(), v.minValue(0)),
41
+ height: v.pipe(v.number(), v.finite(), v.minValue(0)),
42
+ /** The preset's key (`shaderPresetKey`) when the frame was rendered. */
43
+ preset: v.pipe(v.string(), v.nonEmpty())
44
+ })
45
+ )
46
+ })
47
+
48
+ export type ShaderPaint = v.InferOutput<typeof shaderPaintSchema>
@@ -0,0 +1,101 @@
1
+ import type { SceneGraph } from '../index'
2
+ import type { ComponentPropertyDefinition, SceneNode, SlotSettings } from '../types'
3
+ import { slotPropertyId } from './frames'
4
+
5
+ /** The settings a new slot starts with: no limits, any layer allowed. */
6
+ export const DEFAULT_SLOT_SETTINGS: SlotSettings = {
7
+ allowPreferredValuesOnly: false,
8
+ displayEmptyByDefault: false,
9
+ stretchChildOnInsert: false
10
+ }
11
+
12
+ /**
13
+ * The main component a layer belongs to, which defines the slots inside it. Layers of an
14
+ * instance are not authored there, so a layer under an instance has none.
15
+ */
16
+ export function slotOwner(graph: SceneGraph, node: SceneNode): SceneNode | undefined {
17
+ let current = node.parentId ? graph.getNode(node.parentId) : undefined
18
+ while (current && current.type !== 'CANVAS') {
19
+ if (current.type === 'COMPONENT') return current
20
+ if (current.type === 'INSTANCE') return undefined
21
+ current = current.parentId ? graph.getNode(current.parentId) : undefined
22
+ }
23
+ return undefined
24
+ }
25
+
26
+ /** Whether a frame inside a main component can become a slot. */
27
+ export function canCreateSlot(graph: SceneGraph, node: SceneNode): boolean {
28
+ return node.type === 'FRAME' && !slotPropertyId(node) && !!slotOwner(graph, node)
29
+ }
30
+
31
+ function uniqueSlotName(owner: SceneNode, base: string): string {
32
+ const taken = new Set(owner.componentPropertyDefinitions.map((definition) => definition.name))
33
+ if (!taken.has(base)) return base
34
+ let index = 2
35
+ while (taken.has(`${base} ${index}`)) index++
36
+ return `${base} ${index}`
37
+ }
38
+
39
+ /**
40
+ * Make a frame of a main component a slot: define a SLOT property, named after the frame, on
41
+ * the component and bind the frame's children to it. Instances pick up the slot on their next
42
+ * sync.
43
+ */
44
+ export function createSlotProperty(
45
+ graph: SceneGraph,
46
+ frameId: string,
47
+ id: string
48
+ ): ComponentPropertyDefinition | null {
49
+ const frame = graph.getNode(frameId)
50
+ const owner = frame && canCreateSlot(graph, frame) ? slotOwner(graph, frame) : undefined
51
+ if (!frame || !owner) return null
52
+ const definition: ComponentPropertyDefinition = {
53
+ id,
54
+ name: uniqueSlotName(owner, frame.name.trim() || 'Slot'),
55
+ type: 'SLOT',
56
+ defaultValue: '',
57
+ preferredValues: [],
58
+ slotSettings: { ...DEFAULT_SLOT_SETTINGS }
59
+ }
60
+ graph.updateNode(owner.id, {
61
+ componentPropertyDefinitions: [...owner.componentPropertyDefinitions, definition]
62
+ })
63
+ graph.updateNode(frame.id, {
64
+ componentPropertyReferences: [
65
+ ...frame.componentPropertyReferences,
66
+ { propertyId: id, field: 'SLOT_CONTENT' }
67
+ ]
68
+ })
69
+ return definition
70
+ }
71
+
72
+ /** What a slot's settings panel can change. */
73
+ export type SlotPropertyPatch = Partial<
74
+ Pick<ComponentPropertyDefinition, 'name' | 'description' | 'preferredValues'>
75
+ > & { slotSettings?: Partial<SlotSettings> }
76
+
77
+ /** Change a slot property's name, description, preferred components, or limits. */
78
+ export function updateSlotProperty(
79
+ graph: SceneGraph,
80
+ ownerId: string,
81
+ propertyId: string,
82
+ patch: SlotPropertyPatch
83
+ ): boolean {
84
+ const owner = graph.getNode(ownerId)
85
+ const current = owner?.componentPropertyDefinitions.find(
86
+ (definition) => definition.id === propertyId && definition.type === 'SLOT'
87
+ )
88
+ if (!owner || !current) return false
89
+ const { slotSettings, ...fields } = patch
90
+ const next: ComponentPropertyDefinition = {
91
+ ...current,
92
+ ...fields,
93
+ slotSettings: { ...DEFAULT_SLOT_SETTINGS, ...current.slotSettings, ...slotSettings }
94
+ }
95
+ graph.updateNode(owner.id, {
96
+ componentPropertyDefinitions: owner.componentPropertyDefinitions.map((definition) =>
97
+ definition.id === propertyId ? next : definition
98
+ )
99
+ })
100
+ return true
101
+ }
@@ -0,0 +1,124 @@
1
+ import type { SceneGraph } from '../index'
2
+ import { getInstanceOverride, setInstanceOverride } from '../instance-overrides'
3
+ import { cloneChildrenWithMapping } from '../instances/sync'
4
+ import type { SceneNode } from '../types'
5
+ import { ownsSlotContent, slotPropertyId } from './frames'
6
+
7
+ /**
8
+ * Where layers may be added, moved, or removed under a parent:
9
+ * - `free`: outside any instance, or inside a component definition;
10
+ * - `slot`: inside a slot of an instance, whose content the instance owns or can claim;
11
+ * - `locked`: anywhere else inside an instance, whose layers come from its component.
12
+ */
13
+ export type SlotScope =
14
+ | { kind: 'free' }
15
+ | { kind: 'slot'; frame: SceneNode; instance: SceneNode; propertyId: string }
16
+ | { kind: 'locked'; instance: SceneNode }
17
+
18
+ function parentOf(graph: SceneGraph, node: SceneNode): SceneNode | undefined {
19
+ return node.parentId ? graph.nodes.get(node.parentId) : undefined
20
+ }
21
+
22
+ function nearestInstance(graph: SceneGraph, node: SceneNode): SceneNode | undefined {
23
+ let current = parentOf(graph, node)
24
+ while (current && current.type !== 'INSTANCE') current = parentOf(graph, current)
25
+ return current
26
+ }
27
+
28
+ export function slotScope(graph: SceneGraph, parentId: string): SlotScope {
29
+ let current = graph.nodes.get(parentId)
30
+ while (current) {
31
+ const propertyId = slotPropertyId(current)
32
+ if (propertyId) {
33
+ const instance = nearestInstance(graph, current)
34
+ return instance ? { kind: 'slot', frame: current, instance, propertyId } : { kind: 'free' }
35
+ }
36
+ if (current.type === 'INSTANCE') return { kind: 'locked', instance: current }
37
+ current = parentOf(graph, current)
38
+ }
39
+ return { kind: 'free' }
40
+ }
41
+
42
+ /** Every layer below `node`; `enterInstances` also walks the layers of nested instances. */
43
+ function descendants(graph: SceneGraph, node: SceneNode, enterInstances: boolean): SceneNode[] {
44
+ const result: SceneNode[] = []
45
+ const visit = (parent: SceneNode): void => {
46
+ for (const childId of parent.childIds) {
47
+ const child = graph.nodes.get(childId)
48
+ if (!child) continue
49
+ result.push(child)
50
+ if (enterInstances || child.type !== 'INSTANCE') visit(child)
51
+ }
52
+ }
53
+ visit(node)
54
+ return result
55
+ }
56
+
57
+ /**
58
+ * Make the instance own its slot's content, as Figma does on the first edit: the layers
59
+ * stay where they are, but stop following the component. Overrides the instance held for
60
+ * them become their own values, or move to the nested instance they belong to.
61
+ */
62
+ export function claimSlotContent(
63
+ graph: SceneGraph,
64
+ scope: Extract<SlotScope, { kind: 'slot' }>
65
+ ): void {
66
+ const { frame, instance, propertyId } = scope
67
+ if (ownsSlotContent(graph, frame, propertyId)) return
68
+ const overrides = instance.instanceOverrides
69
+ for (const node of descendants(graph, frame, false)) {
70
+ overrides.descendants.delete(node.id)
71
+ if (node.type !== 'INSTANCE') {
72
+ graph.updateNode(node.id, { componentId: null })
73
+ continue
74
+ }
75
+ // A nested instance keeps the overrides its former owner applied inside it.
76
+ for (const inner of descendants(graph, node, true)) {
77
+ const fields = overrides.descendants.get(inner.id)
78
+ if (!fields) continue
79
+ for (const [field, value] of fields)
80
+ if (field !== 'sourceComponentId')
81
+ setInstanceOverride(node.instanceOverrides, node.id, inner.id, field, value)
82
+ overrides.descendants.delete(inner.id)
83
+ }
84
+ graph.updateNode(node.id, { instanceOverrides: node.instanceOverrides })
85
+ }
86
+ graph.updateNode(instance.id, {
87
+ instanceOverrides: overrides,
88
+ componentPropertyAssignments: { ...instance.componentPropertyAssignments, [propertyId]: '' }
89
+ })
90
+ }
91
+
92
+ /** The component layer an instance layer was cloned from. */
93
+ function componentSource(instance: SceneNode, node: SceneNode): string | null {
94
+ const mapped = getInstanceOverride(
95
+ instance.instanceOverrides,
96
+ instance.id,
97
+ node.id,
98
+ 'sourceComponentId'
99
+ )
100
+ return typeof mapped === 'string' ? mapped : node.componentId
101
+ }
102
+
103
+ /** Return the slot to its component's content: the instance stops owning it. */
104
+ export function resetSlotContent(
105
+ graph: SceneGraph,
106
+ scope: Extract<SlotScope, { kind: 'slot' }>
107
+ ): void {
108
+ const { frame, instance, propertyId } = scope
109
+ for (const childId of Array.from(frame.childIds)) graph.deleteNode(childId)
110
+ const assignments = { ...instance.componentPropertyAssignments }
111
+ Reflect.deleteProperty(assignments, propertyId)
112
+ graph.updateNode(instance.id, { componentPropertyAssignments: assignments })
113
+ const source = componentSource(instance, frame)
114
+ if (source && graph.nodes.has(source)) cloneChildrenWithMapping(graph, source, frame.id)
115
+ }
116
+
117
+ /** Remove everything from the slot; the instance keeps owning it, now empty. */
118
+ export function clearSlotContent(
119
+ graph: SceneGraph,
120
+ scope: Extract<SlotScope, { kind: 'slot' }>
121
+ ): void {
122
+ claimSlotContent(graph, scope)
123
+ for (const childId of Array.from(scope.frame.childIds)) graph.deleteNode(childId)
124
+ }