@open-pencil/scene-graph 0.17.0-beta.5 → 0.17.0-beta.6

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 (151) hide show
  1. package/dist/comments/schema.d.ts.map +1 -1
  2. package/dist/comments/schema.js +1 -0
  3. package/dist/comments/schema.js.map +1 -1
  4. package/dist/comments/threads.d.ts +2 -0
  5. package/dist/comments/threads.d.ts.map +1 -1
  6. package/dist/comments/threads.js +11 -5
  7. package/dist/comments/threads.js.map +1 -1
  8. package/dist/components/properties.d.ts.map +1 -1
  9. package/dist/components/properties.js +1 -1
  10. package/dist/components/properties.js.map +1 -1
  11. package/dist/constants.d.ts +12 -2
  12. package/dist/constants.d.ts.map +1 -1
  13. package/dist/constants.js +42 -1
  14. package/dist/constants.js.map +1 -1
  15. package/dist/copy.d.ts.map +1 -1
  16. package/dist/copy.js +2 -0
  17. package/dist/copy.js.map +1 -1
  18. package/dist/css/grid.d.ts.map +1 -1
  19. package/dist/css/grid.js +27 -3
  20. package/dist/css/grid.js.map +1 -1
  21. package/dist/css/index.d.ts +3 -3
  22. package/dist/css/index.js +3 -3
  23. package/dist/css/layout.d.ts +13 -1
  24. package/dist/css/layout.d.ts.map +1 -1
  25. package/dist/css/layout.js +26 -1
  26. package/dist/css/layout.js.map +1 -1
  27. package/dist/css/values.d.ts +18 -1
  28. package/dist/css/values.d.ts.map +1 -1
  29. package/dist/css/values.js +39 -1
  30. package/dist/css/values.js.map +1 -1
  31. package/dist/geometry.d.ts +6 -6
  32. package/dist/geometry.d.ts.map +1 -1
  33. package/dist/geometry.js +4 -20
  34. package/dist/geometry.js.map +1 -1
  35. package/dist/graph.d.ts +5 -2
  36. package/dist/graph.d.ts.map +1 -1
  37. package/dist/graph.js +16 -6
  38. package/dist/graph.js.map +1 -1
  39. package/dist/icons/glyph.d.ts.map +1 -1
  40. package/dist/icons/glyph.js +1 -1
  41. package/dist/icons/glyph.js.map +1 -1
  42. package/dist/ids.js +1 -1
  43. package/dist/ids.js.map +1 -1
  44. package/dist/index.d.ts +2 -2
  45. package/dist/instances/index.d.ts +6 -1
  46. package/dist/instances/index.d.ts.map +1 -1
  47. package/dist/instances/index.js +20 -8
  48. package/dist/instances/index.js.map +1 -1
  49. package/dist/instances/swap.js +1 -1
  50. package/dist/instances/swap.js.map +1 -1
  51. package/dist/instances/sync.js +25 -1
  52. package/dist/instances/sync.js.map +1 -1
  53. package/dist/layout/index.d.ts +2 -1
  54. package/dist/layout/index.js +2 -1
  55. package/dist/layout/strokes.d.ts +10 -0
  56. package/dist/layout/strokes.d.ts.map +1 -0
  57. package/dist/layout/strokes.js +30 -0
  58. package/dist/layout/strokes.js.map +1 -0
  59. package/dist/node-defaults.d.ts.map +1 -1
  60. package/dist/node-defaults.js +49 -37
  61. package/dist/node-defaults.js.map +1 -1
  62. package/dist/outline/flatten.d.ts.map +1 -1
  63. package/dist/outline/flatten.js +2 -2
  64. package/dist/outline/flatten.js.map +1 -1
  65. package/dist/parse-path.d.ts +4 -1
  66. package/dist/parse-path.d.ts.map +1 -1
  67. package/dist/parse-path.js +15 -1
  68. package/dist/parse-path.js.map +1 -1
  69. package/dist/paths/index.d.ts +2 -2
  70. package/dist/paths/index.js +2 -2
  71. package/dist/paths/network.d.ts +26 -6
  72. package/dist/paths/network.d.ts.map +1 -1
  73. package/dist/paths/network.js +79 -13
  74. package/dist/paths/network.js.map +1 -1
  75. package/dist/paths/smooth-corners.d.ts.map +1 -1
  76. package/dist/paths/smooth-corners.js +1 -1
  77. package/dist/paths/smooth-corners.js.map +1 -1
  78. package/dist/primitives/index.d.ts +1 -7
  79. package/dist/primitives/index.d.ts.map +1 -1
  80. package/dist/shaders/model.d.ts.map +1 -1
  81. package/dist/shaders/model.js +1 -1
  82. package/dist/shaders/model.js.map +1 -1
  83. package/dist/shared-styles.d.ts.map +1 -1
  84. package/dist/shared-styles.js +2 -9
  85. package/dist/shared-styles.js.map +1 -1
  86. package/dist/strokes.d.ts +39 -0
  87. package/dist/strokes.d.ts.map +1 -0
  88. package/dist/strokes.js +104 -0
  89. package/dist/strokes.js.map +1 -0
  90. package/dist/text/index.d.ts +2 -1
  91. package/dist/text/index.js +2 -1
  92. package/dist/text/runs.d.ts +29 -0
  93. package/dist/text/runs.d.ts.map +1 -0
  94. package/dist/text/runs.js +72 -0
  95. package/dist/text/runs.js.map +1 -0
  96. package/dist/transfer/dependencies.d.ts.map +1 -1
  97. package/dist/transfer/dependencies.js +1 -1
  98. package/dist/transfer/dependencies.js.map +1 -1
  99. package/dist/types.d.ts +35 -2
  100. package/dist/types.d.ts.map +1 -1
  101. package/dist/types.js.map +1 -1
  102. package/dist/variables/resolution.d.ts.map +1 -1
  103. package/dist/variables/resolution.js +1 -1
  104. package/dist/variables/resolution.js.map +1 -1
  105. package/dist/vector-network.d.ts.map +1 -1
  106. package/dist/vector-network.js +2 -4
  107. package/dist/vector-network.js.map +1 -1
  108. package/package.json +10 -13
  109. package/src/comments/schema.ts +1 -0
  110. package/src/comments/threads.ts +13 -5
  111. package/src/components/properties.ts +2 -1
  112. package/src/constants.ts +25 -1
  113. package/src/copy.ts +2 -0
  114. package/src/css/grid.ts +31 -3
  115. package/src/css/index.ts +13 -2
  116. package/src/css/layout.ts +36 -0
  117. package/src/css/values.ts +49 -0
  118. package/src/geometry.ts +9 -27
  119. package/src/graph.ts +13 -6
  120. package/src/icons/glyph.ts +2 -1
  121. package/src/ids.ts +1 -1
  122. package/src/instances/index.ts +24 -9
  123. package/src/instances/swap.ts +2 -1
  124. package/src/instances/sync.ts +41 -0
  125. package/src/layout/index.ts +1 -0
  126. package/src/layout/strokes.ts +23 -0
  127. package/src/node-defaults.ts +48 -33
  128. package/src/outline/flatten.ts +2 -1
  129. package/src/parse-path.ts +14 -0
  130. package/src/paths/network.ts +90 -13
  131. package/src/paths/smooth-corners.ts +2 -1
  132. package/src/primitives/index.ts +0 -5
  133. package/src/shaders/model.ts +2 -1
  134. package/src/shared-styles.ts +3 -4
  135. package/src/strokes.ts +121 -0
  136. package/src/text/index.ts +1 -0
  137. package/src/text/runs.ts +80 -0
  138. package/src/transfer/dependencies.ts +2 -1
  139. package/src/types.ts +37 -0
  140. package/src/variables/resolution.ts +2 -1
  141. package/src/vector-network.ts +2 -4
  142. package/dist/arrays.d.ts +0 -17
  143. package/dist/arrays.d.ts.map +0 -1
  144. package/dist/arrays.js +0 -38
  145. package/dist/arrays.js.map +0 -1
  146. package/dist/random.d.ts +0 -7
  147. package/dist/random.d.ts.map +0 -1
  148. package/dist/random.js +0 -25
  149. package/dist/random.js.map +0 -1
  150. package/src/arrays.ts +0 -37
  151. package/src/random.ts +0 -28
