@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,156 @@
1
+ import type { SceneGraph } from '../index'
2
+ import type { Color, Vector } from '../primitives'
3
+ import { randomHex } from '../random'
4
+ import type { CommentReply, CommentThread, SceneNode } from '../types'
5
+
6
+ /** Who writes a comment: their name and, in a collaboration room, their color. */
7
+ export interface CommentAuthor {
8
+ name: string
9
+ color?: Color
10
+ }
11
+
12
+ function newCommentId(prefix: 'c' | 'r'): string {
13
+ return `${prefix}_${randomHex(8)}`
14
+ }
15
+
16
+ /** When a comment is written or changed, as stored: an ISO timestamp. */
17
+ export function commentTimestamp(): string {
18
+ return new Date().toISOString()
19
+ }
20
+
21
+ /** Oldest first, the order threads and replies are shown and numbered in. */
22
+ export function byCreatedAt(a: { createdAt: string }, b: { createdAt: string }): number {
23
+ return a.createdAt.localeCompare(b.createdAt)
24
+ }
25
+
26
+ /** A thread's replies, without the deleted ones kept as tombstones. */
27
+ export function liveReplies(thread: CommentThread): CommentReply[] {
28
+ return thread.replies.filter((entry) => !entry.deleted)
29
+ }
30
+
31
+ /** Whether `author` started the thread or replied to it, as Figma's "Only your threads" counts. */
32
+ export function takesPartInThread(thread: CommentThread, author: string): boolean {
33
+ return thread.author === author || liveReplies(thread).some((entry) => entry.author === author)
34
+ }
35
+
36
+ /** The thread with `id`, unless it is missing or deleted. */
37
+ export function findLiveCommentThread(
38
+ threads: readonly CommentThread[],
39
+ id: string
40
+ ): CommentThread | undefined {
41
+ return threads.find((thread) => thread.id === id && !thread.deleted)
42
+ }
43
+
44
+ /**
45
+ * The layer a comment on `node` is kept on: its top-level layer, as Figma attaches comments, or
46
+ * within a section the section's own child, as frames move about inside it.
47
+ */
48
+ function commentLayer(graph: SceneGraph, node: SceneNode, pageId: string): SceneNode {
49
+ const isSection = (id: string | null) => !!id && graph.getNode(id)?.type === 'SECTION'
50
+ return (
51
+ graph.closest(node.id, (layer) => layer.parentId === pageId || isSection(layer.parentId)) ??
52
+ node
53
+ )
54
+ }
55
+
56
+ /**
57
+ * Where a pin at a canvas point is kept: on the top-level layer under it, or on `node`'s when
58
+ * given, so it follows that layer; on the canvas when nothing is there.
59
+ */
60
+ export function commentAnchor(graph: SceneGraph, pageId: string, at: Vector, node?: SceneNode) {
61
+ const target = node ?? graph.hitTest(at.x, at.y, pageId)
62
+ const layer = target ? commentLayer(graph, target, pageId) : null
63
+ const abs = layer ? graph.getAbsolutePosition(layer.id) : null
64
+ return {
65
+ nodeId: layer?.id ?? null,
66
+ nodeName: layer?.name ?? null,
67
+ offsetX: abs ? at.x - abs.x : 0,
68
+ offsetY: abs ? at.y - abs.y : 0,
69
+ x: at.x,
70
+ y: at.y
71
+ }
72
+ }
73
+
74
+ /** Where a thread's pin is now: on its layer while that layer exists, else where it was left. */
75
+ export function commentPosition(graph: SceneGraph, thread: CommentThread): Vector {
76
+ const node = thread.nodeId ? graph.getNode(thread.nodeId) : undefined
77
+ if (!node) return { x: thread.x, y: thread.y }
78
+ const abs = graph.getAbsolutePosition(node.id)
79
+ return { x: abs.x + (thread.offsetX ?? 0), y: abs.y + (thread.offsetY ?? 0) }
80
+ }
81
+
82
+ /** A new thread pinned at a canvas point of a page. */
83
+ export function createCommentThread(
84
+ graph: SceneGraph,
85
+ options: {
86
+ pageId: string
87
+ at: Vector
88
+ /** Pin it on this layer's top-level layer rather than on whatever is at `at`. */
89
+ node?: SceneNode
90
+ author: CommentAuthor
91
+ text: string
92
+ now: string
93
+ }
94
+ ): CommentThread {
95
+ const { pageId, at, node, author, text, now } = options
96
+ return {
97
+ id: newCommentId('c'),
98
+ pageId,
99
+ pageName: graph.getNode(pageId)?.name,
100
+ ...commentAnchor(graph, pageId, at, node),
101
+ author: author.name,
102
+ authorColor: author.color,
103
+ text,
104
+ createdAt: now,
105
+ updatedAt: now,
106
+ resolved: false,
107
+ replies: []
108
+ }
109
+ }
110
+
111
+ export function createCommentReply(author: CommentAuthor, text: string, now: string): CommentReply {
112
+ return {
113
+ id: newCommentId('r'),
114
+ author: author.name,
115
+ authorColor: author.color,
116
+ text,
117
+ createdAt: now
118
+ }
119
+ }
120
+
121
+ /** The threads with one changed and marked as edited at `now`, for merging with other copies. */
122
+ export function editCommentThread(
123
+ threads: readonly CommentThread[],
124
+ id: string,
125
+ now: string,
126
+ edit: (thread: CommentThread) => CommentThread
127
+ ): CommentThread[] {
128
+ return threads.map((thread) => (thread.id === id ? { ...edit(thread), updatedAt: now } : thread))
129
+ }
130
+
131
+ /** A reply ends up in the thread and reopens it, as answering a resolved comment does. */
132
+ export function replyToCommentThread(thread: CommentThread, reply: CommentReply): CommentThread {
133
+ return { ...thread, resolved: false, resolvedAt: null, replies: [...thread.replies, reply] }
134
+ }
135
+
136
+ export function resolveCommentThread(
137
+ thread: CommentThread,
138
+ resolved: boolean,
139
+ now: string
140
+ ): CommentThread {
141
+ return { ...thread, resolved, resolvedAt: resolved ? now : null }
142
+ }
143
+
144
+ /** Deleted threads and replies stay as tombstones, so a stale copy cannot bring them back. */
145
+ export function deleteCommentThread(thread: CommentThread): CommentThread {
146
+ return { ...thread, deleted: true }
147
+ }
148
+
149
+ export function deleteCommentReply(thread: CommentThread, replyId: string): CommentThread {
150
+ return {
151
+ ...thread,
152
+ replies: thread.replies.map((entry) =>
153
+ entry.id === replyId ? { ...entry, deleted: true } : entry
154
+ )
155
+ }
156
+ }
@@ -0,0 +1,61 @@
1
+ import type { SceneGraph } from '../index'
2
+ import { instanceMainComponent } from '../instances/main-component'
3
+ import { walkInstanceSources } from '../instances/source-walk'
4
+ import type { SceneNode } from '../types'
5
+ import { componentPropertyDefinitions } from './properties'
6
+
7
+ /**
8
+ * Instances a component can expose: those in its own layers, not inside another instance,
9
+ * whose content belongs to that instance's component.
10
+ */
11
+ export function exposableInstances(graph: SceneGraph, componentId: string): SceneNode[] {
12
+ const found: SceneNode[] = []
13
+ const visit = (parentId: string): void => {
14
+ for (const child of graph.getChildren(parentId)) {
15
+ if (child.type === 'INSTANCE') found.push(child)
16
+ else visit(child.id)
17
+ }
18
+ }
19
+ visit(componentId)
20
+ return found
21
+ }
22
+
23
+ /**
24
+ * The layers of an instance that stand for exposed nested instances of its component, in
25
+ * layer order. Each is matched to its source the way instance sync matches children.
26
+ */
27
+ export function exposedInstances(graph: SceneGraph, instance: SceneNode): SceneNode[] {
28
+ const found: SceneNode[] = []
29
+ walkInstanceSources(graph, instance, (source, target) => {
30
+ if (source.type !== 'INSTANCE') return true
31
+ if (source.isExposedInstance) found.push(target)
32
+ return false
33
+ })
34
+ return found
35
+ }
36
+
37
+ const OWNER_TYPES = new Set<SceneNode['type']>(['INSTANCE', 'COMPONENT', 'COMPONENT_SET'])
38
+
39
+ /** Why Figma refuses to expose an instance, or null when it may be exposed. */
40
+ export type InstanceExposureIssue = 'not-in-component' | 'not-primary' | 'nothing-to-expose'
41
+
42
+ /**
43
+ * Whether an instance may be exposed, under Figma's rules: it sits in a component's own layers
44
+ * (an instance's copy follows its source) and its component has properties or exposes nested
45
+ * instances itself.
46
+ */
47
+ export function instanceExposureIssue(
48
+ graph: SceneGraph,
49
+ instance: SceneNode
50
+ ): InstanceExposureIssue | null {
51
+ const owner = instance.parentId
52
+ ? graph.closest(instance.parentId, (node) => OWNER_TYPES.has(node.type))
53
+ : undefined
54
+ if (!owner) return 'not-in-component'
55
+ if (owner.type === 'INSTANCE') return 'not-primary'
56
+ const component = instanceMainComponent(graph, instance)
57
+ const exposes =
58
+ componentPropertyDefinitions(graph, instance).length > 0 ||
59
+ (!!component && exposableInstances(graph, component.id).some((node) => node.isExposedInstance))
60
+ return exposes ? null : 'nothing-to-expose'
61
+ }
@@ -1,6 +1,9 @@
1
1
  import type { SceneGraph } from '../index'
