@open-pencil/scene-graph 0.17.0-beta.1 → 0.17.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 (236) hide show
  1. package/dist/arrow-caps.d.ts.map +1 -1
  2. package/dist/arrow-caps.js +2 -5
  3. package/dist/arrow-caps.js.map +1 -1
  4. package/dist/behaviours/index.d.ts +2 -2
  5. package/dist/behaviours/index.js +2 -2
  6. package/dist/behaviours/kinds.d.ts +11 -5
  7. package/dist/behaviours/kinds.d.ts.map +1 -1
  8. package/dist/behaviours/kinds.js +76 -75
  9. package/dist/behaviours/kinds.js.map +1 -1
  10. package/dist/behaviours/layers.d.ts.map +1 -1
  11. package/dist/behaviours/layers.js +3 -2
  12. package/dist/behaviours/layers.js.map +1 -1
  13. package/dist/behaviours/model.d.ts +7 -4
  14. package/dist/behaviours/model.d.ts.map +1 -1
  15. package/dist/behaviours/model.js +16 -9
  16. package/dist/behaviours/model.js.map +1 -1
  17. package/dist/behaviours/schema.d.ts +118 -4
  18. package/dist/behaviours/schema.d.ts.map +1 -1
  19. package/dist/behaviours/schema.js +18 -3
  20. package/dist/behaviours/schema.js.map +1 -1
  21. package/dist/behaviours/spec.d.ts.map +1 -1
  22. package/dist/behaviours/spec.js +3 -2
  23. package/dist/behaviours/spec.js.map +1 -1
  24. package/dist/bindings.js +9 -1
  25. package/dist/bindings.js.map +1 -1
  26. package/dist/checkpoint.d.ts +31 -2
  27. package/dist/checkpoint.d.ts.map +1 -1
  28. package/dist/checkpoint.js +176 -5
  29. package/dist/checkpoint.js.map +1 -1
  30. package/dist/components/index.d.ts +3 -3
  31. package/dist/components/index.js +3 -3
  32. package/dist/components/properties.d.ts +13 -1
  33. package/dist/components/properties.d.ts.map +1 -1
  34. package/dist/components/properties.js +58 -3
  35. package/dist/components/properties.js.map +1 -1
  36. package/dist/components/variants.d.ts +16 -10
  37. package/dist/components/variants.d.ts.map +1 -1
  38. package/dist/components/variants.js +39 -13
  39. package/dist/components/variants.js.map +1 -1
  40. package/dist/connectors/hit.d.ts.map +1 -1
  41. package/dist/connectors/hit.js +1 -7
  42. package/dist/connectors/hit.js.map +1 -1
  43. package/dist/connectors/pieces.d.ts.map +1 -1
  44. package/dist/connectors/pieces.js +2 -5
  45. package/dist/connectors/pieces.js.map +1 -1
  46. package/dist/copy.d.ts.map +1 -1
  47. package/dist/copy.js +9 -15
  48. package/dist/copy.js.map +1 -1
  49. package/dist/css/blend.d.ts +11 -0
  50. package/dist/css/blend.d.ts.map +1 -0
  51. package/dist/css/blend.js +30 -0
  52. package/dist/css/blend.js.map +1 -0
  53. package/dist/css/index.d.ts +2 -1
  54. package/dist/css/index.js +2 -1
  55. package/dist/cubic.d.ts +7 -0
  56. package/dist/cubic.d.ts.map +1 -0
  57. package/dist/cubic.js +17 -0
  58. package/dist/cubic.js.map +1 -0
  59. package/dist/export-format.d.ts +14 -1
  60. package/dist/export-format.d.ts.map +1 -1
  61. package/dist/export-format.js +26 -1
  62. package/dist/export-format.js.map +1 -1
  63. package/dist/fields/text.d.ts +2 -2
  64. package/dist/fields/text.d.ts.map +1 -1
  65. package/dist/fields/text.js +2 -1
  66. package/dist/fields/text.js.map +1 -1
  67. package/dist/figjam/index.d.ts +2 -2
  68. package/dist/figjam/index.js +2 -2
  69. package/dist/figjam/palette.d.ts +13 -2
  70. package/dist/figjam/palette.d.ts.map +1 -1
  71. package/dist/figjam/palette.js +30 -2
  72. package/dist/figjam/palette.js.map +1 -1
  73. package/dist/generated/index.d.ts +2 -2
  74. package/dist/generated/index.js +2 -2
  75. package/dist/generated/shape-with-text.d.ts +7 -2
  76. package/dist/generated/shape-with-text.d.ts.map +1 -1
  77. package/dist/generated/shape-with-text.js +20 -3
  78. package/dist/generated/shape-with-text.js.map +1 -1
  79. package/dist/geometry.d.ts +30 -46
  80. package/dist/geometry.d.ts.map +1 -1
  81. package/dist/geometry.js +63 -131
  82. package/dist/geometry.js.map +1 -1
  83. package/dist/graph.d.ts +1 -0
  84. package/dist/graph.d.ts.map +1 -1
  85. package/dist/graph.js +15 -3
  86. package/dist/graph.js.map +1 -1
  87. package/dist/guides.d.ts +3 -1
  88. package/dist/guides.d.ts.map +1 -1
  89. package/dist/guides.js +5 -1
  90. package/dist/guides.js.map +1 -1
  91. package/dist/hit-test.d.ts.map +1 -1
  92. package/dist/hit-test.js +42 -29
  93. package/dist/hit-test.js.map +1 -1
  94. package/dist/index.d.ts +2 -2
  95. package/dist/instances/fields.d.ts +2 -2
  96. package/dist/instances/fields.d.ts.map +1 -1
  97. package/dist/instances/fields.js +8 -0
  98. package/dist/instances/fields.js.map +1 -1
  99. package/dist/instances/index.d.ts +1 -3
  100. package/dist/instances/index.d.ts.map +1 -1
  101. package/dist/instances/index.js +36 -30
  102. package/dist/instances/index.js.map +1 -1
  103. package/dist/instances/kept-overrides.js +204 -0
  104. package/dist/instances/kept-overrides.js.map +1 -0
  105. package/dist/instances/main-component.d.ts +3 -1
  106. package/dist/instances/main-component.d.ts.map +1 -1
  107. package/dist/instances/main-component.js +10 -2
  108. package/dist/instances/main-component.js.map +1 -1
  109. package/dist/instances/overrides.d.ts +4 -1
  110. package/dist/instances/overrides.d.ts.map +1 -1
  111. package/dist/instances/overrides.js +18 -2
  112. package/dist/instances/overrides.js.map +1 -1
  113. package/dist/instances/swap.js +288 -0
  114. package/dist/instances/swap.js.map +1 -0
  115. package/dist/instances/sync.js +84 -32
  116. package/dist/instances/sync.js.map +1 -1
  117. package/dist/node-defaults.d.ts.map +1 -1
  118. package/dist/node-defaults.js +1 -1
  119. package/dist/node-defaults.js.map +1 -1
  120. package/dist/outline/flatten.d.ts +15 -0
  121. package/dist/outline/flatten.d.ts.map +1 -0
  122. package/dist/outline/flatten.js +189 -0
  123. package/dist/outline/flatten.js.map +1 -0
  124. package/dist/outline/heads.js +34 -0
  125. package/dist/outline/heads.js.map +1 -0
  126. package/dist/outline/hit.d.ts +21 -0
  127. package/dist/outline/hit.d.ts.map +1 -0
  128. package/dist/outline/hit.js +276 -0
  129. package/dist/outline/hit.js.map +1 -0
  130. package/dist/outline/index.d.ts +5 -0
  131. package/dist/outline/index.js +5 -0
  132. package/dist/outline/point.d.ts +16 -0
  133. package/dist/outline/point.d.ts.map +1 -0
  134. package/dist/outline/point.js +42 -0
  135. package/dist/outline/point.js.map +1 -0
  136. package/dist/outline/shapes.d.ts +35 -0
  137. package/dist/outline/shapes.d.ts.map +1 -0
  138. package/dist/outline/shapes.js +181 -0
  139. package/dist/outline/shapes.js.map +1 -0
  140. package/dist/plugin-data/fields.d.ts +2 -1
  141. package/dist/plugin-data/fields.d.ts.map +1 -1
  142. package/dist/plugin-data/fields.js +19 -4
  143. package/dist/plugin-data/fields.js.map +1 -1
  144. package/dist/scaling/tree.js +1 -1
  145. package/dist/shared-styles.d.ts +14 -1
  146. package/dist/shared-styles.d.ts.map +1 -1
  147. package/dist/shared-styles.js +63 -2
  148. package/dist/shared-styles.js.map +1 -1
  149. package/dist/slots/content.d.ts.map +1 -1
  150. package/dist/slots/content.js +2 -0
  151. package/dist/slots/content.js.map +1 -1
  152. package/dist/slots/frames.d.ts +2 -0
  153. package/dist/slots/frames.d.ts.map +1 -1
  154. package/dist/slots/frames.js +7 -2
  155. package/dist/slots/frames.js.map +1 -1
  156. package/dist/text/index.d.ts +2 -2
  157. package/dist/text/index.js +3 -3
  158. package/dist/text/lengths.d.ts +6 -1
  159. package/dist/text/lengths.d.ts.map +1 -1
  160. package/dist/text/lengths.js +10 -1
  161. package/dist/text/lengths.js.map +1 -1
  162. package/dist/text/overflow.d.ts +2 -2
  163. package/dist/text/overflow.js.map +1 -1
  164. package/dist/text/picture.d.ts +1 -2
  165. package/dist/text/picture.d.ts.map +1 -1
  166. package/dist/text/picture.js +1 -4
  167. package/dist/text/picture.js.map +1 -1
  168. package/dist/transfer/index.js +1 -1
  169. package/dist/transfer/nodes.js +9 -5
  170. package/dist/transfer/nodes.js.map +1 -1
  171. package/dist/types.d.ts +27 -1
  172. package/dist/types.d.ts.map +1 -1
  173. package/dist/types.js.map +1 -1
  174. package/dist/variables/bindings.d.ts +28 -5
  175. package/dist/variables/bindings.d.ts.map +1 -1
  176. package/dist/variables/bindings.js +104 -14
  177. package/dist/variables/bindings.js.map +1 -1
  178. package/dist/variables/fields.d.ts +19 -1
  179. package/dist/variables/fields.d.ts.map +1 -1
  180. package/dist/variables/fields.js +36 -1
  181. package/dist/variables/fields.js.map +1 -1
  182. package/dist/variables/index.d.ts +3 -3
  183. package/dist/variables/index.d.ts.map +1 -1
  184. package/dist/variables/index.js +23 -8
  185. package/dist/variables/index.js.map +1 -1
  186. package/package.json +7 -1
  187. package/src/arrow-caps.ts +2 -5
  188. package/src/behaviours/kinds.ts +51 -34
  189. package/src/behaviours/layers.ts +4 -2
  190. package/src/behaviours/model.ts +22 -11
  191. package/src/behaviours/schema.ts +20 -4
  192. package/src/behaviours/spec.ts +8 -2
  193. package/src/bindings.ts +11 -2
  194. package/src/checkpoint.ts +251 -4
  195. package/src/components/properties.ts +92 -2
  196. package/src/components/variants.ts +51 -30
  197. package/src/connectors/hit.ts +1 -12
  198. package/src/connectors/pieces.ts +2 -5
  199. package/src/copy.ts +9 -15
  200. package/src/css/blend.ts +27 -0
  201. package/src/css/index.ts +1 -0
  202. package/src/cubic.ts +14 -0
  203. package/src/export-format.ts +29 -0
  204. package/src/fields/text.ts +3 -1
  205. package/src/figjam/palette.ts +29 -1
  206. package/src/generated/shape-with-text.ts +28 -2
  207. package/src/geometry.ts +78 -198
  208. package/src/graph.ts +27 -3
  209. package/src/guides.ts +5 -0
  210. package/src/hit-test.ts +67 -54
  211. package/src/instances/fields.ts +8 -0
  212. package/src/instances/index.ts +58 -31
  213. package/src/instances/kept-overrides.ts +280 -0
  214. package/src/instances/main-component.ts +12 -0
  215. package/src/instances/overrides.ts +27 -1
  216. package/src/instances/swap.ts +451 -0
  217. package/src/instances/sync.ts +141 -42
  218. package/src/node-defaults.ts +2 -1
  219. package/src/outline/flatten.ts +190 -0
  220. package/src/outline/heads.ts +52 -0
  221. package/src/outline/hit.ts +369 -0
  222. package/src/outline/index.ts +4 -0
  223. package/src/outline/point.ts +59 -0
  224. package/src/outline/shapes.ts +207 -0
  225. package/src/plugin-data/fields.ts +15 -2
  226. package/src/shared-styles.ts +82 -1
  227. package/src/slots/content.ts +2 -0
  228. package/src/slots/frames.ts +9 -7
  229. package/src/text/lengths.ts +10 -0
  230. package/src/text/overflow.ts +2 -2
  231. package/src/text/picture.ts +0 -4
  232. package/src/transfer/nodes.ts +7 -5
  233. package/src/types.ts +28 -0
  234. package/src/variables/bindings.ts +125 -14
  235. package/src/variables/fields.ts +46 -1
  236. package/src/variables/index.ts +35 -2
