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

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 +3 -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 +47 -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 +3 -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 +50 -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
package/src/constants.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Color } from './primitives'
2
- import type { GlassEffectParams } from './types'
2
+ import type { GlassEffectParams, NoiseEffectParams, TextureEffectParams } from './types'
3
3
 
4
4
  export const BLACK: Color = { r: 0, g: 0, b: 0, a: 1 }
5
5
  export const WHITE: Color = { r: 1, g: 1, b: 1, a: 1 }
@@ -12,6 +12,30 @@ export const UNSET_GLASS: Readonly<GlassEffectParams> = {
12
12
  lightIntensity: 0,
13
13
  dispersion: 0
14
14
  }
15
+ /** The grain of a noise effect whose values are missing: none of the layer covered. */
16
+ export const UNSET_NOISE: Readonly<NoiseEffectParams> = {
17
+ noiseType: 'MONOTONE',
18
+ noiseSize: { x: 1, y: 1 },
19
+ density: 0
20
+ }
21
+ /** A new noise effect's grain, as Figma's effects panel starts one: black at 25%, fully dense. */
22
+ export const DEFAULT_NOISE: Readonly<NoiseEffectParams> = {
23
+ noiseType: 'MONOTONE',
24
+ noiseSize: { x: 0.5, y: 0.5 },
25
+ density: 1
26
+ }
27
+ /** The colour a new noise effect's grains start in. */
28
+ export const DEFAULT_NOISE_COLOR: Readonly<Color> = { r: 0, g: 0, b: 0, a: 0.25 }
29
+ /** A new texture effect's grain, as Figma's effects panel starts one, with a radius of 4. */
30
+ export const DEFAULT_TEXTURE: Readonly<TextureEffectParams> = {
31
+ noiseSize: { x: 4, y: 4 },
32
+ clipToShape: false
33
+ }
34
+ /** The grain of a texture effect whose values are missing; its radius of 0 moves nothing. */
35
+ export const UNSET_TEXTURE: Readonly<TextureEffectParams> = {
36
+ noiseSize: { x: 1, y: 1 },
37
+ clipToShape: true
38
+ }
15
39
  /** The lens a new glass effect starts with when nothing sets its values. */