@@ -52,6 +52,21 @@ export function newStrokeGeometry(
52
52
  return { weight: first?.weight ?? node.strokeWeight, align: first?.align ?? node.strokeAlign }
53
53
  }
54
54
 
55
+ /** A caller's list, or a fresh empty one: a list default belongs to the one layer it was made for. */
56
+ function ownList<T>(given: T[] | undefined): T[] {
57
+ return given ?? []
58
+ }
59
+
60
+ /** A caller's record, or a fresh empty one, for the same reason. */
61
+ function ownRecord<V>(given: Record<string, V> | undefined): Record<string, V> {
62
+ return given ?? {}
63
+ }
64
+
65
+ /** A new layer's fills: black on text, none elsewhere. */
66
+ function defaultFills(type: NodeType): SceneNode['fills'] {
67
+ return type === 'TEXT' ? [{ type: 'SOLID', color: BLACK, opacity: 1, visible: true }] : []
68
+ }
69
+
55
70
  export function createDefaultNode(
56
71
  generateId: () => string,
57
72
  type: NodeType,
@@ -60,25 +75,25 @@ export function createDefaultNode(
60
75
  // A literal ending in a spread is built one field at a time, and V8 keeps an object given this
61
76
  // many fields that way in dictionary mode, about 3 KB more per layer; a spread copy of a
62
77
  // finished literal keeps fast fields, in JavaScriptCore as well.
78
+ // Imports supply most lists and records, so a default is made only where the caller gives none.
63
79
  const defaults = {
64
80
  id: generateId(),
65
81
  type,
66
82
  name: type.charAt(0) + type.slice(1).toLowerCase(),
67
83
  parentId: null,
68
- childIds: [],
84
+ childIds: ownList(overrides.childIds),
69
85
  x: 0,
70
86
  y: 0,
71
87
  width: 100,
72
88
  height: 100,
73
89
  rotation: 0,
74
- source: createDefaultSourceMetadata(),
90
+ source: overrides.source ?? createDefaultSourceMetadata(),
75
91
  derivedLayout: null,
76
- fills:
77
- type === 'TEXT' ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }] : [],
78
- strokes: [],
79
- effects: [],
80
- layoutGrids: [],
81
- guides: [],
92
+ fills: overrides.fills ?? defaultFills(type),
93
+ strokes: ownList(overrides.strokes),
94
+ effects: ownList(overrides.effects),
95
+ layoutGrids: ownList(overrides.layoutGrids),
96
+ guides: ownList(overrides.guides),
82
97
  fillStyleId: null,
83
98
  strokeStyleId: null,
84
99
  textStyleId: null,
@@ -127,8 +142,8 @@ export function createDefaultNode(
127
142
  layoutAlignSelf: 'AUTO',
128
143
  vectorNetwork: null,
129
144
  handleMirroring: 'NONE',
130
- fillGeometry: [],
131
- strokeGeometry: [],
145
+ fillGeometry: ownList(overrides.fillGeometry),
146
+ strokeGeometry: ownList(overrides.strokeGeometry),
132
147
  arcData: null,
133
148
  textAlignVertical: 'TOP',
134
149
  textAutoResize: 'NONE',
@@ -136,24 +151,24 @@ export function createDefaultNode(
136
151
  textDecoration: 'NONE',
137
152
  textDecorationStyle: 'SOLID',
138
153
  textDecorationThickness: null,
139
- textDecorationFills: [],
154
+ textDecorationFills: ownList(overrides.textDecorationFills),
140
155
  textDecorationSkipInk: true,
141
156
  textUnderlineOffset: null,
142
157
  maxLines: null,
143
- textParagraphs: [],
158
+ textParagraphs: ownList(overrides.textParagraphs),
144
159
  listSpacing: 0,
145
160
  paragraphSpacing: 0,
146
161
  paragraphIndent: 0,
147
162
  hangingList: false,
148
- styleRuns: [],
149
- fontVariations: [],
163
+ styleRuns: ownList(overrides.styleRuns),
164
+ fontVariations: ownList(overrides.fontVariations),
150
165
  opticalSizeFromFontSize: true,
151
- fontFeatures: [],
166
+ fontFeatures: ownList(overrides.fontFeatures),
152
167
  horizontalConstraint: 'MIN',
153
168
  verticalConstraint: 'MIN',
154
169
  strokeCap: 'NONE',
155
170
  strokeJoin: 'MITER',
156
- dashPattern: [],
171
+ dashPattern: ownList(overrides.dashPattern),
157
172
  borderTopWeight: 0,
158
173
  borderRightWeight: 0,
159
174
  borderBottomWeight: 0,
@@ -172,14 +187,14 @@ export function createDefaultNode(
172
187
  connectorLineType: 'ELBOWED',
173
188
  connectorStartCap: 'ROUND',
174
189
  connectorEndCap: 'ARROW_LINES',
175
- connectorControlPoints: [],
190
+ connectorControlPoints: ownList(overrides.connectorControlPoints),
176
191
  connectorCurveHandles: null,
177
192
  connectorLabelPosition: null,
178
193
  isMask: false,
179
194
  maskType: 'ALPHA',
180
195
  maskIsOutline: false,
181
- gridTemplateColumns: [],
182
- gridTemplateRows: [],
196
+ gridTemplateColumns: ownList(overrides.gridTemplateColumns),
197
+ gridTemplateRows: ownList(overrides.gridTemplateRows),
183
198
  gridColumnGap: 0,
184
199
  gridRowGap: 0,
185
200
  gridPosition: null,
@@ -196,11 +211,11 @@ export function createDefaultNode(
196
211
  shapeUserHeight: 0,
197
212
  shapeTruncates: false,
198
213
  componentId: null,
199
- instanceOverrides: createInstanceOverrideState(),
200
- componentPropertyDefinitions: [],
201
- componentPropertyReferences: [],
202
- componentPropertyAssignments: {},
203
- componentPropertyValues: {},
214
+ instanceOverrides: overrides.instanceOverrides ?? createInstanceOverrideState(),
215
+ componentPropertyDefinitions: ownList(overrides.componentPropertyDefinitions),
216
+ componentPropertyReferences: ownList(overrides.componentPropertyReferences),
217
+ componentPropertyAssignments: ownRecord(overrides.componentPropertyAssignments),
218
+ componentPropertyValues: ownRecord(overrides.componentPropertyValues),
204
219
  componentKey: null,
205
220
  sourceLibraryKey: null,
206
221
  publishId: null,
@@ -213,17 +228,17 @@ export function createDefaultNode(
213
228
  isSymbolPublishable: false,
214
229
  isExposedInstance: false,
215
230
  symbolDescription: '',
216
- symbolLinks: [],
217
- variantPropSpecs: [],
218
- boundVariables: {},
219
- variableBindingScales: {},
220
- variableAssignmentScales: {},
231
+ symbolLinks: ownList(overrides.symbolLinks),
232
+ variantPropSpecs: ownList(overrides.variantPropSpecs),
233
+ boundVariables: ownRecord(overrides.boundVariables),
234
+ variableBindingScales: ownRecord(overrides.variableBindingScales),
235
+ variableAssignmentScales: ownRecord(overrides.variableAssignmentScales),
221
236
  componentScale: 1,
222
- variableModes: {},
223
- exportSettings: [],
237
+ variableModes: ownRecord(overrides.variableModes),
238
+ exportSettings: ownList(overrides.exportSettings),
224
239
  status: null,
225
- pluginData: [],
226
- pluginRelaunchData: [],
240
+ pluginData: ownList(overrides.pluginData),
241
+ pluginRelaunchData: ownList(overrides.pluginRelaunchData),
227
242
  internalOnly: false,
228
243
  flipX: false,
229
244
  flipY: false,
@@ -1,4 +1,5 @@
1
- import { appendAll } from '../arrays'
1
+ import { appendAll } from '@open-pencil/std/arrays'
2
+
2
3
  import { cubicPoint } from '../cubic'
3
4
  import { GeometryCommand, readGeometryBlob } from '../geometry'
4
5
  import { buildChains } from '../paths/network'
package/src/parse-path.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import svgpath from 'svgpath'
2
2
 
3
+ import type { Rect } from './primitives'
3
4
  import type { VectorNetwork, VectorVertex, VectorSegment, VectorRegion, WindingRule } from './types'
4
5
 
5
6
  interface SubPath {
@@ -242,3 +243,16 @@ function parsePath(
242
243
 
243
244
  return { ok: true, network: { vertices, segments, regions } }
244
245
  }
246
+
247
+ /** A `viewBox` value as a rect, or null when it is malformed or does not establish a viewport. */
248
+ export function parseSVGViewBoxValue(value: string | null | undefined): Rect | null {
249
+ if (!value) return null
250
+ const values = value
251
+ .trim()
252
+ .split(/[\s,]+/)
253
+ .map(Number)
254
+ if (values.length !== 4 || values.some((entry) => !Number.isFinite(entry))) return null
255
+ const [x = 0, y = 0, width = 0, height = 0] = values
256
+ if (width <= 0 || height <= 0) return null
257
+ return { x, y, width, height }
258
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Vector } from '../primitives'
2
- import type { VectorRegion, VectorSegment, VectorVertex } from '../types'
2
+ import type { VectorNetwork, VectorRegion, VectorSegment, VectorVertex } from '../types'
3
3
  import type { PathSink } from './sink'
4
4
 
5
5
  export function addSegmentDirected(
@@ -264,32 +264,109 @@ export interface StrokeRun {
264
264
  closed: boolean
265
265
  }
266
266
 
267
+ export type RunContinuation = (vertex: number, from: number) => number | undefined
268
+
267
269
  /**
268
- * Segments chained into runs as Figma strokes a network: a run passes through every vertex
269
- * exactly two segments meet at, so its corners take the stroke's join and only its open ends take
270
- * caps. Runs stop at open ends and at junctions where three or more segments meet.
270
+ * The indices of the segments meeting at each vertex, in segment order; a segment from a vertex to
271
+ * itself is listed there once. `include` leaves out the segments it returns false for.
271
272
  */
272
- export function strokeRuns(segments: VectorSegment[]): StrokeRun[] {
273
- const incident = new Map<number, number[]>()
273
+ export function segmentsByVertex(
274
+ segments: readonly VectorSegment[],
275
+ include?: (index: number) => boolean
276
+ ): Map<number, number[]> {
277
+ const byVertex = new Map<number, number[]>()
274
278
  const meet = (vertex: number, index: number) => {
275
- const list = incident.get(vertex)
279
+ const list = byVertex.get(vertex)
276
280
  if (list) list.push(index)
277
- else incident.set(vertex, [index])
281
+ else byVertex.set(vertex, [index])
278
282
  }
279
283
  for (const [index, segment] of segments.entries()) {
284
+ if (include && !include(index)) continue
280
285
  meet(segment.start, index)
281
286
  if (segment.end !== segment.start) meet(segment.end, index)
282
287
  }
288
+ return byVertex
289
+ }
290
+
291
+ /**
292
+ * The direction segment `index` leaves `vertex` in: along its handle there, or with that handle
293
+ * collapsed, toward the far end's control point, as a cubic leaves toward its next distinct
294
+ * control point; a straight segment leaves along its chord.
295
+ */
296
+ export function leavingDirection(
297
+ network: Pick<VectorNetwork, 'vertices' | 'segments'>,
298
+ index: number,
299
+ vertex: number
300
+ ): Vector {
301
+ const segment = network.segments[index]
302
+ const atStart = segment.start === vertex
303
+ const handle = atStart ? segment.tangentStart : segment.tangentEnd
304
+ if (handle.x !== 0 || handle.y !== 0) return handle
305
+ const from = network.vertices[vertex]
306
+ const to = network.vertices[atStart ? segment.end : segment.start]
307
+ const farHandle = atStart ? segment.tangentEnd : segment.tangentStart
308
+ const control = { x: to.x + farHandle.x - from.x, y: to.y + farHandle.y - from.y }
309
+ if (control.x !== 0 || control.y !== 0) return control
310
+ return { x: to.x - from.x, y: to.y - from.y }
311
+ }
312
+
313
+ /**
314
+ * The pairs of segments a stroke may join at each vertex: the two at a vertex exactly two meet at,
315
+ * and with several regions, also each two region edges next to each other around a vertex,
316
+ * which region strokes join where the gap between them is unfilled, open segments aside.
317
+ */
318
+ export function joinedSegmentPairs(
319
+ network: VectorNetwork
320
+ ): [vertex: number, a: number, b: number][] {
321
+ const pairs: [number, number, number][] = []
322
+ for (const [vertex, indices] of segmentsByVertex(network.segments)) {
323
+ if (indices.length === 2) pairs.push([vertex, indices[0], indices[1]])
324
+ }
325
+ if (network.regions.length < 2) return pairs
326
+ const bounding = new Set(network.regions.flatMap((region) => region.loops.flat()))
327
+ const edges = segmentsByVertex(
328
+ network.segments,
329
+ (index) => bounding.has(index) && network.segments[index].start !== network.segments[index].end
330
+ )
331
+ for (const [vertex, indices] of edges) {
332
+ if (indices.length < 2) continue
333
+ const angle = (index: number) => {
334
+ const direction = leavingDirection(network, index, vertex)
335
+ return Math.atan2(direction.y, direction.x)
336
+ }
337
+ const around = indices.toSorted((a, b) => angle(a) - angle(b))
338
+ for (const [position, index] of around.entries()) {
339
+ pairs.push([vertex, index, around[(position + 1) % around.length]])
340
+ }
341
+ }
342
+ return pairs
343
+ }
344
+
345
+ /**
346
+ * Segments chained into runs as Figma strokes a network: by default a run passes through every
347
+ * vertex exactly two segments meet at, so its corners take the stroke's join and only its open
348
+ * ends take caps. Runs stop at open ends and at junctions where three or more segments meet, unless
349
+ * `continuation` names a segment to go on with there.
350
+ */
351
+ export function strokeRuns(segments: VectorSegment[], continuation?: RunContinuation): StrokeRun[] {
352
+ const incident = segmentsByVertex(segments)
283
353
  const used = new Set<number>()
284
354
  const across = (index: number, vertex: number) =>
285
355
  segments[index].start === vertex ? segments[index].end : segments[index].start
286
- /** Extends a run through `vertex` for as long as two segments meet at each vertex reached. */
356
+ const throughPairs: RunContinuation = (vertex, from) => {
357
+ const meeting = incident.get(vertex)
358
+ if (meeting?.length !== 2) {
359
+ return undefined
360
+ }
361
+ return meeting[0] === from ? meeting[1] : meeting[0]
362
+ }
363
+ const continueAt = continuation ?? throughPairs
287
364
  const extend = (vertex: number, from: number, add: (index: number) => void) => {
288
365
  for (;;) {
289
- const meeting = incident.get(vertex)
290
- if (meeting?.length !== 2) return vertex
291
- const next = meeting[0] === from ? meeting[1] : meeting[0]
292
- if (used.has(next)) return vertex
366
+ const next = continueAt(vertex, from)
367
+ if (next === undefined || used.has(next)) {
368
+ return vertex
369
+ }
293
370
  used.add(next)
294
371
  add(next)
295
372
  vertex = across(next, vertex)
@@ -1,4 +1,5 @@
1
- import { minOf } from '../arrays'
1
+ import { minOf } from '@open-pencil/std/arrays'
2
+
2
3
  import type { SceneNode } from '../types'
3
4
  import type { PathSink } from './sink'
4
5
 
@@ -36,9 +36,4 @@ export interface Rect {
36
36
  height: number
37
37
  }
38
38
 
39
- export type JSONPrimitive = string | number | boolean | null
40
- export type JSONValue = JSONPrimitive | JSONObject | JSONArray
41
- export type JSONObject = { [key: string]: unknown }
42
- export type JSONArray = unknown[]
43
-
44
39
  export * from './schema'
@@ -1,11 +1,12 @@
1
1
  import { sha1 } from '@noble/hashes/legacy.js'
2
2
  import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'
3
3
 
4
+ import { randomHex } from '@open-pencil/std/random'
5
+
4
6
  import { TRANSPARENT } from '../constants'
5
7
  import { imagePaintHashes } from '../images'
6
8
  import { readAllPluginData, withAllPluginData } from '../plugin-data/field'
7
9
  import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'
8
- import { randomHex } from '../random'
9
10
  import type { Fill, SceneNode } from '../types'
10
11
  import type { ShaderPaint, ShaderPreset } from './schema'
11
12
 
@@ -1,10 +1,12 @@
1
1
  import { compact, isEqual, omit, pick } from 'es-toolkit'
2
2
 
3
+ import { randomHex } from '@open-pencil/std/random'
4
+
3
5
  import { BLACK } from './constants'
4
6
  import { copyEffects, copyFills, copyLayoutGrids } from './copy'
5
7
  import type { SceneGraph } from './graph'
6
8
  import { newStrokeGeometry } from './node-defaults'
7
- import { randomHex } from './random'
9
+ import { STROKE_LINE_KEYS } from './strokes'
8
10
  import { styleRunReferences } from './text/references'
9
11
  import type {
10
12
  CharacterStyleOverride,
@@ -121,9 +123,6 @@ export function getSharedStyles(graph: SceneGraph, kind: SharedStyleKind): Share
121
123
  return styles.sort((left, right) => left.name.localeCompare(right.name))
122
124
  }
123
125
 
124
- /** What a stroke draws along beside its paint: the layer's, not its stroke style's. */
125
- const STROKE_LINE_KEYS = ['weight', 'align', 'cap', 'join', 'dashPattern'] as const
126
-
127
126
  /**
128
127
  * Whether new strokes only change how their lines run, keeping every paint. A stroke style gives
129
128
  * paints only, so such a write keeps it; any other strokes write leaves it, as setting even the
package/src/strokes.ts ADDED
@@ -0,0 +1,121 @@
1
+ import { isEqual } from 'es-toolkit'
2
+
3
+ import { copyStroke } from './copy'
4
+ import type { SceneNode, Stroke } from './types'
5
+
6
+ /** What a stroke draws along beside its paint. */
7
+ export const STROKE_LINE_KEYS = [
8
+ 'weight',
9
+ 'align',
10
+ 'cap',
11
+ 'join',
12
+ 'dashPattern'
13
+ ] as const satisfies readonly (keyof Stroke)[]
14
+
15
+ type StrokeLineKey = (typeof STROKE_LINE_KEYS)[number]
16
+
17
+ /**
18
+ * The layer field that keeps each line value. Figma keeps one of each per layer; a layer here
19
+ * also keeps them on each stroke, which the renderer draws.
20
+ */
21
+ export const STROKE_LINE_FIELDS = {
22
+ weight: 'strokeWeight',
23
+ align: 'strokeAlign',
24
+ cap: 'strokeCap',
25
+ join: 'strokeJoin',
26
+ dashPattern: 'dashPattern'
27
+ } as const satisfies Record<StrokeLineKey, keyof SceneNode>
28
+
29
+ export type StrokeLines = Partial<Pick<Stroke, StrokeLineKey>>
30
+
31
+ /** The value a stroke draws with; a stroke without a dash draws solid. */
32
+ export function strokeLine(stroke: Stroke, key: StrokeLineKey): Stroke[StrokeLineKey] {
33
+ return key === 'dashPattern' ? (stroke.dashPattern ?? []) : stroke[key]
34
+ }
35
+
36
+ /** `strokes` with each line field `values` names, as a layer field set alone gives every stroke. */
37
+ export function withStrokeLines(strokes: readonly Stroke[], values: StrokeLines): Stroke[] {
38
+ return strokes.map((stroke) => {
39
+ const next = copyStroke(stroke)
40
+ for (const key of STROKE_LINE_KEYS) {
41
+ const value = values[key]
42
+ if (value !== undefined) Reflect.set(next, key, structuredClone(value))
43
+ }
44
+ return next
45
+ })
46
+ }
47
+
48
+ /**
49
+ * What else `changes` sets so a layer's line fields and its strokes agree: new strokes set the
50
+ * layer's fields to the first stroke's, and a layer field set without strokes goes to every
51
+ * stroke. Strokes win when `changes` sets both, so restoring strokes restores what they draw.
52
+ * Only fields whose value changes are returned, so an instance overrides no more than an edit
53
+ * changed. A layer without strokes keeps its fields for the next stroke (`newStrokeGeometry`).
54
+ */
55
+ export function strokeLineChanges(
56
+ node: SceneNode,
57
+ changes: Partial<SceneNode>
58
+ ): Partial<SceneNode> {
59
+ if (changes.strokes) {
60
+ const first = changes.strokes.at(0)
61
+ if (!first) return {}
62
+ const derived: Partial<SceneNode> = {}
63
+ for (const key of STROKE_LINE_KEYS) {
64
+ const field = STROKE_LINE_FIELDS[key]
65
+ const current = field in changes ? changes[field] : node[field]
66
+ // A stroke without its own cap or join draws with the layer's.
67
+ const value = strokeLine(first, key) ?? current
68
+ if (!isEqual(current, value)) Reflect.set(derived, field, structuredClone(value))
69
+ }
70
+ // Strokes without their own cap or join take the layer's, so every stroke says what it draws.
71
+ const cap = derived.strokeCap ?? changes.strokeCap ?? node.strokeCap
72
+ const join = derived.strokeJoin ?? changes.strokeJoin ?? node.strokeJoin
73
+ if (changes.strokes.some((stroke) => stroke.cap === undefined || stroke.join === undefined)) {
74
+ derived.strokes = changes.strokes.map((stroke) => ({
75
+ ...copyStroke(stroke),
76
+ cap: stroke.cap ?? cap,
77
+ join: stroke.join ?? join
78
+ }))
79
+ }
80
+ return derived
81
+ }
82
+ if (node.strokes.length === 0) return {}
83
+ const values: StrokeLines = {}
84
+ let set = false
85
+ for (const key of STROKE_LINE_KEYS) {
86
+ const value = changes[STROKE_LINE_FIELDS[key]]
87
+ if (value === undefined) continue
88
+ Reflect.set(values, key, value)
89
+ set = true
90
+ }
91
+ // Most writes, such as a move or a layout pass, set no line field.
92
+ if (!set) return {}
93
+ const strokes = withStrokeLines(node.strokes, values)
94
+ return isEqual(strokes, node.strokes) ? {} : { strokes }
95
+ }
96
+
97
+ /**
98
+ * Whether the strokes `changes` sets differ from `node`'s by more than the layer fields the same
99
+ * write sets: a paint, a stroke added or removed, or a stroke's line that no layer field records.
100
+ * Figma overrides a weight or dash set on an instance layer alone, so a component's later paint
101
+ * change still reaches the copy (live).
102
+ */
103
+ export function changesMoreThanStrokeLines(node: SceneNode, changes: Partial<SceneNode>): boolean {
104
+ const next = changes.strokes
105
+ if (!next) return false
106
+ if (next.length !== node.strokes.length) return true
107
+ const lines: StrokeLines = {}
108
+ for (const key of STROKE_LINE_KEYS) {
109
+ const value = changes[STROKE_LINE_FIELDS[key]]
110
+ if (value !== undefined) Reflect.set(lines, key, value)
111
+ }
112
+ // Strokes written without a cap or join take the layer's, as `strokeLineChanges` gives them,
113
+ // and a stroke without a dash draws as solid as one with an empty dash.
114
+ const drawn = (stroke: Stroke): Stroke => ({
115
+ ...stroke,
116
+ cap: stroke.cap ?? node.strokeCap,
117
+ join: stroke.join ?? node.strokeJoin,
118
+ dashPattern: stroke.dashPattern ?? []
119
+ })
120
+ return !isEqual(withStrokeLines(node.strokes, lines).map(drawn), next.map(drawn))
121
+ }
package/src/text/index.ts CHANGED
@@ -5,3 +5,4 @@ export * from './references'
5
5
  export * from './lengths'
6
6
  export * from './overflow'
7
7
  export * from './schema'
8
+ export * from './runs'
@@ -0,0 +1,80 @@
1
+ import { isEqual } from 'es-toolkit/predicate'
2
+
3
+ import type { CharacterStyleOverride, SceneNode, StyleRun } from '../types'
4
+
5
+ /** The run that styles `text[index]`, if one does. */
6
+ export function styleRunAt(runs: readonly StyleRun[], index: number): StyleRun | undefined {
7
+ return runs.find((run) => index >= run.start && index < run.start + run.length)
8
+ }
9
+
10
+ /** The language `text[index]` is shaped in: its run's, or the text's own. */
11
+ export function textLanguageAt(
12
+ node: Pick<SceneNode, 'styleRuns' | 'textLanguage'>,
13
+ index: number
14
+ ): string | null {
15
+ const language = styleRunAt(node.styleRuns, index)?.style.textLanguage
16
+ return language !== undefined ? language : node.textLanguage
17
+ }
18
+
19
+ /**
20
+ * Adds `style` over `[start, start + length)` to runs built in text order, extending the last
21
+ * run instead when it ends at `start` with an equal style. An empty style or range adds nothing,
22
+ * since those characters keep the text's own style.
23
+ */
24
+ export function appendStyleRun(
25
+ runs: StyleRun[],
26
+ start: number,
27
+ length: number,
28
+ style: CharacterStyleOverride
29
+ ): void {
30
+ if (length <= 0 || Object.keys(style).length === 0) return
31
+ const previous = runs.at(-1)
32
+ if (previous && previous.start + previous.length === start && isEqual(previous.style, style))
33
+ previous.length += length
34
+ else runs.push({ start, length, style })
35
+ }
36
+
37
+ /** A stretch of text in one style: a run's, or the text's own where `style` is null. */
38
+ export interface StyleRunPiece {
39
+ start: number
40
+ end: number
41
+ style: CharacterStyleOverride | null
42
+ }
43
+
44
+ /**
45
+ * The first `length` characters cut at their runs, in order and covering every character once:
46
+ * a run's part that an earlier run already covers, or that lies past the text, is left out.
47
+ * `boundary` moves each cut to where the text may be cut, such as out of a surrogate pair.
48
+ */
49
+ export function styleRunPieces(
50
+ runs: readonly StyleRun[],
51
+ length: number,
52
+ boundary: (index: number) => number = (index) => index
53
+ ): StyleRunPiece[] {
54
+ const pieces: StyleRunPiece[] = []
55
+ let at = 0
56
+ for (const run of runs.toSorted((a, b) => a.start - b.start)) {
57
+ const start = Math.min(length, Math.max(at, boundary(run.start)))
58
+ const end = Math.min(length, boundary(run.start + run.length))
59
+ if (start > at) pieces.push({ start: at, end: start, style: null })
60
+ if (end > start) pieces.push({ start, end, style: run.style })
61
+ at = Math.max(start, end)
62
+ }
63
+ if (at < length) pieces.push({ start: at, end: length, style: null })
64
+ return pieces
65
+ }
66
+
67
+ /** Each of the first `length` characters' overrides, merged from the runs over it in order. */
68
+ export function characterOverrides(
69
+ runs: readonly StyleRun[],
70
+ length: number
71
+ ): CharacterStyleOverride[] {
72
+ const styles = Array.from({ length }, (): CharacterStyleOverride => ({}))
73
+ for (const run of runs) {
74
+ const end = Math.min(length, run.start + run.length)
75
+ for (let index = Math.max(0, run.start); index < end; index++) {
76
+ styles[index] = { ...styles[index], ...run.style }
77
+ }
78
+ }
79
+ return styles
80
+ }
@@ -1,4 +1,5 @@
1
- import { appendAll } from '../arrays'
1
+ import { appendAll } from '@open-pencil/std/arrays'
2
+
2
3
  import type { SceneGraph } from '../graph'
3
4
  import { imagePaintHashes } from '../images'
4
5
  import { overriddenBindingField } from '../instances/overrides'
package/src/types.ts CHANGED
@@ -287,6 +287,33 @@ export interface ProgressiveBlur {
287
287
  endOffset: Vector
288
288
  }
289
289
 
290
+ /**
291
+ * A Noise effect's grain, in Figma's plugin terms: `MONOTONE` grains in the effect's colour,
292
+ * `DUOTONE` in it and `secondaryColor`, `MULTITONE` in many colours at `opacity`. `noiseSize` is a
293
+ * grain's size in px, which Figma keeps within 0 to 100, and `density` how much of the layer the
294
+ * grains cover, 0 to 1. `seed` picks the pattern; Figma's plugin API neither shows nor sets it.
295
+ */
296
+ export interface NoiseEffectParams {
297
+ noiseType: NoiseType
298
+ noiseSize: Vector
299
+ density: number
300
+ secondaryColor?: Color
301
+ opacity?: number
302
+ seed?: number
303
+ }
304
+
305
+ /**
306
+ * A Texture effect's grain, which roughens the layer's edges: `noiseSize` is the grain's size in
307
+ * px, within 0 to 100 as Figma keeps it, and `clipToShape` keeps the roughened layer inside its
308
+ * own outline. The effect's `radius` is how far the grain moves the edges. `.fig` files name the
309
+ * effect `GRAIN`.
310
+ */
311
+ export interface TextureEffectParams {
312
+ noiseSize: Vector
313
+ clipToShape: boolean
314
+ seed?: number
315
+ }
316
+
290
317
  export interface Effect {
291
318
  type:
292
319
  | 'DROP_SHADOW'
@@ -295,6 +322,8 @@ export interface Effect {
295
322
  | 'BACKGROUND_BLUR'
296
323
  | 'FOREGROUND_BLUR'
297
324
  | 'GLASS'
325
+ | 'NOISE'
326
+ | 'TEXTURE'
298
327
  color: Color
299
328
  offset: Vector
300
329
  radius: number
@@ -306,6 +335,10 @@ export interface Effect {
306
335
  glass?: GlassEffectParams
307
336
  /** Set on a layer or background blur that is progressive, and only there. */
308
337
  progressive?: ProgressiveBlur
338
+ /** Set on a `NOISE` effect, and only there. */
339
+ noise?: NoiseEffectParams
340
+ /** Set on a `TEXTURE` effect, and only there. */
341
+ texture?: TextureEffectParams
309
342
  }
310
343
 
311
344
  export type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'
@@ -654,6 +687,8 @@ export interface CommentReply {
654
687
  author: string
655
688
  /** The author's collaboration color when they wrote it, for their avatar. */
656
689
  authorColor?: Color
690
+ /** The agent that wrote it, for `author` or as itself. */
691
+ agent?: string
657
692
  /** Markdown: bold, italic, strikethrough, links and lists. */
658
693
  text: string
659
694
  createdAt: string
@@ -678,6 +713,8 @@ export interface CommentThread {
678
713
  author: string
679
714
  /** The author's collaboration color when they wrote it, for their avatar. */
680
715
  authorColor?: Color
716
+ /** The agent that wrote it, for `author` or as itself. */
717
+ agent?: string
681
718
  /** Markdown: bold, italic, strikethrough, links and lists. */
682
719
  text: string
683
720
  createdAt: string
@@ -1,4 +1,5 @@
1
- import { appendAll } from '../arrays'
1
+ import { appendAll } from '@open-pencil/std/arrays'
2
+
2
3
  import type { SceneGraph } from '../graph'
3
4
  import type { Color } from '../primitives'
4
5
  import type { Variable, VariableLiteral, VariableValue } from '../types'