@canvas-commons/2d 0.2.0

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 (183) hide show
  1. package/LICENSE +22 -0
  2. package/editor/index.css +40 -0
  3. package/editor/index.js +525 -0
  4. package/editor/index.js.map +1 -0
  5. package/lib/index-OvpZ-GsA.d.ts +5673 -0
  6. package/lib/index-OvpZ-GsA.d.ts.map +1 -0
  7. package/lib/index.d.ts +2 -0
  8. package/lib/index.js +10326 -0
  9. package/lib/index.js.map +1 -0
  10. package/lib/jsx-dev-runtime.d.ts +2 -0
  11. package/lib/jsx-dev-runtime.js +2 -0
  12. package/lib/jsx-runtime.d.ts +2 -0
  13. package/lib/jsx-runtime.js +28 -0
  14. package/lib/jsx-runtime.js.map +1 -0
  15. package/package.json +79 -0
  16. package/src/editor/NodeInspectorConfig.tsx +76 -0
  17. package/src/editor/PreviewOverlayConfig.tsx +65 -0
  18. package/src/editor/Provider.tsx +109 -0
  19. package/src/editor/SceneGraphTabConfig.tsx +87 -0
  20. package/src/editor/icons/CircleIcon.tsx +7 -0
  21. package/src/editor/icons/CodeIcon.tsx +8 -0
  22. package/src/editor/icons/CurveIcon.tsx +7 -0
  23. package/src/editor/icons/GridIcon.tsx +7 -0
  24. package/src/editor/icons/IconMap.ts +35 -0
  25. package/src/editor/icons/ImgIcon.tsx +8 -0
  26. package/src/editor/icons/LayoutIcon.tsx +9 -0
  27. package/src/editor/icons/LineIcon.tsx +7 -0
  28. package/src/editor/icons/NodeIcon.tsx +7 -0
  29. package/src/editor/icons/RayIcon.tsx +7 -0
  30. package/src/editor/icons/RectIcon.tsx +7 -0
  31. package/src/editor/icons/ShapeIcon.tsx +7 -0
  32. package/src/editor/icons/TxtIcon.tsx +8 -0
  33. package/src/editor/icons/VideoIcon.tsx +7 -0
  34. package/src/editor/icons/View2DIcon.tsx +10 -0
  35. package/src/editor/index.css +0 -0
  36. package/src/editor/index.ts +19 -0
  37. package/src/editor/shortcuts.ts +27 -0
  38. package/src/editor/tree/DetachedRoot.tsx +27 -0
  39. package/src/editor/tree/NodeElement.tsx +72 -0
  40. package/src/editor/tree/TreeElement.tsx +70 -0
  41. package/src/editor/tree/TreeRoot.tsx +10 -0
  42. package/src/editor/tree/ViewRoot.tsx +20 -0
  43. package/src/editor/tree/index.module.scss +45 -0
  44. package/src/editor/tree/index.ts +4 -0
  45. package/src/editor/tree/navigation.ts +145 -0
  46. package/src/editor/tsconfig.build.json +5 -0
  47. package/src/editor/tsconfig.json +12 -0
  48. package/src/editor/tsdoc.json +4 -0
  49. package/src/editor/utils/SignalSet.ts +37 -0
  50. package/src/editor/utils/index.ts +1 -0
  51. package/src/editor/vite-env.d.ts +1 -0
  52. package/src/lib/code/CodeCursor.ts +468 -0
  53. package/src/lib/code/CodeDiffer.ts +77 -0
  54. package/src/lib/code/CodeFragment.ts +96 -0
  55. package/src/lib/code/CodeHighlighter.ts +73 -0
  56. package/src/lib/code/CodeMetrics.ts +47 -0
  57. package/src/lib/code/CodeRange.test.ts +113 -0
  58. package/src/lib/code/CodeRange.ts +222 -0
  59. package/src/lib/code/CodeScope.ts +100 -0
  60. package/src/lib/code/CodeSelection.ts +28 -0
  61. package/src/lib/code/CodeSignal.ts +348 -0
  62. package/src/lib/code/CodeTokenizer.ts +54 -0
  63. package/src/lib/code/DefaultHighlightStyle.ts +98 -0
  64. package/src/lib/code/LezerHighlighter.ts +113 -0
  65. package/src/lib/code/diff.test.ts +311 -0
  66. package/src/lib/code/diff.ts +319 -0
  67. package/src/lib/code/extractRange.ts +125 -0
  68. package/src/lib/code/index.ts +13 -0
  69. package/src/lib/components/Bezier.ts +103 -0
  70. package/src/lib/components/Camera.ts +401 -0
  71. package/src/lib/components/Circle.ts +310 -0
  72. package/src/lib/components/Code.ts +532 -0
  73. package/src/lib/components/CubicBezier.ts +115 -0
  74. package/src/lib/components/Curve.ts +460 -0
  75. package/src/lib/components/Grid.ts +134 -0
  76. package/src/lib/components/Icon.ts +153 -0
  77. package/src/lib/components/Img.ts +328 -0
  78. package/src/lib/components/Knot.ts +156 -0
  79. package/src/lib/components/Latex.ts +537 -0
  80. package/src/lib/components/Layout.ts +1101 -0
  81. package/src/lib/components/Line.ts +394 -0
  82. package/src/lib/components/Node.ts +1941 -0
  83. package/src/lib/components/Path.ts +132 -0
  84. package/src/lib/components/Polygon.ts +266 -0
  85. package/src/lib/components/QuadBezier.ts +103 -0
  86. package/src/lib/components/Ray.ts +126 -0
  87. package/src/lib/components/Rect.ts +219 -0
  88. package/src/lib/components/SVG.ts +853 -0
  89. package/src/lib/components/Shape.ts +322 -0
  90. package/src/lib/components/Spline.ts +318 -0
  91. package/src/lib/components/Txt.test.tsx +81 -0
  92. package/src/lib/components/Txt.ts +204 -0
  93. package/src/lib/components/TxtLeaf.ts +210 -0
  94. package/src/lib/components/Video.ts +368 -0
  95. package/src/lib/components/View2D.ts +85 -0
  96. package/src/lib/components/__logs__/image-without-source.ts +18 -0
  97. package/src/lib/components/__logs__/line-without-points.ts +31 -0
  98. package/src/lib/components/__logs__/reactive-playback-rate.ts +22 -0
  99. package/src/lib/components/__logs__/spline-with-insufficient-knots.ts +25 -0
  100. package/src/lib/components/__tests__/Camera.test.tsx +73 -0
  101. package/src/lib/components/__tests__/children.test.tsx +142 -0
  102. package/src/lib/components/__tests__/clone.test.tsx +126 -0
  103. package/src/lib/components/__tests__/fontInheritance.test.tsx +102 -0
  104. package/src/lib/components/__tests__/generatorTest.ts +27 -0
  105. package/src/lib/components/__tests__/mockScene2D.ts +50 -0
  106. package/src/lib/components/__tests__/query.test.tsx +122 -0
  107. package/src/lib/components/__tests__/state.test.tsx +60 -0
  108. package/src/lib/components/index.ts +26 -0
  109. package/src/lib/components/types.ts +35 -0
  110. package/src/lib/curves/ArcSegment.ts +169 -0
  111. package/src/lib/curves/CircleSegment.ts +99 -0
  112. package/src/lib/curves/CubicBezierSegment.ts +80 -0
  113. package/src/lib/curves/CurveDrawingInfo.ts +11 -0
  114. package/src/lib/curves/CurvePoint.ts +15 -0
  115. package/src/lib/curves/CurveProfile.ts +28 -0
  116. package/src/lib/curves/KnotInfo.ts +10 -0
  117. package/src/lib/curves/LineSegment.ts +75 -0
  118. package/src/lib/curves/Polynomial.ts +355 -0
  119. package/src/lib/curves/Polynomial2D.ts +62 -0
  120. package/src/lib/curves/PolynomialSegment.ts +151 -0
  121. package/src/lib/curves/QuadBezierSegment.ts +66 -0
  122. package/src/lib/curves/Segment.ts +31 -0
  123. package/src/lib/curves/UniformPolynomialCurveSampler.ts +93 -0
  124. package/src/lib/curves/createCurveProfileLerp.ts +471 -0
  125. package/src/lib/curves/getBezierSplineProfile.ts +227 -0
  126. package/src/lib/curves/getCircleProfile.ts +86 -0
  127. package/src/lib/curves/getPathProfile.ts +177 -0
  128. package/src/lib/curves/getPointAtDistance.ts +21 -0
  129. package/src/lib/curves/getPolylineProfile.test.ts +21 -0
  130. package/src/lib/curves/getPolylineProfile.ts +88 -0
  131. package/src/lib/curves/getRectProfile.ts +138 -0
  132. package/src/lib/curves/index.ts +16 -0
  133. package/src/lib/decorators/canvasStyleSignal.ts +15 -0
  134. package/src/lib/decorators/colorSignal.ts +9 -0
  135. package/src/lib/decorators/compound.ts +85 -0
  136. package/src/lib/decorators/computed.ts +18 -0
  137. package/src/lib/decorators/defaultStyle.ts +15 -0
  138. package/src/lib/decorators/filtersSignal.ts +133 -0
  139. package/src/lib/decorators/index.ts +10 -0
  140. package/src/lib/decorators/initializers.ts +32 -0
  141. package/src/lib/decorators/nodeName.ts +13 -0
  142. package/src/lib/decorators/signal.test.ts +89 -0
  143. package/src/lib/decorators/signal.ts +348 -0
  144. package/src/lib/decorators/spacingSignal.ts +15 -0
  145. package/src/lib/decorators/transformSignals.test.ts +858 -0
  146. package/src/lib/decorators/transformSignals.ts +1633 -0
  147. package/src/lib/decorators/vector2Signal.ts +35 -0
  148. package/src/lib/globals.d.ts +2 -0
  149. package/src/lib/index.ts +9 -0
  150. package/src/lib/jsx-dev-runtime.ts +2 -0
  151. package/src/lib/jsx-runtime.ts +45 -0
  152. package/src/lib/morphers/PathMorpher.ts +8 -0
  153. package/src/lib/morphers/defaultMorpher.ts +43 -0
  154. package/src/lib/morphers/index.ts +4 -0
  155. package/src/lib/morphers/manimMorpher.ts +658 -0
  156. package/src/lib/parse-svg-path.d.ts +14 -0
  157. package/src/lib/partials/Filter.ts +185 -0
  158. package/src/lib/partials/Gradient.ts +103 -0
  159. package/src/lib/partials/Pattern.ts +35 -0
  160. package/src/lib/partials/RoughConfig.ts +180 -0
  161. package/src/lib/partials/ShaderConfig.ts +122 -0
  162. package/src/lib/partials/index.ts +5 -0
  163. package/src/lib/partials/types.ts +58 -0
  164. package/src/lib/scenes/Scene2D.ts +167 -0
  165. package/src/lib/scenes/index.ts +3 -0
  166. package/src/lib/scenes/makeScene2D.ts +19 -0
  167. package/src/lib/scenes/useScene2D.ts +6 -0
  168. package/src/lib/tsconfig.build.json +5 -0
  169. package/src/lib/tsconfig.json +11 -0
  170. package/src/lib/tsdoc.json +4 -0
  171. package/src/lib/utils/CanvasUtils.ts +304 -0
  172. package/src/lib/utils/PathDataBuilder.ts +320 -0
  173. package/src/lib/utils/diff.test.ts +453 -0
  174. package/src/lib/utils/diff.ts +148 -0
  175. package/src/lib/utils/index.ts +5 -0
  176. package/src/lib/utils/is.ts +11 -0
  177. package/src/lib/utils/makeSignalExtensions.ts +29 -0
  178. package/src/lib/utils/rough.ts +513 -0
  179. package/src/lib/utils/withDefaults.tsx +26 -0
  180. package/src/tsconfig.base.json +18 -0
  181. package/src/tsconfig.build.json +8 -0
  182. package/src/tsconfig.json +5 -0
  183. package/tsconfig.project.json +7 -0