16
40
  export const DEFAULT_GLASS: Readonly<GlassEffectParams> = {
17
41
  refraction: 0.5,
package/src/copy.ts CHANGED
@@ -36,6 +36,7 @@ export function copyFill<T extends Fill>(f: T): T {
36
36
  if (f.gradientStops) copy.gradientStops = f.gradientStops.map(copyGradientStop)
37
37
  if (f.gradientTransform) copy.gradientTransform = { ...f.gradientTransform }
38
38
  if (f.imageTransform) copy.imageTransform = { ...f.imageTransform }
39
+ if (f.filters) copy.filters = { ...f.filters }
39
40
  if (f.patternSpacing) copy.patternSpacing = { ...f.patternSpacing }
40
41
  if (f.noiseSize) copy.noiseSize = { ...f.noiseSize }
41
42
  return copy
@@ -52,6 +53,8 @@ export function copyStroke(s: Stroke): Stroke {
52
53
  export function copyEffect(e: Effect): Effect {
53
54
  const copy: Effect = { ...e, color: { ...e.color }, offset: { ...e.offset } }
54
55
  if (e.glass) copy.glass = { ...e.glass }
56
+ if (e.noise) copy.noise = structuredClone(e.noise)
57
+ if (e.texture) copy.texture = structuredClone(e.texture)
55
58
  if (e.progressive) {
56
59
  copy.progressive = {
57
60
  startRadius: e.progressive.startRadius,
package/src/css/grid.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import valueParser, { type FunctionNode, type Node } from 'postcss-value-parser'
2
2
 
3
- import { appendAll } from '../arrays'
3
+ import { appendAll } from '@open-pencil/std/arrays'
4
+
4
5
  import { MAX_GRID_TRACKS } from '../layout/limits'
5
6
  import type { GridTrack } from '../types'
6
7
  import { parseCSSNumber } from './values'
@@ -65,12 +66,39 @@ function functionTracks(node: FunctionNode): GridTrack[] {
65
66
  }
66
67
  }
67
68
 
69
+ /**
70
+ * A word's track sizes past the line names in it, such as `[start]200px[end]`, which the value
71
+ * parser keeps as one word; names may run across words, as in `[a b]`, so whether the word
72
+ * starts inside them comes in and whether it ends inside them goes out.
73
+ */
74
+ function sizesOutsideNames(word: string, inNames: boolean): { sizes: string[]; inNames: boolean } {
75
+ const sizes: string[] = []
76
+ let size = ''
77
+ let names = inNames
78
+ for (const char of word) {
79
+ if (char === '[' || char === ']') {
80
+ if (size) sizes.push(size)
81
+ size = ''
82
+ names = char === '['
83
+ } else if (!names) {
84
+ size += char
85
+ }
86
+ }
87
+ if (size) sizes.push(size)
88
+ return { sizes, inNames: names }
89
+ }
90
+
68
91
  function tracksOf(nodes: Node[]): GridTrack[] {
69
92
  const tracks: GridTrack[] = []
93
+ // Line names, such as `[start]` or `[a b]`, name the lines between tracks and size none.
94
+ let inNames = false
70
95
  for (const node of nodes) {
71
96
  if (tracks.length >= MAX_GRID_TRACKS) break
72
- if (node.type === 'word') tracks.push(wordTrack(node.value))
73
- else if (node.type === 'function') appendAll(tracks, functionTracks(node))
97
+ if (node.type === 'word') {
98
+ const word = sizesOutsideNames(node.value, inNames)
99
+ inNames = word.inNames
100
+ appendAll(tracks, word.sizes.map(wordTrack))
101
+ } else if (node.type === 'function') appendAll(tracks, functionTracks(node))
74
102
  }
75
103
  return tracks.slice(0, MAX_GRID_TRACKS)
76
104
  }
package/src/css/index.ts CHANGED
@@ -3,8 +3,10 @@ export { parseCSSGridTracks } from './grid'
3
3
  export {
4
4
  parseCSSAlignItems,
5
5
  parseCSSAlignSelf,
6
+ parseCSSAspectRatio,
6
7
  parseCSSFlexDirection,
7
- parseCSSJustifyContent
8
+ parseCSSJustifyContent,
9
+ type CSSAspectRatio
8
10
  } from './layout'
9
11
  export { parseCSSShadows } from './shadows'
10
12
  export {
@@ -24,4 +26,13 @@ export {
24
26
  type CSSTransformBox,
25
27
  type CSSTransformStyle
26
28
  } from './transform'
27
- export { dimension, parseCSSColor, parseCSSNumber, splitCSSValue } from './values'
29
+ export {
30
+ dimension,
31
+ parseCSSColor,
32
+ parseCSSNumber,
33
+ parseCSSURLReferences,
34
+ parseCSSURLs,
35
+ parsePaintFallback,
36
+ parseFragmentReference,
37
+ splitCSSValue
38
+ } from './values'
package/src/css/layout.ts CHANGED
@@ -51,3 +51,39 @@ export function parseCSSAlignSelf(value: string | undefined): LayoutAlignSelf |
51
51
  const keyword = alignmentKeyword(value)
52
52
  return keyword === 'normal' ? 'STRETCH' : parseLayoutAlignSelf(keyword)
53
53
  }
54
+
55
+ /** An `aspect-ratio`: width over height, and whether an `auto` stands beside it. */
56
+ export interface CSSAspectRatio {
57
+ ratio: number
58
+ /** With `auto`, the ratio sizes the content box, whatever `box-sizing` says. */
59
+ auto: boolean
60
+ }
61
+
62
+ /**
63
+ * The ratio an `aspect-ratio` value sizes a box by: a number, or a width and a height either
64
+ * side of a slash, with an `auto` on either side or none. Null for `auto` alone and for a ratio
65
+ * with a zero, negative, or infinite side.
66
+ */
67
+ export function parseCSSAspectRatio(value: string | undefined): CSSAspectRatio | null {
68
+ if (!value) return null
69
+ const isAuto = (node: valueParser.Node) =>
70
+ node.type === 'word' && node.value.toLowerCase() === 'auto'
71
+ const all = valueParser(value).nodes.filter(
72
+ (node) => node.type !== 'space' && node.type !== 'comment'
73
+ )
74
+ const nodes = all.filter((node) => !isAuto(node))
75
+ const auto = nodes.length < all.length
76
+ const [width, slash, height] = nodes
77
+ if (nodes.length === 0 || width.type !== 'word') return null
78
+ const across = Number(width.value)
79
+ if (nodes.length === 1) return positiveRatio(across, auto)
80
+ if (nodes.length !== 3 || slash.type !== 'div' || slash.value !== '/' || height.type !== 'word') {
81
+ return null
82
+ }
83
+ const down = Number(height.value)
84
+ return down > 0 ? positiveRatio(across / down, auto) : null
85
+ }
86
+
87
+ function positiveRatio(ratio: number, auto: boolean): CSSAspectRatio | null {
88
+ return Number.isFinite(ratio) && ratio > 0 ? { ratio, auto } : null
89
+ }
package/src/css/values.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import { compact } from 'es-toolkit'
1
2
  import valueParser from 'postcss-value-parser'
3
+ import { decode, parsePath } from 'ufo'
2
4
 
3
5
  import { tryParseColor } from '../color'
4
6
  import type { Color } from '../primitives'
@@ -48,3 +50,50 @@ export function splitCSSValue(value: string): string[] {
48
50
  .nodes.filter((node) => node.type !== 'space' && node.type !== 'comment')
49
51
  .map((node) => valueParser.stringify(node))
50
52
  }
53
+
54
+ /**
55
+ * The id of the element a reference points to in its own document, as `href="#mark"` and
56
+ * `url(#clip)` point, decoded; null for a reference to another file or without a fragment.
57
+ */
58
+ export function parseFragmentReference(reference: string | null | undefined): string | null {
59
+ if (!reference) return null
60
+ const { pathname, search, hash } = parsePath(reference.trim())
61
+ if (pathname || search || hash.length < 2) return null
62
+ return decode(hash.slice(1))
63
+ }
64
+
65
+ /** What each `url()` in a CSS value points at, quoted or not, such as an image's data URL. */
66
+ export function parseCSSURLs(value: string | undefined): string[] {
67
+ const urls: string[] = []
68
+ if (!value) return urls
69
+ valueParser(value).walk((node) => {
70
+ if (node.type !== 'function' || node.value.toLowerCase() !== 'url') return true
71
+ const target = node.nodes.at(0)?.value
72
+ if (target) urls.push(target)
73
+ return false
74
+ })
75
+ return urls
76
+ }
77
+
78
+ /**
79
+ * What a paint written as `url(#id) fallback` falls back to when its reference cannot be used:
80
+ * the value without its `url()`, or undefined when nothing follows it, which paints nothing.
81
+ */
82
+ export function parsePaintFallback(value: string): string | undefined {
83
+ const rest = valueParser
84
+ .stringify(
85
+ valueParser(value).nodes.filter(
86
+ (node) => node.type !== 'function' || node.value.toLowerCase() !== 'url'
87
+ )
88
+ )
89
+ .trim()
90
+ return rest || undefined
91
+ }
92
+
93
+ /**
94
+ * The ids a CSS value points at with local `url(#id)` references, as `clip-path`, `mask`,
95
+ * `filter`, and SVG paints do, quoted or not.
96
+ */
97
+ export function parseCSSURLReferences(value: string | undefined): string[] {
98
+ return compact(parseCSSURLs(value).map(parseFragmentReference))
99
+ }
package/src/geometry.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { arrowCapOverflow } from './arrow-caps'
2
+ import { joinedSegmentPairs, leavingDirection } from './paths/network'
2
3
  import type { Rect, Vector } from './primitives'
3
4
  import type {
4
5
  ArcData,
@@ -204,6 +205,9 @@ type SideStrokeNode = Pick<
204
205
  | 'borderLeftWeight'
205
206
  >
206
207
 
208
+ /** What deciding on per-side strokes reads: the side weights, and the node's type when known. */
209
+ type StrokeSidesInput = Partial<SideStrokeNode> & { type?: string }
210
+
207
211
  /** The layers the canvas strokes side by side when their sides have weights of their own. */
208
212
  const SIDE_STROKE_TYPES: ReadonlySet<string> = new Set<SceneNode['type']>([
209
213
  'FRAME',
@@ -219,7 +223,7 @@ const SIDE_STROKE_TYPES: ReadonlySet<string> = new Set<SceneNode['type']>([
219
223
  * Whether `node` strokes each side by its own weight. A line or vector keeps one weight whatever
220
224
  * the flag says, since its outline has no sides.
221
225
  */
222
- export function drawsStrokeSides(node: Partial<SideStrokeNode> & { type?: string }): boolean {
226
+ export function drawsStrokeSides(node: StrokeSidesInput): boolean {
223
227
  return node.independentStrokeWeights === true && (!node.type || SIDE_STROKE_TYPES.has(node.type))
224
228
  }
225
229
 
@@ -250,10 +254,7 @@ export function strokeSideWeights(
250
254
  }
251
255
 
252
256
  /** A stroke's weight, or with sides of their own the widest side, for what is not drawn per side. */
253
- export function strokeWeightOf(
254
- node: Partial<SideStrokeNode> & { type?: string },
255
- stroke: Pick<Stroke, 'weight'>
256
- ): number {
257
+ export function strokeWeightOf(node: StrokeSidesInput, stroke: Pick<Stroke, 'weight'>): number {
257
258
  if (!drawsStrokeSides(node)) return stroke.weight
258
259
  return Math.max(
259
260
  node.borderTopWeight ?? 0,
@@ -335,35 +336,16 @@ export function strokeOverflow(
335
336
  return Math.max(overflow, heads > 0 && line ? heads + overflow / 2 : heads)
336
337
  }
337
338
 
338
- /** The direction a segment leaves `vertex` in, along its handle when it has one. */
339
- function leaving(network: VectorNetwork, index: number, vertex: number): Vector {
340
- const segment = network.segments[index]
341
- const atStart = segment.start === vertex
342
- const handle = atStart ? segment.tangentStart : segment.tangentEnd
343
- if (handle.x !== 0 || handle.y !== 0) return handle
344
- const from = network.vertices[vertex]
345
- const to = network.vertices[atStart ? segment.end : segment.start]
346
- return { x: to.x - from.x, y: to.y - from.y }
347
- }
348
-
349
339
  /**
350
340
  * How far past half the stroke the sharpest mitered corner reaches, as a multiple: a corner of
351
341
  * angle θ mitres out to 1/sin(θ/2), unless that passes the miter limit and it bevels instead.
352
- * Corners are the vertices exactly two segments meet at, as the stroke joins them.
353
342
  */
354
343
  function miterRatio(network: VectorNetwork, join: StrokeJoin | undefined, limit = 4): number {
355
- const meeting = new Map<number, number[]>()
356
- for (const [index, segment] of network.segments.entries()) {
357
- for (const vertex of new Set([segment.start, segment.end])) {
358
- meeting.set(vertex, [...(meeting.get(vertex) ?? []), index])
359
- }
360
- }
361
344
  let ratio = 1
362
- for (const [vertex, indices] of meeting) {
363
- if (indices.length !== 2) continue
345
+ for (const [vertex, first, second] of joinedSegmentPairs(network)) {
364
346
  if ((network.vertices[vertex].strokeJoin ?? join ?? 'MITER') !== 'MITER') continue
365
- const a = leaving(network, indices[0], vertex)
366
- const b = leaving(network, indices[1], vertex)
347
+ const a = leavingDirection(network, first, vertex)
348
+ const b = leavingDirection(network, second, vertex)
367
349
  const lengths = Math.hypot(a.x, a.y) * Math.hypot(b.x, b.y)
368
350
  if (lengths === 0) continue
369
351
  const angle = Math.acos(Math.max(-1, Math.min(1, (a.x * b.x + a.y * b.y) / lengths)))
package/src/graph.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable max-lines -- SceneGraph is the facade over the domain modules */
2
2
  import { omitBy, pick } from 'es-toolkit/object'
3
- import { isUndefined } from 'es-toolkit/predicate'
3
+ import { isEmptyObject, isUndefined } from 'es-toolkit/predicate'
4
4
 
5
5
  import { removeStaleBindings } from './bindings'
6
6
  import { BufferedSceneEmitter } from './buffered-events'
@@ -25,6 +25,7 @@ import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'
25
25
  import { updateNodePreview, type NodePreviewObserver } from './preview'
26
26
  import type { Color, Rect, Vector } from './primitives'
27
27
  import { markSourceFieldsEdited } from './source-metadata'
28
+ import { strokeLineChanges } from './strokes'
28
29
  import { textCacheInvalidationChanges } from './text/picture'
29
30
  import { remapCopiedReferences } from './transfer/copied'
30
31
  import type {
@@ -464,6 +465,7 @@ export class SceneGraph {
464
465
 
465
466
  createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {
466
467
  const node = createDefaultNode(() => this.generateEntityId(), type, overrides)
468
+ Object.assign(node, strokeLineChanges(node, overrides))
467
469
  const parent = this.nodes.get(parentId)
468
470
  this.willChangeNode(parent)
469
471
  parent?.childIds.push(node.id)
@@ -586,7 +588,7 @@ export class SceneGraph {
586
588
  }
587
589
  updateNodePreview(id: string, changes: Partial<SceneNode>): void {
588
590
  const node = this.nodes.get(id)
589
- if (node) changes = this.sizedChanges(node, changes)
591
+ if (node) changes = this.impliedChanges(node, changes)
590
592
  const appliedChanges = updateNodePreview(this, id, changes, (node, applied) => {
591
593
  for (const observer of this.changeObservers) observer.previewed?.(node)
592
594
  for (const observe of this.previewObservers) observe(node, applied)
@@ -606,12 +608,17 @@ export class SceneGraph {
606
608
 
607
609
  const node = this.nodes.get(id)
608
610
  if (!node) return
609
- this.applyNodeChanges(node, this.sizedChanges(node, omitBy(changes, isUndefined)))
611
+ this.applyNodeChanges(node, this.impliedChanges(node, omitBy(changes, isUndefined)))
610
612
  }
611
613
 
612
- /** A size set from outside layout, with what it also sets on a generated frame. */
613
- private sizedChanges(node: SceneNode, changes: Partial<SceneNode>): Partial<SceneNode> {
614
- return this.isApplyingLayout ? changes : withGeneratedFrameSize(node, changes)
614
+ /**
615
+ * `changes` with what they also set: a size from outside layout on a generated frame, and
616
+ * strokes and the layer's line fields kept in agreement (`strokeLineChanges`).
617
+ */
618
+ private impliedChanges(node: SceneNode, changes: Partial<SceneNode>): Partial<SceneNode> {
619
+ const sized = this.isApplyingLayout ? changes : withGeneratedFrameSize(node, changes)
620
+ const lines = strokeLineChanges(node, sized)
621
+ return isEmptyObject(lines) ? sized : { ...sized, ...lines }
615
622
  }
616
623
 
617
624
  /** Replay captured properties without dropping explicit undefined values or absent keys. */
@@ -1,6 +1,7 @@
1
1
  import { omit } from 'es-toolkit'
2
2
 
3
- import { maxOf, minOf } from '../arrays'
3
+ import { maxOf, minOf } from '@open-pencil/std/arrays'
4
+
4
5
  import type { Fill, SceneNode, Stroke, VectorNetwork } from '../types'
5
6
  import { readIcon, readIconTint } from './model'
6
7
 
package/src/ids.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { randomIndex } from './random'
1
+ import { randomIndex } from '@open-pencil/std/random'
2
2
 
3
3
  /** Figma reads both parts of a GUID as signed 32-bit integers and drops records beyond them. */
4
4
  const MAX_ID_SESSION = 0x7fffffff
@@ -5,6 +5,7 @@ import {
5
5
  restoreOwnedSlotContent,
6
6
  type ParkedSlotContent
7
7
  } from '../slots/frames'
8
+ import { changesMoreThanStrokeLines } from '../strokes'
8
9
  import type { SceneNode } from '../types'
9
10
  import { applyBoundPaintColorsIn, keepCopyBoundPaints } from '../variables/paints'
10
11
  import { keepOwnContentSize } from './content-size'
@@ -28,6 +29,7 @@ import {
28
29
  import { walkInstanceSources } from './source-walk'
29
30
  import { followComponentLayers } from './swap'
30
31
  import {
32
+ applySyncedStrokeLines,
31
33
  cloneChildrenWithMapping,
32
34
  copyProp,
33
35
  sourceInTargetCoordinates,
@@ -151,15 +153,14 @@ export function swapInstanceComponent(
151
153
  const previousComponent = namedAfter(graph, instance, component)
152
154
  recordNestedSwap(graph, instance, componentId)
153
155
  const source = sourceInTargetCoordinates(component, instance.componentScale)
154
- const updates: Partial<SceneNode> = {
155
- componentId,
156
- ...ownSyncedProps(graph, instance, source).updates
157
- }
156
+ const own = ownSyncedProps(graph, instance, source)
157
+ const updates: Partial<SceneNode> = { componentId, ...own.updates }
158
158
 
159
159
  if (!keepName && (!previousComponent || instance.name === previousComponent.name))
160
160
  updates.name = component.name
161
161
 
162
162
  keepCopyBoundPaints(graph, instance, updates)
163
+ applySyncedStrokeLines(instance, updates, own.kept)
163
164
  const slotContent = detachOwnedSlotContent(graph, instance)
164
165
  graph.updateNode(instanceId, updates)
165
166
  followComponentLayers(graph, instance, component, parkedContent(slotContent))
@@ -332,6 +333,16 @@ export function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: st
332
333
  return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
333
334
  }
334
335
 
336
+ /**
337
+ * The fields `changes` overrides on an instance layer. New strokes that change only what the
338
+ * layer's line fields say override those fields, not the paints (`changesMoreThanStrokeLines`).
339
+ */
340
+ export function instanceOverrideFields(node: SceneNode, changes: Partial<SceneNode>): string[] {
341
+ const fields = Object.keys(changes)
342
+ if (!changes.strokes || changesMoreThanStrokeLines(node, changes)) return fields
343
+ return fields.filter((field) => field !== 'strokes')
344
+ }
345
+
335
346
  export function recordInstanceOverride(
336
347
  graph: SceneGraph,
337
348
  nodeId: string,
@@ -344,10 +355,14 @@ export function recordInstanceOverride(
344
355
  (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field)
345
356
  )
346
357
 
347
- if (relevant.length === 0) return
358
+ const added = relevant.filter(
359
+ (field) => !hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
360
+ )
361
+ if (added.length === 0) return
348
362
 
349
- graph.willChangeNode(instance)
350
- for (const field of relevant)
351
- setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
352
- graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
363
+ // A new state rather than an edit of the old one, so a preview that captured the old state
364
+ // puts it back on cancel.
365
+ const overrides = cloneInstanceOverrideState(instance.instanceOverrides)
366
+ for (const field of added) setInstanceOverride(overrides, instance.id, nodeId, field)
367
+ graph.updateNode(instance.id, { instanceOverrides: overrides })
353
368
  }
@@ -1,6 +1,7 @@
1
1
  import { isEqual } from 'es-toolkit/predicate'
2
2
 
3
- import { appendAll } from '../arrays'
3
+ import { appendAll } from '@open-pencil/std/arrays'
4
+
4
5
  import { reapplyComponentPropertyAssignments } from '../components/properties'
5
6
  import type { SceneGraph } from '../graph'
6
7
  import { ownsSlotContent, slotPropertyId } from '../slots/frames'
@@ -8,6 +8,13 @@ import type { NodeCloneMode } from '../copy'
8
8
  import type { SceneGraph } from '../graph'
9
9
  import { scaleNodeChanges } from '../scaling/node'
10
10
  import { ownsSlotContent, slotPropertyId } from '../slots/frames'
11
+ import {
12
+ STROKE_LINE_FIELDS,
13
+ STROKE_LINE_KEYS,
14
+ strokeLine,
15
+ type StrokeLines,
16
+ withStrokeLines
17
+ } from '../strokes'
11
18
  import type { SceneNode } from '../types'
12
19
  import { resolvedNumericBindings } from '../variables/bindings'
13
20
  import { isNumericVariableBindingField } from '../variables/fields'
@@ -154,6 +161,8 @@ export function updateSyncedProps(
154
161
  applySyncedModes(graph, target, updates)
155
162
  keepCopyBoundPaints(graph, target, updates)
156
163
  }
164
+ // After the copy's own bound paints, which can bring its strokes into the write.
165
+ applySyncedStrokeLines(target, updates, kept)
157
166
  let changed: Partial<SceneNode> | undefined
158
167
  for (const key of Object.keys(updates)) {
159
168
  const current = target[key as keyof SceneNode]
@@ -172,6 +181,38 @@ export function updateSyncedProps(
172
181
  graph.updateNode(target.id, changed)
173
182
  }
174
183
 
184
+ /**
185
+ * Strokes a sync or swap gives a copy draw with the copy's own line fields: the weight,
186
+ * alignment, cap, join, or dash it overrides, and a bound weight resolved in its modes. Figma
187
+ * keeps a stroke weight override when the component's color changes (live).
188
+ */
189
+ export function applySyncedStrokeLines(
190
+ target: SceneNode,
191
+ updates: Partial<SceneNode>,
192
+ kept: (field: string) => boolean
193
+ ): void {
194
+ const strokes = updates.strokes
195
+ const first = strokes?.at(0)
196
+ if (!strokes || !first) return
197
+ const lines: StrokeLines = {}
198
+ let set = false
199
+ for (const key of STROKE_LINE_KEYS) {
200
+ const field = STROKE_LINE_FIELDS[key]
201
+ const own = kept(field)
202
+ const value = own ? target[field] : updates[field]
203
+ if (value === undefined) continue
204
+ // A field the copy overrides holds for every stroke; the component's own values keep its
205
+ // strokes' differences unless a binding resolved the first one apart.
206
+ const differs = own
207
+ ? strokes.some((stroke) => !isEqual(value, strokeLine(stroke, key)))
208
+ : !isEqual(value, strokeLine(first, key))
209
+ if (!differs) continue
210
+ Reflect.set(lines, key, value)
211
+ set = true
212
+ }
213
+ if (set) updates.strokes = withStrokeLines(strokes, lines)
214
+ }
215
+
175
216
  /**
176
217
  * A bound number the sync writes takes the value it resolves to where the copy sits, not the
177
218
  * one its component holds: an instance that sets another mode, or sits in one that does, shows
@@ -4,3 +4,4 @@ export * from './keywords'
4
4
  export * from './limits'
5
5
  export * from './sizing'
6
6
  export * from './spacing'
7
+ export * from './strokes'
@@ -0,0 +1,23 @@
1
+ import type { SceneNode } from '../types'
2
+
3
+ /**
4
+ * The stroke a frame counts inside its padding, per side: its visible INSIDE strokes when its
5
+ * strokes are included in layout, as Figma lays it out and as a CSS border takes room.
6
+ */
7
+ export function includedStrokeWeights(
8
+ node: SceneNode
9
+ ): Record<'top' | 'right' | 'bottom' | 'left', number> {
10
+ const stroke = node.strokes.find((paint) => paint.visible)
11
+ if (!node.strokesIncludedInLayout || stroke?.align !== 'INSIDE') {
12
+ return { top: 0, right: 0, bottom: 0, left: 0 }
13
+ }
14
+ if (!node.independentStrokeWeights) {
15
+ return { top: stroke.weight, right: stroke.weight, bottom: stroke.weight, left: stroke.weight }
16
+ }
17
+ return {
18
+ top: node.borderTopWeight,
19
+ right: node.borderRightWeight,
20
+ bottom: node.borderBottomWeight,
21
+ left: node.borderLeftWeight
22
+ }
23
+ }