2
2
  import { setInstanceOverride } from '../instance-overrides'
3
3
  import { findInstanceAncestor } from '../instances'
4
+ import { instanceMainComponent } from '../instances/main-component'
5
+ import { walkInstanceSources } from '../instances/source-walk'
6
+ import { randomHex } from '../random'
4
7
  import type {
5
8
  ComponentPropertyDefinition,
6
9
  ComponentPropertyReferenceField,
@@ -14,8 +17,8 @@ export interface ComponentPropertyTarget {
14
17
  }
15
18
 
16
19
  export function componentPropertyOwners(graph: SceneGraph, instance: SceneNode): SceneNode[] {
17
- if (instance.type !== 'INSTANCE' || !instance.componentId) return []
18
- const component = graph.getNode(instance.componentId)
20
+ if (instance.type !== 'INSTANCE') return []
21
+ const component = instanceMainComponent(graph, instance)
19
22
  if (!component) return []
20
23
  const parent = component.parentId ? graph.getNode(component.parentId) : null
21
24
  return parent?.type === 'COMPONENT_SET' ? [parent, component] : [component]
@@ -65,24 +68,19 @@ export function findComponentPropertyTargets(
65
68
  instance: SceneNode,
66
69
  propertyId: string
67
70
  ): ComponentPropertyTarget[] {
68
- if (instance.type !== 'INSTANCE' || !instance.componentId) return []
69
- const component = graph.getNode(instance.componentId)
70
- if (!component) return []
71
71
  const targets: ComponentPropertyTarget[] = []
72
- const visit = (sourceParent: SceneNode, instanceParent: SceneNode): void => {
73
- for (const [index, childId] of sourceParent.childIds.entries()) {
74
- const source = graph.getNode(childId)
75
- const targetId = instanceParent.childIds[index]
76
- const target = targetId ? graph.getNode(targetId) : undefined
77
- if (!source || !target) continue
72
+ walkInstanceSources(
73
+ graph,
74
+ instance,
75
+ (source, target) => {
78
76
  const reference = source.componentPropertyReferences.find(
79
77
  (candidate) => candidate.propertyId === propertyId
80
78
  )
81
79
  if (reference) targets.push({ node: target, field: reference.field, source })
82
- visit(source, target)
83
- }
84
- }
85
- visit(component, instance)
80
+ return true
81
+ },
82
+ true
83
+ )
86
84
  return targets
87
85
  }
88
86
 
@@ -236,3 +234,8 @@ export function removeComponentProperty(
236
234
  for (const node of nodes) removePropertyFromNode(graph, node, propertyId)
237
235
  return true
238
236
  }
237
+
238
+ /** A new component property ID, in the `prop:` form the editor, plugin API, and design JSX share. */
239
+ export function createComponentPropertyId(): string {
240
+ return `prop:${randomHex(8)}`
241
+ }
@@ -0,0 +1,53 @@
1
+ import type { SceneGraph } from '../index'
2
+ import type { SceneNode } from '../types'
3
+
4
+ /** Variants in reading order on the canvas: top to bottom, then left to right, then by name. */
5
+ export function compareCanvasPosition(a: SceneNode, b: SceneNode): number {
6
+ return a.y - b.y || a.x - b.x || a.name.localeCompare(b.name)
7
+ }
8
+
9
+ /**
10
+ * A component set's default variant, the one an instance starts as: the variant in its
11
+ * top-left corner, as Figma defines it.
12
+ */
13
+ export function defaultVariant(graph: SceneGraph, set: SceneNode): SceneNode | undefined {
14
+ return graph
15
+ .getChildren(set.id)
16
+ .filter((child) => child.type === 'COMPONENT')
17
+ .sort(compareCanvasPosition)[0]
18
+ }
19
+
20
+ /**
21
+ * The value a variant property starts at: its recorded default when that is one of its options,
22
+ * or else the default variant's, since a document may leave the recorded default empty.
23
+ */
24
+ export function variantDefaultValue(
25
+ graph: SceneGraph,
26
+ set: SceneNode,
27
+ property: { name: string; defaultValue: string; variantOptions?: string[] }
28
+ ): string {
29
+ if (property.variantOptions?.includes(property.defaultValue)) return property.defaultValue
30
+ return defaultVariant(graph, set)?.componentPropertyValues[property.name] ?? property.defaultValue
31
+ }
32
+
33
+ /**
34
+ * The variant with every property at its default value: the recorded defaults when they name a
35
+ * variant, else the default variant, as a document that leaves them out draws it.
36
+ */
37
+ export function restingVariant(graph: SceneGraph, set: SceneNode): SceneNode | undefined {
38
+ const properties = set.componentPropertyDefinitions.filter(
39
+ (definition) => definition.type === 'VARIANT'
40
+ )
41
+ const values = properties.map(
42
+ (property) => [property.name, variantDefaultValue(graph, set, property)] as const
43
+ )
44
+ return (
45
+ graph
46
+ .getChildren(set.id)
47
+ .find(
48
+ (child) =>
49
+ child.type === 'COMPONENT' &&
50
+ values.every(([name, value]) => child.componentPropertyValues[name] === value)
51
+ ) ?? defaultVariant(graph, set)
52
+ )
53
+ }
package/src/constants.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import type { Color } from './primitives'
2
2
 
3
3
  export const BLACK: Color = { r: 0, g: 0, b: 0, a: 1 }
4
+ export const WHITE: Color = { r: 1, g: 1, b: 1, a: 1 }
4
5
  export const TRANSPARENT: Color = { r: 0, g: 0, b: 0, a: 0 }
5
6
  export const DEFAULT_FONT_FAMILY = 'Inter'
6
7
  export const DEFAULT_STROKE_MITER_LIMIT = 4
8
+ export const DEFAULT_STROKE_WEIGHT = 1
package/src/coordinate.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { SceneGraph, SceneNode } from './index'
2
2
  import Matrix, { type Mat3 } from './matrix'
3
+ import { FITTED_CONTAINER_TYPES } from './node-defaults'
3
4
  import type { Rect, Vector } from './primitives'
4
5
 
5
6
  export function getWorldMatrix(node: SceneNode, graph: Pick<SceneGraph, 'getNode'>): Mat3 {
@@ -22,27 +23,58 @@ export function getWorldMatrix(node: SceneNode, graph: Pick<SceneGraph, 'getNode
22
23
  return matrix
23
24
  }
24
25
 
25
- export function getAxisAlignedWorldBounds(node: SceneNode, graph: Pick<SceneGraph, 'getNode'>) {
26
- const matrix = getWorldMatrix(node, graph)
27
- const points = Matrix.mapPoints(matrix, [
28
- 0,
29
- 0,
30
- node.width,
31
- 0,
32
- node.width,
33
- node.height,
34
- 0,
35
- node.height
36
- ])
37
- const xs = [points[0], points[2], points[4], points[6]]
38
- const ys = [points[1], points[3], points[5], points[7]]
39
- const minX = Math.min(...xs)
40
- const maxX = Math.max(...xs)
41
- const minY = Math.min(...ys)
42
- const maxY = Math.max(...ys)
26
+ /** Axis-aligned box around interleaved `x, y` points; empty input gives an empty box at the origin. */
27
+ function boundsOfPoints(points: readonly number[]): Rect {
28
+ if (points.length === 0) return { x: 0, y: 0, width: 0, height: 0 }
29
+ let minX = Infinity
30
+ let minY = Infinity
31
+ let maxX = -Infinity
32
+ let maxY = -Infinity
33
+ for (let i = 0; i < points.length; i += 2) {
34
+ minX = Math.min(minX, points[i])
35
+ minY = Math.min(minY, points[i + 1])
36
+ maxX = Math.max(maxX, points[i])
37
+ maxY = Math.max(maxY, points[i + 1])
38
+ }
43
39
  return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }
44
40
  }
45
41
 
42
+ function cornersOf(node: Pick<SceneNode, 'width' | 'height'>): number[] {
43
+ return [0, 0, node.width, 0, node.width, node.height, 0, node.height]
44
+ }
45
+
46
+ export function getAxisAlignedWorldBounds(node: SceneNode, graph: Pick<SceneGraph, 'getNode'>) {
47
+ return boundsOfPoints(Matrix.mapPoints(getWorldMatrix(node, graph), cornersOf(node)))
48
+ }
49
+
50
+ /** World matrix of a parent; the document root and a missing parent are the identity. */
51
+ export function getParentWorldMatrix(
52
+ parent: SceneNode | undefined,
53
+ graph: Pick<SceneGraph, 'getNode' | 'rootId'>
54
+ ): Mat3 {
55
+ if (!parent || parent.id === graph.rootId) return Matrix.identity()
56
+ return getWorldMatrix(parent, graph)
57
+ }
58
+
59
+ /**
60
+ * Axis-aligned box of `nodes` in `parentId`'s own axes: where a group, frame, or boolean operation
61
+ * made from them sits. Each node's corners are mapped through the parent's inverse world matrix,
62
+ * so a rotated or flipped parent gets a box in its own axes and the nodes keep their drawn places
63
+ * once they move into the container.
64
+ */
65
+ export function getAxisAlignedBoundsInParent(
66
+ nodes: readonly SceneNode[],
67
+ parentId: string,
68
+ graph: Pick<SceneGraph, 'getNode' | 'rootId'>
69
+ ): Rect {
70
+ const toParent =
71
+ Matrix.invert(getParentWorldMatrix(graph.getNode(parentId), graph)) ?? Matrix.identity()
72
+ const points = nodes.flatMap((node) =>
73
+ Matrix.mapPoints(Matrix.multiply(toParent, getWorldMatrix(node, graph)), cornersOf(node))
74
+ )
75
+ return boundsOfPoints(points)
76
+ }
77
+
46
78
  export function getAbsolutePosition(node: SceneNode, graph: SceneGraph): Vector {
47
79
  const matrix = getWorldMatrix(node, graph)
48
80
  const p = Matrix.mapPoints(matrix, [0, 0])
@@ -142,31 +174,7 @@ export function getNodeLocalMatrix(n: SceneNode, position: Vector = n) {
142
174
  return matrix
143
175
  }
144
176
  export function getNodeWorldBounds(node: SceneNode) {
145
- const m = getNodeLocalMatrix(node)
146
-
147
- const points = Matrix.mapPoints(m, [0, 0, node.width, 0, node.width, node.height, 0, node.height])
148
-
149
- let minX = Infinity
150
- let minY = Infinity
151
- let maxX = -Infinity
152
- let maxY = -Infinity
153
-
154
- for (let i = 0; i < points.length; i += 2) {
155
- const x = points[i]
156
- const y = points[i + 1]
157
-
158
- minX = Math.min(minX, x)
159
- minY = Math.min(minY, y)
160
- maxX = Math.max(maxX, x)
161
- maxY = Math.max(maxY, y)
162
- }
163
-
164
- return {
165
- x: minX,
166
- y: minY,
167
- width: maxX - minX,
168
- height: maxY - minY
169
- }
177
+ return boundsOfPoints(Matrix.mapPoints(getNodeLocalMatrix(node), cornersOf(node)))
170
178
  }
171
179
 
172
180
  /**
@@ -224,3 +232,52 @@ export function getWorldHandles(
224
232
  w: { x: pts[14], y: pts[15] }
225
233
  }
226
234
  }
235
+
236
+ type LocalTransform = Pick<SceneNode, 'x' | 'y' | 'rotation' | 'flipX' | 'flipY'>
237
+
238
+ /**
239
+ * Local transform that draws `node` with the given world matrix once it sits under a parent
240
+ * whose world matrix is `parentWorld`. Keeps the node's own `flipX` when the matrix allows it.
241
+ */
242
+ export function localTransformFromWorld(
243
+ node: SceneNode,
244
+ world: Mat3,
245
+ parentWorld: Mat3
246
+ ): LocalTransform | null {
247
+ const parentInverse = Matrix.invert(parentWorld)
248
+ if (!parentInverse) return null
249
+ const local = Matrix.multiply(parentInverse, world)
250
+ const [a, b, , c, d] = local
251
+ const sx = node.flipX ? -1 : 1
252
+ const sy = a * d - b * c < 0 ? -sx : sx
253
+ let rotation = (Math.atan2(sy * c, sx * a) * 180) / Math.PI
254
+ if (Math.abs(rotation) < 1e-9) rotation = 0
255
+ const transform = { rotation, flipX: sx < 0, flipY: sy < 0 }
256
+ const origin = getNodeLocalMatrix({ ...node, ...transform }, { x: 0, y: 0 })
257
+ return { ...transform, x: local[2] - origin[2], y: local[5] - origin[5] }
258
+ }
259
+
260
+ export function isTranslationOnly(matrix: Mat3): boolean {
261
+ return matrix[0] === 1 && matrix[1] === 0 && matrix[3] === 0 && matrix[4] === 1
262
+ }
263
+
264
+ /**
265
+ * Maps a node's parent space into its container's: through the groups and booleans around it,
266
+ * which set no coordinate space of their own. Figma's plugin API reports `x`, `y`, and
267
+ * `relativeTransform` of their children in the container's space. The identity when the parent is
268
+ * not a group.
269
+ */
270
+ export function getParentToContainerMatrix(
271
+ node: SceneNode,
272
+ graph: Pick<SceneGraph, 'getNode'>
273
+ ): Mat3 {
274
+ let matrix = Matrix.identity()
275
+ for (
276
+ let parent = node.parentId ? graph.getNode(node.parentId) : undefined;
277
+ parent && FITTED_CONTAINER_TYPES.has(parent.type);
278
+ parent = parent.parentId ? graph.getNode(parent.parentId) : undefined
279
+ ) {
280
+ matrix = Matrix.multiply(getNodeLocalMatrix(parent), matrix)
281
+ }
282
+ return matrix
283
+ }
package/src/copy.ts CHANGED
@@ -28,8 +28,9 @@ import { cloneVectorNetwork } from './vector-network'
28
28
 
29
29
  // --- Individual copy functions ---
30
30
 
31
- export function copyFill(f: Fill): Fill {
32
- const copy: Fill = { ...f, color: { ...f.color } }
31
+ /** Generic over the paint shape so a stroke keeps its own fields while the paint deep-copies. */
32
+ export function copyFill<T extends Fill>(f: T): T {
33
+ const copy: T = { ...f, color: { ...f.color } }
33
34
  if (f.gradientStops) copy.gradientStops = f.gradientStops.map(copyGradientStop)
34
35
  if (f.gradientTransform) copy.gradientTransform = { ...f.gradientTransform }
35
36
  if (f.imageTransform) copy.imageTransform = { ...f.imageTransform }
@@ -39,7 +40,7 @@ export function copyFill(f: Fill): Fill {
39
40
  }
40
41
 
41
42
  export function copyStroke(s: Stroke): Stroke {
42
- const copy: Stroke = { ...s, color: { ...s.color } }
43
+ const copy = copyFill(s)
43
44
  if (s.dashPattern) {
44
45
  copy.dashPattern = [...s.dashPattern]
45
46
  }
@@ -200,7 +201,8 @@ function copyPropertyDefs(
200
201
  defs?.map((d) => ({
201
202
  ...d,
202
203
  variantOptions: d.variantOptions ? [...d.variantOptions] : undefined,
203
- preferredValues: d.preferredValues ? [...d.preferredValues] : undefined
204
+ preferredValues: d.preferredValues ? [...d.preferredValues] : undefined,
205
+ slotSettings: d.slotSettings ? { ...d.slotSettings } : undefined
204
206
  })) ?? []
205
207
  )
206
208
  }
@@ -240,6 +242,8 @@ export function cloneNodeProps(
240
242
  ...(componentId !== null ? { componentId } : {}),
241
243
  source: createDefaultSourceMetadata(),
242
244
  boundVariables: { ...src.boundVariables },
245
+ variableBindingScales: { ...src.variableBindingScales },
246
+ variableAssignmentScales: { ...src.variableAssignmentScales },
243
247
  variableModes: { ...src.variableModes },
244
248
  instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),
245
249
  componentPropertyAssignments: { ...src.componentPropertyAssignments },
@@ -251,6 +255,8 @@ export function cloneNodeProps(
251
255
  ...rest,
252
256
  ...(componentId !== null ? { componentId } : {}),
253
257
  boundVariables: { ...src.boundVariables },
258
+ variableBindingScales: { ...src.variableBindingScales },
259
+ variableAssignmentScales: { ...src.variableAssignmentScales },
254
260
  variableModes: { ...src.variableModes },
255
261
  instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),
256
262
  fills: copyOpt(src.fills, (value) => markCopySource(value, copyFills(value))),
@@ -266,6 +272,7 @@ export function cloneNodeProps(
266
272
  dashPattern: copyOpt(src.dashPattern, (a) => [...a]),
267
273
  fontVariations: copyOpt(src.fontVariations, (a) => a.map((v) => ({ ...v }))),
268
274
  fontFeatures: copyOpt(src.fontFeatures, (a) => a.map((v) => ({ ...v }))),
275
+ textParagraphs: copyOpt(src.textParagraphs, (a) => a.map((v) => ({ ...v }))),
269
276
  textDecorationFills: copyOpt(src.textDecorationFills, copyFills),
270
277
  fillGeometry: copyOpt(src.fillGeometry, copyGeometryPaths),
271
278
  strokeGeometry: copyOpt(src.strokeGeometry, copyGeometryPaths),
@@ -289,6 +296,7 @@ export function cloneNodeProps(
289
296
  : null,
290
297
  textPathData: src.textPathData ? structuredClone(src.textPathData) : null,
291
298
  textPathBox: src.textPathBox ? { ...src.textPathBox } : null,
292
- gridPosition: src.gridPosition ? { ...src.gridPosition } : null
299
+ gridPosition: src.gridPosition ? { ...src.gridPosition } : null,
300
+ targetAspectRatio: src.targetAspectRatio ? { ...src.targetAspectRatio } : null
293
301
  }
294
302
  }
@@ -0,0 +1,70 @@
1
+ import valueParser, { type FunctionNode, type Node } from 'postcss-value-parser'
2
+
3
+ import type { GridTrack } from '../types'
4
+ import { parseCSSNumber } from './values'
5
+
6
+ /** Bounds a `repeat()` count, which a typo could make huge. */
7
+ const MAX_REPEATED_TRACKS = 100
8
+
9
+ /** `auto`, and sizes a grid track cannot express, size to their content rather than to 0. */
10
+ function autoTrack(): GridTrack {
11
+ return { sizing: 'AUTO', value: 0 }
12
+ }
13
+
14
+ /** A function's arguments, split at its commas. */
15
+ function argumentsOf(node: FunctionNode): Node[][] {
16
+ const args: Node[][] = []
17
+ let current: Node[] = []
18
+ for (const child of node.nodes) {
19
+ if (child.type === 'div' && child.value === ',') {
20
+ args.push(current)
21
+ current = []
22
+ } else {
23
+ current.push(child)
24
+ }
25
+ }
26
+ args.push(current)
27
+ return args
28
+ }
29
+
30
+ function wordTrack(word: string): GridTrack {
31
+ const dimension = valueParser.unit(word)
32
+ if (dimension && dimension.unit.toLowerCase() === 'fr') {
33
+ return { sizing: 'FR', value: Number(dimension.number) || 1 }
34
+ }
35
+ const pixels = parseCSSNumber(word)
36
+ return pixels === null ? autoTrack() : { sizing: 'FIXED', value: pixels }
37
+ }
38
+
39
+ function functionTracks(node: FunctionNode): GridTrack[] {
40
+ const [first = [], second = [], ...rest] = argumentsOf(node)
41
+ switch (node.value.toLowerCase()) {
42
+ case 'repeat': {
43
+ const count = Number(first.find((child) => child.type === 'word')?.value)
44
+ // `auto-fill` and `auto-fit` depend on the container, which a track list cannot know.
45
+ if (!Number.isInteger(count) || count < 1) return [autoTrack()]
46
+ const tracks = tracksOf([second, ...rest].flat())
47
+ return Array.from({ length: Math.min(count, MAX_REPEATED_TRACKS) }, () =>
48
+ tracks.map((track) => ({ ...track }))
49
+ ).flat()
50
+ }
51
+ case 'minmax':
52
+ // The maximum decides how a track grows, as `minmax(0, 1fr)` is a 1fr column.
53
+ return tracksOf(second)
54
+ default:
55
+ return [autoTrack()]
56
+ }
57
+ }
58
+
59
+ function tracksOf(nodes: Node[]): GridTrack[] {
60
+ return nodes.flatMap((node) => {
61
+ if (node.type === 'word') return [wordTrack(node.value)]
62
+ if (node.type === 'function') return functionTracks(node)
63
+ return []
64
+ })
65
+ }
66
+
67
+ /** The tracks of a CSS track list, such as `repeat(3, minmax(0, 1fr)) 120px auto`. */
68
+ export function parseCSSGridTracks(value: string): GridTrack[] {
69
+ return tracksOf(valueParser(value).nodes)
70
+ }
@@ -0,0 +1,9 @@
1
+ export { parseCSSGridTracks } from './grid'
2
+ export {
3
+ parseCSSAlignItems,
4
+ parseCSSAlignSelf,
5
+ parseCSSFlexDirection,
6
+ parseCSSJustifyContent
7
+ } from './layout'
8
+ export { parseCSSShadows } from './shadows'
9
+ export { parseCSSColor, parseCSSNumber, splitCSSValue } from './values'