@@ -0,0 +1,369 @@
1
+ import { compact } from 'es-toolkit'
2
+
3
+ import { arrowCapOverflow, isArrowCap, lineStrokeEnds } from '../arrow-caps'
4
+ import { getWorldMatrix } from '../coordinate'
5
+ import type { SceneGraph } from '../graph'
6
+ import Matrix from '../matrix'
7
+ import type { Vector } from '../primitives'
8
+ import type { Fill, SceneNode, Stroke } from '../types'
9
+ import { hitsArrowHeads } from './heads'
10
+ import { containsByWinding, distanceToLines, distanceToSegment } from './point'
11
+ import { shapeOutline, type OutlineArea, type ShapeOutline } from './shapes'
12
+
13
+ /** Points tested along each edge near the point for whether the filled result changes there. */
14
+ const EDGE_SAMPLES = 8
15
+
16
+ /** How far a flattened curve may stray from the shape when nothing tighter is asked for. */
17
+ const DEFAULT_TOLERANCE = 0.25
18
+
19
+ /**
20
+ * Whether a paint makes its layer clickable, as in Figma: a visible paint that shows something.
21
+ * A paint at 0% opacity, or a gradient whose stops are all transparent, does not; 1% does, and
22
+ * the layer's own opacity does not matter.
23
+ */
24
+ export function isHitPaint(paint: Fill): boolean {
25
+ if (!paint.visible || !(paint.opacity > 0)) return false
26
+ if (paint.gradientStops) return paint.gradientStops.some((stop) => stop.color.a > 0)
27
+ if (paint.type === 'SOLID') return paint.color.a > 0
28
+ return true
29
+ }
30
+
31
+ function insideArea(area: OutlineArea, point: Vector): boolean {
32
+ return containsByWinding(area.contours, area.windingRule, point)
33
+ }
34
+
35
+ /** A stroke's weight; with independent borders the widest side, for layers without per-side lines. */
36
+ function strokeWeightOf(node: SceneNode, stroke: Stroke): number {
37
+ if (node.independentStrokeWeights) {
38
+ return Math.max(
39
+ node.borderTopWeight,
40
+ node.borderRightWeight,
41
+ node.borderBottomWeight,
42
+ node.borderLeftWeight
43
+ )
44
+ }
45
+ return Number.isFinite(stroke.weight) ? stroke.weight : node.strokeWeight
46
+ }
47
+
48
+ /** The farthest a layer's clickable strokes reach outside its box, in its own units. */
49
+ export function strokeReach(node: SceneNode): number {
50
+ let reach = 0
51
+ for (const stroke of node.strokes) {
52
+ if (!isHitPaint(stroke)) continue
53
+ const weight = strokeWeightOf(node, stroke)
54
+ // A line's stroke lies a full weight to one side of it.
55
+ const side = node.type === 'LINE' || stroke.align === 'OUTSIDE'
56
+ reach = Math.max(reach, side ? weight : weight / 2)
57
+ }
58
+ // Arrow heads reach past the stroke.
59
+ const hitStrokes = node.strokes.filter(isHitPaint)
60
+ return Math.max(reach, arrowCapOverflow(hitStrokes, node.strokeCap, node.vectorNetwork))
61
+ }
62
+
63
+ function localPoint(graph: SceneGraph, node: SceneNode, px: number, py: number): Vector | null {
64
+ const inverse = Matrix.invert(getWorldMatrix(node, graph))
65
+ if (!inverse) return null
66
+ const [x, y] = Matrix.mapPoints(inverse, [px, py])
67
+ return { x, y }
68
+ }
69
+
70
+ interface Probe {
71
+ inside: boolean
72
+ /** The point in the layer's own coordinates, where its outline has one. */
73
+ local?: Vector
74
+ /**
75
+ * Whether the outline of the filled area passes within `radius` of the point, counting only
76
+ * edges where the filled result changes from one side to the other.
77
+ */
78
+ edgeWithin: (radius: number) => boolean
79
+ /** Each line a stroke follows, measured from the point in canvas units. */
80
+ lines: LineReach[]
81
+ /** Each line's own stroke weight, where sides differ. */
82
+ lineWeights?: number[]
83
+ /** Whether the layer has an area of its own; strokes on lines are always centred. */
84
+ closed: boolean
85
+ /** Strokes centre on the lines whatever their alignment. */
86
+ centered?: boolean
87
+ /** Strokes follow the filled area's outline, for a shape combined from operands. */
88
+ strokeOnEdge?: boolean
89
+ /** Whether the point lies on or within `radius` of the saved outline a stroke fills. */
90
+ strokeAreaWithin?: (radius: number) => boolean
91
+ }
92
+
93
+ /**
94
+ * Whether an outline made of `edges` passes within `radius` of the point, counting a stretch of
95
+ * edge only where `insideAt` changes from one side of it to the other: edges that cancel or that
96
+ * lie hidden inside or outside the result count for nothing.
97
+ */
98
+ function changingEdgeWithin(
99
+ edges: Vector[][],
100
+ insideAt: (x: number, y: number) => boolean | null,
101
+ point: Vector,
102
+ radius: number,
103
+ tolerance: number
104
+ ): boolean {
105
+ const step = Math.max(1e-6, Math.min(tolerance, radius / 4) / 4)
106
+ for (const edge of edges) {
107
+ for (let i = 0; i + 1 < edge.length; i++) {
108
+ const a = edge[i]
109
+ const b = edge[i + 1]
110
+ if (a.x === b.x && a.y === b.y) continue
111
+ if (distanceToSegment(point, a, b) > radius) continue
112
+ const dx = b.x - a.x
113
+ const dy = b.y - a.y
114
+ const length = Math.hypot(dx, dy)
115
+ const nx = -dy / length
116
+ const ny = dx / length
117
+ // The part of the edge inside the circle, sampled evenly.
118
+ const centre = ((point.x - a.x) * dx + (point.y - a.y) * dy) / (length * length)
119
+ const offset = Math.abs((point.x - a.x) * nx + (point.y - a.y) * ny)
120
+ const half = Math.sqrt(Math.max(0, radius * radius - offset * offset)) / length
121
+ const from = Math.max(0, centre - half)
122
+ const to = Math.min(1, centre + half)
123
+ for (let k = 0; k <= EDGE_SAMPLES; k++) {
124
+ const t = from + ((to - from) * k) / EDGE_SAMPLES
125
+ const qx = a.x + dx * t
126
+ const qy = a.y + dy * t
127
+ const left = insideAt(qx + nx * step, qy + ny * step)
128
+ const right = insideAt(qx - nx * step, qy - ny * step)
129
+ if (left !== null && right !== null && left !== right) return true
130
+ }
131
+ }
132
+ }
133
+ return false
134
+ }
135
+
136
+ /**
137
+ * How a point lies from a line: its distance, and past an open end how far beyond the end it is
138
+ * along the line and how far across it, for a flat cap that paints nothing past the end.
139
+ */
140
+ interface LineReach {
141
+ distance: number
142
+ beyond: number
143
+ across: number
144
+ }
145
+
146
+ function measureLine(
147
+ line: Vector[],
148
+ ends: [boolean, boolean] | undefined,
149
+ point: Vector
150
+ ): LineReach {
151
+ const reach: LineReach = { distance: distanceToLines([line], point), beyond: 0, across: 0 }
152
+ if (!ends || line.length < 2) return reach
153
+ // Past an open end, the point projects beyond the first or last segment.
154
+ const tips: Array<[boolean, Vector, Vector]> = [
155
+ [ends[0], line[0], line[1]],
156
+ [ends[1], line[line.length - 1], line[line.length - 2]]
157
+ ]
158
+ for (const [open, tip, next] of tips) {
159
+ if (!open) continue
160
+ const dx = tip.x - next.x
161
+ const dy = tip.y - next.y
162
+ const length = Math.hypot(dx, dy)
163
+ if (length === 0) continue
164
+ const along = ((point.x - tip.x) * dx + (point.y - tip.y) * dy) / length
165
+ if (along <= 0 || Math.hypot(point.x - tip.x, point.y - tip.y) > reach.distance + 1e-9) continue
166
+ reach.beyond = along
167
+ reach.across = Math.abs((point.x - tip.x) * dy - (point.y - tip.y) * dx) / length
168
+ }
169
+ return reach
170
+ }
171
+
172
+ function probeOutline(outline: ShapeOutline, point: Vector, tolerance: number): Probe {
173
+ const insideAt = (x: number, y: number) =>
174
+ outline.areas.some((area) => insideArea(area, { x, y }))
175
+ const edges = outline.areas.flatMap((area) => area.contours.map(closedLoop))
176
+ const { strokeAreas } = outline
177
+ return {
178
+ inside: insideAt(point.x, point.y),
179
+ local: point,
180
+ edgeWithin: (radius) => changingEdgeWithin(edges, insideAt, point, radius, tolerance),
181
+ lines: outline.lines.map((line, index) => measureLine(line, outline.lineEnds?.[index], point)),
182
+ lineWeights: outline.lineWeights,
183
+ closed: outline.areas.some((area) => area.contours.length > 0),
184
+ centered: outline.strokeCentered,
185
+ strokeAreaWithin: strokeAreas
186
+ ? (radius) =>
187
+ strokeAreas.some((area) => insideArea(area, point)) ||
188
+ changingEdgeWithin(
189
+ strokeAreas.flatMap((area) => area.contours.map(closedLoop)),
190
+ (x, y) => strokeAreas.some((area) => insideArea(area, { x, y })),
191
+ point,
192
+ radius,
193
+ tolerance
194
+ )
195
+ : undefined
196
+ }
197
+ }
198
+
199
+ function closedLoop(contour: Vector[]): Vector[] {
200
+ const first = contour.at(0)
201
+ return first ? [...contour, first] : contour
202
+ }
203
+
204
+ const BOOLEAN_COMBINE: Record<
205
+ NonNullable<SceneNode['booleanOperation']>,
206
+ (hits: boolean[]) => boolean
207
+ > = {
208
+ UNION: (hits) => hits.some(Boolean),
209
+ INTERSECT: (hits) => hits.length > 0 && hits.every(Boolean),
210
+ SUBTRACT: ([first = false, ...rest]) => first && !rest.some(Boolean),
211
+ EXCLUDE: (hits) => compact(hits).length % 2 === 1
212
+ }
213
+
214
+ /** The lines an operand draws its outline along, in canvas coordinates. */
215
+ function operandEdges(graph: SceneGraph, node: SceneNode, tolerance: number): Vector[][] {
216
+ if (node.type === 'BOOLEAN_OPERATION' && node.fillGeometry.length === 0) {
217
+ return graph
218
+ .getChildren(node.id)
219
+ .filter((child) => child.visible)
220
+ .flatMap((child) => operandEdges(graph, child, tolerance))
221
+ }
222
+ const outline =
223
+ node.type === 'BOOLEAN_OPERATION'
224
+ ? shapeOutline({ ...node, type: 'VECTOR', vectorNetwork: null }, tolerance)
225
+ : shapeOutline(node, tolerance)
226
+ if (!outline) return []
227
+ const world = getWorldMatrix(node, graph)
228
+ const local = [
229
+ ...outline.lines,
230
+ ...outline.areas.flatMap((area) => area.contours.map(closedLoop))
231
+ ]
232
+ return local.map((line) =>
233
+ line.map((point) => {
234
+ const [x, y] = Matrix.mapPoints(world, [point.x, point.y])
235
+ return { x, y }
236
+ })
237
+ )
238
+ }
239
+
240
+ /**
241
+ * A boolean operation without saved geometry, combined from its operands as it draws. Its outline
242
+ * runs along the operand edges where the combined result changes from one side to the other, so
243
+ * edges hidden inside or outside the result count for nothing. Each side is probed at most a
244
+ * quarter of a screen pixel out, so a result thinner than that, which draws no visible pixel, is
245
+ * not seen.
246
+ */
247
+ function probeBoolean(
248
+ graph: SceneGraph,
249
+ node: SceneNode,
250
+ px: number,
251
+ py: number,
252
+ tolerance: number
253
+ ): Probe | null {
254
+ const operands = graph.getChildren(node.id).filter((child) => child.visible)
255
+ if (operands.length === 0) return null
256
+ const combine = BOOLEAN_COMBINE[node.booleanOperation ?? 'UNION']
257
+ const insideAt = (x: number, y: number): boolean | null => {
258
+ const hits: boolean[] = []
259
+ for (const operand of operands) {
260
+ const probe = probeNode(graph, operand, x, y, tolerance)
261
+ if (!probe) return null
262
+ hits.push(probe.inside)
263
+ }
264
+ return combine(hits)
265
+ }
266
+ const inside = insideAt(px, py)
267
+ if (inside === null) return null
268
+ const point = { x: px, y: py }
269
+ const edges = operands.flatMap((operand) => operandEdges(graph, operand, tolerance))
270
+ return {
271
+ inside,
272
+ edgeWithin: (radius) => changingEdgeWithin(edges, insideAt, point, radius, tolerance),
273
+ lines: [],
274
+ closed: true,
275
+ strokeOnEdge: true
276
+ }
277
+ }
278
+
279
+ function probeNode(
280
+ graph: SceneGraph,
281
+ node: SceneNode,
282
+ px: number,
283
+ py: number,
284
+ tolerance: number
285
+ ): Probe | null {
286
+ if (node.type === 'BOOLEAN_OPERATION' && node.fillGeometry.length === 0) {
287
+ return probeBoolean(graph, node, px, py, tolerance)
288
+ }
289
+ const outline =
290
+ node.type === 'BOOLEAN_OPERATION'
291
+ ? shapeOutline({ ...node, type: 'VECTOR', vectorNetwork: null }, tolerance)
292
+ : shapeOutline(node, tolerance)
293
+ if (!outline) return null
294
+ const point = localPoint(graph, node, px, py)
295
+ return point ? probeOutline(outline, point, tolerance) : null
296
+ }
297
+
298
+ /** How far from a line a stroke's band reaches toward the point, beyond which it misses. */
299
+ function strokeReachAt(align: Stroke['align'], weight: number, inside: boolean): number {
300
+ if (align === 'INSIDE') return inside ? weight : 0
301
+ if (align === 'OUTSIDE') return inside ? 0 : weight
302
+ return weight / 2
303
+ }
304
+
305
+ function strokeHits(node: SceneNode, stroke: Stroke, probe: Probe, pad: number): boolean {
306
+ if (probe.strokeAreaWithin) return probe.strokeAreaWithin(pad)
307
+ const align = probe.closed && !probe.centered ? stroke.align : 'CENTER'
308
+ if (probe.strokeOnEdge) {
309
+ const weight = strokeWeightOf(node, stroke)
310
+ return probe.edgeWithin(strokeReachAt(align, weight, probe.inside) + pad)
311
+ }
312
+ // A flat cap ends the stroke at the line's end; round and square caps paint past it.
313
+ const cap = stroke.cap ?? node.strokeCap
314
+ const flatEnds = cap === 'NONE'
315
+ const reaches = (line: LineReach, band: number): boolean => {
316
+ if (flatEnds && line.beyond > 0) {
317
+ // Past a flat end, the distance to the painted band's square end.
318
+ return Math.hypot(line.beyond, Math.max(0, line.across - band)) <= pad
319
+ }
320
+ return line.distance <= band + pad
321
+ }
322
+ if (node.type === 'LINE' && probe.local) {
323
+ // Figma strokes a line a full weight to one side, along the path the renderer draws.
324
+ const weight = strokeWeightOf(node, stroke)
325
+ if (!(weight > 0)) return false
326
+ const { start, end } = lineStrokeEnds(node.width, node.height, weight, cap)
327
+ if (reaches(measureLine([start, end], [true, true], probe.local), weight / 2)) return true
328
+ if (!isArrowCap(cap)) return false
329
+ const still = { x: 0, y: 0 }
330
+ const shaft = {
331
+ vertices: [start, end],
332
+ segments: [{ start: 0, end: 1, tangentStart: still, tangentEnd: still }],
333
+ regions: []
334
+ }
335
+ return hitsArrowHeads(shaft, cap, weight, probe.local, pad)
336
+ }
337
+ const network = node.type === 'VECTOR' ? node.vectorNetwork : null
338
+ if (network && probe.local) {
339
+ const weight = strokeWeightOf(node, stroke)
340
+ if (weight > 0 && hitsArrowHeads(network, cap, weight, probe.local, pad)) return true
341
+ }
342
+ return probe.lines.some((line, index) => {
343
+ const weight = probe.lineWeights?.[index] ?? strokeWeightOf(node, stroke)
344
+ // A side with no weight paints no border.
345
+ if (!(weight > 0)) return false
346
+ return reaches(line, strokeReachAt(align, weight, probe.inside))
347
+ })
348
+ }
349
+
350
+ /**
351
+ * Whether a click at the canvas point lands on the shape, as in Figma: inside the area a
352
+ * clickable fill covers, or on the band a clickable stroke draws, either grown by `pad` canvas
353
+ * units. A shape whose paints show nothing is never hit. Null for a layer without an outline to
354
+ * test, which is hit by its box.
355
+ */
356
+ export function hitsShape(
357
+ graph: SceneGraph,
358
+ node: SceneNode,
359
+ px: number,
360
+ py: number,
361
+ pad = 0
362
+ ): boolean | null {
363
+ const tolerance = pad > 0 ? Math.min(DEFAULT_TOLERANCE, pad / 4) : DEFAULT_TOLERANCE
364
+ const probe = probeNode(graph, node, px, py, tolerance)
365
+ if (!probe) return null
366
+ const fills = node.fills.filter(isHitPaint)
367
+ if (fills.length > 0 && probe.closed && (probe.inside || probe.edgeWithin(pad))) return true
368
+ return node.strokes.some((stroke) => isHitPaint(stroke) && strokeHits(node, stroke, probe, pad))
369
+ }
@@ -0,0 +1,4 @@
1
+ export { hitsShape, isHitPaint, strokeReach } from './hit'
2
+ export { shapeOutline, type OutlineArea, type ShapeOutline } from './shapes'
3
+ export { blobContours, loopPoints, segmentPoints } from './flatten'
4
+ export { containsByWinding, distanceToLines, distanceToSegment, windingNumber } from './point'
@@ -0,0 +1,59 @@
1
+ import type { Vector } from '../primitives'
2
+ import type { WindingRule } from '../types'
3
+
4
+ /**
5
+ * The signed number of times closed contours wind around `point`, each closing back to its start
6
+ * as a path fill closes it.
7
+ */
8
+ export function windingNumber(contours: Iterable<Vector[]>, point: Vector): number {
9
+ let winding = 0
10
+ for (const contour of contours) {
11
+ for (let i = 0; i < contour.length; i++) {
12
+ const a = contour[i]
13
+ const b = contour[(i + 1) % contour.length]
14
+ // Which side of the edge a→b the point is on, positive when left.
15
+ const side = (b.x - a.x) * (point.y - a.y) - (point.x - a.x) * (b.y - a.y)
16
+ if (a.y <= point.y) {
17
+ if (b.y > point.y && side > 0) winding++
18
+ } else if (b.y <= point.y && side < 0) {
19
+ winding--
20
+ }
21
+ }
22
+ }
23
+ return winding
24
+ }
25
+
26
+ /** Whether contours filled by `windingRule` cover the point. */
27
+ export function containsByWinding(
28
+ contours: Iterable<Vector[]>,
29
+ windingRule: WindingRule,
30
+ point: Vector
31
+ ): boolean {
32
+ const winding = windingNumber(contours, point)
33
+ return windingRule === 'EVENODD' ? winding % 2 !== 0 : winding !== 0
34
+ }
35
+
36
+ export function distanceToSegment(p: Vector, a: Vector, b: Vector): number {
37
+ const dx = b.x - a.x
38
+ const dy = b.y - a.y
39
+ const lengthSquared = dx * dx + dy * dy
40
+ const t =
41
+ lengthSquared === 0
42
+ ? 0
43
+ : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSquared))
44
+ return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy))
45
+ }
46
+
47
+ /** The distance from the point to the nearest of the polylines. */
48
+ export function distanceToLines(lines: readonly Vector[][], point: Vector): number {
49
+ let nearest = Infinity
50
+ for (const line of lines) {
51
+ if (line.length === 1) {
52
+ nearest = Math.min(nearest, Math.hypot(point.x - line[0].x, point.y - line[0].y))
53
+ }
54
+ for (let i = 0; i + 1 < line.length; i++) {
55
+ nearest = Math.min(nearest, distanceToSegment(point, line[i], line[i + 1]))
56
+ }
57
+ }
58
+ return nearest
59
+ }
@@ -0,0 +1,207 @@
1
+ import { polygonOutline } from '../polygon'
2
+ import type { Vector } from '../primitives'
3
+ import type { SceneNode, WindingRule } from '../types'
4
+ import {
5
+ arcPoints,
6
+ blobContours,
7
+ commandContours,
8
+ loopPoints,
9
+ segmentPoints,
10
+ segmentRuns
11
+ } from './flatten'
12
+
13
+ /** Contours filled together under one winding rule. */
14
+ export interface OutlineArea {
15
+ windingRule: WindingRule
16
+ contours: Vector[][]
17
+ }
18
+
19
+ /**
20
+ * A shape's geometry in its own coordinates, curves flattened: the areas its fills cover and the
21
+ * lines its strokes follow, closed contours ending where they began.
22
+ */
23
+ export interface ShapeOutline {
24
+ areas: OutlineArea[]
25
+ lines: Vector[][]
26
+ /** Each line's own stroke weight, where sides differ, as a rectangle's independent borders. */
27
+ lineWeights?: number[]
28
+ /**
29
+ * Strokes centre on the lines whatever their alignment, as on a network without regions that is
30
+ * open or has no saved stroke geometry.
31
+ */
32
+ strokeCentered?: boolean
33
+ /** For each line, whether its start and its end are open ends, where a stroke's cap is drawn. */
34
+ lineEnds?: Array<[boolean, boolean]>
35
+ /** The saved outline a stroke fills, for a shape whose stroke has no lines to follow. */
36
+ strokeAreas?: OutlineArea[]
37
+ }
38
+
39
+ function closed(contour: Vector[]): Vector[] {
40
+ const first = contour.at(0)
41
+ const last = contour.at(-1)
42
+ if (!first || !last || (first.x === last.x && first.y === last.y)) return contour
43
+ return [...contour, first]
44
+ }
45
+
46
+ function fromContours(contours: Vector[][], windingRule: WindingRule = 'NONZERO'): ShapeOutline {
47
+ return { areas: [{ windingRule, contours }], lines: contours.map(closed) }
48
+ }
49
+
50
+ function cornerRadii(node: SceneNode): [number, number, number, number] {
51
+ const radii: [number, number, number, number] = node.independentCorners
52
+ ? [node.topLeftRadius, node.topRightRadius, node.bottomRightRadius, node.bottomLeftRadius]
53
+ : [node.cornerRadius, node.cornerRadius, node.cornerRadius, node.cornerRadius]
54
+ const limit = Math.min(node.width, node.height) / 2
55
+ return radii.map((radius) => Math.max(0, Math.min(radius, limit))) as typeof radii
56
+ }
57
+
58
+ function rectangleContour(node: SceneNode, tolerance: number): Vector[] {
59
+ const { width: w, height: h } = node
60
+ const [tl, tr, br, bl] = cornerRadii(node)
61
+ const corner = (cx: number, cy: number, r: number, from: number): Vector[] =>
62
+ r > 0 ? arcPoints(cx, cy, r, r, from, from + Math.PI / 2, tolerance) : [{ x: cx, y: cy }]
63
+ return [
64
+ ...corner(w - tr, tr, tr, -Math.PI / 2),
65
+ ...corner(w - br, h - br, br, 0),
66
+ ...corner(bl, h - bl, bl, Math.PI / 2),
67
+ ...corner(tl, tl, tl, Math.PI)
68
+ ]
69
+ }
70
+
71
+ /**
72
+ * A rectangle's four sides with the weight each draws its border at: top, right, bottom, left.
73
+ * Each side runs from the middle of one rounded corner to the middle of the next, as its border
74
+ * is drawn round them.
75
+ */
76
+ function rectangleSides(
77
+ node: SceneNode,
78
+ tolerance: number
79
+ ): Pick<ShapeOutline, 'lines' | 'lineWeights'> {
80
+ const { width: w, height: h } = node
81
+ const [tl, tr, br, bl] = cornerRadii(node)
82
+ const quarter = Math.PI / 4
83
+ const arc = (cx: number, cy: number, r: number, from: number): Vector[] =>
84
+ r > 0 ? arcPoints(cx, cy, r, r, from, from + quarter, tolerance) : [{ x: cx, y: cy }]
85
+ return {
86
+ lines: [
87
+ [...arc(tl, tl, tl, 5 * quarter), ...arc(w - tr, tr, tr, -2 * quarter)],
88
+ [...arc(w - tr, tr, tr, -quarter), ...arc(w - br, h - br, br, 0)],
89
+ [...arc(w - br, h - br, br, quarter), ...arc(bl, h - bl, bl, 2 * quarter)],
90
+ [...arc(bl, h - bl, bl, 3 * quarter), ...arc(tl, tl, tl, 4 * quarter)]
91
+ ],
92
+ lineWeights: [
93
+ node.borderTopWeight,
94
+ node.borderRightWeight,
95
+ node.borderBottomWeight,
96
+ node.borderLeftWeight
97
+ ]
98
+ }
99
+ }
100
+
101
+ const FULL_TURN = Math.PI * 2
102
+
103
+ function ellipseContours(node: SceneNode, tolerance: number): Vector[][] {
104
+ const rx = node.width / 2
105
+ const ry = node.height / 2
106
+ const arc = node.arcData
107
+ const start = arc?.startingAngle ?? 0
108
+ const end = arc?.endingAngle ?? FULL_TURN
109
+ const inner = arc?.innerRadius ?? 0
110
+ const whole = Math.abs(end - start) >= FULL_TURN - 1e-6
111
+ const outer = arcPoints(rx, ry, rx, ry, start, whole ? start + FULL_TURN : end, tolerance)
112
+ if (inner <= 0) return [whole ? outer : [{ x: rx, y: ry }, ...outer]]
113
+ const hole = arcPoints(
114
+ rx,
115
+ ry,
116
+ rx * inner,
117
+ ry * inner,
118
+ whole ? start + FULL_TURN : end,
119
+ start,
120
+ tolerance
121
+ )
122
+ // A whole ring is two loops wound opposite ways; a part ring is one outline across its ends.
123
+ return whole ? [outer, hole] : [[...outer, ...hole]]
124
+ }
125
+
126
+ function vectorOutline(node: SceneNode, tolerance: number): ShapeOutline | null {
127
+ const network = node.vectorNetwork
128
+ const geometry = node.fillGeometry.map((path) => ({
129
+ windingRule: path.windingRule,
130
+ contours: path.commandsBlob.length > 0 ? blobContours(path.commandsBlob, tolerance) : []
131
+ }))
132
+ if (!network) {
133
+ if (geometry.length === 0 && node.strokeGeometry.length === 0) return null
134
+ // Without a network the renderer fills the saved stroke geometry, or draws no stroke.
135
+ const strokeAreas = node.strokeGeometry.map((path) => ({
136
+ windingRule: path.windingRule,
137
+ contours: path.commandsBlob.length > 0 ? blobContours(path.commandsBlob, tolerance) : []
138
+ }))
139
+ return { areas: geometry, lines: [], strokeAreas }
140
+ }
141
+ // A vertex on one segment only is an open end.
142
+ const degree = new Map<number, number>()
143
+ for (const segment of network.segments) {
144
+ degree.set(segment.start, (degree.get(segment.start) ?? 0) + 1)
145
+ degree.set(segment.end, (degree.get(segment.end) ?? 0) + 1)
146
+ }
147
+ const lines: Vector[][] = []
148
+ const lineEnds: Array<[boolean, boolean]> = []
149
+ for (const [index, segment] of network.segments.entries()) {
150
+ const points = segmentPoints(network, index, tolerance)
151
+ if (!points) continue
152
+ lines.push(points)
153
+ lineEnds.push([degree.get(segment.start) === 1, degree.get(segment.end) === 1])
154
+ }
155
+ // Without regions the stroke draws centred on each segment, unless a closed network carries
156
+ // saved stroke geometry, which the renderer draws with its alignment.
157
+ const open = lineEnds.some(([start, end]) => start || end)
158
+ const strokeCentered = network.regions.length === 0 && (open || node.strokeGeometry.length === 0)
159
+ if (geometry.length > 0) return { areas: geometry, lines, lineEnds, strokeCentered }
160
+ const areas =
161
+ network.regions.length > 0
162
+ ? network.regions.map((region) => ({
163
+ windingRule: region.windingRule,
164
+ contours: region.loops.map((loop) => loopPoints(network, loop, tolerance))
165
+ }))
166
+ : // Without regions a fill closes each run of segments, as a path fill does.
167
+ [{ windingRule: 'NONZERO' as const, contours: segmentRuns(network, tolerance) }]
168
+ return { areas, lines, lineEnds, strokeCentered }
169
+ }
170
+
171
+ /**
172
+ * The outline a click is tested against, in the node's own coordinates, with curves within
173
+ * `tolerance` of the shape; null for layers tested by their box, such as text.
174
+ */
175
+ export function shapeOutline(node: SceneNode, tolerance: number): ShapeOutline | null {
176
+ switch (node.type) {
177
+ case 'RECTANGLE':
178
+ case 'ROUNDED_RECTANGLE': {
179
+ const outline = fromContours([rectangleContour(node, tolerance)])
180
+ return node.independentStrokeWeights
181
+ ? { ...outline, ...rectangleSides(node, tolerance) }
182
+ : outline
183
+ }
184
+ case 'ELLIPSE': {
185
+ if (node.fillGeometry.length > 0) return vectorOutline(node, tolerance)
186
+ return fromContours(ellipseContours(node, tolerance))
187
+ }
188
+ case 'POLYGON':
189
+ case 'STAR':
190
+ return fromContours(commandContours(polygonOutline(node), tolerance))
191
+ case 'LINE':
192
+ return {
193
+ areas: [],
194
+ lines: [
195
+ [
196
+ { x: 0, y: 0 },
197
+ { x: node.width, y: node.height }
198
+ ]
199
+ ],
200
+ lineEnds: [[true, true]]
201
+ }
202
+ case 'VECTOR':
203
+ return vectorOutline(node, tolerance)
204
+ default:
205
+ return null
206
+ }
207
+ }
@@ -60,10 +60,23 @@ const exportSettingsSchema: v.GenericSchema<unknown, ExportSetting[]> = v.array(
60
60
  v.pipe(
61
61
  v.object({
62
62
  scale: v.pipe(v.number(), v.finite()),
63
- format: v.custom<ExportFormatId>(isExportFormatId)
63
+ format: v.custom<ExportFormatId>(isExportFormatId),
64
+ suffix: v.optional(v.string()),
65
+ size: v.optional(
66
+ v.object({
67
+ type: v.picklist(['WIDTH', 'HEIGHT']),
68
+ value: v.pipe(v.number(), v.finite())
69
+ })
70
+ ),
71
+ contentsOnly: v.optional(v.boolean()),
72
+ useAbsoluteBounds: v.optional(v.boolean()),
73
+ colorProfile: v.optional(v.picklist(['DOCUMENT', 'SRGB', 'DISPLAY_P3_V4'])),
74
+ svgOutlineText: v.optional(v.boolean()),
75
+ svgIdAttribute: v.optional(v.boolean()),
76
+ svgSimplifyStroke: v.optional(v.boolean())
64
77
  }),
65
78
  // Clamp at the file boundary: imported plugin data may carry a scale the UI never produces.
66
- v.transform(({ scale, format }) => ({ scale: clampExportScale(scale), format }))
79
+ v.transform((setting) => ({ ...setting, scale: clampExportScale(setting.scale) }))
67
80
  )
68
81
  )
69
82