@@ -0,0 +1,1941 @@
1
+ import {
2
+ BBox,
3
+ ColorSignal,
4
+ DependencyContext,
5
+ PossibleColor,
6
+ PossibleSpacing,
7
+ PossibleVector2,
8
+ Promisable,
9
+ ReferenceReceiver,
10
+ Signal,
11
+ SignalValue,
12
+ SimpleSignal,
13
+ SimpleVector2Signal,
14
+ SpacingSignal,
15
+ ThreadGenerator,
16
+ TimingFunction,
17
+ UNIFORM_DESTINATION_MATRIX,
18
+ UNIFORM_SOURCE_MATRIX,
19
+ UNIFORM_TIME,
20
+ Vector2,
21
+ Vector2Signal,
22
+ all,
23
+ clamp,
24
+ createSignal,
25
+ easeInOutCubic,
26
+ isReactive,
27
+ threadable,
28
+ transformScalar,
29
+ unwrap,
30
+ useLogger,
31
+ } from '@canvas-commons/core';
32
+ import {
33
+ NODE_NAME,
34
+ cloneable,
35
+ colorSignal,
36
+ computed,
37
+ getPropertiesOf,
38
+ initial,
39
+ initializeSignals,
40
+ inspectable,
41
+ nodeName,
42
+ parser,
43
+ signal,
44
+ vector2Signal,
45
+ wrapper,
46
+ } from '../decorators';
47
+ import {FiltersSignal, filtersSignal} from '../decorators/filtersSignal';
48
+ import {spacingSignal} from '../decorators/spacingSignal';
49
+ import {
50
+ PositionSignal,
51
+ RotationSignal,
52
+ ScaleSignal,
53
+ positionSignal,
54
+ rotationSignal,
55
+ scaleSignal,
56
+ } from '../decorators/transformSignals';
57
+ import {Filter} from '../partials';
58
+ import {
59
+ PossibleShaderConfig,
60
+ ShaderConfig,
61
+ parseShader,
62
+ } from '../partials/ShaderConfig';
63
+ import {useScene2D} from '../scenes/useScene2D';
64
+ import {drawLine} from '../utils';
65
+ import type {ComponentChild, ComponentChildren, NodeConstructor} from './types';
66
+ import type {View2D} from './View2D';
67
+
68
+ export type NodeState = NodeProps & Record<string, any>;
69
+
70
+ export interface NodeProps {
71
+ ref?: ReferenceReceiver<any>;
72
+ children?: SignalValue<ComponentChildren>;
73
+ /**
74
+ * @deprecated Use {@link children} instead.
75
+ */
76
+ spawner?: SignalValue<ComponentChildren>;
77
+ key?: string;
78
+
79
+ x?: SignalValue<number>;
80
+ y?: SignalValue<number>;
81
+ position?: SignalValue<PossibleVector2>;
82
+ rotation?: SignalValue<number>;
83
+ scaleX?: SignalValue<number>;
84
+ scaleY?: SignalValue<number>;
85
+ scale?: SignalValue<PossibleVector2>;
86
+ skewX?: SignalValue<number>;
87
+ skewY?: SignalValue<number>;
88
+ skew?: SignalValue<PossibleVector2>;
89
+ zIndex?: SignalValue<number>;
90
+
91
+ opacity?: SignalValue<number>;
92
+ filters?: SignalValue<Filter[]>;
93
+
94
+ shadowColor?: SignalValue<PossibleColor>;
95
+ shadowBlur?: SignalValue<number>;
96
+ shadowOffsetX?: SignalValue<number>;
97
+ shadowOffsetY?: SignalValue<number>;
98
+ shadowOffset?: SignalValue<PossibleVector2>;
99
+
100
+ cache?: SignalValue<boolean>;
101
+ /**
102
+ * {@inheritDoc Node.cachePadding}
103
+ */
104
+ cachePaddingTop?: SignalValue<number>;
105
+ /**
106
+ * {@inheritDoc Node.cachePadding}
107
+ */
108
+ cachePaddingBottom?: SignalValue<number>;
109
+ /**
110
+ * {@inheritDoc Node.cachePadding}
111
+ */
112
+ cachePaddingLeft?: SignalValue<number>;
113
+ /**
114
+ * {@inheritDoc Node.cachePadding}
115
+ */
116
+ cachePaddingRight?: SignalValue<number>;
117
+ /**
118
+ * {@inheritDoc Node.cachePadding}
119
+ */
120
+ cachePadding?: SignalValue<PossibleSpacing>;
121
+
122
+ composite?: SignalValue<boolean>;
123
+ compositeOperation?: SignalValue<GlobalCompositeOperation>;
124
+ /**
125
+ * @experimental
126
+ */
127
+ shaders?: PossibleShaderConfig;
128
+ }
129
+
130
+ @nodeName('Node')
131
+ export class Node implements Promisable<Node> {
132
+ /**
133
+ * @internal
134
+ */
135
+ declare public readonly [NODE_NAME]: string;
136
+ declare public isClass: boolean;
137
+
138
+ /**
139
+ * Represents the position of this node in local space of its parent.
140
+ *
141
+ * @example
142
+ * Initializing the position:
143
+ * ```tsx
144
+ * // with a possible vector:
145
+ * <Node position={[1, 2]} />
146
+ * // with individual components:
147
+ * <Node x={1} y={2} />
148
+ * ```
149
+ *
150
+ * Accessing the position:
151
+ * ```tsx
152
+ * // retrieving the vector:
153
+ * const position = node.position();
154
+ * // retrieving an individual component:
155
+ * const x = node.position.x();
156
+ * ```
157
+ *
158
+ * Setting the position:
159
+ * ```tsx
160
+ * // with a possible vector:
161
+ * node.position([1, 2]);
162
+ * node.position(() => [1, 2]);
163
+ * // with individual components:
164
+ * node.position.x(1);
165
+ * node.position.x(() => 1);
166
+ * ```
167
+ */
168
+ @positionSignal()
169
+ declare public readonly position: PositionSignal<this>;
170
+
171
+ public get x() {
172
+ return this.position.x as SimpleSignal<number, this>;
173
+ }
174
+ public get y() {
175
+ return this.position.y as SimpleSignal<number, this>;
176
+ }
177
+
178
+ /**
179
+ * A helper signal for operating on the position in world space.
180
+ *
181
+ * @remarks
182
+ * Retrieving the position using this signal returns the position in world
183
+ * space. Similarly, setting the position using this signal transforms the
184
+ * new value to local space.
185
+ *
186
+ * If the new value is a function, the position of this node will be
187
+ * continuously updated to always match the position returned by the function.
188
+ * This can be useful to "pin" the node in a specific place or to make it
189
+ * follow another node's position.
190
+ *
191
+ * Unlike {@link position}, this signal is not compound - it doesn't contain
192
+ * separate signals for the `x` and `y` components.
193
+ *
194
+ * @deprecated Use `position.abs` instead.
195
+ */
196
+ @wrapper(Vector2)
197
+ @cloneable(false)
198
+ @signal()
199
+ declare public readonly absolutePosition: SimpleVector2Signal<this>;
200
+
201
+ protected getAbsolutePosition(): Vector2 {
202
+ return this.position.abs();
203
+ }
204
+
205
+ protected setAbsolutePosition(value: SignalValue<PossibleVector2>) {
206
+ this.position.abs(value);
207
+ }
208
+
209
+ /**
210
+ * Represents the rotation (in degrees) of this node relative to its parent.
211
+ */
212
+ @initial(0)
213
+ @rotationSignal()
214
+ declare public readonly rotation: RotationSignal<this>;
215
+
216
+ /**
217
+ * A helper signal for operating on the rotation in world space.
218
+ *
219
+ * @remarks
220
+ * Retrieving the rotation using this signal returns the rotation in world
221
+ * space. Similarly, setting the rotation using this signal transforms the
222
+ * new value to local space.
223
+ *
224
+ * If the new value is a function, the rotation of this node will be
225
+ * continuously updated to always match the rotation returned by the function.
226
+ *
227
+ * @deprecated Use `rotation.abs` instead.
228
+ */
229
+ @cloneable(false)
230
+ @signal()
231
+ declare public readonly absoluteRotation: SimpleSignal<number, this>;
232
+
233
+ protected getAbsoluteRotation() {
234
+ return this.rotation.abs();
235
+ }
236
+
237
+ protected setAbsoluteRotation(value: SignalValue<number>) {
238
+ this.rotation.abs(value);
239
+ }
240
+
241
+ /**
242
+ * Represents the scale of this node in local space of its parent.
243
+ *
244
+ * @example
245
+ * Initializing the scale:
246
+ * ```tsx
247
+ * // with a possible vector:
248
+ * <Node scale={[1, 2]} />
249
+ * // with individual components:
250
+ * <Node scaleX={1} scaleY={2} />
251
+ * ```
252
+ *
253
+ * Accessing the scale:
254
+ * ```tsx
255
+ * // retrieving the vector:
256
+ * const scale = node.scale();
257
+ * // retrieving an individual component:
258
+ * const scaleX = node.scale.x();
259
+ * ```
260
+ *
261
+ * Setting the scale:
262
+ * ```tsx
263
+ * // with a possible vector:
264
+ * node.scale([1, 2]);
265
+ * node.scale(() => [1, 2]);
266
+ * // with individual components:
267
+ * node.scale.x(1);
268
+ * node.scale.x(() => 1);
269
+ * ```
270
+ */
271
+ @initial(Vector2.one)
272
+ @scaleSignal('scale')
273
+ declare public readonly scale: ScaleSignal<this>;
274
+
275
+ /**
276
+ * Represents the skew of this node in local space of its parent.
277
+ *
278
+ * @example
279
+ * Initializing the skew:
280
+ * ```tsx
281
+ * // with a possible vector:
282
+ * <Node skew={[40, 20]} />
283
+ * // with individual components:
284
+ * <Node skewX={40} skewY={20} />
285
+ * ```
286
+ *
287
+ * Accessing the skew:
288
+ * ```tsx
289
+ * // retrieving the vector:
290
+ * const skew = node.skew();
291
+ * // retrieving an individual component:
292
+ * const skewX = node.skew.x();
293
+ * ```
294
+ *
295
+ * Setting the skew:
296
+ * ```tsx
297
+ * // with a possible vector:
298
+ * node.skew([40, 20]);
299
+ * node.skew(() => [40, 20]);
300
+ * // with individual components:
301
+ * node.skew.x(40);
302
+ * node.skew.x(() => 40);
303
+ * ```
304
+ */
305
+ @initial(Vector2.zero)
306
+ @vector2Signal('skew')
307
+ declare public readonly skew: Vector2Signal<this>;
308
+
309
+ /**
310
+ * A helper signal for operating on the scale in world space.
311
+ *
312
+ * @remarks
313
+ * Retrieving the scale using this signal returns the scale in world space.
314
+ * Similarly, setting the scale using this signal transforms the new value to
315
+ * local space.
316
+ *
317
+ * If the new value is a function, the scale of this node will be continuously
318
+ * updated to always match the position returned by the function.
319
+ *
320
+ * Unlike {@link scale}, this signal is not compound - it doesn't contain
321
+ * separate signals for the `x` and `y` components.
322
+ *
323
+ * @deprecated Use `scale.abs` instead.
324
+ */
325
+ @wrapper(Vector2)
326
+ @cloneable(false)
327
+ @signal()
328
+ declare public readonly absoluteScale: SimpleVector2Signal<this>;
329
+
330
+ protected getAbsoluteScale(): Vector2 {
331
+ return this.scale.abs();
332
+ }
333
+
334
+ protected setAbsoluteScale(value: SignalValue<PossibleVector2>) {
335
+ this.scale.abs(value);
336
+ }
337
+
338
+ @initial(0)
339
+ @signal()
340
+ declare public readonly zIndex: SimpleSignal<number, this>;
341
+
342
+ @initial(false)
343
+ @signal()
344
+ declare public readonly cache: SimpleSignal<boolean, this>;
345
+
346
+ /**
347
+ * Controls the padding of the cached canvas used by this node.
348
+ *
349
+ * @remarks
350
+ * By default, the size of the cache is determined based on the bounding box
351
+ * of the node and its children. That includes effects such as stroke or
352
+ * shadow. This property can be used to expand the cache area further.
353
+ * Usually used to account for custom effects created by {@link shaders}.
354
+ */
355
+ @spacingSignal('cachePadding')
356
+ declare public readonly cachePadding: SpacingSignal<this>;
357
+
358
+ @initial(false)
359
+ @signal()
360
+ declare public readonly composite: SimpleSignal<boolean, this>;
361
+
362
+ @initial('source-over')
363
+ @signal()
364
+ declare public readonly compositeOperation: SimpleSignal<
365
+ GlobalCompositeOperation,
366
+ this
367
+ >;
368
+
369
+ private readonly compositeOverride = createSignal(0);
370
+
371
+ @threadable()
372
+ protected *tweenCompositeOperation(
373
+ value: SignalValue<GlobalCompositeOperation>,
374
+ time: number,
375
+ timingFunction: TimingFunction,
376
+ ) {
377
+ const nextValue = unwrap(value);
378
+ if (nextValue === 'source-over') {
379
+ yield* this.compositeOverride(1, time, timingFunction);
380
+ this.compositeOverride(0);
381
+ this.compositeOperation(nextValue);
382
+ } else {
383
+ this.compositeOperation(nextValue);
384
+ this.compositeOverride(1);
385
+ yield* this.compositeOverride(0, time, timingFunction);
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Represents the opacity of this node in the range 0-1.
391
+ *
392
+ * @remarks
393
+ * The value is clamped to the range 0-1.
394
+ */
395
+ @initial(1)
396
+ @parser((value: number) => clamp(0, 1, value))
397
+ @signal()
398
+ declare public readonly opacity: SimpleSignal<number, this>;
399
+
400
+ @computed()
401
+ public absoluteOpacity(): number {
402
+ return (this.parent()?.absoluteOpacity() ?? 1) * this.opacity();
403
+ }
404
+
405
+ @filtersSignal()
406
+ declare public readonly filters: FiltersSignal<this>;
407
+
408
+ @initial('#0000')
409
+ @colorSignal()
410
+ declare public readonly shadowColor: ColorSignal<this>;
411
+
412
+ @initial(0)
413
+ @signal()
414
+ declare public readonly shadowBlur: SimpleSignal<number, this>;
415
+
416
+ @vector2Signal('shadowOffset')
417
+ declare public readonly shadowOffset: Vector2Signal<this>;
418
+
419
+ /**
420
+ * @experimental
421
+ */
422
+ @initial([])
423
+ @parser(parseShader)
424
+ @signal()
425
+ declare public readonly shaders: Signal<
426
+ PossibleShaderConfig,
427
+ ShaderConfig[],
428
+ this
429
+ >;
430
+
431
+ @computed()
432
+ protected hasFilters(): boolean {
433
+ return !!this.filters().find(filter => filter.isActive());
434
+ }
435
+
436
+ @computed()
437
+ protected hasShadow() {
438
+ return (
439
+ !!this.shadowColor() &&
440
+ (this.shadowBlur() > 0 ||
441
+ this.shadowOffset.x() !== 0 ||
442
+ this.shadowOffset.y() !== 0)
443
+ );
444
+ }
445
+
446
+ @computed()
447
+ protected filterString(): string {
448
+ let filters = '';
449
+ const matrix = this.compositeToWorld();
450
+ for (const filter of this.filters()) {
451
+ if (filter.isActive()) {
452
+ filters += ' ' + filter.serialize(matrix);
453
+ }
454
+ }
455
+
456
+ return filters;
457
+ }
458
+
459
+ /**
460
+ * @deprecated Use {@link children} instead.
461
+ */
462
+ @inspectable(false)
463
+ @cloneable(false)
464
+ @signal()
465
+ declare protected readonly spawner: SimpleSignal<ComponentChildren, this>;
466
+ protected getSpawner(): ComponentChildren {
467
+ return this.children();
468
+ }
469
+ protected setSpawner(value: SignalValue<ComponentChildren>) {
470
+ this.children(value);
471
+ }
472
+
473
+ @inspectable(false)
474
+ @cloneable(false)
475
+ @signal()
476
+ declare public readonly children: Signal<ComponentChildren, Node[], this>;
477
+ protected setChildren(value: SignalValue<ComponentChildren>) {
478
+ if (this.children.context.raw() === value) {
479
+ return;
480
+ }
481
+
482
+ this.children.context.setter(value);
483
+ if (!isReactive(value)) {
484
+ this.spawnChildren(false, value);
485
+ } else if (!this.hasSpawnedChildren) {
486
+ for (const oldChild of this.realChildren) {
487
+ oldChild.parent(null);
488
+ }
489
+ }
490
+ }
491
+ protected getChildren(): Node[] {
492
+ this.children.context.getter();
493
+ return this.spawnedChildren();
494
+ }
495
+
496
+ @computed()
497
+ protected spawnedChildren(): Node[] {
498
+ const children = this.children.context.getter();
499
+ if (isReactive(this.children.context.raw())) {
500
+ this.spawnChildren(true, children);
501
+ }
502
+ return this.realChildren;
503
+ }
504
+
505
+ @computed()
506
+ protected sortedChildren(): Node[] {
507
+ return [...this.children()].sort((a, b) =>
508
+ Math.sign(a.zIndex() - b.zIndex()),
509
+ );
510
+ }
511
+
512
+ protected view2D: View2D;
513
+ private stateStack: NodeState[] = [];
514
+ protected realChildren: Node[] = [];
515
+ protected hasSpawnedChildren = false;
516
+ private unregister: () => void;
517
+ public readonly parent = createSignal<Node | null>(null);
518
+ public readonly properties = getPropertiesOf(this);
519
+ public readonly key: string;
520
+ public readonly creationStack?: string;
521
+
522
+ public constructor({children, spawner, key, ...rest}: NodeProps) {
523
+ const scene = useScene2D();
524
+ [this.key, this.unregister] = scene.registerNode(this, key);
525
+ this.view2D = scene.getView();
526
+ this.creationStack = new Error().stack;
527
+ initializeSignals(this, rest);
528
+ if (spawner) {
529
+ useLogger().warn({
530
+ message: 'Node.spawner() has been deprecated.',
531
+ remarks: 'Use <code>Node.children()</code> instead.',
532
+ inspect: this.key,
533
+ stack: new Error().stack,
534
+ });
535
+ }
536
+ this.children(spawner ?? children);
537
+ }
538
+
539
+ /**
540
+ * Get the local-to-world matrix for this node.
541
+ *
542
+ * @remarks
543
+ * This matrix transforms vectors from local space of this node to world
544
+ * space.
545
+ *
546
+ * @example
547
+ * Calculate the absolute position of a point located 200 pixels to the right
548
+ * of the node:
549
+ * ```ts
550
+ * const local = new Vector2(0, 200);
551
+ * const world = local.transformAsPoint(node.localToWorld());
552
+ * ```
553
+ */
554
+ @computed()
555
+ public localToWorld(): DOMMatrix {
556
+ const parent = this.parent();
557
+ return parent
558
+ ? parent.localToWorld().multiply(this.localToParent())
559
+ : this.localToParent();
560
+ }
561
+
562
+ /**
563
+ * Get the world-to-local matrix for this node.
564
+ *
565
+ * @remarks
566
+ * This matrix transforms vectors from world space to local space of this
567
+ * node.
568
+ *
569
+ * @example
570
+ * Calculate the position relative to this node for a point located in the
571
+ * top-left corner of the screen:
572
+ * ```ts
573
+ * const world = new Vector2(0, 0);
574
+ * const local = world.transformAsPoint(node.worldToLocal());
575
+ * ```
576
+ */
577
+ @computed()
578
+ public worldToLocal() {
579
+ return this.localToWorld().inverse();
580
+ }
581
+
582
+ /**
583
+ * Get the world-to-parent matrix for this node.
584
+ *
585
+ * @remarks
586
+ * This matrix transforms vectors from world space to local space of this
587
+ * node's parent.
588
+ */
589
+ @computed()
590
+ public worldToParent(): DOMMatrix {
591
+ return this.parent()?.worldToLocal() ?? new DOMMatrix();
592
+ }
593
+
594
+ /**
595
+ * Get the parent-to-world matrix for this node.
596
+ *
597
+ * @remarks
598
+ * This matrix transforms vectors from local space of this node's parent to
599
+ * world space.
600
+ */
601
+ @computed()
602
+ public parentToWorld(): DOMMatrix {
603
+ return this.parent()?.localToWorld() ?? new DOMMatrix();
604
+ }
605
+
606
+ /**
607
+ * Get the local-to-parent matrix for this node.
608
+ *
609
+ * @remarks
610
+ * This matrix transforms vectors from local space of this node to local space
611
+ * of this node's parent.
612
+ */
613
+ @computed()
614
+ public localToParent(): DOMMatrix {
615
+ const matrix = new DOMMatrix();
616
+ matrix.translateSelf(this.x(), this.y());
617
+ matrix.rotateSelf(0, 0, this.rotation());
618
+ matrix.scaleSelf(this.scale.x(), this.scale.y());
619
+ matrix.skewXSelf(this.skew.x());
620
+ matrix.skewYSelf(this.skew.y());
621
+
622
+ return matrix;
623
+ }
624
+
625
+ /**
626
+ * A matrix mapping composite space to world space.
627
+ *
628
+ * @remarks
629
+ * Certain effects such as blur and shadows ignore the current transformation.
630
+ * This matrix can be used to transform their parameters so that the effect
631
+ * appears relative to the closest composite root.
632
+ */
633
+ @computed()
634
+ public compositeToWorld(): DOMMatrix {
635
+ return this.compositeRoot()?.localToWorld() ?? new DOMMatrix();
636
+ }
637
+
638
+ @computed()
639
+ protected compositeRoot(): Node | null {
640
+ if (this.composite()) {
641
+ return this;
642
+ }
643
+
644
+ return this.parent()?.compositeRoot() ?? null;
645
+ }
646
+
647
+ @computed()
648
+ public compositeToLocal() {
649
+ const root = this.compositeRoot();
650
+ if (root) {
651
+ const worldToLocal = this.worldToLocal();
652
+ worldToLocal.m44 = 1;
653
+ return root.localToWorld().multiply(worldToLocal);
654
+ }
655
+ return new DOMMatrix();
656
+ }
657
+
658
+ public view(): View2D {
659
+ return this.view2D;
660
+ }
661
+
662
+ /**
663
+ * Add the given node(s) as the children of this node.
664
+ *
665
+ * @remarks
666
+ * The nodes will be appended at the end of the children list.
667
+ *
668
+ * @example
669
+ * ```tsx
670
+ * const node = <Layout />;
671
+ * node.add(<Rect />);
672
+ * node.add(<Circle />);
673
+ * ```
674
+ * Result:
675
+ * ```mermaid
676
+ * graph TD;
677
+ * layout([Layout])
678
+ * circle([Circle])
679
+ * rect([Rect])
680
+ * layout-->rect;
681
+ * layout-->circle;
682
+ * ```
683
+ *
684
+ * @param node - A node or an array of nodes to append.
685
+ */
686
+ public add(node: ComponentChildren): this {
687
+ return this.insert(node, Infinity);
688
+ }
689
+
690
+ /**
691
+ * Insert the given node(s) at the specified index in the children list.
692
+ *
693
+ * @example
694
+ * ```tsx
695
+ * const node = (
696
+ * <Layout>
697
+ * <Rect />
698
+ * <Circle />
699
+ * </Layout>
700
+ * );
701
+ *
702
+ * node.insert(<Txt />, 1);
703
+ * ```
704
+ *
705
+ * Result:
706
+ * ```mermaid
707
+ * graph TD;
708
+ * layout([Layout])
709
+ * circle([Circle])
710
+ * text([Text])
711
+ * rect([Rect])
712
+ * layout-->rect;
713
+ * layout-->text;
714
+ * layout-->circle;
715
+ * ```
716
+ *
717
+ * @param node - A node or an array of nodes to insert.
718
+ * @param index - An index at which to insert the node(s).
719
+ */
720
+ public insert(node: ComponentChildren, index = 0): this {
721
+ const array: ComponentChild[] = Array.isArray(node) ? node : [node];
722
+ if (array.length === 0) {
723
+ return this;
724
+ }
725
+
726
+ const children = this.children();
727
+ const newChildren = children.slice(0, index);
728
+
729
+ for (const node of array) {
730
+ if (node instanceof Node) {
731
+ newChildren.push(node);
732
+ node.remove();
733
+ node.parent(this);
734
+ }
735
+ }
736
+
737
+ newChildren.push(...children.slice(index));
738
+ this.setParsedChildren(newChildren);
739
+
740
+ return this;
741
+ }
742
+
743
+ /**
744
+ * Remove this node from the tree.
745
+ */
746
+ public remove(): this {
747
+ const current = this.parent();
748
+ if (current === null) {
749
+ return this;
750
+ }
751
+
752
+ current.removeChild(this);
753
+ this.parent(null);
754
+ return this;
755
+ }
756
+
757
+ /**
758
+ * Rearrange this node in relation to its siblings.
759
+ *
760
+ * @remarks
761
+ * Children are rendered starting from the beginning of the children list.
762
+ * We can change the rendering order by rearranging said list.
763
+ *
764
+ * A positive `by` arguments move the node up (it will be rendered on top of
765
+ * the elements it has passed). Negative values move it down.
766
+ *
767
+ * @param by - Number of places by which the node should be moved.
768
+ */
769
+ public move(by = 1): this {
770
+ const parent = this.parent();
771
+ if (by === 0 || !parent) {
772
+ return this;
773
+ }
774
+
775
+ const children = parent.children();
776
+ const newChildren: Node[] = [];
777
+
778
+ if (by > 0) {
779
+ for (let i = 0; i < children.length; i++) {
780
+ const child = children[i];
781
+ if (child === this) {
782
+ const target = i + by;
783
+ for (; i < target && i + 1 < children.length; i++) {
784
+ newChildren[i] = children[i + 1];
785
+ }
786
+ }
787
+ newChildren[i] = child;
788
+ }
789
+ } else {
790
+ for (let i = children.length - 1; i >= 0; i--) {
791
+ const child = children[i];
792
+ if (child === this) {
793
+ const target = i + by;
794
+ for (; i > target && i > 0; i--) {
795
+ newChildren[i] = children[i - 1];
796
+ }
797
+ }
798
+ newChildren[i] = child;
799
+ }
800
+ }
801
+
802
+ parent.setParsedChildren(newChildren);
803
+
804
+ return this;
805
+ }
806
+
807
+ /**
808
+ * Move the node up in relation to its siblings.
809
+ *
810
+ * @remarks
811
+ * The node will exchange places with the sibling right above it (if any) and
812
+ * from then on will be rendered on top of it.
813
+ */
814
+ public moveUp(): this {
815
+ return this.move(1);
816
+ }
817
+
818
+ /**
819
+ * Move the node down in relation to its siblings.
820
+ *
821
+ * @remarks
822
+ * The node will exchange places with the sibling right below it (if any) and
823
+ * from then on will be rendered under it.
824
+ */
825
+ public moveDown(): this {
826
+ return this.move(-1);
827
+ }
828
+
829
+ /**
830
+ * Move the node to the top in relation to its siblings.
831
+ *
832
+ * @remarks
833
+ * The node will be placed at the end of the children list and from then on
834
+ * will be rendered on top of all of its siblings.
835
+ */
836
+ public moveToTop(): this {
837
+ return this.move(Infinity);
838
+ }
839
+
840
+ /**
841
+ * Move the node to the bottom in relation to its siblings.
842
+ *
843
+ * @remarks
844
+ * The node will be placed at the beginning of the children list and from then
845
+ * on will be rendered below all of its siblings.
846
+ */
847
+ public moveToBottom(): this {
848
+ return this.move(-Infinity);
849
+ }
850
+
851
+ /**
852
+ * Move the node to the provided position relative to its siblings.
853
+ *
854
+ * @remarks
855
+ * If the node is getting moved to a lower position, it will be placed below
856
+ * the sibling that's currently at the provided index (if any).
857
+ * If the node is getting moved to a higher position, it will be placed above
858
+ * the sibling that's currently at the provided index (if any).
859
+ *
860
+ * @param index - The index to move the node to.
861
+ */
862
+ public moveTo(index: number): this {
863
+ const parent = this.parent();
864
+ if (!parent) {
865
+ return this;
866
+ }
867
+
868
+ const currentIndex = parent.children().indexOf(this);
869
+ const by = index - currentIndex;
870
+
871
+ return this.move(by);
872
+ }
873
+
874
+ /**
875
+ * Move the node below the provided node in the parent's layout.
876
+ *
877
+ * @remarks
878
+ * The node will be moved below the provided node and from then on will be
879
+ * rendered below it. By default, if the node is already positioned lower than
880
+ * the sibling node, it will not get moved.
881
+ *
882
+ * @param node - The sibling node below which to move.
883
+ * @param directlyBelow - Whether the node should be positioned directly below
884
+ * the sibling. When true, will move the node even if
885
+ * it is already positioned below the sibling.
886
+ */
887
+ public moveBelow(node: Node, directlyBelow = false): this {
888
+ const parent = this.parent();
889
+ if (!parent) {
890
+ return this;
891
+ }
892
+
893
+ if (node.parent() !== parent) {
894
+ useLogger().error(
895
+ "Cannot position nodes relative to each other if they don't belong to the same parent.",
896
+ );
897
+ return this;
898
+ }
899
+
900
+ const children = parent.children();
901
+ const ownIndex = children.indexOf(this);
902
+ const otherIndex = children.indexOf(node);
903
+
904
+ if (!directlyBelow && ownIndex < otherIndex) {
905
+ // Nothing to do if the node is already positioned below the target node.
906
+ // We could move the node so it's directly below the sibling node, but
907
+ // that might suddenly move it on top of other nodes. This is likely
908
+ // not what the user wanted to happen when calling this method.
909
+ return this;
910
+ }
911
+
912
+ const by = otherIndex - ownIndex - 1;
913
+
914
+ return this.move(by);
915
+ }
916
+
917
+ /**
918
+ * Move the node above the provided node in the parent's layout.
919
+ *
920
+ * @remarks
921
+ * The node will be moved above the provided node and from then on will be
922
+ * rendered on top of it. By default, if the node is already positioned
923
+ * higher than the sibling node, it will not get moved.
924
+ *
925
+ * @param node - The sibling node below which to move.
926
+ * @param directlyAbove - Whether the node should be positioned directly above the
927
+ * sibling. When true, will move the node even if it is
928
+ * already positioned above the sibling.
929
+ */
930
+ public moveAbove(node: Node, directlyAbove = false): this {
931
+ const parent = this.parent();
932
+ if (!parent) {
933
+ return this;
934
+ }
935
+
936
+ if (node.parent() !== parent) {
937
+ useLogger().error(
938
+ "Cannot position nodes relative to each other if they don't belong to the same parent.",
939
+ );
940
+ return this;
941
+ }
942
+
943
+ const children = parent.children();
944
+ const ownIndex = children.indexOf(this);
945
+ const otherIndex = children.indexOf(node);
946
+
947
+ if (!directlyAbove && ownIndex > otherIndex) {
948
+ // Nothing to do if the node is already positioned above the target node.
949
+ // We could move the node so it's directly above the sibling node, but
950
+ // that might suddenly move it below other nodes. This is likely not what
951
+ // the user wanted to happen when calling this method.
952
+ return this;
953
+ }
954
+
955
+ const by = otherIndex - ownIndex + 1;
956
+
957
+ return this.move(by);
958
+ }
959
+
960
+ /**
961
+ * Change the parent of this node while keeping the absolute transform.
962
+ *
963
+ * @remarks
964
+ * After performing this operation, the node will stay in the same place
965
+ * visually, but its parent will be changed.
966
+ *
967
+ * @param newParent - The new parent of this node.
968
+ */
969
+ public reparent(newParent: Node): this {
970
+ const position = this.position.abs();
971
+ const rotation = this.rotation.abs();
972
+ const scale = this.scale.abs();
973
+ newParent.add(this);
974
+ this.position.abs(position);
975
+ this.rotation.abs(rotation);
976
+ this.scale.abs(scale);
977
+
978
+ return this;
979
+ }
980
+
981
+ /**
982
+ * Remove all children of this node.
983
+ */
984
+ public removeChildren(): this {
985
+ for (const oldChild of this.realChildren) {
986
+ oldChild.parent(null);
987
+ }
988
+ this.setParsedChildren([]);
989
+
990
+ return this;
991
+ }
992
+
993
+ /**
994
+ * Get the current children of this node.
995
+ *
996
+ * @remarks
997
+ * Unlike {@link children}, this method does not have any side effects.
998
+ * It does not register the `children` signal as a dependency, and it does not
999
+ * spawn any children. It can be used to safely retrieve the current state of
1000
+ * the scene graph for debugging purposes.
1001
+ */
1002
+ public peekChildren(): readonly Node[] {
1003
+ return this.realChildren;
1004
+ }
1005
+
1006
+ /**
1007
+ * Find all descendants of this node that match the given predicate.
1008
+ *
1009
+ * @param predicate - A function that returns true if the node matches.
1010
+ */
1011
+ public findAll<T extends Node>(predicate: (node: any) => node is T): T[];
1012
+ /**
1013
+ * Find all descendants of this node that match the given predicate.
1014
+ *
1015
+ * @param predicate - A function that returns true if the node matches.
1016
+ */
1017
+ public findAll<T extends Node = Node>(predicate: (node: any) => boolean): T[];
1018
+ public findAll<T extends Node>(predicate: (node: any) => node is T): T[] {
1019
+ const result: T[] = [];
1020
+ const queue = this.reversedChildren();
1021
+ while (queue.length > 0) {
1022
+ const node = queue.pop()!;
1023
+ if (predicate(node)) {
1024
+ result.push(node);
1025
+ }
1026
+ const children = node.children();
1027
+ for (let i = children.length - 1; i >= 0; i--) {
1028
+ queue.push(children[i]);
1029
+ }
1030
+ }
1031
+
1032
+ return result;
1033
+ }
1034
+
1035
+ /**
1036
+ * Find the first descendant of this node that matches the given predicate.
1037
+ *
1038
+ * @param predicate - A function that returns true if the node matches.
1039
+ */
1040
+ public findFirst<T extends Node>(
1041
+ predicate: (node: Node) => node is T,
1042
+ ): T | null;
1043
+ /**
1044
+ * Find the first descendant of this node that matches the given predicate.
1045
+ *
1046
+ * @param predicate - A function that returns true if the node matches.
1047
+ */
1048
+ public findFirst<T extends Node = Node>(
1049
+ predicate: (node: Node) => boolean,
1050
+ ): T | null;
1051
+ public findFirst<T extends Node>(
1052
+ predicate: (node: Node) => node is T,
1053
+ ): T | null {
1054
+ const queue = this.reversedChildren();
1055
+ while (queue.length > 0) {
1056
+ const node = queue.pop()!;
1057
+ if (predicate(node)) {
1058
+ return node;
1059
+ }
1060
+ const children = node.children();
1061
+ for (let i = children.length - 1; i >= 0; i--) {
1062
+ queue.push(children[i]);
1063
+ }
1064
+ }
1065
+
1066
+ return null;
1067
+ }
1068
+
1069
+ /**
1070
+ * Find the last descendant of this node that matches the given predicate.
1071
+ *
1072
+ * @param predicate - A function that returns true if the node matches.
1073
+ */
1074
+ public findLast<T extends Node>(
1075
+ predicate: (node: Node) => node is T,
1076
+ ): T | null;
1077
+ /**
1078
+ * Find the last descendant of this node that matches the given predicate.
1079
+ *
1080
+ * @param predicate - A function that returns true if the node matches.
1081
+ */
1082
+ public findLast<T extends Node = Node>(
1083
+ predicate: (node: Node) => boolean,
1084
+ ): T | null;
1085
+ public findLast<T extends Node>(
1086
+ predicate: (node: Node) => node is T,
1087
+ ): T | null {
1088
+ const search: Node[] = [];
1089
+ const queue = this.reversedChildren();
1090
+
1091
+ while (queue.length > 0) {
1092
+ const node = queue.pop()!;
1093
+ search.push(node);
1094
+ const children = node.children();
1095
+ for (let i = children.length - 1; i >= 0; i--) {
1096
+ queue.push(children[i]);
1097
+ }
1098
+ }
1099
+
1100
+ while (search.length > 0) {
1101
+ const node = search.pop()!;
1102
+ if (predicate(node)) {
1103
+ return node;
1104
+ }
1105
+ }
1106
+
1107
+ return null;
1108
+ }
1109
+
1110
+ /**
1111
+ * Find the closest ancestor of this node that matches the given predicate.
1112
+ *
1113
+ * @param predicate - A function that returns true if the node matches.
1114
+ */
1115
+ public findAncestor<T extends Node>(
1116
+ predicate: (node: Node) => node is T,
1117
+ ): T | null;
1118
+ /**
1119
+ * Find the closest ancestor of this node that matches the given predicate.
1120
+ *
1121
+ * @param predicate - A function that returns true if the node matches.
1122
+ */
1123
+ public findAncestor<T extends Node = Node>(
1124
+ predicate: (node: Node) => boolean,
1125
+ ): T | null;
1126
+ public findAncestor<T extends Node>(
1127
+ predicate: (node: Node) => node is T,
1128
+ ): T | null {
1129
+ let parent: Node | null = this.parent();
1130
+ while (parent) {
1131
+ if (predicate(parent)) {
1132
+ return parent;
1133
+ }
1134
+ parent = parent.parent();
1135
+ }
1136
+
1137
+ return null;
1138
+ }
1139
+
1140
+ /**
1141
+ * Get the nth children cast to the specified type.
1142
+ *
1143
+ * @param index - The index of the child to retrieve.
1144
+ */
1145
+ public childAs<T extends Node = Node>(index: number): T | null {
1146
+ return (this.children()[index] as T) ?? null;
1147
+ }
1148
+
1149
+ /**
1150
+ * Get the children array cast to the specified type.
1151
+ */
1152
+ public childrenAs<T extends Node = Node>(): T[] {
1153
+ return this.children() as T[];
1154
+ }
1155
+
1156
+ /**
1157
+ * Get the parent cast to the specified type.
1158
+ */
1159
+ public parentAs<T extends Node = Node>(): T | null {
1160
+ return (this.parent() as T) ?? null;
1161
+ }
1162
+
1163
+ /**
1164
+ * Prepare this node to be disposed of.
1165
+ *
1166
+ * @remarks
1167
+ * This method is called automatically when a scene is refreshed. It will
1168
+ * be called even if the node is not currently attached to the tree.
1169
+ *
1170
+ * The goal of this method is to clean any external references to allow the
1171
+ * node to be garbage collected.
1172
+ */
1173
+ public dispose() {
1174
+ if (!this.unregister) {
1175
+ return;
1176
+ }
1177
+
1178
+ this.stateStack = [];
1179
+ this.unregister();
1180
+ this.unregister = null!;
1181
+ for (const {signal} of this) {
1182
+ signal?.context.dispose();
1183
+ }
1184
+ for (const child of this.realChildren) {
1185
+ child.dispose();
1186
+ }
1187
+ }
1188
+
1189
+ /**
1190
+ * Create a copy of this node.
1191
+ *
1192
+ * @param customProps - Properties to override.
1193
+ */
1194
+ public clone(customProps: NodeState = {}): this {
1195
+ const props = {...customProps};
1196
+ if (isReactive(this.children.context.raw())) {
1197
+ props.children ??= this.children.context.raw();
1198
+ } else if (this.children().length > 0) {
1199
+ props.children ??= this.children().map(child => child.clone());
1200
+ }
1201
+
1202
+ for (const {key, meta, signal} of this) {
1203
+ if (!meta.cloneable || key in props) continue;
1204
+ if (meta.compound) {
1205
+ for (const [key, property] of meta.compoundEntries) {
1206
+ if (property in props) continue;
1207
+ const component = (<Record<string, SimpleSignal<any>>>(
1208
+ (<unknown>signal)
1209
+ ))[key];
1210
+ if (!component.context.isInitial()) {
1211
+ props[property] = component.context.raw();
1212
+ }
1213
+ }
1214
+ } else if (!signal.context.isInitial()) {
1215
+ props[key] = signal.context.raw();
1216
+ }
1217
+ }
1218
+
1219
+ return this.instantiate(props);
1220
+ }
1221
+
1222
+ /**
1223
+ * Create a copy of this node.
1224
+ *
1225
+ * @remarks
1226
+ * Unlike {@link clone}, a snapshot clone calculates any reactive properties
1227
+ * at the moment of cloning and passes the raw values to the copy.
1228
+ *
1229
+ * @param customProps - Properties to override.
1230
+ */
1231
+ public snapshotClone(customProps: NodeState = {}): this {
1232
+ const props = {
1233
+ ...this.getState(),
1234
+ ...customProps,
1235
+ };
1236
+
1237
+ if (this.children().length > 0) {
1238
+ props.children ??= this.children().map(child => child.snapshotClone());
1239
+ }
1240
+
1241
+ return this.instantiate(props);
1242
+ }
1243
+
1244
+ /**
1245
+ * Create a reactive copy of this node.
1246
+ *
1247
+ * @remarks
1248
+ * A reactive copy has all its properties dynamically updated to match the
1249
+ * source node.
1250
+ *
1251
+ * @param customProps - Properties to override.
1252
+ */
1253
+ public reactiveClone(customProps: NodeState = {}): this {
1254
+ const props = {...customProps};
1255
+ if (this.children().length > 0) {
1256
+ props.children ??= this.children().map(child => child.reactiveClone());
1257
+ }
1258
+
1259
+ for (const {key, meta, signal} of this) {
1260
+ if (!meta.cloneable || key in props) continue;
1261
+ props[key] = () => signal();
1262
+ }
1263
+
1264
+ return this.instantiate(props);
1265
+ }
1266
+
1267
+ /**
1268
+ * Create an instance of this node's class.
1269
+ *
1270
+ * @param props - Properties to pass to the constructor.
1271
+ */
1272
+ public instantiate(props: NodeProps = {}): this {
1273
+ return new (<NodeConstructor<NodeProps, this>>this.constructor)(props);
1274
+ }
1275
+
1276
+ /**
1277
+ * Set the children without parsing them.
1278
+ *
1279
+ * @remarks
1280
+ * This method assumes that the caller took care of parsing the children and
1281
+ * updating the hierarchy.
1282
+ *
1283
+ * @param value - The children to set.
1284
+ */
1285
+ protected setParsedChildren(value: Node[]) {
1286
+ this.children.context.setter(value);
1287
+ this.realChildren = value;
1288
+ }
1289
+
1290
+ protected spawnChildren(reactive: boolean, children: ComponentChildren) {
1291
+ const parsedChildren = this.parseChildren(children);
1292
+
1293
+ const keep = new Set<string>();
1294
+ for (const newChild of parsedChildren) {
1295
+ const current = newChild.parent.context.raw() as Node | null;
1296
+ if (current && current !== this) {
1297
+ current.removeChild(newChild);
1298
+ }
1299
+ keep.add(newChild.key);
1300
+ newChild.parent(this);
1301
+ }
1302
+
1303
+ for (const oldChild of this.realChildren) {
1304
+ if (!keep.has(oldChild.key)) {
1305
+ oldChild.parent(null);
1306
+ }
1307
+ }
1308
+
1309
+ this.hasSpawnedChildren = reactive;
1310
+ this.realChildren = parsedChildren;
1311
+ }
1312
+
1313
+ /**
1314
+ * Parse any `ComponentChildren` into an array of nodes.
1315
+ *
1316
+ * @param children - The children to parse.
1317
+ */
1318
+ protected parseChildren(children: ComponentChildren): Node[] {
1319
+ const result: Node[] = [];
1320
+ const array = Array.isArray(children) ? children : [children];
1321
+ for (const child of array) {
1322
+ if (child instanceof Node) {
1323
+ result.push(child);
1324
+ }
1325
+ }
1326
+
1327
+ return result;
1328
+ }
1329
+
1330
+ /**
1331
+ * Remove the given child.
1332
+ */
1333
+ protected removeChild(child: Node) {
1334
+ this.setParsedChildren(this.children().filter(node => node !== child));
1335
+ }
1336
+
1337
+ /**
1338
+ * Whether this node should be cached or not.
1339
+ */
1340
+ protected requiresCache(): boolean {
1341
+ return (
1342
+ this.cache() ||
1343
+ this.opacity() < 1 ||
1344
+ this.compositeOperation() !== 'source-over' ||
1345
+ this.hasFilters() ||
1346
+ this.hasShadow() ||
1347
+ this.shaders().length > 0
1348
+ );
1349
+ }
1350
+
1351
+ @computed()
1352
+ protected cacheCanvas(): CanvasRenderingContext2D {
1353
+ const canvas = document.createElement('canvas').getContext('2d');
1354
+ if (!canvas) {
1355
+ throw new Error('Could not create a cache canvas');
1356
+ }
1357
+
1358
+ return canvas;
1359
+ }
1360
+
1361
+ /**
1362
+ * Get a cache canvas with the contents of this node rendered onto it.
1363
+ */
1364
+ @computed()
1365
+ protected cachedCanvas() {
1366
+ const context = this.cacheCanvas();
1367
+ const cache = this.worldSpaceCacheBBox();
1368
+ const matrix = this.localToWorld();
1369
+
1370
+ context.canvas.width = cache.width;
1371
+ context.canvas.height = cache.height;
1372
+
1373
+ context.setTransform(
1374
+ matrix.a,
1375
+ matrix.b,
1376
+ matrix.c,
1377
+ matrix.d,
1378
+ matrix.e - cache.x,
1379
+ matrix.f - cache.y,
1380
+ );
1381
+ this.draw(context);
1382
+
1383
+ return context;
1384
+ }
1385
+
1386
+ /**
1387
+ * Get a bounding box for the contents rendered by this node.
1388
+ *
1389
+ * @remarks
1390
+ * The returned bounding box should be in local space.
1391
+ */
1392
+ protected getCacheBBox(): BBox {
1393
+ return new BBox();
1394
+ }
1395
+
1396
+ /**
1397
+ * Get a bounding box for the contents rendered by this node as well
1398
+ * as its children.
1399
+ */
1400
+ @computed()
1401
+ public cacheBBox(): BBox {
1402
+ const cache = this.getCacheBBox();
1403
+ const children = this.children();
1404
+ const padding = this.cachePadding();
1405
+ if (children.length === 0) {
1406
+ return cache.addSpacing(padding);
1407
+ }
1408
+
1409
+ const points: Vector2[] = cache.corners;
1410
+ for (const child of children) {
1411
+ const childCache = child.fullCacheBBox();
1412
+ const childMatrix = child.localToParent();
1413
+ points.push(
1414
+ ...childCache.corners.map(r => r.transformAsPoint(childMatrix)),
1415
+ );
1416
+ }
1417
+
1418
+ const bbox = BBox.fromPoints(...points);
1419
+ return bbox.addSpacing(padding);
1420
+ }
1421
+
1422
+ /**
1423
+ * Get a bounding box for the contents rendered by this node (including
1424
+ * effects applied after caching).
1425
+ *
1426
+ * @remarks
1427
+ * The returned bounding box should be in local space.
1428
+ */
1429
+ @computed()
1430
+ protected fullCacheBBox(): BBox {
1431
+ const matrix = this.compositeToLocal();
1432
+ const shadowOffset = this.shadowOffset().transform(matrix);
1433
+ const shadowBlur = transformScalar(this.shadowBlur(), matrix);
1434
+
1435
+ const result = this.cacheBBox().expand(
1436
+ this.filters.blur() * 2 + shadowBlur,
1437
+ );
1438
+
1439
+ if (shadowOffset.x < 0) {
1440
+ result.x += shadowOffset.x;
1441
+ result.width -= shadowOffset.x;
1442
+ } else {
1443
+ result.width += shadowOffset.x;
1444
+ }
1445
+
1446
+ if (shadowOffset.y < 0) {
1447
+ result.y += shadowOffset.y;
1448
+ result.height -= shadowOffset.y;
1449
+ } else {
1450
+ result.height += shadowOffset.y;
1451
+ }
1452
+
1453
+ return result;
1454
+ }
1455
+
1456
+ /**
1457
+ * Get a bounding box in world space for the contents rendered by this node as
1458
+ * well as its children.
1459
+ *
1460
+ * @remarks
1461
+ * This is the same the bounding box returned by {@link cacheBBox} only
1462
+ * transformed to world space.
1463
+ */
1464
+ @computed()
1465
+ protected worldSpaceCacheBBox(): BBox {
1466
+ const viewBBox = BBox.fromSizeCentered(this.view().size()).expand(
1467
+ this.view().cachePadding(),
1468
+ );
1469
+ const canvasBBox = BBox.fromPoints(
1470
+ ...viewBBox.transformCorners(this.view().localToWorld()),
1471
+ );
1472
+ const cacheBBox = BBox.fromPoints(
1473
+ ...this.cacheBBox().transformCorners(this.localToWorld()),
1474
+ );
1475
+
1476
+ return canvasBBox.intersection(cacheBBox).pixelPerfect.expand(2);
1477
+ }
1478
+
1479
+ @computed()
1480
+ protected parentWorldSpaceCacheBBox(): BBox {
1481
+ return (
1482
+ this.findAncestor(node => node.requiresCache())?.worldSpaceCacheBBox() ??
1483
+ new BBox(Vector2.zero, useScene2D().getRealSize())
1484
+ );
1485
+ }
1486
+
1487
+ /**
1488
+ * Prepare the given context for drawing a cached node onto it.
1489
+ *
1490
+ * @remarks
1491
+ * This method is called before the contents of the cache canvas are drawn
1492
+ * on the screen. It can be used to apply effects to the entire node together
1493
+ * with its children, instead of applying them individually.
1494
+ * Effects such as transparency, shadows, and filters use this technique.
1495
+ *
1496
+ * Whether the node is cached is decided by the {@link requiresCache} method.
1497
+ *
1498
+ * @param context - The context using which the cache will be drawn.
1499
+ */
1500
+ protected setupDrawFromCache(context: CanvasRenderingContext2D) {
1501
+ context.globalCompositeOperation = this.compositeOperation();
1502
+ context.globalAlpha *= this.opacity();
1503
+ if (this.hasFilters()) {
1504
+ context.filter = this.filterString();
1505
+ }
1506
+ if (this.hasShadow()) {
1507
+ const matrix = this.compositeToWorld();
1508
+ const offset = this.shadowOffset().transform(matrix);
1509
+ const blur = transformScalar(this.shadowBlur(), matrix);
1510
+
1511
+ context.shadowColor = this.shadowColor().serialize();
1512
+ context.shadowBlur = blur;
1513
+ context.shadowOffsetX = offset.x;
1514
+ context.shadowOffsetY = offset.y;
1515
+ }
1516
+
1517
+ const matrix = this.worldToLocal();
1518
+ context.transform(
1519
+ matrix.a,
1520
+ matrix.b,
1521
+ matrix.c,
1522
+ matrix.d,
1523
+ matrix.e,
1524
+ matrix.f,
1525
+ );
1526
+ }
1527
+
1528
+ protected renderFromSource(
1529
+ context: CanvasRenderingContext2D,
1530
+ source: CanvasImageSource,
1531
+ x: number,
1532
+ y: number,
1533
+ ) {
1534
+ this.setupDrawFromCache(context);
1535
+
1536
+ const compositeOverride = this.compositeOverride();
1537
+ context.drawImage(source, x, y);
1538
+ if (compositeOverride > 0) {
1539
+ context.save();
1540
+ context.globalAlpha *= compositeOverride;
1541
+ context.globalCompositeOperation = 'source-over';
1542
+ context.drawImage(source, x, y);
1543
+ context.restore();
1544
+ }
1545
+ }
1546
+
1547
+ private shaderCanvas(destination: TexImageSource, source: TexImageSource) {
1548
+ const shaders = this.shaders();
1549
+ if (shaders.length === 0) {
1550
+ return null;
1551
+ }
1552
+
1553
+ const scene = useScene2D();
1554
+ const size = scene.getRealSize();
1555
+ const parentCacheRect = this.parentWorldSpaceCacheBBox();
1556
+ const cameraToWorld = new DOMMatrix()
1557
+ .scaleSelf(
1558
+ size.width / parentCacheRect.width,
1559
+ size.height / -parentCacheRect.height,
1560
+ )
1561
+ .translateSelf(
1562
+ parentCacheRect.x / -size.width,
1563
+ parentCacheRect.y / size.height - 1,
1564
+ );
1565
+
1566
+ const cacheRect = this.worldSpaceCacheBBox();
1567
+ const cameraToCache = new DOMMatrix()
1568
+ .scaleSelf(size.width / cacheRect.width, size.height / -cacheRect.height)
1569
+ .translateSelf(cacheRect.x / -size.width, cacheRect.y / size.height - 1)
1570
+ .invertSelf();
1571
+
1572
+ const gl = scene.shaders.getGL();
1573
+ scene.shaders.copyTextures(destination, source);
1574
+ scene.shaders.clear();
1575
+
1576
+ for (const shader of shaders) {
1577
+ const program = scene.shaders.getProgram(shader.fragment);
1578
+ if (!program) {
1579
+ continue;
1580
+ }
1581
+
1582
+ if (shader.uniforms) {
1583
+ for (const [name, uniform] of Object.entries(shader.uniforms)) {
1584
+ const location = gl.getUniformLocation(program, name);
1585
+ if (location === null) {
1586
+ continue;
1587
+ }
1588
+
1589
+ const value = unwrap(uniform);
1590
+ if (typeof value === 'number') {
1591
+ gl.uniform1f(location, value);
1592
+ } else if ('toUniform' in value) {
1593
+ value.toUniform(gl, location);
1594
+ } else if (value.length === 1) {
1595
+ gl.uniform1f(location, value[0]);
1596
+ } else if (value.length === 2) {
1597
+ gl.uniform2f(location, value[0], value[1]);
1598
+ } else if (value.length === 3) {
1599
+ gl.uniform3f(location, value[0], value[1], value[2]);
1600
+ } else if (value.length === 4) {
1601
+ gl.uniform4f(location, value[0], value[1], value[2], value[3]);
1602
+ }
1603
+ }
1604
+ }
1605
+
1606
+ gl.uniform1f(
1607
+ gl.getUniformLocation(program, UNIFORM_TIME),
1608
+ this.view2D.globalTime(),
1609
+ );
1610
+
1611
+ gl.uniform1i(
1612
+ gl.getUniformLocation(program, UNIFORM_TIME),
1613
+ scene.playback.frame,
1614
+ );
1615
+
1616
+ gl.uniformMatrix4fv(
1617
+ gl.getUniformLocation(program, UNIFORM_SOURCE_MATRIX),
1618
+ false,
1619
+ cameraToCache.toFloat32Array(),
1620
+ );
1621
+
1622
+ gl.uniformMatrix4fv(
1623
+ gl.getUniformLocation(program, UNIFORM_DESTINATION_MATRIX),
1624
+ false,
1625
+ cameraToWorld.toFloat32Array(),
1626
+ );
1627
+
1628
+ shader.setup?.(gl, program);
1629
+ scene.shaders.render();
1630
+ shader.teardown?.(gl, program);
1631
+ }
1632
+
1633
+ return gl.canvas;
1634
+ }
1635
+
1636
+ /**
1637
+ * Render this node onto the given canvas.
1638
+ *
1639
+ * @param context - The context to draw with.
1640
+ */
1641
+ public render(context: CanvasRenderingContext2D) {
1642
+ if (this.absoluteOpacity() <= 0) {
1643
+ return;
1644
+ }
1645
+
1646
+ context.save();
1647
+ this.transformContext(context);
1648
+
1649
+ if (this.requiresCache()) {
1650
+ const cacheRect = this.worldSpaceCacheBBox();
1651
+ if (cacheRect.width !== 0 && cacheRect.height !== 0) {
1652
+ const cache = this.cachedCanvas().canvas;
1653
+ const source = this.shaderCanvas(context.canvas, cache);
1654
+ if (source) {
1655
+ this.renderFromSource(context, source, 0, 0);
1656
+ } else {
1657
+ this.renderFromSource(
1658
+ context,
1659
+ cache,
1660
+ cacheRect.position.x,
1661
+ cacheRect.position.y,
1662
+ );
1663
+ }
1664
+ }
1665
+ } else {
1666
+ this.draw(context);
1667
+ }
1668
+
1669
+ context.restore();
1670
+ }
1671
+
1672
+ /**
1673
+ * Draw this node onto the canvas.
1674
+ *
1675
+ * @remarks
1676
+ * This method is used when drawing directly onto the screen as well as onto
1677
+ * the cache canvas.
1678
+ * It assumes that the context have already been transformed to local space.
1679
+ *
1680
+ * @param context - The context to draw with.
1681
+ */
1682
+ protected draw(context: CanvasRenderingContext2D) {
1683
+ this.drawChildren(context);
1684
+ }
1685
+
1686
+ protected drawChildren(context: CanvasRenderingContext2D) {
1687
+ for (const child of this.sortedChildren()) {
1688
+ child.render(context);
1689
+ }
1690
+ }
1691
+
1692
+ /**
1693
+ * Draw an overlay for this node.
1694
+ *
1695
+ * @remarks
1696
+ * The overlay for the currently inspected node is displayed on top of the
1697
+ * canvas.
1698
+ *
1699
+ * The provided context is in screen space. The local-to-screen matrix can be
1700
+ * used to transform all shapes that need to be displayed.
1701
+ * This approach allows to keep the line widths and gizmo sizes consistent,
1702
+ * no matter how zoomed-in the view is.
1703
+ *
1704
+ * @param context - The context to draw with.
1705
+ * @param matrix - A local-to-screen matrix.
1706
+ */
1707
+ public drawOverlay(context: CanvasRenderingContext2D, matrix: DOMMatrix) {
1708
+ const box = this.cacheBBox().transformCorners(matrix);
1709
+ const cache = this.getCacheBBox().transformCorners(matrix);
1710
+ context.strokeStyle = 'white';
1711
+ context.lineWidth = 1;
1712
+ context.beginPath();
1713
+ drawLine(context, box);
1714
+ context.closePath();
1715
+ context.stroke();
1716
+
1717
+ context.strokeStyle = 'blue';
1718
+ context.beginPath();
1719
+ drawLine(context, cache);
1720
+ context.closePath();
1721
+ context.stroke();
1722
+ }
1723
+
1724
+ protected transformContext(context: CanvasRenderingContext2D) {
1725
+ const matrix = this.localToParent();
1726
+ context.transform(
1727
+ matrix.a,
1728
+ matrix.b,
1729
+ matrix.c,
1730
+ matrix.d,
1731
+ matrix.e,
1732
+ matrix.f,
1733
+ );
1734
+ }
1735
+
1736
+ /**
1737
+ * Try to find a node intersecting the given position.
1738
+ *
1739
+ * @param position - The searched position.
1740
+ */
1741
+ public hit(position: Vector2): Node | null {
1742
+ let hit: Node | null = null;
1743
+ const local = position.transformAsPoint(this.localToParent().inverse());
1744
+ const children = this.children();
1745
+ for (let i = children.length - 1; i >= 0; i--) {
1746
+ hit = children[i].hit(local);
1747
+ if (hit) {
1748
+ break;
1749
+ }
1750
+ }
1751
+
1752
+ return hit;
1753
+ }
1754
+
1755
+ /**
1756
+ * Collect all asynchronous resources used by this node.
1757
+ */
1758
+ protected collectAsyncResources() {
1759
+ for (const child of this.children()) {
1760
+ child.collectAsyncResources();
1761
+ }
1762
+ }
1763
+
1764
+ /**
1765
+ * Wait for any asynchronous resources that this node or its children have.
1766
+ *
1767
+ * @remarks
1768
+ * Certain resources like images are always loaded asynchronously.
1769
+ * Awaiting this method makes sure that all such resources are done loading
1770
+ * before continuing the animation.
1771
+ */
1772
+ public async toPromise(): Promise<this> {
1773
+ do {
1774
+ await DependencyContext.consumePromises();
1775
+ this.collectAsyncResources();
1776
+ } while (DependencyContext.hasPromises());
1777
+ return this;
1778
+ }
1779
+
1780
+ /**
1781
+ * Return a snapshot of the node's current signal values.
1782
+ *
1783
+ * @remarks
1784
+ * This method will calculate the values of any reactive properties of the
1785
+ * node at the time the method is called.
1786
+ */
1787
+ public getState(): NodeState {
1788
+ const state: NodeState = {};
1789
+ for (const {key, meta, signal} of this) {
1790
+ if (!meta.cloneable || key in state) continue;
1791
+ state[key] = signal();
1792
+ }
1793
+ return state;
1794
+ }
1795
+
1796
+ /**
1797
+ * Apply the given state to the node, setting all matching signal values to
1798
+ * the provided values.
1799
+ *
1800
+ * @param state - The state to apply to the node.
1801
+ */
1802
+ public applyState(state: NodeState): void;
1803
+ /**
1804
+ * Smoothly transition between the current state of the node and the given
1805
+ * state.
1806
+ *
1807
+ * @param state - The state to transition to.
1808
+ * @param duration - The duration of the transition.
1809
+ * @param timing - The timing function to use for the transition.
1810
+ */
1811
+ public applyState(
1812
+ state: NodeState,
1813
+ duration: number,
1814
+ timing?: TimingFunction,
1815
+ ): ThreadGenerator;
1816
+ public applyState(
1817
+ state: NodeState,
1818
+ duration?: number,
1819
+ timing: TimingFunction = easeInOutCubic,
1820
+ ): ThreadGenerator | void {
1821
+ if (duration === undefined) {
1822
+ for (const key in state) {
1823
+ const signal = this.signalByKey(key);
1824
+ if (signal) {
1825
+ signal(state[key]);
1826
+ }
1827
+ }
1828
+ }
1829
+
1830
+ const tasks: ThreadGenerator[] = [];
1831
+ for (const key in state) {
1832
+ const signal = this.signalByKey(key);
1833
+ if (state[key] !== signal.context.raw()) {
1834
+ tasks.push(signal(state[key], duration!, timing));
1835
+ }
1836
+ }
1837
+
1838
+ return all(...tasks);
1839
+ }
1840
+
1841
+ /**
1842
+ * Push a snapshot of the node's current state onto the node's state stack.
1843
+ *
1844
+ * @remarks
1845
+ * This method can be used together with the {@link restore} method to save a
1846
+ * node's current state and later restore it. It is possible to store more
1847
+ * than one state by calling `save` method multiple times.
1848
+ */
1849
+ public save(): void {
1850
+ this.stateStack.push(this.getState());
1851
+ }
1852
+
1853
+ /**
1854
+ * Restore the node to its last saved state.
1855
+ *
1856
+ * @remarks
1857
+ * This method can be used together with the {@link save} method to restore a
1858
+ * node to a previously saved state. Restoring a node to a previous state
1859
+ * removes that state from the state stack.
1860
+ *
1861
+ * @example
1862
+ * ```tsx
1863
+ * const node = <Circle width={100} height={100} fill={"lightseagreen"} />
1864
+ *
1865
+ * view.add(node);
1866
+ *
1867
+ * // Save the node's current state
1868
+ * node.save();
1869
+ *
1870
+ * // Modify some of the node's properties
1871
+ * yield* node.scale(2, 1);
1872
+ * yield* node.fill('hotpink', 1);
1873
+ *
1874
+ * // Restore the node to its saved state
1875
+ * node.restore();
1876
+ * ```
1877
+ */
1878
+ public restore(): void;
1879
+ /**
1880
+ * Tween the node to its last saved state.
1881
+ *
1882
+ * @remarks
1883
+ * This method can be used together with the {@link save} method to restore a
1884
+ * node to a previously saved state. Restoring a node to a previous state
1885
+ * removes that state from the state stack.
1886
+ *
1887
+ * @example
1888
+ * ```tsx
1889
+ * const node = <Circle width={100} height={100} fill={"lightseagreen"} />
1890
+ *
1891
+ * view.add(node);
1892
+ *
1893
+ * // Save the node's current state
1894
+ * node.save();
1895
+ *
1896
+ * // Modify some of the node's properties
1897
+ * yield* node.scale(2, 1);
1898
+ * yield* node.fill('hotpink', 1);
1899
+ *
1900
+ * // Tween the node to its saved state over 1 second
1901
+ * yield* node.restore(1);
1902
+ * ```
1903
+ *
1904
+ * @param duration - The duration of the transition.
1905
+ * @param timing - The timing function to use for the transition.
1906
+ */
1907
+ public restore(duration: number, timing?: TimingFunction): ThreadGenerator;
1908
+ public restore(
1909
+ duration?: number,
1910
+ timing: TimingFunction = easeInOutCubic,
1911
+ ): ThreadGenerator | void {
1912
+ const state = this.stateStack.pop();
1913
+
1914
+ if (state !== undefined) {
1915
+ return this.applyState(state, duration!, timing);
1916
+ }
1917
+ }
1918
+
1919
+ public *[Symbol.iterator]() {
1920
+ for (const key in this.properties) {
1921
+ const meta = this.properties[key];
1922
+ const signal = this.signalByKey(key);
1923
+ yield {meta, signal, key};
1924
+ }
1925
+ }
1926
+
1927
+ private signalByKey(key: string): SimpleSignal<any> {
1928
+ return (<Record<string, SimpleSignal<any>>>(<unknown>this))[key];
1929
+ }
1930
+
1931
+ private reversedChildren() {
1932
+ const children = this.children();
1933
+ const result: Node[] = [];
1934
+ for (let i = children.length - 1; i >= 0; i--) {
1935
+ result.push(children[i]);
1936
+ }
1937
+ return result;
1938
+ }
1939
+ }
1940
+
1941
+ Node.prototype.isClass = true;