@motionscript/core 0.1.0-alpha.8 → 0.1.0-alpha.9

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 (791) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/LICENSE +201 -201
  3. package/NOTICE +49 -49
  4. package/README.md +91 -91
  5. package/dist/assets/asset-index.js.map +1 -1
  6. package/dist/assets/catalog.js.map +1 -1
  7. package/dist/assets/errors.js.map +1 -1
  8. package/dist/assets/index.js.map +1 -1
  9. package/dist/assets/manager.js.map +1 -1
  10. package/dist/assets/manifest.js.map +1 -1
  11. package/dist/assets/record.js.map +1 -1
  12. package/dist/assets/scope.js.map +1 -1
  13. package/dist/attributes/audio/effects/chain.js.map +1 -1
  14. package/dist/attributes/audio/effects/implementations/echo.js.map +1 -1
  15. package/dist/attributes/audio/effects/implementations/gain.js.map +1 -1
  16. package/dist/attributes/audio/effects/implementations/highpass.js.map +1 -1
  17. package/dist/attributes/audio/effects/implementations/lowpass.js.map +1 -1
  18. package/dist/attributes/audio/effects/implementations/tremolo.js.map +1 -1
  19. package/dist/attributes/audio/effects/index.js.map +1 -1
  20. package/dist/attributes/audio/effects/registry.js.map +1 -1
  21. package/dist/attributes/audio/effects/union.js.map +1 -1
  22. package/dist/attributes/audio/ramp.js.map +1 -1
  23. package/dist/attributes/audio/request.js.map +1 -1
  24. package/dist/attributes/audio/schedule.js.map +1 -1
  25. package/dist/attributes/audio/sound.js.map +1 -1
  26. package/dist/attributes/audio/transition.js.map +1 -1
  27. package/dist/attributes/index.js.map +1 -1
  28. package/dist/attributes/layout/alignment.js.map +1 -1
  29. package/dist/attributes/layout/index.js.map +1 -1
  30. package/dist/attributes/layout/insets.js.map +1 -1
  31. package/dist/attributes/layout/matrix2d.js.map +1 -1
  32. package/dist/attributes/layout/size.js.map +1 -1
  33. package/dist/attributes/layout/space3d.js.map +1 -1
  34. package/dist/attributes/layout/transform3d.js.map +1 -1
  35. package/dist/attributes/layout/vector2.js.map +1 -1
  36. package/dist/attributes/layout/world-transform.js.map +1 -1
  37. package/dist/attributes/mask/boolean.js.map +1 -1
  38. package/dist/attributes/mask/mask.js.map +1 -1
  39. package/dist/attributes/properties/decorator.js.map +1 -1
  40. package/dist/attributes/properties/inputs.js.map +1 -1
  41. package/dist/attributes/properties/typed.js.map +1 -1
  42. package/dist/attributes/render3d/orbit.js.map +1 -1
  43. package/dist/attributes/shape/corners/corner-radius.js.map +1 -1
  44. package/dist/attributes/shape/corners/corner-style.js.map +1 -1
  45. package/dist/attributes/shape/corners/corners.js.map +1 -1
  46. package/dist/attributes/shape/corners/index.js.map +1 -1
  47. package/dist/attributes/shape/effects/backdrop.js.map +1 -1
  48. package/dist/attributes/shape/effects/chain.js.map +1 -1
  49. package/dist/attributes/shape/effects/effect-data.js.map +1 -1
  50. package/dist/attributes/shape/effects/implementations/ascii.js.map +1 -1
  51. package/dist/attributes/shape/effects/implementations/bit-crush.js.map +1 -1
  52. package/dist/attributes/shape/effects/implementations/block-displace.js.map +1 -1
  53. package/dist/attributes/shape/effects/implementations/bloom.js.map +1 -1
  54. package/dist/attributes/shape/effects/implementations/blur.js.map +1 -1
  55. package/dist/attributes/shape/effects/implementations/bulge.js.map +1 -1
  56. package/dist/attributes/shape/effects/implementations/chromatic-aberration.js.map +1 -1
  57. package/dist/attributes/shape/effects/implementations/color-adjustment.js.map +1 -1
  58. package/dist/attributes/shape/effects/implementations/curves.d.ts +2 -2
  59. package/dist/attributes/shape/effects/implementations/curves.js.map +1 -1
  60. package/dist/attributes/shape/effects/implementations/directional-blur.js.map +1 -1
  61. package/dist/attributes/shape/effects/implementations/dither.d.ts +2 -2
  62. package/dist/attributes/shape/effects/implementations/dither.js.map +1 -1
  63. package/dist/attributes/shape/effects/implementations/drop-shadow.js.map +1 -1
  64. package/dist/attributes/shape/effects/implementations/duotone.js.map +1 -1
  65. package/dist/attributes/shape/effects/implementations/edges.js.map +1 -1
  66. package/dist/attributes/shape/effects/implementations/glass.js.map +1 -1
  67. package/dist/attributes/shape/effects/implementations/glow.d.ts +4 -4
  68. package/dist/attributes/shape/effects/implementations/glow.js.map +1 -1
  69. package/dist/attributes/shape/effects/implementations/grain.js.map +1 -1
  70. package/dist/attributes/shape/effects/implementations/grayscale.js.map +1 -1
  71. package/dist/attributes/shape/effects/implementations/halftone.js.map +1 -1
  72. package/dist/attributes/shape/effects/implementations/invert.d.ts +2 -2
  73. package/dist/attributes/shape/effects/implementations/invert.js.map +1 -1
  74. package/dist/attributes/shape/effects/implementations/kaleidoscope.js.map +1 -1
  75. package/dist/attributes/shape/effects/implementations/lut.js.map +1 -1
  76. package/dist/attributes/shape/effects/implementations/magnify.js.map +1 -1
  77. package/dist/attributes/shape/effects/implementations/motion-blur.js.map +1 -1
  78. package/dist/attributes/shape/effects/implementations/oil-paint.js.map +1 -1
  79. package/dist/attributes/shape/effects/implementations/outline.js.map +1 -1
  80. package/dist/attributes/shape/effects/implementations/pixelate.js.map +1 -1
  81. package/dist/attributes/shape/effects/implementations/posterize.js.map +1 -1
  82. package/dist/attributes/shape/effects/implementations/progressive-blur.js.map +1 -1
  83. package/dist/attributes/shape/effects/implementations/radial-blur.js.map +1 -1
  84. package/dist/attributes/shape/effects/implementations/rgb-shift.js.map +1 -1
  85. package/dist/attributes/shape/effects/implementations/scanlines.js.map +1 -1
  86. package/dist/attributes/shape/effects/implementations/scatter.js.map +1 -1
  87. package/dist/attributes/shape/effects/implementations/shader.d.ts +2 -2
  88. package/dist/attributes/shape/effects/implementations/shader.js.map +1 -1
  89. package/dist/attributes/shape/effects/implementations/sharpen.js.map +1 -1
  90. package/dist/attributes/shape/effects/implementations/streak.js.map +1 -1
  91. package/dist/attributes/shape/effects/implementations/threshold.js.map +1 -1
  92. package/dist/attributes/shape/effects/implementations/twirl.js.map +1 -1
  93. package/dist/attributes/shape/effects/implementations/vignette.js.map +1 -1
  94. package/dist/attributes/shape/effects/implementations/vintage.js.map +1 -1
  95. package/dist/attributes/shape/effects/implementations/wave.js.map +1 -1
  96. package/dist/attributes/shape/effects/index.js.map +1 -1
  97. package/dist/attributes/shape/effects/registry.js.map +1 -1
  98. package/dist/attributes/shape/effects/spec.js.map +1 -1
  99. package/dist/attributes/shape/effects/union.js.map +1 -1
  100. package/dist/attributes/shape/fill/blend.js.map +1 -1
  101. package/dist/attributes/shape/fill/chain.js.map +1 -1
  102. package/dist/attributes/shape/fill/coerce.js.map +1 -1
  103. package/dist/attributes/shape/fill/color/constants.js.map +1 -1
  104. package/dist/attributes/shape/fill/color/parser.js.map +1 -1
  105. package/dist/attributes/shape/fill/gradient-stops.js.map +1 -1
  106. package/dist/attributes/shape/fill/implementations/canvas3d.js.map +1 -1
  107. package/dist/attributes/shape/fill/implementations/color.js.map +1 -1
  108. package/dist/attributes/shape/fill/implementations/conic-gradient.js.map +1 -1
  109. package/dist/attributes/shape/fill/implementations/dot-grid.js.map +1 -1
  110. package/dist/attributes/shape/fill/implementations/fractal-noise.js.map +1 -1
  111. package/dist/attributes/shape/fill/implementations/grid.js.map +1 -1
  112. package/dist/attributes/shape/fill/implementations/image.js.map +1 -1
  113. package/dist/attributes/shape/fill/implementations/linear-gradient.js.map +1 -1
  114. package/dist/attributes/shape/fill/implementations/noise.js.map +1 -1
  115. package/dist/attributes/shape/fill/implementations/radial-gradient.js.map +1 -1
  116. package/dist/attributes/shape/fill/implementations/shader.js.map +1 -1
  117. package/dist/attributes/shape/fill/implementations/stripe.js.map +1 -1
  118. package/dist/attributes/shape/fill/implementations/video.js.map +1 -1
  119. package/dist/attributes/shape/fill/index.js.map +1 -1
  120. package/dist/attributes/shape/fill/lerp.js.map +1 -1
  121. package/dist/attributes/shape/fill/media-preset.js.map +1 -1
  122. package/dist/attributes/shape/fill/registry.js.map +1 -1
  123. package/dist/attributes/shape/fill/union.js.map +1 -1
  124. package/dist/attributes/shape/filters/chain.js.map +1 -1
  125. package/dist/attributes/shape/filters/implementations/alpha.js.map +1 -1
  126. package/dist/attributes/shape/filters/implementations/blur.js.map +1 -1
  127. package/dist/attributes/shape/filters/implementations/color-adjustment.js.map +1 -1
  128. package/dist/attributes/shape/filters/implementations/color-matrix.js.map +1 -1
  129. package/dist/attributes/shape/filters/implementations/curves.js.map +1 -1
  130. package/dist/attributes/shape/filters/implementations/echo.js.map +1 -1
  131. package/dist/attributes/shape/filters/implementations/exposure.js.map +1 -1
  132. package/dist/attributes/shape/filters/implementations/grayscale.js.map +1 -1
  133. package/dist/attributes/shape/filters/implementations/posterize-time.js.map +1 -1
  134. package/dist/attributes/shape/filters/index.js.map +1 -1
  135. package/dist/attributes/shape/filters/registry.js.map +1 -1
  136. package/dist/attributes/shape/filters/union.js.map +1 -1
  137. package/dist/attributes/shape/path/anchors.js.map +1 -1
  138. package/dist/attributes/shape/path/bezier.js.map +1 -1
  139. package/dist/attributes/shape/path/index.js.map +1 -1
  140. package/dist/attributes/shape/path/measure.js.map +1 -1
  141. package/dist/attributes/shape/path/morph.js.map +1 -1
  142. package/dist/attributes/shape/path/ops.js.map +1 -1
  143. package/dist/attributes/shape/path/types.js.map +1 -1
  144. package/dist/attributes/shape/path/walk.js.map +1 -1
  145. package/dist/attributes/shape/shaders/index.js.map +1 -1
  146. package/dist/attributes/shape/shaders/language.js.map +1 -1
  147. package/dist/attributes/shape/shaders/pack.js.map +1 -1
  148. package/dist/attributes/shape/shaders/resolve.js.map +1 -1
  149. package/dist/attributes/shape/shadow/index.js.map +1 -1
  150. package/dist/attributes/shape/shadow/shadow.js.map +1 -1
  151. package/dist/attributes/shape/stroke/index.js.map +1 -1
  152. package/dist/attributes/shape/stroke/stroke.js.map +1 -1
  153. package/dist/attributes/shared/operators.js.map +1 -1
  154. package/dist/attributes/text/index.js.map +1 -1
  155. package/dist/attributes/text/ops.js.map +1 -1
  156. package/dist/attributes/text/types.js.map +1 -1
  157. package/dist/browser/chunks/{chunk-LKUYVFU3.js → chunk-4BDLFEOC.js} +1 -1
  158. package/dist/browser/chunks/chunk-4BDLFEOC.js.map +7 -0
  159. package/dist/browser/chunks/{chunk-GKM6UZJR.js → chunk-7DB6BI27.js} +2 -2
  160. package/dist/browser/chunks/chunk-7DB6BI27.js.map +7 -0
  161. package/dist/browser/chunks/{chunk-AOT33LMS.js → chunk-IX53IFBD.js} +2 -2
  162. package/dist/browser/chunks/chunk-IX53IFBD.js.map +7 -0
  163. package/dist/browser/chunks/{chunk-ZRPZPWZU.js → chunk-Q55UPA3E.js} +1 -1
  164. package/dist/browser/chunks/chunk-Q55UPA3E.js.map +7 -0
  165. package/dist/browser/component.js +1 -1
  166. package/dist/browser/experimental.js +1 -1
  167. package/dist/browser/experimental.js.map +1 -1
  168. package/dist/browser/index.js +1 -1
  169. package/dist/browser/index.js.map +1 -1
  170. package/dist/browser/sdk.js +1 -1
  171. package/dist/component.js.map +1 -1
  172. package/dist/components/builtins/audio/audio.js.map +1 -1
  173. package/dist/components/builtins/geometry/composite.js.map +1 -1
  174. package/dist/components/builtins/geometry/geometry.js.map +1 -1
  175. package/dist/components/builtins/geometry/shape-outline.js.map +1 -1
  176. package/dist/components/builtins/layout/layout.js.map +1 -1
  177. package/dist/components/builtins/media/media.js.map +1 -1
  178. package/dist/components/builtins/providers/providers.js.map +1 -1
  179. package/dist/components/builtins/text/number-format.js.map +1 -1
  180. package/dist/components/builtins/text/number-pattern.js.map +1 -1
  181. package/dist/components/builtins/text/text-defaults.js.map +1 -1
  182. package/dist/components/builtins/text/text-layout.js.map +1 -1
  183. package/dist/components/builtins/text/text.d.ts +9 -9
  184. package/dist/components/builtins/text/text.js.map +1 -1
  185. package/dist/components/builtins/three/canvas3d.js.map +1 -1
  186. package/dist/components/builtins/three/grid-geometry3d.js.map +1 -1
  187. package/dist/components/builtins/three/three.js.map +1 -1
  188. package/dist/components/factory/api.js.map +1 -1
  189. package/dist/components/factory/clip-of.js.map +1 -1
  190. package/dist/components/factory/commands-for.js.map +1 -1
  191. package/dist/components/factory/component-audio.js.map +1 -1
  192. package/dist/components/factory/component2d.js.map +1 -1
  193. package/dist/components/factory/component3d.js.map +1 -1
  194. package/dist/components/factory/factory.js.map +1 -1
  195. package/dist/components/factory/timeline.js.map +1 -1
  196. package/dist/components/factory/type-def.js.map +1 -1
  197. package/dist/components/factory/types.js.map +1 -1
  198. package/dist/components/factory/views.js.map +1 -1
  199. package/dist/components/modules/aim.js.map +1 -1
  200. package/dist/components/modules/corners.js.map +1 -1
  201. package/dist/components/modules/flow.js.map +1 -1
  202. package/dist/components/modules/material.js.map +1 -1
  203. package/dist/components/modules/paint.js.map +1 -1
  204. package/dist/components/modules/shapes.js.map +1 -1
  205. package/dist/components/modules/text-layout.js.map +1 -1
  206. package/dist/components/modules/text-style.d.ts +1 -1
  207. package/dist/components/modules/text-style.js.map +1 -1
  208. package/dist/components/modules/three-entries.js.map +1 -1
  209. package/dist/components/modules/view3d.js.map +1 -1
  210. package/dist/components/trees/2d/group-bounds.js.map +1 -1
  211. package/dist/components/trees/2d/node-lifecycle.js.map +1 -1
  212. package/dist/components/trees/2d/node-motion.js.map +1 -1
  213. package/dist/components/trees/2d/node-render.js.map +1 -1
  214. package/dist/components/trees/2d/node-space.js.map +1 -1
  215. package/dist/components/trees/2d/node-transform.js.map +1 -1
  216. package/dist/components/trees/2d/node2d.js.map +1 -1
  217. package/dist/components/trees/audio/index.js.map +1 -1
  218. package/dist/components/trees/audio/node-audio.js.map +1 -1
  219. package/dist/components/trees/index.js.map +1 -1
  220. package/dist/components/trees/node/node-editor-state.js.map +1 -1
  221. package/dist/components/trees/node/node-reactive.js.map +1 -1
  222. package/dist/components/trees/node/node-time.js.map +1 -1
  223. package/dist/components/trees/node/node-walk.js.map +1 -1
  224. package/dist/components/trees/node/node.js.map +1 -1
  225. package/dist/components/trees/root/canvas2d-node.js.map +1 -1
  226. package/dist/components/trees/three/node3d.js.map +1 -1
  227. package/dist/document/audio.js.map +1 -1
  228. package/dist/document/builtins.js.map +1 -1
  229. package/dist/document/command-traits.js.map +1 -1
  230. package/dist/document/deny-globals.js.map +1 -1
  231. package/dist/document/diff.js.map +1 -1
  232. package/dist/document/doc-index.js.map +1 -1
  233. package/dist/document/expression/compile.js.map +1 -1
  234. package/dist/document/expression/index.js.map +1 -1
  235. package/dist/document/expression/ops.js.map +1 -1
  236. package/dist/document/expression/parse.js.map +1 -1
  237. package/dist/document/expression/refs.js.map +1 -1
  238. package/dist/document/expression/types.js.map +1 -1
  239. package/dist/document/expression/walk.js.map +1 -1
  240. package/dist/document/index.js.map +1 -1
  241. package/dist/document/migrate.js.map +1 -1
  242. package/dist/document/missing-node.js.map +1 -1
  243. package/dist/document/node-decorator.js.map +1 -1
  244. package/dist/document/node-descriptor.js.map +1 -1
  245. package/dist/document/placement.js.map +1 -1
  246. package/dist/document/project.js.map +1 -1
  247. package/dist/document/prop-evolution.js.map +1 -1
  248. package/dist/document/registry.js.map +1 -1
  249. package/dist/document/settled-index.js.map +1 -1
  250. package/dist/document/timeline-patch.js.map +1 -1
  251. package/dist/document/timeline.js.map +1 -1
  252. package/dist/document/types.js.map +1 -1
  253. package/dist/document/validate.js.map +1 -1
  254. package/dist/document/vocabulary.js.map +1 -1
  255. package/dist/experimental.d.ts.map +1 -1
  256. package/dist/experimental.js.map +1 -1
  257. package/dist/index.js.map +1 -1
  258. package/dist/layout/bounds.js.map +1 -1
  259. package/dist/layout/constraints.js.map +1 -1
  260. package/dist/layout/flex.js.map +1 -1
  261. package/dist/layout/freeform.js.map +1 -1
  262. package/dist/layout/grid.js.map +1 -1
  263. package/dist/layout/index.js.map +1 -1
  264. package/dist/layout/item.js.map +1 -1
  265. package/dist/layout/ops.js.map +1 -1
  266. package/dist/layout/types.js.map +1 -1
  267. package/dist/platform/audio-sink.js.map +1 -1
  268. package/dist/platform/exporter.js.map +1 -1
  269. package/dist/platform/index.js.map +1 -1
  270. package/dist/platform/stepped-clock.js.map +1 -1
  271. package/dist/platform/storage-adapter.js.map +1 -1
  272. package/dist/platform/ticker.js.map +1 -1
  273. package/dist/project/config.js.map +1 -1
  274. package/dist/project/index.js.map +1 -1
  275. package/dist/project/tree.js.map +1 -1
  276. package/dist/props/host.js.map +1 -1
  277. package/dist/props/index.js.map +1 -1
  278. package/dist/props/observer.js.map +1 -1
  279. package/dist/props/slot.js.map +1 -1
  280. package/dist/renamed-scene-names.js.map +1 -1
  281. package/dist/render/canvas-render-context2d.js.map +1 -1
  282. package/dist/render/clip-contains.js.map +1 -1
  283. package/dist/render/clip.js.map +1 -1
  284. package/dist/render/descriptors/ellipse.js.map +1 -1
  285. package/dist/render/descriptors/line.js.map +1 -1
  286. package/dist/render/descriptors/path-builder.js.map +1 -1
  287. package/dist/render/descriptors/path.js.map +1 -1
  288. package/dist/render/descriptors/polygon.js.map +1 -1
  289. package/dist/render/descriptors/polygram.js.map +1 -1
  290. package/dist/render/descriptors/rect.js.map +1 -1
  291. package/dist/render/descriptors/richtext.js.map +1 -1
  292. package/dist/render/descriptors/shape.js.map +1 -1
  293. package/dist/render/descriptors/text.js.map +1 -1
  294. package/dist/render/descriptors/transform.js.map +1 -1
  295. package/dist/render/graphics2d.js.map +1 -1
  296. package/dist/render/index.js.map +1 -1
  297. package/dist/render/measure-context.js.map +1 -1
  298. package/dist/render/null-render-context.js.map +1 -1
  299. package/dist/render/render-context2d.js.map +1 -1
  300. package/dist/render/render-issue.js.map +1 -1
  301. package/dist/render/surface.js.map +1 -1
  302. package/dist/render/text-defaults.js.map +1 -1
  303. package/dist/render/text-layout.js.map +1 -1
  304. package/dist/render3d/bounds3d.js.map +1 -1
  305. package/dist/render3d/builders.js.map +1 -1
  306. package/dist/render3d/camera.js.map +1 -1
  307. package/dist/render3d/fill3d.js.map +1 -1
  308. package/dist/render3d/geometry.js.map +1 -1
  309. package/dist/render3d/graphics3d.js.map +1 -1
  310. package/dist/render3d/index.js.map +1 -1
  311. package/dist/render3d/inert.js.map +1 -1
  312. package/dist/render3d/light.js.map +1 -1
  313. package/dist/render3d/material.js.map +1 -1
  314. package/dist/render3d/matrix4.js.map +1 -1
  315. package/dist/render3d/render-context3d.js.map +1 -1
  316. package/dist/render3d/resources.js.map +1 -1
  317. package/dist/render3d/rounded-box.js.map +1 -1
  318. package/dist/render3d/scene-settings.js.map +1 -1
  319. package/dist/render3d/scene3d.js.map +1 -1
  320. package/dist/render3d/segments.js.map +1 -1
  321. package/dist/render3d/texture.js.map +1 -1
  322. package/dist/render3d/tracking.js.map +1 -1
  323. package/dist/render3d/transform.js.map +1 -1
  324. package/dist/render3d/vector3.js.map +1 -1
  325. package/dist/render3d/walk.js.map +1 -1
  326. package/dist/runtime/asset-refine.js.map +1 -1
  327. package/dist/runtime/asset-timeline.js.map +1 -1
  328. package/dist/runtime/asset-update.js.map +1 -1
  329. package/dist/runtime/audio-index.js.map +1 -1
  330. package/dist/runtime/builtin-context.js.map +1 -1
  331. package/dist/runtime/clip-instance.js.map +1 -1
  332. package/dist/runtime/clip-store.js.map +1 -1
  333. package/dist/runtime/engine.js.map +1 -1
  334. package/dist/runtime/frame-time.js.map +1 -1
  335. package/dist/runtime/index.js.map +1 -1
  336. package/dist/runtime/node-picking.js.map +1 -1
  337. package/dist/runtime/node-picking3d.js.map +1 -1
  338. package/dist/runtime/placement.js.map +1 -1
  339. package/dist/runtime/playback-controller.js.map +1 -1
  340. package/dist/runtime/playback.js.map +1 -1
  341. package/dist/runtime/precompisition.js.map +1 -1
  342. package/dist/runtime/project-assets.js.map +1 -1
  343. package/dist/runtime/session.js.map +1 -1
  344. package/dist/runtime/settle.js.map +1 -1
  345. package/dist/runtime/state-evaluator.js.map +1 -1
  346. package/dist/runtime/text-geometry.js.map +1 -1
  347. package/dist/sdk/index.js.map +1 -1
  348. package/dist/tween/command-decorator.js.map +1 -1
  349. package/dist/tween/command.js.map +1 -1
  350. package/dist/tween/ease/constants.js.map +1 -1
  351. package/dist/tween/ease/curve.js.map +1 -1
  352. package/dist/tween/ease/describe.js.map +1 -1
  353. package/dist/tween/ease/spec.js.map +1 -1
  354. package/dist/tween/ease/type.js.map +1 -1
  355. package/dist/tween/index.js.map +1 -1
  356. package/dist/tween/inert.js.map +1 -1
  357. package/dist/tween/lerp.js.map +1 -1
  358. package/dist/tween/loop.js.map +1 -1
  359. package/dist/tween/prepare.js.map +1 -1
  360. package/dist/tween/stepper.js.map +1 -1
  361. package/dist/tween/to-command.js.map +1 -1
  362. package/dist/util/clamp.js.map +1 -1
  363. package/dist/util/context.js.map +1 -1
  364. package/dist/util/csv.js.map +1 -1
  365. package/dist/util/generateList.js.map +1 -1
  366. package/dist/util/index.js.map +1 -1
  367. package/dist/util/metrics.js.map +1 -1
  368. package/dist/util/random.js.map +1 -1
  369. package/dist/util/reference.js.map +1 -1
  370. package/dist/util/scheduler.js.map +1 -1
  371. package/package.json +1 -1
  372. package/dist/attributes/audio/filters/chain.d.ts +0 -113
  373. package/dist/attributes/audio/filters/chain.d.ts.map +0 -1
  374. package/dist/attributes/audio/filters/chain.js +0 -104
  375. package/dist/attributes/audio/filters/chain.js.map +0 -1
  376. package/dist/attributes/audio/filters/curve.d.ts +0 -152
  377. package/dist/attributes/audio/filters/curve.d.ts.map +0 -1
  378. package/dist/attributes/audio/filters/curve.js +0 -250
  379. package/dist/attributes/audio/filters/curve.js.map +0 -1
  380. package/dist/attributes/audio/filters/implementations/echo.d.ts +0 -14
  381. package/dist/attributes/audio/filters/implementations/echo.d.ts.map +0 -1
  382. package/dist/attributes/audio/filters/implementations/echo.js +0 -11
  383. package/dist/attributes/audio/filters/implementations/echo.js.map +0 -1
  384. package/dist/attributes/audio/filters/implementations/gain.d.ts +0 -10
  385. package/dist/attributes/audio/filters/implementations/gain.d.ts.map +0 -1
  386. package/dist/attributes/audio/filters/implementations/gain.js +0 -6
  387. package/dist/attributes/audio/filters/implementations/gain.js.map +0 -1
  388. package/dist/attributes/audio/filters/implementations/highpass.d.ts +0 -12
  389. package/dist/attributes/audio/filters/implementations/highpass.d.ts.map +0 -1
  390. package/dist/attributes/audio/filters/implementations/highpass.js +0 -10
  391. package/dist/attributes/audio/filters/implementations/highpass.js.map +0 -1
  392. package/dist/attributes/audio/filters/implementations/lowpass.d.ts +0 -12
  393. package/dist/attributes/audio/filters/implementations/lowpass.d.ts.map +0 -1
  394. package/dist/attributes/audio/filters/implementations/lowpass.js +0 -10
  395. package/dist/attributes/audio/filters/implementations/lowpass.js.map +0 -1
  396. package/dist/attributes/audio/filters/implementations/speed.d.ts +0 -18
  397. package/dist/attributes/audio/filters/implementations/speed.d.ts.map +0 -1
  398. package/dist/attributes/audio/filters/implementations/speed.js +0 -6
  399. package/dist/attributes/audio/filters/implementations/speed.js.map +0 -1
  400. package/dist/attributes/audio/filters/implementations/tremolo.d.ts +0 -12
  401. package/dist/attributes/audio/filters/implementations/tremolo.d.ts.map +0 -1
  402. package/dist/attributes/audio/filters/implementations/tremolo.js +0 -10
  403. package/dist/attributes/audio/filters/implementations/tremolo.js.map +0 -1
  404. package/dist/attributes/audio/filters/index.d.ts +0 -22
  405. package/dist/attributes/audio/filters/index.d.ts.map +0 -1
  406. package/dist/attributes/audio/filters/index.js +0 -8
  407. package/dist/attributes/audio/filters/index.js.map +0 -1
  408. package/dist/attributes/audio/filters/registry.d.ts +0 -36
  409. package/dist/attributes/audio/filters/registry.d.ts.map +0 -1
  410. package/dist/attributes/audio/filters/registry.js +0 -82
  411. package/dist/attributes/audio/filters/registry.js.map +0 -1
  412. package/dist/attributes/audio/filters/union.d.ts +0 -18
  413. package/dist/attributes/audio/filters/union.d.ts.map +0 -1
  414. package/dist/attributes/audio/filters/union.js +0 -28
  415. package/dist/attributes/audio/filters/union.js.map +0 -1
  416. package/dist/attributes/shape/sksl-uniforms.d.ts +0 -146
  417. package/dist/attributes/shape/sksl-uniforms.d.ts.map +0 -1
  418. package/dist/attributes/shape/sksl-uniforms.js +0 -0
  419. package/dist/attributes/shape/sksl-uniforms.js.map +0 -1
  420. package/dist/browser/chunks/chunk-AOT33LMS.js.map +0 -7
  421. package/dist/browser/chunks/chunk-GKM6UZJR.js.map +0 -7
  422. package/dist/browser/chunks/chunk-LKUYVFU3.js.map +0 -7
  423. package/dist/browser/chunks/chunk-ZRPZPWZU.js.map +0 -7
  424. package/dist/component/api.d.ts +0 -508
  425. package/dist/component/api.d.ts.map +0 -1
  426. package/dist/component/api.js +0 -4
  427. package/dist/component/api.js.map +0 -1
  428. package/dist/component/builtins/audio.d.ts +0 -26
  429. package/dist/component/builtins/audio.d.ts.map +0 -1
  430. package/dist/component/builtins/audio.js +0 -41
  431. package/dist/component/builtins/audio.js.map +0 -1
  432. package/dist/component/builtins/canvas3d.d.ts +0 -98
  433. package/dist/component/builtins/canvas3d.d.ts.map +0 -1
  434. package/dist/component/builtins/canvas3d.js +0 -21
  435. package/dist/component/builtins/canvas3d.js.map +0 -1
  436. package/dist/component/builtins/composite.d.ts +0 -56
  437. package/dist/component/builtins/composite.d.ts.map +0 -1
  438. package/dist/component/builtins/composite.js +0 -25
  439. package/dist/component/builtins/composite.js.map +0 -1
  440. package/dist/component/builtins/geometry.d.ts +0 -505
  441. package/dist/component/builtins/geometry.d.ts.map +0 -1
  442. package/dist/component/builtins/geometry.js +0 -107
  443. package/dist/component/builtins/geometry.js.map +0 -1
  444. package/dist/component/builtins/layout.d.ts +0 -88
  445. package/dist/component/builtins/layout.d.ts.map +0 -1
  446. package/dist/component/builtins/layout.js +0 -84
  447. package/dist/component/builtins/layout.js.map +0 -1
  448. package/dist/component/builtins/media.d.ts +0 -95
  449. package/dist/component/builtins/media.d.ts.map +0 -1
  450. package/dist/component/builtins/media.js +0 -149
  451. package/dist/component/builtins/media.js.map +0 -1
  452. package/dist/component/builtins/providers.d.ts +0 -23
  453. package/dist/component/builtins/providers.d.ts.map +0 -1
  454. package/dist/component/builtins/providers.js +0 -30
  455. package/dist/component/builtins/providers.js.map +0 -1
  456. package/dist/component/builtins/text.d.ts +0 -193
  457. package/dist/component/builtins/text.d.ts.map +0 -1
  458. package/dist/component/builtins/text.js +0 -113
  459. package/dist/component/builtins/text.js.map +0 -1
  460. package/dist/component/builtins/three.d.ts +0 -1085
  461. package/dist/component/builtins/three.d.ts.map +0 -1
  462. package/dist/component/builtins/three.js +0 -265
  463. package/dist/component/builtins/three.js.map +0 -1
  464. package/dist/component/clip-of.d.ts +0 -5
  465. package/dist/component/clip-of.d.ts.map +0 -1
  466. package/dist/component/clip-of.js +0 -33
  467. package/dist/component/clip-of.js.map +0 -1
  468. package/dist/component/commands-for.d.ts +0 -19
  469. package/dist/component/commands-for.d.ts.map +0 -1
  470. package/dist/component/commands-for.js +0 -5
  471. package/dist/component/commands-for.js.map +0 -1
  472. package/dist/component/component-audio.d.ts +0 -9
  473. package/dist/component/component-audio.d.ts.map +0 -1
  474. package/dist/component/component-audio.js +0 -18
  475. package/dist/component/component-audio.js.map +0 -1
  476. package/dist/component/component2d.d.ts +0 -9
  477. package/dist/component/component2d.d.ts.map +0 -1
  478. package/dist/component/component2d.js +0 -239
  479. package/dist/component/component2d.js.map +0 -1
  480. package/dist/component/component3d.d.ts +0 -9
  481. package/dist/component/component3d.d.ts.map +0 -1
  482. package/dist/component/component3d.js +0 -99
  483. package/dist/component/component3d.js.map +0 -1
  484. package/dist/component/factory.d.ts +0 -63
  485. package/dist/component/factory.d.ts.map +0 -1
  486. package/dist/component/factory.js +0 -313
  487. package/dist/component/factory.js.map +0 -1
  488. package/dist/component/modules/aim.d.ts +0 -30
  489. package/dist/component/modules/aim.d.ts.map +0 -1
  490. package/dist/component/modules/aim.js +0 -39
  491. package/dist/component/modules/aim.js.map +0 -1
  492. package/dist/component/modules/corners.d.ts +0 -13
  493. package/dist/component/modules/corners.d.ts.map +0 -1
  494. package/dist/component/modules/corners.js +0 -12
  495. package/dist/component/modules/corners.js.map +0 -1
  496. package/dist/component/modules/flow.d.ts +0 -26
  497. package/dist/component/modules/flow.d.ts.map +0 -1
  498. package/dist/component/modules/flow.js +0 -55
  499. package/dist/component/modules/flow.js.map +0 -1
  500. package/dist/component/modules/material.d.ts +0 -40
  501. package/dist/component/modules/material.d.ts.map +0 -1
  502. package/dist/component/modules/material.js +0 -75
  503. package/dist/component/modules/material.js.map +0 -1
  504. package/dist/component/modules/paint.d.ts +0 -71
  505. package/dist/component/modules/paint.d.ts.map +0 -1
  506. package/dist/component/modules/paint.js +0 -106
  507. package/dist/component/modules/paint.js.map +0 -1
  508. package/dist/component/modules/shapes.d.ts +0 -31
  509. package/dist/component/modules/shapes.d.ts.map +0 -1
  510. package/dist/component/modules/shapes.js +0 -43
  511. package/dist/component/modules/shapes.js.map +0 -1
  512. package/dist/component/modules/text-layout.d.ts +0 -26
  513. package/dist/component/modules/text-layout.d.ts.map +0 -1
  514. package/dist/component/modules/text-layout.js +0 -57
  515. package/dist/component/modules/text-layout.js.map +0 -1
  516. package/dist/component/modules/text-style.d.ts +0 -48
  517. package/dist/component/modules/text-style.d.ts.map +0 -1
  518. package/dist/component/modules/text-style.js +0 -63
  519. package/dist/component/modules/text-style.js.map +0 -1
  520. package/dist/component/modules/three-entries.d.ts +0 -23
  521. package/dist/component/modules/three-entries.d.ts.map +0 -1
  522. package/dist/component/modules/three-entries.js +0 -41
  523. package/dist/component/modules/three-entries.js.map +0 -1
  524. package/dist/component/modules/view3d.d.ts +0 -55
  525. package/dist/component/modules/view3d.d.ts.map +0 -1
  526. package/dist/component/modules/view3d.js +0 -160
  527. package/dist/component/modules/view3d.js.map +0 -1
  528. package/dist/component/timeline.d.ts +0 -22
  529. package/dist/component/timeline.d.ts.map +0 -1
  530. package/dist/component/timeline.js +0 -128
  531. package/dist/component/timeline.js.map +0 -1
  532. package/dist/component/type-def.d.ts +0 -26
  533. package/dist/component/type-def.d.ts.map +0 -1
  534. package/dist/component/type-def.js +0 -16
  535. package/dist/component/type-def.js.map +0 -1
  536. package/dist/component/types.d.ts +0 -91
  537. package/dist/component/types.d.ts.map +0 -1
  538. package/dist/component/types.js +0 -88
  539. package/dist/component/types.js.map +0 -1
  540. package/dist/component/views.d.ts +0 -121
  541. package/dist/component/views.d.ts.map +0 -1
  542. package/dist/component/views.js +0 -413
  543. package/dist/component/views.js.map +0 -1
  544. package/dist/document/withdraw.d.ts +0 -28
  545. package/dist/document/withdraw.d.ts.map +0 -1
  546. package/dist/document/withdraw.js +0 -61
  547. package/dist/document/withdraw.js.map +0 -1
  548. package/dist/jsx/jsx-dev-runtime.d.ts +0 -3
  549. package/dist/jsx/jsx-dev-runtime.d.ts.map +0 -1
  550. package/dist/jsx/jsx-dev-runtime.js +0 -3
  551. package/dist/jsx/jsx-dev-runtime.js.map +0 -1
  552. package/dist/jsx/jsx-runtime.d.ts +0 -27
  553. package/dist/jsx/jsx-runtime.d.ts.map +0 -1
  554. package/dist/jsx/jsx-runtime.js +0 -26
  555. package/dist/jsx/jsx-runtime.js.map +0 -1
  556. package/dist/nodes/2d/node-lifecycle.d.ts +0 -46
  557. package/dist/nodes/2d/node-lifecycle.d.ts.map +0 -1
  558. package/dist/nodes/2d/node-lifecycle.js +0 -264
  559. package/dist/nodes/2d/node-lifecycle.js.map +0 -1
  560. package/dist/nodes/2d/node-motion.d.ts +0 -56
  561. package/dist/nodes/2d/node-motion.d.ts.map +0 -1
  562. package/dist/nodes/2d/node-motion.js +0 -86
  563. package/dist/nodes/2d/node-motion.js.map +0 -1
  564. package/dist/nodes/2d/node-render.d.ts +0 -44
  565. package/dist/nodes/2d/node-render.d.ts.map +0 -1
  566. package/dist/nodes/2d/node-render.js +0 -80
  567. package/dist/nodes/2d/node-render.js.map +0 -1
  568. package/dist/nodes/2d/node-space.d.ts +0 -63
  569. package/dist/nodes/2d/node-space.d.ts.map +0 -1
  570. package/dist/nodes/2d/node-space.js +0 -131
  571. package/dist/nodes/2d/node-space.js.map +0 -1
  572. package/dist/nodes/2d/node-transform.d.ts +0 -55
  573. package/dist/nodes/2d/node-transform.d.ts.map +0 -1
  574. package/dist/nodes/2d/node-transform.js +0 -73
  575. package/dist/nodes/2d/node-transform.js.map +0 -1
  576. package/dist/nodes/2d/node2d.d.ts +0 -1111
  577. package/dist/nodes/2d/node2d.d.ts.map +0 -1
  578. package/dist/nodes/2d/node2d.js +0 -1665
  579. package/dist/nodes/2d/node2d.js.map +0 -1
  580. package/dist/nodes/2d/paint-node.d.ts +0 -142
  581. package/dist/nodes/2d/paint-node.d.ts.map +0 -1
  582. package/dist/nodes/2d/paint-node.js +0 -232
  583. package/dist/nodes/2d/paint-node.js.map +0 -1
  584. package/dist/nodes/audio/audio-bus.d.ts +0 -28
  585. package/dist/nodes/audio/audio-bus.d.ts.map +0 -1
  586. package/dist/nodes/audio/audio-bus.js +0 -33
  587. package/dist/nodes/audio/audio-bus.js.map +0 -1
  588. package/dist/nodes/audio/index.d.ts +0 -4
  589. package/dist/nodes/audio/index.d.ts.map +0 -1
  590. package/dist/nodes/audio/index.js +0 -2
  591. package/dist/nodes/audio/index.js.map +0 -1
  592. package/dist/nodes/audio/node-audio.d.ts +0 -107
  593. package/dist/nodes/audio/node-audio.d.ts.map +0 -1
  594. package/dist/nodes/audio/node-audio.js +0 -179
  595. package/dist/nodes/audio/node-audio.js.map +0 -1
  596. package/dist/nodes/audio/sound-node.d.ts +0 -41
  597. package/dist/nodes/audio/sound-node.d.ts.map +0 -1
  598. package/dist/nodes/audio/sound-node.js +0 -71
  599. package/dist/nodes/audio/sound-node.js.map +0 -1
  600. package/dist/nodes/geometry/boolean-node.d.ts +0 -28
  601. package/dist/nodes/geometry/boolean-node.d.ts.map +0 -1
  602. package/dist/nodes/geometry/boolean-node.js +0 -81
  603. package/dist/nodes/geometry/boolean-node.js.map +0 -1
  604. package/dist/nodes/geometry/bounds-shape-node.d.ts +0 -149
  605. package/dist/nodes/geometry/bounds-shape-node.d.ts.map +0 -1
  606. package/dist/nodes/geometry/bounds-shape-node.js +0 -181
  607. package/dist/nodes/geometry/bounds-shape-node.js.map +0 -1
  608. package/dist/nodes/geometry/box-path-node.d.ts +0 -89
  609. package/dist/nodes/geometry/box-path-node.d.ts.map +0 -1
  610. package/dist/nodes/geometry/box-path-node.js +0 -116
  611. package/dist/nodes/geometry/box-path-node.js.map +0 -1
  612. package/dist/nodes/geometry/ellipse-node.d.ts +0 -18
  613. package/dist/nodes/geometry/ellipse-node.d.ts.map +0 -1
  614. package/dist/nodes/geometry/ellipse-node.js +0 -45
  615. package/dist/nodes/geometry/ellipse-node.js.map +0 -1
  616. package/dist/nodes/geometry/group-bounds.d.ts +0 -56
  617. package/dist/nodes/geometry/group-bounds.d.ts.map +0 -1
  618. package/dist/nodes/geometry/group-bounds.js +0 -87
  619. package/dist/nodes/geometry/group-bounds.js.map +0 -1
  620. package/dist/nodes/geometry/mask-node.d.ts +0 -33
  621. package/dist/nodes/geometry/mask-node.d.ts.map +0 -1
  622. package/dist/nodes/geometry/mask-node.js +0 -66
  623. package/dist/nodes/geometry/mask-node.js.map +0 -1
  624. package/dist/nodes/geometry/path-node.d.ts +0 -26
  625. package/dist/nodes/geometry/path-node.d.ts.map +0 -1
  626. package/dist/nodes/geometry/path-node.js +0 -58
  627. package/dist/nodes/geometry/path-node.js.map +0 -1
  628. package/dist/nodes/geometry/polygon-node.d.ts +0 -26
  629. package/dist/nodes/geometry/polygon-node.d.ts.map +0 -1
  630. package/dist/nodes/geometry/polygon-node.js +0 -47
  631. package/dist/nodes/geometry/polygon-node.js.map +0 -1
  632. package/dist/nodes/geometry/polygram-node.d.ts +0 -33
  633. package/dist/nodes/geometry/polygram-node.d.ts.map +0 -1
  634. package/dist/nodes/geometry/polygram-node.js +0 -52
  635. package/dist/nodes/geometry/polygram-node.js.map +0 -1
  636. package/dist/nodes/geometry/rect-node.d.ts +0 -38
  637. package/dist/nodes/geometry/rect-node.d.ts.map +0 -1
  638. package/dist/nodes/geometry/rect-node.js +0 -56
  639. package/dist/nodes/geometry/rect-node.js.map +0 -1
  640. package/dist/nodes/geometry/shape-node.d.ts +0 -71
  641. package/dist/nodes/geometry/shape-node.d.ts.map +0 -1
  642. package/dist/nodes/geometry/shape-node.js +0 -140
  643. package/dist/nodes/geometry/shape-node.js.map +0 -1
  644. package/dist/nodes/geometry/shape-outline.d.ts +0 -93
  645. package/dist/nodes/geometry/shape-outline.d.ts.map +0 -1
  646. package/dist/nodes/geometry/shape-outline.js +0 -470
  647. package/dist/nodes/geometry/shape-outline.js.map +0 -1
  648. package/dist/nodes/index.d.ts +0 -53
  649. package/dist/nodes/index.d.ts.map +0 -1
  650. package/dist/nodes/index.js +0 -35
  651. package/dist/nodes/index.js.map +0 -1
  652. package/dist/nodes/layout/camera-node.d.ts +0 -80
  653. package/dist/nodes/layout/camera-node.d.ts.map +0 -1
  654. package/dist/nodes/layout/camera-node.js +0 -153
  655. package/dist/nodes/layout/camera-node.js.map +0 -1
  656. package/dist/nodes/layout/orbit-camera-node.d.ts +0 -80
  657. package/dist/nodes/layout/orbit-camera-node.d.ts.map +0 -1
  658. package/dist/nodes/layout/orbit-camera-node.js +0 -118
  659. package/dist/nodes/layout/orbit-camera-node.js.map +0 -1
  660. package/dist/nodes/layout/rotated-box.d.ts +0 -20
  661. package/dist/nodes/layout/rotated-box.d.ts.map +0 -1
  662. package/dist/nodes/layout/rotated-box.js +0 -76
  663. package/dist/nodes/layout/rotated-box.js.map +0 -1
  664. package/dist/nodes/media/video-node.d.ts +0 -229
  665. package/dist/nodes/media/video-node.d.ts.map +0 -1
  666. package/dist/nodes/media/video-node.js +0 -350
  667. package/dist/nodes/media/video-node.js.map +0 -1
  668. package/dist/nodes/node/declare-paints.d.ts +0 -19
  669. package/dist/nodes/node/declare-paints.d.ts.map +0 -1
  670. package/dist/nodes/node/declare-paints.js +0 -27
  671. package/dist/nodes/node/declare-paints.js.map +0 -1
  672. package/dist/nodes/node/node-editor-state.d.ts +0 -53
  673. package/dist/nodes/node/node-editor-state.d.ts.map +0 -1
  674. package/dist/nodes/node/node-editor-state.js +0 -23
  675. package/dist/nodes/node/node-editor-state.js.map +0 -1
  676. package/dist/nodes/node/node-reactive.d.ts +0 -89
  677. package/dist/nodes/node/node-reactive.d.ts.map +0 -1
  678. package/dist/nodes/node/node-reactive.js +0 -135
  679. package/dist/nodes/node/node-reactive.js.map +0 -1
  680. package/dist/nodes/node/node-time.d.ts +0 -39
  681. package/dist/nodes/node/node-time.d.ts.map +0 -1
  682. package/dist/nodes/node/node-time.js +0 -14
  683. package/dist/nodes/node/node-time.js.map +0 -1
  684. package/dist/nodes/node/node-walk.d.ts +0 -46
  685. package/dist/nodes/node/node-walk.d.ts.map +0 -1
  686. package/dist/nodes/node/node-walk.js +0 -74
  687. package/dist/nodes/node/node-walk.js.map +0 -1
  688. package/dist/nodes/node/node.d.ts +0 -445
  689. package/dist/nodes/node/node.d.ts.map +0 -1
  690. package/dist/nodes/node/node.js +0 -745
  691. package/dist/nodes/node/node.js.map +0 -1
  692. package/dist/nodes/node/text-defaults.d.ts +0 -32
  693. package/dist/nodes/node/text-defaults.d.ts.map +0 -1
  694. package/dist/nodes/node/text-defaults.js +0 -37
  695. package/dist/nodes/node/text-defaults.js.map +0 -1
  696. package/dist/nodes/root/canvas2d-node.d.ts +0 -163
  697. package/dist/nodes/root/canvas2d-node.d.ts.map +0 -1
  698. package/dist/nodes/root/canvas2d-node.js +0 -264
  699. package/dist/nodes/root/canvas2d-node.js.map +0 -1
  700. package/dist/nodes/root/provider-node.d.ts +0 -47
  701. package/dist/nodes/root/provider-node.d.ts.map +0 -1
  702. package/dist/nodes/root/provider-node.js +0 -63
  703. package/dist/nodes/root/provider-node.js.map +0 -1
  704. package/dist/nodes/root/theme-provider-node.d.ts +0 -29
  705. package/dist/nodes/root/theme-provider-node.d.ts.map +0 -1
  706. package/dist/nodes/root/theme-provider-node.js +0 -43
  707. package/dist/nodes/root/theme-provider-node.js.map +0 -1
  708. package/dist/nodes/text/default-text-style-node.d.ts +0 -103
  709. package/dist/nodes/text/default-text-style-node.d.ts.map +0 -1
  710. package/dist/nodes/text/default-text-style-node.js +0 -146
  711. package/dist/nodes/text/default-text-style-node.js.map +0 -1
  712. package/dist/nodes/text/number-format.d.ts +0 -66
  713. package/dist/nodes/text/number-format.d.ts.map +0 -1
  714. package/dist/nodes/text/number-format.js +0 -227
  715. package/dist/nodes/text/number-format.js.map +0 -1
  716. package/dist/nodes/text/number-node.d.ts +0 -94
  717. package/dist/nodes/text/number-node.d.ts.map +0 -1
  718. package/dist/nodes/text/number-node.js +0 -86
  719. package/dist/nodes/text/number-node.js.map +0 -1
  720. package/dist/nodes/text/number-pattern.d.ts +0 -51
  721. package/dist/nodes/text/number-pattern.d.ts.map +0 -1
  722. package/dist/nodes/text/number-pattern.js +0 -77
  723. package/dist/nodes/text/number-pattern.js.map +0 -1
  724. package/dist/nodes/text/richtext-node.d.ts +0 -68
  725. package/dist/nodes/text/richtext-node.d.ts.map +0 -1
  726. package/dist/nodes/text/richtext-node.js +0 -78
  727. package/dist/nodes/text/richtext-node.js.map +0 -1
  728. package/dist/nodes/text/text-base.d.ts +0 -118
  729. package/dist/nodes/text/text-base.d.ts.map +0 -1
  730. package/dist/nodes/text/text-base.js +0 -153
  731. package/dist/nodes/text/text-base.js.map +0 -1
  732. package/dist/nodes/text/text-layout.d.ts +0 -87
  733. package/dist/nodes/text/text-layout.d.ts.map +0 -1
  734. package/dist/nodes/text/text-layout.js +0 -368
  735. package/dist/nodes/text/text-layout.js.map +0 -1
  736. package/dist/nodes/text/text-node.d.ts +0 -84
  737. package/dist/nodes/text/text-node.d.ts.map +0 -1
  738. package/dist/nodes/text/text-node.js +0 -188
  739. package/dist/nodes/text/text-node.js.map +0 -1
  740. package/dist/nodes/text/text-selection.d.ts +0 -125
  741. package/dist/nodes/text/text-selection.d.ts.map +0 -1
  742. package/dist/nodes/text/text-selection.js +0 -209
  743. package/dist/nodes/text/text-selection.js.map +0 -1
  744. package/dist/nodes/three/camera-nodes.d.ts +0 -109
  745. package/dist/nodes/three/camera-nodes.d.ts.map +0 -1
  746. package/dist/nodes/three/camera-nodes.js +0 -112
  747. package/dist/nodes/three/camera-nodes.js.map +0 -1
  748. package/dist/nodes/three/canvas3d-node.d.ts +0 -295
  749. package/dist/nodes/three/canvas3d-node.d.ts.map +0 -1
  750. package/dist/nodes/three/canvas3d-node.js +0 -486
  751. package/dist/nodes/three/canvas3d-node.js.map +0 -1
  752. package/dist/nodes/three/drawable-nodes.d.ts +0 -173
  753. package/dist/nodes/three/drawable-nodes.d.ts.map +0 -1
  754. package/dist/nodes/three/drawable-nodes.js +0 -284
  755. package/dist/nodes/three/drawable-nodes.js.map +0 -1
  756. package/dist/nodes/three/environment-nodes.d.ts +0 -106
  757. package/dist/nodes/three/environment-nodes.d.ts.map +0 -1
  758. package/dist/nodes/three/environment-nodes.js +0 -134
  759. package/dist/nodes/three/environment-nodes.js.map +0 -1
  760. package/dist/nodes/three/geometry-nodes.d.ts +0 -197
  761. package/dist/nodes/three/geometry-nodes.d.ts.map +0 -1
  762. package/dist/nodes/three/geometry-nodes.js +0 -322
  763. package/dist/nodes/three/geometry-nodes.js.map +0 -1
  764. package/dist/nodes/three/grid-geometry3d.d.ts +0 -62
  765. package/dist/nodes/three/grid-geometry3d.d.ts.map +0 -1
  766. package/dist/nodes/three/grid-geometry3d.js +0 -114
  767. package/dist/nodes/three/grid-geometry3d.js.map +0 -1
  768. package/dist/nodes/three/group3d.d.ts +0 -23
  769. package/dist/nodes/three/group3d.d.ts.map +0 -1
  770. package/dist/nodes/three/group3d.js +0 -21
  771. package/dist/nodes/three/group3d.js.map +0 -1
  772. package/dist/nodes/three/light-nodes.d.ts +0 -120
  773. package/dist/nodes/three/light-nodes.d.ts.map +0 -1
  774. package/dist/nodes/three/light-nodes.js +0 -173
  775. package/dist/nodes/three/light-nodes.js.map +0 -1
  776. package/dist/nodes/three/mesh3d.d.ts +0 -117
  777. package/dist/nodes/three/mesh3d.d.ts.map +0 -1
  778. package/dist/nodes/three/mesh3d.js +0 -147
  779. package/dist/nodes/three/mesh3d.js.map +0 -1
  780. package/dist/nodes/three/node3d.d.ts +0 -230
  781. package/dist/nodes/three/node3d.d.ts.map +0 -1
  782. package/dist/nodes/three/node3d.js +0 -337
  783. package/dist/nodes/three/node3d.js.map +0 -1
  784. package/dist/render/descriptors/latex.d.ts +0 -6
  785. package/dist/render/descriptors/latex.d.ts.map +0 -1
  786. package/dist/render/descriptors/latex.js +0 -2
  787. package/dist/render/descriptors/latex.js.map +0 -1
  788. package/dist/tween/seekable.d.ts +0 -81
  789. package/dist/tween/seekable.d.ts.map +0 -1
  790. package/dist/tween/seekable.js +0 -137
  791. package/dist/tween/seekable.js.map +0 -1
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/attributes/shape/corners/corners.ts", "../../../src/attributes/shape/corners/corner-radius.ts", "../../../src/attributes/shape/corners/corner-style.ts", "../../../src/attributes/shape/effects/effect-data.ts", "../../../src/attributes/shape/fill/lerp.ts", "../../../src/attributes/shape/effects/spec.ts", "../../../src/attributes/shape/effects/implementations/motion-blur.ts", "../../../src/attributes/shape/effects/implementations/ascii.ts", "../../../src/attributes/shape/fill/blend.ts", "../../../src/attributes/shape/shaders/uniforms.ts", "../../../src/attributes/shape/shaders/language.ts", "../../../src/attributes/shape/effects/implementations/blur.ts", "../../../src/attributes/shape/effects/implementations/directional-blur.ts", "../../../src/attributes/shape/effects/implementations/grayscale.ts", "../../../src/attributes/shape/effects/implementations/pixelate.ts", "../../../src/attributes/shape/effects/implementations/bulge.ts", "../../../src/attributes/shape/effects/implementations/magnify.ts", "../../../src/attributes/shape/effects/implementations/bloom.ts", "../../../src/attributes/shape/effects/implementations/vintage.ts", "../../../src/attributes/shape/effects/implementations/chromatic-aberration.ts", "../../../src/attributes/shape/effects/implementations/invert.ts", "../../../src/attributes/shape/effects/implementations/scatter.ts", "../../../src/attributes/shape/effects/implementations/posterize.ts", "../../../src/attributes/shape/effects/implementations/shader.ts", "../../../src/attributes/shape/effects/implementations/outline.ts", "../../../src/attributes/shape/effects/implementations/drop-shadow.ts", "../../../src/attributes/shape/effects/implementations/vignette.ts", "../../../src/attributes/shape/effects/implementations/grain.ts", "../../../src/attributes/shape/effects/implementations/sharpen.ts", "../../../src/attributes/shape/effects/implementations/edges.ts", "../../../src/attributes/shape/effects/implementations/threshold.ts", "../../../src/attributes/shape/effects/implementations/radial-blur.ts", "../../../src/attributes/shape/effects/implementations/halftone.ts", "../../../src/attributes/shape/effects/implementations/dither.ts", "../../../src/attributes/shape/effects/implementations/duotone.ts", "../../../src/attributes/shape/effects/implementations/curves.ts", "../../../src/attributes/shape/effects/implementations/color-adjustment.ts", "../../../src/attributes/shape/effects/implementations/rgb-shift.ts", "../../../src/attributes/shape/effects/implementations/scanlines.ts", "../../../src/attributes/shape/effects/implementations/block-displace.ts", "../../../src/attributes/shape/effects/implementations/bit-crush.ts", "../../../src/attributes/shape/effects/implementations/streak.ts", "../../../src/attributes/shape/effects/implementations/glow.ts", "../../../src/attributes/shape/effects/implementations/oil-paint.ts", "../../../src/attributes/shape/effects/implementations/wave.ts", "../../../src/attributes/shape/effects/implementations/twirl.ts", "../../../src/attributes/shape/effects/implementations/progressive-blur.ts", "../../../src/attributes/shape/effects/implementations/kaleidoscope.ts", "../../../src/attributes/shape/effects/implementations/glass.ts", "../../../src/attributes/shape/effects/implementations/lut.ts", "../../../src/attributes/shape/effects/registry.ts", "../../../src/attributes/shape/shaders/resolve.ts", "../../../src/attributes/shape/effects/chain.ts", "../../../src/attributes/shape/effects/backdrop.ts", "../../../src/attributes/shape/fill/chain.ts", "../../../src/attributes/shape/fill/implementations/grid.ts", "../../../src/attributes/shape/filters/implementations/exposure.ts", "../../../src/attributes/shape/filters/implementations/blur.ts", "../../../src/attributes/shape/filters/implementations/grayscale.ts", "../../../src/attributes/shape/filters/implementations/alpha.ts", "../../../src/attributes/shape/filters/implementations/color-matrix.ts", "../../../src/attributes/shape/filters/implementations/curves.ts", "../../../src/attributes/shape/filters/implementations/color-adjustment.ts", "../../../src/attributes/shape/filters/implementations/posterize-time.ts", "../../../src/attributes/shape/filters/implementations/echo.ts", "../../../src/attributes/shape/filters/registry.ts", "../../../src/attributes/shape/filters/chain.ts", "../../../src/attributes/layout/alignment.ts", "../../../src/attributes/layout/insets.ts", "../../../src/attributes/shape/fill/media-preset.ts", "../../../src/attributes/shape/fill/implementations/image.ts", "../../../src/attributes/shape/fill/implementations/video.ts", "../../../src/render/descriptors/path-builder.ts", "../../../src/render/graphics2d.ts", "../../../src/render3d/texture.ts", "../../../src/render3d/fill3d.ts", "../../../src/render3d/inert.ts", "../../../src/render3d/graphics3d.ts", "../../../src/render3d/render-context3d.ts", "../../../src/render3d/scene-settings.ts", "../../../src/render3d/scene3d.ts", "../../../src/render3d/resources.ts", "../../../src/render3d/walk.ts", "../../../src/attributes/shape/fill/coerce.ts", "../../../src/attributes/shape/fill/implementations/color.ts", "../../../src/attributes/shape/fill/gradient-stops.ts", "../../../src/attributes/shape/fill/implementations/linear-gradient.ts", "../../../src/attributes/shape/fill/implementations/radial-gradient.ts", "../../../src/attributes/shape/fill/implementations/conic-gradient.ts", "../../../src/attributes/shape/fill/implementations/noise.ts", "../../../src/attributes/shape/fill/implementations/fractal-noise.ts", "../../../src/attributes/shape/fill/implementations/stripe.ts", "../../../src/attributes/shape/fill/implementations/dot-grid.ts", "../../../src/attributes/shape/fill/implementations/shader.ts", "../../../src/render3d/tracking.ts", "../../../src/attributes/shape/fill/implementations/canvas3d.ts", "../../../src/attributes/shape/fill/registry.ts", "../../../src/attributes/shape/shadow/shadow.ts", "../../../src/attributes/shape/stroke/stroke.ts", "../../../src/util/clamp.ts", "../../../src/tween/ease/describe.ts", "../../../src/tween/ease/constants.ts", "../../../src/tween/ease/curve.ts", "../../../src/tween/ease/spec.ts", "../../../src/attributes/audio/ramp.ts", "../../../src/attributes/audio/effects/chain.ts", "../../../src/attributes/audio/effects/implementations/gain.ts", "../../../src/attributes/audio/effects/implementations/highpass.ts", "../../../src/attributes/audio/effects/implementations/lowpass.ts", "../../../src/attributes/audio/effects/implementations/tremolo.ts", "../../../src/attributes/audio/effects/implementations/echo.ts", "../../../src/attributes/audio/effects/registry.ts", "../../../src/attributes/layout/matrix2d.ts", "../../../src/attributes/layout/space3d.ts", "../../../src/attributes/layout/size.ts", "../../../src/attributes/text/ops.ts", "../../../src/attributes/properties/decorator.ts", "../../../src/props/slot.ts", "../../../src/tween/to-command.ts", "../../../src/tween/loop.ts", "../../../src/tween/command.ts", "../../../src/tween/prepare.ts", "../../../src/util/context.ts", "../../../src/props/host.ts", "../../../src/tween/command-decorator.ts", "../../../src/props/observer.ts", "../../../src/tween/inert.ts", "../../../src/components/trees/node/node-reactive.ts", "../../../src/components/trees/node/node-time.ts", "../../../src/components/trees/node/node.ts", "../../../src/assets/errors.ts", "../../../src/layout/item.ts", "../../../src/layout/flex.ts", "../../../src/layout/freeform.ts", "../../../src/layout/grid.ts", "../../../src/layout/ops.ts", "../../../src/render3d/vector3.ts", "../../../src/render/clip.ts", "../../../src/attributes/properties/typed.ts", "../../../src/components/trees/2d/node-motion.ts", "../../../src/components/trees/2d/node-lifecycle.ts", "../../../src/attributes/layout/transform3d.ts", "../../../src/components/trees/2d/node-transform.ts", "../../../src/components/trees/2d/node-space.ts", "../../../src/components/trees/2d/node-render.ts", "../../../src/components/trees/2d/node2d.ts", "../../../src/components/trees/audio/node-audio.ts", "../../../src/components/trees/three/node3d.ts", "../../../src/document/node-decorator.ts", "../../../src/render/descriptors/shape.ts", "../../../src/render/descriptors/rect.ts", "../../../src/render/descriptors/ellipse.ts", "../../../src/render/descriptors/polygon.ts", "../../../src/render/descriptors/polygram.ts", "../../../src/render/descriptors/line.ts", "../../../src/render/clip-contains.ts", "../../../src/document/expression/types.ts", "../../../src/document/expression/parse.ts", "../../../src/document/expression/compile.ts", "../../../src/document/expression/walk.ts", "../../../src/document/expression/ops.ts", "../../../src/document/prop-evolution.ts", "../../../src/render/text-defaults.ts", "../../../src/render/canvas-render-context2d.ts", "../../../src/render/null-render-context.ts", "../../../src/components/factory/clip-of.ts", "../../../src/components/factory/timeline.ts", "../../../src/components/factory/type-def.ts", "../../../src/components/factory/views.ts", "../../../src/components/factory/factory.ts", "../../../src/components/trees/2d/group-bounds.ts", "../../../src/components/factory/component2d.ts", "../../../src/components/factory/types.ts", "../../../src/components/modules/corners.ts", "../../../src/components/modules/flow.ts", "../../../src/components/factory/commands-for.ts", "../../../src/components/modules/paint.ts", "../../../src/components/modules/shapes.ts", "../../../src/components/modules/aim.ts", "../../../src/render/descriptors/text.ts", "../../../src/components/modules/text-layout.ts", "../../../src/components/builtins/text/text-layout.ts", "../../../src/runtime/builtin-context.ts", "../../../src/components/factory/api.ts", "../../../src/components/modules/text-style.ts", "../../../src/components/factory/component-audio.ts", "../../../src/components/factory/component3d.ts", "../../../src/components/modules/material.ts", "../../../src/components/modules/three-entries.ts", "../../../src/components/modules/view3d.ts", "../../../src/components/builtins/three/grid-geometry3d.ts"],
4
+ "sourcesContent": ["import { LerpFunction } from \"@/tween/lerp\";\n\n/** A value supplied independently for each of the four corners. */\nexport interface Corners<T> {\n topLeft: T;\n topRight: T;\n bottomLeft: T;\n bottomRight: T;\n}\n\n/**\n * The accepted input grammar for any per-corner property (radius, style),\n * generic over the corner value type `T`:\n *\n * - a single `T` applies uniformly to all four corners;\n * - `{ topLeft, … }` overrides individual corners (unspecified corners fall back\n * to a previous value or the type's default when resolved);\n * - `{ top, bottom }` sets the top pair (`topLeft`, `topRight`) and/or the bottom\n * pair (`bottomLeft`, `bottomRight`);\n * - `{ left, right }` sets the left pair (`topLeft`, `bottomLeft`) and/or the\n * right pair (`topRight`, `bottomRight`).\n */\nexport type CornersInput<T> =\n | T\n | Partial<Corners<T>>\n | { top?: T; bottom?: T }\n | { left?: T; right?: T };\n\n/** Narrows a {@link CornersInput} to its scalar form. */\nexport type CornerScalarGuard<T> = (value: CornersInput<T>) => value is T;\n\nfunction makeUniform<T>(value: T): Corners<T> {\n return { topLeft: value, topRight: value, bottomLeft: value, bottomRight: value };\n}\n\n// The {top,bottom} / {left,right} axis shorthands map to corners as documented\n// on CornersInput. Centralised here so the mapping is a single, test-pinned\n// chokepoint rather than scattered across the resolver.\nfunction fromTopBottom<T>(v: { top?: T; bottom?: T }, fb: Corners<T>): Corners<T> {\n return {\n topLeft: v.top ?? fb.topLeft,\n topRight: v.top ?? fb.topRight,\n bottomLeft: v.bottom ?? fb.bottomLeft,\n bottomRight: v.bottom ?? fb.bottomRight,\n };\n}\n\nfunction fromLeftRight<T>(v: { left?: T; right?: T }, fb: Corners<T>): Corners<T> {\n return {\n topLeft: v.left ?? fb.topLeft,\n topRight: v.right ?? fb.topRight,\n bottomLeft: v.left ?? fb.bottomLeft,\n bottomRight: v.right ?? fb.bottomRight,\n };\n}\n\n/**\n * Resolves a {@link CornersInput} into a fully-specified {@link Corners}.\n *\n * Precedence per corner mirrors the rest of the codebase's mappers:\n * supplied value → `previous` → `fallback`. `isScalar` discriminates the scalar\n * form from the object forms (e.g. `typeof v === \"number\"` for radius, or a\n * string-literal check for style).\n */\nexport function resolveCorners<T>(\n value: CornersInput<T>,\n fallback: T,\n previous: Corners<T> | undefined,\n isScalar: CornerScalarGuard<T>,\n): Corners<T> {\n if (isScalar(value)) {\n return makeUniform(value);\n }\n\n const fb: Corners<T> = previous ?? makeUniform(fallback);\n const obj = value as Record<string, T | undefined>;\n\n // Per-corner keys take precedence over the axis shorthands when mixed, so\n // the more specific form wins.\n if (\"topLeft\" in obj || \"topRight\" in obj || \"bottomLeft\" in obj || \"bottomRight\" in obj) {\n const v = value as Partial<Corners<T>>;\n return {\n topLeft: v.topLeft ?? fb.topLeft,\n topRight: v.topRight ?? fb.topRight,\n bottomLeft: v.bottomLeft ?? fb.bottomLeft,\n bottomRight: v.bottomRight ?? fb.bottomRight,\n };\n }\n if (\"top\" in obj || \"bottom\" in obj) {\n return fromTopBottom(value as { top?: T; bottom?: T }, fb);\n }\n if (\"left\" in obj || \"right\" in obj) {\n return fromLeftRight(value as { left?: T; right?: T }, fb);\n }\n // Empty object: keep the fallback for every corner.\n return { ...fb };\n}\n\n/** Interpolates each corner independently with the supplied per-value lerp. */\nexport function lerpCorners<T>(\n from: Corners<T>,\n to: Corners<T>,\n t: number,\n lerp: LerpFunction<T>,\n): Corners<T> {\n return {\n topLeft: lerp(from.topLeft, to.topLeft, t),\n topRight: lerp(from.topRight, to.topRight, t),\n bottomLeft: lerp(from.bottomLeft, to.bottomLeft, t),\n bottomRight: lerp(from.bottomRight, to.bottomRight, t),\n };\n}\n\n/** Returns true when all four corners are equal (under `eq`, default `Object.is`). */\nexport function isUniformCorners<T>(c: Corners<T>, eq: (a: T, b: T) => boolean = Object.is): boolean {\n return eq(c.topLeft, c.topRight) && eq(c.topLeft, c.bottomLeft) && eq(c.topLeft, c.bottomRight);\n}\n", "import { lerpNumber } from \"@/tween/lerp\";\nimport type { CornerRadiusOps } from \"@/attributes/shared/operators\";\nimport { Corners, CornersInput, resolveCorners, lerpCorners, isUniformCorners } from \"./corners\";\n\n/** Per-corner border radius values, all fully resolved to numbers. */\nexport type CornerRadiusResolved = Corners<number>;\n\n/**\n * Accepted corner radius input for a Rect: a single number applies uniformly to\n * all corners; an object overrides corners individually (`{ topLeft, … }`) or by\n * axis (`{ top, bottom }` / `{ left, right }`). An already-resolved value passes\n * through. Unspecified corners fall back to a previous value or 0 when resolved.\n */\nexport type RectCornerRadius = CornersInput<number> | CornerRadiusResolved;\n\n/**\n * The corner-radius attribute's op set: `resolve`/`lerp` for `Shapes.corners`,\n * plus the uniform/zero checks a renderer needs to pick a cheap draw path.\n */\nexport const cornerRadiusOps: CornerRadiusOps = {\n // A resolved value is structurally a full per-corner `CornersInput<number>`,\n // so pin T=number and let resolveCorners re-resolve it idempotently.\n resolve: (value, previous) => resolveCorners(value as CornersInput<number>, 0, previous, (v): v is number => typeof v === \"number\"),\n lerp: (from, to, t) => lerpCorners(from, to, t, lerpNumber),\n isUniformInput: (value): value is number => typeof value === \"number\",\n isUniform: (value) => isUniformCorners(value),\n isZero: (value) => value.topLeft === 0 && value.topRight === 0 && value.bottomLeft === 0 && value.bottomRight === 0,\n};\n", "import { LerpFunction } from \"@/tween/lerp\";\nimport type { AttributeOps, HasUniformCheck } from \"@/attributes/shared/operators\";\nimport { Corners, CornersInput, resolveCorners, lerpCorners, isUniformCorners } from \"./corners\";\n\n/**\n * How a single corner is shaped once it has a non-zero radius:\n * - `'rounded'` — a circular arc;\n * - `'angled'` — a straight diagonal chamfer cut across the corner.\n */\nexport type CornerStyle = \"rounded\" | \"angled\";\n\n/** Per-corner resolved styles. */\nexport type CornerStyleResolved = Corners<CornerStyle>;\n\n/**\n * Accepted corner style input for a Rect: a single {@link CornerStyle} applies to\n * all corners; an object overrides corners individually (`{ topLeft, … }`) or by\n * axis (`{ top, bottom }` / `{ left, right }`). An already-resolved value passes\n * through. Unspecified corners fall back to a previous value or `'rounded'` when\n * resolved.\n */\nexport type RectCornerStyle = CornersInput<CornerStyle> | CornerStyleResolved;\n\n/**\n * The corner-style attribute's op set — no zero check, since style has no zero\n * value. \"Interpolating\" corner styles means snapping at the midpoint — corner\n * style is a discrete enum, so it switches at `t = 0.5` rather than blending,\n * matching the codebase's convention for discrete properties (see e.g. the\n * pixelate effect).\n */\nexport const cornerStyleOps: AttributeOps<RectCornerStyle, CornerStyleResolved>\n & HasUniformCheck<RectCornerStyle, CornerStyleResolved> = {\n resolve: (value, previous) => resolveCorners(value as CornersInput<CornerStyle>, \"rounded\", previous, (v): v is CornerStyle => v === \"rounded\" || v === \"angled\"),\n lerp: (from, to, t) => lerpCorners(from, to, t, (f, g) => (t < 0.5 ? f : g)),\n isUniformInput: (value): value is CornerStyle => value === \"rounded\" || value === \"angled\",\n isUniform: (value) => isUniformCorners(value),\n};\n\n/**\n * Scalar (single-value) corner style tween for shapes whose vertices don't map to\n * named corners — polygons and polygrams apply one style to every vertex, so they\n * use this instead of {@link cornerStyleOps}'s per-corner form.\n */\nexport const lerpCornerScalarStyle: LerpFunction<CornerStyle> = (from, to, t) => (t < 0.5 ? from : to);\n", "import type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { AssetScope } from \"@/assets/scope\";\nimport type { Color, NormalizedColor } from \"../fill/color/parser\";\nimport { parseColor } from \"../fill/color/parser\";\n\n/**\n * Which layer an effect runs on: the node's own content (`\"foreground\"`, the\n * default) or the **backdrop** — the content already painted beneath the node.\n * A backdrop effect is applied to whatever lies underneath the node and clipped\n * to the node's silhouette, so the node's own edges stay sharp (Figma-style).\n */\nexport type EffectMode = \"foreground\" | \"backdrop\";\n\n/**\n * How a backend must realise an effect.\n *\n * - `\"filter\"` (the default) — the effect transforms colours in place, so it\n * composes as a plain image filter alongside its neighbours in the chain.\n * - `\"shader\"` — the effect *resamples pixel positions* (warps, bands, or\n * otherwise reads neighbouring texels), so it needs the content snapshotted\n * into a texture and redrawn through a lens rather than composed.\n *\n * This is a statement about the effect, not about any particular backend: it\n * says the effect needs random access to its source, which is why it belongs\n * here next to `lerp`/`equals` rather than in the renderer.\n */\nexport type EffectSurface = \"filter\" | \"shader\";\n\n/**\n * Axis (or axes) an effect acts along.\n *\n * `\"both\"` (= `{ x: 1, y: 1 }`) uses the full 2D vector; `\"x\"`/`\"y\"` isolate a\n * single axis; a {@link Vector2} gives fractional control per axis. Shared by\n * every axis-selecting effect so `scatter` and `motionBlur` speak the same\n * vocabulary.\n */\nexport type EffectAxis = \"x\" | \"y\" | \"both\" | Vector2;\n\n/** Resolve an {@link EffectAxis} to its per-axis scale vector. */\nexport function resolveEffectAxis(axis: EffectAxis): Vector2 {\n switch (axis) {\n case \"x\": return { x: 1, y: 0 };\n case \"y\": return { x: 0, y: 1 };\n case \"both\": return { x: 1, y: 1 };\n default: return { x: axis.x, y: axis.y };\n }\n}\n\n/** Do two {@link EffectAxis} values resolve to the same scale vector? */\nexport function sameEffectAxis(a: EffectAxis, b: EffectAxis): boolean {\n const av = resolveEffectAxis(a);\n const bv = resolveEffectAxis(b);\n return av.x === bv.x && av.y === bv.y;\n}\n\n/**\n * Resolve a colour-valued effect option to its RGBA tuple.\n *\n * Colour options are stored **as authored** (a CSS string, a theme alias, or an\n * already-normalised tuple) rather than parsed at build time, so a raw effect\n * literal — `{ type: 'outline', color: 'primary', … }` — behaves exactly like the\n * builder form, and a theme alias still resolves against whatever `setTheme`\n * installed. Backends call this to get numbers; `lerp` calls it on both ends.\n */\nexport function resolveEffectColor(color: Color): NormalizedColor {\n return Array.isArray(color) ? color : parseColor(color);\n}\n\n/** Do two colour options resolve to the same RGBA? (`'red'` === `'#ff0000'`.) */\nexport function sameEffectColor(a: Color, b: Color): boolean {\n if (a === b) return true;\n const av = resolveEffectColor(a);\n const bv = resolveEffectColor(b);\n return av[0] === bv[0] && av[1] === bv[1] && av[2] === bv[2] && av[3] === bv[3];\n}\n\n/**\n * Mixin: every effect declares the layer it targets via {@link EffectMode}.\n * Omitted is treated as `\"foreground\"`. A single uniform field across all effects\n * means the backdrop/foreground classifier never has to branch on `type`.\n */\nexport interface ModedEffect {\n mode?: EffectMode;\n /**\n * Confine the effect's output to the alpha it was handed — the node's own\n * silhouette, rather than the rectangle its bleed would otherwise fill.\n *\n * Off (the default) a blur, bloom, outline or streak spreads *past* the\n * content that produced it, which is usually the point. On, the effect is\n * clipped back into the shape: a bloom that lights the node without\n * haloing the page around it, a blur that softens a fill without fraying its\n * edge — Figma's \"clip content\" applied to the effect rather than the layer.\n *\n * Honoured on both render paths — `EffectRegistry.compose` clips an\n * ImageFilter chain per effect, and `resolveForegroundCapture` blends a\n * shader effect's lens into the content it was given — so the flag means the\n * same thing whichever way an effect happens to be realised.\n *\n * Redundant in `mode: 'backdrop'`, where the effect is already confined to\n * the node's silhouette by definition.\n */\n clip?: boolean;\n}\n\n/**\n * Cross-cutting options accepted by every effect builder — the builder-side view\n * of {@link ModedEffect}. Each builder's own options type intersects this, so\n * `mode` is spelled the same way everywhere:\n *\n * Effects.blur({ radius: 8, mode: 'backdrop' })\n *\n * This is the extension point for future chain-wide options (e.g. a wet/dry\n * `mix`): add the field here and to {@link EFFECT_OPTION_KEYS} and every builder\n * picks it up.\n */\nexport type EffectOptions = ModedEffect;\n\n/**\n * The {@link EffectOptions} keys {@link withEffectOptions} copies onto a built\n * effect. `satisfies` keeps this in lockstep with the interface (mirroring\n * `TEXT_STYLE_KEYS`), and `withEffectOptions` iterates it rather than naming\n * fields, so adding an option here is the only edit needed.\n */\nexport const EFFECT_OPTION_KEYS = [\"mode\", \"clip\"] as const satisfies readonly (keyof EffectOptions)[];\n\n/**\n * Merge cross-cutting options onto a built effect, **skipping undefined keys**.\n *\n * Omitting rather than writing `undefined` matters: the per-effect `equals()`\n * implementations compare `mode` directly, so a spread that sets `mode:\n * undefined` is not equal to an effect that never set it at all.\n */\nexport function withEffectOptions<T extends object>(base: T, options?: EffectOptions): T & EffectOptions {\n const out = { ...base } as T & EffectOptions;\n if (!options) return out;\n for (const key of EFFECT_OPTION_KEYS) {\n const value = options[key];\n // Indexed write through a widened view: the keys no longer share one\n // value type (`mode` is an EffectMode, `clip` a boolean), so `out[key]`\n // narrows to their intersection — `never` — under a union key.\n if (value !== undefined) (out as Record<string, unknown>)[key] = value;\n }\n return out;\n}\n\n/**\n * Normalise a builder's single argument to its options object.\n *\n * Every effect builder takes exactly one parameter; those with a dominant\n * animated scalar also accept that scalar directly, so `blur(8)` and\n * `blur({ radius: 8 })` produce the same effect. `key` names the field a bare\n * number maps onto.\n */\nexport function scalarOptions<O extends object>(\n arg: number | O | undefined,\n key: keyof O,\n): Partial<O> & EffectOptions {\n if (arg === undefined) return {};\n if (typeof arg === \"number\") return { [key]: arg } as Partial<O> & EffectOptions;\n return arg;\n}\n\nexport interface EffectData<T> {\n /**\n * Linearly interpolates between two effect states.\n * @param from The starting state of the effect.\n * @param to The target state of the effect.\n * @param t The interpolation factor (usually a normalized value between 0 and 1).\n * @returns A new effect state representing the blended value.\n */\n lerp: (from: T, to: T, t: number) => T;\n\n /**\n * Compares two effect states for deep equality.\n * @param a The first effect state.\n * @param b The second effect state.\n * @returns True if the effects are structurally identical, otherwise false.\n */\n equals: (a: T, b: T) => boolean;\n\n /**\n * How a backend must realise this effect. Defaults to `\"filter\"`; effects\n * that resample pixel positions declare `\"shader\"`. Drives which render path\n * the effect takes — see {@link EffectSurface}.\n *\n * A predicate handles effects whose surface depends on their own fields —\n * a foreground shader composes as a filter, while the same effect in\n * backdrop mode resamples what is beneath it.\n */\n surface?: EffectSurface | ((effect: T) => EffectSurface);\n\n /**\n * Normalise an authored effect into the shape the rest of the pipeline\n * expects — the mirror of `FillData.resolve`, which a fill has and an effect\n * did not.\n *\n * Called once per property write, through `resolveChainEffects`, which is\n * the single funnel every effect reaches a node by (the `effects` prop's\n * mapper and `Graphics2D.effects`). That makes it the one place a stored\n * document can be migrated forward — an older spelling of a type or a field\n * is rewritten here rather than being understood separately by `lerp`,\n * `equals`, the surface predicate and the backend.\n *\n * **Return the effect unchanged when nothing needs rewriting.** It runs on\n * every write, so allocating a copy per call would churn for the\n * overwhelming majority of effects, which need no normalisation at all.\n */\n resolve?(effect: T): T;\n\n /**\n * An effect that samples a texture declares it here, as an image fill does:\n * an undeclared asset is a lookup the effect can only read as \"no texture\".\n */\n declare?(effect: T, assets: AssetScope): void;\n}\n", "/**\n * Low-level color interpolation utilities.\n *\n * These helpers operate on {@link NormalizedColor} tuples (linear [R, G, B, A]\n * in the 0–1 range) and are used by fill implementations that need per-channel\n * lerp without pulling in the full fill-registry machinery.\n */\n\nimport { Color, NormalizedColor, parseColor } from \"./color/parser\";\nimport type { AttributeOps } from \"@/attributes/shared/operators\";\n\n/** Linearly interpolates two normalized RGBA colors channel-by-channel. */\nexport function lerpColor(from: NormalizedColor, to: NormalizedColor, t: number): NormalizedColor {\n return [\n from[0] + (to[0] - from[0]) * t,\n from[1] + (to[1] - from[1]) * t,\n from[2] + (to[2] - from[2]) * t,\n from[3] + (to[3] - from[3]) * t,\n ];\n}\n\n/** Helpers the colour attribute carries beyond its mapper and lerp. */\nexport interface ColorOps {\n /**\n * `#rrggbb`, or `#rrggbbaa` when not opaque — for a consumer that takes a\n * colour as a string, such as a resolved `Types.color` entry read back.\n */\n hex(value: Color): string;\n}\n\n/** The colour attribute's op set: parses a CSS string (or passes an already-normalized\n * tuple through) and interpolates in normalized space. */\nexport const colorOps: AttributeOps<Color, NormalizedColor> & ColorOps = {\n resolve,\n lerp: lerpColor,\n hex(value) {\n const [r, g, b, a] = resolve(value);\n const alpha = byte(a);\n return `#${byte(r)}${byte(g)}${byte(b)}${alpha === \"ff\" ? \"\" : alpha}`;\n },\n};\n\nfunction resolve(value: Color): NormalizedColor {\n return Array.isArray(value) ? value : parseColor(value);\n}\n\nfunction byte(channel: number): string {\n return Math.round(Math.min(1, Math.max(0, channel)) * 255).toString(16).padStart(2, \"0\");\n}\n\n", "import { lerpNumber } from \"@/tween/lerp\";\nimport { lerpVector2, type Vector2 } from \"@/attributes/layout/vector2\";\nimport { lerpColor } from \"@/attributes/shape/fill/lerp\";\nimport type { Color } from \"@/attributes/shape/fill/color/parser\";\nimport type { AssetScope } from \"@/assets/scope\";\nimport type { EffectAxis, EffectData, EffectMode, EffectOptions, EffectSurface, ModedEffect } from \"./effect-data\";\nimport { resolveEffectColor, sameEffectAxis, sameEffectColor, scalarOptions, withEffectOptions } from \"./effect-data\";\n\n/**\n * How a parameter's value is shaped, which decides its default interpolation,\n * equality and how a renderer encodes it into a uniform.\n */\nexport type EffectParamKind =\n | \"number\"\n | \"color\"\n | \"vec2\"\n | \"enum\"\n | \"boolean\"\n | \"axis\"\n | \"text\"\n | \"colors\"\n | \"numbers\"\n | \"points\"\n | \"table\"\n | \"uniforms\";\n\n/** What a number measures, for a host's units and a renderer's scaling. */\nexport type EffectParamUnit = \"px\" | \"deg\" | \"percent\" | \"factor\" | \"normalized\";\n\n/** The picker family an effect is listed under. */\nexport type EffectGroup = \"blur\" | \"light\" | \"color\" | \"stylize\" | \"distort\" | \"glitch\";\n\n/** The control an inspector should draw for a parameter. */\nexport type EffectParamControl = \"number\" | \"slider\" | \"angle\" | \"hue\" | \"segmented\" | \"select\" | \"text\" | \"color\" | \"point\" | \"toggle\";\n\n/** Per-parameter inspector hints. None of them changes what the effect does. */\nexport interface EffectParamHints {\n /** i18n leaf for the field's label; defaults to the parameter name. */\n readonly label?: string;\n readonly control?: EffectParamControl;\n /** Shown on the effect's row beside its name (one per effect). */\n readonly inline?: boolean;\n /** Inspector position; defaults to the declaration order. */\n readonly order?: number;\n /** For an angle: where 0° points (the bearing turns clockwise). Defaults to `\"right\"`. */\n readonly zero?: \"right\" | \"top\";\n /** i18n group for an enum's option labels. */\n readonly optionsLabel?: string;\n /** Not offered as a field: the value a fresh effect carries is kept as is. */\n readonly hidden?: boolean;\n /** Where a freshly inserted effect starts, when the builder default would show nothing. */\n readonly initial?: unknown;\n}\n\n/** Interpolates one parameter. `from`/`to` are the whole effects, for parameters that depend on a sibling. */\nexport type EffectParamLerp<T> = (a: T, b: T, t: number, from: Record<string, unknown>, to: Record<string, unknown>) => T;\n\n/**\n * One parameter of a built-in effect: a stored field of the effect object.\n *\n * `T` is the stored type, `In` what a builder accepts for it (`normalize` maps\n * one to the other: a bare number for a per-axis count, say). Only the\n * serialisable fields reach {@link EffectDescriptor}.\n */\nexport interface EffectParamDef<T = unknown, In = T> extends EffectParamHints {\n readonly kind: EffectParamKind;\n /** What the builder writes when the option is omitted (an input, before `normalize`). */\n readonly default?: In;\n /** The stored field may be absent (`colorAdjustment`'s fields, `curves.channel`). */\n readonly optional?: boolean;\n /** The builder's options type requires it. */\n readonly required?: boolean;\n readonly min?: number;\n readonly max?: number;\n readonly step?: number;\n readonly unit?: EffectParamUnit;\n /** An enum's values, in the order a renderer indexes them. */\n readonly options?: readonly (string | number)[];\n readonly normalize?: (input: In) => T;\n /** `\"step\"` switches at the midpoint; omitted uses the kind's interpolation. */\n readonly lerp?: \"step\" | EffectParamLerp<T>;\n readonly equals?: (a: T, b: T) => boolean;\n /** Type carrier only; never set. */\n readonly __type?: [T, In];\n}\n\n/** An effect's parameters, by stored field name, in builder (and stored-key) order. */\nexport type EffectParamTable = Readonly<Record<string, EffectParamDef<any, any>>>;\n\n/**\n * The declarative definition of a built-in effect: its parameters (types,\n * defaults, ranges, inspector hints) plus the behaviour that has to stay code.\n * Core's types, builder defaults, `lerp`/`equals` and the host-facing\n * {@link EffectDescriptor} are derived from it, and the renderers bind their\n * shader uniforms to its parameter names.\n */\nexport interface EffectSpec<T extends string = string, P extends EffectParamTable = EffectParamTable> {\n readonly type: T;\n readonly params: P;\n readonly group: EffectGroup;\n /** The option a bare number passed to the builder sets. */\n readonly scalar?: string;\n /** The builder's `mode` when none is given. */\n readonly defaultMode?: EffectMode;\n /** The one layer the effect does anything on. */\n readonly onlyOn?: EffectMode;\n /** Builder options at which the effect draws nothing, or `null` when it has none. */\n readonly neutral: Readonly<Record<string, unknown>> | null;\n readonly surface?: EffectData<any>[\"surface\"];\n readonly resolve?: (effect: any) => any;\n readonly declare?: (effect: any, assets: AssetScope) => void;\n /** Wraps or replaces the derived interpolation, which it is handed as `derived`. */\n readonly lerp?: (from: any, to: any, t: number, derived: (from: any, to: any, t: number) => any) => any;\n readonly equals?: (a: any, b: any) => boolean;\n}\n\ntype ParamValue<D> = D extends { readonly __type?: [infer T, unknown] } ? T : never;\ntype ParamInput<D> = D extends { readonly __type?: [unknown, infer I] } ? I : never;\ntype IsOptional<D> = D extends { readonly optional: true } ? true : false;\ntype IsRequired<D> = D extends { readonly required: true } ? true : false;\n\n/** The stored fields an effect's parameters describe. */\nexport type EffectFields<P extends EffectParamTable> = {\n -readonly [K in keyof P as IsOptional<P[K]> extends true ? never : K]: ParamValue<P[K]>;\n} & {\n -readonly [K in keyof P as IsOptional<P[K]> extends true ? K : never]?: ParamValue<P[K]>;\n};\n\n/** A builder's options for an effect: every parameter as input, plus `mode`/`clip`. */\nexport type EffectOptionsOf<P extends EffectParamTable> = {\n -readonly [K in keyof P as IsRequired<P[K]> extends true ? K : never]: ParamInput<P[K]>;\n} & {\n -readonly [K in keyof P as IsRequired<P[K]> extends true ? never : K]?: ParamInput<P[K]>;\n} & EffectOptions;\n\n/** The effect object a spec describes. */\nexport type EffectOf<S extends EffectSpec> = { type: S[\"type\"] } & ModedEffect & EffectFields<S[\"params\"]>;\n\n/** Declares a built-in effect; see {@link EffectSpec}. */\nexport function defineEffect<const T extends string, const P extends EffectParamTable>(\n spec: EffectSpec<T, P>,\n): EffectSpec<T, P> {\n return spec;\n}\n\n/** The middle of the layer, every centre option's default. Shared, as it always was. */\nexport const CENTER: Vector2 = { x: 0.5, y: 0.5 };\n\ntype Options<T, In = T> = Omit<EffectParamDef<T, In>, \"kind\" | \"__type\" | \"options\" | \"normalize\" | \"lerp\" | \"equals\">;\n// Kept out of the inferred options so a lambda here is typed by its parameter.\ntype Behaviour<T> = Pick<EffectParamDef<T>, \"lerp\" | \"equals\">;\n\n/** Parameter constructors for {@link defineEffect}. */\nexport const param = {\n number<const O extends Options<number>>(o: O & Behaviour<number> & { normalize?: (input: number) => number }): EffectParamDef<number> & NoInfer<O> & { kind: \"number\" } {\n return { kind: \"number\", ...o };\n },\n color<const O extends Options<Color>>(o: O & Behaviour<Color>): EffectParamDef<Color> & NoInfer<O> & { kind: \"color\" } {\n return { kind: \"color\", ...o };\n },\n /** A point or per-axis pair. `fromNumber` lets the builder take a bare number for it. */\n vec2<const O extends Options<Vector2, number | Vector2> & { fromNumber?: \"both\" | \"y\" }>(\n o: O & Behaviour<Vector2>,\n ): EffectParamDef<Vector2, O extends { fromNumber: string } ? number | Vector2 : Vector2> & NoInfer<O> & { kind: \"vec2\" } {\n const normalize = o.fromNumber === undefined\n ? undefined\n : o.fromNumber === \"both\"\n ? (v: number | Vector2) => (typeof v === \"number\" ? { x: v, y: v } : v)\n : (v: number | Vector2) => (typeof v === \"number\" ? { x: 0, y: v } : v);\n return { kind: \"vec2\", ...(normalize ? { normalize } : {}), ...o } as never;\n },\n choice<const V extends string | number, const O extends Options<V>>(\n options: readonly V[],\n o: O & Behaviour<V>,\n ): EffectParamDef<V> & NoInfer<O> & { kind: \"enum\"; options: readonly V[] } {\n return { kind: \"enum\", options, lerp: \"step\", ...o };\n },\n boolean<const O extends Options<boolean>>(o: O & Behaviour<boolean>): EffectParamDef<boolean> & NoInfer<O> & { kind: \"boolean\" } {\n return { kind: \"boolean\", lerp: \"step\", ...o };\n },\n axis<const O extends Options<EffectAxis>>(o: O & Behaviour<EffectAxis>): EffectParamDef<EffectAxis> & NoInfer<O> & { kind: \"axis\" } {\n return { kind: \"axis\", lerp: \"step\", ...o };\n },\n text<V extends string = string, const O extends Options<V> = Options<V>>(o: O & Behaviour<V>): EffectParamDef<V> & NoInfer<O> & { kind: \"text\" } {\n return { kind: \"text\", lerp: \"step\", ...o };\n },\n /**\n * A parameter of stored type `T` that no generic kind covers, curried so\n * `T` is given and the options inferred: `param.of<Color[]>()({ kind: \"colors\", … })`.\n * It steps and compares by `===` unless given `lerp`/`equals`.\n */\n of<T>() {\n return <const O extends Options<T> & { kind: EffectParamKind }>(o: O & Behaviour<T>): EffectParamDef<T> & NoInfer<O> =>\n ({ lerp: \"step\", ...o }) as never;\n },\n};\n\nconst step = <T>(a: T, b: T, t: number): T => (t < 0.5 ? a : b);\nconst same = (a: unknown, b: unknown) => a === b;\nconst sameVector = (a: Vector2, b: Vector2) => a.x === b.x && a.y === b.y;\n\nconst KIND_LERP: Partial<Record<EffectParamKind, EffectParamLerp<any>>> = {\n number: lerpNumber,\n color: (a: Color, b: Color, t) => lerpColor(resolveEffectColor(a), resolveEffectColor(b), t),\n vec2: lerpVector2,\n};\n\nconst KIND_EQUALS: Partial<Record<EffectParamKind, (a: any, b: any) => boolean>> = {\n color: sameEffectColor,\n vec2: sameVector,\n axis: sameEffectAxis,\n};\n\nfunction paramLerp(def: EffectParamDef<any, any>): EffectParamLerp<unknown> {\n if (typeof def.lerp === \"function\") return def.lerp;\n const kind = def.lerp === \"step\" ? undefined : KIND_LERP[def.kind];\n if (!kind) return step;\n // An absent optional field tweens from what it means when absent.\n if (def.optional && def.default !== undefined) {\n const fallback = def.default;\n return (a, b, t, from, to) => kind(a ?? fallback, b ?? fallback, t, from, to);\n }\n return kind;\n}\n\n/** The derived `EffectData` of a spec: generic per-kind `lerp`/`equals` unless the spec gives its own. */\nexport function effectDataOf<S extends EffectSpec>(spec: S): EffectData<EffectOf<S>> {\n const entries = Object.entries(spec.params);\n const lerps = entries.map(([name, def]) => [name, paramLerp(def)] as const);\n const equals = entries.map(([name, def]) => [name, def.equals ?? KIND_EQUALS[def.kind] ?? same] as const);\n const derived = (from: EffectOf<S>, to: EffectOf<S>, t: number): EffectOf<S> => {\n const out: Record<string, unknown> = { type: spec.type };\n const f = from as unknown as Record<string, unknown>;\n const g = to as unknown as Record<string, unknown>;\n for (const [name, lerp] of lerps) out[name] = lerp(f[name], g[name], t, f, g);\n return out as EffectOf<S>;\n };\n const custom = spec.lerp;\n const data: EffectData<EffectOf<S>> = {\n lerp: custom ? (from, to, t) => custom(from, to, t, derived) : derived,\n equals: spec.equals ?? ((a, b) => {\n const x = a as unknown as Record<string, unknown>;\n const y = b as unknown as Record<string, unknown>;\n return equals.every(([name, eq]) => eq(x[name], y[name]));\n }),\n };\n if (spec.surface !== undefined) data.surface = spec.surface;\n if (spec.resolve) data.resolve = spec.resolve;\n if (spec.declare) data.declare = spec.declare;\n return data;\n}\n\n// Arrays are copied so editing one effect's list never reaches another's;\n// objects (a centre point) are shared, as they always were.\nconst copyDefault = (value: unknown) => (Array.isArray(value) ? [...value] : value);\n\n/**\n * Builds an effect from builder input: the scalar shorthand, then each\n * parameter's option or default (normalised), then `mode`/`clip`.\n */\nexport function buildEffect<S extends EffectSpec>(\n spec: S,\n arg: number | EffectOptionsOf<S[\"params\"]> | undefined,\n): EffectOf<S> {\n const o = (spec.scalar\n ? scalarOptions(arg as number | Record<string, unknown> | undefined, spec.scalar as never)\n : (arg ?? {})) as Record<string, unknown> & EffectOptions;\n const out: Record<string, unknown> = { type: spec.type };\n for (const [name, def] of Object.entries(spec.params)) {\n const value = o[name] ?? copyDefault(def.default);\n if (value === undefined) continue;\n out[name] = def.normalize ? def.normalize(value) : value;\n }\n const options = spec.defaultMode && o.mode === undefined ? { ...o, mode: spec.defaultMode } : o;\n return withEffectOptions(out, options) as unknown as EffectOf<S>;\n}\n\n/** A JSON value — what every field of an {@link EffectDescriptor} is made of. */\nexport type EffectJson = string | number | boolean | null | EffectJson[] | { [key: string]: EffectJson };\n\n/** One parameter of an {@link EffectDescriptor}. */\nexport interface EffectParamDescriptor {\n /** The stored field it writes. */\n name: string;\n kind: EffectParamKind;\n /** What the builder writes when it is omitted, as stored (colours as authored). */\n default?: EffectJson;\n /** The builder's options require it. */\n required?: boolean;\n /** The stored field may be absent. */\n optional?: boolean;\n min?: number;\n max?: number;\n step?: number;\n unit?: EffectParamUnit;\n options?: (string | number)[];\n /** Tweens continuously (false: switches at the midpoint). */\n animatable: boolean;\n /** i18n leaf for the label; the name unless the spec says otherwise. */\n label: string;\n control?: EffectParamControl;\n inline?: boolean;\n /** Inspector position. */\n order: number;\n zero?: \"right\" | \"top\";\n optionsLabel?: string;\n hidden?: boolean;\n initial?: EffectJson;\n}\n\n/**\n * A built-in effect, described for a host: what its fields are, their kinds,\n * defaults and ranges, and how an inspector should lay them out. Plain JSON, so\n * it can be shipped to a UI as is.\n */\nexport interface EffectDescriptor {\n type: string;\n group: EffectGroup;\n /** `\"dynamic\"`: depends on the effect's `mode` (the user shader). */\n surface: EffectSurface | \"dynamic\";\n scalar?: string;\n defaultMode?: EffectMode;\n onlyOn?: EffectMode;\n /** Stored fields at which it draws nothing (the rest at their defaults); `null` when it has none. */\n neutral: { [key: string]: EffectJson } | null;\n /** In stored-key order; sort by `order` for the inspector's. */\n params: EffectParamDescriptor[];\n}\n\nconst json = (value: unknown): EffectJson | undefined =>\n value === undefined ? undefined : (JSON.parse(JSON.stringify(value)) as EffectJson);\n\n/** The serialisable {@link EffectDescriptor} of a spec. */\nexport function describeSpec(spec: EffectSpec): EffectDescriptor {\n const params = Object.entries(spec.params).map(([name, def], index): EffectParamDescriptor => {\n const stored = def.default !== undefined && def.normalize ? def.normalize(def.default) : def.default;\n const out: EffectParamDescriptor = {\n name,\n kind: def.kind,\n animatable: def.lerp !== \"step\",\n label: def.label ?? name,\n order: def.order ?? index,\n };\n const optional = {\n default: json(stored),\n required: def.required,\n optional: def.optional,\n min: def.min,\n max: def.max,\n step: def.step,\n unit: def.unit,\n options: def.options ? [...def.options] : undefined,\n control: def.control,\n inline: def.inline,\n zero: def.zero,\n optionsLabel: def.optionsLabel,\n hidden: def.hidden,\n initial: json(def.initial),\n };\n for (const [key, value] of Object.entries(optional)) {\n if (value !== undefined) (out as unknown as Record<string, unknown>)[key] = value;\n }\n return out;\n });\n const out: EffectDescriptor = {\n type: spec.type,\n group: spec.group,\n surface: typeof spec.surface === \"function\" ? \"dynamic\" : (spec.surface ?? \"filter\"),\n neutral: spec.neutral === null ? null : (json(Object.fromEntries(Object.entries(spec.neutral).map(([name, value]) => {\n const normalize = spec.params[name]?.normalize;\n return [name, normalize ? normalize(value) : value];\n }))) as { [key: string]: EffectJson }),\n params,\n };\n if (spec.scalar) out.scalar = spec.scalar;\n if (spec.defaultMode) out.defaultMode = spec.defaultMode;\n if (spec.onlyOn) out.onlyOn = spec.onlyOn;\n return out;\n}\n", "import { lerpNumber } from \"@/tween/lerp\";\nimport { lerpVector2 } from \"@/attributes/layout/vector2\";\nimport type { ModedEffect, EffectData } from \"../effect-data\";\nimport { resolveEffectAxis } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/** Shutter phase presets — see {@link MotionBlurEffect.alignment}. */\nexport type MotionBlurAlignment = \"behind\" | \"centered\" | \"ahead\" | number;\n\n/**\n * Velocity-driven motion blur. Unlike {@link DirectionalBlurEffect}, whose smear\n * is authored, this derives its direction and length from the node's actual\n * per-frame motion (sampled by the renderer), modelled on After Effects' shutter\n * angle (`length`) and shutter phase (`alignment`). A static node renders sharp.\n */\nexport interface MotionBlurEffect extends ModedEffect, EffectFields<typeof motionBlurSpec.params> {\n type: \"motionBlur\";\n}\n\n/** Resolve {@link MotionBlurEffect.alignment} to a shutter-phase number in −1…1. */\nexport function resolveMotionBlurAlignment(alignment: MotionBlurAlignment): number {\n switch (alignment) {\n case \"behind\": return -1;\n case \"centered\": return 0;\n case \"ahead\": return 1;\n default: return Math.max(-1, Math.min(1, alignment));\n }\n}\n\n/** The {@link MotionBlurEffect} spec: its parameters, defaults and ranges. */\nexport const motionBlurSpec = defineEffect({\n type: \"motionBlur\",\n group: \"blur\",\n scalar: \"length\",\n neutral: { length: 0 },\n params: {\n /**\n * Shutter \"openness\" as a percentage, the user-friendly form of a shutter\n * angle. `100` ≈ 360° = a smear spanning the node's full per-frame\n * displacement; `0` = no blur.\n */\n length: param.number({ default: 50, min: 0, unit: \"percent\", label: \"shutter\", inline: true }),\n /**\n * Shutter phase — where the smear sits relative to the node's current\n * position along its motion: `'behind'` (−1) trails it, `'centered'` (0)\n * straddles it, `'ahead'` (1) leads it; a number in −1…1 sits between.\n */\n alignment: param.of<MotionBlurAlignment>()({\n kind: \"enum\",\n default: \"centered\",\n options: [\"centered\", \"behind\", \"ahead\"],\n optionsLabel: \"motionBlurAlignment\",\n // Resolved to a phase, so e.g. 'behind' → 'ahead' sweeps.\n lerp: (a, b, t) => lerpNumber(resolveMotionBlurAlignment(a), resolveMotionBlurAlignment(b), t),\n equals: (a, b) => resolveMotionBlurAlignment(a) === resolveMotionBlurAlignment(b),\n }),\n /** Renderer quality hint; above 32 switches to multi-tap accumulation. */\n samples: param.number({ default: 16, min: 1, step: 1, hidden: true }),\n /** Blur-length multiplier. */\n strength: param.number({ default: 1, min: 0, max: 2, control: \"slider\" }),\n /** Per-axis velocity scale. */\n axis: param.axis({\n default: \"both\",\n optionsLabel: \"effectAxis\",\n lerp: (a, b, t) => lerpVector2(resolveEffectAxis(a), resolveEffectAxis(b), t),\n }),\n },\n});\n\nexport const motionBlurEffect: EffectData<MotionBlurEffect> = effectDataOf(motionBlurSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Built-in glyph ramps, each ordered **least ink first**: `charset[0]` stands in\n * for the darkest cells and the last entry for the lightest.\n *\n * That ordering is about the *result*, not the glyph. On the default white ink\n * over black, an empty cell is the darkest thing the effect can draw and a solid\n * one the brightest, so least-ink-first is exactly dark-to-light. Invert the ink\n * and background — black on white, the paper look — and the same ramp is used\n * back to front automatically, so a custom ramp only ever has to be written once.\n *\n * - `'standard'` — the classic ten-step ASCII ramp.\n * - `'blocks'` — Unicode shading blocks; the most legible at small cell sizes,\n * because each step really is a fixed fraction of coverage.\n * - `'braille'` — braille dot patterns, the finest ramp of the set.\n * - `'binary'` — just `0` and `1`: a two-tone cut rather than a ramp.\n * - `'hex'` — `0`–`F`, the hex-dump look. Its \"ramp\" is nominal, since a glyph's\n * ink doesn't track its digit, so expect texture rather than tone.\n */\nexport type AsciiCharset = \"standard\" | \"blocks\" | \"braille\" | \"binary\" | \"hex\";\n\n/** The ramp each named charset expands to. Exported so a backend needn't guess. */\nexport const ASCII_CHARSETS: Record<AsciiCharset, string> = {\n standard: \" .:-=+*#%@\",\n blocks: \" ░▒▓█\",\n braille: \" ⠄⣀⣄⣤⣶⣷⣿\",\n binary: \"01\",\n hex: \"0123456789ABCDEF\",\n};\n\n/** Resolve a charset option to its literal ramp; unknown names fall back to `'standard'`. */\nexport function resolveAsciiCharset(charset: AsciiCharset | string): string {\n return ASCII_CHARSETS[charset as AsciiCharset] ?? charset;\n}\n\n/**\n * ASCII art: the content is divided into a grid of cells, each cell's tone is\n * matched to a glyph, and that glyph is drawn in its place.\n *\n * The glyphs come from a texture baked once per charset/font/size — the first\n * effect to use the renderer's resource hook.\n */\nexport interface AsciiEffect extends ModedEffect, EffectFields<typeof asciiSpec.params> {\n type: \"ascii\";\n}\n\n/** The {@link AsciiEffect} spec: its parameters, defaults and ranges. */\nexport const asciiSpec = defineEffect({\n type: \"ascii\",\n group: \"stylize\",\n // Reads one texel per cell and a glyph texture alongside it.\n surface: \"shader\",\n scalar: \"size\",\n // Replaces the image with glyphs at every size.\n neutral: null,\n params: {\n /** Cell size in pixels — the width of one character. */\n size: param.number({ default: 12, min: 2, unit: \"px\", label: \"cellSize\", inline: true }),\n /** A named ramp, or a custom string ordered least-ink-first. */\n charset: param.of<AsciiCharset | string>()({\n kind: \"enum\",\n default: \"standard\",\n options: Object.keys(ASCII_CHARSETS),\n optionsLabel: \"asciiCharset\",\n }),\n /** Family the glyphs are baked in; a monospace face reads best. */\n fontFamily: param.text({ default: \"monospace\" }),\n /** Glyph colour when `colored` is false. */\n ink: param.color({ default: \"white\" }),\n /** Colour behind the glyphs (`'transparent'` to overlay). */\n background: param.color({ default: \"black\" }),\n /** Tint each glyph with its own cell's colour instead of using `ink`. */\n colored: param.boolean({ default: false }),\n },\n});\n\nexport const asciiEffect: EffectData<AsciiEffect> = effectDataOf(asciiSpec);\n", "/**\n * Blend mode definitions.\n *\n * Mirrors the CSS `mix-blend-mode` keyword set. The renderer maps each string\n * to an integer hash for fast uniform uploads.\n */\n\n/** Every supported blend mode, in hash-index order. */\nexport const BlendModes = [\n \"multiply\",\n \"screen\",\n \"overlay\",\n \"darken\",\n \"lighten\",\n \"color-dodge\",\n \"color-burn\",\n \"hard-light\",\n \"soft-light\",\n \"difference\",\n \"exclusion\",\n \"hue\",\n \"saturation\",\n \"color\",\n \"luminosity\",\n \"normal\"\n] as const;\n\n/** CSS `mix-blend-mode` keyword — derived from {@link BlendModes}. */\nexport type BlendMode = typeof BlendModes[number];\n\n/**\n * Blend modes a node/layer can carry. Adds Figma's `pass-through` to the fill\n * {@link BlendMode} set. `pass-through` (the node default) means the layer is\n * *not* isolated: its opacity scales each child/fill's contribution while those\n * children still blend directly against the backdrop. Any other value isolates\n * the node — its children flatten into a group that then blends against the\n * backdrop with the chosen mode. Fills never accept `pass-through`.\n */\nexport const NodeBlendModes = [...BlendModes, \"pass-through\"] as const;\n\n/** Layer blend mode — {@link BlendMode} plus `pass-through`. Node2D-only. */\nexport type NodeBlendMode = typeof NodeBlendModes[number];\n\n// Pre-built reverse lookup so getBlendModeHash is O(1).\nconst BLEND_MODE_HASH: Record<BlendMode, number> =\n Object.fromEntries(\n BlendModes.map((mode, i) => [mode, i])\n ) as Record<BlendMode, number>;\n\n/** Returns the integer hash for a blend mode, used as a shader uniform. */\nexport function getBlendModeHash(blend: BlendMode): number {\n return BLEND_MODE_HASH[blend];\n}\n", "/**\n * Uniform values shared by the `shader` fill and the `shader` effect: the\n * authoring shapes, their canonical record, and how two records interpolate\n * and compare. The renderer binds the record to the program's `struct Params`\n * by name.\n */\n\nimport { lerpNumber } from '@/tween/lerp';\n\n/** A single uniform value: a float, or a flat array for a vector/matrix/array uniform. */\nexport type ShaderUniformValue = number | number[];\n\n/** A named uniform, in the positional `[{name, value}]` form older shader effects were written with. */\nexport interface ShaderUniform {\n name: string;\n value: ShaderUniformValue;\n}\n\n/** Uniform values keyed by the name they are declared under in the shader. */\nexport type ShaderUniformRecord = Record<string, ShaderUniformValue>;\n\n// ---------------------------------------------------------------------------\n// Diagnostics\n// ---------------------------------------------------------------------------\n\n/**\n * Warnings already emitted, keyed by scope + message.\n *\n * Normalising runs on every resolve, so an unguarded warn is thousands of\n * identical lines in an export. Cleared past a ceiling so a pathological scene\n * can't grow this without bound.\n */\nconst warned = new Set<string>();\n\nfunction warnOnce(scope: string, message: string): void {\n const key = `${scope}\u0000${message}`;\n if (warned.has(key)) return;\n if (warned.size > 512) warned.clear();\n warned.add(key);\n console.warn(`[shader] ${message}`);\n}\n\n// ---------------------------------------------------------------------------\n// Authoring shapes → canonical record\n// ---------------------------------------------------------------------------\n\n/** Flatten a value to the float list it contributes, or null if it isn't numeric. */\nfunction flattenValue(name: string, value: unknown): ShaderUniformValue | null {\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n warnOnce('normalize', `uniform \"${name}\" is ${value}; ignoring it.`);\n return null;\n }\n return value;\n }\n if (!Array.isArray(value)) {\n warnOnce('normalize', `uniform \"${name}\" is not a number or number array; ignoring it.`);\n return null;\n }\n // `[[r,g,b,a], …]` is how an author naturally writes a colour array uniform,\n // and the renderer takes the whole thing as one flat float run either way.\n const flat = (value as unknown[]).flat(Infinity) as unknown[];\n const out: number[] = [];\n for (const entry of flat) {\n if (typeof entry !== 'number' || !Number.isFinite(entry)) {\n warnOnce('normalize', `uniform \"${name}\" contains a non-finite entry; ignoring it.`);\n return null;\n }\n out.push(entry);\n }\n return out;\n}\n\n/**\n * Normalise either authoring shape to a canonical record.\n *\n * Accepts the record form and the positional `[{name, value}]` array older\n * shader effects were written with. Keys are **sorted**, which makes the resolved fill canonical: two\n * authors writing the same uniforms in a different order produce the same object,\n * so `equals` and any structural diff agree with the renderer (which reads by\n * name and never sees the order at all).\n */\nexport function normalizeUniforms(\n input: ShaderUniformRecord | readonly ShaderUniform[] | undefined,\n): ShaderUniformRecord {\n if (!input) return {};\n const pairs: Array<[string, unknown]> = Array.isArray(input)\n ? (input as readonly ShaderUniform[]).map((u) => [u.name, u.value])\n : Object.entries(input as ShaderUniformRecord);\n\n const out: ShaderUniformRecord = {};\n for (const [name, value] of pairs.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {\n const flat = flattenValue(name, value);\n if (flat !== null) out[name] = flat;\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Interpolation and equality\n// ---------------------------------------------------------------------------\n\n/** Component-wise lerp. Mismatched shapes snap, since there is no in-between arity. */\nexport function lerpUniformValue(a: ShaderUniformValue, b: ShaderUniformValue, t: number): ShaderUniformValue {\n if (typeof a === 'number' && typeof b === 'number') return lerpNumber(a, b, t);\n if (Array.isArray(a) && Array.isArray(b)) {\n const len = Math.max(a.length, b.length);\n return Array.from({ length: len }, (_, i) => lerpNumber(a[i] ?? 0, b[i] ?? 0, t));\n }\n return t < 0.5 ? a : b;\n}\n\nexport function uniformValuesEqual(a: ShaderUniformValue, b: ShaderUniformValue): boolean {\n if (typeof a === 'number' && typeof b === 'number') return a === b;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n }\n return false;\n}\n\n/**\n * Interpolate two uniform records over the **union** of their keys.\n *\n * A key present on one side only holds at the value it has rather than\n * interpolating from zero: the shader still declares it, so dropping it would\n * write zeros mid-tween and read as the uniform snapping to black/none. This is\n * also what makes the self-pair `lerpFillArray` builds for an unmatched fill\n * layer a no-op on the uniforms.\n */\nexport function lerpUniformRecord(\n a: ShaderUniformRecord,\n b: ShaderUniformRecord,\n t: number,\n): ShaderUniformRecord {\n const out: ShaderUniformRecord = {};\n for (const name of [...Object.keys(a), ...Object.keys(b)].sort()) {\n if (name in out) continue;\n const from = a[name];\n const to = b[name];\n if (from === undefined) out[name] = to;\n else if (to === undefined) out[name] = from;\n else out[name] = lerpUniformValue(from, to, t);\n }\n return out;\n}\n\n/** Compare by key *set*, not insertion order. */\nexport function uniformRecordsEqual(a: ShaderUniformRecord, b: ShaderUniformRecord): boolean {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n return aKeys.every((name) => {\n const other = b[name];\n return other !== undefined && uniformValuesEqual(a[name], other);\n });\n}\n", "/**\n * The language a custom shader is written in: WGSL, the only one the renderer\n * runs. A fill defines `fn fill(in: FillIn) -> vec4f`, an effect\n * `fn effect(in: EffectIn) -> vec4f`; uniforms are the members of\n * `struct Params`, read as `u.<name>`.\n */\nexport type ShaderLanguage = \"wgsl\";\n\n/** Whether a shader fill, shader effect or shader pack is WGSL: its `language` is absent or `\"wgsl\"`. */\nexport function isWgslShader(shader: { language?: string }): boolean {\n return shader.language === undefined || shader.language === \"wgsl\";\n}\n\n/**\n * The version of the WGSL contract a shader is written against: `FillIn` /\n * `EffectIn`, the helpers, and uniforms bound to `struct Params` by name\n * (packages/renderer/DESIGN.md §6.3). Bumped only by a change that would draw\n * an existing shader differently. A WGSL fill or effect resolves with\n * `contract` set (stamped with this when absent), so a stored document says\n * what it was written for and a renderer can tell a newer one apart.\n */\nexport const WGSL_CONTRACT = 1;\n\n/** The contract a shader states, or the current one for a WGSL shader that states none; `undefined` for any other language. */\nexport function shaderContractOf(shader: { language?: string; contract?: number }): number | undefined {\n if (!isWgslShader(shader)) return undefined;\n return shader.contract ?? WGSL_CONTRACT;\n}\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\nexport interface BlurEffect extends ModedEffect, EffectFields<typeof blurSpec.params> {\n type: \"blur\";\n}\n\n/** The {@link BlurEffect} spec: its parameters, defaults and ranges. */\nexport const blurSpec = defineEffect({\n type: \"blur\",\n group: \"blur\",\n scalar: \"radius\",\n neutral: { radius: 0 },\n params: {\n /** Blur spread in pixels. */\n radius: param.number({ default: 0, required: true, min: 0, unit: \"px\", inline: true, initial: 4 }),\n },\n});\n\nexport const blurEffect: EffectData<BlurEffect> = effectDataOf(blurSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Motion-blur-style directional (linear) blur. Unlike {@link BlurEffect}, which\n * blurs uniformly in all directions, this smears the node's own content along a\n * single axis.\n */\nexport interface DirectionalBlurEffect extends ModedEffect, EffectFields<typeof directionalBlurSpec.params> {\n type: \"directionalBlur\";\n}\n\n/** The {@link DirectionalBlurEffect} spec: its parameters, defaults and ranges. */\nexport const directionalBlurSpec = defineEffect({\n type: \"directionalBlur\",\n group: \"blur\",\n scalar: \"radius\",\n neutral: { radius: 0 },\n params: {\n /** Smear length in pixels along `angle`. */\n radius: param.number({ default: 0, required: true, min: 0, unit: \"px\", label: \"length\", inline: true, order: 1, initial: 10 }),\n /** Smear axis in degrees — 0 = horizontal, 90 = vertical. */\n angle: param.number({ default: 0, unit: \"deg\", order: 0 }),\n },\n});\n\nexport const directionalBlurEffect: EffectData<DirectionalBlurEffect> = effectDataOf(directionalBlurSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\nexport interface GrayscaleEffect extends ModedEffect, EffectFields<typeof grayscaleSpec.params> {\n type: \"grayscale\";\n}\n\n/** The {@link GrayscaleEffect} spec: its parameters, defaults and ranges. */\nexport const grayscaleSpec = defineEffect({\n type: \"grayscale\",\n group: \"color\",\n scalar: \"amount\",\n neutral: { amount: 0 },\n params: {\n /** 0–1: 0 = original, 1 = fully desaturated. */\n amount: param.number({ default: 0, required: true, min: 0, max: 1, control: \"slider\", inline: true, initial: 1 }),\n },\n});\n\nexport const grayscaleEffect: EffectData<GrayscaleEffect> = effectDataOf(grayscaleSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * After Effects-style Mosaic / pixelate.\n *\n * `blocks` is the *number of blocks* across the node on each axis, exactly like\n * AE's Mosaic \"Horizontal Blocks\" / \"Vertical Blocks\". A count equal to the\n * node's pixel dimension on that axis leaves the image untouched (one block per\n * pixel); lower counts give larger, coarser blocks. For a 1920×1080 image,\n * `{ x: 1920, y: 1080 }` is pristine and `{ x: 200, y: 180 }` is heavily\n * pixelated.\n *\n * `sharpColors` mirrors AE's \"Sharp Colors\" checkbox: when `true` each block is\n * a single solid colour with hard edges (nearest-neighbour); when `false` the\n * block colours are smoothly interpolated between centres (linear).\n */\nexport interface PixelateEffect extends ModedEffect, EffectFields<typeof pixelateSpec.params> {\n type: \"pixelate\";\n}\n\n/** The {@link PixelateEffect} spec: its parameters, defaults and ranges. */\nexport const pixelateSpec = defineEffect({\n type: \"pixelate\",\n group: \"stylize\",\n scalar: \"blocks\",\n // Resolution-relative: inert only while a block is finer than the pixel grid.\n neutral: { blocks: 1920 },\n params: {\n /** Block count per axis; a bare number sets both. */\n blocks: param.vec2({ default: 1, fromNumber: \"both\", required: true, min: 1, step: 1, initial: { x: 64, y: 64 } }),\n /** AE \"Sharp Colors\": solid blocks (true) vs. smoothly blended. */\n sharpColors: param.boolean({ default: true }),\n },\n});\n\nexport const pixelateEffect: EffectData<PixelateEffect> = effectDataOf(pixelateSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { CENTER, defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\nexport interface BulgeEffect extends ModedEffect, EffectFields<typeof bulgeSpec.params> {\n type: \"bulge\";\n}\n\n/** The {@link BulgeEffect} spec: its parameters, defaults and ranges. */\nexport const bulgeSpec = defineEffect({\n type: \"bulge\",\n group: \"distort\",\n // Warps its source: samples a displaced texel per fragment.\n surface: \"shader\",\n scalar: \"strength\",\n neutral: { strength: 0 },\n params: {\n /** Positive bulges (barrel), negative pinches (pincushion). Range ≈ −1…1. */\n strength: param.number({ default: 0, required: true, min: -1, max: 1, control: \"slider\", inline: true, initial: 0.5 }),\n /** Lens centre in 0–1 layer coords. */\n center: param.vec2({ default: CENTER, min: 0, max: 1, step: 0.01, unit: \"normalized\", label: \"lensCenter\" }),\n },\n});\n\nexport const bulgeEffect: EffectData<BulgeEffect> = effectDataOf(bulgeSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { CENTER, defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\nexport interface MagnifyEffect extends ModedEffect, EffectFields<typeof magnifySpec.params> {\n type: \"magnify\";\n}\n\n/** The {@link MagnifyEffect} spec: its parameters, defaults and ranges. */\nexport const magnifySpec = defineEffect({\n type: \"magnify\",\n group: \"distort\",\n // Resamples the backdrop about `center`.\n surface: \"shader\",\n scalar: \"scale\",\n defaultMode: \"backdrop\",\n onlyOn: \"backdrop\",\n neutral: { scale: 1 },\n params: {\n /** Magnification factor — 1 = none, 2 = 2×, 0.5 = zoomed out. */\n scale: param.number({ default: 2, min: 0, step: 0.1, unit: \"factor\", label: \"magnification\", inline: true }),\n /** Magnify centre in 0–1 layer coords. */\n center: param.vec2({ default: CENTER, min: 0, max: 1, step: 0.01, unit: \"normalized\", label: \"lensCenter\" }),\n },\n});\n\nexport const magnifyEffect: EffectData<MagnifyEffect> = effectDataOf(magnifySpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\nexport interface BloomEffect extends ModedEffect, EffectFields<typeof bloomSpec.params> {\n type: \"bloom\";\n}\n\n/** The {@link BloomEffect} spec: its parameters, defaults and ranges. */\nexport const bloomSpec = defineEffect({\n type: \"bloom\",\n group: \"light\",\n scalar: \"intensity\",\n neutral: { intensity: 0 },\n params: {\n /** 0–1 luminance cutoff — only pixels brighter than this bloom. */\n threshold: param.number({ default: 0.7, min: 0, max: 1, control: \"slider\" }),\n /** Spread in pixels. */\n radius: param.number({ default: 12, min: 0, unit: \"px\" }),\n /** Additive multiplier for the bloom pass. */\n intensity: param.number({ default: 1, min: 0, max: 3, control: \"slider\", inline: true }),\n },\n});\n\nexport const bloomEffect: EffectData<BloomEffect> = effectDataOf(bloomSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\nexport interface VintageEffect extends ModedEffect, EffectFields<typeof vintageSpec.params> {\n type: \"vintage\";\n}\n\n/** The {@link VintageEffect} spec: its parameters, defaults and ranges. */\nexport const vintageSpec = defineEffect({\n type: \"vintage\",\n group: \"color\",\n scalar: \"amount\",\n neutral: { amount: 0, warmth: 0 },\n params: {\n /** 0–1: 0 = original, 1 = full sepia + desaturate. */\n amount: param.number({ default: 1, min: 0, max: 1, control: \"slider\", inline: true }),\n /** −1…1: negative = cool/cyan tint, positive = warm/amber. */\n warmth: param.number({ default: 0.2, min: -1, max: 1, control: \"slider\" }),\n },\n});\n\nexport const vintageEffect: EffectData<VintageEffect> = effectDataOf(vintageSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\nexport interface ChromaticAberrationEffect extends ModedEffect, EffectFields<typeof chromaticAberrationSpec.params> {\n type: \"chromaticAberration\";\n}\n\n/** The {@link ChromaticAberrationEffect} spec: its parameters, defaults and ranges. */\nexport const chromaticAberrationSpec = defineEffect({\n type: \"chromaticAberration\",\n group: \"glitch\",\n scalar: \"amount\",\n neutral: { amount: 0 },\n params: {\n /** Pixel offset distance for the R/B fringe. */\n amount: param.number({ default: 4, min: 0, unit: \"px\", inline: true }),\n /** Fringe axis in degrees — 0 = horizontal, R right / B left. */\n angle: param.number({ default: 0, unit: \"deg\" }),\n },\n});\n\nexport const chromaticAberrationEffect: EffectData<ChromaticAberrationEffect> = effectDataOf(chromaticAberrationSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Which channel(s) / colour space component the invert is applied to.\n *\n * - `'red' | 'green' | 'blue'` — invert a single RGB channel.\n * - `'rgba'` — invert red, green and blue (alpha untouched).\n * - `'alpha'` — invert the alpha channel.\n * - `'hue'` — rotate hue by 180°.\n * - `'luminance'` — invert perceptual luminance (BT.709) while preserving chroma.\n */\nexport type InvertChannel =\n | \"red\"\n | \"green\"\n | \"blue\"\n | \"rgba\"\n | \"alpha\"\n | \"hue\"\n | \"luminance\";\n\nexport interface InvertEffect extends ModedEffect, EffectFields<typeof invertSpec.params> {\n type: \"invert\";\n}\n\n/** The {@link InvertEffect} spec: its parameters, defaults and ranges. */\nexport const invertSpec = defineEffect({\n type: \"invert\",\n group: \"color\",\n scalar: \"strength\",\n neutral: { strength: 0 },\n params: {\n /** Which channel / colour component to invert. */\n channel: param.choice([\"rgba\", \"red\", \"green\", \"blue\", \"alpha\", \"hue\", \"luminance\"] satisfies InvertChannel[], { default: \"rgba\", optionsLabel: \"invertChannel\" }),\n /** 0–1: blend from original (0) to fully inverted (1). */\n strength: param.number({ default: 1, min: 0, max: 1, control: \"slider\", inline: true }),\n },\n});\n\nexport const invertEffect: EffectData<InvertEffect> = effectDataOf(invertSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\nexport interface ScatterEffect extends ModedEffect, EffectFields<typeof scatterSpec.params> {\n type: \"scatter\";\n}\n\n/** The {@link ScatterEffect} spec: its parameters, defaults and ranges. */\nexport const scatterSpec = defineEffect({\n type: \"scatter\",\n group: \"glitch\",\n // Displaces each pixel by a hash of its position, so it needs random access\n // to its source. It was realised as a displacement-map ImageFilter until the\n // filter path's layer snapping was found to re-roll the field whenever the\n // node stood on a fractional pixel — see the renderer's `scatter` handler,\n // which carries the full account.\n surface: \"shader\",\n scalar: \"strength\",\n neutral: { strength: 0 },\n params: {\n /** Maximum random pixel displacement. */\n strength: param.number({ default: 10, min: 0, unit: \"px\", inline: true }),\n /** Axis pixels are scattered along. */\n axis: param.axis({ default: \"both\", label: \"direction\", optionsLabel: \"effectAxis\" }),\n },\n});\n\nexport const scatterEffect: EffectData<ScatterEffect> = effectDataOf(scatterSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * After Effects-style Posterize.\n *\n * Quantizes each colour channel into `levels` evenly-spaced brightness steps, so\n * smooth gradients collapse into flat bands. `levels` is the number of tones per\n * channel (matching AE's single \"Level\" parameter): 2 → pure two-tone per\n * channel, higher values keep more detail. Below 2 there is nothing to band, so\n * the effect is a no-op.\n */\nexport interface PosterizeEffect extends ModedEffect, EffectFields<typeof posterizeSpec.params> {\n type: \"posterize\";\n}\n\n/** The {@link PosterizeEffect} spec: its parameters, defaults and ranges. */\nexport const posterizeSpec = defineEffect({\n type: \"posterize\",\n group: \"color\",\n // Reads its source texel-by-texel through a banding shader.\n surface: \"shader\",\n scalar: \"levels\",\n neutral: { levels: 255 },\n params: {\n /** Number of brightness levels per channel (≥ 2). */\n levels: param.number({ default: 4, min: 2, step: 1, inline: true }),\n },\n});\n\nexport const posterizeEffect: EffectData<PosterizeEffect> = effectDataOf(posterizeSpec);\n", "import { BlendModes, type BlendMode } from \"../../fill/blend\";\nimport type { ModedEffect, EffectData } from \"../effect-data\";\nimport {\n lerpUniformRecord,\n normalizeUniforms,\n uniformRecordsEqual,\n type ShaderUniform,\n type ShaderUniformRecord,\n} from \"../../shaders/uniforms\";\nimport { shaderContractOf, type ShaderLanguage } from \"../../shaders/language\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * A custom shader, classified by the shared {@link EffectMode}:\n *\n * - `'backdrop'`: `sample_src` reads a snapshot of the canvas content beneath\n * the node. For magnification, distortion, ripple. The result replaces the\n * backdrop within the node's silhouette clip.\n *\n * - `'foreground'` (the default): `sample_src` reads the node's own layer, and\n * the output replaces it, or composites onto it with {@link blendMode}.\n *\n * Named for the paint it is the sibling of: this is the same act as a `shader`\n * **fill**, on a layer instead of inside a path.\n */\nexport interface ShaderEffect extends ModedEffect {\n type: \"shader\";\n /**\n * The program. In WGSL it defines `fn effect(in: EffectIn) -> vec4f`\n * (premultiplied), reads its input with `sample_src(uv)` /\n * `sample_src_px(px)` — the node's layer, or in `'backdrop'` mode what lies\n * beneath it — and its uniforms as `u`, the `struct Params` it declares.\n */\n source: string;\n /** The language `source` is written in; WGSL when absent. */\n language?: ShaderLanguage;\n /** WGSL only: the contract version it is written against; `resolve` stamps `WGSL_CONTRACT` when absent. */\n contract?: number;\n /**\n * How far past the node's box (logical px) a WGSL effect may draw — a glow,\n * a ripple that spills. The layer it runs over grows by it. Default 0.\n */\n reach?: number;\n /**\n * Uniform values, by name. Values lerp component-wise.\n *\n * The positional `[{ name, value }]` array older documents carry is still\n * accepted and normalised on the way in; both are bound by name.\n */\n uniforms: ShaderUniformRecord | ShaderUniform[];\n /**\n * The shader pack this was built from, when it was built from one.\n *\n * **Reserved, and carried rather than read.** A pack resolves to a plain\n * uniform record before it reaches here, so nothing in the render path needs\n * this — the frame is identical with or without it. What it exists for is the\n * trip back: a document stores resolved uniforms, and without a reference to\n * the pack a host reopening a saved scene has a set of numbers and no way to\n * know which of them were `twist` and `ink`, so the property panel it drew\n * when the shader was applied cannot be drawn again.\n *\n * An id naming a pack that is not registered is **not** an error: the shader\n * still renders, because the uniforms it needs are already in the document.\n * The host simply cannot offer the panel, which is the honest degradation —\n * refusing to render a scene because an editor cannot edit it would be the\n * wrong way round.\n */\n shaderId?: string;\n /**\n * Blend mode used when `mode` is `'foreground'`; the output replaces the\n * layer when absent. Ignored for `'backdrop'`.\n */\n blendMode?: BlendMode;\n}\n\n// The hand-written interface and the spec describe the same fields.\ntype ShaderFields = Omit<ShaderEffect, \"type\" | keyof ModedEffect>;\ntype SpecFields = EffectFields<typeof shaderSpec.params>;\nconst _specAgrees: [ShaderFields extends SpecFields ? true : false, SpecFields extends ShaderFields ? true : false] = [true, true];\n\n/**\n * The {@link ShaderEffect} spec. Its fields are described for a host; its\n * interpolation, equality and surface stay hand-written, since they are about a\n * program and its uniform record rather than a set of parameters.\n */\nexport const shaderSpec = defineEffect({\n type: \"shader\",\n group: \"stylize\",\n // An arbitrary user shader: neutrality is the author's to define.\n neutral: null,\n params: {\n source: param.text({ required: true, hidden: true }),\n language: {\n ...param.choice([\"wgsl\"] satisfies ShaderLanguage[], { optional: true, hidden: true }),\n // \"sksl\" is the retired value documents from before WGSL carry: it draws nothing and is reported.\n options: [\"wgsl\", \"sksl\"],\n },\n reach: param.number({ optional: true, min: 0, unit: \"px\", hidden: true }),\n uniforms: param.of<ShaderUniformRecord | ShaderUniform[]>()({ kind: \"uniforms\", default: {}, hidden: true }),\n shaderId: param.text({ optional: true, hidden: true }),\n blendMode: param.choice(BlendModes, { optional: true, optionsLabel: \"blendMode\" }),\n },\n // Returns the effect untouched when it already states its contract, which\n // is what keeps `resolveChainEffects` from copying an array per write.\n resolve: (effect: ShaderEffect) => {\n const contract = effect.contract ?? shaderContractOf(effect);\n return contract === effect.contract ? effect : { ...effect, contract };\n },\n // The program and what it is blended with snap at the midpoint, as the\n // `shader` fill's source does: the source is the compile-cache key, so there\n // is no program halfway between two. Only the uniform values interpolate\n // (over the union of names), which keeps a same-program tween smooth.\n lerp: (from: ShaderEffect, to: ShaderEffect, t: number): ShaderEffect => {\n const near = t < 0.5 ? from : to;\n return {\n type: \"shader\",\n source: near.source,\n ...(near.language !== undefined ? { language: near.language } : {}),\n ...(near.contract !== undefined ? { contract: near.contract } : {}),\n ...(from.reach !== undefined || to.reach !== undefined\n ? { reach: (from.reach ?? 0) + ((to.reach ?? 0) - (from.reach ?? 0)) * t }\n : {}),\n ...(near.shaderId !== undefined ? { shaderId: near.shaderId } : {}),\n mode: near.mode,\n blendMode: near.blendMode,\n uniforms: lerpUniformRecord(\n normalizeUniforms(from.uniforms),\n normalizeUniforms(to.uniforms),\n t,\n ),\n };\n },\n equals: (a: ShaderEffect, b: ShaderEffect) =>\n a.source === b.source &&\n a.language === b.language &&\n a.contract === b.contract &&\n (a.reach ?? 0) === (b.reach ?? 0) &&\n a.mode === b.mode &&\n a.blendMode === b.blendMode &&\n uniformRecordsEqual(normalizeUniforms(a.uniforms), normalizeUniforms(b.uniforms)),\n // A backdrop shader resamples what is beneath the node, so it needs a redraw scope.\n surface: (effect: ShaderEffect) => (effect.mode === \"backdrop\" ? \"shader\" : \"filter\"),\n});\n\nexport const shaderEffect = effectDataOf(shaderSpec) as unknown as EffectData<ShaderEffect>;\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Where the outline sits relative to the node's silhouette — the same three\n * choices Figma and Illustrator offer for a stroke:\n *\n * - `\"outside\"` grows outward from the edge, leaving the content untouched.\n * - `\"inside\"` eats inward, so the node's footprint never changes.\n * - `\"center\"` straddles the edge, half of `width` on each side.\n */\nexport type OutlinePosition = \"outside\" | \"center\" | \"inside\";\n\n/**\n * A coloured band traced around the node's silhouette — the alpha outline\n * (a.k.a. \"stroke\" in Figma) that geometry strokes can't give you when the\n * silhouette comes from text, an image's alpha, or a whole subtree.\n */\nexport interface OutlineEffect extends ModedEffect, EffectFields<typeof outlineSpec.params> {\n type: \"outline\";\n}\n\n/** The {@link OutlineEffect} spec: its parameters, defaults and ranges. */\nexport const outlineSpec = defineEffect({\n type: \"outline\",\n group: \"stylize\",\n // Reads a ring of neighbouring texels to dilate/erode the source's alpha.\n surface: \"shader\",\n scalar: \"width\",\n onlyOn: \"foreground\",\n neutral: { width: 0 },\n params: {\n /** Band thickness in pixels. */\n width: param.number({ default: 4, min: 0, unit: \"px\", inline: true }),\n /** Band colour. */\n color: param.color({ default: \"black\" }),\n /** Which side of the edge the band grows from. */\n position: param.choice([\"outside\", \"center\", \"inside\"] satisfies OutlinePosition[], { default: \"outside\", optionsLabel: \"outlinePosition\" }),\n },\n});\n\nexport const outlineEffect: EffectData<OutlineEffect> = effectDataOf(outlineSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * A shadow cast from the node's **alpha silhouette** rather than from its\n * geometry — the drop shadow that a `shadow` prop can't give you when the shape\n * on screen isn't the shape of the path.\n *\n * A shape's `shadow` fills the node's own outline with the shadow colour and\n * blurs it, which is exactly right for a rect, an ellipse or a star. It is\n * exactly wrong for anything whose visible form comes from *pixels*: a cut-out\n * PNG, a video with an alpha channel, a line of text, a whole subtree. All of\n * those cast a blurred **rectangle**, because the rectangle is what their path\n * is — and on a cut-out subject that reads as a bug rather than as a shadow.\n *\n * So this one is computed from what the node actually drew. Same relationship\n * to `shadow` that {@link OutlineEffect} has to `stroke`: the geometry version\n * is cheaper and sharper where the path *is* the picture, and this one is the\n * answer everywhere else.\n *\n * Offsets are in the scene's own axes — a positive `y` lifts the shadow upward,\n * matching `ShadowProp.offset` rather than the y-down device space the shader\n * runs in, so the two kinds of shadow move the same way under the same numbers.\n */\nexport interface DropShadowEffect extends ModedEffect, EffectFields<typeof dropShadowSpec.params> {\n type: \"dropShadow\";\n}\n\n/** The {@link DropShadowEffect} spec: its parameters, defaults and ranges. */\nexport const dropShadowSpec = defineEffect({\n type: \"dropShadow\",\n group: \"stylize\",\n surface: \"shader\",\n // Softness is the knob a shadow is usually reached for by.\n scalar: \"blur\",\n onlyOn: \"foreground\",\n // Nowhere to fall, no softness and no growth: nothing of it is ever visible.\n neutral: { offsetX: 0, offsetY: 0, blur: 0, spread: 0 },\n params: {\n /** Horizontal displacement in pixels. */\n offsetX: param.number({ default: 0, unit: \"px\", label: \"shadowX\" }),\n /** Vertical displacement in pixels, positive being upward. */\n offsetY: param.number({ default: -8, unit: \"px\", label: \"shadowY\" }),\n /** Softness in pixels, on a `blur` effect's scale. */\n blur: param.number({ default: 16, min: 0, unit: \"px\", label: \"shadowBlur\", inline: true }),\n /** Grows the silhouette before blurring, in pixels. */\n spread: param.number({ default: 0, min: 0, unit: \"px\", label: \"shadowSpread\" }),\n /** Shadow colour. */\n color: param.color({ default: \"black\" }),\n },\n});\n\nexport const dropShadowEffect: EffectData<DropShadowEffect> = effectDataOf(dropShadowSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Darkened corners — the lens falloff every photo grade reaches for.\n *\n * The node box is normalised to a unit ellipse, so the falloff follows the\n * node's aspect ratio rather than an off-centre circle. Everything inside\n * `radius` is untouched; from there to `radius + softness` the tint ramps in\n * with a smoothstep, reaching `amount` at the corners.\n */\nexport interface VignetteEffect extends ModedEffect, EffectFields<typeof vignetteSpec.params> {\n type: \"vignette\";\n}\n\n/** The {@link VignetteEffect} spec: its parameters, defaults and ranges. */\nexport const vignetteSpec = defineEffect({\n type: \"vignette\",\n group: \"light\",\n // Needs each pixel's position within the node box to compute its falloff.\n surface: \"shader\",\n scalar: \"amount\",\n neutral: { amount: 0 },\n params: {\n /** 0–1 tint strength at the very edge. 0 = off. */\n amount: param.number({ default: 0.5, min: 0, max: 1, control: \"slider\", inline: true }),\n /** 0–1 normalised radius where the falloff starts (1 ≈ the box corners). */\n radius: param.number({ default: 0.75, min: 0, max: 1, control: \"slider\" }),\n /** 0–1 width of the ramp; 0 is a hard ring, 1 a long gradient. */\n softness: param.number({ default: 0.5, min: 0, max: 1, control: \"slider\" }),\n /** Tint colour — black darkens (the classic look), white blows the edges out. */\n color: param.color({ default: \"black\", label: \"tint\" }),\n },\n});\n\nexport const vignetteEffect: EffectData<VignetteEffect> = effectDataOf(vignetteSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Film grain — per-pixel noise blended into the node's own content.\n *\n * The noise is *signed* (it lightens and darkens around the source value) and\n * scaled by the local alpha, so it never bleeds past the silhouette and never\n * shifts the average exposure.\n *\n * Grain that doesn't move reads as a texture rather than as film, so\n * {@link animated} re-seeds the field every frame from the node's elapsed time.\n * For a deterministic render (e.g. a pixel-diff test) leave it off and animate\n * {@link seed} instead — a tween over `seed` gives the same shimmer frame-locked\n * to the timeline.\n */\nexport interface GrainEffect extends ModedEffect, EffectFields<typeof grainSpec.params> {\n type: \"grain\";\n}\n\n/** The {@link GrainEffect} spec: its parameters, defaults and ranges. */\nexport const grainSpec = defineEffect({\n type: \"grain\",\n group: \"stylize\",\n // Hashes each pixel's position into a noise value.\n surface: \"shader\",\n scalar: \"amount\",\n neutral: { amount: 0 },\n params: {\n /** 0–1 noise amplitude. */\n amount: param.number({ default: 0.25, min: 0, max: 1, control: \"slider\", inline: true }),\n /** Grain cell size in pixels. */\n size: param.number({ default: 1, min: 1, unit: \"px\", label: \"grainSize\" }),\n /** Random field offset — animate it for frame-locked shimmer. */\n seed: param.number({ default: 0, step: 1 }),\n /** Re-seed every frame from elapsed time. */\n animated: param.boolean({ default: false }),\n /** Per-channel colour speckle instead of luminance noise. */\n colored: param.boolean({ default: false }),\n },\n});\n\nexport const grainEffect: EffectData<GrainEffect> = effectDataOf(grainSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Unsharp mask — the standard sharpen: subtract a blurred copy of the content\n * from itself and add the difference back, which exaggerates local contrast at\n * edges.\n *\n * out = c + amount · (c − blur(c, radius))\n *\n * `radius` sets the scale of detail affected (a small radius crisps fine texture,\n * a large one adds \"clarity\" to broad shapes); `amount` sets how hard. Past\n * ~2 the classic halo artefact shows up, which is sometimes the point.\n */\nexport interface SharpenEffect extends ModedEffect, EffectFields<typeof sharpenSpec.params> {\n type: \"sharpen\";\n}\n\n/** The {@link SharpenEffect} spec: its parameters, defaults and ranges. */\nexport const sharpenSpec = defineEffect({\n type: \"sharpen\",\n group: \"blur\",\n // Convolves a neighbourhood, so it resamples.\n surface: \"shader\",\n scalar: \"amount\",\n neutral: { amount: 0 },\n params: {\n /** Edge-contrast boost. */\n amount: param.number({ default: 1, min: 0, max: 4, control: \"slider\", inline: true }),\n /** Radius of the blurred reference, in pixels. */\n radius: param.number({ default: 1, min: 0, unit: \"px\" }),\n },\n});\n\nexport const sharpenEffect: EffectData<SharpenEffect> = effectDataOf(sharpenSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Which convolution kernel detects the edges.\n *\n * - `\"sobel\"` — gradient magnitude with a centre-weighted 3×3 pair. The default:\n * thick, smooth, noise-tolerant edges.\n * - `\"prewitt\"` — the same gradient pair without the centre weighting. Slightly\n * thinner and more literal, noisier on gradients.\n * - `\"laplacian\"` — second derivative in one pass. Finest lines, picks up texture\n * the gradient operators smooth over.\n */\nexport type EdgeKernel = \"sobel\" | \"prewitt\" | \"laplacian\";\n\n/**\n * Edge detection — replaces the content with the magnitude of its own gradient,\n * so flat areas go black and boundaries light up.\n */\nexport interface EdgesEffect extends ModedEffect, EffectFields<typeof edgesSpec.params> {\n type: \"edges\";\n}\n\n/** The {@link EdgesEffect} spec: its parameters, defaults and ranges. */\nexport const edgesSpec = defineEffect({\n type: \"edges\",\n group: \"stylize\",\n // Convolves a 3×3 neighbourhood.\n surface: \"shader\",\n scalar: \"strength\",\n neutral: { strength: 0 },\n params: {\n /** Multiplier on the detected gradient. */\n strength: param.number({ default: 1, min: 0, max: 4, control: \"slider\", inline: true }),\n /** Which operator measures the gradient. */\n kernel: param.choice([\"sobel\", \"prewitt\", \"laplacian\"] satisfies EdgeKernel[], { default: \"sobel\", optionsLabel: \"edgeKernel\" }),\n /** Detect per RGB channel instead of on luminance. */\n colored: param.boolean({ default: false }),\n },\n});\n\nexport const edgesEffect: EffectData<EdgesEffect> = effectDataOf(edgesSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Two-tone cut: every pixel brighter than `level` becomes white, everything\n * else black — the stencil / high-contrast look.\n *\n * `smoothness` widens the cut into a ramp centred on `level`, which both\n * anti-aliases the boundary and, at higher values, keeps some midtone\n * modelling instead of a pure stencil.\n */\nexport interface ThresholdEffect extends ModedEffect, EffectFields<typeof thresholdSpec.params> {\n type: \"threshold\";\n}\n\n/** The {@link ThresholdEffect} spec: its parameters, defaults and ranges. */\nexport const thresholdSpec = defineEffect({\n type: \"threshold\",\n group: \"color\",\n // A non-linear per-pixel remap, drawn as its own pass.\n surface: \"shader\",\n scalar: \"level\",\n // Flattens colour to two tones at every level and smoothness.\n neutral: null,\n params: {\n /** 0–1 cut point. */\n level: param.number({ default: 0.5, min: 0, max: 1, control: \"slider\", inline: true }),\n /** 0–1 ramp width around the cut (just enough to anti-alias by default). */\n smoothness: param.number({ default: 0.05, min: 0, max: 1, control: \"slider\" }),\n },\n});\n\nexport const thresholdEffect: EffectData<ThresholdEffect> = effectDataOf(thresholdSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { CENTER, defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Which way the samples are smeared around {@link RadialBlurEffect.center}.\n *\n * - `\"zoom\"` — along the radius: a rush toward or away from the centre.\n * - `\"spin\"` — along the tangent: rotational motion about the centre.\n *\n * (After Effects calls this the effect's \"Type\"; here that name belongs to the\n * effect discriminator, so the field is `style`.)\n */\nexport type RadialBlurStyle = \"zoom\" | \"spin\";\n\n/**\n * After Effects' Radial Blur — the source is sampled repeatedly along a path\n * that radiates from (`zoom`) or circles (`spin`) a centre point, and the taps\n * are averaged. The centre stays sharp and the smear grows with distance, which\n * is what makes it read as speed rather than as softness.\n */\nexport interface RadialBlurEffect extends ModedEffect, EffectFields<typeof radialBlurSpec.params> {\n type: \"radialBlur\";\n}\n\n/** The {@link RadialBlurEffect} spec: its parameters, defaults and ranges. */\nexport const radialBlurSpec = defineEffect({\n type: \"radialBlur\",\n group: \"blur\",\n // Resamples along a path per pixel.\n surface: \"shader\",\n scalar: \"amount\",\n neutral: { amount: 0 },\n params: {\n /** Smear length, 0–1. */\n amount: param.number({ default: 0.5, min: 0, max: 1, control: \"slider\", inline: true, order: 1 }),\n /** Radial rush (`'zoom'`) or rotational streak (`'spin'`). */\n style: param.choice([\"zoom\", \"spin\"] satisfies RadialBlurStyle[], { default: \"zoom\", control: \"segmented\", optionsLabel: \"radialBlurStyle\", order: 0 }),\n /** Blur centre in 0–1 layer coords. */\n center: param.vec2({ default: CENTER, min: 0, max: 1, step: 0.01, unit: \"normalized\", order: 2 }),\n /** Taps averaged per pixel (max 32). A quality knob, so it snaps. */\n samples: param.number({ default: 16, min: 2, max: 32, step: 1, lerp: \"step\", hidden: true, order: 3 }),\n },\n});\n\nexport const radialBlurEffect: EffectData<RadialBlurEffect> = effectDataOf(radialBlurSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * The screen pattern each halftone cell is drawn with.\n *\n * - `\"dot\"` — the classic circular dot that grows with tone.\n * - `\"line\"` — a line screen: parallel rules that thicken with tone.\n * - `\"cross\"` — crossed rules, a coarse engraving / crosshatch.\n */\nexport type HalftoneShape = \"dot\" | \"line\" | \"cross\";\n\n/**\n * How many plates the screen is separated into.\n *\n * - `\"mono\"` — one black screen over luminance. The newsprint look.\n * - `\"cmyk\"` — four plates at the classic process angles (C 15°, M 75°, Y 0°,\n * K 45°). Pulling the shared darkness onto a K plate is what keeps neutrals\n * neutral, so this is the one that reads as *printed*.\n * - `\"rgb\"` — one screen per RGB channel. Cheaper and occasionally the look you\n * want, but with no K plate every grey prints three overlapping mid-dots, so\n * anything neutral turns to colour noise. Prefer `\"cmyk\"` for print looks.\n */\nexport type HalftoneSeparation = \"mono\" | \"rgb\" | \"cmyk\";\n\n/**\n * Halftone screen — the newsprint / comic-book look. The image is divided into a\n * rotated grid of cells and each cell's tone becomes the size of a mark, so\n * continuous shading is reproduced by varying dot area rather than intensity.\n *\n * `separation` picks how many plates the image is split across — see\n * {@link HalftoneSeparation}.\n */\nexport interface HalftoneEffect extends ModedEffect, EffectFields<typeof halftoneSpec.params> {\n type: \"halftone\";\n}\n\n/** The {@link HalftoneEffect} spec: its parameters, defaults and ranges. */\nexport const halftoneSpec = defineEffect({\n type: \"halftone\",\n group: \"stylize\",\n // Cell position drives the mark, so it needs each pixel's coordinates.\n surface: \"shader\",\n scalar: \"size\",\n // Resolution-relative: inert only while the cell is finer than the pixel grid.\n neutral: { size: 0.5 },\n params: {\n /** Cell pitch in pixels. */\n size: param.number({ default: 8, min: 1, unit: \"px\", label: \"cellSize\", inline: true }),\n /** Screen rotation in degrees. */\n angle: param.number({ default: 45, unit: \"deg\", control: \"angle\", label: \"screenAngle\" }),\n /** Mark drawn per cell. */\n shape: param.choice([\"dot\", \"line\", \"cross\"] satisfies HalftoneShape[], { default: \"dot\", optionsLabel: \"halftoneShape\" }),\n /** Plates to screen into. */\n separation: param.choice([\"mono\", \"rgb\", \"cmyk\"] satisfies HalftoneSeparation[], { default: \"mono\", optionsLabel: \"halftoneSeparation\" }),\n },\n});\n\nexport const halftoneEffect: EffectData<HalftoneEffect> = effectDataOf(halftoneSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Size of the Bayer threshold matrix: 2×2, 4×4 or 8×8. Bigger matrices carry\n * more distinct threshold levels, so the pattern is finer and the apparent tonal\n * range wider — 2 is a blunt checkerboard, 8 the smooth classic ordered dither.\n */\nexport type DitherMatrix = 2 | 4 | 8;\n\n/**\n * Where a pixel's threshold comes from.\n *\n * - `'bayer'` — the recursive ordered matrix. Its lattice *is* the look: the\n * crosshatch is visible at every density, which is what reads as 8-bit and\n * what makes it beat against the pixel grid at some `scale`s.\n * - `'blue'` — a void-and-cluster blue-noise field. Every density stays\n * homogeneous, so the tone is reproduced with no lattice and no moiré. Pick\n * this when the dither should be texture rather than pattern.\n *\n * `matrix` only applies to `'bayer'`.\n */\nexport type DitherNoise = 'bayer' | 'blue';\n\n/**\n * Ordered dithering — quantize the image to `levels` tones per channel, but\n * offset each pixel's rounding by a threshold pattern first. The error is traded\n * for texture instead of banding, which is how 8-bit hardware faked gradients.\n *\n * `noise` picks which pattern: the classic Bayer matrix (visible crosshatch, the\n * retro look) or blue noise (no visible structure at any density).\n *\n * Contrast with `posterize`, which quantizes with no threshold pattern and so\n * produces flat bands.\n */\nexport interface DitherEffect extends ModedEffect, EffectFields<typeof ditherSpec.params> {\n type: \"dither\";\n}\n\n/** The {@link DitherEffect} spec: its parameters, defaults and ranges. */\nexport const ditherSpec = defineEffect({\n type: \"dither\",\n group: \"stylize\",\n // The threshold depends on the pixel's position in the pattern.\n surface: \"shader\",\n scalar: \"levels\",\n neutral: { levels: 255 },\n params: {\n /** Output tones per channel, ≥ 2. */\n levels: param.number({ default: 2, min: 2, max: 32, step: 1, inline: true, order: 0 }),\n /** Bayer matrix size. Ignored when `noise` is `'blue'`. */\n matrix: param.choice([2, 4, 8] satisfies DitherMatrix[], { default: 4, optionsLabel: \"ditherMatrix\", order: 2 }),\n /** Pattern cell size in pixels. */\n scale: param.number({ default: 1, min: 1, step: 1, unit: \"px\", label: \"cellSize\", order: 3 }),\n /** Dither luminance to black and white. */\n monochrome: param.boolean({ default: false, order: 4 }),\n /**\n * Threshold pattern. `'bayer'` is the classic ordered matrix — a visible\n * crosshatch, the retro look, which can beat against the pixel grid at\n * some `scale`s. `'blue'` is a void-and-cluster blue-noise field: same\n * tone reproduction, no lattice, no moiré.\n */\n noise: param.choice([\"bayer\", \"blue\"] satisfies DitherNoise[], { default: \"bayer\", label: \"ditherNoise\", optionsLabel: \"ditherNoise\", order: 1 }),\n },\n});\n\nexport const ditherEffect: EffectData<DitherEffect> = effectDataOf(ditherSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Duotone / gradient map — remap the content's luminance onto a two-colour ramp,\n * so black becomes `shadows`, white becomes `highlights`, and everything between\n * interpolates. Chroma in the source is discarded; only its brightness survives.\n *\n * The editorial two-colour treatment (Spotify covers, risograph posters) and the\n * general \"tint a photo to brand colours\" tool, both from one pair of colours.\n */\nexport interface DuotoneEffect extends ModedEffect, EffectFields<typeof duotoneSpec.params> {\n type: \"duotone\";\n}\n\n/** The {@link DuotoneEffect} spec: its parameters, defaults and ranges. */\nexport const duotoneSpec = defineEffect({\n type: \"duotone\",\n group: \"color\",\n // A luminance ramp is a plain affine colour transform, so it composes as an\n // ImageFilter (the default surface) rather than needing a shader scope.\n scalar: \"amount\",\n neutral: { amount: 0 },\n params: {\n /** 0–1 blend from the original colours to the full ramp. */\n amount: param.number({ default: 1, min: 0, max: 1, control: \"slider\", inline: true }),\n /** Colour the darkest tones map to. */\n shadows: param.color({ default: \"black\" }),\n /** Colour the brightest tones map to. */\n highlights: param.color({ default: \"white\" }),\n },\n});\n\nexport const duotoneEffect: EffectData<DuotoneEffect> = effectDataOf(duotoneSpec);\n", "import { lerpNumber } from \"@/tween/lerp\";\nimport type { ModedEffect, EffectData } from \"../effect-data\";\nimport type { CurvesChannel } from \"../../filters/implementations/curves\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Tone curve as a **node effect** — the same adjustment `Adjustments.curves`\n * applies to a photo, now available on any node, so a group of shapes or a text\n * block can be graded the same way.\n *\n * Shares its type name, fields and renderer handler with {@link CurvesFilter}\n * (the media-fill filter); the only difference is the `mode` flag every scene\n * effect carries. Keeping them one implementation is deliberate — a curve should\n * not mean two different things depending on what it is attached to.\n */\nexport interface CurvesEffect extends ModedEffect, EffectFields<typeof curvesSpec.params> {\n type: \"curves\";\n}\n\n/** The {@link CurvesEffect} spec: its parameters, defaults and ranges. */\nexport const curvesSpec = defineEffect({\n type: \"curves\",\n group: \"color\",\n // A curve is a *lookup*, and a colour matrix cannot express one: it is affine\n // by construction and a curve is authored for its bends. Evaluating it per\n // pixel needs the source as a shader it can read — the same reason `lut` is a\n // shader scope, and the same trade: exact, at the cost of a pass. See the\n // renderer's `curvesEffectHandler` for what that means for ordering.\n surface: \"shader\",\n neutral: { points: [[0, 0], [1, 1]] },\n params: {\n /** Curve control points as `[input, output]` pairs in 0–1. Move pairwise, as `curvesFilter.lerp`. */\n points: param.of<[number, number][]>()({\n kind: \"points\",\n required: true,\n lerp: (from, to, t) => from.map(([x, y], i) => {\n const [tx, ty] = to[i] ?? [x, y];\n return [lerpNumber(x, tx, t), lerpNumber(y, ty, t)] as [number, number];\n }),\n equals: (a, b) => a.length === b.length && a.every(([x, y], i) => x === b[i]?.[0] && y === b[i]?.[1]),\n }),\n /** Channel(s) the curve applies to. An intermediate channel name is meaningless, so it cuts. */\n channel: param.choice([\"rgb\", \"r\", \"g\", \"b\", \"a\"] satisfies CurvesChannel[], { default: \"rgb\", optional: true }),\n },\n});\n\nexport const curvesEffect: EffectData<CurvesEffect> = effectDataOf(curvesSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Photographic tonal and colour adjustments as a **node effect** — the grading\n * panel `Adjustments.colorAdjustment` gives an image fill, now available on any\n * node. All fields are optional and default to neutral.\n *\n * Shares its type name and renderer handler with `ColorAdjustmentFilter` (the\n * media-fill filter) with one deliberate difference: no `vignette` field. That\n * knob was never implemented on the filter — a vignette needs each pixel's\n * position, which a colour matrix does not have — so the node effect leaves it\n * out and `Effects.vignette()` provides the real thing.\n */\nexport interface ColorAdjustmentEffect extends ModedEffect, EffectFields<typeof colorAdjustmentSpec.params> {\n type: \"colorAdjustment\";\n}\n\n/** The {@link ColorAdjustmentEffect} spec: its parameters, defaults and ranges. */\nexport const colorAdjustmentSpec = defineEffect({\n type: \"colorAdjustment\",\n group: \"color\",\n neutral: { contrast: 1, saturation: 1, temperature: 0 },\n // Every field is optional; `default` is what an absent one means.\n params: {\n /** −1…1, additive. */\n brightness: param.number({ default: 0, optional: true, min: -1, max: 1, control: \"slider\", inline: true }),\n /** 0…2, multiplicative around mid-grey. */\n contrast: param.number({ default: 1, optional: true, min: 0, max: 2, control: \"slider\" }),\n /** 0…3, multiplicative. */\n saturation: param.number({ default: 1, optional: true, min: 0, max: 3, control: \"slider\" }),\n /** Hue rotation in degrees. */\n hue: param.number({ default: 0, optional: true, unit: \"deg\", control: \"hue\" }),\n /** −1…1, saturation weighted toward muted colours. */\n vibrance: param.number({ default: 0, optional: true, min: -1, max: 1, control: \"slider\" }),\n /** −1…1, lifts or crushes the dark end. */\n shadows: param.number({ default: 0, optional: true, min: -1, max: 1, control: \"slider\" }),\n /** −1…1, lifts or crushes the bright end. */\n highlights: param.number({ default: 0, optional: true, min: -1, max: 1, control: \"slider\" }),\n /** −1…1, cool to warm. */\n temperature: param.number({ default: 0, optional: true, min: -1, max: 1, control: \"slider\" }),\n /** −1…1, green to magenta. */\n tint: param.number({ default: 0, optional: true, min: -1, max: 1, control: \"slider\", label: \"tintAmount\" }),\n },\n});\n\nexport const colorAdjustmentEffect: EffectData<ColorAdjustmentEffect> = effectDataOf(colorAdjustmentSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Per-channel spatial offset — the red/green/blue planes pulled apart along\n * independent vectors.\n *\n * Where `chromaticAberration` models a *lens*, so its fringing is symmetric and\n * driven by one distance and angle, this is the digital-artefact version: each\n * channel is displaced wherever you point it, including all three differently.\n * That freedom is what makes it the RGB-tear component of a glitch, and it is\n * why the two effects coexist rather than one subsuming the other.\n *\n * Offsets are in px and scale with the node, like every other px option.\n */\nexport interface RgbShiftEffect extends ModedEffect, EffectFields<typeof rgbShiftSpec.params> {\n type: \"rgbShift\";\n}\n\n/** The {@link RgbShiftEffect} spec: its parameters, defaults and ranges. */\nexport const rgbShiftSpec = defineEffect({\n type: \"rgbShift\",\n group: \"glitch\",\n // Samples each channel at a different position.\n surface: \"shader\",\n neutral: { red: { x: 0, y: 0 }, green: { x: 0, y: 0 }, blue: { x: 0, y: 0 } },\n params: {\n /** Red plane offset in px. */\n red: param.vec2({ default: { x: 4, y: 0 }, unit: \"px\", label: \"redOffset\" }),\n /** Green plane offset in px. */\n green: param.vec2({ default: { x: 0, y: 0 }, unit: \"px\", label: \"greenOffset\" }),\n /** Blue plane offset in px. */\n blue: param.vec2({ default: { x: -4, y: 0 }, unit: \"px\", label: \"blueOffset\" }),\n },\n});\n\nexport const rgbShiftEffect: EffectData<RgbShiftEffect> = effectDataOf(rgbShiftSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * CRT scanlines — periodic dark bands across the content.\n *\n * `offset` scrolls the band pattern; animating it past `spacing` produces the\n * slow vertical roll of a mistuned display, and it wraps, so a linear tween of\n * `offset` loops seamlessly.\n */\nexport interface ScanlinesEffect extends ModedEffect, EffectFields<typeof scanlinesSpec.params> {\n type: \"scanlines\";\n}\n\n/** The {@link ScanlinesEffect} spec: its parameters, defaults and ranges. */\nexport const scanlinesSpec = defineEffect({\n type: \"scanlines\",\n group: \"stylize\",\n // The band a pixel falls in depends on its position.\n surface: \"shader\",\n scalar: \"darkness\",\n neutral: { darkness: 0 },\n params: {\n /** Distance between band centres in px. */\n spacing: param.number({ default: 4, min: 1, unit: \"px\", order: 1 }),\n /** 0–1 share of each period the dark band covers. */\n thickness: param.number({ default: 0.5, min: 0, max: 1, control: \"slider\", order: 2 }),\n /** 0–1 how far the bands darken. */\n darkness: param.number({ default: 0.5, min: 0, max: 1, control: \"slider\", inline: true, order: 0 }),\n /** Band offset in px — animate to roll the pattern; it wraps. */\n offset: param.number({ default: 0, unit: \"px\", order: 3 }),\n /** Band angle in degrees; 0 = horizontal. */\n angle: param.number({ default: 0, unit: \"deg\", control: \"angle\", order: 4 }),\n },\n});\n\nexport const scanlinesEffect: EffectData<ScanlinesEffect> = effectDataOf(scanlinesSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Datamosh-style tearing: the content is cut into bands and each band is\n * displaced by a random amount.\n *\n * `density` is what separates this from noise — only that fraction of bands\n * move at all, so the image stays readable and the tear reads as a fault rather\n * than as static. Turn it to 1 and every band shifts.\n *\n * The displacement is a pure function of the band index and `seed`, so a frame\n * always re-renders identically. Animate `seed` (in whole steps) to make the\n * glitch jump between distinct states rather than sliding smoothly, which is\n * what makes it read as digital.\n */\nexport interface BlockDisplaceEffect extends ModedEffect, EffectFields<typeof blockDisplaceSpec.params> {\n type: \"blockDisplace\";\n}\n\n/** The {@link BlockDisplaceEffect} spec: its parameters, defaults and ranges. */\nexport const blockDisplaceSpec = defineEffect({\n type: \"blockDisplace\",\n group: \"glitch\",\n // Resamples the source at a displaced position.\n surface: \"shader\",\n scalar: \"amount\",\n neutral: { amount: 0 },\n params: {\n /** Maximum displacement in px. */\n amount: param.number({ default: 20, min: 0, unit: \"px\", inline: true }),\n /** Band thickness in px. */\n size: param.number({ default: 16, min: 1, unit: \"px\", label: \"bandSize\" }),\n /** 0–1 fraction of bands that move at all. */\n density: param.number({ default: 0.3, min: 0, max: 1, control: \"slider\" }),\n /** Random field offset — step it to jump between glitch states. */\n seed: param.number({ default: 0, step: 1 }),\n /** Which way bands slide. */\n axis: param.axis({ default: \"x\", label: \"direction\", optionsLabel: \"effectAxis\" }),\n },\n});\n\nexport const blockDisplaceEffect: EffectData<BlockDisplaceEffect> = effectDataOf(blockDisplaceSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * A fixed hardware palette to snap colours to.\n *\n * - `'none'` — no palette; quantize each channel to `bits` instead.\n * - `'gameboy'` — the DMG's four greens.\n * - `'cga'` — IBM CGA palette 1 high-intensity (black, cyan, magenta, white).\n * - `'nes'` — a representative 16-colour cut of the NES master palette.\n */\nexport type BitCrushPalette = \"none\" | \"gameboy\" | \"cga\" | \"nes\";\n\n/**\n * Colour-depth reduction: either quantize each channel to `bits`, or snap every\n * pixel to its nearest entry in a fixed hardware palette.\n *\n * The distinction from `posterize` and `dither` is *which* colours survive.\n * Posterize keeps an evenly-spaced grid per channel; this can instead force an\n * arbitrary, uneven, historically-specific set — which is what actually makes\n * something look like a Game Boy rather than merely low-colour.\n *\n * Pairs naturally with `dither`: quantize here, and let an ordered dither carry\n * the error so gradients survive the palette cut.\n */\nexport interface BitCrushEffect extends ModedEffect, EffectFields<typeof bitCrushSpec.params> {\n type: \"bitCrush\";\n}\n\n/** The {@link BitCrushEffect} spec: its parameters, defaults and ranges. */\nexport const bitCrushSpec = defineEffect({\n type: \"bitCrush\",\n group: \"stylize\",\n // A palette search is per-pixel non-linear; no LUT colour filter in this build.\n surface: \"shader\",\n scalar: \"bits\",\n neutral: { amount: 0 },\n params: {\n /** Bits per channel when `palette` is `'none'`, 1–8. */\n bits: param.number({ default: 3, min: 1, max: 8, step: 1, inline: true }),\n /** Fixed hardware palette to snap to. A halfway palette is meaningless, so it cuts. */\n palette: param.choice([\"none\", \"gameboy\", \"cga\", \"nes\"] satisfies BitCrushPalette[], { default: \"none\", optionsLabel: \"bitCrushPalette\" }),\n /** 0–1 blend between original and crushed. */\n amount: param.number({ default: 1, min: 0, max: 1, control: \"slider\" }),\n },\n});\n\nexport const bitCrushEffect: EffectData<BitCrushEffect> = effectDataOf(bitCrushSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Anamorphic glare — a bright pass smeared along one axis and screened back on.\n *\n * Where `bloom` spreads light equally in all directions, this spreads it along\n * `angle` only. That asymmetry is the entire anamorphic look: the horizontal\n * flare a wide lens throws off a highlight, rather than a halo around it.\n */\nexport interface StreakEffect extends ModedEffect, EffectFields<typeof streakSpec.params> {\n type: \"streak\";\n}\n\n/** The {@link StreakEffect} spec: its parameters, defaults and ranges. */\nexport const streakSpec = defineEffect({\n type: \"streak\",\n group: \"light\",\n // An anisotropic blur of a colour-matrix bright pass — all ImageFilter work.\n scalar: \"intensity\",\n neutral: { intensity: 0 },\n params: {\n /** Additive multiplier for the streak pass. */\n intensity: param.number({ default: 1, min: 0, max: 3, control: \"slider\", inline: true }),\n /** 0–1 luminance cutoff. */\n threshold: param.number({ default: 0.7, min: 0, max: 1, control: \"slider\" }),\n /** Smear length in pixels. */\n length: param.number({ default: 120, min: 0, unit: \"px\" }),\n /** Smear axis in degrees; 0 = horizontal. */\n angle: param.number({ default: 0, unit: \"deg\", control: \"angle\" }),\n },\n});\n\nexport const streakEffect: EffectData<StreakEffect> = effectDataOf(streakSpec);\n", "import { lerpNumber } from \"@/tween/lerp\";\nimport { lerpColor } from \"@/attributes/shape/fill/lerp\";\nimport { BlendModes } from \"@/attributes/shape/fill/blend\";\nimport type { Color } from \"@/attributes/shape/fill/color/parser\";\nimport type { ModedEffect, EffectData } from \"../effect-data\";\nimport { resolveEffectColor, sameEffectColor } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * What the glow reads to decide how much a pixel glows.\n *\n * `\"luminance\"` is the photographic reading — bright pixels bleed, dark ones\n * don't, and {@link GlowEffect.threshold} sets where the cut falls.\n * `\"alpha\"` ignores colour entirely and glows every opaque pixel equally, which\n * is what you want when the glow is a halo around a shape rather than light\n * escaping an image.\n */\nexport type GlowChannel = \"luminance\" | \"alpha\";\n\n/**\n * What the glow is coloured with.\n *\n * - `\"none\"` keeps the source's own colours, scaled by intensity.\n * - `\"solid\"` paints the whole glow one {@link GlowEffect.color}.\n * - `\"ramp\"` maps glow strength through {@link GlowEffect.colors} /\n * {@link GlowEffect.stops}, which is what makes a glow read as heat, neon or\n * an aurora rather than as a brighter copy of the layer.\n */\nexport type GlowTint = \"none\" | \"solid\" | \"ramp\";\n\n/**\n * How the ramp repeats once {@link GlowEffect.cycles} takes it past one pass.\n *\n * The two names are the usual gradient tile modes, and mean what they mean there:\n * `\"repeat\"` restarts at the first stop (a hard seam between last and first),\n * `\"mirror\"` walks back down through the stops (seamless, at the cost of\n * halving the apparent frequency).\n */\nexport type GlowLoopStyle = \"mirror\" | \"repeat\";\n\n/** Where the source layer sits relative to the glow it produced. */\nexport type GlowOriginal = \"behind\" | \"front\" | \"hidden\";\n\n/**\n * A glow: the bright (or opaque) parts of a layer, spread outward and composited\n * back — optionally recoloured through a ramp keyed on how strongly each pixel\n * glows.\n *\n * The difference from `bloom`, which is otherwise the same three numbers: bloom\n * is a `\"filter\"` effect and is therefore bounded by the node's own rect, and it\n * can only screen its bright-pass back. This spreads past the box, chooses its\n * compositing, and can be coloured. See {@link EffectData.surface} below.\n */\nexport interface GlowEffect extends ModedEffect, EffectFields<typeof glowSpec.params> {\n type: \"glow\";\n}\n\n// White at the core falling to a warm amber.\nconst GLOW_RAMP_COLORS: Color[] = [\"white\", \"#ffa640\"];\nconst GLOW_RAMP_STOPS: number[] = [0, 1];\n\n/** The {@link GlowEffect} spec: its parameters, defaults and ranges. */\nexport const glowSpec = defineEffect({\n type: \"glow\",\n group: \"light\",\n surface: \"shader\",\n scalar: \"intensity\",\n // `intensity: 0` alone is not enough: `original: 'hidden'` would carry over\n // from the effect being faded and erase the node.\n neutral: { intensity: 0, original: \"behind\" },\n // Kept from the hand-written lerp: ramps of different lengths snap the whole\n // glow, not only the ramp, at the midpoint.\n lerp: <G extends { colors: Color[] }>(from: G, to: G, t: number, derived: (a: G, b: G, t: number) => G) =>\n from.colors.length !== to.colors.length ? { ...(t < 0.5 ? from : to) } : derived(from, to, t),\n params: {\n /** What decides a pixel's glow strength. */\n channel: param.choice([\"luminance\", \"alpha\"] satisfies GlowChannel[], { default: \"luminance\", control: \"segmented\", optionsLabel: \"glowChannel\", order: 9 }),\n /** 0-1 luminance cutoff; read only when `channel` is `'luminance'`. */\n threshold: param.number({ default: 0.5, min: 0, max: 1, control: \"slider\", order: 0 }),\n /** Spread distance in pixels. */\n radius: param.number({ default: 25, min: 0, unit: \"px\", order: 1 }),\n /** Dilation applied before the blur, in pixels — gives the glow a solid core. */\n spread: param.number({ default: 0, min: 0, unit: \"px\", order: 2 }),\n /** Additive multiplier for the glow pass. */\n intensity: param.number({ default: 1, min: 0, max: 3, control: \"slider\", inline: true, order: 3 }),\n /** Which way the glow spreads; `'x'`/`'y'` give anamorphic streaks. */\n axis: param.axis({ default: \"both\", control: \"segmented\", optionsLabel: \"effectAxis\", order: 10 }),\n /** Where the source layer sits relative to the glow. */\n original: param.choice([\"behind\", \"front\", \"hidden\"] satisfies GlowOriginal[], { default: \"behind\", control: \"segmented\", optionsLabel: \"glowOriginal\", order: 11 }),\n /** How the glow merges with the layer. */\n blend: param.choice(BlendModes, { default: \"screen\", optionsLabel: \"blendMode\", order: 12 }),\n /** What the glow is coloured with. */\n tint: param.choice([\"none\", \"solid\", \"ramp\"] satisfies GlowTint[], { default: \"none\", control: \"segmented\", optionsLabel: \"glowTint\", order: 4 }),\n /** The glow's colour when `tint` is `'solid'`. */\n color: param.color({ default: \"white\", order: 5 }),\n /**\n * Ramp colours when `tint` is `'ramp'`, parallel to `stops`.\n *\n * Componentwise when both ramps have the same number of stops. When the\n * counts differ there is no correspondence to interpolate along (stop 2\n * of 3 and stop 2 of 5 are not the same place), so it snaps at the\n * midpoint: a ramp that silently gained stops mid-tween reads as a bug.\n */\n colors: param.of<Color[]>()({\n kind: \"colors\",\n default: GLOW_RAMP_COLORS,\n hidden: true,\n order: 13,\n lerp: (a, b, t) => (a.length !== b.length ? (t < 0.5 ? a : b) : a.map((c, i) => lerpColor(resolveEffectColor(c), resolveEffectColor(b[i]), t))),\n equals: (a, b) => a.length === b.length && a.every((c, i) => sameEffectColor(c, b[i])),\n }),\n /** Each ramp colour's position, 0-1 ascending (evenly spaced when absent). */\n stops: param.of<number[]>()({\n kind: \"numbers\",\n default: GLOW_RAMP_STOPS,\n hidden: true,\n order: 14,\n lerp: (a, b, t, from, to) => ((from.colors as Color[]).length !== (to.colors as Color[]).length\n ? (t < 0.5 ? a : b)\n : a.map((s, i) => lerpNumber(s, b[i] ?? s, t))),\n equals: (a, b) => a.length === b.length && a.every((s, i) => s === b[i]),\n }),\n /** How the ramp repeats past one pass. */\n loopStyle: param.choice([\"mirror\", \"repeat\"] satisfies GlowLoopStyle[], { default: \"mirror\", control: \"segmented\", optionsLabel: \"glowLoopStyle\", order: 6 }),\n /** Ramp traversals across the glow's strength range. */\n cycles: param.number({ default: 1, min: 1, max: 10, step: 0.1, order: 7 }),\n /** Offset along the ramp in degrees of one cycle; animate to move colour. */\n phase: param.number({ default: 0, unit: \"deg\", control: \"angle\", order: 8 }),\n },\n});\n\nexport const glowEffect: EffectData<GlowEffect> = effectDataOf(glowSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Kuwahara filter — the painterly one.\n *\n * Each pixel looks at four overlapping quadrant windows and takes the mean of\n * whichever is *flattest*. Averaging within a region but never across a boundary\n * is what makes it read as brushwork: flat areas smooth into strokes while edges\n * stay crisp, where a plain blur would soften both.\n *\n * Cost grows with the square of `radius` — four windows of `(radius+1)²` samples\n * each — so this is the most expensive effect in the set by a wide margin.\n */\nexport interface OilPaintEffect extends ModedEffect, EffectFields<typeof oilPaintSpec.params> {\n type: \"oilPaint\";\n}\n\n/** The {@link OilPaintEffect} spec: its parameters, defaults and ranges. */\nexport const oilPaintSpec = defineEffect({\n type: \"oilPaint\",\n group: \"blur\",\n // Reads a large neighbourhood per pixel.\n surface: \"shader\",\n scalar: \"radius\",\n neutral: { radius: 0 },\n params: {\n /** Window radius in pixels — brush size, capped at 6. */\n radius: param.number({ default: 3, min: 0, max: 6, step: 1, unit: \"px\", label: \"brush\", inline: true }),\n },\n});\n\nexport const oilPaintEffect: EffectData<OilPaintEffect> = effectDataOf(oilPaintSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { CENTER, defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * How the wave's crests are laid out.\n *\n * - `\"linear\"` — parallel crests running across the node, travelling along\n * `angle`. Flags, banners, wobbling type, heat shimmer.\n * - `\"radial\"` — concentric rings expanding from `center`. The pond-ripple /\n * drop-impact look, and the one that reads as *something happened here*.\n */\nexport type WaveShape = \"linear\" | \"radial\";\n\n/**\n * Sine displacement — the procedural warp that needs no asset.\n *\n * Pixels are resampled at a position offset by a sine of their own coordinate,\n * so the content ripples without anything being generated or loaded. For an\n * arbitrary warp driven by an image, see `displace`.\n *\n * `phase` is in degrees and the sine wraps, so a **linear tween of `phase` over\n * 360 loops seamlessly** — that is how you make the wave travel. Animating it is\n * the whole point; a static wave reads as a distortion rather than as motion.\n */\nexport interface WaveEffect extends ModedEffect, EffectFields<typeof waveSpec.params> {\n type: \"wave\";\n}\n\n/** The {@link WaveEffect} spec: its parameters, defaults and ranges. */\nexport const waveSpec = defineEffect({\n type: \"wave\",\n group: \"distort\",\n // Resamples the source at an offset position.\n surface: \"shader\",\n scalar: \"amplitude\",\n neutral: { amplitude: 0 },\n params: {\n /**\n * Peak displacement in px per axis. A bare number means the Y axis only:\n * a wave that displaces along its own direction of travel just smears.\n */\n amplitude: param.vec2({ default: 20, fromNumber: \"y\", unit: \"px\" }),\n /** Distance between crests in px. */\n wavelength: param.number({ default: 120, min: 1, unit: \"px\", inline: true }),\n /** Phase in degrees; tween over 360 for one seamless loop. */\n phase: param.number({ default: 0, step: 1, unit: \"deg\" }),\n /** Parallel bands or concentric rings. */\n shape: param.choice([\"linear\", \"radial\"] satisfies WaveShape[], { default: \"linear\", label: \"crestShape\", optionsLabel: \"waveShape\" }),\n /** Direction the crests advance along, in degrees. `'linear'` only. */\n angle: param.number({ default: 0, unit: \"deg\", control: \"angle\" }),\n /** Ring origin in 0–1 layer coords. `'radial'` only. */\n center: param.vec2({ default: CENTER, min: 0, max: 1, step: 0.01, unit: \"normalized\", label: \"ringCenter\" }),\n },\n});\n\nexport const waveEffect: EffectData<WaveEffect> = effectDataOf(waveSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { CENTER, defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Twirl / swirl — the content is rotated about `center` by an amount that falls\n * off with distance, so the middle spins and the rim stays put.\n *\n * The falloff is what separates this from simply rotating the node: rotation is\n * rigid, this shears. Everything inside `radius` twists by a fraction of `angle`\n * that reaches full strength at the centre and zero at the rim, which is what\n * makes it read as a vortex rather than a transform.\n *\n * Animating `angle` past a full turn keeps winding — there is no wrap point, so\n * a long tween produces an ever-tightening spiral.\n */\nexport interface TwirlEffect extends ModedEffect, EffectFields<typeof twirlSpec.params> {\n type: \"twirl\";\n}\n\n/** The {@link TwirlEffect} spec: its parameters, defaults and ranges. */\nexport const twirlSpec = defineEffect({\n type: \"twirl\",\n group: \"distort\",\n // Resamples the source at a rotated position.\n surface: \"shader\",\n scalar: \"angle\",\n neutral: { angle: 0 },\n params: {\n /** Rotation at the centre in degrees. */\n angle: param.number({ default: 180, unit: \"deg\", label: \"twist\", inline: true }),\n /** 0–1 radius of influence (1 = the whole node). */\n radius: param.number({ default: 1, min: 0, max: 1, control: \"slider\", label: \"reach\" }),\n /** Vortex centre in 0–1 layer coords. */\n center: param.vec2({ default: CENTER, min: 0, max: 1, step: 0.01, unit: \"normalized\", label: \"vortexCenter\" }),\n },\n});\n\nexport const twirlEffect: EffectData<TwirlEffect> = effectDataOf(twirlSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { CENTER, defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * How the blur ramp is laid out across the node.\n *\n * - `\"linear\"` — the ramp runs along `angle`, so the blur builds from one edge\n * toward the other. The gradient/fade-to-blur strip under a toolbar or over\n * the bottom of a hero image.\n * - `\"radial\"` — the ramp runs outward from `center`, so the middle stays sharp\n * and the surround softens. A cheap depth-of-field / tilt-shift.\n */\nexport type ProgressiveBlurShape = \"linear\" | \"radial\";\n\n/**\n * Blur whose radius *ramps* across the node instead of being uniform.\n *\n * A plain blur is a constant; this interpolates from `startRadius` to `radius`\n * between `start` and `end` along the ramp, which is what makes content appear\n * to dissolve into softness rather than simply being out of focus.\n *\n * **In `mode: 'backdrop'` this is the frosted panel with a falloff** — the\n * translucent bar whose blur fades out at its edge instead of stopping at a hard\n * line. That is the case a plain backdrop blur cannot express, and the reason\n * this effect exists.\n *\n * Cost scales with `samples`, which are spent on the *widest* part of the ramp;\n * pixels below `start` return the source untouched without sampling at all.\n */\nexport interface ProgressiveBlurEffect extends ModedEffect, EffectFields<typeof progressiveBlurSpec.params> {\n type: \"progressiveBlur\";\n}\n\n/** The {@link ProgressiveBlurEffect} spec: its parameters, defaults and ranges. */\nexport const progressiveBlurSpec = defineEffect({\n type: \"progressiveBlur\",\n group: \"blur\",\n // Averages a neighbourhood whose extent varies per pixel.\n surface: \"shader\",\n scalar: \"radius\",\n neutral: { radius: 0 },\n params: {\n /** Blur spread in px at the far end of the ramp. */\n radius: param.number({ default: 24, min: 0, unit: \"px\", label: \"endBlur\", order: 2 }),\n /** Blur spread in px at the near end of the ramp (0: sharp, what it did before the field existed). */\n startRadius: param.number({ default: 0, min: 0, unit: \"px\", label: \"startBlur\", order: 1 }),\n /** Ramp layout. */\n shape: param.choice([\"linear\", \"radial\"] satisfies ProgressiveBlurShape[], { default: \"linear\", control: \"segmented\", label: \"rampShape\", optionsLabel: \"rampShape\", order: 0 }),\n /** 0–1 where the blur starts building. */\n start: param.number({ default: 0, min: -0.5, max: 1.5, control: \"slider\", label: \"rampStart\", order: 3 }),\n /** 0–1 where it reaches `radius`. */\n end: param.number({ default: 1, min: -0.5, max: 1.5, control: \"slider\", label: \"rampEnd\", order: 4 }),\n /** Ramp direction in degrees; 0 = left-to-right, 90 = downward. */\n angle: param.number({ default: 90, unit: \"deg\", control: \"angle\", order: 5 }),\n /** Ramp origin in 0–1 layer coords. `'radial'` only. */\n center: param.vec2({ default: CENTER, min: 0, max: 1, step: 0.01, unit: \"normalized\", order: 6 }),\n /** Taps averaged at full radius, 2–32. A fractional count would just round, so it snaps. */\n samples: param.number({ default: 20, min: 2, max: 32, step: 1, lerp: \"step\", hidden: true, order: 7, initial: 16 }),\n },\n});\n\nexport const progressiveBlurEffect: EffectData<ProgressiveBlurEffect> = effectDataOf(progressiveBlurSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { CENTER, defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Kaleidoscope — the content is folded into `segments` mirrored wedges around\n * `center`, so one slice of the source is repeated around a circle.\n *\n * Only the wedge starting at `angle` is ever read; every other segment is that\n * same wedge reflected or rotated into place. That is why rotating `angle`\n * animates so well — the pattern stays locked while *different source material*\n * sweeps through the wedge, which is the effect people actually want and is not\n * the same as rotating the node.\n *\n * `segments` counts the mirrored pairs, so 6 gives the familiar snowflake. It is\n * discrete: a tween snaps rather than passing through a fractional fold, which\n * would tear.\n */\nexport interface KaleidoscopeEffect extends ModedEffect, EffectFields<typeof kaleidoscopeSpec.params> {\n type: \"kaleidoscope\";\n}\n\n/** The {@link KaleidoscopeEffect} spec: its parameters, defaults and ranges. */\nexport const kaleidoscopeSpec = defineEffect({\n type: \"kaleidoscope\",\n group: \"distort\",\n // Resamples the source at a reflected position.\n surface: \"shader\",\n scalar: \"segments\",\n // `segments` is discrete, so the neutral is the continuous blend.\n neutral: { amount: 0 },\n params: {\n /**\n * Number of mirrored wedges; below 2 is a no-op. Discrete: a fractional\n * wedge cannot tile the circle, so it rounds and a tween snaps.\n */\n segments: param.number({ default: 6, normalize: Math.round, min: 2, max: 64, step: 1, lerp: \"step\", inline: true }),\n /** Rotation of the pattern in degrees — animate to sweep the source. */\n angle: param.number({ default: 0, step: 1, unit: \"deg\" }),\n /** Fold origin in 0–1 layer coords. */\n center: param.vec2({ default: CENTER, min: 0, max: 1, step: 0.01, unit: \"normalized\", label: \"foldCenter\" }),\n /** Radial offset of the sampled wedge. */\n offset: param.number({ default: 0, min: -1, max: 1, control: \"slider\", label: \"wedgeOffset\" }),\n /** 0–1 blend from the original to the folded pattern. */\n amount: param.number({ default: 1, min: 0, max: 1, control: \"slider\" }),\n },\n});\n\nexport const kaleidoscopeEffect: EffectData<KaleidoscopeEffect> = effectDataOf(kaleidoscopeSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * Figma's Glass: the backdrop seen through a slab of glass whose edge curves\n * down to the node's outline — refracted, split into a spectrum at the curve,\n * optionally frosted, with a rim of light.\n *\n * The fields are Figma's own, in Figma's units, so values copied from a Figma\n * file render the same: `depth` and `frost` are px, `lightAngle` is degrees\n * clockwise from the top, and the rest are 0–100 amounts.\n *\n * Glass only has meaning on the **backdrop** — there is nothing to refract in a\n * node's own paint — so `Effects.glass()` defaults `mode` to `'backdrop'` and the\n * renderer's handler serves that target only.\n */\nexport interface GlassEffect extends ModedEffect, EffectFields<typeof glassSpec.params> {\n type: \"glass\";\n}\n\n/** The {@link GlassEffect} spec: its parameters, defaults and ranges. */\nexport const glassSpec = defineEffect({\n type: \"glass\",\n group: \"light\",\n // Resamples the backdrop through a bevel, three times per fragment.\n surface: \"shader\",\n scalar: \"refraction\",\n defaultMode: \"backdrop\",\n onlyOn: \"backdrop\",\n // No curved edge means nothing to refract or light along.\n neutral: { depth: 0 },\n params: {\n /** Where the light comes from, in degrees clockwise from the top. */\n lightAngle: param.number({ default: -45, unit: \"deg\", control: \"angle\", zero: \"top\" }),\n /** 0–100 brightness of the light. */\n lightIntensity: param.number({ default: 80, min: 0, max: 100, unit: \"percent\" }),\n /** 0–100 how strongly the curved edge bends the backdrop. */\n refraction: param.number({ default: 80, min: 0, max: 100, step: 1, control: \"slider\", inline: true }),\n /** How far the curved edge reaches in from the outline, px. */\n depth: param.number({ default: 20, min: 0, max: 100, step: 1, unit: \"px\", control: \"slider\" }),\n /** 0–100 spectral split along the curved edge. */\n dispersion: param.number({ default: 50, min: 0, max: 100, step: 1, control: \"slider\" }),\n /** Backdrop blur radius, px. */\n frost: param.number({ default: 4, min: 0, max: 100, step: 1, unit: \"px\", control: \"slider\" }),\n /** 0–100 how far the projected light spreads in from the rim. */\n splay: param.number({ default: 0, min: 0, max: 100, step: 1, control: \"slider\" }),\n },\n});\n\nexport const glassEffect: EffectData<GlassEffect> = effectDataOf(glassSpec);\n", "import type { ModedEffect, EffectData } from \"../effect-data\";\nimport { defineEffect, effectDataOf, param, type EffectFields } from \"../spec\";\n\n/**\n * A 3D colour lookup table — the `.cube` a colourist hands you.\n *\n * The one adjustment in the roster that is not a formula. Everything else here\n * says what to *do* to a colour; a LUT is a measured cube of what each colour\n * should *become*, which is how film-stock and print emulations are shipped and\n * why no combination of curves and matrices substitutes for one. Applying it is\n * a trilinear lookup per pixel.\n *\n * A node effect rather than a media-only adjustment, deliberately: everything\n * outside {@link NonFilterEffect} is automatically an `EffectAdjustment` too, so\n * one implementation grades an image fill's own pixels *and* a whole node —\n * which is what lets a graded photo and the graded titles over it be the same\n * look rather than two things kept in step by hand.\n *\n * ## The table\n *\n * Flat RGB triples, **red-fastest** — index `((b · size) + g) · size + r`, times\n * three — which is the order a `.cube` file writes its lines in, so a parser\n * fills this with no transposition to get wrong.\n *\n * It is a `Float32Array` and it is treated as **immutable and shared**: `equals`\n * compares it by reference and `lerp` hard-cuts it, exactly as `texture` does\n * with its `src`. That is not laziness. A 33³ cube is 107,811 floats; comparing\n * it per frame would cost more than the draw, interpolating it would allocate a\n * second cube per frame, and the renderer's GPU upload is cached against this\n * very identity. Hand the same array back each frame and a LUT costs one texture\n * upload for the life of the scene; build a fresh one per frame and it costs one\n * per frame.\n *\n * Cross-fading two *different* LUTs is therefore a cut, not a blend. That is the\n * honest answer — there is no meaningful midpoint between two measured cubes —\n * and the way to dissolve between looks is two fills, or {@link amount}.\n */\nexport interface LutEffect extends ModedEffect, EffectFields<typeof lutSpec.params> {\n type: \"lut\";\n}\n\n/** The {@link LutEffect} spec: its parameters, defaults and ranges. */\nexport const lutSpec = defineEffect({\n type: \"lut\",\n group: \"color\",\n // It samples a second texture at a coordinate derived from the source's own\n // colour, so it needs the source as a shader it can read — not a colour\n // matrix it can compose.\n surface: \"shader\",\n // A LUT's neutral is its mix, not its table.\n neutral: { amount: 0 },\n params: {\n /** The cube: flat RGB triples, red-fastest. Compared by reference, cut by `lerp`. */\n table: param.of<Float32Array>()({ kind: \"table\", required: true, hidden: true }),\n /**\n * Entries per axis. Cuts with the table: a table read at the wrong stride\n * is not a wrong colour, it is garbage.\n */\n size: param.number({ required: true, min: 2, step: 1, lerp: \"step\", hidden: true }),\n /** 0–1 mix against the ungraded colour. */\n amount: param.number({ default: 1, min: 0, max: 1, control: \"slider\", inline: true }),\n },\n});\n\nexport const lutEffect: EffectData<LutEffect> = effectDataOf(lutSpec);\n", "import { NodeEffect } from \"./union\";\n\nimport { blurEffect, blurSpec } from \"./implementations/blur\";\nimport { directionalBlurEffect, directionalBlurSpec } from \"./implementations/directional-blur\";\nimport { grayscaleEffect, grayscaleSpec } from \"./implementations/grayscale\";\nimport { pixelateEffect, pixelateSpec } from \"./implementations/pixelate\";\nimport { bulgeEffect, bulgeSpec } from \"./implementations/bulge\";\nimport { magnifyEffect, magnifySpec } from \"./implementations/magnify\";\nimport { bloomEffect, bloomSpec } from \"./implementations/bloom\";\nimport { vintageEffect, vintageSpec } from \"./implementations/vintage\";\nimport { chromaticAberrationEffect, chromaticAberrationSpec } from \"./implementations/chromatic-aberration\";\nimport { invertEffect, invertSpec } from \"./implementations/invert\";\nimport { scatterEffect, scatterSpec } from \"./implementations/scatter\";\nimport { posterizeEffect, posterizeSpec } from \"./implementations/posterize\";\nimport { motionBlurEffect, motionBlurSpec } from \"./implementations/motion-blur\";\nimport { shaderEffect, shaderSpec } from \"./implementations/shader\";\nimport { outlineEffect, outlineSpec } from \"./implementations/outline\";\nimport { dropShadowEffect, dropShadowSpec } from \"./implementations/drop-shadow\";\nimport { vignetteEffect, vignetteSpec } from \"./implementations/vignette\";\nimport { grainEffect, grainSpec } from \"./implementations/grain\";\nimport { sharpenEffect, sharpenSpec } from \"./implementations/sharpen\";\nimport { edgesEffect, edgesSpec } from \"./implementations/edges\";\nimport { thresholdEffect, thresholdSpec } from \"./implementations/threshold\";\nimport { radialBlurEffect, radialBlurSpec } from \"./implementations/radial-blur\";\nimport { halftoneEffect, halftoneSpec } from \"./implementations/halftone\";\nimport { ditherEffect, ditherSpec } from \"./implementations/dither\";\nimport { duotoneEffect, duotoneSpec } from \"./implementations/duotone\";\nimport { curvesEffect, curvesSpec } from \"./implementations/curves\";\nimport { colorAdjustmentEffect, colorAdjustmentSpec } from \"./implementations/color-adjustment\";\nimport { rgbShiftEffect, rgbShiftSpec } from \"./implementations/rgb-shift\";\nimport { scanlinesEffect, scanlinesSpec } from \"./implementations/scanlines\";\nimport { blockDisplaceEffect, blockDisplaceSpec } from \"./implementations/block-displace\";\nimport { bitCrushEffect, bitCrushSpec } from \"./implementations/bit-crush\";\nimport { asciiEffect, asciiSpec } from \"./implementations/ascii\";\nimport { streakEffect, streakSpec } from \"./implementations/streak\";\nimport { glowEffect, glowSpec } from \"./implementations/glow\";\nimport { oilPaintEffect, oilPaintSpec } from \"./implementations/oil-paint\";\nimport { waveEffect, waveSpec } from \"./implementations/wave\";\nimport { twirlEffect, twirlSpec } from \"./implementations/twirl\";\nimport { progressiveBlurEffect, progressiveBlurSpec } from \"./implementations/progressive-blur\";\nimport { kaleidoscopeEffect, kaleidoscopeSpec } from \"./implementations/kaleidoscope\";\nimport { glassEffect, glassSpec } from \"./implementations/glass\";\nimport { lutEffect, lutSpec } from \"./implementations/lut\";\nimport { EffectData, EffectSurface, EFFECT_OPTION_KEYS } from \"./effect-data\";\nimport { describeSpec, type EffectDescriptor, type EffectSpec } from \"./spec\";\nimport type { AssetScope } from \"@/assets/scope\";\n\n\n/**\n * Every built-in effect: its spec (the parameters a host and the renderers\n * read) and the `EffectData` derived from it, in registration order.\n */\nconst BUILT_INS: readonly (readonly [EffectSpec, EffectData<any>])[] = [\n [blurSpec, blurEffect],\n [directionalBlurSpec, directionalBlurEffect],\n [grayscaleSpec, grayscaleEffect],\n [pixelateSpec, pixelateEffect],\n [bulgeSpec, bulgeEffect],\n [magnifySpec, magnifyEffect],\n [bloomSpec, bloomEffect],\n [vintageSpec, vintageEffect],\n [chromaticAberrationSpec, chromaticAberrationEffect],\n [invertSpec, invertEffect],\n [scatterSpec, scatterEffect],\n [posterizeSpec, posterizeEffect],\n [motionBlurSpec, motionBlurEffect],\n [shaderSpec, shaderEffect],\n [outlineSpec, outlineEffect],\n [dropShadowSpec, dropShadowEffect],\n [vignetteSpec, vignetteEffect],\n [grainSpec, grainEffect],\n [sharpenSpec, sharpenEffect],\n [edgesSpec, edgesEffect],\n [thresholdSpec, thresholdEffect],\n [radialBlurSpec, radialBlurEffect],\n [halftoneSpec, halftoneEffect],\n [ditherSpec, ditherEffect],\n [duotoneSpec, duotoneEffect],\n [curvesSpec, curvesEffect],\n [colorAdjustmentSpec, colorAdjustmentEffect],\n [rgbShiftSpec, rgbShiftEffect],\n [scanlinesSpec, scanlinesEffect],\n [blockDisplaceSpec, blockDisplaceEffect],\n [bitCrushSpec, bitCrushEffect],\n [asciiSpec, asciiEffect],\n [streakSpec, streakEffect],\n [glowSpec, glowEffect],\n [oilPaintSpec, oilPaintEffect],\n [waveSpec, waveEffect],\n [twirlSpec, twirlEffect],\n [progressiveBlurSpec, progressiveBlurEffect],\n [kaleidoscopeSpec, kaleidoscopeEffect],\n [glassSpec, glassEffect],\n [lutSpec, lutEffect],\n];\n\nconst EFFECTS = new Map<string, EffectData<NodeEffect>>(BUILT_INS.map(([spec, data]) => [spec.type, data]));\nconst SPECS = new Map<string, EffectSpec>(BUILT_INS.map(([spec]) => [spec.type, spec]));\n\nfunction dataFor(type: string): EffectData<NodeEffect> | undefined {\n return EFFECTS.get(type);\n}\n\n/**\n * Normalise one authored effect — see {@link EffectData.resolve}.\n *\n * Returns the effect untouched when its type registers no `resolve`, which is\n * every effect but one.\n */\nexport function resolveEffect(effect: NodeEffect): NodeEffect {\n const data = dataFor(effect.type);\n return data?.resolve ? data.resolve(effect) : effect;\n}\n\n/**\n * Every registered effect type, in registration order.\n *\n * The roster itself, so a contract test can sweep the whole set rather than a\n * hand-kept list that silently misses whatever was added last.\n */\nexport const effectTypes = (): string[] => [...EFFECTS.keys()];\n\n/** The spec of a built-in effect type, or `undefined`. */\nexport function effectSpec(type: string): EffectSpec | undefined {\n return SPECS.get(type);\n}\n\nconst descriptors = new Map<string, EffectDescriptor>();\n\n/**\n * A built-in effect type described for a host — its fields' kinds, defaults,\n * ranges and inspector hints, as plain JSON (see {@link EffectDescriptor}).\n * `undefined` for a type core does not know.\n */\nexport function describeEffect(type: string): EffectDescriptor | undefined {\n const spec = effectSpec(type);\n if (!spec) return undefined;\n let out = descriptors.get(spec.type);\n if (!out) descriptors.set(spec.type, (out = describeSpec(spec)));\n return structuredClone(out);\n}\n\n/** {@link describeEffect} for every built-in effect, in registration order. */\nexport function effectDescriptors(): EffectDescriptor[] {\n return [...SPECS.keys()].map((type) => describeEffect(type)!);\n}\n\n/** True when `type` has a registered `EffectData` handler. */\nexport function hasEffect(type: string): boolean {\n return dataFor(type) !== undefined;\n}\n\n/**\n * How a backend must realise `effect` — see {@link EffectSurface}. Unknown types\n * fall back to `\"filter\"`, the composable default.\n */\nexport function effectSurface(effect: NodeEffect): EffectSurface {\n const surface = dataFor(effect.type)?.surface;\n if (surface === undefined) return \"filter\";\n return typeof surface === \"function\" ? surface(effect) : surface;\n}\n\nexport function declareEffect(effect: NodeEffect, assets: AssetScope): void {\n dataFor(effect.type)?.declare?.(effect, assets);\n}\n\n/**\n * Interpolates two effects of the same type.\n *\n * The cross-cutting {@link EFFECT_OPTION_KEYS} (`mode`, `clip`) are carried here\n * for every kind, switching at the midpoint like any non-interpolable value, so\n * an effect's own `lerp` only has to describe its parameters and a new option\n * cannot be dropped by one of 45 hand-written copies.\n *\n * @internal\n */\nexport function lerpEffect(from: NodeEffect, to: NodeEffect, t: number): NodeEffect {\n if (from.type !== to.type) return t < 0.5 ? from : to;\n const data = dataFor(from.type);\n if (!data) return t < 0.5 ? from : to;\n const lerped = data.lerp(from, to, t);\n const source = t < 0.5 ? from : to;\n let out: NodeEffect | undefined;\n for (const key of EFFECT_OPTION_KEYS) {\n if (lerped[key] === source[key]) continue;\n // Copy lazily, and omit rather than write `undefined`: the equality\n // checks compare these fields directly.\n out ??= { ...lerped } as NodeEffect;\n const target = out as unknown as Record<string, unknown>;\n if (source[key] === undefined) delete target[key];\n else target[key] = source[key];\n }\n return out ?? lerped;\n}\n\n/**\n * Do two effects describe the same look? The effect's own `equals` compares its\n * parameters; the type and the cross-cutting {@link EFFECT_OPTION_KEYS} are\n * compared here for every kind.\n *\n * @internal\n */\nexport function equalsEffect(a: NodeEffect, b: NodeEffect): boolean {\n if (a.type !== b.type) return false;\n if (EFFECT_OPTION_KEYS.some((key) => a[key] !== b[key])) return false;\n const data = dataFor(a.type);\n return data ? data.equals(a, b) : a === b;\n}\n", "import { parseColor } from \"../fill/color/parser\";\nimport type { ShaderUniformRecord, ShaderUniformValue } from \"./uniforms\";\nimport type { Shader, ShaderProperty } from \"./pack\";\n\n/** Overrides for a pack's properties, by property id. */\nexport type ShaderPropertyValues = Record<string, unknown>;\n\n/** Component names a multi-part property may map, in the order they index. */\nconst COMPONENTS = [\"x\", \"y\", \"z\", \"w\"] as const;\nconst COLOR_COMPONENTS = [\"r\", \"g\", \"b\", \"a\"] as const;\n\n/**\n * Turn a pack's properties, plus any overrides, into the uniform record the\n * renderer writes.\n *\n * This is the whole job of a property: it is an *editable* value, and a uniform\n * is where that value has to end up. One property may feed several uniforms —\n * see `ShaderPropertyBase.inputs` — which is why this cannot be a rename.\n *\n * The pack's own `uniforms` are merged in first and the properties win: the\n * more specific statement of the same value takes it.\n */\nexport function resolveShaderProperties(\n pack: Shader,\n overrides?: ShaderPropertyValues,\n): ShaderUniformRecord {\n const out: ShaderUniformRecord = { ...(pack.uniforms ?? {}) };\n\n for (const [id, property] of Object.entries(pack.properties)) {\n const supplied = overrides && id in overrides ? overrides[id] : property.default;\n const parts = componentsOf(property, supplied, id, pack.name);\n if (!parts) continue;\n for (const [component, uniform] of Object.entries(property.inputs)) {\n const value = parts[component];\n if (value === undefined) {\n warn(`shader \"${pack.name}\" property \"${id}\" has no \"${component}\" to write to \"${uniform}\".`);\n continue;\n }\n out[uniform] = value;\n }\n }\n\n if (overrides) {\n for (const id of Object.keys(overrides)) {\n if (id in pack.properties) continue;\n warn(`shader \"${pack.name}\" has no property \"${id}\"; the override is ignored.`);\n }\n }\n\n return out;\n}\n\n/**\n * Split one property's value across the components its `inputs` name.\n *\n * A property naming only `value` passes its whole value through, which is the\n * common case and the reason a scalar needs no ceremony. One naming `x`/`y` (or\n * `r`/`g`/`b`/`a`) indexes into the value, which is what lets a `point` drive two\n * separate `float` uniforms in a source that never declared a `float2`.\n */\nfunction componentsOf(\n property: ShaderProperty,\n value: unknown,\n id: string,\n where: string,\n): Record<string, ShaderUniformValue> | undefined {\n const flat = toUniformValue(property, value, id, where);\n if (flat === undefined) return undefined;\n\n const names = Object.keys(property.inputs);\n if (names.length === 1 && names[0] === \"value\") return { value: flat };\n\n const parts = typeof flat === \"number\" ? [flat] : flat;\n const out: Record<string, ShaderUniformValue> = { value: flat };\n for (const [index, name] of COMPONENTS.entries()) {\n if (parts[index] !== undefined) out[name] = parts[index];\n }\n for (const [index, name] of COLOR_COMPONENTS.entries()) {\n if (parts[index] !== undefined) out[name] = parts[index];\n }\n return out;\n}\n\n/** One property's value as floats, by its kind. */\nfunction toUniformValue(\n property: ShaderProperty,\n value: unknown,\n id: string,\n where: string,\n): ShaderUniformValue | undefined {\n switch (property.kind) {\n case \"number\":\n case \"slider\":\n case \"angle\":\n case \"hue\":\n return asFinite(value, id, where);\n\n // A `bool` cannot be a uniform member in WGSL; a float of 1 or 0 is what a shader can branch on.\n case \"boolean\":\n return value ? 1 : 0;\n\n case \"color\":\n return asColor(value, id, where);\n\n case \"vector\":\n case \"point\":\n return asFloats(value, id, where);\n\n // An unknown kind still resolves: its value reaches its uniforms\n // untouched, so a shader a host cannot fully draw still renders.\n default:\n return typeof value === \"number\" || Array.isArray(value)\n ? (value as ShaderUniformValue)\n : undefined;\n }\n}\n\nfunction asFinite(value: unknown, id: string, where: string): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n warn(`shader \"${where}\" property \"${id}\" expects a number, got ${JSON.stringify(value)}.`);\n return undefined;\n}\n\n/**\n * A colour as four floats in 0–1.\n *\n * A CSS string is parsed rather than refused, so a theme token, an `oklch()` and\n * the `\"white/10\"` opacity suffix all reach a shader — `parseColor` is the one\n * place any of those are understood, and a shader pack has no reason to be the\n * exception.\n */\nfunction asColor(value: unknown, id: string, where: string): number[] | undefined {\n if (typeof value === \"string\") {\n const [r, g, b, a] = parseColor(value);\n return [r, g, b, a];\n }\n return asFloats(value, id, where);\n}\n\nfunction asFloats(value: unknown, id: string, where: string): number[] | undefined {\n if (Array.isArray(value) && value.every((v) => typeof v === \"number\" && Number.isFinite(v))) {\n return value as number[];\n }\n if (typeof value === \"object\" && value !== null) {\n const point = value as { x?: unknown; y?: unknown };\n if (typeof point.x === \"number\" && typeof point.y === \"number\") return [point.x, point.y];\n }\n warn(`shader \"${where}\" property \"${id}\" expects numbers, got ${JSON.stringify(value)}.`);\n return undefined;\n}\n\nconst warned = new Set<string>();\n\nfunction warn(message: string): void {\n if (warned.has(message)) return;\n if (warned.size > 256) warned.clear();\n warned.add(message);\n console.warn(`[shader] ${message}`);\n}\n", "import { NodeEffect } from \"./union\";\nimport type { BlendMode } from \"../fill/blend\";\nimport type { EffectOptions } from \"./effect-data\";\nimport { scalarOptions, withEffectOptions } from \"./effect-data\";\nimport { resolveEffect, lerpEffect } from \"./registry\";\nimport { buildEffect, type EffectOptionsOf } from \"./spec\";\nimport { blurSpec } from \"./implementations/blur\";\nimport { directionalBlurSpec } from \"./implementations/directional-blur\";\nimport { grayscaleSpec } from \"./implementations/grayscale\";\nimport { pixelateSpec } from \"./implementations/pixelate\";\nimport { bulgeSpec } from \"./implementations/bulge\";\nimport { magnifySpec } from \"./implementations/magnify\";\nimport { bloomSpec } from \"./implementations/bloom\";\nimport { vintageSpec } from \"./implementations/vintage\";\nimport { chromaticAberrationSpec } from \"./implementations/chromatic-aberration\";\nimport { invertSpec } from \"./implementations/invert\";\nimport { scatterSpec } from \"./implementations/scatter\";\nimport { posterizeSpec } from \"./implementations/posterize\";\nimport { motionBlurSpec } from \"./implementations/motion-blur\";\nimport { outlineSpec } from \"./implementations/outline\";\nimport { dropShadowSpec } from \"./implementations/drop-shadow\";\nimport { vignetteSpec } from \"./implementations/vignette\";\nimport { lutSpec } from \"./implementations/lut\";\nimport { grainSpec } from \"./implementations/grain\";\nimport { sharpenSpec } from \"./implementations/sharpen\";\nimport { edgesSpec } from \"./implementations/edges\";\nimport { thresholdSpec } from \"./implementations/threshold\";\nimport { radialBlurSpec } from \"./implementations/radial-blur\";\nimport { halftoneSpec } from \"./implementations/halftone\";\nimport { ditherSpec } from \"./implementations/dither\";\nimport { duotoneSpec } from \"./implementations/duotone\";\nimport { curvesSpec } from \"./implementations/curves\";\nimport { rgbShiftSpec } from \"./implementations/rgb-shift\";\nimport { scanlinesSpec } from \"./implementations/scanlines\";\nimport { blockDisplaceSpec } from \"./implementations/block-displace\";\nimport { bitCrushSpec } from \"./implementations/bit-crush\";\nimport { asciiSpec } from \"./implementations/ascii\";\nimport { oilPaintSpec } from \"./implementations/oil-paint\";\nimport { streakSpec } from \"./implementations/streak\";\nimport { glowSpec } from \"./implementations/glow\";\nimport { waveSpec } from \"./implementations/wave\";\nimport { twirlSpec } from \"./implementations/twirl\";\nimport { progressiveBlurSpec } from \"./implementations/progressive-blur\";\nimport { kaleidoscopeSpec } from \"./implementations/kaleidoscope\";\nimport { glassSpec } from \"./implementations/glass\";\nimport type { AttributeOps } from \"@/attributes/shared/operators\";\nimport { normalizeUniforms, type ShaderUniform, type ShaderUniformRecord } from \"../shaders/uniforms\";\nimport { resolveShaderProperties, type ShaderPropertyValues } from \"../shaders/resolve\";\nimport type { EffectShader } from \"../shaders/pack\";\nimport type { ColorAdjustmentEffect } from \"./implementations/color-adjustment\";\n\n/**\n * Every effect builder takes **exactly one argument**: an options object\n * carrying all of that effect's data. Builders with one dominant animated\n * scalar also accept that scalar directly, so the common case stays terse:\n *\n * Effects.blur(8)\n * Effects.blur({ radius: 8, mode: 'backdrop' })\n *\n * Field names are shared vocabulary across every effect — `radius` is always a\n * pixel distance, `amount` always a 0–1 intensity, `angle` always degrees,\n * `center` always a 0–1 normalised point, `axis` always an {@link EffectAxis}.\n */\n\n/** Gaussian blur. Scalar shorthand sets `radius`. */\nexport type BlurOptions = EffectOptionsOf<typeof blurSpec.params>;\n\n/** Directional (linear) blur. Scalar shorthand sets `radius`. */\nexport type DirectionalBlurOptions = EffectOptionsOf<typeof directionalBlurSpec.params>;\n\n/** Desaturation. Scalar shorthand sets `amount`. */\nexport type GrayscaleOptions = EffectOptionsOf<typeof grayscaleSpec.params>;\n\n/**\n * After Effects-style Mosaic. Scalar shorthand sets `blocks` on both axes.\n *\n * `blocks` is the *number of blocks* across the node, so a count equal to the\n * node's pixel size on that axis is pristine and lower counts are coarser.\n */\nexport type PixelateOptions = EffectOptionsOf<typeof pixelateSpec.params>;\n\n/** Bulge / pinch lens over the node's content, or the backdrop. Scalar shorthand sets `strength`. */\nexport type BulgeOptions = EffectOptionsOf<typeof bulgeSpec.params>;\n\n/** Magnifier lens over the backdrop. Scalar shorthand sets `scale`. */\nexport type MagnifyOptions = EffectOptionsOf<typeof magnifySpec.params>;\n\n/** Bloom (glow). Scalar shorthand sets `intensity`. */\nexport type BloomOptions = EffectOptionsOf<typeof bloomSpec.params>;\n\n/** Vintage / film-look colour grading. Scalar shorthand sets `amount`. */\nexport type VintageOptions = EffectOptionsOf<typeof vintageSpec.params>;\n\n/** Lens-dispersion colour fringing. Scalar shorthand sets `amount`. */\nexport type ChromaticAberrationOptions = EffectOptionsOf<typeof chromaticAberrationSpec.params>;\n\n/** Colour invert. Scalar shorthand sets `strength`. */\nexport type InvertOptions = EffectOptionsOf<typeof invertSpec.params>;\n\n/** Per-pixel random jitter. Scalar shorthand sets `strength`. */\nexport type ScatterOptions = EffectOptionsOf<typeof scatterSpec.params>;\n\n/** Colour banding. Scalar shorthand sets `levels`. */\nexport type PosterizeOptions = EffectOptionsOf<typeof posterizeSpec.params>;\n\n/** Velocity-driven motion blur. Scalar shorthand sets `length`. */\nexport type MotionBlurOptions = EffectOptionsOf<typeof motionBlurSpec.params>;\n\n/**\n * A custom shader. `mode` selects the path:\n *\n * - `'foreground'` (the default) — `sample_src` reads the node's layer; the output\n * replaces it, or composites onto it with `blendMode`.\n * - `'backdrop'` — `sample_src` reads a snapshot of what is painted beneath the\n * node. `blendMode` is unused.\n */\nexport interface ShaderEffectOptions extends EffectOptions {\n /**\n * The WGSL program, or a registered\n * **shader pack** — a program plus the editable values it publishes.\n *\n * A pack resolves to plain uniforms here, so nothing below this builder\n * knows one exists; what survives into the document is the resolved record\n * plus a `shaderId` naming the pack, which is what lets a host reopen its\n * property panel from a saved scene.\n */\n source: string | EffectShader;\n /**\n * Property overrides, by property id, when {@link source} is a pack.\n *\n * Anything not named here takes the pack's own default. Ignored — with a\n * warning — for a bare source string, which has no properties to override.\n */\n values?: ShaderPropertyValues;\n /**\n * Uniform values by name — lerped between animation frames (default `{}`).\n *\n * The positional `[{ name, value }]` array still works; both are bound by\n * name now, so the array's order no longer means anything.\n */\n uniforms?: ShaderUniformRecord | ShaderUniform[];\n /** How a foreground shader composites onto the layer; its output replaces the layer when absent. */\n blendMode?: BlendMode;\n /** How far past the node's box (logical px) a WGSL effect may draw. Default 0. */\n reach?: number;\n}\n\n/** Coloured band around the node's silhouette. Scalar shorthand sets `width`. */\nexport type OutlineOptions = EffectOptionsOf<typeof outlineSpec.params>;\n\n/**\n * A shadow cast from the node's silhouette. Scalar shorthand sets `blur`, since\n * softness is the knob a shadow is usually reached for by.\n */\nexport type DropShadowOptions = EffectOptionsOf<typeof dropShadowSpec.params>;\n\n/** Darkened edges / lens falloff. Scalar shorthand sets `amount`. */\nexport type VignetteOptions = EffectOptionsOf<typeof vignetteSpec.params>;\n\n/** Film grain. Scalar shorthand sets `amount`. */\n/**\n * A 3D colour lookup table — see {@link LutEffect} for the table's layout and\n * why it is compared by reference.\n *\n * No scalar shorthand: the dominant argument is a whole cube, and a builder that\n * took `Effects.lut(table)` would still need the size beside it to read it.\n */\nexport type LutOptions = EffectOptionsOf<typeof lutSpec.params>;\n\nexport type GrainOptions = EffectOptionsOf<typeof grainSpec.params>;\n\n/** Unsharp-mask sharpen. Scalar shorthand sets `amount`. */\nexport type SharpenOptions = EffectOptionsOf<typeof sharpenSpec.params>;\n\n/** Edge detection. Scalar shorthand sets `strength`. */\nexport type EdgesOptions = EffectOptionsOf<typeof edgesSpec.params>;\n\n/** Two-tone luminance cut. Scalar shorthand sets `level`. */\nexport type ThresholdOptions = EffectOptionsOf<typeof thresholdSpec.params>;\n\n/** Zoom / spin blur about a point. Scalar shorthand sets `amount`. */\nexport type RadialBlurOptions = EffectOptionsOf<typeof radialBlurSpec.params>;\n\n/** Halftone print screen. Scalar shorthand sets `size`. */\nexport type HalftoneOptions = EffectOptionsOf<typeof halftoneSpec.params>;\n\n/** Ordered (Bayer) dithering. Scalar shorthand sets `levels`. */\nexport type DitherOptions = EffectOptionsOf<typeof ditherSpec.params>;\n\n/** Two-colour luminance ramp. Scalar shorthand sets `amount`. */\nexport type DuotoneOptions = EffectOptionsOf<typeof duotoneSpec.params>;\n\n/** Tone curve through control points. */\nexport type CurvesOptions = EffectOptionsOf<typeof curvesSpec.params>;\n\n/** Photographic grading. Every field is optional and defaults to neutral. */\nexport type ColorAdjustmentOptions = Omit<ColorAdjustmentEffect, 'type'> & EffectOptions;\n\n/**\n * Per-channel RGB offset. Scalar shorthand sets `amount`, which spreads red and\n * blue apart horizontally by that many pixels and leaves green put — the\n * everyday case. Name `red`/`green`/`blue` for full control.\n */\nexport type RgbShiftOptions = EffectOptionsOf<typeof rgbShiftSpec.params> & {\n /** Shorthand: ±px horizontal spread of red vs. blue (default 4); `red`/`blue` override it. */\n amount?: number;\n};\n\n/** CRT scanlines. Scalar shorthand sets `darkness`. */\nexport type ScanlinesOptions = EffectOptionsOf<typeof scanlinesSpec.params>;\n\n/** Datamosh-style band tearing. Scalar shorthand sets `amount`. */\nexport type BlockDisplaceOptions = EffectOptionsOf<typeof blockDisplaceSpec.params>;\n\n/** ASCII art from a glyph grid. Scalar shorthand sets `size`. */\nexport type AsciiOptions = EffectOptionsOf<typeof asciiSpec.params>;\n\n/** Anamorphic glare — a bright pass smeared along one axis. Scalar shorthand sets `intensity`. */\nexport type StreakOptions = EffectOptionsOf<typeof streakSpec.params>;\n\n/**\n * A glow — bright (or opaque) areas spread outward and composited back, with\n * optional recolouring. Scalar shorthand sets `intensity`.\n *\n * Unlike `bloom`, this spreads past the node's own box, chooses how the source\n * composites against it, and can be coloured through a ramp.\n */\nexport type GlowOptions = EffectOptionsOf<typeof glowSpec.params>;\n\n/** Kuwahara brushwork. Scalar shorthand sets `radius`. */\nexport type OilPaintOptions = EffectOptionsOf<typeof oilPaintSpec.params>;\n\n/** Sine warp. Scalar shorthand sets `amplitude` on the Y axis — the everyday ripple. */\nexport type WaveOptions = EffectOptionsOf<typeof waveSpec.params>;\n\n/** Twirl / swirl vortex. Scalar shorthand sets `angle`. */\nexport type TwirlOptions = EffectOptionsOf<typeof twirlSpec.params>;\n\n/**\n * Blur that ramps across the node. Scalar shorthand sets `radius`.\n *\n * `mode: 'backdrop'` gives the frosted panel whose blur fades out rather than\n * ending at a hard edge.\n */\nexport type ProgressiveBlurOptions = EffectOptionsOf<typeof progressiveBlurSpec.params>;\n\n/** Mirrored wedges around a point. Scalar shorthand sets `segments`. */\nexport type KaleidoscopeOptions = EffectOptionsOf<typeof kaleidoscopeSpec.params>;\n\n/**\n * Figma's Glass over the backdrop. Scalar shorthand sets `refraction`.\n *\n * Figma's fields, units and defaults (light `-45°` at 80, refraction 80, depth\n * 20 px, dispersion 50, frost 4, splay 0), so a bare `Effects.glass()` is the\n * glass Figma adds and values copied from a Figma file render the same.\n *\n * Defaults to `{ mode: 'backdrop' }`; there is nothing to refract in a node's\n * own paint, so the foreground is a no-op.\n */\nexport type GlassOptions = EffectOptionsOf<typeof glassSpec.params>;\n\n/** Colour-depth reduction. Scalar shorthand sets `bits`. */\nexport type BitCrushOptions = EffectOptionsOf<typeof bitCrushSpec.params>;\n\n/**\n * Immutable, chainable list of node effects.\n *\n * Each builder method returns a new `EffectChain` with the effect appended,\n * so chains are safe to share and branch.\n *\n * @example\n * const fx = Effects.blur(4).grayscale(0.5);\n * node.effects = fx; // assign directly\n * node.effects = [...fx, { type: 'pixelate', ... }]; // spread into array\n */\nexport class EffectChain {\n constructor(public list: NodeEffect[] = []) { }\n\n private append(effect: NodeEffect): EffectChain {\n return new EffectChain([...this.list, effect]);\n }\n\n /**\n * Append a Gaussian blur. Pass `{ mode: \"backdrop\" }` to blur the content\n * beneath the node (clipped to its silhouette, Figma-style) instead of the\n * node's own content.\n */\n blur(options: number | BlurOptions) {\n return this.append(buildEffect(blurSpec, options));\n }\n\n /**\n * Append a motion-blur-style directional (linear) blur, smearing the node's\n * own content along a single axis (or the backdrop, with `{ mode: \"backdrop\" }`).\n */\n directionalBlur(options: number | DirectionalBlurOptions) {\n return this.append(buildEffect(directionalBlurSpec, options));\n }\n\n /**\n * Append an After Effects-style Mosaic / pixelate. `blocks` is the *number of\n * blocks* across the node (a count equal to the node's pixel size on that\n * axis is pristine; lower is coarser), not a pixel block size.\n */\n pixelate(options: number | PixelateOptions) {\n return this.append(buildEffect(pixelateSpec, options));\n }\n\n /** Append a grayscale effect. `{ mode: \"backdrop\" }` desaturates the backdrop. */\n grayscale(options: number | GrayscaleOptions) {\n return this.append(buildEffect(grayscaleSpec, options));\n }\n\n /**\n * Append a bulge/pinch lens. A barrel distortion magnifies the centre and\n * pins the edges; a negative strength pinches the centre inward instead.\n * `mode: \"backdrop\"` points the same lens at what is painted beneath the\n * node, giving a glass dome over the layers below rather than a warp of the\n * node's own paint.\n */\n bulge(options: number | BulgeOptions) {\n return this.append(buildEffect(bulgeSpec, options));\n }\n\n /**\n * Append a magnify lens that magnifies the backdrop beneath the node. The lens\n * fills the node's bounding box and is clipped to its silhouette, so whatever\n * is painted underneath shows through scaled about `center` — like a\n * magnifying glass shaped to the node.\n *\n * Defaults to `{ mode: 'backdrop' }`; pass `mode` explicitly to override.\n */\n magnify(options?: number | MagnifyOptions) {\n return this.append(buildEffect(magnifySpec, options));\n }\n\n /**\n * Append a bloom (glow) effect. Bright areas bleed soft light outward via a\n * screen-blend of the blurred bright-pass onto the layer.\n */\n bloom(options?: number | BloomOptions) {\n return this.append(buildEffect(bloomSpec, options));\n }\n\n /** Append a vintage / film-look colour grading effect. */\n vintage(options?: number | VintageOptions) {\n return this.append(buildEffect(vintageSpec, options));\n }\n\n /**\n * Append a chromatic aberration effect — red/blue colour fringing that mimics\n * lens dispersion.\n */\n chromaticAberration(options?: number | ChromaticAberrationOptions) {\n return this.append(buildEffect(chromaticAberrationSpec, options));\n }\n\n /** Append a colour-invert effect. */\n invert(options?: number | InvertOptions) {\n return this.append(buildEffect(invertSpec, options));\n }\n\n /**\n * Append a scatter effect — randomly jitters the node's own pixels, smearing\n * its content like After Effects' Scatter.\n */\n scatter(options?: number | ScatterOptions) {\n return this.append(buildEffect(scatterSpec, options));\n }\n\n /**\n * Append an After Effects-style posterize effect — quantizes each colour\n * channel into `levels` evenly-spaced bands, flattening gradients into steps.\n */\n posterize(options?: number | PosterizeOptions) {\n return this.append(buildEffect(posterizeSpec, options));\n }\n\n /**\n * Append velocity-driven motion blur — smears the node's own content along its\n * actual per-frame motion (a static node stays sharp). Modelled on After\n * Effects' shutter angle (`length`) and shutter phase (`alignment`).\n */\n motionBlur(options?: number | MotionBlurOptions) {\n return this.append(buildEffect(motionBlurSpec, options));\n }\n\n /**\n * Append an outline — a coloured band traced around the node's silhouette,\n * including alpha silhouettes (text, an image's cutout, a whole subtree) that\n * a geometry `stroke` can't follow.\n */\n outline(options?: number | OutlineOptions) {\n return this.append(buildEffect(outlineSpec, options));\n }\n\n /**\n * Append a drop shadow cast from the node's **silhouette** — including alpha\n * silhouettes (text, an image's cutout, a whole subtree) that a geometry\n * `shadow` can't follow, since that one fills the node's path.\n */\n dropShadow(options?: number | DropShadowOptions) {\n return this.append(buildEffect(dropShadowSpec, options));\n }\n\n /**\n * Append a vignette — a soft tint ramping in toward the node's corners. The\n * falloff follows the node's aspect ratio, so a wide node darkens along its\n * short edges the way a lens would.\n */\n vignette(options?: number | VignetteOptions) {\n return this.append(buildEffect(vignetteSpec, options));\n }\n\n /**\n * Append film grain. Static grain reads as texture rather than film, so pass\n * `{ animated: true }` to re-seed it each frame — or tween `seed` when the\n * render has to stay deterministic.\n */\n /**\n * Apply a 3D colour lookup table.\n *\n * The whole point of a LUT is that it is *someone else's* colour science, so\n * there is nothing to default beyond how much of it to use: `amount` is the\n * mix and everything else is the file.\n *\n * @example\n * Effects.lut({ table, size: 33 }) // the full look\n * Effects.lut({ table, size: 33, amount: 0.6 })\n */\n lut(options: LutOptions) {\n return this.append(buildEffect(lutSpec, options));\n }\n\n grain(options?: number | GrainOptions) {\n return this.append(buildEffect(grainSpec, options));\n }\n\n /** Append an unsharp-mask sharpen — local contrast boosted at `radius` scale. */\n sharpen(options?: number | SharpenOptions) {\n return this.append(buildEffect(sharpenSpec, options));\n }\n\n /**\n * Append edge detection — flat areas go black and boundaries light up with\n * the magnitude of the local gradient.\n */\n edges(options?: number | EdgesOptions) {\n return this.append(buildEffect(edgesSpec, options));\n }\n\n /**\n * Append a luminance threshold — a two-tone stencil cut at `level`, with\n * `smoothness` widening the cut into a ramp.\n */\n threshold(options?: number | ThresholdOptions) {\n return this.append(buildEffect(thresholdSpec, options));\n }\n\n /**\n * Append a radial blur — samples smeared along the radius (`'zoom'`, the\n * default) or the tangent (`'spin'`) about `center`, leaving the centre sharp.\n */\n radialBlur(options?: number | RadialBlurOptions) {\n return this.append(buildEffect(radialBlurSpec, options));\n }\n\n /**\n * Append a halftone screen — the newsprint look, where tone becomes the size\n * of a mark on a rotated grid.\n */\n halftone(options?: number | HalftoneOptions) {\n return this.append(buildEffect(halftoneSpec, options));\n }\n\n /**\n * Append ordered (Bayer) dithering — quantization to `levels` tones per\n * channel with the error traded for a retro crosshatch pattern.\n */\n dither(options?: number | DitherOptions) {\n return this.append(buildEffect(ditherSpec, options));\n }\n\n /**\n * Append a duotone / gradient map — the content's luminance remapped onto a\n * `shadows` → `highlights` ramp, discarding its original chroma.\n */\n duotone(options?: number | DuotoneOptions) {\n return this.append(buildEffect(duotoneSpec, options));\n }\n\n /**\n * Append a tone curve — the same adjustment `Adjustments.curves` applies to a\n * photo, on any node.\n */\n curves(options: CurvesOptions) {\n return this.append(buildEffect(curvesSpec, options));\n }\n\n /**\n * Append photographic grading (brightness / contrast / saturation / vibrance /\n * shadows / highlights / temperature / tint) — `Adjustments.colorAdjustment`\n * on any node. For darkened edges use {@link EffectChain.vignette}.\n */\n colorAdjustment(options: ColorAdjustmentOptions) {\n // Destructure `mode` out rather than spreading it through: a caller who\n // writes `{ mode: undefined }` would otherwise plant the key on the\n // effect, and `equals()` compares `mode` directly. `withEffectOptions`\n // skips undefined, so handing it back there is safe.\n const { mode, ...fields } = options;\n return this.append(withEffectOptions({ type: \"colorAdjustment\" as const, ...fields }, { mode }));\n }\n\n /**\n * Append a per-channel RGB offset — the digital cousin of\n * {@link EffectChain.chromaticAberration}, where each plane goes where you\n * point it instead of following a lens model.\n */\n rgbShift(options?: number | RgbShiftOptions) {\n const o = scalarOptions(options, \"amount\");\n const spread = o.amount;\n return this.append(buildEffect(rgbShiftSpec, spread === undefined ? o : {\n ...o,\n red: o.red ?? { x: spread, y: 0 },\n blue: o.blue ?? { x: -spread, y: 0 },\n }));\n }\n\n /**\n * Append CRT scanlines. Animate `offset` past `spacing` to roll the bands;\n * the pattern wraps, so a linear tween loops seamlessly.\n */\n scanlines(options?: number | ScanlinesOptions) {\n return this.append(buildEffect(scanlinesSpec, options));\n }\n\n /**\n * Append datamosh-style band tearing. Step `seed` in whole numbers to jump\n * between distinct glitch states rather than sliding between them.\n */\n blockDisplace(options?: number | BlockDisplaceOptions) {\n return this.append(buildEffect(blockDisplaceSpec, options));\n }\n\n /**\n * Append colour-depth reduction — `bits` per channel, or a fixed hardware\n * palette. Pair with {@link EffectChain.dither} so gradients survive the cut.\n */\n bitCrush(options?: number | BitCrushOptions) {\n return this.append(buildEffect(bitCrushSpec, options));\n }\n\n /**\n * Append ASCII art — the content divided into a grid of cells, each cell's\n * tone replaced by the glyph that carries a matching amount of ink.\n *\n * Set `background: 'transparent'` to lay the glyphs over whatever is behind\n * the node instead of over a solid field.\n */\n ascii(options?: number | AsciiOptions) {\n return this.append(buildEffect(asciiSpec, options));\n }\n\n /**\n * Append Kuwahara brushwork — averages within a region but never across an\n * edge, so flat areas smooth into strokes while boundaries stay crisp.\n * By some margin the most expensive effect in the set; keep `radius` small.\n */\n oilPaint(options?: number | OilPaintOptions) {\n return this.append(buildEffect(oilPaintSpec, options));\n }\n\n /**\n * Append an anamorphic streak — a bright pass smeared along one axis and\n * screened back on. {@link EffectChain.bloom} spreads light in every\n * direction; this spreads it in one.\n */\n streak(options?: number | StreakOptions) {\n return this.append(buildEffect(streakSpec, options));\n }\n\n /**\n * Append a glow — the bright (or opaque) parts of the layer spread outward\n * and composited back, optionally recoloured through a ramp.\n *\n * `bloom` is the cheaper relative: it screens a blurred bright-pass back\n * within the node's own box. This one spreads past that box, lets the source\n * sit behind, in front of, or nowhere at all, and can map glow strength onto\n * `colors`/`stops` — which is what a heat, neon or aurora look needs.\n */\n glow(options?: number | GlowOptions) {\n return this.append(buildEffect(glowSpec, options));\n }\n\n /**\n * Append a custom WGSL shader. `mode` picks the layer it runs on, which\n * `sample_src` reads: the node's own layer, or what is painted beneath it\n * (`'backdrop'`).\n */\n shader(options: ShaderEffectOptions) {\n const pack = typeof options.source === \"string\" ? undefined : options.source;\n if (pack && pack.scope !== \"effect\") {\n throw new Error(\n `Effects.shader was given a \"${(pack as { scope: string }).scope}\" shader ` +\n `(\"${pack.name}\"). A fill shader has no backdrop to sample and is bound to a ` +\n `shape's box; use Fills.shader.`,\n );\n }\n // A backdrop pack supplies the default; a caller may still say otherwise.\n const mode = options.mode ?? (pack?.backdrop ? \"backdrop\" : \"foreground\");\n const source = pack ? pack.source : (options.source as string);\n const uniforms = pack\n ? { ...resolveShaderProperties(pack, options.values), ...normalizeUniforms(options.uniforms ?? {}) }\n : (options.uniforms ?? {});\n const base = {\n type: \"shader\" as const,\n source,\n language: \"wgsl\" as const,\n ...(options.reach ? { reach: options.reach } : {}),\n uniforms,\n ...(pack?.id !== undefined ? { shaderId: pack.id } : {}),\n };\n // blendMode only applies to the foreground overlay; leaving it undefined\n // for a backdrop shader keeps `equals()` comparing like with like.\n const effect: NodeEffect = mode === \"foreground\" && options.blendMode\n ? { ...base, blendMode: options.blendMode }\n : base;\n return this.append(withEffectOptions(effect, { mode }));\n }\n\n /**\n * Append a sine warp. Tween `phase` over 360 to make the wave travel — it\n * wraps, so a linear tween loops seamlessly.\n */\n wave(options?: number | WaveOptions) {\n return this.append(buildEffect(waveSpec, options));\n }\n\n /**\n * Append a twirl / swirl vortex — a rotation about `center` that falls off\n * with distance, so the middle spins while the rim stays pinned.\n */\n twirl(options?: number | TwirlOptions) {\n return this.append(buildEffect(twirlSpec, options));\n }\n\n /**\n * Append a blur whose radius ramps across the node rather than being\n * uniform. With `{ mode: 'backdrop' }` this is the frosted panel whose blur\n * fades out instead of ending at a hard edge.\n */\n progressiveBlur(options?: number | ProgressiveBlurOptions) {\n return this.append(buildEffect(progressiveBlurSpec, options));\n }\n\n /**\n * Append a kaleidoscope fold. Animating `angle` sweeps fresh source material\n * through the sampled wedge while the pattern itself stays locked — which is\n * not what rotating the node does.\n */\n kaleidoscope(options?: number | KaleidoscopeOptions) {\n return this.append(buildEffect(kaleidoscopeSpec, options));\n }\n\n /**\n * Append Figma's Glass — the backdrop refracted, dispersed and frosted\n * through a curved edge on the node's outline, with a rim of light.\n *\n * Like `magnify`, this reads what is painted *beneath* the node and is\n * clipped to its outline, so the shape's own edges stay sharp. It needs no\n * map: the curve is derived from the outline itself, so it follows a\n * rounded rect, an ellipse, a hand-drawn path or text equally.\n *\n * Defaults to `{ mode: 'backdrop' }`; pass `mode` explicitly to override.\n */\n glass(options?: number | GlassOptions) {\n return this.append(buildEffect(glassSpec, options));\n }\n\n /** Allows spreading the chain into an array: `[...Effects.blur(5)]`. */\n *[Symbol.iterator]() {\n yield* this.list;\n }\n\n /** Serializes to the raw effect array so frameworks that call `toJSON` get a plain value. */\n toJSON() {\n return this.list;\n }\n}\n\n/**\n * Accepted shapes for a node's `effects` prop.\n *\n * Mirrors {@link Fill}: a single {@link NodeEffect}, an `EffectChain` builder\n * result, or an array mixing effects and chains (each chain contributes all its\n * effects in place). Already-resolved effects are themselves `NodeEffect`s, so\n * a node's read-back `effects` can be assigned straight back.\n *\n * Effects.blur(8) // chain\n * { type: 'blur', radius: 8 } // single effect\n * [Effects.blur(8), { type: 'invert' }] // mixed array\n * [...Effects.blur(8), grayscaleEffect]\n */\nexport type Effect =\n | NodeEffect\n | EffectChain\n | (NodeEffect | EffectChain)[];\n\n/**\n * Entry point for building effect chains fluently.\n *\n * An empty {@link EffectChain}, so `Effects.blur(8)` *is* `new EffectChain().blur(8)`\n * — every builder's signature and documentation has exactly one definition, on\n * the class, which is also what an editor shows when you hover `Effects.blur`.\n * (A parallel object of arrow functions would need its own copy of all 41 docs,\n * and hovering it showed none of them.)\n *\n * The chain is immutable — every builder returns a *new* chain — so sharing one\n * empty instance as the entry point is safe.\n *\n * @example\n * node.effects = Effects.blur(8).grayscale(1);\n */\nexport const Effects = new EffectChain();\n\n/**\n * Normalises any {@link Effect} value to a plain `NodeEffect[]`.\n * Used internally when reading props before rendering or interpolation.\n *\n * Chains used as array elements are flattened so each contributes its effects\n * in place: `[Effects.blur(8), grayscaleEffect]` — as is the plain array a chain\n * serializes to, which is how that value reads back out of a stored document.\n */\nexport function resolveChainEffects(effects: Effect | undefined): NodeEffect[] {\n if (effects === undefined) return [];\n if (effects instanceof EffectChain) return resolveAll(effects.list);\n if (Array.isArray(effects)) {\n const out: NodeEffect[] = [];\n for (const item of effects) {\n if (item instanceof EffectChain) out.push(...resolveAll(item.list));\n else if (Array.isArray(item)) out.push(...resolveChainEffects(item as Effect));\n else out.push(resolveEffect(item));\n }\n return out;\n }\n return [resolveEffect(effects)];\n}\n\n/**\n * Resolve every effect in `list`, returning **the same array** when none of them\n * needed it — which is the overwhelming majority, since one effect type\n * registers a `resolve` at all.\n *\n * The identity is load-bearing, not a micro-optimisation: this runs on every\n * write of an `effects` prop, and `lerpEffectArray` short-circuits on\n * `from === to`. Copying unconditionally would defeat that for every node in\n * every scene to migrate one effect type.\n */\nfunction resolveAll(list: NodeEffect[]): NodeEffect[] {\n let out: NodeEffect[] | undefined;\n for (let i = 0; i < list.length; i++) {\n const resolved = resolveEffect(list[i]);\n if (!out && resolved !== list[i]) out = list.slice(0, i);\n out?.push(resolved);\n }\n return out ?? list;\n}\n\n/** The effect-chain attribute's op set — the `effects` prop's resolve/lerp pair. */\nexport const effectsOps: AttributeOps<Effect, NodeEffect[]> = {\n resolve: (effects) => resolveChainEffects(effects),\n lerp: (from, to, t) => {\n if (from === to) return from;\n const maxLen = Math.max(from.length, to.length);\n const result: NodeEffect[] = [];\n for (let i = 0; i < maxLen; i++) {\n const a = from[i];\n const b = to[i];\n if (a && b) {\n result.push(lerpEffect(a, b, t));\n } else if (a) {\n result.push(a);\n } else if (b) {\n result.push(b);\n }\n }\n return result;\n },\n};\n", "import type { NodeEffect } from \"./union\";\nimport { effectSurface } from \"./registry\";\n\n/**\n * Backdrop/foreground classification for effects.\n *\n * Every effect carries a uniform {@link EffectMode} via {@link ModedEffect}, so\n * classification is a single field read — no branching on `effect.type`. An\n * effect with `mode === \"backdrop\"` runs on the content painted *beneath* the\n * node (clipped to its silhouette); anything else is a foreground effect over\n * the node's own content.\n */\n\n/** Does this effect target the backdrop beneath the node rather than its own content? */\nexport const isBackdropEffect = (effect: NodeEffect): boolean => effect.mode === \"backdrop\";\n\n/**\n * Shared result for the overwhelmingly common \"this node has no effects\" case.\n *\n * Both classifiers below run once per node per frame during render, and `.filter`\n * allocates a fresh array even when there is nothing to filter. On a scene with\n * thousands of plain shapes that is thousands of throwaway arrays per frame, for\n * an answer that is always the same empty list.\n */\nconst NONE: NodeEffect[] = [];\n\n/** The backdrop-targeting effects in `effects`, for the renderer's backdrop pass. */\nexport const backdropEffects = (effects: NodeEffect[]): NodeEffect[] =>\n effects.length === 0 ? NONE : effects.filter(isBackdropEffect);\n\n/**\n * Foreground effects that warp/band the node's *own* content and therefore need\n * a snapshot-and-redraw scope rather than a composable image filter.\n *\n * Driven by each effect's declared {@link EffectSurface}, so adding a shader\n * effect needs no edit here. Author chain order is preserved: index 0 is the\n * outermost scope, and the renderer nests the rest inside it.\n */\nexport function foregroundShaderEffects(effects: NodeEffect[]): NodeEffect[] {\n if (effects.length === 0) return NONE;\n return effects.filter((e) => e.mode !== \"backdrop\" && effectSurface(e) === \"shader\");\n}\n", "import type { Color } from \"./color/parser\";\nimport type { BlendMode } from \"./blend\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { ImageAdjustment, VideoAdjustment } from \"../filters/chain\";\nimport type { MediaPresetProp, VideoPresetProp } from \"./media-preset\";\nimport type { FillProp, FillResolved, FillSpace } from \"./union\";\nimport { normalizeUniforms } from \"../shaders/uniforms\";\nimport { resolveShaderProperties, type ShaderPropertyValues } from \"../shaders/resolve\";\nimport type { FillShader } from \"../shaders/pack\";\nimport type { ImageCrop, ImageFit, ImageMatrix } from \"./implementations/image\";\nimport type { Alignment } from \"@/attributes/layout/alignment\";\nimport type { FractalNoiseFillProp } from \"./implementations/fractal-noise\";\nimport type { DotGridFillProp } from \"./implementations/dot-grid\";\nimport type { GridFillProp } from \"./implementations/grid\";\nimport type { ShaderFillProp } from \"./implementations/shader\";\nimport type { Scene3D } from \"@/render3d/scene3d\";\n\n/** Placement options shared by the image and video fill builders. */\nexport interface MediaPlacementOptions {\n /** How the (cropped) source is scaled into the node's bounds. Default `'fill'`. */\n fit?: ImageFit;\n /** Window onto the source, in fractions of its own size, applied before `fit`. */\n crop?: ImageCrop;\n /** Magnification on top of the fitted scale. `1` is the fitted size. */\n zoom?: number;\n /** The point held fixed as `zoom` scales; also the alignment when it doesn't cover. */\n anchor?: Alignment;\n /** Raw source→shape matrix; bypasses `crop`/`fit`/`zoom`/`anchor` and the bounds. */\n matrix?: ImageMatrix;\n}\n\n/** Author-facing options for a {@link FillChain.video} layer. */\nexport interface VideoFillOptions extends FillOptions, MediaPlacementOptions {\n /** The grade laid over the footage — an adjustment chain plus a 0–1 mix. */\n preset?: VideoPresetProp;\n /** @deprecated Moved to `preset.adjustments`. Removed in the next major. */\n filters?: VideoAdjustment;\n /**\n * Explicit source time to paint, in seconds. Omit it and the clip plays by\n * itself, timed from the moment the node painting it appeared — set it only\n * to drive the playhead yourself (`null` hands the playhead back).\n */\n timestamp?: number | null;\n /** Whether playback advances with the node's clock. Defaults to `true`. */\n playing?: boolean;\n trimStart?: number;\n trimEnd?: number;\n /** Seconds after the painting node appears before playback begins. Default `0`. */\n playStart?: number;\n speed?: number;\n loop?: 'forward' | 'reverse' | 'none';\n duration?: number;\n}\n\n/**\n * Cross-cutting options shared by every fill layer. These map onto the\n * `opacity` / `blend` fields each fill prop already accepts, plus the\n * `space` directive carried generically by the registry.\n */\nexport interface FillOptions {\n opacity?: number;\n blend?: BlendMode;\n space?: FillSpace;\n}\n\n/** Strip `undefined` option keys so the produced props stay minimal/comparable. */\nfunction withOptions<T extends object>(base: T, options: FillOptions = {}): T & FillOptions {\n const out = { ...base } as T & FillOptions;\n if (options.opacity !== undefined) out.opacity = options.opacity;\n if (options.blend !== undefined) out.blend = options.blend;\n if (options.space !== undefined) out.space = options.space;\n return out;\n}\n\n/**\n * Immutable, chainable list of fill layers.\n *\n * Each builder method returns a new `FillChain` with the layer appended, so\n * chains are safe to share and branch — mirroring {@link EffectChain}.\n *\n * @example\n * const bg = Fills.image('./background.jpg', { blend: 'overlay', opacity: 0.2 })\n * .color('red', { opacity: 0.3 });\n * node.fill = bg; // assign directly\n * node.fill = [...bg, 'white']; // spread into an array\n */\nexport class FillChain {\n constructor(public list: FillProp[] = []) { }\n\n /** Append a solid color fill. A CSS string or normalized `[r,g,b,a]`. */\n color(color: Color, options?: FillOptions) {\n return new FillChain([...this.list, withOptions({ type: 'solid' as const, color }, options)]);\n }\n\n /**\n * Append an image fill from `src`.\n *\n * @example\n * Fills.image('./city.jpg', { zoom: 1.4, anchor: 'topCenter', crop: { bottom: 0.2 } })\n */\n image(\n src: string,\n options?: FillOptions & MediaPlacementOptions & {\n /** The grade laid over the picture — an adjustment chain plus a 0–1 mix. */\n preset?: MediaPresetProp;\n /** @deprecated Moved to `preset.adjustments`. Removed in the next major. */\n filters?: ImageAdjustment;\n },\n ) {\n const { fit, crop, zoom, anchor, matrix, preset, filters, ...common } = options ?? {};\n // Both are forwarded unresolved: `imageFill.resolve` is the one place\n // that flattens a chain and folds the deprecated prop into the preset,\n // so a fill built here and a fill written as a literal cannot disagree\n // about what a grade means.\n return new FillChain([...this.list, withOptions({\n type: 'image' as const,\n src,\n fit, crop, zoom, anchor, matrix,\n preset, filters,\n }, common)]);\n }\n\n /**\n * Append a video fill from `src`. Plays by default: its source timestamp is\n * derived as it paints, from how long the node carrying the fill has\n * existed — so the clip runs wherever the fill is used (fill, overlay,\n * stroke, shadow, a custom node's `Graphics2D`) with nothing to advance.\n */\n video(src: string, options?: VideoFillOptions) {\n const { fit, crop, zoom, anchor, matrix, preset, filters, timestamp, playing, trimStart, trimEnd, playStart, speed, loop, duration, ...common } = options ?? {};\n return new FillChain([...this.list, withOptions({\n type: 'video' as const,\n src,\n fit, crop, zoom, anchor, matrix, preset, filters,\n timestamp,\n playing: playing ?? true,\n trimStart, trimEnd, playStart, speed, loop, duration,\n }, common)]);\n }\n\n\n /** Append a linear gradient between `colors`. */\n linearGradient(colors: Color[], options?: FillOptions & { stops?: number[]; start?: Vector2; end?: Vector2 }) {\n const { stops, start, end, ...common } = options ?? {};\n return new FillChain([...this.list, withOptions({ type: 'linear-gradient' as const, colors, stops, start, end }, common)]);\n }\n\n /** Append a radial gradient between `colors`. */\n radialGradient(colors: Color[], options?: FillOptions & { stops?: number[]; center?: Vector2; radius?: number }) {\n const { stops, center, radius, ...common } = options ?? {};\n return new FillChain([...this.list, withOptions({ type: 'radial-gradient' as const, colors, stops, center, radius }, common)]);\n }\n\n /** Append a conic gradient between `colors`. */\n conicGradient(colors: Color[], options?: FillOptions & { stops?: number[]; center?: Vector2; startAngle?: number }) {\n const { stops, center, startAngle, ...common } = options ?? {};\n return new FillChain([...this.list, withOptions({ type: 'conic-gradient' as const, colors, stops, center, startAngle }, common)]);\n }\n\n /** Append a noise (speckle) fill. Tween `seed` to make the static crawl. */\n noise(options?: FillOptions & { size?: Vector2; density?: number; color?: Color; seed?: number }) {\n const { size, density, color, seed, ...common } = options ?? {};\n return new FillChain([...this.list, withOptions({ type: 'noise' as const, size, density, color, seed }, common)]);\n }\n\n /**\n * Append a fractal (fBm) noise fill — a continuous field rather than the\n * speckle {@link noise} paints. Cloud, marble, smoke, terrain, plasma.\n *\n * Tween `offset` to travel through the field (it flows); tween `seed` to\n * shift to a different field entirely (it churns).\n */\n fractalNoise(options?: FillOptions & Omit<FractalNoiseFillProp, 'type' | 'opacity' | 'blend'>) {\n const {\n basis, octaves, frequency, lacunarity, gain, seed, offset, angle,\n colors, stops, contrast, ...common\n } = options ?? {};\n return new FillChain([...this.list, withOptions(\n {\n type: 'fractalNoise' as const,\n basis, octaves, frequency, lacunarity, gain, seed, offset, angle,\n colors, stops, contrast,\n },\n common,\n )]);\n }\n\n /**\n * Append a custom shader fill — the escape hatch past {@link noise} and\n * {@link fractalNoise}, where the author writes the fragment function.\n *\n * The WGSL `source` defines `fn fill(in: FillIn) -> vec4f` and declares its\n * uniforms as `struct Params`, read as `u.<name>`. It returns\n * **premultiplied** rgba, without folding `opacity` in (the layer's opacity is\n * already applied, so applying it twice squares it). Uniforms are keyed by\n * their declared name, so order is irrelevant.\n *\n * Keep `source` constant — it is the compile-cache key, so it snaps at a\n * tween's midpoint and rebuilding it per frame compiles a program per frame.\n * Everything that changes belongs in a uniform, which is an in-place write.\n *\n * @example\n * Fills.shader(GLOW, { uniforms: { amount: 0.6 } })\n */\n shader(\n source: string | FillShader,\n options?: FillOptions\n & Omit<ShaderFillProp, 'type' | 'source' | 'language' | 'opacity' | 'blend' | 'shaderId'>\n & { values?: ShaderPropertyValues },\n ) {\n const pack = typeof source === 'string' ? undefined : source;\n if (pack && pack.scope !== 'fill') {\n throw new Error(\n `Fills.shader was given a \"${(pack as { scope: string }).scope}\" shader ` +\n `(\"${pack.name}\"). An effect shader samples a backdrop a fill does not have; ` +\n `use Effects.shader.`,\n );\n }\n const { uniforms, textures, values, ...common } = options ?? {};\n // A pack resolves to plain uniforms here; anything passed as `uniforms`\n // still wins, matching how an author value overrides a built-in.\n const resolved = pack\n ? { ...resolveShaderProperties(pack, values), ...normalizeUniforms(uniforms ?? {}) }\n : uniforms;\n return new FillChain([...this.list, withOptions(\n {\n type: 'shader' as const,\n source: typeof source === 'string' ? source : source.source,\n language: 'wgsl' as const,\n uniforms: resolved,\n textures,\n ...(pack?.id !== undefined ? { shaderId: pack.id } : {}),\n },\n common,\n )]);\n }\n\n /** Append a stripe (hatch) fill. */\n stripe(options?: FillOptions & { gap?: number; strokeWidth?: number; angle?: number; color?: Color }) {\n const { gap, strokeWidth, angle, color, ...common } = options ?? {};\n return new FillChain([...this.list, withOptions({ type: 'stripe' as const, gap, strokeWidth, angle, color }, common)]);\n }\n\n /**\n * Append a dot-grid fill — a lattice of dots at a pixel pitch.\n *\n * Tween `offset` to drift the field under a shape that isn't moving; tween\n * `spacing` or `radius` to breathe it.\n *\n * @example\n * Fills.dotGrid({ radius: 1.5, spacing: 24, color: 'muted' })\n */\n dotGrid(options?: FillOptions & Omit<DotGridFillProp, 'type' | 'opacity' | 'blend'>) {\n const { radius, spacing, offset, color, ...common } = options ?? {};\n return new FillChain([...this.list, withOptions(\n { type: 'dotGrid' as const, radius, spacing, offset, color },\n common,\n )]);\n }\n\n /**\n * Append a grid fill — ruled lines dividing the shape into cells, with an\n * optional finer ruling nested inside each one.\n *\n * Sized in divisions of the shape rather than in px (unlike {@link dotGrid}),\n * so it holds its structure as the shape resizes.\n *\n * @example\n * Fills.grid({ divisions: 8, subdivisions: 4, color: 'border' })\n */\n grid(options?: FillOptions & Omit<GridFillProp, 'type' | 'opacity' | 'blend'>) {\n const {\n divisions, subdivisions, offset, strokeWidth, subdivisionWidth, color, ...common\n } = options ?? {};\n return new FillChain([...this.list, withOptions(\n {\n type: 'grid' as const,\n divisions, subdivisions, offset, strokeWidth, subdivisionWidth, color,\n },\n common,\n )]);\n }\n\n /**\n * Append a 3D scene, painted through the shape's own path.\n *\n * Takes a **built** {@link Scene3D}, never a builder — per-frame freshness\n * comes from where the value is produced (a `renderSelf`, or a `() => …`\n * reactive binding), like every other fill.\n *\n * Note two same-type 3D layers hard-cut rather than cross-fading, because a\n * command list has no meaningful in-between. To dissolve between two scenes,\n * stack them and tween their opacities in opposite directions.\n */\n canvas3D(scene: Scene3D, options?: FillOptions & { maxPixelRatio?: number; antialias?: boolean }) {\n const { maxPixelRatio, antialias, ...common } = options ?? {};\n return new FillChain([...this.list, withOptions({ type: 'canvas3D' as const, scene, maxPixelRatio, antialias }, common)]);\n }\n\n /** Allows spreading the chain into an array: `[...Fills.color('red')]`. */\n *[Symbol.iterator]() {\n yield* this.list;\n }\n\n /** Serializes to the raw fill array so frameworks that call `toJSON` get a plain value. */\n toJSON() {\n return this.list;\n }\n}\n\n/**\n * Accepted shapes for a node's `fill` prop.\n *\n * Can be a single fill, a `FillChain` builder result, an already-resolved\n * {@link FillResolved}, or an array mixing any of these (each chain contributes\n * all its layers in place):\n *\n * 'red' // plain CSS color\n * Fills.image('bg.jpg') // chain\n * ['#e8c584', Fills.image('bg.jpg')]\n * ['#e8c584', ...Fills.image('bg.jpg')]\n * resolvedFills // FillResolved[] passes through\n */\nexport type Fill =\n | FillProp\n | FillResolved\n | FillChain\n | (FillProp | FillResolved | FillChain)[];\n\n/**\n * Entry point for building fill chains fluently.\n *\n * An empty {@link FillChain}, so `Fills.image(src)` *is* `new FillChain().image(src)`\n * — every builder's signature and documentation has one definition, on the\n * class, which is what an editor shows when you hover `Fills.image`. The chain\n * is immutable (each builder returns a new one), so sharing one empty instance\n * as the entry point is safe.\n *\n * @example\n * node.fill = Fills.image('./bg.jpg', { opacity: 0.2 }).color('red', { opacity: 0.3 });\n */\nexport const Fills = new FillChain();\n\n/**\n * Normalises any {@link Fill} value to a plain `FillProp[]`.\n * Used by `resolveFillArray` before resolving to the renderer shape.\n *\n * Already-resolved fills (`FillResolved`) structurally satisfy `FillProp`, so\n * they pass straight through and `resolveFill` re-normalises them idempotently.\n */\nexport function resolveChainFill(fill: Fill | undefined): FillProp[] {\n if (fill == null) return [];\n if (fill instanceof FillChain) return fill.list;\n if (Array.isArray(fill)) {\n // Flatten any chains used as array elements so each contributes its\n // layers in place: `['#e8c584', Fills.image('bg.jpg')]` — and the plain\n // array a chain serializes to, which is how that value reads back out of\n // a stored document.\n const out: FillProp[] = [];\n for (const item of fill) {\n if (item instanceof FillChain) out.push(...item.list);\n else if (Array.isArray(item)) out.push(...resolveChainFill(item as Fill));\n else out.push(item as FillProp);\n }\n return out;\n }\n return [fill as FillProp];\n}\n", "import { Color, NormalizedColor, parseColor } from '../color/parser';\nimport type { BlendMode } from '../blend';\nimport type { FillData } from '../registry';\nimport { lerpNumber } from '@/tween/lerp';\nimport { Vector2 } from '@/attributes/layout/vector2';\n\n/**\n * Ruled lines in both axes — graph paper, a chart's backing, a layout guide, the\n * floor plane of a diagram.\n *\n * Measured in **divisions of the shape**, not in pixels, which is the whole\n * difference between this and {@link DotGridFillProp}: a grid of 8 stays a grid\n * of 8 when the shape resizes, so it reads as structure the figure is built on\n * rather than as a texture laid over it. The cells follow the box — a 16:9 shape\n * divided 8 ways has 8 columns and 8 rows of 16:9 cells — because a grid that\n * kept its cells square would leave a ragged strip down one side of every shape\n * that isn't.\n *\n * {@link subdivisions} nests a finer grid inside each cell, drawn by default at\n * {@link MINOR_WIDTH_RATIO} of the division line's width. Thinner rather than\n * fainter: a half-width line antialiases to a lighter one at any zoom, so the two\n * orders stay distinguishable at every scale without a second colour to keep in\n * sync. {@link subdivisionWidth} overrides that when the default ratio isn't the\n * look wanted.\n */\nexport interface GridFillProp {\n type: 'grid';\n /** How many cells the shape is divided into, per axis. Tween it to zoom the grid. */\n divisions?: number;\n /** How many finer cells nest inside each division. `1` draws no minor lines. */\n subdivisions?: number;\n /** Shifts the whole ruling, in px. */\n offset?: Vector2;\n /** Thickness of a division line, in px. `0` leaves the coarse ruling undrawn. */\n strokeWidth?: number;\n /**\n * Thickness of a subdivision line, in px. Defaults to\n * {@link MINOR_WIDTH_RATIO} of {@link strokeWidth} — so a grid that only\n * states one width still gets two visibly different orders.\n */\n subdivisionWidth?: number;\n color?: Color;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface GridFillResolved {\n type: 'grid';\n divisions: number;\n subdivisions: number;\n offset: Vector2;\n strokeWidth: number;\n subdivisionWidth: number;\n color: NormalizedColor;\n opacity?: number;\n blend?: BlendMode;\n}\n\n/** Quarters, hairline, no minor ruling — the plainest grid that is still one. */\nconst DEFAULT_DIVISIONS = 4;\nconst DEFAULT_SUBDIVISIONS = 1;\nconst DEFAULT_STROKE_WIDTH = 1;\n\n/** How thick a subdivision line is relative to a division one. */\nexport const MINOR_WIDTH_RATIO = 0.5;\n\nexport const gridFill: FillData<GridFillResolved> = {\n resolve: (prop: GridFillProp) => {\n const raw = prop.color ?? ([0, 0, 0, 1] as NormalizedColor);\n const strokeWidth = prop.strokeWidth ?? DEFAULT_STROKE_WIDTH;\n return {\n type: 'grid',\n divisions: prop.divisions ?? DEFAULT_DIVISIONS,\n subdivisions: prop.subdivisions ?? DEFAULT_SUBDIVISIONS,\n offset: prop.offset ?? { x: 0, y: 0 },\n strokeWidth,\n // Derived from the width actually in force rather than from the\n // default, so stating only `strokeWidth: 4` still yields a minor\n // ruling in proportion to it.\n subdivisionWidth: prop.subdivisionWidth ?? strokeWidth * MINOR_WIDTH_RATIO,\n color: Array.isArray(raw) ? (raw as NormalizedColor) : parseColor(raw as string),\n opacity: prop.opacity,\n blend: prop.blend,\n };\n },\n // `divisions` interpolates continuously — a fractional count is a grid caught\n // mid-zoom, which is exactly what tweening one should look like. The renderer\n // rounds `subdivisions` instead, so the minor ruling always nests a whole\n // number of times inside a cell and a tween of it steps rather than sliding\n // the fine lines out of alignment with the coarse ones.\n lerp: (a, b, t) => ({\n divisions: lerpNumber(a.divisions, b.divisions, t),\n subdivisions: lerpNumber(a.subdivisions, b.subdivisions, t),\n offset: {\n x: lerpNumber(a.offset.x, b.offset.x, t),\n y: lerpNumber(a.offset.y, b.offset.y, t),\n },\n strokeWidth: lerpNumber(a.strokeWidth, b.strokeWidth, t),\n subdivisionWidth: lerpNumber(a.subdivisionWidth, b.subdivisionWidth, t),\n color: [\n lerpNumber(a.color[0], b.color[0], t),\n lerpNumber(a.color[1], b.color[1], t),\n lerpNumber(a.color[2], b.color[2], t),\n lerpNumber(a.color[3], b.color[3], t),\n ],\n opacity: lerpNumber(a.opacity ?? 1, b.opacity ?? 1, t),\n }),\n equals: (a, b) =>\n a.divisions === b.divisions &&\n a.subdivisions === b.subdivisions &&\n a.offset.x === b.offset.x && a.offset.y === b.offset.y &&\n a.strokeWidth === b.strokeWidth &&\n a.subdivisionWidth === b.subdivisionWidth &&\n a.color[0] === b.color[0] && a.color[1] === b.color[1] &&\n a.color[2] === b.color[2] && a.color[3] === b.color[3],\n};\n", "import type { FilterData } from \"../registry\";\nimport { lerpNumber } from \"@/tween/lerp\";\n\n/** Scales the overall luminance of the media layer. */\nexport interface ExposureFilter {\n type: 'exposure';\n /** Exposure multiplier. 1 = unchanged, >1 brighter, <1 darker. */\n amount: number;\n}\n\nexport const exposureFilter: FilterData<ExposureFilter> = {\n lerp: (from, to, t) => ({ type: \"exposure\", amount: lerpNumber(from.amount, to.amount, t) }),\n equals: (a, b) => a.amount === b.amount,\n};\n", "import type { FilterData } from \"../registry\";\nimport { lerpNumber } from \"@/tween/lerp\";\n\n/** Applies a Gaussian blur to the media layer. */\nexport interface BlurFilter {\n type: 'blur';\n /** Blur radius in pixels. */\n radius: number;\n}\n\nexport const blurFilter: FilterData<BlurFilter> = {\n lerp: (from, to, t) => ({ type: \"blur\", radius: lerpNumber(from.radius, to.radius, t) }),\n equals: (a, b) => a.radius === b.radius,\n};\n", "import type { FilterData } from \"../registry\";\nimport { lerpNumber } from \"@/tween/lerp\";\n\n/** Desaturates the media layer toward black and white. */\nexport interface GrayscaleFilter {\n type: 'grayscale';\n /** 0 = original, 1 = fully grayscale. */\n amount: number;\n}\n\nexport const grayscaleFilter: FilterData<GrayscaleFilter> = {\n lerp: (from, to, t) => ({ type: \"grayscale\", amount: lerpNumber(from.amount, to.amount, t) }),\n equals: (a, b) => a.amount === b.amount,\n};\n", "import type { FilterData } from \"../registry\";\nimport { lerpNumber } from \"@/tween/lerp\";\n\n/** Multiplies every pixel's alpha channel by `amount`, fading the entire layer. */\nexport interface AlphaFilter {\n type: 'alpha';\n /** 0 = fully transparent, 1 = unchanged. */\n amount: number;\n}\n\nexport const alphaFilter: FilterData<AlphaFilter> = {\n lerp: (from, to, t) => ({ type: \"alpha\", amount: lerpNumber(from.amount, to.amount, t) }),\n equals: (a, b) => a.amount === b.amount,\n};\n", "import type { FilterData } from \"../registry\";\nimport { lerpNumber } from \"@/tween/lerp\";\n\n/**\n * Applies an arbitrary 4×5 color transform.\n *\n * The matrix is row-major with rows [R, G, B, A], each row being\n * [rScale, gScale, bScale, aScale, bias]. Useful for tinting,\n * channel swaps, or any effect not covered by the named filters.\n */\nexport interface ColorMatrixFilter {\n type: 'colorMatrix';\n /** 4×5 row-major color matrix. */\n matrix: number[];\n}\n\nexport const colorMatrixFilter: FilterData<ColorMatrixFilter> = {\n // Lerps each matrix coefficient independently; missing target coefficients\n // hold their source value so partial matrices still animate gracefully.\n lerp: (from, to, t) => ({\n type: \"colorMatrix\",\n matrix: from.matrix.map((v, i) => lerpNumber(v, to.matrix[i] ?? v, t)),\n }),\n equals: (a, b) => a.matrix.length === b.matrix.length && a.matrix.every((v, i) => v === b.matrix[i]),\n};\n", "import type { FilterData } from \"../registry\";\nimport { lerpNumber } from \"@/tween/lerp\";\n\n/** Which color channel(s) a curves adjustment targets. */\nexport type CurvesChannel = 'rgb' | 'r' | 'g' | 'b' | 'a';\n\n/**\n * Remaps pixel values along a tone curve defined by control points.\n *\n * Points are [input, output] pairs in the [0, 1] range. The renderer\n * interpolates a smooth curve through them. Applies to composite RGB\n * by default; set `channel` to target a single channel.\n */\nexport interface CurvesFilter {\n type: 'curves';\n /** Curve control points as [input, output] pairs in [0, 1]. */\n points: [number, number][];\n /** Channel(s) to apply the curve to. Default 'rgb'. */\n channel?: CurvesChannel;\n}\n\nexport const curvesFilter: FilterData<CurvesFilter> = {\n // Channel hard-cuts at t=0.5 because interpolating between channel names\n // would produce meaningless intermediate states.\n lerp: (from, to, t) => ({\n type: \"curves\",\n channel: t < 0.5 ? from.channel : to.channel,\n points: from.points.map(([x, y], i) => {\n const [tx, ty] = to.points[i] ?? [x, y];\n return [lerpNumber(x, tx, t), lerpNumber(y, ty, t)] as [number, number];\n }),\n }),\n equals: (a, b) =>\n a.channel === b.channel &&\n a.points.length === b.points.length &&\n a.points.every(([x, y], i) => x === b.points[i]?.[0] && y === b.points[i]?.[1]),\n};\n", "import type { FilterData } from \"../registry\";\nimport { lerpNumber } from \"@/tween/lerp\";\n\n/**\n * A collection of photographic-style tonal and color adjustments.\n * All fields are optional; omitted fields use their neutral default.\n */\nexport interface ColorAdjustmentFilter {\n type: 'colorAdjustment';\n /** -1 to 1 (0 = unchanged). Shifts the overall lightness without clipping like exposure does. */\n brightness?: number;\n /** 0 to 2 (1 = unchanged). Spreads highlights and shadows further apart. */\n contrast?: number;\n /** 0 to 3 (1 = unchanged). Scales color saturation uniformly. */\n saturation?: number;\n /** Hue rotation in degrees (0 = unchanged), luma-preserving. Wraps at 360. */\n hue?: number;\n /** -1 to 1 (0 = unchanged). Boosts muted colors more than vibrant ones. */\n vibrance?: number;\n /** -1 to 1 (0 = unchanged). Lifts or crushes shadow regions. */\n shadows?: number;\n /** -1 to 1 (0 = unchanged). Brightens or dims highlight regions. */\n highlights?: number;\n /** -1 to 1 (0 = unchanged). Negative = cool (blue), positive = warm (orange). */\n temperature?: number;\n /** -1 to 1 (0 = unchanged). Negative = green shift, positive = magenta shift. */\n tint?: number;\n /** 0 to 1 (0 = none). Darkens the edges of the frame. */\n vignette?: number;\n}\n\nexport const colorAdjustmentFilter: FilterData<ColorAdjustmentFilter> = {\n lerp: (from, to, t) => ({\n type: \"colorAdjustment\",\n brightness: lerpNumber(from.brightness ?? 0, to.brightness ?? 0, t),\n contrast: lerpNumber(from.contrast ?? 1, to.contrast ?? 1, t),\n saturation: lerpNumber(from.saturation ?? 1, to.saturation ?? 1, t),\n hue: lerpNumber(from.hue ?? 0, to.hue ?? 0, t),\n vibrance: lerpNumber(from.vibrance ?? 0, to.vibrance ?? 0, t),\n shadows: lerpNumber(from.shadows ?? 0, to.shadows ?? 0, t),\n highlights: lerpNumber(from.highlights ?? 0, to.highlights ?? 0, t),\n temperature: lerpNumber(from.temperature ?? 0, to.temperature ?? 0, t),\n tint: lerpNumber(from.tint ?? 0, to.tint ?? 0, t),\n vignette: lerpNumber(from.vignette ?? 0, to.vignette ?? 0, t),\n }),\n equals: (a, b) =>\n a.brightness === b.brightness &&\n a.contrast === b.contrast &&\n a.saturation === b.saturation &&\n a.hue === b.hue &&\n a.vibrance === b.vibrance &&\n a.shadows === b.shadows &&\n a.highlights === b.highlights &&\n a.temperature === b.temperature &&\n a.tint === b.tint &&\n a.vignette === b.vignette,\n};\n", "import type { FilterData } from \"../registry\";\nimport { lerpNumber } from \"@/tween/lerp\";\n\n/**\n * Resamples a video fill to a lower frame rate, holding each source frame for a\n * `1 / fps` interval — the \"stop-motion\" / stutter look (After Effects' Posterize\n * Time). Purely temporal: it changes *which* source timestamp is shown, not the\n * pixels, so it is consumed in the video fill's per-frame `update()` (it never\n * reaches the pixel-filter / `setImageFilter` path). No-op on image fills.\n */\nexport interface PosterizeTimeFilter {\n type: 'posterizeTime';\n /** Target frame rate the source playhead snaps to, in frames per second. */\n fps: number;\n}\n\nexport const posterizeTimeFilter: FilterData<PosterizeTimeFilter> = {\n lerp: (from, to, t) => ({ type: \"posterizeTime\", fps: lerpNumber(from.fps, to.fps, t) }),\n equals: (a, b) => a.fps === b.fps,\n};\n", "import type { FilterData } from \"../registry\";\nimport type { BlendMode } from \"../../fill/blend\";\nimport { lerpNumber } from \"@/tween/lerp\";\n\n/**\n * Composites the current video frame with a trail of past frames (After Effects'\n * Echo), each delayed by `delay` seconds and faded by a `decay` factor. Needs\n * several decoded frames at once, so — unlike the pixel filters — it is rendered\n * by a dedicated multi-pass path in the video fill renderer rather than the\n * `setImageFilter` chain. Video-only; a no-op on image fills.\n *\n * The trail reaches back `echoes * delay` source seconds; frames outside the\n * adapter's decoded back-window are simply skipped (the trail fills in over the\n * first second of playback after a cold seek).\n */\nexport interface VideoEchoFilter {\n type: 'echo';\n /** Number of past-frame taps drawn behind the current frame. */\n echoes: number;\n /** Delay between successive taps, in source seconds. */\n delay: number;\n /** Per-tap alpha multiplier; tap `n` is drawn at `decay ** n`. Default 0.5. */\n decay?: number;\n /** Blend mode used to composite the echo taps. Default `'screen'`. */\n blend?: BlendMode;\n}\n\nexport const echoFilter: FilterData<VideoEchoFilter> = {\n lerp: (from, to, t) => ({\n type: \"echo\",\n echoes: Math.round(lerpNumber(from.echoes, to.echoes, t)),\n delay: lerpNumber(from.delay, to.delay, t),\n decay: lerpNumber(from.decay ?? 0.5, to.decay ?? 0.5, t),\n // Blend is a discrete enum, so it hard-cuts at the midpoint.\n blend: t < 0.5 ? from.blend : to.blend,\n }),\n equals: (a, b) =>\n a.echoes === b.echoes &&\n a.delay === b.delay &&\n (a.decay ?? 0.5) === (b.decay ?? 0.5) &&\n a.blend === b.blend,\n};\n", "import { MediaAdjustment, VideoOnlyAdjustment } from \"./union\";\nimport { declareEffect, effectSurface, hasEffect, lerpEffect } from \"../effects/registry\";\nimport type { NodeEffect } from \"../effects/union\";\nimport type { AssetScope } from \"@/assets/scope\";\n\nimport { exposureFilter } from \"./implementations/exposure\";\nimport { blurFilter } from \"./implementations/blur\";\nimport { grayscaleFilter } from \"./implementations/grayscale\";\nimport { alphaFilter } from \"./implementations/alpha\";\nimport { colorMatrixFilter } from \"./implementations/color-matrix\";\nimport { curvesFilter } from \"./implementations/curves\";\nimport { colorAdjustmentFilter } from \"./implementations/color-adjustment\";\nimport { posterizeTimeFilter } from \"./implementations/posterize-time\";\nimport { echoFilter } from \"./implementations/echo\";\n\n/** Any concrete filter object accepted on a media fill — pixel or video-only. */\nexport type AnyFilter = MediaAdjustment | VideoOnlyAdjustment;\n\n/** Interpolation and equality contract every filter implementation must implement. */\nexport interface FilterData<T extends AnyFilter> {\n /** Return a new filter linearly interpolated between `from` and `to` at progress `t` (0–1). */\n lerp(from: T, to: T, t: number): T;\n /** Return true when both filters are visually identical (used to skip redundant redraws). */\n equals(a: T, b: T): boolean;\n}\n\n/**\n * Maps each filter `type` to its `FilterData` handler. Statically imported\n * constants (no runtime registration step), mirroring the `FILLS` map in the\n * fill registry — so the table is always populated and there is no side-effect\n * import to forget.\n *\n * It holds only the filters that exist *solely* as filters. Most of the roster\n * is {@link EffectAdjustment} — a node effect applied to a fill's own pixels — and\n * those are looked up in the effects registry rather than duplicated here, so\n * `dither` interpolates the same way whether it is on a node or on an image.\n */\nconst FILTERS = new Map<string, FilterData<AnyFilter>>([\n [\"exposure\", exposureFilter as FilterData<AnyFilter>],\n [\"blur\", blurFilter as FilterData<AnyFilter>],\n [\"grayscale\", grayscaleFilter as FilterData<AnyFilter>],\n [\"alpha\", alphaFilter as FilterData<AnyFilter>],\n [\"colorMatrix\", colorMatrixFilter as FilterData<AnyFilter>],\n [\"curves\", curvesFilter as FilterData<AnyFilter>],\n [\"colorAdjustment\", colorAdjustmentFilter as FilterData<AnyFilter>],\n [\"posterizeTime\", posterizeTimeFilter as FilterData<AnyFilter>],\n [\"echo\", echoFilter as FilterData<AnyFilter>],\n]);\n\n/**\n * Video-only filter types. These are consumed by the video fill's per-frame\n * `update()` (`posterizeTime`) or a dedicated multi-pass renderer (`echo`),\n * not the pixel filter chain. `isPixelFilter` lets a renderer skip them when\n * composing that chain.\n */\nconst VIDEO_ONLY = new Set<string>([\"posterizeTime\", \"echo\"]);\n\n/** True when `type` is a pixel filter that composes into a media fill's filter chain. */\nexport function isPixelFilter(type: string): boolean {\n return !VIDEO_ONLY.has(type);\n}\n\n/** True when `type` has a registered `FilterData` handler, here or in the effects registry. */\nexport function hasFilter(type: string): boolean {\n return FILTERS.has(type) || hasEffect(type);\n}\n\n/**\n * Interpolate between two individual filters at progress `t`.\n * Falls back to a hard cut at t = 0.5 when the types differ or are unregistered.\n *\n * A type with no dedicated `FilterData` is an {@link EffectAdjustment}, so it is\n * handed to `lerpEffect` — one interpolation per effect, whether it is animated\n * on a node or inside a fill.\n */\nexport function lerpFilter(from: AnyFilter, to: AnyFilter, t: number): AnyFilter {\n if (from.type !== to.type) return t < 0.5 ? from : to;\n const data = FILTERS.get(from.type);\n if (data) return data.lerp(from, to, t);\n return lerpEffect(from as NodeEffect, to as NodeEffect, t) as AnyFilter;\n}\n\n/**\n * The filters defined here reference nothing, but an {@link EffectAdjustment} can —\n * `lut` samples an image — and an undeclared one is a lookup the effect can only\n * read as \"no lookup table\".\n */\nexport function declareFilter(filter: AnyFilter, assets: AssetScope): void {\n if (FILTERS.has(filter.type)) return;\n declareEffect(filter as NodeEffect, assets);\n}\n\n/**\n * How a backend must realise `filter` — `\"shader\"` when it resamples pixel\n * positions and therefore has to wrap the fill's shader rather than compose\n * into its `ImageFilter` chain. The filters defined here are all `\"filter\"`;\n * an {@link EffectAdjustment} answers with its effect's own declaration.\n */\nexport function filterSurface(filter: AnyFilter): \"filter\" | \"shader\" {\n if (FILTERS.has(filter.type)) return \"filter\";\n // A filter is applied to the fill's own pixels, so it is never a backdrop\n // effect however the underlying effect's `mode` predicate reads.\n return effectSurface({ ...filter, mode: \"foreground\" } as NodeEffect);\n}\n\n/**\n * {@link lerpFilterArray} over two *optional* arrays, answering `undefined`\n * when neither side has a filter.\n *\n * A media fill's `lerp` is spread over the whole fill (`{...a, ...lerp(a,b,t)}`),\n * so returning `[]` for the overwhelmingly common no-filter case would allocate\n * a fresh array per fill per frame and turn an absent field into a present one.\n */\nexport function lerpOptionalFilters<T extends AnyFilter>(\n from: T[] | undefined,\n to: T[] | undefined,\n t: number,\n): T[] | undefined {\n if (!from?.length && !to?.length) return undefined;\n return lerpFilterArray(from ?? [], to ?? [], t) as T[];\n}\n\n/**\n * Interpolate between two filter arrays of potentially different lengths.\n * Indices present in only one array are kept as-is; matched indices are lerped pairwise.\n */\nexport function lerpFilterArray(from: AnyFilter[], to: AnyFilter[], t: number): AnyFilter[] {\n const maxLen = Math.max(from.length, to.length);\n const result: AnyFilter[] = [];\n for (let i = 0; i < maxLen; i++) {\n const a = from[i];\n const b = to[i];\n if (a && b) {\n result.push(lerpFilter(a, b, t));\n } else if (a) {\n result.push(a);\n } else if (b) {\n result.push(b);\n }\n }\n return result;\n}\n", "import { MediaAdjustment, VideoOnlyAdjustment } from \"./union\";\nimport { EffectChain } from \"../effects/chain\";\nimport type { BlendMode } from \"../fill/blend\";\nimport type { ColorAdjustmentFilter } from \"./implementations/color-adjustment\";\nimport type { CurvesChannel } from \"./implementations/curves\";\nimport type { EffectOptions } from \"../effects/effect-data\";\nimport type {\n AsciiOptions,\n BitCrushOptions,\n BlockDisplaceOptions,\n BloomOptions,\n BulgeOptions,\n ChromaticAberrationOptions,\n DirectionalBlurOptions,\n DitherOptions,\n DuotoneOptions,\n EdgesOptions,\n GrainOptions,\n HalftoneOptions,\n InvertOptions,\n LutOptions,\n KaleidoscopeOptions,\n OilPaintOptions,\n PixelateOptions,\n PosterizeOptions,\n ProgressiveBlurOptions,\n RadialBlurOptions,\n RgbShiftOptions,\n ScanlinesOptions,\n ScatterOptions,\n SharpenOptions,\n ShaderEffectOptions,\n StreakOptions,\n ThresholdOptions,\n TwirlOptions,\n VignetteOptions,\n VintageOptions,\n WaveOptions,\n} from \"../effects/chain\";\n\n/** Any concrete filter a chain may hold — pixel or video-only. */\ntype AnyFilter = MediaAdjustment | VideoOnlyAdjustment;\n\n/**\n * ## Adjustments and filters are two layers, not two names for one thing\n *\n * An **adjustment** is the unit an author writes: `Adjustments.blur(8)`, one\n * entry in the ordered chain a media fill's `preset` carries. A **filter** is\n * the primitive the renderer realises it as — `BlurFilter`, `CurvesFilter`, and\n * the `FilterData` handlers in `registry.ts`.\n *\n * Most of the time the two are one-to-one, which is what makes the distinction\n * look like pedantry. It isn't: an editor above this layer composes adjustments\n * that have no primitive of their own (a lift/gamma/gain grade is three\n * per-channel `CurvesFilter`s), and one primitive — the LUT's texture lookup —\n * is reached through no chain builder at all. Naming the two layers apart is\n * what lets that mapping be written down instead of assumed.\n *\n * It also settles a collision with no good answer otherwise: the options for\n * `Adjustments.colorAdjustment(…)` are named after the primitive they omit from\n * (`ColorAdjustmentFilterOptions`), because `ColorAdjustmentAdjustmentOptions`\n * is not a name anyone should have to type.\n *\n * ## The builders\n *\n * Media adjustments follow the same one-argument rule as node effects: every\n * builder takes a single options object, and those with one dominant scalar\n * also accept that scalar directly. Field names are the shared vocabulary —\n * `radius` for a pixel distance, `amount` for a 0–1 intensity — so\n * `Adjustments.blur(8)` and `Effects.blur(8)` describe the same quantity.\n *\n * Most of the roster *is* the node-effect roster: an adjustment is an effect\n * applied to one fill layer's own pixels instead of to a node and everything\n * beneath it, so `Adjustments.oilPaint(4)` and `Effects.oilPaint(4)` are the\n * same implementation reached two ways. See {@link EffectAdjustment} for the\n * short list of effects that cannot be adjustments.\n */\n\n/** Gaussian blur. Scalar shorthand sets `radius`. */\nexport interface BlurFilterOptions {\n /** Blur radius in pixels. */\n radius: number;\n}\n\n/** Desaturation. Scalar shorthand sets `amount`. */\nexport interface GrayscaleFilterOptions {\n /** 0 = original, 1 = fully grayscale. */\n amount: number;\n}\n\n/** Alpha (opacity) multiply. Scalar shorthand sets `amount`. */\nexport interface AlphaFilterOptions {\n /** 0 = fully transparent, 1 = unchanged. */\n amount: number;\n}\n\n/** Luminance scale. Scalar shorthand sets `amount`. */\nexport interface ExposureFilterOptions {\n /** Exposure multiplier. 1 = unchanged, >1 brighter, <1 darker. */\n amount: number;\n}\n\n/** Raw 4×5 row-major colour matrix. Array shorthand sets `matrix`. */\nexport interface ColorMatrixFilterOptions {\n /** 4×5 row-major colour matrix: rows R, G, B, A of `[r, g, b, a, bias]`. */\n matrix: number[];\n}\n\n/** Tone curve through control points. */\nexport interface CurvesFilterOptions {\n /** Curve control points as [input, output] pairs in [0, 1]. */\n points: [number, number][];\n /** Channel(s) to apply the curve to (default `'rgb'`). */\n channel?: CurvesChannel;\n}\n\n/** Photographic tonal/colour adjustments. All fields optional. */\nexport type ColorAdjustmentFilterOptions = Omit<ColorAdjustmentFilter, 'type'>;\n\n/** Stop-motion frame-rate resample (video only). Scalar shorthand sets `fps`. */\nexport interface PosterizeTimeFilterOptions {\n /** Target frame rate the source playhead snaps to. */\n fps: number;\n}\n\n/** Motion-trail echo of past frames (video only). */\nexport interface EchoFilterOptions {\n /** Number of past-frame taps drawn behind the current frame. */\n echoes: number;\n /** Delay between successive taps, in source seconds. */\n delay: number;\n /** Per-tap alpha multiplier; tap `n` is drawn at `decay ** n` (default 0.5). */\n decay?: number;\n /** Blend mode used to composite the echo taps (default `'screen'`). */\n blend?: BlendMode;\n}\n\n/**\n * A node effect's builder options as a **filter** accepts them: the same\n * fields minus the cross-cutting {@link EffectOptions} (today `mode`).\n *\n * A filter is on the fill's own pixels by definition, so there is no backdrop\n * to point it at — dropping the knob is clearer than accepting it and silently\n * ignoring it. Scalar shorthands survive untouched.\n */\ntype AsFilterOptions<T> = T extends number ? number : Omit<T, keyof EffectOptions>;\n\n/** Normalise a `number | Options` filter argument onto its dominant field. */\nfunction scalarFilter<O extends object>(arg: number | O, key: keyof O): O {\n return typeof arg === \"number\" ? ({ [key]: arg } as O) : arg;\n}\n\n/**\n * The single effect a one-builder {@link EffectChain} produced.\n *\n * Every effect-backed filter routes through here rather than re-declaring the\n * effect literal, so defaults, scalar shorthands and field normalisation have\n * exactly one definition — the one scenes already use.\n */\nfunction fromEffect(chain: EffectChain): AnyFilter {\n return chain.list[0] as AnyFilter;\n}\n\n/**\n * Immutable, chainable list of media filters — the filters valid on an **image**\n * fill.\n *\n * Each builder method returns a new chain with the filter appended, so chains\n * are safe to share and branch. {@link VideoAdjustmentChain} extends this with the\n * video-only temporal filters; the split is what keeps `posterizeTime` off an\n * image fill, mirroring how `Fill` is structured.\n *\n * @example\n * const chain = Adjustments.blur(4).grayscale(0.5);\n * node.filters = chain; // assign directly\n * node.filters = [...chain, { type: 'alpha', amount: 0.5 }]; // spread into array\n */\nexport class AdjustmentChain {\n constructor(public list: AnyFilter[] = []) { }\n\n /**\n * Append `filter`, returning a chain of the same class — so the video\n * subclass keeps its extra builders reachable after an inherited one.\n */\n protected append(filter: AnyFilter): this {\n const Ctor = this.constructor as new (list: AnyFilter[]) => this;\n return new Ctor([...this.list, filter]);\n }\n\n // -- Filters with no node-effect counterpart -------------------------\n\n /** Append a Gaussian blur. */\n blur(options: number | BlurFilterOptions) {\n const { radius } = scalarFilter(options, \"radius\");\n return this.append({ type: 'blur', radius });\n }\n\n /** Append a grayscale filter. */\n grayscale(options: number | GrayscaleFilterOptions) {\n const { amount } = scalarFilter(options, \"amount\");\n return this.append({ type: 'grayscale', amount });\n }\n\n /** Append an alpha (opacity) filter. */\n alpha(options: number | AlphaFilterOptions) {\n const { amount } = scalarFilter(options, \"amount\");\n return this.append({ type: 'alpha', amount });\n }\n\n /** Append an exposure filter. */\n exposure(options: number | ExposureFilterOptions) {\n const { amount } = scalarFilter(options, \"amount\");\n return this.append({ type: 'exposure', amount });\n }\n\n /** Append a color-adjustment filter from the given partial settings. */\n colorAdjustment(options: ColorAdjustmentFilterOptions) {\n return this.append({ type: 'colorAdjustment', ...options });\n }\n\n /** Append a raw 4×5 row-major color matrix. */\n colorMatrix(options: number[] | ColorMatrixFilterOptions) {\n const matrix = Array.isArray(options) ? options : options.matrix;\n return this.append({ type: 'colorMatrix', matrix });\n }\n\n /** Append a curves filter from control `points` ([input, output] pairs). */\n curves(options: CurvesFilterOptions) {\n return this.append({ type: 'curves', points: options.points, channel: options.channel });\n }\n\n // -- Blur family ------------------------------------------------------\n\n /** Append a directional (linear) blur, smearing the fill along one axis. */\n directionalBlur(options: AsFilterOptions<number | DirectionalBlurOptions>) {\n return this.append(fromEffect(new EffectChain().directionalBlur(options)));\n }\n\n /** Append a radial blur — zoom or spin streaks about a centre point. */\n radialBlur(options?: AsFilterOptions<number | RadialBlurOptions>) {\n return this.append(fromEffect(new EffectChain().radialBlur(options)));\n }\n\n /**\n * Append a progressive blur — a blur that ramps across the fill, for the\n * frosted-toward-one-edge look.\n */\n progressiveBlur(options?: AsFilterOptions<number | ProgressiveBlurOptions>) {\n return this.append(fromEffect(new EffectChain().progressiveBlur(options)));\n }\n\n /** Append a bloom (glow): bright areas bleed soft light outward. */\n bloom(options?: AsFilterOptions<number | BloomOptions>) {\n return this.append(fromEffect(new EffectChain().bloom(options)));\n }\n\n /** Append anamorphic streaks off the fill's highlights. */\n streak(options?: AsFilterOptions<number | StreakOptions>) {\n return this.append(fromEffect(new EffectChain().streak(options)));\n }\n\n /** Append an unsharp-mask sharpen. */\n sharpen(options?: AsFilterOptions<number | SharpenOptions>) {\n return this.append(fromEffect(new EffectChain().sharpen(options)));\n }\n\n // -- Colour -----------------------------------------------------------\n\n /** Append a colour invert (negative). */\n invert(options?: AsFilterOptions<number | InvertOptions>) {\n return this.append(fromEffect(new EffectChain().invert(options)));\n }\n\n /** Append a vintage / film-look grade (sepia + desaturate + warmth). */\n vintage(options?: AsFilterOptions<number | VintageOptions>) {\n return this.append(fromEffect(new EffectChain().vintage(options)));\n }\n\n /** Append a duotone map — remap luminance between two colours. */\n duotone(options?: AsFilterOptions<number | DuotoneOptions>) {\n return this.append(fromEffect(new EffectChain().duotone(options)));\n }\n\n /** Append colour banding: quantize to `levels` tones per channel. */\n posterize(options?: AsFilterOptions<number | PosterizeOptions>) {\n return this.append(fromEffect(new EffectChain().posterize(options)));\n }\n\n /** Append a hard luminance threshold (1-bit black/white). */\n threshold(options?: AsFilterOptions<number | ThresholdOptions>) {\n return this.append(fromEffect(new EffectChain().threshold(options)));\n }\n\n /** Append a bit-depth crush, optionally snapping to a hardware palette. */\n bitCrush(options?: AsFilterOptions<number | BitCrushOptions>) {\n return this.append(fromEffect(new EffectChain().bitCrush(options)));\n }\n\n // -- Texture / pattern ------------------------------------------------\n\n /**\n * Append ordered (Bayer) dithering — quantize to `levels` tones, hiding the\n * banding in a repeating threshold pattern.\n */\n dither(options?: AsFilterOptions<number | DitherOptions>) {\n return this.append(fromEffect(new EffectChain().dither(options)));\n }\n\n /** Append a halftone screen — print-style dots (or lines) sized by tone. */\n halftone(options?: AsFilterOptions<number | HalftoneOptions>) {\n return this.append(fromEffect(new EffectChain().halftone(options)));\n }\n\n /** Append film grain. Animate it by tweening `seed`. */\n grain(options?: AsFilterOptions<number | GrainOptions>) {\n return this.append(fromEffect(new EffectChain().grain(options)));\n }\n\n /** Append a 3D colour lookup table — see {@link EffectChain.lut}. */\n lut(options: AsFilterOptions<LutOptions>) {\n return this.append(fromEffect(new EffectChain().lut(options as LutOptions)));\n }\n\n /** Append CRT-style scanlines. */\n scanlines(options?: AsFilterOptions<number | ScanlinesOptions>) {\n return this.append(fromEffect(new EffectChain().scanlines(options)));\n }\n\n /** Append an After Effects-style Mosaic — `blocks` across the fill. */\n pixelate(options: AsFilterOptions<number | PixelateOptions>) {\n return this.append(fromEffect(new EffectChain().pixelate(options)));\n }\n\n /**\n * Append Kuwahara \"oil paint\" brushwork: average within a region, never\n * across an edge, so flat areas smooth into strokes while edges stay crisp.\n *\n * Cost grows with `radius²` — the most expensive filter in the set.\n */\n oilPaint(options?: AsFilterOptions<number | OilPaintOptions>) {\n return this.append(fromEffect(new EffectChain().oilPaint(options)));\n }\n\n /** Append an ASCII-art remap of the fill through a glyph ramp. */\n ascii(options?: AsFilterOptions<number | AsciiOptions>) {\n return this.append(fromEffect(new EffectChain().ascii(options)));\n }\n\n /** Append an edge-detect pass (Sobel / Prewitt / Laplacian). */\n edges(options?: AsFilterOptions<number | EdgesOptions>) {\n return this.append(fromEffect(new EffectChain().edges(options)));\n }\n\n /** Append a darkened border falling off toward the fill's corners. */\n vignette(options?: AsFilterOptions<number | VignetteOptions>) {\n return this.append(fromEffect(new EffectChain().vignette(options)));\n }\n\n // -- Displacement / lens ----------------------------------------------\n\n /** Append lens-dispersion colour fringing. */\n chromaticAberration(options?: AsFilterOptions<number | ChromaticAberrationOptions>) {\n return this.append(fromEffect(new EffectChain().chromaticAberration(options)));\n }\n\n /** Append a hard per-channel RGB offset (the glitchy cousin of the above). */\n rgbShift(options?: AsFilterOptions<number | RgbShiftOptions>) {\n return this.append(fromEffect(new EffectChain().rgbShift(options)));\n }\n\n /** Append per-pixel random jitter. */\n scatter(options?: AsFilterOptions<number | ScatterOptions>) {\n return this.append(fromEffect(new EffectChain().scatter(options)));\n }\n\n /** Append horizontal band tearing — the datamosh / bad-signal look. */\n blockDisplace(options?: AsFilterOptions<number | BlockDisplaceOptions>) {\n return this.append(fromEffect(new EffectChain().blockDisplace(options)));\n }\n\n /** Append a bulge (barrel) or, with a negative strength, a pinch. */\n bulge(options: AsFilterOptions<number | BulgeOptions>) {\n return this.append(fromEffect(new EffectChain().bulge(options)));\n }\n\n /** Append a twirl (swirl about a centre point). */\n twirl(options?: AsFilterOptions<number | TwirlOptions>) {\n return this.append(fromEffect(new EffectChain().twirl(options)));\n }\n\n /** Append a sine/triangle/square wave warp. */\n wave(options?: AsFilterOptions<number | WaveOptions>) {\n return this.append(fromEffect(new EffectChain().wave(options)));\n }\n\n /** Append a kaleidoscope mirror of the fill about a centre point. */\n kaleidoscope(options?: AsFilterOptions<number | KaleidoscopeOptions>) {\n return this.append(fromEffect(new EffectChain().kaleidoscope(options)));\n }\n\n /** Append a custom shader pass over the fill. */\n shader(options: AsFilterOptions<ShaderEffectOptions>) {\n return this.append(fromEffect(new EffectChain().shader(options)));\n }\n\n /** Allows spreading the chain into an array: `[...Adjustments.blur(5)]`. */\n *[Symbol.iterator]() {\n yield* this.list;\n }\n\n /** Serializes to the raw filter array so frameworks that call `toJSON` get a plain value. */\n toJSON() {\n return this.list;\n }\n}\n\n/**\n * An {@link AdjustmentChain} plus the video-only temporal filters — the\n * filters valid on a **video** fill.\n *\n * @example\n * node.filters = VideoAdjustments.posterizeTime(6).grayscale(1);\n */\nexport class VideoAdjustmentChain extends AdjustmentChain {\n /** Append a posterize-time filter; snaps the video playhead to `fps`. */\n posterizeTime(options: number | PosterizeTimeFilterOptions) {\n const { fps } = scalarFilter(options, \"fps\");\n return this.append({ type: 'posterizeTime', fps });\n }\n\n /** Append an echo (motion-trail) filter over the clip's past frames. */\n echo(options: EchoFilterOptions) {\n return this.append({ type: 'echo', ...options });\n }\n}\n\n/**\n * Accepted shapes for an **image** fill's `filters` prop — a single pixel\n * filter, a plain array of them, or a filter chain. Mirrors how `Fill` is the\n * loose author-facing union for a fill. Video-only filters are excluded here.\n */\nexport type ImageAdjustment = MediaAdjustment | MediaAdjustment[] | AdjustmentChain;\n\n/**\n * Accepted shapes for a **video** fill's `filters` prop — the pixel filters\n * plus the video-only temporal filters (`posterizeTime`, `echo`).\n */\nexport type VideoAdjustment =\n | (MediaAdjustment | VideoOnlyAdjustment)\n | (MediaAdjustment | VideoOnlyAdjustment)[]\n | AdjustmentChain;\n\n/**\n * Entry point for building **image** filter chains fluently.\n *\n * An empty chain, so `Adjustments.blur(8)` is `new AdjustmentChain().blur(8)`\n * — and every builder's signature and documentation has one definition, on\n * {@link AdjustmentChain}, which is what an editor shows on hover.\n *\n * Contains only pixel filters; video-only filters (`posterizeTime`, `echo`)\n * live on {@link VideoAdjustments} because image fills cannot use them.\n *\n * @example\n * node.filters = Adjustments.blur(8).grayscale(1);\n * Rect({ fill: Fills.image('bg.jpg', { filters: Adjustments.oilPaint(4) }) })\n */\nexport const Adjustments = new AdjustmentChain();\n\n/**\n * Entry point for building **video** filter chains fluently — every\n * {@link Adjustments} builder plus the video-only temporal ones.\n *\n * @example\n * node.filters = VideoAdjustments.posterizeTime(6);\n * node.filters = VideoAdjustments.grayscale(1).blur(6);\n */\nexport const VideoAdjustments = new VideoAdjustmentChain();\n\n/**\n * The previous name for {@link Adjustments}.\n *\n * Kept because a scene is *source code in someone else's project*: a rename that\n * only shows up as a compile error in a file we can't edit is still a rename that\n * broke their build. The alias costs one line and buys a release in which both\n * spellings work.\n *\n * @deprecated Use {@link Adjustments}. Removed in the next major.\n */\nexport const ImageFilters = Adjustments;\n\n/**\n * The previous name for {@link VideoAdjustments}.\n *\n * @deprecated Use {@link VideoAdjustments}. Removed in the next major.\n */\nexport const VideoFilters = VideoAdjustments;\n\n/**\n * Normalises any `ImageAdjustment`/`VideoAdjustment` value to a plain filter array.\n * Used internally when reading props before rendering or interpolation.\n */\nexport function resolveChainAdjustments(filters: ImageAdjustment | VideoAdjustment | undefined): AnyFilter[] {\n if (filters === undefined) return [];\n if (filters instanceof AdjustmentChain) return filters.list;\n if (Array.isArray(filters)) return filters;\n return [filters];\n}\n", "import { Vector2, lerpVector2 } from \"./vector2\";\nimport { BoxBounds } from \"@/layout/bounds\";\nimport type { AttributeOps } from \"@/attributes/shared/operators\";\n\n/**\n * Named positions inside a box: the nine alignment keys (`center`, `topLeft`, …).\n * Each maps to a per-axis point in `[-1, 1]`: x is -1 (left) … +1 (right), y is\n * -1 (bottom) … +1 (top) — the y-up convention used throughout layout.\n */\nexport type AlignmentKey =\n | \"center\"\n | \"topLeft\"\n | \"topRight\"\n | \"bottomLeft\"\n | \"bottomRight\"\n | \"topCenter\"\n | \"bottomCenter\"\n | \"centerLeft\"\n | \"centerRight\";\n\n/**\n * A normalised point inside a box — the single value type behind every \"which\n * point of this thing\" prop: `Node2D.pivot` (what it rotates about), a container's\n * `align` (where children sit), a gradient's `center` (where it emits from) and\n * an image fill's `anchor` (which point of the source meets the box).\n *\n * Those props keep distinct names because they position *different things*; what\n * they share is this type, this `[-1, 1]` y-up space, and this vocabulary — so a\n * value read off one can be handed to another and mean the same place.\n *\n * Accepts a named position (`'center'`) or an explicit {@link Vector2}.\n */\nexport type Alignment = AlignmentKey | Vector2;\n\nconst ALIGNMENTS: Record<AlignmentKey, Vector2> = {\n topLeft: { x: -1, y: 1 },\n topCenter: { x: 0, y: 1 },\n topRight: { x: 1, y: 1 },\n centerLeft: { x: -1, y: 0 },\n center: { x: 0, y: 0 },\n centerRight: { x: 1, y: 0 },\n bottomLeft: { x: -1, y: -1 },\n bottomCenter: { x: 0, y: -1 },\n bottomRight: { x: 1, y: -1 },\n};\n\n/** The nine named alignment keys in reading order: top row left to right, then\n * the middle row, then the bottom row. */\nconst ALIGNMENT_KEYS: readonly AlignmentKey[] = Object.keys(ALIGNMENTS) as AlignmentKey[];\n\n// `resolve`'s own logic, pulled out only so the alignment-positioning helpers\n// below can reach it without going through a `this`-bound method call.\nfunction resolveOne(value: Alignment): Vector2 {\n if (typeof value === \"string\") {\n const named = Object.hasOwn(ALIGNMENTS, value) ? ALIGNMENTS[value] : undefined;\n if (!named) {\n throw new Error(`Unknown alignment value: '${value}'`);\n }\n return { ...named };\n }\n return { x: value.x, y: value.y };\n}\n\n/**\n * The alignment attribute's op set: `pivot`, `align`, `center` and `anchor` all\n * use `resolve`/`lerp`. The rest is the shared alignment-*positioning* math for\n * `Node2D` — used by both the constructor (reactive binding form) and a `to()`\n * step (one-shot form): a named alignment (`'topRight'`, `'centerLeft'`, …)\n * resolves to a normalised pivot `a` in `[-1, 1]` (y-up), and landing that\n * alignment on a target scene-space point means the node's centre sits at\n * `target - a·(size/2)` — the inverse of the offset from centre to the\n * alignment. Kept here rather than duplicated between `Node2D`'s constructor\n * and `_prepareStep`.\n */\n\nexport type AlignmentOps = {\n /** The nine named keys in reading order, top-left to bottom-right. */\n readonly keys: readonly AlignmentKey[];\n /** Whether `value` is one of the nine named keys — the strings `resolve` accepts. */\n isKey(value: unknown): value is AlignmentKey;\n /** Validate a node's alignment-positioning props: at most one named alignment, and an\n * alignment cannot be combined with an explicit `pivot` (the alignment derives one). */\n validateProps(props: Record<string, unknown>): void;\n /** The first named alignment key present in `props`, or `undefined` if none. */\n findKey(props: Record<string, unknown>): AlignmentKey | undefined;\n /** Resolve a named alignment + the centre offset that lands it on `target`, given a\n * concrete layout rect. Used by the one-shot `to()` path: returns the pivot to\n * apply plus the absolute `x`/`y` the node's centre must move to. */\n resolveTargetOnce(alignmentKey: AlignmentKey, rect: BoxBounds, target: Vector2): { pivot: Vector2; x: number; y: number };\n /** Reactive binding form used by the constructor: given a (possibly dynamic) target\n * accessor and a live layout-rect accessor, returns the pivot to write plus `x`/`y`\n * binding callbacks that re-evaluate whenever the target or the node's layout changes. */\n bindTarget(alignmentKey: AlignmentKey, getTarget: () => Vector2, getRect: () => BoxBounds): { pivot: Vector2; x: () => number; y: () => number };\n}\nexport const alignmentOps: AttributeOps<Alignment, Vector2> & AlignmentOps = {\n resolve: resolveOne,\n lerp: lerpVector2,\n keys: ALIGNMENT_KEYS,\n\n isKey(value): value is AlignmentKey {\n return typeof value === \"string\" && Object.hasOwn(ALIGNMENTS, value);\n },\n\n validateProps(props) {\n const present = ALIGNMENT_KEYS.filter(k => props[k] !== undefined);\n if (present.length > 1) {\n throw new Error(`Cannot set multiple alignment props at once: ${present.join(', ')}`);\n }\n if (present.length === 1 && props['pivot'] !== undefined) {\n throw new Error(`Cannot set both alignment prop '${present[0]}' and 'pivot' at the same time`);\n }\n },\n\n findKey(props) {\n return ALIGNMENT_KEYS.find(k => props[k] !== undefined);\n },\n\n resolveTargetOnce(alignmentKey, rect, target) {\n const a = resolveOne(alignmentKey);\n return {\n pivot: a,\n x: target.x - a.x * (rect.width / 2),\n y: target.y - a.y * (rect.height / 2),\n };\n },\n\n bindTarget(alignmentKey, getTarget, getRect) {\n const a = resolveOne(alignmentKey);\n return {\n pivot: a,\n x: () => getTarget().x - a.x * (getRect().width / 2),\n y: () => getTarget().y - a.y * (getRect().height / 2),\n };\n },\n};\n", "import { lerpNumber } from \"@/tween/lerp\";\nimport type { AttributeOps } from \"@/attributes/shared/operators\";\nimport type { BoxBounds } from \"@/layout/bounds\";\nimport { Size2D } from \"./size\";\n\n/** Fully resolved per-side edge insets. */\nexport interface InsetsResolved {\n left: number;\n right: number;\n top: number;\n bottom: number;\n}\n\n\nexport type InsetsProps = number | Partial<InsetsResolved> & {\n horizontal?: number;\n vertical?: number;\n};\n\n/**\n * Accepted shapes for a four-sided inset prop.\n *\n * The type is named for the shape (four edge insets), not for one use of it:\n * `Node2D.padding` insets a layout box in pixels, an image fill's `crop` insets a\n * source in fractions. Same value, same shorthands, same tween — different roles,\n * and each prop names its own.\n *\n * Mirrors {@link Fill}: the loose author-facing {@link InsetsProps} (a number or\n * per-side/symmetric object) plus the strict {@link InsetsResolved} — a read-back\n * resolved value structurally satisfies `InsetsProps`, so it passes through\n * `insetsOps.resolve` idempotently and can be assigned straight back.\n *\n * node.padding = 3 // uniform\n * node.padding = { horizontal: 8, top: 4 } // mixed\n * node.padding = otherNode.padding // resolved passes through\n */\nexport type Insets = InsetsProps | InsetsResolved;\n\n\n/**\n * The insets attribute's op set — used by `insetsProperty` and anywhere else a\n * four-sided inset (padding, an image fill's `crop`, …) resolves and tweens.\n *\n * `insetBounds` computes the inner content area produced by subtracting a\n * resolved inset from an outer size — pure, works for any width/height pair,\n * with `x`/`y` carrying the offset of the inner-area center relative to the\n * outer-area center. `outsetSize` is its inverse: adds padding back onto\n * an inner size to get the outer size that contains it.\n */\n\nexport interface InsetsOps {\n\n insetBounds(outerWidth: number, outerHeight: number, pad: InsetsResolved): BoxBounds;\n outsetSize(innerWidth: number, innerHeight: number, pad: InsetsResolved): Size2D;\n}\n\nexport const insetsOps: AttributeOps<InsetsProps, InsetsResolved> & InsetsOps = {\n resolve: (value: InsetsProps, previous?: InsetsResolved): InsetsResolved => {\n if (typeof value === \"number\") {\n return { left: value, right: value, top: value, bottom: value };\n }\n\n // Fallback resolution order: Specific side -> Symmetric shortcut -> Previous fallback -> Default 0\n return {\n left: value.left ?? value.horizontal ?? previous?.left ?? 0,\n right: value.right ?? value.horizontal ?? previous?.right ?? 0,\n top: value.top ?? value.vertical ?? previous?.top ?? 0,\n bottom: value.bottom ?? value.vertical ?? previous?.bottom ?? 0,\n };\n },\n lerp: (from: InsetsResolved, to: InsetsResolved, t: number): InsetsResolved => {\n return {\n left: lerpNumber(from.left, to.left, t),\n right: lerpNumber(from.right, to.right, t),\n top: lerpNumber(from.top, to.top, t),\n bottom: lerpNumber(from.bottom, to.bottom, t),\n };\n },\n insetBounds: (outerWidth, outerHeight, pad) => ({\n width: Math.max(0, outerWidth - pad.left - pad.right),\n height: Math.max(0, outerHeight - pad.top - pad.bottom),\n x: (pad.left - pad.right) / 2,\n y: (pad.top - pad.bottom) / 2,\n }),\n outsetSize: (innerWidth, innerHeight, pad) => ({\n width: innerWidth + pad.left + pad.right,\n height: innerHeight + pad.top + pad.bottom,\n }),\n};\n", "import { lerpNumber } from \"@/tween/lerp\";\nimport type { AssetScope } from \"@/assets/scope\";\nimport { declareFilter, lerpFilterArray } from \"../filters/registry\";\nimport { resolveChainAdjustments } from \"../filters/chain\";\nimport type { ImageAdjustment, VideoAdjustment } from \"../filters/chain\";\nimport type { MediaAdjustment, VideoOnlyAdjustment } from \"../filters/union\";\n\n/**\n * A **preset**: the grade a media fill carries — an ordered chain of\n * adjustments plus one dry/wet mix.\n *\n * This replaces the bare `filters` array a media fill used to take, and the\n * reason it is a wrapper rather than a second sibling prop is `intensity`. A\n * grade is authored as a *look*, and the question asked of a look constantly is\n * \"the same, but less\" — which is one number about the whole chain, not a number\n * to be smeared back across every adjustment in it. Scaling each adjustment\n * toward its own neutral is the approximation you are forced into when the\n * renderer can't mix; here it can, so it does, and \"50% of this LUT\" means\n * exactly what it says.\n *\n * The old `filters` prop is still accepted and folded in — see\n * {@link resolveMediaPreset}.\n */\nexport interface MediaPresetProp {\n /** The chain: one adjustment, a plain array, or an {@link AdjustmentChain}. */\n adjustments?: ImageAdjustment;\n /**\n * How much of the grade to apply, 0–1. Defaults to 1.\n *\n * A real mix against the ungraded pixels, not a scaling of the chain's own\n * values.\n */\n intensity?: number;\n}\n\n/** {@link MediaPresetProp} for a video fill, which also admits the temporal adjustments. */\nexport interface VideoPresetProp {\n adjustments?: VideoAdjustment;\n intensity?: number;\n}\n\n/** A preset with its chain flattened and its mix defaulted. */\nexport interface MediaPresetResolved<A = MediaAdjustment> {\n adjustments: A[];\n intensity: number;\n}\n\n/** The preset a fill has when it says nothing — no chain, fully wet. */\nconst NEUTRAL: MediaPresetResolved<never> = { adjustments: [], intensity: 1 };\n\n/**\n * Normalise a fill's grade, folding in the deprecated `filters` prop.\n *\n * `undefined` — not an empty preset — when there is no grade at all, because a\n * media fill with no adjustments takes a cheaper path through the renderer and\n * an always-present key would take every ungraded image in a project off it.\n * The same rule `crop` follows one level up.\n *\n * `filters` loses to `adjustments` when a fill somehow carries both: the new\n * spelling is the one the author reached for most recently.\n */\nexport function resolveMediaPreset(\n preset: MediaPresetProp | VideoPresetProp | undefined,\n legacyFilters?: ImageAdjustment | VideoAdjustment,\n): MediaPresetResolved<MediaAdjustment | VideoOnlyAdjustment> | undefined {\n const chain = preset?.adjustments ?? legacyFilters;\n const adjustments = resolveChainAdjustments(chain);\n if (adjustments.length === 0) return undefined;\n return {\n adjustments,\n // Clamped rather than trusted: an intensity outside 0–1 would make the\n // renderer's mix extrapolate past the graded image, which is a look\n // nobody asked for and no control can produce.\n intensity: Math.min(1, Math.max(0, preset?.intensity ?? 1)),\n };\n}\n\n/**\n * Interpolate two presets.\n *\n * The chain lerps pairwise (see {@link lerpFilterArray}) and the mix lerps as a\n * number, so a grade can be animated either way — by moving the adjustments'\n * own values, or by moving `intensity`.\n *\n * **An absent preset is read as the other side's chain at `intensity: 0`**, not\n * as an empty chain. That is the whole reason the mix is worth having, and it\n * fixes something the bare `filters` array could not express: `lerpFilterArray`\n * keeps an index present on only one side *as-is*, so tweening a fill from\n * grayscaled to ungraded used to hold the grayscale at full strength for the\n * entire tween and then cut. Holding the chain and fading the mix is what\n * \"remove this grade over half a second\" has always meant.\n */\nexport function lerpMediaPreset<A extends MediaAdjustment | VideoOnlyAdjustment>(\n a: MediaPresetResolved<A> | undefined,\n b: MediaPresetResolved<A> | undefined,\n t: number,\n): MediaPresetResolved<A> | undefined {\n if (!a && !b) return undefined;\n const from = a ?? { adjustments: b!.adjustments, intensity: 0 };\n const to = b ?? { adjustments: a!.adjustments, intensity: 0 };\n return {\n adjustments: lerpFilterArray(from.adjustments, to.adjustments, t) as A[],\n intensity: lerpNumber(from.intensity, to.intensity, t),\n };\n}\n\nexport function declareMediaPreset(\n preset: MediaPresetResolved<MediaAdjustment | VideoOnlyAdjustment> | undefined,\n assets: AssetScope,\n): void {\n for (const adjustment of preset?.adjustments ?? []) declareFilter(adjustment, assets);\n}\n\n/** The neutral preset, for a reader that would rather not branch on `undefined`. */\nexport function neutralPreset<A>(): MediaPresetResolved<A> {\n return NEUTRAL as MediaPresetResolved<A>;\n}\n", "import type { BlendMode } from '../blend';\nimport type { MediaAdjustment } from '../../filters/union';\nimport type { ImageAdjustment } from '../../filters/chain';\nimport type { FillData } from '../registry';\nimport {\n declareMediaPreset,\n lerpMediaPreset,\n resolveMediaPreset,\n type MediaPresetProp,\n type MediaPresetResolved,\n} from '../media-preset';\nimport { Alignment, alignmentOps } from '@/attributes/layout/alignment';\nimport { Insets, InsetsResolved, insetsOps } from '@/attributes/layout/insets';\nimport { Vector2, lerpVector2 } from '@/attributes/layout/vector2';\nimport { lerpNumber } from '@/tween/lerp';\n\n/**\n * How an image (or video frame) is scaled into its node's bounds.\n *\n * - `'fill'` — scale uniformly to cover the bounds, cropping the overflow.\n * The Figma-style default; no distortion, no letterboxing.\n * - `'fit'` — scale uniformly to be fully contained, letterboxing as needed.\n * - `'tile'` — repeat the image at its native size (× `zoom`).\n * - `'stretch'`— scale each axis independently to fill the bounds exactly,\n * distorting the aspect ratio.\n */\nexport type ImageFit = 'fill' | 'fit' | 'tile' | 'stretch';\n\n/**\n * A raw image→shape matrix (3×3, row-major) as a 9-element `Float32Array` or a\n * 3×3 nested array. The escape hatch: see {@link ImageFillProp.matrix}.\n */\nexport type ImageMatrix = Float32Array | number[][];\n\n/**\n * A rectangular window onto the source, as **fractions of the source's own\n * size** (0–1) inset from each edge: `{ left: 0.25 }` discards the left quarter.\n *\n * Fractions rather than pixels so a crop is resolution-independent — the same\n * value reads identically at 1× and 4K, and survives swapping `src` for a\n * differently-sized asset. Everything downstream (`fit`, `zoom`, `anchor`) then\n * treats the cropped window *as if it were the whole image*, so a crop composes\n * with the fit modes instead of fighting them.\n *\n * Reuses the {@link Insets} shape, so the shorthands come free — and so do\n * `insetsOps.resolve`/`insetsOps.lerp`, which is what makes a crop tween:\n * `0.1` · `{ horizontal: 0.2 }` · `{ left: 0.1, top: 0.05 }`.\n */\nexport type ImageCrop = Insets;\n\nexport interface ImageFillProp {\n type: 'image';\n src: string;\n\n /** How the (cropped) image is scaled into the node's bounds. Defaults to `'fill'`. */\n fit?: ImageFit;\n\n /**\n * Window onto the source, applied **before** `fit` — see {@link ImageCrop}.\n *\n * Not honoured by `fit: 'tile'`: the shader repeats the whole texture, so\n * there is no way to tile a sub-rect of it.\n */\n crop?: ImageCrop;\n\n /**\n * Magnification applied **on top of** whatever `fit` resolved. `1` (the\n * default) is the fitted size, `2` twice that, `0.5` half.\n *\n * A multiplier rather than an absolute scale so it stays meaningful under\n * every mode and at any node size: `zoom: 2` means \"twice as big as it would\n * otherwise be\" whether the fit was cover, contain or native tiling. Under\n * `'tile'` the fitted scale is 1 (native size), so `zoom` there is the tile\n * size multiplier.\n */\n zoom?: number;\n\n /**\n * The point held fixed as `zoom` scales, and the alignment of the image\n * inside the bounds when it doesn't cover them. Defaults to `'center'`.\n *\n * The same `[-1, 1]` y-up space as `pivot`/`align` (so `'topLeft'`,\n * `'centerRight'` and `{ x, y }` all work, through the same `alignmentOps.resolve`).\n * The named point of the source lands on the same named point of the box:\n * `anchor: 'topLeft'` pins the source's top-left corner to the box's, so\n * zooming grows away from it. At the default centre this reproduces the\n * classic centred cover/contain placement exactly.\n *\n * Ignored by `'tile'` (a repeating texture has no corner to pin) and inert\n * under `'stretch'` at `zoom: 1` (the image already fills both axes).\n */\n anchor?: Alignment;\n\n /**\n * Raw image→shape matrix. The escape hatch: it wins outright, bypassing\n * `crop`/`fit`/`zoom`/`anchor` **and** the shape bounds, so it must carry the\n * translation itself. Named `matrix` rather than `transform` because a node's\n * `transform` is its x/y/scale/rotation; this is specifically the 3×3 that\n * maps image pixels into the shape's local space.\n */\n matrix?: ImageMatrix;\n\n /** The grade laid over this picture — see {@link MediaPresetProp}. */\n preset?: MediaPresetProp;\n /**\n * @deprecated Moved to `preset.adjustments`. Still read, and folded into the\n * preset on resolve, so a scene written against the old prop keeps grading\n * the way it did. Removed in the next major.\n */\n filters?: ImageAdjustment;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface ImageFillResolved {\n type: 'image';\n src: string;\n fit?: ImageFit;\n /** Fractional insets, all four sides present. */\n crop?: InsetsResolved;\n zoom?: number;\n /** Normalised `[-1, 1]` y-up point. */\n anchor?: Vector2;\n matrix?: ImageMatrix;\n /** Absent when the fill is ungraded — see {@link resolveMediaPreset}. */\n preset?: MediaPresetResolved<MediaAdjustment>;\n opacity?: number;\n blend?: BlendMode;\n}\n\n/** Zero crop — the whole source. Shared by the lerp when only one side crops. */\nconst NO_CROP: InsetsResolved = { left: 0, right: 0, top: 0, bottom: 0 };\n/** The default anchor, resolved. */\nconst CENTER: Vector2 = { x: 0, y: 0 };\n\n/**\n * Normalise the loose author-facing shapes once, so the backend's matrix builder\n * reads plain resolved values (`crop` always four sides, `anchor` always a\n * vector) rather than re-deriving them per frame.\n */\n/** @internal */\nexport function resolveImagePlacement(\n prop: { crop?: ImageCrop; anchor?: Alignment },\n): { crop?: InsetsResolved; anchor?: Vector2 } {\n return {\n crop: prop.crop === undefined ? undefined : insetsOps.resolve(prop.crop),\n anchor: prop.anchor === undefined ? undefined : alignmentOps.resolve(prop.anchor),\n };\n}\n\n/**\n * Interpolate the placement props shared by the image and video fills. Kept in\n * one place so the two fills cannot drift — they describe the same geometry and\n * are consumed by the same `computeImageMatrix`.\n */\n/** @internal */\nexport function lerpImagePlacement(\n a: { crop?: InsetsResolved; zoom?: number; anchor?: Vector2; matrix?: ImageMatrix },\n b: { crop?: InsetsResolved; zoom?: number; anchor?: Vector2; matrix?: ImageMatrix },\n t: number,\n): { crop?: InsetsResolved; zoom: number; anchor: Vector2; matrix?: ImageMatrix } {\n return {\n // A raw matrix is not interpolable geometry — it snaps (at the midpoint,\n // like `fit`), and authors who want a moving matrix bind the prop to a\n // thunk instead.\n matrix: t < 0.5 ? a.matrix : b.matrix,\n // Stay `undefined` when neither side crops, so an uncropped fill keeps\n // taking the cheap path and reads back as it was authored.\n crop: a.crop || b.crop ? insetsOps.lerp(a.crop ?? NO_CROP, b.crop ?? NO_CROP, t) : undefined,\n zoom: lerpNumber(a.zoom ?? 1, b.zoom ?? 1, t),\n anchor: lerpVector2(a.anchor ?? CENTER, b.anchor ?? CENTER, t),\n };\n}\n\nexport const imageFill: FillData<ImageFillResolved> = {\n // `crop`/`anchor` are destructured out before the spread: an optional prop\n // re-added by a later spread widens to a *union* of both types, so leaving\n // them in would type the resolved crop as `ImageCrop | InsetsResolved`.\n // `filters` is destructured out alongside them: it is the deprecated spelling\n // of the grade, folded into `preset` here, and letting it through the spread\n // would leave a stale array on the resolved fill for the renderer to find.\n resolve: ({ crop, anchor, preset, filters, ...prop }: ImageFillProp): ImageFillResolved => ({\n ...prop,\n ...resolveImagePlacement({ crop, anchor }),\n preset: resolveMediaPreset(preset, filters) as\n | MediaPresetResolved<MediaAdjustment>\n | undefined,\n }),\n lerp: (a, b, t) => ({\n src: t < 0.5 ? a.src : b.src,\n fit: t < 0.5 ? a.fit : b.fit,\n ...lerpImagePlacement(a, b, t),\n opacity: (a.opacity ?? 1) + ((b.opacity ?? 1) - (a.opacity ?? 1)) * t,\n // The grade animates with the fill. Leaving it out let `lerpFill`'s\n // `{...a, ...lerp()}` spread carry the *from* fill's grade for the whole\n // tween, so tweening a fill from `grayscale(0)` to `grayscale(1)` did\n // nothing until the prop snapped to the target at the end.\n preset: lerpMediaPreset(a.preset, b.preset, t),\n }),\n equals: (a, b) => a.src === b.src,\n declare: (fill, assets) => {\n assets.image(fill.src);\n declareMediaPreset(fill.preset, assets);\n },\n};\n", "import type { BlendMode } from '../blend';\nimport type { MediaAdjustment, VideoOnlyAdjustment } from '../../filters/union';\nimport type { PosterizeTimeFilter } from '../../filters/implementations/posterize-time';\nimport type { FillData } from '../registry';\nimport type { ImageCrop, ImageFit, ImageMatrix } from './image';\nimport { lerpImagePlacement, resolveImagePlacement } from './image';\nimport type { Alignment } from '@/attributes/layout/alignment';\nimport type { InsetsResolved } from '@/attributes/layout/insets';\nimport type { Vector2 } from '@/attributes/layout/vector2';\nimport { lerpNumber } from '@/tween/lerp';\nimport type { VideoAdjustment } from '../../filters/chain';\nimport {\n declareMediaPreset,\n lerpMediaPreset,\n resolveMediaPreset,\n type MediaPresetResolved,\n type VideoPresetProp,\n} from '../media-preset';\n\n/** Adjustments a video fill carries — the pixel ones plus the video-only ones. */\ntype VideoFillFilter = MediaAdjustment | VideoOnlyAdjustment;\n\nexport interface VideoFillProp {\n type: 'video';\n src: string;\n /** How the (cropped) frame is scaled into the node's bounds. Defaults to `'fill'`. */\n fit?: ImageFit;\n /** Window onto the source frame, applied before `fit`. See {@link ImageCrop}. */\n crop?: ImageCrop;\n /** Magnification on top of the fitted scale. See {@link ImageFillProp.zoom}. */\n zoom?: number;\n /** The point held fixed as `zoom` scales. See {@link ImageFillProp.anchor}. */\n anchor?: Alignment;\n /** Raw frame→shape matrix; wins over everything above. See {@link ImageFillProp.matrix}. */\n matrix?: ImageMatrix;\n /**\n * Source time to paint, in seconds — an **explicit override**. Omit it (the\n * default) and the timestamp is derived at draw time from how long the node\n * painting the fill has existed, so a video fill plays on its own wherever\n * it is used (fill, overlay, stroke, shadow, a raw `Graphics2D` in a custom\n * node) with nothing to wire up. Set it to drive the playhead yourself —\n * e.g. tween it to scrub the clip.\n *\n * Pass `null` to hand the playhead back to the clock: `Node2D.set` skips\n * `undefined` values (it merges a partial), so `null` is what un-does an\n * override that is already live.\n */\n timestamp?: number | null;\n /** Whether the derived timestamp advances with the node's clock. Default `true`. */\n playing?: boolean;\n trimStart?: number;\n trimEnd?: number;\n /**\n * Seconds after the painting node appears before playback begins (default\n * `0`). Use it when the fill joins a node that already existed — a video\n * cross-faded in at 4s into a node's life would otherwise open 4s into the\n * clip. Negative values start the clip already in progress.\n */\n playStart?: number;\n speed?: number;\n /** The grade laid over this footage — see {@link VideoPresetProp}. */\n preset?: VideoPresetProp;\n /**\n * @deprecated Moved to `preset.adjustments`. Still read and folded into the\n * preset on resolve. Removed in the next major.\n */\n filters?: VideoAdjustment;\n loop?: 'forward' | 'reverse' | 'none';\n duration?: number;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface VideoFillResolved {\n type: 'video';\n src: string;\n fit?: ImageFit;\n crop?: InsetsResolved;\n zoom?: number;\n anchor?: Vector2;\n matrix?: ImageMatrix;\n /** Explicit source time, or `undefined`/`null` to derive it — see {@link VideoFillProp.timestamp}. */\n timestamp?: number | null;\n playing: boolean;\n trimStart?: number;\n trimEnd?: number;\n playStart?: number;\n speed?: number;\n /** Absent when the fill is ungraded — see {@link resolveMediaPreset}. */\n preset?: MediaPresetResolved<VideoFillFilter>;\n loop?: 'forward' | 'reverse' | 'none';\n duration?: number;\n opacity?: number;\n blend?: BlendMode;\n}\n\n/**\n * The source time a video fill paints at, given `elapsed` — how long the node\n * painting it has existed (`NodeRenderState.elapsed`).\n *\n * A pure function of the fill and the clock, called by the backend as it paints,\n * the same way a motion blur is resolved against the node's sampled velocity.\n * Deriving it at draw time (rather than advancing a stored timestamp each tick)\n * is what lets a video fill play anywhere paint is accepted — stroke, shadow,\n * a text run, a component's raw `Graphics2D` — instead of only on the two\n * nodes that remembered to update it. It also makes frame *N* identical however\n * the playhead reached it, so scrubbing and export agree with playback.\n *\n * `sourceDuration` is the clip's real length in seconds, used to resolve the\n * `trimEnd` default and the loop cycle. Pass `undefined` (or a non-positive\n * value) when it isn't known yet — playback then runs linearly and unlooped,\n * which is what a decoder that hasn't opened the container can honour anyway.\n */\nexport function resolveVideoTimestamp(\n fill: VideoFillResolved,\n elapsed: number,\n sourceDuration?: number,\n): number {\n const start = fill.trimStart ?? 0;\n return posterizeTimestamp(fill, start, rawTimestamp(fill, elapsed, sourceDuration, start));\n}\n\n/** {@link resolveVideoTimestamp} before the posterize-time quantization. */\nfunction rawTimestamp(\n fill: VideoFillResolved,\n elapsed: number,\n sourceDuration: number | undefined,\n start: number,\n): number {\n // An authored timestamp wins outright: the author is driving the playhead.\n if (fill.timestamp != null) return fill.timestamp;\n // Paused with no authored time: hold the clip's first frame.\n if (!fill.playing) return start;\n\n const played = Math.max(0, elapsed - (fill.playStart ?? 0)) * (fill.speed ?? 1);\n return sourceTimeFor(played, start, trimEndFor(fill, sourceDuration), fill.loop, fill.duration);\n}\n\n/**\n * The clip's out point: what the fill states, or the source's own length once\n * the container has been opened, or unbounded while it has not.\n *\n * `Infinity` is the unbounded sentinel here, as it is throughout the audio side\n * (`Sound.trimEnd`, `AudioRequest.endAt`) — a decoder that has not read the\n * container cannot answer \"how long\", and running linearly and unlooped is what\n * it can honour in the meantime.\n */\nexport function trimEndFor(\n fill: Pick<VideoFillResolved, 'trimEnd'>,\n sourceDuration: number | undefined,\n): number {\n const hasDuration = sourceDuration !== undefined && Number.isFinite(sourceDuration) && sourceDuration > 0;\n return fill.trimEnd ?? (hasDuration ? sourceDuration : Infinity);\n}\n\n/**\n * Where `played` seconds of *consumed source* land inside the trimmed window,\n * once looping and clamping are applied.\n *\n * Split out of {@link rawTimestamp} because two callers now need it and only one\n * of them derives `played` the same way. The fill computes it linearly from the\n * clock; a {@link Video} node driven by a `segments` schedule computes it by\n * walking that schedule, since a paused stretch consumes no source at all. What\n * \"and then it wraps\" or \"and then it stops\" means is the same for both, and\n * this is the one place that says so.\n */\nexport function sourceTimeFor(\n /** Seconds of source consumed so far — already scaled by playback rate. */\n played: number,\n /** The trim-in point, which every result is measured from. */\n start: number,\n /** The trim-out point, or `Infinity` while the source's length is unknown. */\n end: number,\n loop: 'forward' | 'reverse' | 'none' | undefined,\n /** An explicit loop-cycle length; defaults to the trimmed clip's own. */\n cycleLength?: number,\n): number {\n const rawLoopDuration = cycleLength ?? (end !== Infinity ? end - start : undefined);\n const loopDuration = rawLoopDuration !== undefined && rawLoopDuration > 0 ? rawLoopDuration : undefined;\n if ((loop ?? 'none') !== 'none' && loopDuration !== undefined) {\n const cycle = played % loopDuration;\n if (loop === 'reverse') {\n const ping = Math.floor(played / loopDuration) % 2 === 0;\n return start + (ping ? cycle : loopDuration - cycle);\n }\n return start + cycle;\n }\n const linear = start + played;\n return end !== Infinity ? Math.min(linear, end) : linear;\n}\n\n/**\n * Posterize Time: snap the resolved source timestamp to a coarser grid so each\n * frame is held for a full 1/fps interval (the stop-motion look). Done after\n * trim/speed/loop so the quantization lives in source-time space and lines up\n * with the adapter's decoded-frame grid. `floor` (not round) holds a frame for\n * its whole interval, matching After Effects.\n */\nfunction posterizeTimestamp(fill: VideoFillResolved, start: number, timestamp: number): number {\n const posterize = fill.preset?.adjustments.find(\n (f): f is PosterizeTimeFilter => f.type === 'posterizeTime',\n );\n if (!posterize || posterize.fps <= 0) return timestamp;\n const grid = 1 / posterize.fps;\n return start + Math.floor((timestamp - start) / grid) * grid;\n}\n\nexport const videoFill: FillData<VideoFillResolved> = {\n // See `imageFill.resolve` for why `crop`/`anchor` are destructured out.\n resolve: ({ crop, anchor, preset, filters, ...prop }: VideoFillProp): VideoFillResolved => ({\n ...prop,\n ...resolveImagePlacement({ crop, anchor }),\n preset: resolveMediaPreset(preset, filters) as\n | MediaPresetResolved<VideoFillFilter>\n | undefined,\n playing: prop.playing ?? true,\n }),\n lerp: (a, b, t) => ({\n src: t < 0.5 ? a.src : b.src,\n fit: t < 0.5 ? a.fit : b.fit,\n ...lerpImagePlacement(a, b, t),\n loop: t < 0.5 ? a.loop : b.loop,\n duration: t < 0.5 ? a.duration : b.duration,\n trimStart: t < 0.5 ? a.trimStart : b.trimStart,\n trimEnd: t < 0.5 ? a.trimEnd : b.trimEnd,\n playStart: t < 0.5 ? a.playStart : b.playStart,\n playing: t < 0.5 ? a.playing : b.playing,\n opacity: (a.opacity ?? 1) + ((b.opacity ?? 1) - (a.opacity ?? 1)) * t,\n // Both derived (the common case) stays derived — lerping `?? 0` here\n // would pin the tween's result to an explicit timestamp and freeze the\n // clip for as long as the tween's output is live.\n timestamp: a.timestamp == null && b.timestamp == null\n ? undefined\n : lerpNumber(a.timestamp ?? 0, b.timestamp ?? 0, t),\n speed: lerpNumber(a.speed ?? 1, b.speed ?? 1, t),\n // See the note on `imageFill.lerp` — without this the *from* fill's\n // grade rides the whole tween and snaps at the end.\n preset: lerpMediaPreset(a.preset, b.preset, t),\n }),\n equals: (a, b) => a.src === b.src,\n declare: (fill, assets) => {\n assets.video(fill.src, { start: fill.trimStart ?? 0, end: fill.trimEnd });\n declareMediaPreset(fill.preset, assets);\n },\n};\n", "import { PathCommand } from \"./path\";\nimport type { PathState } from \"./path\";\n\n/**\n * A full or partial revolution of an ellipse, in the same **y-up** space the\n * commands themselves are authored in (`y = 100` is 100px *above* the centre,\n * matching a node's `x`/`y`). Angles are degrees from 3 o'clock, positive\n * counter-clockwise — the vocabulary the `Ellipse` node already uses.\n */\nexport interface EllipseArc {\n /** Centre. Both default to the origin. */\n x?: number;\n y?: number;\n width: number;\n /** Defaults to `width`, i.e. a circle. */\n height?: number;\n /** Where on the perimeter the curve starts. */\n startAngle?: number;\n /** Degrees travelled; negative goes clockwise. Past ±360 it keeps looping. */\n sweep?: number;\n}\n\nexport class PathBuilder {\n private _cmds: PathCommand[] = [];\n private _x = 0;\n private _y = 0;\n private _startX = 0;\n private _startY = 0;\n private _open = false;\n\n moveTo(x: number, y: number): this {\n this._cmds.push({ type: \"M\", x, y });\n this._startX = x;\n this._startY = y;\n return this._at(x, y);\n }\n\n lineTo(x: number, y: number): this {\n this._cmds.push({ type: \"L\", x, y });\n return this._at(x, y);\n }\n\n bezierCurveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): this {\n this._cmds.push({ type: \"C\", x1, y1, x2, y2, x, y });\n return this._at(x, y);\n }\n\n quadraticCurveTo(x1: number, y1: number, x: number, y: number): this {\n this._cmds.push({ type: \"Q\", x1, y1, x, y });\n return this._at(x, y);\n }\n\n /** The raw SVG arc command: an elliptical arc to (`x`, `y`), picked out of the four candidates by `largeArc`/`sweep`. */\n arcTo(rx: number, ry: number, rotation: number, largeArc: 0 | 1, sweep: 0 | 1, x: number, y: number): this {\n this._cmds.push({ type: \"A\", rx, ry, rotation, largeArc, sweep, x, y });\n return this._at(x, y);\n }\n\n /**\n * An **open** elliptical arc: the perimeter of {@link EllipseArc} from\n * `startAngle` through `sweep` degrees.\n *\n * Continues the current subpath — a straight line joins the pen's position\n * to the arc's start when the two differ — so `moveTo(...).arc(...)` is one\n * unbroken curve, which is what a `moveTo` command following the path needs.\n * A new `M` there would be a subpath break the walk teleports across.\n *\n * ```ts\n * new PathBuilder().arc({ x: 0, y: 0, width: 400, startAngle: 180, sweep: -180 });\n * ```\n */\n arc(arc: EllipseArc): this {\n const { cx, cy, rx, ry, from, sweep } = resolveArc(arc);\n const start = pointOn(cx, cy, rx, ry, from);\n if (!this._open) this.moveTo(start.x, start.y);\n else if (start.x !== this._x || start.y !== this._y) this.lineTo(start.x, start.y);\n return this._sweep(cx, cy, rx, ry, from, sweep);\n }\n\n /**\n * A **closed** subpath tracing an ellipse — the shape form of {@link arc}.\n *\n * A `sweep` short of a full turn closes across the chord back to the start;\n * for a pie wedge or an annular sector, that is an `Ellipse` node's `ratio`.\n */\n ellipse(arc: EllipseArc): this {\n const { cx, cy, rx, ry, from, sweep } = resolveArc(arc);\n const start = pointOn(cx, cy, rx, ry, from);\n this.moveTo(start.x, start.y);\n this._sweep(cx, cy, rx, ry, from, sweep);\n return this.close();\n }\n\n close(): this {\n this._cmds.push({ type: \"Z\" });\n return this._at(this._startX, this._startY);\n }\n\n toCommands(): PathCommand[] {\n return [...this._cmds];\n }\n\n toPathState(partial: Omit<Partial<PathState>, \"data\"> = {}): Partial<PathState> {\n return { ...partial, data: this._cmds };\n }\n\n /** Record where the pen ended up, so {@link arc} knows whether it has to join up to its start. */\n private _at(x: number, y: number): this {\n this._x = x;\n this._y = y;\n this._open = true;\n return this;\n }\n\n /**\n * Emit the arc as segments of at most a quarter turn. One `A` command cannot\n * express a full revolution at all (its endpoints would coincide, leaving the\n * arc undefined) and grows imprecise well before that, so the split is what\n * makes `sweep` a real angle rather than a value capped just under 360.\n */\n private _sweep(cx: number, cy: number, rx: number, ry: number, from: number, sweep: number): this {\n if (sweep === 0) return this;\n const steps = Math.ceil(Math.abs(sweep) / 90);\n const step = sweep / steps;\n const direction = sweep > 0 ? 1 : 0;\n for (let i = 1; i <= steps; i++) {\n const p = pointOn(cx, cy, rx, ry, from + step * i);\n this.arcTo(rx, ry, 0, 0, direction, p.x, p.y);\n }\n return this;\n }\n}\n\nfunction resolveArc(arc: EllipseArc): { cx: number; cy: number; rx: number; ry: number; from: number; sweep: number } {\n return {\n cx: arc.x ?? 0,\n cy: arc.y ?? 0,\n rx: arc.width / 2,\n ry: (arc.height ?? arc.width) / 2,\n from: arc.startAngle ?? 0,\n sweep: arc.sweep ?? 360,\n };\n}\n\nfunction pointOn(cx: number, cy: number, rx: number, ry: number, angle: number): { x: number; y: number } {\n const rad = (angle * Math.PI) / 180;\n return { x: cx + rx * Math.cos(rad), y: cy + ry * Math.sin(rad) };\n}\n", "import type { RectState } from \"./descriptors/rect\";\nimport type { EllipseState } from \"./descriptors/ellipse\";\nimport type { PathState } from \"./descriptors/path\";\nimport type { LineState } from \"./descriptors/line\";\nimport type { PolygonState } from \"./descriptors/polygon\";\nimport type { PolygramState } from \"./descriptors/polygram\";\nimport type { TextState } from \"./descriptors/text\";\nimport type { RichTextState } from \"./descriptors/richtext\";\nimport type { ShapeAlignmentInput } from \"./descriptors/shape\";\nimport { PathBuilder } from \"./descriptors/path-builder\";\nimport type { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { Stroke } from \"@/attributes/shape/stroke/stroke\";\nimport type { Shadow } from \"@/attributes/shape/shadow/shadow\";\nimport type { NodeEffect } from \"@/attributes/shape/effects/union\";\n// A direct leaf import, not the `@/attributes` barrel: this file sits inside a\n// cycle the barrel would close on itself (fill's canvas3d implementation →\n// render3d → Node2D → RenderContext2D → here), so importing the barrel here\n// leaves `effectsOps` (and anything else evaluated before it) undefined at\n// module-init time on that path.\nimport { type Effect, effectsOps } from \"@/attributes/shape/effects/chain\";\nimport type { Alignment } from \"@/attributes/layout/alignment\";\nimport type { MaskOptions } from \"@/attributes/mask/mask\";\n\n/**\n * A union-level rotate/scale applied to the whole drawn silhouette. `center` is\n * the pivot the union turns about: either an explicit {@link Vector2} in the\n * graphics' local coordinate space, or a **named alignment** (`'center'`,\n * `'topRight'`, …) the renderer resolves against the union's bounding box. When\n * omitted the renderer pivots about the centre of that bounding box.\n */\nexport interface GraphicsTransform {\n rotation: number;\n scale: number;\n center?: Alignment;\n}\n\n/**\n * The kinds of shape ops a {@link Graphics2D} can record. Each carries the partial\n * descriptor state for that shape, exactly as the old per-shape context methods\n * accepted.\n */\nexport type GraphicsShapeOp =\n | { kind: \"rect\"; state: Partial<RectState> & ShapeAlignmentInput }\n | { kind: \"ellipse\"; state: Partial<EllipseState> & ShapeAlignmentInput }\n | { kind: \"path\"; state: Partial<PathState> }\n | { kind: \"line\"; state: Partial<LineState> }\n | { kind: \"polygon\"; state: Partial<PolygonState> & ShapeAlignmentInput }\n | { kind: \"polygram\"; state: Partial<PolygramState> & ShapeAlignmentInput }\n | { kind: \"text\"; state: Partial<TextState> & ShapeAlignmentInput }\n | { kind: \"richText\"; state: Partial<RichTextState> & ShapeAlignmentInput };\n\n/**\n * A single recorded operation in a {@link Graphics2D} command list. Shape ops\n * declare geometry; paint ops (fill/stroke/shadow) apply to the accumulated\n * shapes; cut/mask ops composite. The renderer replays this list in order via\n * `RenderContext2D.draw()`.\n */\nexport type GraphicsOp =\n | GraphicsShapeOp\n | { kind: \"fill\"; fills: Fill }\n | { kind: \"stroke\"; strokes: Stroke }\n | { kind: \"shadow\"; shadows: Shadow }\n | { kind: \"cut\" }\n | { kind: \"mask\"; options?: MaskOptions }\n | { kind: \"applyMask\" }\n | { kind: \"endMask\" }\n | { kind: \"effects\"; effects: NodeEffect[] };\n\nconst SHAPE_KINDS = new Set<GraphicsOp[\"kind\"]>([\n \"rect\", \"ellipse\", \"path\", \"line\", \"polygon\", \"polygram\", \"text\", \"richText\",\n]);\n\n/**\n * A renderer-agnostic, chainable shape/paint builder.\n *\n * `Graphics2D` records a sequence of shape declarations and paint/compositing\n * operations without touching any renderer. A built `Graphics2D` is handed to a\n * `RenderContext2D` via `ctx.draw(graphics)`, which replays the recorded ops\n * against its concrete drawing backend.\n *\n * const g = new Graphics2D()\n * .ellipse({ width: 100, height: 100 })\n * .rect({ width: 40, height: 40, rotation: 30 }) // per-shape: tilts this rect only\n * .fill(Fills.color(\"red\"))\n * .stroke({ weight: 2, fill: \"black\" })\n * .rotation(15) // graphics-level: turns the whole union\n * .effects(Effects.blur(6)); // graphics-level: blurs the whole drawn union\n * ctx.draw(g);\n *\n * Multiple shapes chained before a paint call are combined into a single surface\n * and painted together (one gradient maps across all of them). `cut()` uses the\n * most-recently declared shape as a cutter against the shapes before it. The\n * `mask()/applyMask()/endMask()` ops support an inline mask scope within a single\n * `draw()`.\n *\n * Transforms come in two flavours. A per-shape `rotation`/`scale` is passed\n * *inside* a shape's params (e.g. `.rect({ ..., rotation: 30, scale: 1.2 })`):\n * it's baked into that shape's geometry before it joins the union. The\n * graphics-level `.rotation(value, center?)` / `.scale(value, center?)`\n * modifiers instead transform the *whole union* of shapes about a pivot\n * (default: the union's bounding-box centre) — turning or growing the entire\n * drawn silhouette as one.\n *\n * `opacity()` is graphics-level: it composites the entire drawn result (all\n * shapes together) into one layer at the given alpha, exactly like a node-level\n * transform — so a trailing `.opacity(0.4)` dims the whole union.\n *\n * `effects()` scopes like `fill()`: it applies to the shapes and paints\n * accumulated *since the previous `effects()` call* (or the start), then closes\n * that group off — shapes declared after it start a fresh, unaffected group, as\n * if a new `Graphics2D` had begun. So `.ellipse().ellipse().fill().effects(Effects.blur(8))`\n * blurs those two ellipses as one union, and a following `.rect().fill()` renders\n * crisp. Chaining a second `.effects()` later filters only that later group.\n */\nexport class Graphics2D {\n private _ops: GraphicsOp[] = [];\n private _opacity: number = 1;\n private _rotation: number = 0;\n private _scale: number = 1;\n private _transformCenter?: Alignment;\n\n // ─── Shapes ──────────────────────────────────────────────────────────────\n\n rect(state: Partial<RectState> & ShapeAlignmentInput): this {\n this._ops.push({ kind: \"rect\", state });\n return this;\n }\n\n ellipse(state: Partial<EllipseState> & ShapeAlignmentInput): this {\n this._ops.push({ kind: \"ellipse\", state });\n return this;\n }\n\n /** Declare a vector path, either from a `PathState` or a `PathBuilder`. */\n path(state: Partial<PathState> | PathBuilder): this {\n const resolved = state instanceof PathBuilder ? state.toPathState() : state;\n this._ops.push({ kind: \"path\", state: resolved });\n return this;\n }\n\n line(state: Partial<LineState>): this {\n this._ops.push({ kind: \"line\", state });\n return this;\n }\n\n polygon(state: Partial<PolygonState> & ShapeAlignmentInput): this {\n this._ops.push({ kind: \"polygon\", state });\n return this;\n }\n\n polygram(state: Partial<PolygramState> & ShapeAlignmentInput): this {\n this._ops.push({ kind: \"polygram\", state });\n return this;\n }\n\n text(state: Partial<TextState> & ShapeAlignmentInput): this {\n this._ops.push({ kind: \"text\", state });\n return this;\n }\n\n richText(state: Partial<RichTextState> & ShapeAlignmentInput): this {\n this._ops.push({ kind: \"richText\", state });\n return this;\n }\n\n // ─── Paint ───────────────────────────────────────────────────────────────\n\n fill(fills: Fill): this {\n this._ops.push({ kind: \"fill\", fills });\n return this;\n }\n\n stroke(strokes: Stroke): this {\n this._ops.push({ kind: \"stroke\", strokes });\n return this;\n }\n\n shadow(shadows: Shadow): this {\n this._ops.push({ kind: \"shadow\", shadows });\n return this;\n }\n\n // ─── Compositing ─────────────────────────────────────────────────────────\n\n /**\n * Use the last-declared shape as a cutter: union the shapes before it and\n * subtract that last shape, leaving the result as the current surface so\n * subsequent shapes and paint calls treat everything as one.\n */\n cut(): this {\n this._ops.push({ kind: \"cut\" });\n return this;\n }\n\n /**\n * Open an inline mask scope. Shapes declared after this (until `applyMask()`)\n * are the mask; shapes after `applyMask()` are the content. Close with\n * `endMask()`.\n */\n mask(options?: MaskOptions): this {\n this._ops.push({ kind: \"mask\", options });\n return this;\n }\n\n applyMask(): this {\n this._ops.push({ kind: \"applyMask\" });\n return this;\n }\n\n endMask(): this {\n this._ops.push({ kind: \"endMask\" });\n return this;\n }\n\n // ─── Modifiers ───────────────────────────────────────────────────────────\n\n /**\n * Set the opacity of the whole graphics group (0–1). The entire drawn result\n * is composited into one layer at this alpha, so overlapping shapes don't\n * double up. Applies to everything in the list, not just the last shape.\n */\n opacity(opacity: number): this {\n this._opacity = opacity;\n return this;\n }\n\n /**\n * Apply image effects to the current shape group, scoped like {@link fill}:\n * the shapes and paints recorded since the previous `effects()` call (or the\n * start of this `Graphics2D`) are composited through the composed filter as one\n * layer, so the effect reads that group's union silhouette (a blur bleeds\n * across the group's combined edges, not each shape's). Calling `effects()`\n * *closes* the group — shapes declared afterwards start a fresh, unfiltered\n * group, as if a new `Graphics2D` had begun. Accepts an {@link Effect} — a\n * single effect, an array, or an `Effects`/`EffectChain` builder result —\n * normalised to a `NodeEffect[]`.\n */\n effects(effects: Effect): this {\n this._ops.push({ kind: \"effects\", effects: effectsOps.resolve(effects) });\n return this;\n }\n\n /**\n * Rotate the whole union of shapes (degrees) about `center` — either an\n * explicit {@link Vector2} in local space or a **named alignment** (`'topRight'`,\n * `'bottomCenter'`, …) resolved against the union's bounding box (default: the\n * box's centre). Unlike a per-shape `rotation` passed inside a shape's params,\n * this mutates the combined silhouette — every shape turns together as one\n * figure.\n */\n rotation(rotation: number, center?: Alignment): this {\n this._rotation = rotation;\n if (center !== undefined) this._transformCenter = center;\n return this;\n }\n\n /**\n * Scale the whole union of shapes about `center` — an explicit {@link Vector2}\n * or a **named alignment** resolved against the union's bounding box (default:\n * the box's centre). Like {@link rotation}, this transforms the combined\n * silhouette rather than a single shape.\n */\n scale(scale: number, center?: Alignment): this {\n this._scale = scale;\n if (center !== undefined) this._transformCenter = center;\n return this;\n }\n\n // ─── Consumption ─────────────────────────────────────────────────────────\n\n /** The recorded ops, in order. Consumed by `RenderContext2D.draw()`. */\n ops(): readonly GraphicsOp[] {\n return this._ops;\n }\n\n /** Graphics2D-level opacity (0–1) for the whole group. Default 1. */\n groupOpacity(): number {\n return this._opacity;\n }\n\n /**\n * True when the whole graphics needs a composited layer (opacity < 1). Effects\n * no longer force a whole-graphics layer — each `effects` op scopes its own\n * layer to its shape group during replay (see {@link effects}).\n */\n needsGroupLayer(): boolean {\n return this._opacity < 1;\n }\n\n /**\n * The union-level rotate/scale set by {@link rotation} / {@link scale}, or\n * `null` when both are identity. The renderer applies this as a canvas\n * transform about `center` (default: the union's bbox centre) wrapping the\n * whole drawn union.\n */\n groupTransform(): GraphicsTransform | null {\n if (this._rotation === 0 && this._scale === 1) return null;\n return { rotation: this._rotation, scale: this._scale, center: this._transformCenter };\n }\n\n /** True when this Graphics2D has no shape ops (only paint/compositing) — used by\n * renderers to paint an externally-prepared surface (e.g. a boolean result)\n * without resetting their shape accumulator. */\n isPaintOnly(): boolean {\n return !this._ops.some((op) => SHAPE_KINDS.has(op.kind));\n }\n\n /**\n * A structural copy of this graphics with its op list replaced and every\n * group-level modifier (opacity, rotation, scale, transform centre) carried\n * over.\n *\n * A copy rather than a mutation because a node is free to build one\n * `Graphics2D` and submit it more than once — `Text` draws the same op list for\n * its fill, overlay and stroke passes — and each submission may sit under\n * different ambient state. Rewriting the shared instance would leak one\n * scope's resolution into the next.\n *\n * `@internal` — the seam `applyGraphicsTextDefaults` (see\n * `render/text-defaults.ts`) folds inherited text defaults through; not part\n * of the authoring surface.\n */\n /** @internal */\n _withOps(ops: GraphicsOp[]): Graphics2D {\n const next = new Graphics2D();\n next._ops = ops;\n next._opacity = this._opacity;\n next._rotation = this._rotation;\n next._scale = this._scale;\n next._transformCenter = this._transformCenter;\n return next;\n }\n}\n", "import type { Vector2 } from \"@/attributes/layout/vector2\";\n// Type-only, like `Color` above: `render3d` is pure data and never reaches into\n// the render or node layers at runtime. See SurfaceSource3D.\nimport type { Graphics2D } from \"@/render/graphics2d\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport type { Node2D } from \"@/components/trees/2d/node2d\";\n\n/** How sampling behaves outside the 0–1 UV range. */\nexport type TextureWrap3D = \"clamp\" | \"repeat\" | \"mirror\";\n\n/** How texels are blended when the texture is scaled. */\nexport type TextureFilter3D = \"nearest\" | \"linear\";\n\n/**\n * Which colour space the texture's data is in.\n *\n * `\"srgb\"` for anything representing a *colour* an eye would see (albedo/`map`,\n * `emissiveMap`), so the renderer linearizes it before lighting maths.\n * `\"linear\"` for *data* maps whose channels are numbers rather than colours\n * (`normalMap`, `roughnessMap`, `metalnessMap`, `aoMap`, `displacementMap`) —\n * linearizing those would corrupt them. Each map slot defaults correctly, so\n * this only needs setting for unusual pipelines.\n */\nexport type TextureColorSpace3D = \"srgb\" | \"linear\";\n\n/** Sampler state shared by every texture source. */\nexport interface TextureOptions3D {\n wrapS?: TextureWrap3D;\n wrapT?: TextureWrap3D;\n /** UV scale. `[2, 2]` tiles twice on each axis (needs a `repeat` wrap). */\n repeat?: Vector2 | readonly [number, number];\n offset?: Vector2 | readonly [number, number];\n /** UV rotation in **degrees**, about {@link center}. */\n rotation?: number;\n center?: Vector2 | readonly [number, number];\n magFilter?: TextureFilter3D;\n minFilter?: TextureFilter3D;\n /** Sharpness at grazing angles. Clamped to the GPU's maximum. */\n anisotropy?: number;\n flipY?: boolean;\n colorSpace?: TextureColorSpace3D;\n}\n\n/**\n * A texture loaded from the project's asset manifest.\n *\n * `src` is discovered by the asset-tracking render pass and requested through\n * core's ordinary image pipeline — the very same path a 2D image fill uses — so\n * the pixels are decoded and resident *before* the frame that needs them draws.\n */\nexport interface ImageTexture3D extends TextureOptions3D {\n src: string;\n}\n\n/**\n * A texture built from raw RGBA8888 bytes — the escape hatch for procedurally\n * generated pixels (gradient ramps, noise, LUTs, data encoded as colour).\n */\nexport interface DataTexture3D extends TextureOptions3D {\n data: ArrayLike<number>;\n width: number;\n height: number;\n /**\n * Bump to force a re-upload after mutating `data` in place. Mutation is\n * invisible to identity comparison, so without this the renderer cannot\n * tell the bytes changed. See {@link BufferGeometry3D.revision}.\n */\n revision?: number;\n}\n\n/**\n * A texture whose pixels are Motion Script's own 2D output, rasterized offscreen\n * — the way to put a chart, a readout or a whole laid-out UI onto 3D geometry.\n *\n * `source` is a value, not a name and not a mounted node: either a built\n * {@link Graphics2D} command list, or a `Node2D` subtree. Both are supplied directly,\n * so there is no matching indirection and nothing has to live in a particular\n * place in the scene tree.\n *\n * g3.plane({ map: Tex.surface(scopeGraphics, 1024, 640) })\n * g3.plane({ map: Tex.surface(statsSubtree, 1024, 640) })\n *\n * A `Node2D` source is *adopted for binding* by whatever paints the scene — it gets\n * that node's asset catalog, inherited context and clock, which is what makes a\n * webfont shape and an `<Image>` load. It is never laid out or painted by the\n * scene tree; it is measured against `width`×`height` and drawn into the buffer.\n *\n * **Hoist the source.** Building it fresh inside the scene builder allocates a new\n * subtree every frame — re-binding, re-laying-out, defeating the texture cache and\n * leaking. Declare it once and pass the same instance.\n *\n * That hoisting rule is also what removed this descriptor's old `key`: a hoisted\n * source *is* a stable identity, so the renderer keys the GPU texture off the\n * source object itself (in a `WeakMap`) rather than off its ordinal in the scene\n * walk. A conditionally-emitted surface therefore needs nothing written by hand,\n * and a source that goes out of scope becomes collectable instead of orphaning\n * its texture — which the ordinal scheme could not do.\n */\nexport interface SurfaceTexture3D extends TextureOptions3D {\n /** A built `Graphics2D`, or a `Node2D` subtree. Typed structurally — see below. */\n source: SurfaceSource3D;\n /** Buffer width in pixels. This *is* the texture's resolution. */\n width: number;\n /** Buffer height in pixels. */\n height: number;\n /**\n * Declare the source's pixels unchanging, so the buffer is rasterized once\n * and reused rather than redrawn every frame.\n *\n * Set by `resolveFill3D` for a fill chain, whose layers describe the same\n * image on every frame; an author's own source is live by default, which is\n * what makes an animated `Graphics2D` or a prop-driven subtree work with no\n * bookkeeping. Needs {@link identity} to be cacheable.\n *\n * @internal\n */\n static?: boolean;\n /**\n * Cache identity for a synthesized source.\n *\n * An author's source is identified by the source object itself (see the note\n * above), which is exactly right for something hoisted. A source built *for*\n * a fill is a fresh object every frame and has no such identity, so the value\n * it was derived from supplies one.\n *\n * @internal\n */\n identity?: string;\n /**\n * Ceiling on the buffer's device-pixel ratio. Default 1, i.e. the buffer is\n * exactly `width` × `height`.\n *\n * Unlike a 2D node — which wants to match the display — a surface is sampled by\n * a 3D material at whatever size the geometry occupies on screen, so the honest\n * control is `width`/`height`. Raise this only when a surface is viewed close\n * up and reads soft.\n */\n maxPixelRatio?: number;\n}\n\n/**\n * What a {@link SurfaceTexture3D} can be painted from: a built {@link Graphics2D}\n * command list, or a {@link Node2D} subtree.\n *\n * Both imports are **type-only**, exactly as `Color` is — `render3d` describes\n * scenes as data and never reaches into the render or node layers at runtime, and\n * a value import of `Node2D` here would close a real module cycle. Consumers narrow\n * with {@link resolveSurfaceSource}.\n */\nexport type SurfaceSource3D = Graphics2D | Node;\n\n// Declared against the dimension-agnostic base because that is what a built\n// node is typed as, so `Tex.surface(new Rect({ … }), …)` type-checks without a\n// cast. It has to be a 2D subtree in fact — the renderer lays it out and draws it\n// into a 2D buffer — and `resolveSurfaceSource` narrows to that; handing it a\n// `Node3D` fails at render time rather than here.\n\n/** A {@link SurfaceSource3D} narrowed to the arm its renderer should take. */\nexport type ResolvedSurfaceSource =\n | { kind: \"graphics\"; graphics: Graphics2D }\n | { kind: \"node\"; node: Node2D };\n\n/**\n * Narrow a surface source to the arm that knows how to draw it: a `Graphics2D` is\n * replayed into a render context, a `Node2D` is laid out against the buffer and\n * rendered.\n *\n * Structural rather than `instanceof`, because that would need value imports of\n * both classes and close the cycle the type-only imports above avoid. `Graphics2D`\n * is a command recorder and exposes `ops()`; a `Node2D` has no such method. The\n * union makes any *other* value a type error, so this only has to separate two\n * known shapes rather than validate an unknown one.\n */\nexport function resolveSurfaceSource(source: SurfaceSource3D): ResolvedSurfaceSource {\n return typeof (source as Graphics2D).ops === \"function\"\n ? { kind: \"graphics\", graphics: source as Graphics2D }\n : { kind: \"node\", node: source as Node2D };\n}\n\n/**\n * A texture reference. A bare string is sugar for `{ src }`, so the common case\n * is `map: \"/wood.png\"`.\n */\nexport type Texture3D = string | ImageTexture3D | DataTexture3D | SurfaceTexture3D;\n\n/** True for the raw-bytes form (vs. an asset-backed {@link ImageTexture3D}). */\nexport function isDataTexture3D(texture: Texture3D): texture is DataTexture3D {\n return typeof texture !== \"string\" && \"data\" in texture;\n}\n\n/** True for the {@link SurfaceTexture3D} form — pixels are rasterized from 2D. */\nexport function isSurfaceTexture3D(texture: Texture3D): texture is SurfaceTexture3D {\n return typeof texture !== \"string\" && \"source\" in texture;\n}\n\n/** Normalize the string shorthand to an {@link ImageTexture3D}. */\nexport function resolveTexture3D(texture: Texture3D): ImageTexture3D | DataTexture3D | SurfaceTexture3D {\n return typeof texture === \"string\" ? { src: texture } : texture;\n}\n\n/**\n * The asset `src` a texture reads from, or `null` when it has none (a data or\n * surface texture). Used by the asset-tracking pass to enumerate what a 3D scene\n * needs loaded — a `null` here means \"nothing to request\", not \"not a texture\".\n */\nexport function texture3DSource(texture: Texture3D): string | null {\n if (typeof texture === \"string\") return texture;\n if (isDataTexture3D(texture) || isSurfaceTexture3D(texture)) return null;\n return texture.src;\n}\n\n/**\n * True for a string that names an asset rather than a colour.\n *\n * Leading `/` or `.` is a path by construction; otherwise the extension decides.\n * A colour never matches either, and a bare name like `\"wood\"` is a colour —\n * which is right, since an asset reference without a path or extension is not\n * something the manifest could resolve either.\n */\nexport function looksLikeAssetPath(value: string): boolean {\n return value.startsWith(\"/\")\n || value.startsWith(\".\")\n || /\\.(png|jpe?g|webp|avif|svg|ktx2?|hdr|exr|mp4|webm|mov)$/i.test(value);\n}\n", "import { type Color, type NormalizedColor, parseColor } from \"@/attributes/shape/fill/color/parser\";\nimport { lerpColor } from \"@/attributes/shape/fill/lerp\";\nimport type { Fill } from \"@/attributes/shape/fill/chain\";\n// A value import, unlike the type-only ones in `texture.ts`: building the rect a\n// fill chain is painted into needs the recorder itself. Safe because\n// `render/graphics2d` reaches only the *effects* chain at runtime, never back\n// into `render3d` — see the note on `SurfaceSource3D`.\nimport { Graphics2D } from \"@/render/graphics2d\";\nimport { looksLikeAssetPath } from \"./texture\";\nimport type { SurfaceSource3D, Texture3D } from \"./texture\";\n\nexport { looksLikeAssetPath };\n\n/**\n * What a surface is made of.\n *\n * The same value a 2D `fill` takes, so a mesh and a rect are described with one\n * vocabulary: a colour, a gradient, an image, a video, a noise field, a whole\n * stack of blended layers — and, because a `Node2D` subtree and a built\n * `Graphics2D` are fills too, any 2D content at all.\n *\n * This is the 3D counterpart of Spline's material *stack*, built on the fill\n * chain that already exists rather than on a second set of layer types. What it\n * replaces is a flat `color` plus five separate texture slots (`map`,\n * `emissiveMap`, `alphaMap`, `envMap`, `lightMap`), each of which was a fill\n * wearing a different name.\n */\nexport type Fill3D = Color | Fill | Texture3D | SurfaceSource3D;\n\n/** What a {@link Fill3D} contributes to a material descriptor. */\nexport interface ResolvedFill3D {\n color?: Color;\n map?: Texture3D;\n}\n\n/** Sizing for the buffer a rich fill is rasterized into. */\nexport interface Fill3DOptions {\n /** Default 512. */\n width?: number;\n /** Default 512. */\n height?: number;\n}\n\nconst DEFAULT_SIZE = 512;\n\n/**\n * Resolve a {@link Fill3D} into the material fields it describes.\n *\n * Three outcomes, and which one applies is decided by what the fill *is* rather\n * than by an author picking a slot:\n *\n * - **A colour** stays a colour. `fill=\"tomato\"` writes `material.color`, costs\n * nothing, and is by far the common case — so it must not be the one that\n * allocates a texture.\n * - **A texture** (an asset path, or any `Texture3D` descriptor) becomes `map`.\n * - **Anything richer** — a gradient, a layer stack, a `Node2D` subtree, a built\n * `Graphics2D`, a nested `Scene3D` — is painted into an offscreen buffer and\n * bound as `map`, through exactly the `Tex.surface` machinery that already\n * existed for putting 2D content on geometry.\n *\n * That last arm is what makes the 2D and 3D fill vocabularies genuinely one\n * thing: `Fills.canvas3D(scene)` inside a chain renders 3D into a layer of a\n * material on a mesh, with no new code path, because the 2D fill renderer was\n * already able to do it.\n */\nexport function resolveFill3D(\n fill: Fill3D | undefined,\n options: Fill3DOptions = {},\n): ResolvedFill3D {\n if (fill === undefined || fill === null) return {};\n\n if (typeof fill === \"string\") {\n // A bare string is ambiguous between a colour and an asset path, and both\n // are things authors write. Resolved the way the material handler already\n // resolved a `color` that looked like a file — so this is the existing\n // rule moved somewhere it can be stated once.\n return looksLikeAssetPath(fill) ? { map: fill } : { color: fill };\n }\n\n if (Array.isArray(fill)) {\n // A `Color` is also an array — of numbers. A fill chain is an array of\n // layers, which are strings or objects.\n if (fill.every((entry) => typeof entry === \"number\")) {\n return { color: fill as unknown as Color };\n }\n return { map: rasterized(fill as Fill, options) };\n }\n\n if (typeof fill === \"object\") {\n if (isSurfaceSourceValue(fill)) return { map: surfaceFor(fill as SurfaceSource3D, options) };\n if (isTextureDescriptor(fill)) return { map: fill as Texture3D };\n if (isSolidLayer(fill)) return { color: (fill as { color: Color }).color };\n }\n\n return { map: rasterized(fill as Fill, options) };\n}\n\n/**\n * A surface texture painting `source` directly.\n *\n * Identity comes from the source object, which the `Tex.surface` contract already\n * requires to be hoisted — so nothing has to be written by hand and a source that\n * goes out of scope stops being cached.\n */\nfunction surfaceFor(source: SurfaceSource3D, options: Fill3DOptions): Texture3D {\n return {\n source,\n width: options.width ?? DEFAULT_SIZE,\n height: options.height ?? DEFAULT_SIZE,\n };\n}\n\n/**\n * A surface texture painting a fill chain into a rect that fills the buffer.\n *\n * Marked `static` and given a derived identity, because a fill chain describes\n * the *same* pixels every frame unless one of its own values moved. Without both\n * of those a gradient on a cube would re-rasterize a 512² offscreen buffer and\n * re-upload it sixty times a second to produce an identical image — which is\n * exactly the trap that makes \"just render it to a texture\" a bad idea in\n * general, and is worth the small amount of bookkeeping to avoid.\n *\n * A chain holding something genuinely live (a video layer, a `Fills.canvas3D`) is\n * still re-rasterized: those carry object identity, which `fillIdentity` folds in\n * and which changes when the content does.\n */\nfunction rasterized(fill: Fill, options: Fill3DOptions): Texture3D {\n const width = options.width ?? DEFAULT_SIZE;\n const height = options.height ?? DEFAULT_SIZE;\n return {\n source: new Graphics2D().rect({ width, height }).fill(fill),\n width,\n height,\n static: true,\n identity: `fill:${fillIdentity(fill)}:${width}x${height}`,\n };\n}\n\n/** True for a `Texture3D` descriptor object (not a source value). */\nfunction isTextureDescriptor(value: object): boolean {\n return \"src\" in value || \"data\" in value || (\"source\" in value && \"width\" in value);\n}\n\n/**\n * True for a value that is 2D content to be painted, rather than a descriptor.\n *\n * Structural, like `resolveSurfaceSource`, and for the same reason: an\n * `instanceof` here would need value imports of `Node2D` and close a real module\n * cycle. A `Scene3D` also exposes `ops()`, so it is excluded explicitly — it is a\n * fill *layer* (`Fills.canvas3D`) rather than a 2D source, and routing it through\n * the chain arm is what gets it composited with the rest of the stack.\n */\nfunction isSurfaceSourceValue(value: object): boolean {\n const bag = value as Record<string, unknown>;\n if (typeof bag.cameraDescriptor === \"function\") return false;\n if (typeof bag.ops === \"function\") return true;\n return typeof bag.id === \"string\" && typeof bag.attach === \"function\";\n}\n\n/** True for a single solid-colour fill layer, which needs no texture. */\nfunction isSolidLayer(value: object): boolean {\n const bag = value as Record<string, unknown>;\n if (bag.type !== \"solid\" || bag.color === undefined) return false;\n // Anything beyond the colour — a per-layer opacity, a blend mode, a\n // reference space — is a composite the colour slot cannot express.\n return bag.opacity === undefined && bag.blend === undefined && bag.space === undefined;\n}\n\n/**\n * Interpolate two fills.\n *\n * Colours interpolate — that is the overwhelmingly common tween and it must not\n * snap. Anything else holds the start value and swaps at the end, because there\n * is no meaningful halfway between a gradient and a photograph; cross-fading two\n * surfaces is a *stack* (`fill={[a, b]}` with the second layer's opacity tweened),\n * which is how it is expressed in 2D too.\n *\n * The colour test is deliberately cheap and allocation-free: resolving a rich\n * fill builds a `Graphics2D` and a texture descriptor, and doing that twice per\n * frame for a tween that is going to snap anyway would be pure waste.\n */\nexport function lerpFill3D(from: Fill3D, to: Fill3D, t: number): Fill3D {\n const start = asPlainColor(from);\n const end = asPlainColor(to);\n if (start !== null && end !== null) {\n return lerpColor(normalize(start), normalize(end), t) as unknown as Fill3D;\n }\n return t < 1 ? from : to;\n}\n\n/** The colour a fill *is*, or `null` when it is anything richer. No allocation. */\nfunction asPlainColor(fill: Fill3D | undefined): Color | null {\n if (fill === undefined || fill === null) return null;\n if (typeof fill === \"string\") return looksLikeAssetPath(fill) ? null : fill;\n if (Array.isArray(fill)) {\n return fill.every((entry) => typeof entry === \"number\") ? (fill as unknown as Color) : null;\n }\n if (typeof fill === \"object\" && isSolidLayer(fill)) return (fill as { color: Color }).color;\n return null;\n}\n\nfunction normalize(color: Color): NormalizedColor {\n return Array.isArray(color) ? (color as NormalizedColor) : parseColor(color);\n}\n\nconst objectIds = new WeakMap<object, string>();\nlet objectCounter = 0;\n\n/**\n * A stable key for a fill value.\n *\n * Plain data is walked and sorted; anything with a prototype of its own — a\n * `Scene3D`, a `Graphics2D`, a video source — is keyed by object identity, which\n * is both cheaper than serialising it and the honest answer, since two different\n * instances describe two different things whatever their fields say. A\n * `FillChain` is unwrapped to its list first, so building one inline still\n * produces the same key for the same layers.\n */\nfunction fillIdentity(value: unknown): string {\n if (value === null || typeof value !== \"object\") return String(value);\n if (Array.isArray(value)) return `[${value.map(fillIdentity).join(\",\")}]`;\n\n const list = (value as { list?: unknown }).list;\n if (Array.isArray(list)) return fillIdentity(list);\n\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n let id = objectIds.get(value);\n if (id === undefined) {\n id = `@${objectCounter++}`;\n objectIds.set(value, id);\n }\n return id;\n }\n\n const bag = value as Record<string, unknown>;\n return `{${Object.keys(bag).sort().map((key) => `${key}:${fillIdentity(bag[key])}`).join(\",\")}}`;\n}\n", "import type { Graphics3DOp } from \"./graphics3d\";\nimport type { Material3D } from \"./material\";\n\n/**\n * Development warnings for 3D inputs that are accepted, typed and recorded, and\n * that no renderer acts on.\n *\n * A few corners of the 3D vocabulary are declared ahead of the backend: the post\n * chain, HDR/EXR/cubemap environments, `params` on a geometry or an environment,\n * `extends` on a shader material and OBJ models. Each is stored faithfully and\n * read by nothing, so a scene that uses one renders exactly like a scene without\n * it — and with no error, which is the part that costs an afternoon. These say so\n * once, in development, naming the input and what to do instead.\n *\n * Each message is printed once per session. Nothing here changes what is\n * recorded, so none of it can move a frame.\n */\n\nconst warned = new Set<string>();\nlet development: boolean | undefined;\n\n/** Read once: in Node, `process.env` is a lookup per access. */\nfunction isDevelopment(): boolean {\n return (development ??= process.env.NODE_ENV !== \"production\");\n}\n\n/**\n * Print `message` once per `key`, in development only.\n * @internal\n */\nexport function warnInert3D(key: string, message: string): void {\n if (!isDevelopment() || warned.has(key)) return;\n warned.add(key);\n console.warn(`[motionscript] ${message}`);\n}\n\n/** Forget what has been warned, so a test can see the same warning again. @internal */\nexport function resetInertWarnings3D(): void {\n warned.clear();\n}\n\n/**\n * Check one recorded drawable for inputs the renderer ignores.\n * @internal\n */\nexport function inspectDrawable3D(op: Graphics3DOp): void {\n if (!isDevelopment()) return;\n\n if (\"geometry\" in op) {\n const params = op.geometry.params;\n if (params && Object.keys(params).length > 0) {\n warnInert3D(\n `geometry-params:${op.geometry.type}`,\n `\\`params\\` on a \"${op.geometry.type}\" geometry is not applied: three builds a geometry from its named fields and nothing assigns \\`params\\` onto it. `\n + \"Set the geometry's own fields instead. (`params` is applied on materials, lights and cameras.)\",\n );\n }\n }\n\n if (\"material\" in op) {\n const materials = Array.isArray(op.material) ? op.material : [op.material];\n for (const material of materials as readonly Material3D[]) {\n if (material.type === \"shader\" && material.extends != null) {\n warnInert3D(\n \"shader-extends\",\n `\\`extends: \"${material.extends}\"\\` on a shader material is not applied: the shader replaces the built-in model, so scene lighting, shadows and fog do not reach it. `\n + \"Write the lighting you need in the shader.\",\n );\n }\n }\n }\n\n if (op.kind === \"model\" && /\\.obj(?:$|[?#])/i.test(op.src)) {\n warnInert3D(\n \"model-obj\",\n `The model \"${op.src}\" is an OBJ file, and only glTF/GLB models load: it will draw nothing. Convert it to .glb.`,\n );\n }\n}\n", "import type { Color } from \"@/attributes/shape/fill/color/parser\";\nimport type {\n BoxGeometry3D, BufferGeometry3D, CapsuleGeometry3D, CircleGeometry3D, ConeGeometry3D,\n CylinderGeometry3D, ExtrudeGeometry3D, Geometry3D, LatheGeometry3D,\n PlaneGeometry3D, PolyhedronGeometry3D, RingGeometry3D, SphereGeometry3D,\n TorusGeometry3D, TorusKnotGeometry3D, TubeGeometry3D,\n} from \"./geometry\";\nimport type { Material3D, Shading3D } from \"./material\";\nimport type { Texture3D } from \"./texture\";\nimport { resolveFill3D, type Fill3D } from \"./fill3d\";\nimport { inspectDrawable3D } from \"./inert\";\nimport { type Transform3D, type Blend3D, type Faces3D } from \"./transform\";\nimport type { Vector3Input } from \"./vector3\";\n\n// ─── Ops ─────────────────────────────────────────────────────────────────────\n\n/** One clip of a model's baked animation, sampled at an explicit time. */\nexport interface ModelAnimation3D {\n /** Clip name, or its index in the file. Defaults to the first clip. */\n clip?: string | number;\n /**\n * Seconds into the clip. **Explicit by design** — the renderer seeks to this\n * time rather than advancing by a delta, which is what keeps a model's\n * animation identical whether the frame was reached by playing forward or by\n * scrubbing backwards.\n */\n time: number;\n /** Blend weight, for cross-fading clips. Default 1. */\n weight?: number;\n}\n\n/**\n * How a `line` op connects its points: in order, or as disjoint start/end pairs,\n * or in order and closed back to the start.\n */\nexport type LineMode3D = \"strip\" | \"segments\" | \"loop\";\n\n/**\n * One recorded operation in a {@link Graphics3D} command list.\n *\n * Every op draws something. Hierarchy, lights and the camera are *scene*\n * concerns, recorded by the `Node3D` tree into a `Scene3D` — this is only ever\n * \"what one node paints\", which is exactly what a `Graphics2D` is in 2D.\n *\n * A drawable's geometry and material are *inline sub-descriptors*, not ops,\n * because in a 3D scene graph they are properties of an object rather than\n * children of it.\n */\nexport type Graphics3DOp =\n | { kind: \"mesh\"; geometry: Geometry3D; material: Material3D | readonly Material3D[]; transform?: Transform3D }\n | {\n kind: \"instances\";\n geometry: Geometry3D;\n material: Material3D;\n /** Per-instance placement. Length drives the instance count. */\n instances: readonly Transform3D[];\n /** Per-instance tint. Needs a material that reads instance colour. */\n colors?: readonly Color[];\n transform?: Transform3D;\n }\n | { kind: \"points\"; geometry: Geometry3D; material: Material3D; transform?: Transform3D }\n | {\n kind: \"line\";\n geometry: Geometry3D;\n material: Material3D;\n mode: LineMode3D;\n transform?: Transform3D;\n }\n | { kind: \"sprite\"; material: Material3D; transform?: Transform3D }\n | {\n kind: \"model\";\n src: string;\n animation?: readonly ModelAnimation3D[];\n /** Replace materials on the loaded graph, keyed by mesh or material name. */\n override?: Readonly<Record<string, Material3D>>;\n transform?: Transform3D;\n };\n\n/**\n * Op kinds that put something in the scene (as opposed to shaping the tree).\n *\n * Shared with `Scene3D`, whose op list is this one plus `push`/`pop`/`light`/\n * `camera` — so \"is anything actually drawn here\" has a single definition.\n */\n/** @internal */\nexport const DRAWABLE_KINDS: ReadonlySet<string> = new Set([\n \"mesh\", \"light\", \"instances\", \"points\", \"line\", \"sprite\", \"model\",\n]);\n\n// ─── Shorthand ───────────────────────────────────────────────────────────────\n\n/**\n * Material fields promoted onto the geometry sugar methods, so the common case is\n * one flat call: `.box({ width: 2, fill: \"red\", roughness: 0.3 })`.\n *\n * `fill` is the whole 2D fill vocabulary — see {@link Fill3D} — and is what a\n * flat `color` plus a `map` slot used to be. The rest is surface *response*\n * (how light behaves on it) rather than colour, which is the line Spline's\n * material panel draws too and the reason those stay separate fields.\n *\n * These desugar at record time into a full {@link Material3D} — `standard` by\n * default, `basic` when {@link unlit} is set — so the recorded op list stays\n * canonical. Pass {@link material} to bypass the shorthand entirely; every\n * renderer-level knob that is not a design decision (`depthWrite`, `alphaTest`,\n * `toneMapped`, `polygonOffset`, …) lives there and only there.\n */\nexport interface MaterialShorthand3D {\n /** A full descriptor (or an array, for multi-material). Wins over the rest. */\n material?: Material3D | readonly Material3D[];\n /** What the surface is made of: a colour, a texture, a gradient, 2D content. */\n fill?: Fill3D;\n opacity?: number;\n roughness?: number;\n metalness?: number;\n /** Self-illumination. Bloom in the post chain is what makes it glow. */\n emission?: Color;\n emissionStrength?: number;\n normalMap?: Texture3D;\n roughnessMap?: Texture3D;\n metalnessMap?: Texture3D;\n aoMap?: Texture3D;\n alphaMap?: Texture3D;\n envMapIntensity?: number;\n wireframe?: boolean;\n /** Facet or smooth shading. Default `\"smooth\"`. */\n shading?: Shading3D;\n /** Which faces to rasterize. Default `\"front\"`. */\n faces?: Faces3D;\n vertexColors?: boolean;\n blend?: Blend3D;\n /** Shade with an unlit `basic` material instead of `standard`. */\n unlit?: boolean;\n}\n\n/** Transform + material shorthand, accepted by every geometry sugar method. */\nexport type MeshShorthand3D = Transform3D & MaterialShorthand3D;\n\nconst TRANSFORM_KEYS = [\n \"position\", \"rotation\", \"quaternion\", \"scale\", \"lookAt\",\n \"visible\", \"shadow\", \"renderOrder\",\n] as const;\n\n/**\n * Shorthand keys copied straight onto the built descriptor.\n *\n * `fill` is deliberately absent: it resolves into `color` *and* `map` rather than\n * being one field, so it is handled on its own in {@link resolveMaterialShorthand3D}.\n */\nconst MATERIAL_SHORTHAND_KEYS = [\n \"opacity\", \"roughness\", \"metalness\",\n \"emission\", \"emissionStrength\", \"normalMap\", \"roughnessMap\",\n \"metalnessMap\", \"aoMap\", \"alphaMap\", \"envMapIntensity\", \"wireframe\",\n \"shading\", \"faces\", \"vertexColors\", \"blend\",\n] as const;\n\n/** Every key the shorthand owns, for stripping a geometry bag. */\nconst SHORTHAND_KEYS: readonly string[] = [...MATERIAL_SHORTHAND_KEYS, \"fill\", \"material\", \"unlit\"];\n\n/**\n * Pull the {@link Transform3D} fields out of a shorthand bag. Takes `object` so\n * the concrete option types at each call site pass without a cast, and returns\n * `undefined` rather than `{}` when there is nothing to apply — an absent\n * transform lets the renderer skip the matrix write entirely.\n */\nfunction pickTransform(source: object): Transform3D | undefined {\n const bag = source as Record<string, unknown>;\n let out: Record<string, unknown> | undefined;\n for (const key of TRANSFORM_KEYS) {\n if (bag[key] !== undefined) (out ??= {})[key] = bag[key];\n }\n return out as Transform3D | undefined;\n}\n\n/**\n * Build the material a shorthand bag describes. Always returns one, so a recorded\n * drawable op never has to be interpreted with \"…or the default\" in mind.\n *\n * Exported because `Mesh3D` desugars the identical bag from its own props: this\n * is where `fill` becomes `color`-or-`map`, and two copies of that decision is\n * two chances for a node and a builder call to paint differently.\n *\n * @internal\n */\nexport function resolveMaterialShorthand3D(source: MaterialShorthand3D): Material3D | readonly Material3D[] {\n if (source.material !== undefined) return source.material;\n\n const material: Record<string, unknown> = { type: source.unlit ? \"basic\" : \"standard\" };\n\n const fill = resolveFill3D(source.fill);\n if (fill.color !== undefined) material.color = fill.color;\n if (fill.map !== undefined) material.map = fill.map;\n\n for (const key of MATERIAL_SHORTHAND_KEYS) {\n const value = (source as Record<string, unknown>)[key];\n if (value !== undefined) material[key] = value;\n }\n return material as unknown as Material3D;\n}\n\n/** Drop the shorthand/transform keys, leaving only a geometry's own params. */\nfunction pickGeometry<T>(source: object, type: string): T {\n const bag = source as Record<string, unknown>;\n const out: Record<string, unknown> = { type };\n for (const key in bag) {\n if (SHORTHAND_KEYS.includes(key)) continue;\n if ((TRANSFORM_KEYS as readonly string[]).includes(key)) continue;\n if (bag[key] !== undefined) out[key] = bag[key];\n }\n return out as T;\n}\n\n/** Geometry params only, with `type` and the inherited passthrough removed. */\ntype ParamsOf<G> = Omit<G, \"type\">;\n\n// ─── Recorder ────────────────────────────────────────────────────────────────\n\n/**\n * What one 3D node draws — the `Graphics2D` of 3D.\n *\n * Records an ordered list of drawables (meshes, instanced meshes, points, lines,\n * sprites, models), each with its own geometry, material and local transform.\n * That is the whole surface: it holds no camera, no lights and no hierarchy,\n * because those are properties of a *scene* rather than of a thing in one, and\n * the `Node3D` tree owns them. The exact division `Graphics2D` and\n * `RenderContext2D` already make in 2D.\n *\n * render: (ctx) => ctx.draw(new Graphics3D()\n * .box({ width: 2, cornerRadius: 0.15, fill: \"#e0533d\", roughness: 0.3 })),\n *\n * Nothing here touches a renderer: a built `Graphics3D` is handed to a\n * {@link RenderContext3D}, which splices its ops into the scene being recorded.\n *\n * ── One flat bag, deliberately ────────────────────────────────────────────────\n * `Graphics2D` paints with a *chained* `.rect(…).fill(…)`, and this does not,\n * which is the one place the two recorders diverge on purpose. In 2D a `fill` is\n * a **group-scoped op** covering the shapes recorded before it; in 3D a material\n * belongs to exactly one object, because a mesh *is* geometry plus material.\n * A chained `.box().fill()` would imply a group material that has nothing to\n * scope over, so the shape and what it is made of are stated together instead.\n *\n * ── Angles are DEGREES ────────────────────────────────────────────────────────\n * Every angle here — Euler rotations, sweep arcs, UV rotation — is in degrees,\n * matching the engine's 2D `rotation`. The renderer converts.\n *\n * ── Animation ─────────────────────────────────────────────────────────────────\n * A `Graphics3D` is rebuilt from scratch every frame, so animation is just\n * reading the node's own state while building:\n *\n * const Rig = component3d({\n * key: \"rig\",\n * state: { spin: 0, lift: Types.custom<Vector3>([0, 0, 0], { lerp: lerpVector3 }) },\n * render: (ctx, s) => ctx.draw(new Graphics3D()\n * .box({ rotation: [0, s.spin, 0], position: s.lift })),\n * });\n * // a `to` of { spin: 360 } over two seconds turns it\n *\n * Note the `lerp` on `lift`. An entry holding a non-number needs an explicit\n * tween (`lerpVector3`, `lerpEuler3`, `slerpQuaternion`) or `to()` has nothing\n * to interpolate it with and leaves it alone.\n *\n * ── Reconciliation identity ───────────────────────────────────────────────────\n * The renderer caches one live 3D object per op and mutates it between frames\n * rather than rebuilding. Identity is **derived**: it comes from the owning\n * `Node3D` plus a signature of what the op actually draws, so a builder that\n * emits ops conditionally reuses the right cache entry with nothing written by\n * hand. There is no `key` to set.\n *\n * ── What is cheap to animate ──────────────────────────────────────────────────\n * Transforms and most material values are in-place writes, so they cost nothing\n * per frame. **Geometry parameters are not** — three geometries are immutable, so\n * tweening `.box({ width: this.size })` reallocates the mesh every frame. Scale\n * the object instead: `.box({ width: 1, scale: [this.size, 1, 1] })`. The fields marked\n * \"structural\" on `MaterialCommon3D` recompile the shader program and should be\n * set once, not tweened.\n */\nexport class Graphics3D {\n private _ops: Graphics3DOp[] = [];\n\n /** Append one op, flagging (in development) inputs no renderer acts on. */\n private record(op: Graphics3DOp): void {\n inspectDrawable3D(op);\n this._ops.push(op);\n }\n\n // ─── Meshes ──────────────────────────────────────────────────────────────\n\n /**\n * Record a mesh from an explicit geometry and material. The geometry sugar\n * methods below all funnel here.\n */\n mesh(\n geometry: Geometry3D,\n material?: Material3D | readonly Material3D[],\n transform?: Transform3D,\n ): this {\n this.record({\n kind: \"mesh\",\n geometry,\n material: material ?? { type: \"standard\" },\n transform,\n });\n return this;\n }\n\n /** Record a mesh from a geometry `type` plus a flat shorthand bag. */\n private sugar(type: Geometry3D[\"type\"], options?: MeshShorthand3D): this {\n const source: MeshShorthand3D = options ?? {};\n return this.mesh(\n pickGeometry<Geometry3D>(source, type),\n resolveMaterialShorthand3D(source),\n pickTransform(source),\n );\n }\n\n box(options?: ParamsOf<BoxGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"box\", options);\n }\n sphere(options?: ParamsOf<SphereGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"sphere\", options);\n }\n plane(options?: ParamsOf<PlaneGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"plane\", options);\n }\n cylinder(options?: ParamsOf<CylinderGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"cylinder\", options);\n }\n cone(options?: ParamsOf<ConeGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"cone\", options);\n }\n torus(options?: ParamsOf<TorusGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"torus\", options);\n }\n torusKnot(options?: ParamsOf<TorusKnotGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"torusKnot\", options);\n }\n circle(options?: ParamsOf<CircleGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"circle\", options);\n }\n ring(options?: ParamsOf<RingGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"ring\", options);\n }\n capsule(options?: ParamsOf<CapsuleGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"capsule\", options);\n }\n polyhedron(options: ParamsOf<PolyhedronGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"polyhedron\", options);\n }\n extrude(options: ParamsOf<ExtrudeGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"extrude\", options);\n }\n lathe(options: ParamsOf<LatheGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"lathe\", options);\n }\n tube(options: ParamsOf<TubeGeometry3D> & MeshShorthand3D): this {\n return this.sugar(\"tube\", options);\n }\n\n // ─── Other drawables ─────────────────────────────────────────────────────\n\n /**\n * Record many copies of one geometry in a single draw call. The way to put\n * thousands of objects on screen — a plain `mesh` per copy would not keep up.\n *\n * g3.instances(Geo.box({ width: 0.2 }), Mat.standard({ color: \"cyan\" }),\n * positions.map(p => ({ position: p })))\n */\n instances(\n geometry: Geometry3D,\n material: Material3D,\n instances: readonly Transform3D[],\n options?: { colors?: readonly Color[]; transform?: Transform3D },\n ): this {\n this.record({\n kind: \"instances\",\n geometry,\n material,\n instances,\n colors: options?.colors,\n transform: options?.transform,\n });\n return this;\n }\n\n /** Record a point cloud — one sprite-like dot per vertex of `geometry`. */\n points(\n geometry: Geometry3D,\n material?: Material3D,\n transform?: Transform3D,\n ): this {\n this.record({\n kind: \"points\",\n geometry,\n material: material ?? { type: \"points\" },\n transform,\n });\n return this;\n }\n\n /**\n * Record a line. Give it either explicit `points` or a `geometry` (typically\n * `Geo.edges(...)` for a wireframe outline).\n *\n * `closed` joins the last point back to the first, as the 2D `line` op's\n * own field does. `segments` treats the points as disjoint start/end pairs\n * instead — the form `Geo.edges(...)` produces. (There is no subdivision to\n * confuse it with: a line is drawn from the points it is given.)\n */\n line(options: {\n points?: readonly Vector3Input[];\n geometry?: Geometry3D;\n material?: Material3D;\n /** Join the last point back to the first. */\n closed?: boolean;\n /** Treat the points as disjoint start/end pairs. */\n segments?: boolean;\n /** The line's paint. Cap and join have no meaning on a GL line. */\n stroke?: LineStroke3D;\n opacity?: number;\n transform?: Transform3D;\n } & Transform3D): this {\n const { points, geometry, material, closed, segments, stroke, opacity } = options;\n\n if (!points && !geometry) {\n throw new Error(\"Graphics3D.line() needs either `points` or `geometry`.\");\n }\n\n const resolved: Material3D = material ?? {\n type: stroke?.dash !== undefined ? \"lineDashed\" : \"lineBasic\",\n ...(stroke?.fill !== undefined ? { color: stroke.fill } : {}),\n ...(stroke?.weight !== undefined ? { width: stroke.weight } : {}),\n ...(stroke?.dash !== undefined\n ? { dashSize: stroke.dash[0], gapSize: stroke.dash[1] ?? stroke.dash[0] }\n : {}),\n ...(opacity !== undefined ? { opacity } : {}),\n } as Material3D;\n\n this.record({\n kind: \"line\",\n geometry: geometry ?? lineBuffer(points!),\n material: resolved,\n mode: segments ? \"segments\" : closed ? \"loop\" : \"strip\",\n transform: pickTransform(options),\n });\n return this;\n }\n\n /** Record a camera-facing textured quad. */\n sprite(options: { fill?: Fill3D; material?: Material3D; opacity?: number } & Transform3D): this {\n const { fill, material, opacity } = options;\n const paint = resolveFill3D(fill);\n const resolved: Material3D = material ?? {\n type: \"sprite\",\n ...(paint.map !== undefined ? { map: paint.map } : {}),\n ...(paint.color !== undefined ? { color: paint.color } : {}),\n ...(opacity !== undefined ? { opacity } : {}),\n } as Material3D;\n this.record({\n kind: \"sprite\",\n material: resolved,\n transform: pickTransform(options),\n });\n return this;\n }\n\n /**\n * Record a loaded model. **glTF/GLB only**: any other format (an `.obj`, say)\n * resolves to an empty slot and draws nothing, and in development the first\n * one recorded warns.\n *\n * Baked animation is sampled by explicit `time`, never advanced by a delta, so\n * a model stays frame-identical under scrubbing.\n */\n model(options: {\n src: string;\n animation?: ModelAnimation3D | readonly ModelAnimation3D[];\n override?: Readonly<Record<string, Material3D>>;\n } & Transform3D): this {\n const { src, animation, override } = options;\n this.record({\n kind: \"model\",\n src,\n animation: animation === undefined\n ? undefined\n : Array.isArray(animation) ? animation : [animation as ModelAnimation3D],\n override,\n transform: pickTransform(options),\n });\n return this;\n }\n\n // ─── Consumption ─────────────────────────────────────────────────────────\n\n /** The recorded ops, in order. Replayed by the renderer. */\n ops(): readonly Graphics3DOp[] {\n return this._ops;\n }\n\n /** True when this node draws nothing. */\n isEmpty(): boolean {\n return this._ops.length === 0;\n }\n}\n\n/**\n * A 3D line's paint, named after the 2D `Stroke` it mirrors.\n *\n * `cap`, `join` and the rest of the 2D stroke vocabulary are deliberately absent:\n * they describe a stroked *path*, and a GL line has no outline to cap. Note that\n * `weight` above 1 is ignored by most WebGL implementations — for a genuinely\n * thick line, draw a `tube`.\n */\nexport interface LineStroke3D {\n /** The line's colour. Named `fill` to match the 2D `Stroke`. */\n fill?: Color;\n weight?: number;\n /** Dash and gap lengths, in world units. */\n dash?: readonly [number, number?];\n}\n\n/** The buffer each points array was last flattened into, and the revision it was uploaded under. */\nconst lineBuffers = new WeakMap<readonly Vector3Input[], { readonly position: Float32Array; readonly revision: number }>();\nlet lineRevision = 0;\n\n/**\n * `points` as a line's buffer. The same array holding the same values gets the\n * same buffer and revision back, so a renderer uploads an unchanged line once,\n * not every frame; the values are checked, so one changed in place still lands.\n */\nfunction lineBuffer(points: readonly Vector3Input[]): BufferGeometry3D {\n let kept = lineBuffers.get(points);\n if (!kept || !holds(kept.position, points)) {\n kept = { position: flattenPoints(points), revision: ++lineRevision };\n lineBuffers.set(points, kept);\n }\n return { type: \"buffer\", position: kept.position, revision: kept.revision };\n}\n\n/** Flatten `Vector3Input`s into the packed `[x, y, z, …]` a buffer wants. */\nfunction flattenPoints(points: readonly Vector3Input[]): Float32Array {\n const out = new Float32Array(points.length * 3);\n let i = 0;\n for (const point of points) {\n if (typeof point === \"number\") {\n out[i] = out[i + 1] = out[i + 2] = point;\n } else if (Array.isArray(point)) {\n out[i] = point[0] ?? 0;\n out[i + 1] = point[1] ?? 0;\n out[i + 2] = point[2] ?? 0;\n } else {\n const v = point as { x: number; y: number; z: number };\n out[i] = v.x ?? 0;\n out[i + 1] = v.y ?? 0;\n out[i + 2] = v.z ?? 0;\n }\n i += 3;\n }\n return out;\n}\n\n/** Whether `buffer` is what flattening `points` would give. */\nfunction holds(buffer: Float32Array, points: readonly Vector3Input[]): boolean {\n if (buffer.length !== points.length * 3) return false;\n let i = 0;\n for (const point of points) {\n let x: number, y: number, z: number;\n if (typeof point === \"number\") {\n x = y = z = point;\n } else if (Array.isArray(point)) {\n x = point[0] ?? 0;\n y = point[1] ?? 0;\n z = point[2] ?? 0;\n } else {\n const v = point as { x: number; y: number; z: number };\n x = v.x ?? 0;\n y = v.y ?? 0;\n z = v.z ?? 0;\n }\n if (buffer[i] !== Math.fround(x) || buffer[i + 1] !== Math.fround(y) || buffer[i + 2] !== Math.fround(z)) return false;\n i += 3;\n }\n return true;\n}\n", "import type { Graphics3D } from \"./graphics3d\";\nimport type { CameraData3D } from \"./camera\";\nimport type { LightData3D } from \"./light\";\nimport type {\n EnvironmentData3D, FogData3D, PostEffect3D, Shadows3D, ToneSettings3D,\n} from \"./scene-settings\";\nimport type { Transform3D } from \"./transform\";\nimport type { Color } from \"@/attributes/shape/fill/color/parser\";\n\n/**\n * Per-node state supplied to {@link RenderContext3D.begin} for the duration of a\n * `Node3D`'s draw scope — the 3D counterpart of `NodeRenderState`.\n *\n * There is no layout rect and no motion here, because neither means anything for\n * an object in space: a 3D node's whole placement *is* its `transform`.\n */\nexport interface Node3DRenderState {\n /**\n * Stable node identifier.\n *\n * This is what gives the renderer's cache real identity: keyed by the node\n * that recorded it, a drawable survives a conditional sibling appearing or\n * disappearing, where a positional index would renumber and rebuild the tail.\n */\n id: string;\n /** This node's placement relative to its parent. */\n transform?: Transform3D;\n}\n\n/**\n * The rendering context passed to every `Node3D` when it draws itself.\n *\n * The 3D sibling of `RenderContext2D`, and deliberately not its subclass: the two\n * share no members, because a 3D scene is described with a camera, lights and\n * meshes rather than with paths, paint and clips.\n *\n * The division of labour mirrors 2D exactly. A {@link Graphics3D} is *what one\n * node draws* — geometry and material, nothing else — the way a `Graphics2D` is\n * shapes and paint. Everything that belongs to the scene rather than to a thing\n * in it is a call on the context:\n *\n * protected renderSelf(ctx: RenderContext3D): void {\n * ctx.light({ type: \"ambient\", intensity: 0.4 });\n * }\n *\n * `begin(state)` / `end()` bracket each node's draw call and carry its identity\n * and placement, so nesting is the node tree's nesting and the renderer can\n * cache per node rather than per slot.\n *\n * `Scene3D` is the implementation core ships; it records the calls into a value a\n * backend replays.\n *\n * There is no `background`. What is drawn behind a 3D scene is either a **2D\n * fill** on the viewport — which composites correctly already, is unaffected by\n * anything in the 3D pass, and gets the whole fill chain — or a sky, which is\n * part of {@link environment} because an HDRI that lights a scene and the\n * panorama you see behind it are one thing.\n */\nexport abstract class RenderContext3D {\n /**\n * Open a node draw scope. Must be paired with {@link end}. Everything\n * recorded until then is nested under this node and inherits its transform.\n */\n abstract begin(state: Node3DRenderState): void;\n\n /** Close the innermost scope opened by {@link begin}. */\n abstract end(): void;\n\n /** Draw what this node paints. */\n abstract draw(graphics: Graphics3D): void;\n\n /** Add a light at the current scope. */\n abstract light(light: LightData3D, transform?: Transform3D): void;\n\n /**\n * Place the scene camera at the current scope.\n *\n * Recorded in the hierarchy rather than set as a scene-wide field, so a camera\n * nested inside a moving group is carried by that group — the renderer\n * composes its world transform the same way it does for a mesh. A scene with\n * no camera gets a default framing; a scene that declares more than one keeps\n * the last, since there is only ever one view.\n */\n abstract camera(camera: CameraData3D): void;\n\n // ── Scene-wide settings ──────────────────────────────────────────────────\n //\n // Unlike a light or a camera these have no position, so they are not\n // hierarchical: a scene has exactly one fog and one environment, and the last\n // node to set one wins.\n\n /** Set the scene fog. A bare colour is sugar for `{ color }`; `null` clears it. */\n abstract fog(fog: FogData3D | Color | null): void;\n /** Set the image-based lighting environment and sky, or `null` for none. */\n abstract environment(environment: EnvironmentData3D | null): void;\n /** Enable/configure shadow casting for the whole scene. */\n abstract shadows(settings?: Shadows3D): void;\n /** Set tone mapping and exposure. */\n abstract tone(settings: ToneSettings3D): void;\n /** Append post-processing passes, applied in order after the scene renders. */\n abstract post(effects: PostEffect3D | readonly PostEffect3D[]): void;\n}\n", "import type { Color } from \"@/attributes/shape/fill/color/parser\";\nimport type { Passthrough3D } from \"./geometry\";\nimport type { Uniform3D } from \"./material\";\nimport type { Vector3Input } from \"./vector3\";\n\n/**\n * Depth haze that fades distant geometry toward a colour.\n *\n * One shape rather than a discriminated pair: setting {@link density} is\n * exponential fog and setting {@link near}/{@link far} is linear, which is what\n * the old `type` field said twice. Writing `type: \"exponential\"` beside a `far`\n * silently dropped the `far`; there is nothing to get wrong now.\n *\n * `color` is derived from the viewport's own fill when omitted. Fog that does not\n * match what is behind it reads as a grey wall rather than as distance, and the\n * two colours being separately typed by hand is exactly how they drift.\n */\nexport interface FogData3D {\n color?: Color;\n /** Linear fog: distance at which fog begins. */\n near?: number;\n /** Linear fog: distance at which fog is total. */\n far?: number;\n /** Exponential-squared falloff. Wins over {@link near}/{@link far}. */\n density?: number;\n}\n\n/**\n * Image-based lighting, and the sky it comes from.\n *\n * Light and background are one control because they are one physical thing: an\n * HDRI that lights a scene is the same panorama you see behind it, and having\n * them as two nodes meant setting one, wondering why metal was black or why the\n * sky was missing, and setting the other.\n *\n * This is also *all* that is left of the old `Background3D`. A solid colour, a\n * gradient or a flat image behind the scene is a **2D fill** — `Canvas3D` is a\n * `Rect` and already composites its 3D pass over its own fill layers, the\n * renderer already clears transparent, and neither lighting nor fog touches a\n * three background, so the 3D path was doing strictly less than the 2D one it sat\n * in front of. What genuinely needs the 3D pass is a sky that *reprojects* as the\n * camera turns, which is this.\n *\n * ── What renders today ────────────────────────────────────────────────────────\n * Only {@link preset} `\"studio\"` (a neutral grey room generated per renderer).\n * {@link src} and {@link faces} are declared, tracked by the asset window and\n * recorded, but no backend loads an HDR, EXR or cubemap: an environment that\n * names only those lights nothing and draws no {@link background}. {@link params}\n * is not applied either. In development, the first of each warns.\n */\nexport interface EnvironmentData3D extends Passthrough3D {\n /**\n * A 360° panorama — `.hdr`/`.exr` for real IBL, or a plain image.\n * **Not loaded yet**: see the note on the type.\n */\n src?: string;\n /**\n * Six faces, in three's order: +X, −X, +Y, −Y, +Z, −Z.\n * **Not loaded yet**: see the note on the type.\n */\n faces?: readonly string[];\n /** A built-in studio interior. Needs no asset — the fastest way to good metal. The only environment that renders. */\n preset?: \"studio\";\n /** Multiplies the light received. Default 1. */\n intensity?: number;\n /** Rotate the panorama, in **degrees**. */\n rotation?: Vector3Input;\n /** Also draw it behind the scene, as an infinitely distant sky. Draws the `preset`; there is nothing to draw for `src`/`faces`. */\n background?: boolean;\n /** Blur applied to the background only, 0–1. Leaves the lighting sharp. */\n blur?: number;\n}\n\n/**\n * Scene-wide shadow settings.\n *\n * `quality` stands in for the map resolution and the filter three exposes\n * separately (`pcf`, `pcfSoft`, `vsm`, `mapSize`): those two are chosen together\n * in practice, and neither is a design decision. Individual lights soften their\n * own shadow; objects opt out with `shadow={false}`.\n *\n * Enabling shadows recompiles every material that receives them, so treat this as\n * setup rather than something to animate.\n */\nexport interface ShadowSettings3D {\n enabled?: boolean;\n /** Default `\"medium\"`. */\n quality?: \"low\" | \"medium\" | \"high\";\n}\n\n/** Shadows as written on a viewport: a switch, or the settings. */\nexport type Shadows3D = boolean | ShadowSettings3D;\n\n/** Normalize a viewport's `shadows` prop. */\nexport function resolveShadows3D(value: Shadows3D | undefined): ShadowSettings3D | null {\n if (value === undefined || value === false) return null;\n if (value === true) return { enabled: true };\n return { enabled: true, ...value };\n}\n\n/**\n * How high-dynamic-range colour is mapped into displayable range.\n *\n * `\"aces\"` is the filmic default most renderers use and handles bright\n * highlights gracefully; `\"none\"` clips them. Materials opt out individually with\n * `toneMapped: false` — useful for UI-like overlays that must keep an exact colour.\n */\nexport type ToneMapping3D =\n | \"none\"\n | \"linear\"\n | \"reinhard\"\n | \"cineon\"\n | \"aces\"\n | \"agx\"\n | \"neutral\";\n\n/** Tone mapping and exposure, as a viewport carries them. */\nexport interface ToneSettings3D {\n mapping?: ToneMapping3D;\n /** Stops of exposure applied before mapping. Default 1. */\n exposure?: number;\n}\n\n/**\n * A full-frame post-processing pass, applied after the scene renders.\n *\n * Deliberately short, because most of what used to be here is a 2D effect. A\n * `Canvas3D` is a `Node2D`, so it already carries the whole `effects` chain —\n * vignette, grain, colour grading, blur, chromatic aberration and the rest run\n * over the composited result with no 3D pass involved, and post-process\n * antialiasing is what the viewport's own `antialias` already does with MSAA.\n *\n * What is left are the passes that genuinely need what only the 3D pass has:\n * `ssao` and `dof` read the depth buffer, `outline` reads object ids, and `bloom`\n * reads **HDR radiance before tone mapping** — which is why an emissive surface\n * blooms here and merely brightens under the 2D chain. `shaderPass` stays as the\n * escape hatch for a pass that needs to sit inside the 3D composite.\n *\n * Post-processing forces the render through an offscreen target, so a scene with\n * any of these costs more than one without, even for a cheap effect.\n *\n * **No pass is applied yet.** The chain is recorded on the scene and read only to\n * track the textures a `shaderPass` names; a scene with `bloom` renders exactly\n * like one without, and so does every `params` on an effect. The first `post` set\n * in development warns. Until the passes land, use the 2D `effects` of the\n * `Canvas3D`, which run over its composited result.\n */\nexport type PostEffect3D =\n /** Bleeds light from bright pixels, in HDR. What makes `emission` actually glow. */\n | ({ type: \"bloom\"; strength?: number; radius?: number; threshold?: number } & Passthrough3D)\n /** Contact shadows in creases, from screen-space geometry. */\n | ({ type: \"ssao\"; radius?: number; intensity?: number } & Passthrough3D)\n | ({ type: \"outline\"; color?: Color; thickness?: number } & Passthrough3D)\n /** Depth of field. `focus` is the sharp distance, `aperture` the blur strength. */\n | ({ type: \"dof\"; focus?: number; aperture?: number; maxBlur?: number } & Passthrough3D)\n /** Anything expressible as one fragment pass inside the 3D composite. */\n | ({ type: \"shaderPass\"; fragment: string; uniforms?: Readonly<Record<string, Uniform3D>> } & Passthrough3D);\n", "import { DRAWABLE_KINDS, Graphics3D, type Graphics3DOp } from \"./graphics3d\";\nimport { RenderContext3D, type Node3DRenderState } from \"./render-context3d\";\nimport type { CameraData3D, OrthographicCameraData3D, PerspectiveCameraData3D } from \"./camera\";\nimport type { LightData3D } from \"./light\";\nimport {\n resolveShadows3D,\n type EnvironmentData3D, type FogData3D, type PostEffect3D,\n type ShadowSettings3D, type Shadows3D, type ToneSettings3D,\n} from \"./scene-settings\";\nimport { warnInert3D } from \"./inert\";\nimport type { Shadow3D, Transform3D } from \"./transform\";\nimport type { Color } from \"@/attributes/shape/fill/color/parser\";\n\n/** Options accepted by every `Camera3D` node and by {@link Scene3D.perspective}. */\ntype ParamsOf<T extends { type: string }> = Omit<T, \"type\">;\n\n/**\n * One recorded operation in a {@link Scene3D}.\n *\n * A superset of {@link Graphics3DOp}: everything a node draws, plus the four\n * things that describe the scene around it — the `push`/`pop` nesting the node\n * tree produces, the lights in it, and where it is viewed from.\n */\nexport type Scene3DOp =\n | { kind: \"push\"; transform?: Transform3D }\n | { kind: \"pop\" }\n | { kind: \"light\"; light: LightData3D; transform?: Transform3D }\n | { kind: \"camera\"; camera: CameraData3D }\n | Graphics3DOp;\n\n/**\n * A recorded 3D scene — and the {@link RenderContext3D} that records it.\n *\n * One value plays both parts, exactly as `Graphics2D` is both the builder and the\n * thing handed to a backend. A `Node3D` tree draws into it, and the result is a\n * flat op list plus a handful of scene-wide settings that a renderer replays.\n *\n * Almost always produced for you: a `Canvas3D` opens one per frame, walks its\n * `Node3D` children through it and paints the result through its own path. The\n * builder surface below is the escape hatch — it is what lets a scene be shaded\n * through *any* 2D shape rather than only a rect:\n *\n * const scene = new Scene3D()\n * .perspective({ orbit: 30, elevation: 20, distance: 6 })\n * .light({ type: \"ambient\", intensity: 0.4 })\n * .draw(new Graphics3D().box({ width: 2, fill: \"tomato\" }));\n *\n * Text({ text: \"DEPTH\", fontSize: 320, fill: scene })\n *\n * A bare `Scene3D` coerces to a `canvas3D` fill the way a bare CSS string coerces\n * to a solid one, so `fill={scene}` and `fill={[\"#0b0d12\", scene]}` both work.\n */\nexport class Scene3D extends RenderContext3D {\n private _ops: Scene3DOp[] = [];\n private _camera: CameraData3D | null = null;\n private _fog: FogData3D | null = null;\n private _environment: EnvironmentData3D | null = null;\n private _shadows: ShadowSettings3D | null = null;\n private _tone: ToneSettings3D | null = null;\n private _post: PostEffect3D[] = [];\n /** Open `push` count, so {@link assertBalanced} can report a leak. */\n private _depth = 0;\n /**\n * The `shadow` of each open node scope, innermost last (`undefined` for a\n * scope that states none). What a drawable that states none of its own takes.\n */\n private _shadowScopes: (Shadow3D | undefined)[] = [];\n\n // ─── Node scopes ─────────────────────────────────────────────────────────\n\n override begin(state: Node3DRenderState): void {\n // The node's id rides on the transform's `key`, which is the renderer's\n // identity slot — so a group is cached against the node that opened it\n // rather than against its index among its siblings.\n this._ops.push({ kind: \"push\", transform: { ...state.transform, key: state.id } });\n this._shadowScopes.push(state.transform?.shadow);\n this._depth++;\n }\n\n override end(): void {\n this._ops.push({ kind: \"pop\" });\n this._shadowScopes.pop();\n this._depth--;\n }\n\n // ─── Drawables ───────────────────────────────────────────────────────────\n\n /**\n * Splice what a node draws into the scene at the current scope.\n *\n * The ops are copied rather than referenced: a `Graphics3D` is rebuilt every\n * frame, so there is nothing to share, and a flat list is what the renderer\n * walks.\n *\n * A drawable that states no `shadow` of its own takes the one of the node\n * scope it is drawn in. That is what carries a node's `shadow` to its mesh: the\n * node's scope becomes a group, and a renderer reads casting and receiving off\n * the mesh, never off a group, so the scope's value would otherwise never be\n * seen. A `shadow` on the op itself wins.\n */\n override draw(graphics: Graphics3D): this {\n const ops = graphics.ops();\n const scope = this._shadowScopes[this._shadowScopes.length - 1];\n for (let i = 0; i < ops.length; i++) {\n const op = ops[i];\n if (scope === undefined || op.transform?.shadow !== undefined) {\n this._ops.push(op);\n } else {\n this._ops.push({ ...op, transform: { ...op.transform, shadow: scope } });\n }\n }\n return this;\n }\n\n // ─── Lights ──────────────────────────────────────────────────────────────\n\n override light(light: LightData3D, transform?: Transform3D): this {\n this._ops.push({ kind: \"light\", light, transform });\n return this;\n }\n\n // ─── Camera ──────────────────────────────────────────────────────────────\n\n override camera(camera: CameraData3D): this {\n this._camera = camera;\n this._ops.push({ kind: \"camera\", camera });\n return this;\n }\n\n /** Set a perspective camera. The usual choice. */\n perspective(options?: ParamsOf<PerspectiveCameraData3D>): this {\n return this.camera({ type: \"perspective\", ...options } as PerspectiveCameraData3D);\n }\n\n /** Set an orthographic camera — parallel projection, for isometric looks. */\n orthographic(options?: ParamsOf<OrthographicCameraData3D>): this {\n return this.camera({ type: \"orthographic\", ...options } as OrthographicCameraData3D);\n }\n\n // ─── Scene settings ──────────────────────────────────────────────────────\n //\n // Fields rather than ops: a scene has exactly one fog and one environment.\n // Recording them positionally would imply an ordering that doesn't exist.\n // Last writer wins.\n\n override fog(fog: FogData3D | Color | null): this {\n if (fog === null) {\n this._fog = null;\n } else if (typeof fog === \"object\" && !Array.isArray(fog)) {\n this._fog = fog as FogData3D;\n } else {\n this._fog = { color: fog as Color };\n }\n return this;\n }\n\n override environment(environment: EnvironmentData3D | null): this {\n if (environment) {\n if (environment.src !== undefined || (environment.faces?.length ?? 0) > 0) {\n warnInert3D(\n \"environment-src\",\n \"An environment's `src` and `faces` (HDR, EXR, cubemap) are recorded, and no backend loads them. Only `preset: \\\"studio\\\"` is rendered: \"\n + \"without a preset the scene gets no image-based light and its `background` is not drawn.\",\n );\n }\n if (environment.params && Object.keys(environment.params).length > 0) {\n warnInert3D(\n \"environment-params\",\n \"`params` on an environment is not applied: nothing assigns it onto the generated environment.\",\n );\n }\n }\n this._environment = environment;\n return this;\n }\n\n override shadows(settings?: Shadows3D): this {\n this._shadows = resolveShadows3D(settings ?? true);\n return this;\n }\n\n override tone(settings: ToneSettings3D): this {\n this._tone = settings;\n return this;\n }\n\n override post(effects: PostEffect3D | readonly PostEffect3D[]): this {\n const added = Array.isArray(effects) ? (effects as PostEffect3D[]) : [effects as PostEffect3D];\n if (added.length > 0) {\n warnInert3D(\n \"post\",\n `Post-processing (${added.map((effect) => `\"${effect.type}\"`).join(\", \")}) is recorded, and no backend applies a pass: the scene renders exactly as it would without \\`post\\`. `\n + \"Use the Canvas3D's 2D `effects` over the composited result instead.\",\n );\n }\n this._post.push(...added);\n return this;\n }\n\n // ─── Consumption ─────────────────────────────────────────────────────────\n\n /** The recorded ops, in order. Replayed by the renderer. */\n ops(): readonly Scene3DOp[] {\n return this._ops;\n }\n\n /** The camera, or `null` to let the renderer supply a default framing. */\n cameraDescriptor(): CameraData3D | null {\n return this._camera;\n }\n fogDescriptor(): FogData3D | null {\n return this._fog;\n }\n environmentDescriptor(): EnvironmentData3D | null {\n return this._environment;\n }\n shadowSettings(): ShadowSettings3D | null {\n return this._shadows;\n }\n toneSettings(): ToneSettings3D | null {\n return this._tone;\n }\n postEffects(): readonly PostEffect3D[] {\n return this._post;\n }\n\n /**\n * True when nothing would be drawn — no mesh, light or other drawable. The\n * node skips the whole 3D pass (and the WebGL context entirely) in that case.\n */\n isEmpty(): boolean {\n return !this._ops.some((op) => DRAWABLE_KINDS.has(op.kind));\n }\n\n /**\n * Throw if `push` and `pop` are unbalanced. Called once by the consumer before\n * replay, so a mismatched scope fails loudly rather than silently reparenting\n * everything after it.\n *\n * A `Node3D` tree cannot get this wrong — `begin`/`end` are bracketed by the\n * walk — so in practice this catches a hand-built scene.\n */\n assertBalanced(): void {\n if (this._depth !== 0) {\n const verb = this._depth > 0 ? \"unclosed begin()\" : \"extra end()\";\n throw new Error(\n `Scene3D has ${Math.abs(this._depth)} ${verb}.`,\n );\n }\n }\n}\n", "/**\n * Backend seams for 3D runtime and resource loading.\n *\n * Core describes 3D scenes but cannot load a 3D runtime — `three` lives in the\n * rendering backend, and core must not import it. So core declares the capability\n * here and the backend registers an implementation at module load, the same shape\n * as the other platform seams (`StorageAdapter`, `Ticker`) and the same\n * \"core owns *whether*, backend owns *how*\" split as `EffectSurface`.\n *\n * With no backend registered every function here is an inert no-op, which is what\n * keeps core usable headless and in unit tests.\n */\n\nimport type { Disposer } from \"@/assets/record\";\n\n/** Loads the backend's 3D runtime. Idempotent and memoised by the backend. */\nexport type Canvas3DWarmup = () => Promise<void>;\n\n/**\n * Loads a resource core can't decode itself. `kind` tells the backend which\n * loader to use; the returned {@link Disposer} frees the parsed result when the\n * asset window moves past it.\n */\nexport type Canvas3DResourceKind = \"hdr\" | \"exr\" | \"gltf\" | \"obj\" | \"cubemap\";\nexport type Canvas3DResourceLoader = (kind: Canvas3DResourceKind, src: string) => Promise<Disposer>;\n\n/**\n * The cache key a loader-backed resource is tracked and stored under.\n *\n * Stated once here because **two packages have to agree on it and neither owns\n * both ends**: core's `declare3DResources` declares the key into the asset\n * scope, and the backend's loader is what later looks the parsed result up by\n * it. A backend that built the string itself would be one refactor away from\n * caching under a key nothing ever reads — a model that silently never appears,\n * which is precisely the failure this seam exists to make impossible.\n *\n * `src` goes last and unescaped: it is a URL and may hold colons of its own, so\n * a reader has to split on the first two separators and take the remainder\n * whole rather than splitting on every one — see {@link parseCanvas3DResourceKey}.\n */\nexport function canvas3DResourceKey(kind: Canvas3DResourceKind, src: string): string {\n return `three:${kind}:${src}`;\n}\n\n/**\n * The `kind` and `src` a {@link canvas3DResourceKey} was built from, or `null`\n * when the string is not one.\n *\n * The inverse exists because the backend's warm queue holds keys rather than\n * pairs: `warmPendingCanvas3D` has to re-drive whatever is outstanding knowing\n * only what it was handed.\n */\nexport function parseCanvas3DResourceKey(\n key: string,\n): { kind: Canvas3DResourceKind; src: string } | null {\n if (!key.startsWith(\"three:\")) return null;\n const rest = key.slice(\"three:\".length);\n const split = rest.indexOf(\":\");\n if (split <= 0) return null;\n return {\n kind: rest.slice(0, split) as Canvas3DResourceKind,\n src: rest.slice(split + 1),\n };\n}\n\nlet warmup: Canvas3DWarmup | null = null;\nlet resourceLoader: Canvas3DResourceLoader | null = null;\n\n/**\n * Register the 3D runtime loader. Called by the rendering backend before it draws,\n * never at import — authors never call this.\n */\nexport function registerCanvas3DWarmup(fn: Canvas3DWarmup): void {\n warmup = fn;\n}\n\n/**\n * Register the loader for resource types core can't decode (HDR/EXR env maps,\n * glTF/OBJ models). Called once by the rendering backend.\n */\nexport function registerCanvas3DResourceLoader(fn: Canvas3DResourceLoader): void {\n resourceLoader = fn;\n}\n\n/**\n * Kick off loading the 3D runtime.\n *\n * `Canvas3D.declareAssets()` loads it through the asset timeline — *before* any\n * frame is drawn — so by the time the first 3D frame paints the runtime is\n * normally already resident and the render pass stays synchronous. The renderer\n * still has a per-frame fallback for the case where it isn't.\n *\n * @internal\n */\nexport function warmCanvas3D(): Promise<void> | void {\n return warmup?.();\n}\n\n/** The registered resource loader, or `null` when no backend supplied one. @internal */\nexport function canvas3DResourceLoader(): Canvas3DResourceLoader | null {\n return resourceLoader;\n}\n\n/** True when a backend has registered a 3D runtime. @internal */\nexport function hasCanvas3DBackend(): boolean {\n return warmup !== null;\n}\n", "/**\n * Structural walks over a built {@link Graphics3D} or {@link Scene3D}.\n *\n * A `Graphics3D` is a flat op list with a handful of scene-level descriptors\n * hanging off it, and more than one consumer needs to sweep the same surface for\n * the same thing. {@link forEachTexture3D} is that sweep for textures: asset\n * discovery uses it during precomp to decide what to load, and the renderer uses\n * it at paint time to find the surface textures it has to rasterize first.\n *\n * Keeping it here rather than in either caller is what stops the two from\n * drifting — a texture slot added to a material must be seen by *both*, or a map\n * loads and never draws (or draws and never loads).\n */\n\nimport type { Graphics3D } from \"./graphics3d\";\nimport { Scene3D } from \"./scene3d\";\nimport type { Material3D } from \"./material\";\nimport { looksLikeAssetPath, type Texture3D } from \"./texture\";\n\n/** Material fields that hold a {@link Texture3D}. */\nexport const TEXTURE_KEYS: readonly string[] = [\n \"map\", \"alphaMap\", \"aoMap\", \"normalMap\", \"displacementMap\", \"envMap\",\n \"lightMap\", \"emissionMap\", \"roughnessMap\", \"metalnessMap\", \"specularMap\",\n \"gradientMap\", \"matcap\", \"clearcoatMap\", \"clearcoatNormalMap\",\n \"clearcoatRoughnessMap\", \"transmissionMap\", \"thicknessMap\",\n];\n\n/**\n * True for a texture descriptor object (vs. a plain uniform value).\n *\n * Structural, because {@link Texture3D} has no `type` discriminant — each member\n * is branded by the presence of its own payload key.\n */\nexport function isTextureLike(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n return \"src\" in value || \"data\" in value || \"source\" in value;\n}\n\n/**\n * Visit every {@link Texture3D} a scene references — material map slots, and\n * shader and post-effect uniforms.\n *\n * Visits duplicates; callers dedupe on whatever key they care about. Does **not**\n * cover model/environment resources, which are not textures and go through the\n * backend's own loader — see `declare3DResources`.\n */\nexport function forEachTexture3D(g3: Graphics3D | Scene3D, visit: (texture: Texture3D) => void): void {\n const uniforms = (bag: Record<string, unknown> | undefined): void => {\n if (!bag) return;\n for (const key in bag) {\n const value = bag[key];\n // A bare string is a texture path only when it looks like one; any\n // other string is a colour uniform and names no asset.\n if ((typeof value === \"string\" && looksLikeAssetPath(value)) || isTextureLike(value)) {\n visit(value as Texture3D);\n }\n }\n };\n\n const material = (value: Material3D | readonly Material3D[] | undefined): void => {\n if (value === undefined) return;\n const list = Array.isArray(value) ? value : [value as Material3D];\n for (const entry of list) {\n const bag = entry as unknown as Record<string, unknown>;\n for (const key of TEXTURE_KEYS) {\n if (bag[key] !== undefined) visit(bag[key] as Texture3D);\n }\n // A shader's uniforms can hold textures too.\n uniforms(bag.uniforms as Record<string, unknown> | undefined);\n }\n };\n\n for (const op of g3.ops()) {\n switch (op.kind) {\n case \"mesh\":\n case \"points\":\n case \"line\":\n case \"instances\":\n material(op.material);\n break;\n case \"sprite\":\n material(op.material);\n break;\n case \"model\":\n if (op.override) {\n for (const key in op.override) material(op.override[key]);\n }\n break;\n // push/pop/light reference no textures.\n }\n }\n\n // Only a whole scene has a post chain; what a single node draws has none.\n // The environment's own panorama is not visited here: it is loaded through\n // the backend's HDR/EXR loader rather than the image pipeline, and\n // `trackEnvironment` is what declares it.\n if (!(g3 instanceof Scene3D)) return;\n\n for (const effect of g3.postEffects()) {\n uniforms((effect as { uniforms?: Record<string, unknown> }).uniforms);\n }\n}\n", "/**\n * Cross-type fill coercion for tweening.\n *\n * The renderer dispatches by `fill.type`, so an in-between frame of a tween must\n * be a fully-formed fill of a single concrete type. When the two endpoints of a\n * tween have different types (e.g. a solid `color` animating into a\n * `linear-gradient`, or one gradient kind into another) we first promote both\n * endpoints to a common target type, then run that type's normal `lerp`.\n *\n * The rules, in order:\n *\n * - `color` is treated as a degenerate gradient — a single solid color. It is\n * the least \"rich\" fill, so when one side is a color and the other a\n * gradient, the gradient type wins and the color is expanded into a uniform\n * gradient (every stop set to that color). A uniform gradient renders\n * identically to the flat color, so frame 0 of a color→gradient tween looks\n * exactly like the color, then morphs into the gradient.\n *\n * - Two *different* gradient types share no geometry (a linear gradient's\n * start/end has no radial-gradient counterpart). There is no meaningful\n * in-between for that geometry, so we coerce toward the destination (`to`)\n * type: colors/stops/opacity interpolate while the geometry adopts the\n * destination's, snapped at frame 0.\n *\n * Coercion never mutates its input; it returns a fresh resolved fill.\n */\n\nimport type { NormalizedColor } from \"./color/parser\";\nimport type { FillResolved, FillCommon, FillSpace } from \"./union\";\nimport type { BlendMode } from \"./blend\";\nimport type { SolidFillResolved } from \"./implementations/color\";\nimport type { LinearGradientFillResolved } from \"./implementations/linear-gradient\";\nimport type { RadialGradientFillResolved } from \"./implementations/radial-gradient\";\nimport type { ConicGradientFillResolved } from \"./implementations/conic-gradient\";\n\n/**\n * Resolved fills that carry a `colors` array (every gradient variant), with the\n * cross-cutting {@link FillCommon} fields (`space`) mixed in — mirroring how the\n * registry's `FillResolved` union wraps each implementation in `WithCommon`.\n */\ntype GradientResolved = FillCommon & (\n | LinearGradientFillResolved\n | RadialGradientFillResolved\n | ConicGradientFillResolved\n);\n\n/** Fill types that can participate in cross-type color/gradient tweening. */\nconst GRADIENT_TYPES = new Set<FillResolved[\"type\"]>([\n \"linear-gradient\",\n \"radial-gradient\",\n \"conic-gradient\",\n]);\n\n/** True if `type` is a gradient (linear/radial/conic). */\nexport function isGradientType(type: FillResolved[\"type\"]): boolean {\n return GRADIENT_TYPES.has(type);\n}\n\n/**\n * True if `a` and `b` can be tweened across their differing types — i.e. each is\n * either a solid color or a gradient, and at least one is a gradient. (Same-type\n * pairs are handled by the registry directly and never reach coercion.)\n */\nexport function canCoerce(a: FillResolved, b: FillResolved): boolean {\n const aColorish = a.type === \"solid\" || isGradientType(a.type);\n const bColorish = b.type === \"solid\" || isGradientType(b.type);\n if (!aColorish || !bColorish) return false;\n // At least one gradient — color↔color is same-type and never reaches here.\n return isGradientType(a.type) || isGradientType(b.type);\n}\n\n/** Builds a stop list of `count` evenly spaced positions in [0, 1]. */\nfunction evenStops(count: number): number[] {\n return Array.from({ length: count }, (_, i) => i / Math.max(1, count - 1));\n}\n\n/**\n * Expands a solid color into a gradient of `targetType` whose every stop is that\n * color, matching `stopCount` colors so the resulting gradient lerps cleanly\n * against the real gradient on the other side. The geometry defaults match each\n * gradient's `resolve()` so a uniform gradient renders as a flat color.\n */\nfunction colorToGradient(\n color: NormalizedColor,\n opacity: number | undefined,\n blend: BlendMode | undefined,\n space: FillSpace | undefined,\n targetType: GradientResolved[\"type\"],\n stopCount: number,\n): GradientResolved {\n const n = Math.max(2, stopCount);\n const colors: NormalizedColor[] = Array.from({ length: n }, () => [...color] as NormalizedColor);\n const stops = evenStops(n);\n const common = { colors, stops, opacity, blend, space };\n\n switch (targetType) {\n case \"linear-gradient\":\n return { type: \"linear-gradient\", ...common, start: { x: -1, y: 1 }, end: { x: 1, y: -1 } };\n case \"radial-gradient\":\n return { type: \"radial-gradient\", ...common, center: { x: 0, y: 0 }, radius: 100 };\n case \"conic-gradient\":\n return { type: \"conic-gradient\", ...common, center: { x: 0, y: 0 }, startAngle: 0 };\n }\n}\n\n/**\n * Re-types a gradient as `targetType`, carrying its colors/stops/opacity and\n * adopting the target type's default geometry. Used when tweening between two\n * different gradient kinds, whose geometries are not interpolatable.\n */\nfunction retypeGradient(\n g: GradientResolved,\n targetType: GradientResolved[\"type\"],\n): GradientResolved {\n if (g.type === targetType) return g;\n const common = { colors: g.colors, stops: g.stops, opacity: g.opacity, blend: g.blend, space: g.space };\n switch (targetType) {\n case \"linear-gradient\":\n return { type: \"linear-gradient\", ...common, start: { x: -1, y: 1 }, end: { x: 1, y: -1 } };\n case \"radial-gradient\":\n return { type: \"radial-gradient\", ...common, center: { x: 0, y: 0 }, radius: 100 };\n case \"conic-gradient\":\n return { type: \"conic-gradient\", ...common, center: { x: 0, y: 0 }, startAngle: 0 };\n }\n}\n\n/**\n * Promotes two differing-type fills (color and/or gradient) to a single common\n * type so the registry can lerp them with that type's `lerp`. Returns the\n * coerced `[a, b]` pair, both guaranteed to share `result[0].type`.\n *\n * Caller must have checked {@link canCoerce} first.\n */\nexport function coercePair(a: FillResolved, b: FillResolved): [FillResolved, FillResolved] {\n const aIsColor = a.type === \"solid\";\n const bIsColor = b.type === \"solid\";\n\n // color → gradient: expand the color to match the gradient's type.\n if (aIsColor && !bIsColor) {\n const grad = b as GradientResolved;\n const expanded = colorToGradient(\n (a as SolidFillResolved).color, a.opacity, a.blend, a.space, grad.type, grad.colors.length,\n );\n return [expanded, grad];\n }\n // gradient → color: expand the color (b) to match the gradient's (a) type.\n if (bIsColor && !aIsColor) {\n const grad = a as GradientResolved;\n const expanded = colorToGradient(\n (b as SolidFillResolved).color, b.opacity, b.blend, b.space, grad.type, grad.colors.length,\n );\n return [grad, expanded];\n }\n\n // Two different gradient types: coerce toward the destination (b) type.\n const ga = a as GradientResolved;\n const gb = b as GradientResolved;\n return [retypeGradient(ga, gb.type), gb];\n}\n", "import { Color, NormalizedColor, parseColor } from '../color/parser';\nimport type { BlendMode } from '../blend';\nimport type { FillData } from '../registry';\nimport { lerpNumber } from '@/tween/lerp';\n\nexport interface SolidFillProp {\n type: 'solid';\n color: Color;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface SolidFillResolved {\n type: 'solid';\n color: NormalizedColor;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport const colorFill: FillData<SolidFillResolved> = {\n resolve: (prop: SolidFillProp) => ({\n type: 'solid',\n color: Array.isArray(prop.color)\n ? (prop.color as NormalizedColor)\n : parseColor(prop.color as string),\n opacity: prop.opacity,\n blend: prop.blend,\n }),\n lerp: (a, b, t) => ({\n color: [\n lerpNumber(a.color[0], b.color[0], t),\n lerpNumber(a.color[1], b.color[1], t),\n lerpNumber(a.color[2], b.color[2], t),\n lerpNumber(a.color[3], b.color[3], t),\n ],\n opacity: (a.opacity ?? 1) + ((b.opacity ?? 1) - (a.opacity ?? 1)) * t,\n }),\n equals: (a, b) => a.color === b.color,\n};\n", "import type { NormalizedColor } from './color/parser';\nimport { lerpColor } from './lerp';\n\n/** A colour ramp: `colors[i]` sits at `stops[i]` (ascending, 0 to 1). */\nexport interface ColorRamp {\n colors: NormalizedColor[];\n stops: number[];\n}\n\n/** The colour of `ramp` at `position`: clamped past either end, linear between stops. */\nfunction sampleRamp(ramp: ColorRamp, position: number): NormalizedColor {\n const { colors, stops } = ramp;\n const last = colors.length - 1;\n if (position <= stops[0]) return colors[0];\n if (position >= stops[last]) return colors[last];\n let hi = 1;\n while (stops[hi] < position) hi++;\n const lo = hi - 1;\n const span = stops[hi] - stops[lo];\n return lerpColor(colors[lo], colors[hi], span > 0 ? (position - stops[lo]) / span : 0);\n}\n\n/**\n * The colour of `ramp` for the `k`-th of several stops that share `position`: the\n * ramp's own stop there when it has one (a hard edge keeps both sides), else\n * the interpolated value.\n */\nfunction colorAt(ramp: ColorRamp, position: number, k: number): NormalizedColor {\n const first = ramp.stops.indexOf(position);\n if (first === -1) return sampleRamp(ramp, position);\n let count = 1;\n while (ramp.stops[first + count] === position) count++;\n return ramp.colors[first + Math.min(k, count - 1)];\n}\n\nconst sameStops = (a: number[], b: number[]) => a.length === b.length && a.every((s, i) => s === b[i]);\n\n/**\n * Interpolates two colour ramps. Two ramps with the same stop positions are\n * blended stop by stop. Otherwise both are resampled onto the union of their\n * positions first (a position either ramp doubles, as for a hard edge, is kept\n * doubled), so a tween between a 2-stop and a 3-stop gradient is the destination\n * ramp at `t = 1` rather than the source's stop count with the destination's\n * colours merged in.\n */\nexport function lerpColorRamp(a: ColorRamp, b: ColorRamp, t: number): ColorRamp {\n if (sameStops(a.stops, b.stops)) {\n return {\n colors: a.colors.map((c, i) => lerpColor(c, b.colors[i], t)),\n stops: a.stops.slice(),\n };\n }\n const count = new Map<number, number>();\n for (const ramp of [a, b]) {\n const own = new Map<number, number>();\n for (const s of ramp.stops) own.set(s, (own.get(s) ?? 0) + 1);\n for (const [s, n] of own) count.set(s, Math.max(count.get(s) ?? 0, n));\n }\n const colors: NormalizedColor[] = [];\n const stops: number[] = [];\n for (const position of [...count.keys()].sort((x, y) => x - y)) {\n for (let k = 0; k < count.get(position)!; k++) {\n colors.push(lerpColor(colorAt(a, position, k), colorAt(b, position, k), t));\n stops.push(position);\n }\n }\n return { colors, stops };\n}\n", "import { Color, NormalizedColor, parseColor } from '../color/parser';\nimport type { BlendMode } from '../blend';\nimport type { FillData } from '../registry';\nimport { lerpColorRamp } from '../gradient-stops';\nimport { lerpVector2, Vector2 } from '@/attributes/layout/vector2';\n\nexport interface LinearGradientFillProp {\n type: 'linear-gradient';\n colors: Color[];\n stops?: number[];\n start?: Vector2;\n end?: Vector2;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface LinearGradientFillResolved {\n type: 'linear-gradient';\n colors: NormalizedColor[];\n stops: number[];\n start: Vector2;\n end: Vector2;\n opacity?: number;\n blend?: BlendMode;\n}\n\nfunction toNormalized(c: Color): NormalizedColor {\n return Array.isArray(c) ? (c as NormalizedColor) : parseColor(c as string);\n}\n\nexport const linearGradientFill: FillData<LinearGradientFillResolved> = {\n resolve: (prop: LinearGradientFillProp) => ({\n type: 'linear-gradient',\n colors: prop.colors.map(toNormalized),\n stops: prop.stops ?? prop.colors.map((_, i) => i / Math.max(1, prop.colors.length - 1)),\n start: prop.start ?? { x: -1, y: 1 },\n end: prop.end ?? { x: 1, y: -1 },\n opacity: prop.opacity,\n blend: prop.blend,\n }),\n lerp: (a, b, t) => ({\n ...lerpColorRamp(a, b, t),\n start: lerpVector2(a.start, b.start, t),\n end: lerpVector2(a.end, b.end, t),\n opacity: (a.opacity ?? 1) + ((b.opacity ?? 1) - (a.opacity ?? 1)) * t,\n }),\n equals: (a, b) =>\n a.start.x === b.start.x && a.start.y === b.start.y &&\n a.end.x === b.end.x && a.end.y === b.end.y &&\n a.colors.length === b.colors.length &&\n a.colors.every((c, i) => c === b.colors[i]),\n};\n", "import { Color, NormalizedColor, parseColor } from '../color/parser';\nimport type { BlendMode } from '../blend';\nimport type { FillData } from '../registry';\nimport { lerpColorRamp } from '../gradient-stops';\nimport { lerpNumber } from '@/tween/lerp';\nimport { lerpVector2, Vector2 } from '@/attributes/layout/vector2';\n\nexport interface RadialGradientFillProp {\n type: 'radial-gradient';\n colors: Color[];\n stops?: number[];\n center?: Vector2;\n radius?: number;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface RadialGradientFillResolved {\n type: 'radial-gradient';\n colors: NormalizedColor[];\n stops: number[];\n center: Vector2;\n radius: number;\n opacity?: number;\n blend?: BlendMode;\n}\n\nfunction toNormalized(c: Color): NormalizedColor {\n return Array.isArray(c) ? (c as NormalizedColor) : parseColor(c as string);\n}\n\nexport const radialGradientFill: FillData<RadialGradientFillResolved> = {\n resolve: (prop: RadialGradientFillProp) => ({\n type: 'radial-gradient',\n colors: prop.colors.map(toNormalized),\n stops: prop.stops ?? prop.colors.map((_, i) => i / Math.max(1, prop.colors.length - 1)),\n center: prop.center ?? { x: 0, y: 0 },\n radius: prop.radius ?? 100,\n opacity: prop.opacity,\n blend: prop.blend,\n }),\n lerp: (a, b, t) => ({\n ...lerpColorRamp(a, b, t),\n center: lerpVector2(a.center, b.center, t),\n radius: lerpNumber(a.radius, b.radius, t),\n opacity: lerpNumber(a.opacity ?? 1, b.opacity ?? 1, t),\n }),\n equals: (a, b) =>\n a.center.x === b.center.x && a.center.y === b.center.y &&\n a.radius === b.radius &&\n a.colors.length === b.colors.length &&\n a.colors.every((c, i) => c === b.colors[i]),\n};\n", "import { Color, NormalizedColor, parseColor } from '../color/parser';\nimport type { BlendMode } from '../blend';\nimport type { FillData } from '../registry';\nimport { lerpColorRamp } from '../gradient-stops';\nimport { lerpNumber } from '@/tween/lerp';\nimport { lerpVector2, Vector2 } from '@/attributes/layout/vector2';\n\nexport interface ConicGradientFillProp {\n type: 'conic-gradient';\n colors: Color[];\n stops?: number[];\n center?: Vector2;\n startAngle?: number;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface ConicGradientFillResolved {\n type: 'conic-gradient';\n colors: NormalizedColor[];\n stops: number[];\n center: Vector2;\n startAngle?: number;\n opacity?: number;\n blend?: BlendMode;\n}\n\nfunction toNormalized(c: Color): NormalizedColor {\n return Array.isArray(c) ? (c as NormalizedColor) : parseColor(c as string);\n}\n\nexport const conicGradientFill: FillData<ConicGradientFillResolved> = {\n resolve: (prop: ConicGradientFillProp) => ({\n type: 'conic-gradient',\n colors: prop.colors.map(toNormalized),\n stops: prop.stops ?? prop.colors.map((_, i) => i / Math.max(1, prop.colors.length - 1)),\n center: prop.center ?? { x: 0, y: 0 },\n startAngle: prop.startAngle,\n opacity: prop.opacity,\n blend: prop.blend,\n }),\n lerp: (a, b, t) => ({\n ...lerpColorRamp(a, b, t),\n center: lerpVector2(a.center, b.center, t),\n startAngle: lerpNumber(a.startAngle ?? 0, b.startAngle ?? 0, t),\n opacity: lerpNumber(a.opacity ?? 1, b.opacity ?? 1, t),\n }),\n equals: (a, b) =>\n a.center.x === b.center.x && a.center.y === b.center.y &&\n (a.startAngle ?? 0) === (b.startAngle ?? 0) &&\n a.colors.length === b.colors.length &&\n a.colors.every((c, i) => c === b.colors[i]),\n};\n", "import { Color, NormalizedColor, parseColor } from '../color/parser';\nimport type { BlendMode } from '../blend';\nimport type { FillData } from '../registry';\nimport { lerpNumber } from '@/tween/lerp';\nimport { Vector2 } from '@/attributes/layout/vector2';\n\n/**\n * Sparse per-pixel speckle — dust, static, stipple.\n *\n * A *source*, painted inside the shape's own path: unlike `Effects.grain`, which\n * modulates whatever has already been drawn (including children and, in backdrop\n * mode, what lies beneath), this simply stacks as another fill layer. Reach for\n * the effect to grain a composite; reach for this to texture one shape.\n *\n * For a continuous noise *field* rather than speckle — cloud, marble, smoke —\n * see {@link FractalNoiseFillProp}.\n */\nexport interface NoiseFillProp {\n type: 'noise';\n size?: Vector2;\n density?: number;\n color?: Color;\n /**\n * Random field offset. Tween it to make the speckle crawl — without this the\n * field is fixed, and animated static could only be had from the grain effect.\n */\n seed?: number;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface NoiseFillResolved {\n type: 'noise';\n size: Vector2;\n density: number;\n color: NormalizedColor;\n seed: number;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport const noiseFill: FillData<NoiseFillResolved> = {\n resolve: (prop: NoiseFillProp) => {\n const raw = prop.color ?? ([0, 0, 0, 1] as NormalizedColor);\n return {\n type: 'noise',\n size: prop.size ?? { x: 1, y: 1 },\n density: prop.density ?? 1,\n color: Array.isArray(raw) ? (raw as NormalizedColor) : parseColor(raw as string),\n seed: prop.seed ?? 0,\n opacity: prop.opacity,\n blend: prop.blend,\n };\n },\n lerp: (a, b, t) => ({\n size: {\n x: lerpNumber(a.size.x, b.size.x, t),\n y: lerpNumber(a.size.y, b.size.y, t),\n },\n density: lerpNumber(a.density, b.density, t),\n seed: lerpNumber(a.seed, b.seed, t),\n color: [\n lerpNumber(a.color[0], b.color[0], t),\n lerpNumber(a.color[1], b.color[1], t),\n lerpNumber(a.color[2], b.color[2], t),\n lerpNumber(a.color[3], b.color[3], t),\n ],\n opacity: lerpNumber(a.opacity ?? 1, b.opacity ?? 1, t),\n }),\n equals: (a, b) =>\n a.size.x === b.size.x && a.size.y === b.size.y &&\n a.density === b.density &&\n a.seed === b.seed &&\n a.color[0] === b.color[0] && a.color[1] === b.color[1] &&\n a.color[2] === b.color[2] && a.color[3] === b.color[3],\n};\n", "import { Color, NormalizedColor, parseColor } from '../color/parser';\nimport type { BlendMode } from '../blend';\nimport type { FillData } from '../registry';\nimport { lerpColorRamp } from '../gradient-stops';\nimport { lerpNumber } from '@/tween/lerp';\nimport { lerpVector2, Vector2 } from '@/attributes/layout/vector2';\n\n/**\n * Which noise function the octaves are summed from.\n *\n * - `'value'` — smoothed value noise. The cheapest, and the softest: clouds,\n * haze, paper fibre, subtle mottling.\n * - `'simplex'` — gradient noise. More even, fewer axis-aligned artefacts than\n * value noise, and the right default for anything organic seen up close.\n * - `'ridged'` — simplex folded about zero and inverted, so the *zero crossings*\n * become sharp crests. Mountains, lightning, veins, marble.\n * - `'worley'` — cellular (Voronoi) distance. Not a sum of smooth octaves but a\n * distance field, so it gives edges rather than blur: scales, cracked earth,\n * caustics, stained glass.\n */\nexport type FractalNoiseBasis = 'value' | 'simplex' | 'ridged' | 'worley';\n\n/**\n * Fractal (fBm) noise — the procedural material source.\n *\n * Where {@link NoiseFillProp} is sparse per-pixel speckle (dust, static), this\n * is a continuous *field*: several octaves of smooth noise summed at rising\n * frequency and falling amplitude, which is what produces cloud, smoke, marble,\n * wood, terrain and plasma rather than grain.\n *\n * It is a fill, so it paints inside the shape's path and stacks with the rest of\n * the fill array. It composes with the effect layer rather than duplicating it:\n * `duotone` over it is marble, `threshold` over it is an organic matte,\n * `posterize` over it is topographic banding, and `displace` pointed at the same\n * look is water.\n *\n * `seed` shifts the whole field, so tweening it drifts the pattern; tween\n * `offset` instead to *travel* through it, which is what reads as flowing.\n */\nexport interface FractalNoiseFillProp {\n type: 'fractalNoise';\n /** Which noise function the octaves come from (default `'simplex'`). */\n basis?: FractalNoiseBasis;\n /** How many octaves are summed, 1–8 (default 4). Each one doubles the cost. */\n octaves?: number;\n /** Cycles of the first octave across the shape — a number, or per-axis (default 3). */\n frequency?: number | Vector2;\n /** Frequency multiplier per octave (default 2). */\n lacunarity?: number;\n /** Amplitude multiplier per octave; below 1 the detail fades in (default 0.5). */\n gain?: number;\n /** Field offset — random-access into the noise. Animate to drift. */\n seed?: number;\n /** Pan through the field, in cycles. Animate to make the pattern flow. */\n offset?: Vector2;\n /** Rotation of the field in degrees (default 0). */\n angle?: number;\n /** Colours the 0–1 field maps onto, low to high (default black → white). */\n colors?: Color[];\n /** Positions of each colour in 0–1 (default evenly spaced). */\n stops?: number[];\n /** Steepen (>1) or flatten (<1) the field before the ramp (default 1). */\n contrast?: number;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface FractalNoiseFillResolved {\n type: 'fractalNoise';\n basis: FractalNoiseBasis;\n octaves: number;\n frequency: Vector2;\n lacunarity: number;\n gain: number;\n seed: number;\n offset: Vector2;\n angle: number;\n colors: NormalizedColor[];\n stops: number[];\n contrast: number;\n opacity?: number;\n blend?: BlendMode;\n}\n\nfunction toNormalized(c: Color): NormalizedColor {\n return Array.isArray(c) ? (c as NormalizedColor) : parseColor(c as string);\n}\n\nconst BLACK: NormalizedColor = [0, 0, 0, 1];\nconst WHITE: NormalizedColor = [1, 1, 1, 1];\n\n/** Normalise the `frequency` shorthand to a per-axis cycle count. */\nconst toFrequency = (f: number | Vector2 | undefined): Vector2 =>\n f === undefined ? { x: 3, y: 3 } : typeof f === 'number' ? { x: f, y: f } : f;\n\nexport const fractalNoiseFill: FillData<FractalNoiseFillResolved> = {\n resolve: (prop: FractalNoiseFillProp) => {\n const colors = prop.colors?.length ? prop.colors.map(toNormalized) : [BLACK, WHITE];\n return {\n type: 'fractalNoise',\n basis: prop.basis ?? 'simplex',\n // Clamped here rather than in the shader so `equals` and the cache\n // key see the same value the renderer loops over.\n octaves: Math.max(1, Math.min(8, Math.round(prop.octaves ?? 4))),\n frequency: toFrequency(prop.frequency),\n lacunarity: prop.lacunarity ?? 2,\n gain: prop.gain ?? 0.5,\n seed: prop.seed ?? 0,\n offset: prop.offset ?? { x: 0, y: 0 },\n angle: prop.angle ?? 0,\n colors,\n stops: prop.stops ?? colors.map((_, i) => i / Math.max(1, colors.length - 1)),\n contrast: prop.contrast ?? 1,\n opacity: prop.opacity,\n blend: prop.blend,\n };\n },\n lerp: (a, b, t) => ({\n // The basis picks a different noise function entirely, so there is no\n // in-between field to cross to — snap, like every other enum-valued option.\n basis: t < 0.5 ? a.basis : b.basis,\n // Octave count bounds the shader's loop; a fractional one would round.\n octaves: t < 0.5 ? a.octaves : b.octaves,\n frequency: lerpVector2(a.frequency, b.frequency, t),\n lacunarity: lerpNumber(a.lacunarity, b.lacunarity, t),\n gain: lerpNumber(a.gain, b.gain, t),\n seed: lerpNumber(a.seed, b.seed, t),\n offset: lerpVector2(a.offset, b.offset, t),\n angle: lerpNumber(a.angle, b.angle, t),\n ...lerpColorRamp(a, b, t),\n contrast: lerpNumber(a.contrast, b.contrast, t),\n opacity: lerpNumber(a.opacity ?? 1, b.opacity ?? 1, t),\n }),\n equals: (a, b) =>\n a.basis === b.basis &&\n a.octaves === b.octaves &&\n a.frequency.x === b.frequency.x && a.frequency.y === b.frequency.y &&\n a.lacunarity === b.lacunarity &&\n a.gain === b.gain &&\n a.seed === b.seed &&\n a.offset.x === b.offset.x && a.offset.y === b.offset.y &&\n a.angle === b.angle &&\n a.contrast === b.contrast &&\n a.colors.length === b.colors.length &&\n a.colors.every((c, i) => {\n const d = b.colors[i];\n return d != null && c[0] === d[0] && c[1] === d[1] && c[2] === d[2] && c[3] === d[3];\n }) &&\n a.stops.length === b.stops.length &&\n a.stops.every((s, i) => s === b.stops[i]),\n};\n", "import { Color, NormalizedColor, parseColor } from '../color/parser';\nimport type { BlendMode } from '../blend';\nimport type { FillData } from '../registry';\nimport { lerpNumber } from '@/tween/lerp';\n\nexport interface StripeFillProp {\n type: 'stripe';\n gap?: number;\n strokeWidth?: number;\n angle?: number;\n color?: Color;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface StripeFillResolved {\n type: 'stripe';\n gap?: number;\n strokeWidth?: number;\n angle?: number;\n color?: NormalizedColor;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport const stripeFill: FillData<StripeFillResolved> = {\n resolve: (prop: StripeFillProp) => ({\n type: 'stripe',\n gap: prop.gap,\n strokeWidth: prop.strokeWidth,\n angle: prop.angle,\n color: prop.color != null\n ? Array.isArray(prop.color)\n ? (prop.color as NormalizedColor)\n : parseColor(prop.color as string)\n : undefined,\n opacity: prop.opacity,\n blend: prop.blend,\n }),\n lerp: (a, b, t) => ({\n gap: lerpNumber(a.gap ?? 8, b.gap ?? 8, t),\n strokeWidth: lerpNumber(a.strokeWidth ?? 1, b.strokeWidth ?? 1, t),\n angle: lerpNumber(a.angle ?? -45, b.angle ?? -45, t),\n color: a.color && b.color ? [\n lerpNumber(a.color[0], b.color[0], t),\n lerpNumber(a.color[1], b.color[1], t),\n lerpNumber(a.color[2], b.color[2], t),\n lerpNumber(a.color[3], b.color[3], t),\n ] : (a.color ?? b.color),\n opacity: lerpNumber(a.opacity ?? 1, b.opacity ?? 1, t),\n }),\n equals: (a, b) =>\n a.gap === b.gap &&\n a.strokeWidth === b.strokeWidth &&\n a.angle === b.angle &&\n a.color?.[0] === b.color?.[0] && a.color?.[1] === b.color?.[1] &&\n a.color?.[2] === b.color?.[2] && a.color?.[3] === b.color?.[3],\n};\n", "import { Color, NormalizedColor, parseColor } from '../color/parser';\nimport type { BlendMode } from '../blend';\nimport type { FillData } from '../registry';\nimport { lerpNumber } from '@/tween/lerp';\nimport { Vector2 } from '@/attributes/layout/vector2';\n\n/**\n * A regular lattice of dots — the ground under a diagram, graph paper, the\n * printed-halftone look, the \"canvas\" backdrop every design tool draws.\n *\n * Measured in **pixels**, like {@link StripeFillProp} and unlike\n * {@link GridFillProp}: a dot field is a texture, so its pitch should not change\n * when the shape carrying it is resized. That is also what makes `offset` worth\n * having — sliding the lattice is how the field parallaxes, and it is the one\n * piece of geometry a px-space pattern cannot fake by moving the node.\n *\n * Rendered from a shader rather than a baked tile, so `radius` and `spacing`\n * stay exact at fractional values and animating any of them costs a uniform\n * write rather than a texture rebuild.\n */\nexport interface DotGridFillProp {\n type: 'dotGrid';\n /** Dot radius in px. Larger than half of {@link spacing} makes the dots merge. */\n radius?: number;\n /** Distance between one dot's centre and the next, in px, on both axes. */\n spacing?: number;\n /** Shifts the whole lattice, in px. Tween it to drift the field. */\n offset?: Vector2;\n color?: Color;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface DotGridFillResolved {\n type: 'dotGrid';\n radius: number;\n spacing: number;\n offset: Vector2;\n color: NormalizedColor;\n opacity?: number;\n blend?: BlendMode;\n}\n\n/** A 2px dot every 16px: reads as graph paper at 100% without dominating it. */\nconst DEFAULT_RADIUS = 2;\nconst DEFAULT_SPACING = 16;\n\nexport const dotGridFill: FillData<DotGridFillResolved> = {\n resolve: (prop: DotGridFillProp) => {\n const raw = prop.color ?? ([0, 0, 0, 1] as NormalizedColor);\n return {\n type: 'dotGrid',\n radius: prop.radius ?? DEFAULT_RADIUS,\n spacing: prop.spacing ?? DEFAULT_SPACING,\n offset: prop.offset ?? { x: 0, y: 0 },\n color: Array.isArray(raw) ? (raw as NormalizedColor) : parseColor(raw as string),\n opacity: prop.opacity,\n blend: prop.blend,\n };\n },\n lerp: (a, b, t) => ({\n radius: lerpNumber(a.radius, b.radius, t),\n spacing: lerpNumber(a.spacing, b.spacing, t),\n offset: {\n x: lerpNumber(a.offset.x, b.offset.x, t),\n y: lerpNumber(a.offset.y, b.offset.y, t),\n },\n color: [\n lerpNumber(a.color[0], b.color[0], t),\n lerpNumber(a.color[1], b.color[1], t),\n lerpNumber(a.color[2], b.color[2], t),\n lerpNumber(a.color[3], b.color[3], t),\n ],\n opacity: lerpNumber(a.opacity ?? 1, b.opacity ?? 1, t),\n }),\n equals: (a, b) =>\n a.radius === b.radius &&\n a.spacing === b.spacing &&\n a.offset.x === b.offset.x && a.offset.y === b.offset.y &&\n a.color[0] === b.color[0] && a.color[1] === b.color[1] &&\n a.color[2] === b.color[2] && a.color[3] === b.color[3],\n};\n", "import type { BlendMode } from '../blend';\nimport type { FillData } from '../registry';\nimport {\n lerpUniformRecord,\n normalizeUniforms,\n uniformRecordsEqual,\n type ShaderUniform,\n type ShaderUniformRecord,\n} from '../../shaders/uniforms';\nimport { shaderContractOf, type ShaderLanguage } from '../../shaders/language';\n\n/**\n * Ceiling on bound textures: a fill wanting more than a handful is really a 3D\n * scene, and the cap keeps a typo in a generated list from exhausting texture units.\n */\nconst MAX_TEXTURES = 4;\n\n/** An image the shader samples. */\nexport interface ShaderTexture {\n /** The name the shader pack gives this texture. */\n name: string;\n /** Asset path, resolved like any other image fill's `src`. */\n src: string;\n}\n\n/**\n * A custom WGSL shader, painted as a fill.\n *\n * The source defines `fn fill(in: FillIn) -> vec4f`, returning **premultiplied**\n * rgba; `in` carries `uv` (0–1 across the box), `local` (px from the box's\n * top-left), `size`, `time` and `scale` (device px per px), and the uniforms are\n * `u`, a `struct Params` the source declares. The first of `textures` is what\n * `sample_texture(uv)` reads.\n *\n * The escape hatch at the end of the procedural spectrum: where\n * {@link NoiseFillProp} and {@link FractalNoiseFillProp} expose a fixed set of\n * knobs over a fixed field, this hands the whole fragment function to the author.\n * It is still a fill, so it paints inside the shape's own path — an `Ellipse`, a\n * `Path`, a run of `Text` — stacks as one layer in the fill array, and inherits\n * the layer's `opacity`/`blend`/`space` like every other kind.\n *\n * Rect({ fill: Fills.shader(src, { uniforms: { amount: 0.4 } }) })\n * Text({ text: \"DEPTH\", fontSize: 320, fill: Fills.shader(src) })\n *\n * It must *not* fold `opacity` in: the fill layer's opacity is already applied\n * to the output, so a shader applying it again renders at the square of what\n * was asked for.\n *\n * `source` is the compile-cache key, so it **snaps** at a tween's midpoint rather\n * than interpolating — tweening it would compile a program per frame. Keep the\n * source constant (hoist it to module scope) and put everything that changes in a\n * uniform, which costs nothing: uniform values are an in-place write.\n */\nexport interface ShaderFillProp {\n type: 'shader';\n /** The program. Hoist it; don't rebuild it per frame. */\n source: string;\n /** The language `source` is written in; WGSL when absent. */\n language?: ShaderLanguage;\n /** WGSL only: the contract version it is written against (`WGSL_CONTRACT` when absent). */\n contract?: number;\n /**\n * The shader pack this was built from, when it was built from one.\n *\n * **Reserved, and carried rather than read.** A pack resolves to a plain\n * uniform record before it reaches here, so nothing in the render path needs\n * it — the frame is identical with or without it. What it exists for is the\n * trip back: a document stores resolved uniforms, and without a reference to\n * the pack a host reopening a saved scene has a set of numbers and no way to\n * know which of them were `twist` and `ink`, so the property panel it drew\n * when the shader was applied cannot be drawn again.\n *\n * An id naming a pack that is not registered is **not** an error: the shader\n * still renders, because the uniforms it needs are already in the document.\n * The host simply cannot offer the panel.\n */\n shaderId?: string;\n /**\n * Uniform values keyed by their declared name. The positional\n * `[{name, value}]` array is accepted too, so a shader can move between an\n * effect and a fill unchanged.\n */\n uniforms?: ShaderUniformRecord | readonly ShaderUniform[];\n /** Images the shader samples. */\n textures?: readonly ShaderTexture[];\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface ShaderFillResolved {\n type: 'shader';\n source: string;\n language: ShaderLanguage;\n /** WGSL only. See {@link ShaderFillProp.contract}. */\n contract?: number;\n /** See {@link ShaderFillProp.shaderId}. */\n shaderId?: string;\n uniforms: ShaderUniformRecord;\n textures?: ShaderTexture[];\n opacity?: number;\n blend?: BlendMode;\n}\n\n/** Copy the texture list, dropping malformed entries and capping the length. */\nfunction resolveTextures(textures: readonly ShaderTexture[] | undefined): ShaderTexture[] | undefined {\n if (!textures?.length) return undefined;\n const out: ShaderTexture[] = [];\n for (const texture of textures) {\n if (!texture?.name || !texture?.src) continue;\n if (out.length >= MAX_TEXTURES) {\n console.warn(`[shader] A shader fill declares more than ${MAX_TEXTURES} textures; the rest are ignored.`);\n break;\n }\n out.push({ name: texture.name, src: texture.src });\n }\n return out.length ? out : undefined;\n}\n\nfunction withContract(shader: { language?: string; contract?: number }): { contract?: number } {\n const contract = shaderContractOf(shader);\n return contract === undefined ? {} : { contract };\n}\n\nfunction texturesEqual(a: ShaderTexture[] | undefined, b: ShaderTexture[] | undefined): boolean {\n if (a === b) return true;\n if (!a || !b || a.length !== b.length) return false;\n return a.every((t, i) => t.name === b[i].name && t.src === b[i].src);\n}\n\nexport const shaderFill: FillData<ShaderFillResolved> = {\n resolve: (prop: ShaderFillProp) => ({\n type: 'shader',\n source: prop.source ?? '',\n // A stored document may still say \"sksl\"; carried so the renderer can report it.\n language: prop.language ?? 'wgsl',\n ...withContract(prop),\n // Carried, never read: see `ShaderFillProp.shaderId`. Omitted when absent\n // so `equals` compares like with like for a fill that never had one.\n ...(prop.shaderId !== undefined ? { shaderId: prop.shaderId } : {}),\n // Normalised (and key-sorted) here rather than at paint time so `equals`\n // and any structural diff see the same canonical record the renderer\n // binds, whichever authoring shape it came in as.\n uniforms: normalizeUniforms(prop.uniforms),\n textures: resolveTextures(prop.textures),\n opacity: prop.opacity,\n blend: prop.blend,\n }),\n\n // `source` and `textures` snap; only the uniform values and `opacity`\n // interpolate. The source is the compile-cache key, so there is nothing\n // halfway between two programs to cross to — the same reason an image\n // fill's `src` and a 3D fill's scene snap.\n //\n // Deliberately returns neither `type` nor `blend`: `FillResult` omits both and\n // `lerpFill` reassembles via `{ ...a, ...lerp(...) }`, which is also what makes\n // the ragged-array self-pair (a fill fading against a copy of itself, when two\n // fill arrays differ in length) work.\n lerp: (a, b, t) => ({\n source: t < 0.5 ? a.source : b.source,\n language: t < 0.5 ? a.language : b.language,\n ...withContract(t < 0.5 ? a : b),\n uniforms: lerpUniformRecord(a.uniforms, b.uniforms, t),\n textures: t < 0.5 ? a.textures : b.textures,\n opacity: (a.opacity ?? 1) + ((b.opacity ?? 1) - (a.opacity ?? 1)) * t,\n }),\n\n equals: (a, b) =>\n a.source === b.source &&\n a.contract === b.contract &&\n uniformRecordsEqual(a.uniforms, b.uniforms) &&\n texturesEqual(a.textures, b.textures),\n\n // Runs off the same descriptors the renderer binds, so what gets loaded can't\n // drift from what gets sampled.\n declare: (fill, assets) => {\n for (const texture of fill.textures ?? []) assets.image(texture.src);\n },\n};\n", "/**\n * Asset discovery for 3D scenes.\n *\n * Walks a {@link Graphics3D}'s or {@link Scene3D}'s descriptors for the resources it references and\n * declares them into an {@link AssetScope}, so the ordinary asset timeline →\n * `AssetManager.loadAt` chain has them decoded and resident *before* the frame\n * that needs them renders. That is what lets the 3D draw stay synchronous.\n *\n * This runs off the very same descriptors the real render consumes — the node\n * builds its `Graphics3D` through one method that both paths call — so what gets\n * loaded cannot drift from what gets drawn.\n */\n\nimport type { AssetScope } from \"@/assets/scope\";\nimport type { LoaderFn } from \"@/assets/record\";\nimport type { Graphics3D } from \"./graphics3d\";\nimport { Scene3D } from \"./scene3d\";\nimport type { Geometry3D } from \"./geometry\";\nimport type { EnvironmentData3D } from \"./scene-settings\";\nimport { isSurfaceTexture3D, resolveSurfaceSource, texture3DSource } from \"./texture\";\nimport {\n canvas3DResourceKey, canvas3DResourceLoader,\n type Canvas3DResourceKind, type Canvas3DResourceLoader,\n} from \"./resources\";\nimport { forEachTexture3D } from \"./walk\";\n\n/**\n * Declare every asset a 3D scene or drawable list needs: textures as images, models\n * and environment panoramas through the backend's loader, and each `Tex.surface`\n * node source as a subtree of the declaring node.\n *\n * A `Graphics2D` surface source declares nothing.\n */\nexport function declare3DResources(g3: Graphics3D | Scene3D, assets: AssetScope): void {\n forEachTexture3D(g3, (value) => {\n if (isSurfaceTexture3D(value)) {\n const source = resolveSurfaceSource(value.source);\n if (source.kind === \"node\") assets.subtree(source.node);\n return;\n }\n const src = texture3DSource(value);\n if (src !== null) assets.image(src);\n });\n\n const geometry = (value: Geometry3D | undefined): void => {\n if (value === undefined) return;\n if (value.type === \"modelGeometry\") {\n declareLoader(\"gltf\", value.src, assets);\n } else if (value.type === \"edges\" || value.type === \"wireframe\") {\n geometry(value.source);\n }\n };\n\n for (const op of g3.ops()) {\n switch (op.kind) {\n case \"mesh\":\n case \"points\":\n case \"line\":\n case \"instances\":\n geometry(op.geometry);\n break;\n case \"model\":\n declareLoader(\"gltf\", op.src, assets);\n break;\n }\n }\n\n if (g3 instanceof Scene3D) declareEnvironment(g3.environmentDescriptor(), assets);\n}\n\n/** An environment's panoramas. A `preset` is generated and needs nothing. */\nexport function declareEnvironment(\n environment: Pick<EnvironmentData3D, \"src\" | \"faces\"> | null,\n assets: AssetScope,\n): void {\n if (environment === null) return;\n if (environment.src !== undefined) declareLoader(hdrKind(environment.src), environment.src, assets);\n for (const face of environment.faces ?? []) declareLoader(hdrKind(face), face, assets);\n}\n\n// Stable per backend loader and key, so declaring a resource again hands the scope\n// the same function rather than tripping its conflicting-loader check.\nconst resourceLoads = new WeakMap<Canvas3DResourceLoader, Map<string, LoaderFn>>();\n\nfunction declareLoader(kind: Canvas3DResourceKind, src: string, assets: AssetScope): void {\n const load = canvas3DResourceLoader();\n if (!load) return;\n const key = canvas3DResourceKey(kind, src);\n let byKey = resourceLoads.get(load);\n if (!byKey) resourceLoads.set(load, (byKey = new Map()));\n let fn = byKey.get(key);\n if (!fn) byKey.set(key, (fn = () => load(kind, src)));\n assets.loader(key, fn);\n}\n\nfunction hdrKind(src: string): Canvas3DResourceKind {\n const lower = src.toLowerCase();\n if (lower.endsWith(\".exr\")) return \"exr\";\n return \"hdr\";\n}\n", "import type { BlendMode } from '../blend';\nimport type { FillData } from '../registry';\nimport type { Scene3D } from '@/render3d/scene3d';\nimport { declare3DResources } from '@/render3d/tracking';\n\n/**\n * A 3D scene, painted as a fill.\n *\n * 3D is paint, not structure: the renderer draws the scene to a texture and\n * shades the shape's own path with it. So it clips to whatever painted it — an\n * `Ellipse`, a `Path`, a run of `Text` — stacks with the other fills in the\n * array, and inherits the fill layer's `opacity`/`blend`/`space` like any other.\n *\n * Ellipse({ fill: Fills.canvas3D(scene) })\n * Rect({ fill: [\"#0b0d12\", scene, Fills.linearGradient([\"transparent\", \"#000/60\"])] })\n *\n * The payload is a **built** {@link Scene3D}, never a builder callback. Per-frame\n * freshness comes from where the value is produced — a `renderSelf` runs every\n * frame, and a `() => …` prop is an ordinary reactive binding — which is exactly\n * how every other fill behaves.\n */\nexport interface Canvas3DFillProp {\n type: 'canvas3D';\n /** The scene to draw. Rebuilt by its producer each frame; never a callback. */\n scene: Scene3D;\n /**\n * Ceiling on the 3D buffer's device-pixel ratio. Default 2.\n *\n * Exists so a high-scale export doesn't allocate a quadratically larger\n * render buffer than the scene needs — a 4× export of a 1080p shape would\n * otherwise ask for a 16× buffer.\n */\n maxPixelRatio?: number;\n /** Multisample the 3D pass. Default true. */\n antialias?: boolean;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport interface Canvas3DFillResolved {\n type: 'canvas3D';\n scene: Scene3D;\n maxPixelRatio?: number;\n antialias?: boolean;\n opacity?: number;\n blend?: BlendMode;\n}\n\nexport const canvas3DFill: FillData<Canvas3DFillResolved> = {\n // Nothing to normalise — the defaults for maxPixelRatio/antialias are applied\n // at render time so the resolved shape stays minimal and comparable.\n resolve: (prop: Canvas3DFillProp) => ({ ...prop }),\n\n // A scene is a command list: there is no meaningful value halfway between two\n // of them, so it snaps, exactly as an image fill's `src` does. Only `opacity`\n // interpolates. Deliberately returns neither `type` nor `blend` — `FillResult`\n // omits both and `lerpFill` reassembles via `{ ...a, ...lerp(...) }`, which is\n // also what makes the ragged-array self-pair (a fill fading against a copy of\n // itself, when the two fill arrays differ in length) work.\n lerp: (a, b, t) => ({\n scene: t < 0.5 ? a.scene : b.scene,\n maxPixelRatio: a.maxPixelRatio ?? b.maxPixelRatio,\n antialias: a.antialias ?? b.antialias,\n opacity: (a.opacity ?? 1) + ((b.opacity ?? 1) - (a.opacity ?? 1)) * t,\n }),\n\n // Reference identity is the only comparison a Scene3D supports — it has no\n // structural hash and `ops()` returns its live array. Nothing in the codebase\n // calls this today; it exists to satisfy the interface.\n equals: (a, b) => a.scene === b.scene,\n\n // Runs off the same descriptors the renderer consumes, so what gets loaded\n // cannot drift from what gets drawn.\n declare: (fill, assets) => {\n declare3DResources(fill.scene, assets);\n },\n};\n", "import type { AssetScope } from \"@/assets/scope\";\nimport { FillProp, FillResolved, FillSpace } from \"./union\";\nimport { Fill, resolveChainFill } from \"./chain\";\nimport { canCoerce, coercePair } from \"./coerce\";\nimport type { AttributeOps } from \"@/attributes/shared/operators\";\n\nimport { colorFill } from \"./implementations/color\";\nimport { linearGradientFill } from \"./implementations/linear-gradient\";\nimport { radialGradientFill } from \"./implementations/radial-gradient\";\nimport { conicGradientFill } from \"./implementations/conic-gradient\";\nimport { noiseFill } from \"./implementations/noise\";\nimport { fractalNoiseFill } from \"./implementations/fractal-noise\";\nimport { stripeFill } from \"./implementations/stripe\";\nimport { dotGridFill } from \"./implementations/dot-grid\";\nimport { gridFill } from \"./implementations/grid\";\nimport { shaderFill } from \"./implementations/shader\";\nimport { imageFill } from \"./implementations/image\";\nimport { videoFill } from \"./implementations/video\";\nimport { canvas3DFill } from \"./implementations/canvas3d\";\n// The one value import from `render3d` into the fill layer, for the bare-scene\n// coercion in `resolveFill`. Acyclic: `render3d` only imports `Color` back from\n// here, and does so type-only.\nimport { Scene3D } from \"@/render3d/scene3d\";\n\ntype FillResult<T extends FillResolved> = Omit<Omit<T, \"type\">, \"blend\">;\n\nexport interface FillData<T extends FillResolved> {\n resolve(prop: any): T;\n equals(a: T, b: T): boolean;\n lerp(from: FillResult<T>, to: FillResult<T>, t: number): FillResult<T>;\n declare?(fill: T, assets: AssetScope): void;\n}\n\nconst FILLS = new Map<string, FillData<FillResolved>>([\n [\"solid\", colorFill as FillData<FillResolved>],\n [\"linear-gradient\", linearGradientFill as FillData<FillResolved>],\n [\"radial-gradient\", radialGradientFill as FillData<FillResolved>],\n [\"conic-gradient\", conicGradientFill as FillData<FillResolved>],\n [\"noise\", noiseFill as FillData<FillResolved>],\n [\"fractalNoise\", fractalNoiseFill as FillData<FillResolved>],\n [\"stripe\", stripeFill as FillData<FillResolved>],\n [\"dotGrid\", dotGridFill as FillData<FillResolved>],\n [\"grid\", gridFill as FillData<FillResolved>],\n [\"shader\", shaderFill as FillData<FillResolved>],\n [\"image\", imageFill as FillData<FillResolved>],\n [\"video\", videoFill as FillData<FillResolved>],\n [\"canvas3D\", canvas3DFill as FillData<FillResolved>],\n]);\n\nfunction get(name: string): FillData<FillResolved> {\n const data = FILLS.get(name);\n if (!data) throw new Error(`Fill \"${name}\" is not registered`);\n return data;\n}\n\nexport function resolveFill(prop: FillProp): FillResolved {\n if (typeof prop === \"string\") return resolveFill({ type: \"solid\", color: prop });\n // A bare built scene is shorthand for a 3D fill, the same way a bare CSS\n // string is shorthand for a solid one.\n if (prop instanceof Scene3D) return resolveFill({ type: \"canvas3D\", scene: prop });\n const resolved = get(prop.type).resolve(prop);\n // `space` is a cross-cutting rendering directive (like `blend`); carry it\n // through generically so each fill `resolve()` doesn't have to know about it.\n const space = (prop as { space?: FillSpace }).space;\n return space !== undefined ? { ...resolved, space } : resolved;\n}\n\n/**\n * What an empty media slot paints: an image fill naming no source.\n *\n * The renderer turns an empty `src` into the transparency checkerboard rather\n * than into nothing. Both media nodes reach for this when their own source is\n * unset, so the two cannot end up drawing different placeholders.\n *\n * Resolved once and shared: it has no props to vary, and the two places that key\n * per-fill state by object identity (`paintSlot`, `preflighted`) are both scoped\n * to one node's single `applyFills` call, where this can appear only once.\n *\n * Declared here rather than beside the image fill's own implementation because\n * resolving one needs {@link resolveFill}, and that lives on this side of the\n * dependency — the implementations are what the registry imports, not the other\n * way round.\n */\nexport const UNSET_MEDIA_FILL: FillResolved = resolveFill({\n type: \"image\",\n src: \"\",\n} as FillProp);\n\n/**\n * True when `a` and `b` can be interpolated into a single fill by {@link\n * lerpFill} without throwing — i.e. they share a type with the same `blend`, or\n * they're a color/gradient pair {@link canCoerce} can promote to one type.\n *\n * Pairs that fail this (e.g. color↔image, image↔video, or same-type fills with\n * differing blend modes) have no meaningful single-type in-between; {@link\n * fillOps}'s `lerp` cross-fades them as two stacked layers instead.\n */\nexport function canLerpFill(a: FillResolved, b: FillResolved): boolean {\n if (a.type === b.type) return a.blend === b.blend;\n return canCoerce(a, b);\n}\n\nexport function lerpFill(a: FillResolved, b: FillResolved, t: number): FillResolved {\n const clamped = Math.min(1, Math.max(0, t));\n\n // Cross-type tween (color↔gradient, or gradient↔gradient of different\n // kinds): promote both endpoints to a common type, then lerp with that\n // type's lerp. blend cannot interpolate, so it snaps with the rest of the\n // coerced shape.\n if (a.type !== b.type) {\n if (!canCoerce(a, b)) {\n throw new Error(`No registered lerp for fills of type \"${a.type}\" and \"${b.type}\"`);\n }\n const [ca, cb] = coercePair(a, b);\n return { ...ca, ...get(ca.type).lerp(ca, cb, clamped) };\n }\n\n if (a.blend !== b.blend) {\n throw new Error(`No registered lerp for fills of type \"${a.type}\" and \"${b.type}\"`);\n }\n return { ...a, ...get(a.type).lerp(a, b, clamped) };\n}\n\n/** Returns `fill` with its effective opacity scaled by `factor` (clamped to ≥0). */\nfunction scaleOpacity(fill: FillResolved, factor: number): FillResolved {\n return { ...fill, opacity: (fill.opacity ?? 1) * Math.max(0, factor) };\n}\n\nexport function declareFill(fill: FillResolved, assets: AssetScope): void {\n FILLS.get(fill.type)?.declare?.(fill, assets);\n}\n\n/** The fill-layer attribute's op set — the `fill` prop's resolve/lerp pair. */\nexport const fillOps: AttributeOps<Fill, FillResolved[]> = {\n resolve: (prop) => resolveChainFill(prop).map(resolveFill),\n lerp: (from, to, t) => {\n if (from === to) return from;\n if (!from.length && !to.length) return [];\n const clamped = Math.min(1, Math.max(0, t));\n const maxLength = Math.max(from.length, to.length);\n const result: FillResolved[] = [];\n for (let i = 0; i < maxLength; i++) {\n const f = from[i];\n const tf = to[i];\n if (f && tf) {\n // Interpolate in place when the two fills share an interpolatable\n // shape (same type, or a coercible color/gradient pair). When they\n // don't (e.g. color↔image, image↔video) there is no single-type\n // in-between, so cross-fade instead: paint the outgoing fill fading\n // out beneath the incoming fill fading in. The dropped-out endpoints\n // are omitted so a static array of one fill stays a single layer.\n if (canLerpFill(f, tf)) {\n result.push(lerpFill(f, tf, clamped));\n } else {\n if (clamped < 1) result.push(scaleOpacity(f, 1 - clamped));\n if (clamped > 0) result.push(scaleOpacity(tf, clamped));\n }\n } else if (f) {\n result.push(lerpFill(f, { ...f, opacity: 0 }, clamped));\n } else if (tf) {\n result.push(lerpFill({ ...tf, opacity: 0 }, tf, clamped));\n }\n }\n return result;\n },\n};\n", "import { fillOps } from '../fill/registry';\nimport { FillResolved } from '../fill/union';\nimport { Fill } from '../fill/chain';\nimport { Vector2, lerpVector2 } from '@/attributes/layout/vector2';\nimport type { AttributeOps } from '@/attributes/shared/operators';\n\n// ── Prop (loose) ─────────────────────────────────────────────────────────────\n\nexport interface ShadowProp {\n blur?: number;\n /** Offset of the shadow from the shape, in px. Defaults to `{ x: 0, y: 0 }`. */\n offset?: Vector2;\n /** Any loose fill: a CSS color string, fill prop object, resolved fill, or {@link FillChain}/array of layers. */\n fill?: Fill;\n /** When true, the shadow is cast inward (inset) instead of as a drop shadow. Defaults to false. */\n inner?: boolean;\n /**\n * Grows (positive) or shrinks (negative) the shadow's silhouette before it\n * is offset and blurred, like CSS `box-shadow` spread. Only honoured for\n * ellipses and rectangles, whose geometry can be resized cleanly; ignored\n * for other shapes. Defaults to 0.\n */\n spread?: number;\n}\n/**\n * Fully resolved shadow — all fields normalised with defaults applied.\n * Compatible with the lerp registry (IFill is used for fill to avoid\n * breaking the existing lerp/registry pipeline).\n */\nexport interface ShadowResolved {\n blur: number;\n /** Offset of the shadow from the shape, in px. */\n offset?: Vector2;\n /** Resolved fill layers, painted bottom-to-top like a node's `fill`. */\n fill: FillResolved[];\n /** When true, the shadow is cast inward (inset) instead of as a drop shadow. */\n inner: boolean;\n /** Silhouette grow (positive) / shrink (negative) before blur, in px. Only ellipses and rects honour it. */\n spread: number;\n}\n\n/**\n * Accepted shapes for a node's `shadow` prop: a single loose {@link ShadowProp},\n * an array of them (stacked), or an already-resolved {@link ShadowResolved}/array\n * — resolved values pass through `resolveShadow` idempotently, so a node's\n * read-back `shadow` can be assigned straight back.\n */\nexport type Shadow =\n | ShadowProp\n | ShadowResolved\n | (ShadowProp | ShadowResolved)[];\n\n// ── Resolve ──────────────────────────────────────────────────────────────────\n\nexport function resolveShadow(prop: ShadowProp, previous?: ShadowResolved): ShadowResolved {\n return {\n blur: prop.blur ?? previous?.blur ?? 0,\n offset: prop.offset ?? previous?.offset,\n fill: prop.fill != null ? fillOps.resolve(prop.fill) : (previous?.fill ?? fillOps.resolve('transparent')),\n inner: prop.inner ?? previous?.inner ?? false,\n spread: prop.spread ?? previous?.spread ?? 0,\n };\n}\n\n// ── Lerp ─────────────────────────────────────────────────────────────────────\n\nfunction lerpShadow(from: ShadowResolved, to: ShadowResolved, t: number): ShadowResolved {\n return {\n blur: from.blur + (to.blur - from.blur) * t,\n offset: lerpVector2(from.offset ?? { x: 0, y: 0 }, to.offset ?? { x: 0, y: 0 }, t),\n fill: fillOps.lerp(from.fill, to.fill, t),\n // inner/outer is a discrete kind — keep the start's until the tween completes.\n inner: t < 1 ? from.inner : to.inner,\n spread: from.spread + (to.spread - from.spread) * t,\n };\n}\n\n/** The shadow-layer attribute's op set — the `shadow` prop's resolve/lerp pair. */\nexport const shadowOps: AttributeOps<Shadow, ShadowResolved[]> = {\n resolve: (prop, previous) => {\n if (prop == null) return [];\n const arr = Array.isArray(prop) ? prop : [prop];\n return arr.map((p, i) => resolveShadow(p as ShadowProp, previous?.[i]));\n },\n lerp: (from, to, t) => {\n if (from === to) return from;\n const len = Math.max(from.length, to.length);\n const result: ShadowResolved[] = [];\n for (let i = 0; i < len; i++) {\n const f = from[i];\n const tf = to[i];\n if (!f) { result.push(tf); continue; }\n if (!tf) { result.push(f); continue; }\n result.push(lerpShadow(f, tf, t));\n }\n return result;\n },\n};\n", "import { fillOps } from '@/attributes/shape/fill/registry';\nimport { FillResolved } from '../fill/union';\nimport { Fill } from '../fill/chain';\nimport type { AttributeOps } from '@/attributes/shared/operators';\n\n// ── Align ──────────────────────────────────────────────────────────────────\n\n/**\n * Where the stroke sits relative to the shape's edge. Resolves to a number in\n * the range `[-1, 1]`: -1 = fully inside the outline, 0 = centered (straddles the edge,\n * half in/half out), +1 = fully outside. Named values map to the endpoints;\n * intermediate numbers bias the stroke partway, like Figma's stroke alignment.\n */\nexport type StrokeAlign = number | 'inside' | 'center' | 'outside';\n\n/** Resolve a loose `align` prop to a clamped number in [-1, 1]. */\nexport function resolveStrokeAlign(align: StrokeAlign | undefined, fallback: number): number {\n if (align == null) return fallback;\n if (typeof align === 'number') return Math.max(-1, Math.min(1, align));\n switch (align) {\n case 'inside': return -1;\n case 'center': return 0;\n case 'outside': return 1;\n }\n return fallback;\n}\n\n// ── Cap & Join ───────────────────────────────────────────────────────────────\n\n/** How the ends of an open stroke are shaped. */\nexport type StrokeCap = 'butt' | 'round' | 'square';\n\n/**\n * A shape one end of an open contour wears in place of a cap, sized by\n * `capScale`. `arrow` is an open chevron; `triangle` and `stealth` are filled\n * heads with their tip on the path's end; `dot`, `box`, `diamond` and `bar` sit\n * centred on it.\n */\nexport type StrokeMarker = 'arrow' | 'triangle' | 'stealth' | 'dot' | 'box' | 'diamond' | 'bar';\n\n/** What one end of an open contour wears: a cap, or a marker. */\nexport type StrokeEnd = StrokeCap | StrokeMarker;\n\n/** A marker's length as a multiple of the stroke's weight, where none is given. */\nexport const DEFAULT_CAP_SCALE = 4;\n\nexport function isStrokeMarker(end: StrokeEnd | undefined): end is StrokeMarker {\n switch (end) {\n case 'arrow':\n case 'triangle':\n case 'stealth':\n case 'dot':\n case 'box':\n case 'diamond':\n case 'bar': return true;\n }\n return false;\n}\n\n/** How two stroke segments are joined at a corner. */\nexport type StrokeJoin = 'miter' | 'round' | 'bevel';\n\n/** Normalise a loose `cap` prop, falling back when omitted/unknown. */\nexport function resolveStrokeCap(cap: StrokeCap | undefined, fallback: StrokeCap): StrokeCap {\n if (cap == null) return fallback;\n switch (cap) {\n case 'butt':\n case 'round':\n case 'square': return cap;\n }\n return fallback;\n}\n\n/** Normalise a loose `startCap`/`endCap` prop, falling back when omitted/unknown. */\nexport function resolveStrokeEnd(end: StrokeEnd | undefined, fallback: StrokeCap): StrokeEnd {\n return isStrokeMarker(end) ? end : resolveStrokeCap(end, fallback);\n}\n\n/** Normalise a loose `join` prop, falling back when omitted/unknown. */\nexport function resolveStrokeJoin(join: StrokeJoin | undefined, fallback: StrokeJoin): StrokeJoin {\n if (join == null) return fallback;\n switch (join) {\n case 'miter':\n case 'round':\n case 'bevel': return join;\n }\n return fallback;\n}\n\n// ── Prop (loose) ─────────────────────────────────────────────────────────────\n\nexport interface StrokeProp {\n /** Stroke width in pixels. Defaults to 1. */\n weight?: number;\n /** Any loose fill: a CSS color string, fill prop object, resolved fill, or {@link FillChain}/array of layers. */\n fill?: Fill;\n /** Dash pattern. A single number `n` becomes `[n, n]`. */\n dash?: number | number[];\n dashOffset?: number;\n /**\n * Where the stroke sits relative to the edge: a number in [-1, 1] or one of\n * `'inside'` (-1), `'center'` (0), `'outside'` (1). Defaults to `'inside'`,\n * so the stroke stays within the shape's measured bounds (like a CSS border)\n * rather than leaking half its width outside.\n */\n align?: StrokeAlign;\n /**\n * How the ends of each dash, and of an open stroke, are shaped: `'butt'`\n * (flush, the default), `'round'`, or `'square'`. `startCap`/`endCap`\n * override it at the path's own two ends.\n */\n cap?: StrokeCap;\n /** The cap or marker at the start of each open contour, in place of `cap`. */\n startCap?: StrokeEnd;\n /** The cap or marker at the end of each open contour, in place of `cap`. */\n endCap?: StrokeEnd;\n /**\n * A marker's length as a multiple of `weight` (default `4`), so a head keeps\n * its proportion as the stroke thickens. A marker never outgrows its\n * contour: on a short one it shrinks to fit.\n */\n capScale?: number;\n /**\n * How two segments meet at a corner: `'miter'` (sharp, the default),\n * `'round'`, or `'bevel'` (flattened).\n */\n join?: StrokeJoin;\n /**\n * Maximum ratio of miter length to stroke width before a `'miter'` join is\n * truncated to a bevel. Only affects `join: 'miter'`. Defaults to 4.\n */\n miterLimit?: number;\n}\n\n/**\n * Fully resolved stroke — all fields normalised with defaults applied.\n * Compatible with the lerp registry (IFill is used for fill to avoid\n * breaking the existing lerp/registry pipeline).\n */\nexport interface StrokeResolved {\n weight: number;\n /** Resolved fill layers, painted bottom-to-top like a node's `fill`. */\n fill: FillResolved[];\n dash?: number[];\n dashOffset: number;\n /** Stroke placement in [-1, 1]: -1 inside, 0 center, +1 outside. */\n align: number;\n /** End-cap shape for dash ends, and for open strokes' ends unless overridden. */\n cap: StrokeCap;\n /** Absent means the end follows `cap`. */\n startCap?: StrokeEnd;\n endCap?: StrokeEnd;\n capScale: number;\n /** Corner join shape. */\n join: StrokeJoin;\n /** Miter limit (only used when `join` is `'miter'`). */\n miterLimit: number;\n}\n\n/**\n * Accepted shapes for a node's `stroke` prop: a single loose {@link StrokeProp},\n * an array of them (stacked bottom-to-top), or an already-resolved\n * {@link StrokeResolved}/array — resolved values pass through `resolveStroke`\n * idempotently, so a node's read-back `stroke` can be assigned straight back.\n */\nexport type Stroke =\n | StrokeProp\n | StrokeResolved\n | (StrokeProp | StrokeResolved)[];\n\n// ── Resolve ──────────────────────────────────────────────────────────────────\n\nexport function resolveStroke(prop: StrokeProp, previous?: StrokeResolved): StrokeResolved {\n let dash: number[] | undefined;\n if (prop.dash != null) {\n const raw = Array.isArray(prop.dash) ? prop.dash : [prop.dash];\n dash = raw.length === 1 ? [raw[0], raw[0]] : raw;\n } else {\n dash = previous?.dash;\n }\n const cap = resolveStrokeCap(prop.cap, previous?.cap ?? 'butt');\n return {\n weight: prop.weight ?? previous?.weight ?? 1,\n fill: prop.fill != null ? fillOps.resolve(prop.fill) : (previous?.fill ?? fillOps.resolve('transparent')),\n dash,\n dashOffset: prop.dashOffset ?? previous?.dashOffset ?? 0,\n align: resolveStrokeAlign(prop.align, previous?.align ?? -1),\n cap,\n startCap: prop.startCap != null ? resolveStrokeEnd(prop.startCap, cap) : previous?.startCap,\n endCap: prop.endCap != null ? resolveStrokeEnd(prop.endCap, cap) : previous?.endCap,\n capScale: Math.max(0, prop.capScale ?? previous?.capScale ?? DEFAULT_CAP_SCALE),\n join: resolveStrokeJoin(prop.join, previous?.join ?? 'miter'),\n miterLimit: prop.miterLimit ?? previous?.miterLimit ?? 4,\n };\n}\n\n// ── Lerp ─────────────────────────────────────────────────────────────────────\n\nfunction lerpDashArray(from: number[] | undefined, to: number[] | undefined, t: number): number[] | undefined {\n const fArray = from || [];\n const tArray = to || [];\n if (fArray.length === 0 && tArray.length === 0) return from;\n\n const len = Math.max(fArray.length, tArray.length);\n const result: number[] = new Array(len);\n for (let i = 0; i < len; i++) {\n // Pad shorter arrays with 0 to ensure smooth transitions.\n const fVal = fArray[i] ?? 0;\n const tVal = tArray[i] ?? 0;\n result[i] = fVal + (tVal - fVal) * t;\n }\n return result;\n}\n\nfunction lerpStroke(from: StrokeResolved, to: StrokeResolved, t: number): StrokeResolved {\n return {\n weight: from.weight + (to.weight - from.weight) * t,\n fill: fillOps.lerp(from.fill, to.fill, t),\n dash: lerpDashArray(from.dash, to.dash, t) as number[],\n dashOffset: from.dashOffset + (to.dashOffset - from.dashOffset) * t,\n align: from.align + (to.align - from.align) * t,\n // cap/join are discrete enums — snap at the midpoint.\n cap: t < 0.5 ? from.cap : to.cap,\n startCap: t < 0.5 ? from.startCap : to.startCap,\n endCap: t < 0.5 ? from.endCap : to.endCap,\n capScale: from.capScale + (to.capScale - from.capScale) * t,\n join: t < 0.5 ? from.join : to.join,\n miterLimit: from.miterLimit + (to.miterLimit - from.miterLimit) * t,\n };\n}\n\n/** The stroke-layer attribute's op set — the `stroke` prop's resolve/lerp pair. */\nexport const strokeOps: AttributeOps<Stroke, StrokeResolved[]> = {\n resolve: (prop, previous) => {\n if (prop == null) return [];\n const arr = Array.isArray(prop) ? prop : [prop];\n return arr.map((p, i) => resolveStroke(p as StrokeProp, previous?.[i]));\n },\n lerp: (from, to, t) => {\n if (from === to) return from;\n const len = Math.max(from.length, to.length);\n const result: StrokeResolved[] = [];\n for (let i = 0; i < len; i++) {\n const f = from[i];\n const tf = to[i];\n if (!f) { result.push(tf); continue; }\n if (!tf) { result.push(f); continue; }\n result.push(lerpStroke(f, tf, t));\n }\n return result;\n },\n};\n", "/**\n * Clamps a number between a minimum and maximum value.\n *\n * @param value - The number to clamp.\n * @param min - The lower bound.\n * @param max - The upper bound.\n * @returns The clamped number.\n */\nexport const clamp = (value: number, min: number, max: number): number => {\n return Math.max(min, Math.min(value, max));\n};\n\n/** Shorthand for `clamp(t, 0, 1)`, commonly used to normalize tween progress. */\nexport function clamp01(t: number) {\n return clamp(t, 0, 1);\n}\n", "import type { EasingFunction } from \"./type\";\n\n/**\n * Descriptions of engine-built easings, by function.\n *\n * Every engine easing is an anonymous closure, so `fn.name` is `\"\"` and cannot\n * tell two of them apart. A constructor that knows what it built records a short,\n * deterministic description here, which is what a cache key can be built from.\n */\nconst descriptions = new WeakMap<EasingFunction, string>();\nconst identities = new WeakMap<EasingFunction, string>();\nlet identityCounter = 0;\n\n/** Record what `ease` is, and hand it back. @internal */\nexport function describeEase<F extends EasingFunction>(ease: F, description: string): F {\n descriptions.set(ease, description);\n return ease;\n}\n\n/** What an engine-built ease was recorded as, or `undefined` for any other function. @internal */\nexport function easeDescription(ease: EasingFunction): string | undefined {\n return descriptions.get(ease);\n}\n\n/**\n * A string that is equal for two easings exactly when they are the same ease.\n *\n * An engine easing keys by its description, so building the same one twice (a\n * document rebuilt from the same row) gives the same key. A function the engine\n * did not build keys by its own identity: a different function is always a\n * different key, which may over-report a change but never hides one.\n *\n * @internal\n */\nexport function easeKey(ease: EasingFunction): string {\n const described = descriptions.get(ease);\n if (described !== undefined) return described;\n let id = identities.get(ease);\n if (id === undefined) {\n id = `fn#${identityCounter++}`;\n identities.set(ease, id);\n }\n return id;\n}\n", "import { clamp01 } from \"@/util/clamp\";\nimport { EasingFunction } from \"./type\";\nimport { describeEase } from \"./describe\";\n\nexport type StandardEase =\n | 'sine' | 'quad' | 'cubic' | 'quart' | 'quint'\n | 'expo' | 'circ' | 'back' | 'elastic' | 'bounce';\n\n/** Default ease family used when no `type` is specified. */\nexport const DEFAULT_EASE: StandardEase = 'quad';\n\nexport interface EaseConfig {\n /** Standard ease family (default: 'quad'). */\n type?: StandardEase;\n /** Used by 'back' (default: 1.70158). */\n overshoot?: number;\n /** Used by 'elastic' (default: 1). */\n amplitude?: number;\n /** Used by 'elastic' (default: 0.3). */\n period?: number;\n}\n\nexport type EaseParams = StandardEase | EaseConfig;\n\nconst PI = Math.PI;\n\ntype ResolvedConfig = EaseConfig & { type: StandardEase };\n\nconst parseConfig = (params?: EaseParams): ResolvedConfig => {\n if (params === undefined) return { type: DEFAULT_EASE };\n if (typeof params === 'string') return { type: params };\n return { ...params, type: params.type ?? DEFAULT_EASE };\n};\n\n// \"Ease in\" curve for each standard family, parameterized by an EaseConfig.\n// easeOut/easeInOut are derived from this via reflection, matching the\n// classic Penner construction.\nconst inMath: Record<StandardEase, (t: number, config: EaseConfig) => number> = {\n sine: (t) => 1 - Math.cos((t * PI) / 2),\n quad: (t) => t * t,\n cubic: (t) => t * t * t,\n quart: (t) => t * t * t * t,\n quint: (t) => t * t * t * t * t,\n expo: (t) => (t === 0 ? 0 : Math.pow(2, 10 * (t - 1))),\n circ: (t) => 1 - Math.sqrt(1 - t * t),\n back: (t, config) => {\n const s = config.overshoot ?? 1.70158;\n return t * t * ((s + 1) * t - s);\n },\n elastic: (t, config) => {\n if (t === 0 || t === 1) return t;\n const a = config.amplitude ?? 1;\n const p = config.period ?? 0.3;\n const s = (p / (2 * PI)) * Math.asin(1 / a);\n return -(a * Math.pow(2, 10 * (t - 1)) * Math.sin(((t - 1 - s) * 2 * PI) / p));\n },\n bounce: (t) => {\n const bounceOut = (x: number) => {\n const n1 = 7.5625;\n const d1 = 2.75;\n if (x < 1 / d1) return n1 * x * x;\n if (x < 2 / d1) return n1 * (x -= 1.5 / d1) * x + 0.75;\n if (x < 2.5 / d1) return n1 * (x -= 2.25 / d1) * x + 0.9375;\n return n1 * (x -= 2.625 / d1) * x + 0.984375;\n };\n return 1 - bounceOut(1 - t);\n },\n};\n\n/** A key-ready description of a standard ease: its direction, family and every tuning value. */\nconst describeConfig = (direction: 'in' | 'out' | 'inOut', config: ResolvedConfig): string =>\n `${direction}:${config.type}:${config.overshoot ?? '_'}:${config.amplitude ?? '_'}:${config.period ?? '_'}`;\n\nexport const linear = (): EasingFunction => describeEase((t) => clamp01(t), 'lin');\n\nexport const easeIn = (params?: EaseParams): EasingFunction => {\n const config = parseConfig(params);\n return describeEase((t) => inMath[config.type](clamp01(t), config), describeConfig('in', config));\n};\n\nexport const easeOut = (params?: EaseParams): EasingFunction => {\n const config = parseConfig(params);\n return describeEase((t) => 1 - inMath[config.type](1 - clamp01(t), config), describeConfig('out', config));\n};\n\nexport const easeInOut = (params?: EaseParams): EasingFunction => {\n const config = parseConfig(params);\n // 'back' and 'elastic' need different default tuning at the midpoint than\n // their easeIn/easeOut counterparts (the classic Penner in-out variants\n // scale overshoot and default period differently), so resolve those here\n // rather than reusing the easeIn/easeOut defaults verbatim.\n const inOutConfig: ResolvedConfig = config.type === 'back'\n ? { ...config, overshoot: (config.overshoot ?? 1.70158) * 1.525 }\n : config.type === 'elastic'\n ? { ...config, period: config.period ?? 0.45 }\n : config;\n return describeEase((t) => {\n t = clamp01(t);\n return t < 0.5\n ? inMath[inOutConfig.type](2 * t, inOutConfig) / 2\n : 1 - inMath[inOutConfig.type](2 * (1 - t), inOutConfig) / 2;\n }, describeConfig('inOut', config));\n};\n", "import type { EasingFunction } from \"./type\";\nimport { describeEase } from \"./describe\";\n\n/**\n * A hand-drawn timing function: a chain of cubic Bézier segments from (0, 0)\n * to (1, 1), where x is progress through the duration and y how far along the\n * animation is. This is what an `EaseSpec` of `kind: \"custom\"` carries inline\n * in its `args`, so a drawn curve travels with the document rather than\n * needing a host to register a function under a key. Two things keep the\n * drawing a function of x, and both are enforced here rather than trusted: a\n * control point is clamped into its own segment's x span, and an absent handle\n * resolves to the Catmull-Rom tangent. y is deliberately not clamped to [0, 1]\n * — overshooting the target and settling back is a real move.\n */\n\n/** A point in curve space, or a handle offset within it. */\nexport interface CurveVector {\n x: number;\n y: number;\n}\n\n/** One control point of a custom easing curve. */\nexport interface CurvePoint {\n x: number;\n y: number;\n /** The handle steering the segment leaving this point. Absent = auto. */\n out?: CurveVector;\n /** The handle steering the segment arriving at it. Absent = auto. */\n in?: CurveVector;\n}\n\n/** One cubic Bézier segment of the curve, in absolute curve space. */\nexport interface EaseCurveSegment {\n p0: CurveVector;\n c1: CurveVector;\n c2: CurveVector;\n p3: CurveVector;\n}\n\nconst clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));\n\n/** The curve as Bézier segments, every auto handle and every clamp resolved. */\nexport function curveSegments(points: readonly CurvePoint[]): EaseCurveSegment[] {\n const segments: EaseCurveSegment[] = [];\n for (let i = 0; i < points.length - 1; i++) {\n const p0 = points[i];\n const p3 = points[i + 1];\n const before = points[i - 1] ?? p0;\n const after = points[i + 2] ?? p3;\n\n const c1 = p0.out\n ? { x: p0.x + p0.out.x, y: p0.y + p0.out.y }\n : { x: p0.x + (p3.x - before.x) / 6, y: p0.y + (p3.y - before.y) / 6 };\n const c2 = p3.in\n ? { x: p3.x + p3.in.x, y: p3.y + p3.in.y }\n : { x: p3.x - (after.x - p0.x) / 6, y: p3.y - (after.y - p0.y) / 6 };\n\n segments.push({\n p0: { x: p0.x, y: p0.y },\n c1: { x: clamp(c1.x, p0.x, p3.x), y: c1.y },\n c2: { x: clamp(c2.x, p0.x, p3.x), y: c2.y },\n p3: { x: p3.x, y: p3.y },\n });\n }\n return segments;\n}\n\n/** A cubic Bézier evaluated on one axis. */\nfunction bezier(a: number, b: number, c: number, d: number, t: number): number {\n const mt = 1 - t;\n return mt * mt * mt * a + 3 * mt * mt * t * b + 3 * mt * t * t * c + t * t * t * d;\n}\n\n/**\n * The curve parameter at which a segment reaches `x`. Bisection rather than\n * Newton: x is monotonic along the segment, so halving converges, where Newton\n * needs a derivative that goes to zero exactly at the flat ends an ease-in-out\n * is made of.\n */\nexport function curveSegmentT(segment: EaseCurveSegment, x: number): number {\n let low = 0;\n let high = 1;\n for (let i = 0; i < 30; i++) {\n const mid = (low + high) / 2;\n const at = bezier(segment.p0.x, segment.c1.x, segment.c2.x, segment.p3.x, mid);\n if (at < x) low = mid;\n else high = mid;\n }\n return (low + high) / 2;\n}\n\n/** Whether `value` is a drawable curve: two or more finite points. */\nexport function isEaseCurve(value: unknown): value is CurvePoint[] {\n return Array.isArray(value) && value.length >= 2 && value.every(isFinitePoint);\n}\n\nfunction isFinitePoint(value: unknown): value is CurveVector {\n if (typeof value !== \"object\" || value === null) return false;\n const { x, y } = value as Partial<CurveVector>;\n return typeof x === \"number\" && Number.isFinite(x) && typeof y === \"number\" && Number.isFinite(y);\n}\n\n/** The easing a curve runs as: progress in, eased progress out. */\nexport function curveEase(points: readonly CurvePoint[]): EasingFunction {\n const segments = curveSegments(points);\n if (segments.length === 0) return describeEase((x) => x, 'lin');\n\n return describeEase((x) => {\n if (x <= 0) return segments[0].p0.y;\n const last = segments[segments.length - 1];\n if (x >= 1) return last.p3.y;\n\n let segment = last;\n for (const candidate of segments) {\n if (x <= candidate.p3.x) {\n segment = candidate;\n break;\n }\n }\n const t = curveSegmentT(segment, x);\n return bezier(segment.p0.y, segment.c1.y, segment.c2.y, segment.p3.y, t);\n }, `curve:${JSON.stringify(points)}`);\n}\n", "import { easeIn, easeInOut, easeOut, linear, type EaseParams, type StandardEase } from \"./constants\";\nimport { curveEase, isEaseCurve, type CurvePoint } from \"./curve\";\nimport { easeDescription } from \"./describe\";\nimport type { EasingFunction } from \"./type\";\n\n/**\n * How something eases, as data.\n *\n * Mirrors the `linear`/`easeIn`/`easeOut`/`easeInOut` families in\n * `tween/ease/constants.ts` — `kind` picks the direction, `args` picks the\n * family and its knobs.\n *\n * `kind: \"custom\"` takes a drawn curve in `args`, or the key a host passed to\n * `Registry.addEase`/`RegistryOptions.eases` for an ease no standard family\n * expresses.\n */\nexport interface EaseSpec {\n kind: \"linear\" | \"in\" | \"out\" | \"inOut\" | \"custom\";\n /**\n * Family and its parameters (`\"quad\"`, or `{ type: \"back\", overshoot: 2 }`)\n * for every `kind` but `\"custom\"`, whose `args` is instead the drawn curve\n * itself — a {@link CurvePoint} chain from (0, 0) to (1, 1), so the timing\n * travels with the document — or the `Registry.addEase` key of a function\n * the host registered.\n */\n args?: EaseParams | CurvePoint[] | string;\n}\n\nexport const EASE_KINDS: ReadonlySet<string> = new Set<EaseSpec[\"kind\"]>([\"linear\", \"in\", \"out\", \"inOut\", \"custom\"]);\n\n/** The function `spec` runs as. A registry key resolves through `lookup`, and throws without one. */\nexport function easeOfSpec(spec: EaseSpec, lookup?: (key: string) => EasingFunction | undefined, known?: () => readonly string[]): EasingFunction {\n switch (spec.kind) {\n case \"linear\": return linear();\n case \"in\": return easeIn(spec.args as EaseParams | undefined);\n case \"out\": return easeOut(spec.args as EaseParams | undefined);\n case \"inOut\": return easeInOut(spec.args as EaseParams | undefined);\n case \"custom\": {\n const key = spec.args;\n if (isEaseCurve(key)) return curveEase(key);\n if (typeof key !== \"string\") {\n throw new Error(`A \"custom\" ease needs a curve or its Registry.addEase key in \\`args\\` (got ${JSON.stringify(spec.args)}).`);\n }\n const fn = lookup?.(key);\n if (!fn) {\n const registered = known?.().join(\", \") || \"none\";\n throw new Error(lookup\n ? `No ease registered under \"${key}\". Registered: ${registered}.`\n : `The ease \"${key}\" names a Registry entry, which nothing here can resolve; use a standard ease or a drawn curve.`);\n }\n return fn;\n }\n }\n}\n\nconst STANDARD: ReadonlySet<string> = new Set<StandardEase>([\"sine\", \"quad\", \"cubic\", \"quart\", \"quint\", \"expo\", \"circ\", \"back\", \"elastic\", \"bounce\"]);\n\n/** The spec an engine-built ease was made from, or `undefined` for a function the engine did not build. */\nexport function specOfEase(ease: EasingFunction): EaseSpec | undefined {\n const description = easeDescription(ease);\n if (description === undefined) return undefined;\n if (description === \"lin\") return { kind: \"linear\" };\n if (description.startsWith(\"curve:\")) return { kind: \"custom\", args: JSON.parse(description.slice(6)) as CurvePoint[] };\n const [direction, type, overshoot, amplitude, period] = description.split(\":\");\n if ((direction !== \"in\" && direction !== \"out\" && direction !== \"inOut\") || !STANDARD.has(type)) return undefined;\n const tuning = { overshoot, amplitude, period };\n const config: Record<string, unknown> = { type };\n for (const [name, value] of Object.entries(tuning)) {\n if (value !== undefined && value !== \"_\") config[name] = Number(value);\n }\n return { kind: direction, args: Object.keys(config).length === 1 ? (type as StandardEase) : (config as EaseParams) };\n}\n", "import { linear } from \"@/tween/ease/constants\";\nimport { easeOfSpec, specOfEase, type EaseSpec } from \"@/tween/ease/spec\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport { lerpNumber } from \"@/tween/lerp\";\nimport type { AttributeOps } from \"@/attributes/shared/operators\";\n\n/**\n * One point of a {@link Ramp}: a value, placed `at` seconds after the start or\n * `before` seconds before the end, and the ease of the segment arriving at it\n * (linear when absent).\n */\nexport type RampKey =\n | { readonly at: number; readonly before?: undefined; readonly value: number; readonly ease?: EaseSpec }\n | { readonly before: number; readonly at?: undefined; readonly value: number; readonly ease?: EaseSpec };\n\n/**\n * Automation for one audio param, as plain JSON.\n *\n * A `before` key stays where it is when the clip is trimmed, which is what makes\n * \"the last second\" mean the last second of whatever length the clip has.\n */\nexport interface Ramp {\n readonly keys: readonly RampKey[];\n}\n\n/** An audio param: a constant, or a {@link Ramp}. */\nexport type Param = number | Ramp;\n\n/** A ramp key's time and ease, resolved against one length. */\nexport interface ResolvedRampKey {\n readonly time: number;\n readonly value: number;\n readonly ease: EasingFunction;\n /** Linear into this key, so a device can schedule a cheap ramp rather than a baked curve. */\n readonly linear: boolean;\n}\n\ninterface Segment {\n readonly from?: number;\n readonly to?: number;\n readonly duration?: number;\n readonly ease?: EaseSpec;\n}\n\n/** An ease as data, or an engine-built function (which records the data it came from). */\nexport type RampEase = EaseSpec | EasingFunction;\n\nconst segmentsOf = new WeakMap<RampChain, readonly Segment[]>();\n\n/**\n * The fluent builder: `ramp(0, 1, 0.5).hold().ramp(1, 0, 1)`.\n *\n * Its one own field is `keys`, so it is a {@link Ramp} and serializes to one.\n * Segments before the first bare `hold()` are placed from the start, segments\n * after it from the end, and the hold stretches to fill whatever lies between.\n */\nexport class RampChain implements Ramp {\n readonly keys: readonly RampKey[];\n\n constructor(segments: readonly Segment[] = []) {\n segmentsOf.set(this, segments);\n this.keys = keysOf(segments);\n }\n\n /** Append a ramp from `from` to `to` over `duration` seconds. */\n ramp(from: number, to: number, duration: number, options?: { readonly ease?: RampEase }): RampChain {\n return this._append({ from, to, duration, ease: specOf(options?.ease) });\n }\n\n /** Append a hold: for `duration` seconds, or, bare, for whatever the clip leaves over. */\n hold(duration?: number): RampChain {\n return this._append({ duration });\n }\n\n private _append(segment: Segment): RampChain {\n return new RampChain([...(segmentsOf.get(this) ?? []), segment]);\n }\n}\n\n/** A ramp from `from` to `to` over `duration` seconds. */\nexport function ramp(from: number, to: number, duration: number, options?: { readonly ease?: RampEase }): RampChain {\n return new RampChain().ramp(from, to, duration, options);\n}\n\n/** A hold; bare `hold()` stretches to fill the middle of the clip. */\nexport function hold(duration?: number): RampChain {\n return new RampChain().hold(duration);\n}\n\nfunction specOf(ease: RampEase | undefined): EaseSpec | undefined {\n if (ease === undefined) return undefined;\n const spec = typeof ease === \"function\" ? specOfEase(ease) : ease;\n if (!spec) {\n throw new TypeError(\"A ramp's ease is stored as data, and this function has none: pass an EaseSpec, or an engine-built ease (easeIn, easeOut, easeInOut, curveEase).\");\n }\n return spec.kind === \"linear\" ? undefined : spec;\n}\n\nfunction keysOf(segments: readonly Segment[]): RampKey[] {\n let previous: number | undefined;\n const values = segments.map((s) => {\n const from = s.from ?? previous;\n const to = s.to ?? from;\n previous = to;\n return { from, to };\n });\n\n const keys: RampKey[] = [];\n const push = (key: RampKey): void => {\n const last = keys[keys.length - 1];\n if (last && !key.ease && last.at === key.at && last.before === key.before && last.value === key.value) return;\n keys.push(key);\n };\n const withEase = (s: Segment) => (s.ease ? { ease: s.ease } : {});\n\n const fill = segments.findIndex((s) => s.duration === undefined);\n const head = fill < 0 ? segments.length : fill;\n let at = 0;\n for (let i = 0; i < head; i++) {\n const s = segments[i];\n const duration = Math.max(0, s.duration ?? 0);\n const { from, to } = values[i];\n if (from !== undefined) push({ at, value: from });\n if (to !== undefined) push({ at: at + duration, value: to, ...withEase(s) });\n at += duration;\n }\n if (fill < 0) return keys;\n\n const tail = segments.slice(fill + 1);\n if (tail.some((s) => s.duration === undefined) && process.env.NODE_ENV !== \"production\") {\n console.warn(\"[motionscript] A ramp has more than one bare hold(); only the first stretches, the rest are zero-length.\");\n }\n let before = tail.reduce((sum, s) => sum + Math.max(0, s.duration ?? 0), 0);\n for (let i = fill + 1; i < segments.length; i++) {\n const s = segments[i];\n const duration = Math.max(0, s.duration ?? 0);\n const { from, to } = values[i];\n if (from !== undefined) push({ before, value: from });\n before -= duration;\n if (to !== undefined) push({ before: Math.max(0, before), value: to, ...withEase(s) });\n }\n return keys;\n}\n\n/** Whether `p` is a {@link Ramp}: anything with a `keys` array, a parsed copy included. */\nexport function isRamp(p: unknown): p is Ramp {\n return typeof p === \"object\" && p !== null && Array.isArray((p as Ramp).keys);\n}\n\nconst LINEAR = linear();\nconst resolved = new WeakMap<Ramp, { readonly length: number; readonly keys: readonly ResolvedRampKey[] }>();\n\n/**\n * The keys of `ramp` placed on a clip `length` seconds long, in time order.\n *\n * Every time is clamped to the clip, so a ramp longer than its clip is cut, not\n * squeezed. Keys whose anchors cross (a start key past an end key on a short\n * clip) are sorted by where they land, with a development warning.\n */\nexport function resolveRamp(ramp: Ramp, length: number): readonly ResolvedRampKey[] {\n const clip = Number.isFinite(length) && length > 0 ? length : 0;\n const cached = resolved.get(ramp);\n if (cached && cached.length === clip) return cached.keys;\n\n let crossed = false;\n let last = -Infinity;\n const keys = ramp.keys.map((key) => {\n const time = Math.min(clip, Math.max(0, key.before !== undefined ? clip - key.before : key.at ?? 0));\n if (time < last) crossed = true;\n last = time;\n const ease = key.ease ? easeOfSpec(key.ease) : LINEAR;\n return { time, value: key.value, ease, linear: !key.ease || key.ease.kind === \"linear\" };\n });\n if (crossed) {\n keys.sort((a, b) => a.time - b.time);\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(`[motionscript] A ramp's start and end keys cross on a ${clip.toFixed(3)}s clip; they play in the order they land.`);\n }\n }\n resolved.set(ramp, { length: clip, keys });\n return keys;\n}\n\n/** The value of `ramp` at `t` seconds into a clip `length` seconds long, `fallback` when it has no keys. */\nexport function sampleRamp(ramp: Ramp, t: number, length: number, fallback: number): number {\n const keys = resolveRamp(ramp, length);\n if (keys.length === 0) return fallback;\n if (t <= keys[0].time) return keys[0].value;\n for (let i = 1; i < keys.length; i++) {\n const key = keys[i];\n if (t > key.time) continue;\n const previous = keys[i - 1];\n const span = key.time - previous.time;\n return lerpNumber(previous.value, key.value, key.ease(span > 0 ? (t - previous.time) / span : 1));\n }\n return keys[keys.length - 1].value;\n}\n\n/** The value of `p` at `t`, for a number its own value. */\nexport function sampleParam(p: Param, t: number, length: number, fallback: number): number {\n return isRamp(p) ? sampleRamp(p, t, length, fallback) : p;\n}\n\n/** One representative number: the value itself, or the ramp's value at its start. */\nexport function staticValue(p: Param, fallback = 0): number {\n if (!isRamp(p)) return p;\n let first: RampKey | undefined;\n for (const key of p.keys) {\n if (key.at !== undefined && (first?.at === undefined || key.at < first.at)) first = key;\n }\n return (first ?? p.keys[0])?.value ?? fallback;\n}\n\n/** Equal for two params exactly when they sound the same: what tells a device a param was edited. */\nexport function paramKey(p: Param | undefined): string {\n if (p === undefined) return \"_\";\n return isRamp(p) ? `r${JSON.stringify(p.keys)}` : String(p);\n}\n\n/** Two numbers lerp; a ramp on either side hard-cuts at the midpoint. */\nexport function lerpParam(from: Param, to: Param, t: number): Param {\n if (typeof from === \"number\" && typeof to === \"number\") return lerpNumber(from, to, t);\n return t < 0.5 ? from : to;\n}\n\nexport function equalsParam(a: Param | undefined, b: Param | undefined): boolean {\n if (a === b) return true;\n if (typeof a === \"number\" || typeof b === \"number\" || a === undefined || b === undefined) return false;\n return paramKey(a) === paramKey(b);\n}\n\n/** The audio-param attribute's op set: resolve is the identity, lerp is {@link lerpParam}. */\nexport const audioParamOps: AttributeOps<Param, Param> = {\n resolve: (value) => value,\n lerp: lerpParam,\n};\n\nconst INTEGRATION_STEP = 0.001;\n/** The most cells one table holds: past it a long source gets coarser cells, not a bigger table. */\nconst MAX_CELLS = 20000;\n\n/**\n * `∫ 1/speed` tabulated once per ramp and source length: `clip[i]` is the clip\n * seconds spent by the start of cell `i`, so either direction is a lookup\n * rather than a walk from zero. A device asks hundreds of times a second of\n * clip while scheduling a rate, and walking from zero each time was quadratic.\n */\ninterface SpeedTable {\n readonly step: number;\n readonly clip: Float64Array;\n readonly rate: Float64Array;\n}\n\nconst speedTables = new WeakMap<Ramp, Map<string, SpeedTable>>();\n\nfunction speedTableOf(speed: Ramp, sourceLength: number, step: number): SpeedTable {\n let byLength = speedTables.get(speed);\n if (!byLength) speedTables.set(speed, (byLength = new Map()));\n const key = `${sourceLength}:${step}`;\n const cached = byLength.get(key);\n if (cached) return cached;\n const cells = Math.max(1, Math.min(MAX_CELLS, Math.ceil(sourceLength / step)));\n const size = sourceLength / cells;\n const clip = new Float64Array(cells + 1);\n const rate = new Float64Array(cells);\n for (let i = 0; i < cells; i++) {\n rate[i] = Math.max(1e-6, sampleRamp(speed, (i + 0.5) * size, sourceLength, 1));\n clip[i + 1] = clip[i] + size / rate[i];\n }\n const table = { step: size, clip, rate };\n if (byLength.size >= 8) byLength.clear();\n byLength.set(key, table);\n return table;\n}\n\n/**\n * Clip seconds spent playing the first `upper` source seconds under a speed\n * ramp: `∫ 1/speed(τ) dτ`. The ramp is placed on `sourceLength`, the source\n * seconds it is authored over, and speed is floored just above zero.\n */\nexport function integrateSpeedToClipTime(speed: Ramp, sourceLength: number, upper: number = sourceLength, step = INTEGRATION_STEP): number {\n const end = Math.min(upper, sourceLength);\n if (end <= 0) return 0;\n const table = speedTableOf(speed, sourceLength, step);\n const cell = Math.min(table.rate.length - 1, Math.floor(end / table.step));\n return table.clip[cell] + (end - cell * table.step) / table.rate[cell];\n}\n\n/** Inverse of {@link integrateSpeedToClipTime}: the source seconds reached after `clipElapsed` clip seconds. */\nexport function sourceTimeAtClipElapsed(speed: Ramp, sourceLength: number, clipElapsed: number, step = INTEGRATION_STEP): number {\n if (clipElapsed <= 0 || sourceLength <= 0) return 0;\n const table = speedTableOf(speed, sourceLength, step);\n const { clip, rate } = table;\n if (clipElapsed >= clip[clip.length - 1]) return sourceLength;\n let lo = 0;\n let hi = rate.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (clip[mid] <= clipElapsed) lo = mid;\n else hi = mid - 1;\n }\n return Math.min(sourceLength, lo * table.step + (clipElapsed - clip[lo]) * rate[lo]);\n}\n", "import { AudioEffect } from \"./union\";\nimport { Param, isRamp } from \"../ramp\";\n\n/**\n * Every builder takes one options object, and those with one dominant param\n * also take that param directly — a number or a {@link Ramp}, so\n * `AudioEffects.lowpass(ramp(8000, 400, 2))` works.\n */\n\n/** Gain. Param shorthand sets `value`. */\nexport interface GainEffectOptions {\n /** 1 = unchanged, 0 = silent, >1 = louder. */\n value: Param;\n}\n\n/** High-pass filter. Param shorthand sets `frequency`. */\nexport interface HighPassEffectOptions {\n /** Rolls off content below this frequency, in Hz. */\n frequency: Param;\n /** Resonance at the cutoff (default 1). */\n q?: Param;\n}\n\n/** Low-pass filter. Param shorthand sets `frequency`. */\nexport interface LowPassEffectOptions {\n /** Rolls off content above this frequency, in Hz. */\n frequency: Param;\n /** Resonance at the cutoff (default 1). */\n q?: Param;\n}\n\n/** Amplitude wobble. Param shorthand sets `rate`. */\nexport interface TremoloEffectOptions {\n /** Wobble rate in Hz. */\n rate: Param;\n /** Modulation depth, 0–1 (default 0.5). */\n depth?: Param;\n}\n\n/** Delay line with feedback. Param shorthand sets `delay`. */\nexport interface EchoEffectOptions {\n /** Delay time in seconds. */\n delay: Param;\n /** Feedback amount, 0–<1 (default 0.4). */\n feedback?: Param;\n /** Wet mix, 0–1 (default 0.5). */\n mix?: Param;\n}\n\n/** A ramp is an object too, so the shorthand test has to ask {@link isRamp}, or it reads as an options bag. */\nfunction scalarParam<O extends object>(arg: Param | O, key: keyof O): O {\n return typeof arg === \"number\" || isRamp(arg) ? ({ [key]: arg } as O) : (arg as O);\n}\n\n/**\n * Immutable, chainable list of audio effects, applied in order (index 0\n * closest to the source).\n *\n * @example\n * const chain = AudioEffects.gain(1.5).lowpass(800).echo(0.3);\n */\nexport class AudioEffectChain {\n constructor(public list: AudioEffect[] = []) { }\n\n private append(effect: AudioEffect): AudioEffectChain {\n return new AudioEffectChain([...this.list, effect]);\n }\n\n gain(options: Param | GainEffectOptions) {\n const { value } = scalarParam(options, \"value\");\n return this.append({ type: 'gain', value });\n }\n\n /** Alias for {@link gain}. */\n volume(options: Param | GainEffectOptions) {\n return this.gain(options);\n }\n\n /** Rolls off content below `frequency` Hz. */\n highpass(options: Param | HighPassEffectOptions) {\n const { frequency, q } = scalarParam(options, \"frequency\");\n return this.append({ type: 'highpass', frequency, q });\n }\n\n /** Rolls off content above `frequency` Hz. */\n lowpass(options: Param | LowPassEffectOptions) {\n const { frequency, q } = scalarParam(options, \"frequency\");\n return this.append({ type: 'lowpass', frequency, q });\n }\n\n /** A `rate` Hz wobble at `depth` (0–1). */\n tremolo(options: Param | TremoloEffectOptions) {\n const { rate, depth } = scalarParam(options, \"rate\");\n return this.append({ type: 'tremolo', rate, depth: depth ?? 0.5 });\n }\n\n /** `delay` seconds, `feedback` 0–<1, optional wet `mix` 0–1. */\n echo(options: Param | EchoEffectOptions) {\n const { delay, feedback, mix } = scalarParam(options, \"delay\");\n return this.append({ type: 'echo', delay, feedback: feedback ?? 0.4, mix });\n }\n\n *[Symbol.iterator]() {\n yield* this.list;\n }\n\n toJSON() {\n return this.list;\n }\n}\n\n/** What an `effects` prop accepts: one effect, a plain array, or a chain. */\nexport type AudioEffectsInput = AudioEffect[] | AudioEffectChain | AudioEffect;\n\n/** An empty {@link AudioEffectChain}: `AudioEffects.gain(1.5)` is `new AudioEffectChain().gain(1.5)`. */\nexport const AudioEffects = new AudioEffectChain();\n\nexport function resolveAudioEffects(effects: AudioEffectsInput | undefined): AudioEffect[] {\n if (effects === undefined) return [];\n if (effects instanceof AudioEffectChain) return effects.list;\n if (Array.isArray(effects)) return effects;\n return [effects];\n}\n", "import type { AudioEffectData } from \"../registry\";\nimport { Param, lerpParam, equalsParam } from \"../../ramp\";\n\n/** Scales the clip's amplitude by a linear factor. */\nexport interface GainEffect {\n type: 'gain';\n /** Linear gain multiplier. 1 = unchanged, 0 = silent, >1 = louder. May be a ramp. */\n value: Param;\n}\n\nexport const gainEffect: AudioEffectData<GainEffect> = {\n lerp: (from, to, t) => ({ type: \"gain\", value: lerpParam(from.value, to.value, t) }),\n equals: (a, b) => equalsParam(a.value, b.value),\n};\n", "import type { AudioEffectData } from \"../registry\";\nimport { Param, lerpParam, equalsParam } from \"../../ramp\";\n\n/** Attenuates frequencies below `frequency`, passing the highs through. */\nexport interface HighPassEffect {\n type: 'highpass';\n /** Cutoff frequency in Hz. Content below this is rolled off. May be a ramp. */\n frequency: Param;\n /** Resonance (Q) at the cutoff. Default 1. May be a ramp. */\n q?: Param;\n}\n\nexport const highPassEffect: AudioEffectData<HighPassEffect> = {\n lerp: (from, to, t) => ({\n type: \"highpass\",\n frequency: lerpParam(from.frequency, to.frequency, t),\n q: lerpParam(from.q ?? 1, to.q ?? 1, t),\n }),\n equals: (a, b) => equalsParam(a.frequency, b.frequency) && equalsParam(a.q ?? 1, b.q ?? 1),\n};\n", "import type { AudioEffectData } from \"../registry\";\nimport { Param, lerpParam, equalsParam } from \"../../ramp\";\n\n/** Attenuates frequencies above `frequency`, passing the lows through. */\nexport interface LowPassEffect {\n type: 'lowpass';\n /** Cutoff frequency in Hz. Content above this is rolled off. May be a ramp. */\n frequency: Param;\n /** Resonance (Q) at the cutoff. Default 1. May be a ramp. */\n q?: Param;\n}\n\nexport const lowPassEffect: AudioEffectData<LowPassEffect> = {\n lerp: (from, to, t) => ({\n type: \"lowpass\",\n frequency: lerpParam(from.frequency, to.frequency, t),\n q: lerpParam(from.q ?? 1, to.q ?? 1, t),\n }),\n equals: (a, b) => equalsParam(a.frequency, b.frequency) && equalsParam(a.q ?? 1, b.q ?? 1),\n};\n", "import type { AudioEffectData } from \"../registry\";\nimport { Param, lerpParam, equalsParam } from \"../../ramp\";\n\n/** Modulates the clip's amplitude with a low-frequency oscillator for a wobble effect. */\nexport interface TremoloEffect {\n type: 'tremolo';\n /** Modulation rate in Hz (how fast the volume pulses). May be a ramp. */\n rate: Param;\n /** Modulation depth, 0–1. 0 = no effect, 1 = full dips to silence. May be a ramp. */\n depth: Param;\n}\n\nexport const tremoloEffect: AudioEffectData<TremoloEffect> = {\n lerp: (from, to, t) => ({\n type: \"tremolo\",\n rate: lerpParam(from.rate, to.rate, t),\n depth: lerpParam(from.depth, to.depth, t),\n }),\n equals: (a, b) => equalsParam(a.rate, b.rate) && equalsParam(a.depth, b.depth),\n};\n", "import type { AudioEffectData } from \"../registry\";\nimport { Param, lerpParam, equalsParam } from \"../../ramp\";\n\n/** Adds a delayed, fading repeat of the signal (a feedback echo / simple delay). */\nexport interface EchoEffect {\n type: 'echo';\n /** Delay before the first repeat, in seconds. May be a ramp. */\n delay: Param;\n /** Feedback amount, 0–<1. Each repeat is scaled by this; higher = more repeats. May be a ramp. */\n feedback: Param;\n /** Wet/dry mix, 0–1. 0 = dry only, 1 = full wet. Default 0.5. May be a ramp. */\n mix?: Param;\n}\n\nexport const echoEffect: AudioEffectData<EchoEffect> = {\n lerp: (from, to, t) => ({\n type: \"echo\",\n delay: lerpParam(from.delay, to.delay, t),\n feedback: lerpParam(from.feedback, to.feedback, t),\n mix: lerpParam(from.mix ?? 0.5, to.mix ?? 0.5, t),\n }),\n equals: (a, b) =>\n equalsParam(a.delay, b.delay) && equalsParam(a.feedback, b.feedback) && equalsParam(a.mix ?? 0.5, b.mix ?? 0.5),\n};\n", "import { AudioEffect } from \"@/attributes/audio/effects/union\";\nimport { type AudioEffectsInput, resolveAudioEffects } from \"@/attributes/audio/effects/chain\";\nimport type { AttributeOps } from \"@/attributes/shared/operators\";\nimport { gainEffect } from \"./implementations/gain\";\nimport { highPassEffect } from \"./implementations/highpass\";\nimport { lowPassEffect } from \"./implementations/lowpass\";\nimport { tremoloEffect } from \"./implementations/tremolo\";\nimport { echoEffect } from \"./implementations/echo\";\n\n/** Interpolation and equality contract every registered audio effect must implement. */\nexport interface AudioEffectData<T extends AudioEffect> {\n /** Return a new effect linearly interpolated between `from` and `to` at progress `t` (0–1). */\n lerp(from: T, to: T, t: number): T;\n /** Return true when both effects are audibly identical (used to skip redundant work). */\n equals(a: T, b: T): boolean;\n}\n\n/**\n * Every built-in effect's handler, keyed by its `type` — an effect missing here\n * is a type error. Seeded into the registry rather than registered by each\n * effect's own module: core is `sideEffects: false`, so a module imported only\n * to run a `register` call is one a bundler may drop, and the effect it held\n * would then hard-cut instead of interpolating, with nothing raised.\n */\nconst BUILT_IN_EFFECTS: { [K in AudioEffect[\"type\"]]: AudioEffectData<Extract<AudioEffect, { type: K }>> } = {\n gain: gainEffect,\n highpass: highPassEffect,\n lowpass: lowPassEffect,\n tremolo: tremoloEffect,\n echo: echoEffect,\n};\n\n/** Central registry that maps audio-effect type strings to their `AudioEffectData` handlers. */\nexport class AudioEffectRegistry {\n private static registry = new Map<string, AudioEffectData<AudioEffect>>(\n Object.entries(BUILT_IN_EFFECTS) as [string, AudioEffectData<AudioEffect>][],\n );\n\n /**\n * Register an effect type.\n * Throws if the same `type` key is registered more than once to catch accidental double-imports.\n */\n static register<T extends AudioEffect>(type: string, data: AudioEffectData<T>): void {\n if (this.registry.has(type)) {\n throw new Error(`Audio effect \"${type}\" is already registered`);\n }\n this.registry.set(type, data as AudioEffectData<AudioEffect>);\n }\n\n /** Look up the `AudioEffectData` for a given type key, or `undefined` if not registered. */\n static get(type: string): AudioEffectData<AudioEffect> | undefined {\n return this.registry.get(type);\n }\n\n /** Return true when an effect type has been registered. */\n static has(type: string): boolean {\n return this.registry.has(type);\n }\n\n /**\n * Interpolate between two individual effects at progress `t`.\n * Falls back to a hard cut at t = 0.5 when the types differ or are unregistered.\n */\n static lerp(from: AudioEffect, to: AudioEffect, t: number): AudioEffect {\n if (from.type !== to.type) return t < 0.5 ? from : to;\n const data = this.registry.get(from.type);\n return data ? data.lerp(from, to, t) : (t < 0.5 ? from : to);\n }\n\n /**\n * Interpolate between two effect arrays of potentially different lengths.\n * Indices present in only one array are kept as-is; matched indices are lerped pairwise.\n */\n static lerpArray(from: AudioEffect[], to: AudioEffect[], t: number): AudioEffect[] {\n const maxLen = Math.max(from.length, to.length);\n const result: AudioEffect[] = [];\n for (let i = 0; i < maxLen; i++) {\n const a = from[i];\n const b = to[i];\n if (a && b) {\n result.push(AudioEffectRegistry.lerp(a, b, t));\n } else if (a) {\n result.push(a);\n } else if (b) {\n result.push(b);\n }\n }\n return result;\n }\n}\n\n/** The audio-effect-chain attribute's op set — the `effects` prop's resolve/lerp pair. */\nexport const audioEffectsOps: AttributeOps<AudioEffectsInput, AudioEffect[]> = {\n resolve: resolveAudioEffects,\n lerp: AudioEffectRegistry.lerpArray,\n};\n", "import { Vector2 } from \"@/attributes/layout/vector2\";\n\n/**\n * A 2D transform stored as the members of a 3×3 matrix:\n *\n * ```\n * | a c e |\n * | b d f |\n * | g h i |\n * ```\n *\n * Point mapping is `x' = (a·x + c·y + e) / w`, `y' = (b·x + d·y + f) / w`, with\n * `w = g·x + h·y + i`. This is the same column-order convention the DOM\n * uses, so matrices compose in draw order: `parent.multiply(child)` is the world\n * transform of `child`.\n *\n * **The bottom row is optional, and leaving it off means `[0 0 1]`** — an\n * ordinary affine transform, where `w` is 1 everywhere and the divide falls\n * away. Every matrix in the engine was exactly that until\n * {@link nodeProjectedMatrix} arrived: a node tilted out of its own plane\n * projects through a *homography*, and a homography does not fit in six numbers.\n * Rather than a second matrix type — with a second `multiply`, `invert` and\n * `applyToPoint` beside it, which is precisely how a renderer and a hit test end\n * up disagreeing about where a node is — the row lives here, and everything that\n * has no use for it simply omits it.\n */\n/** @internal */\nexport interface Matrix2D {\n a: number; b: number; c: number; d: number; e: number; f: number;\n /** Perspective row, x term. Omitted on an affine transform (means `0`). */\n g?: number;\n /** Perspective row, y term. Omitted on an affine transform (means `0`). */\n h?: number;\n /** Perspective row, constant term. Omitted on an affine transform (means `1`). */\n i?: number;\n}\n\n/** @internal Whether `m` carries a perspective row — i.e. whether `w` is not always 1. */\nexport function isProjective(m: Matrix2D): boolean {\n return (m.g ?? 0) !== 0 || (m.h ?? 0) !== 0 || (m.i ?? 1) !== 1;\n}\n\n/**\n * Guard the perspective divide. A point on the vanishing line has `w = 0` and\n * projects to infinity, which is a real answer no coordinate can hold; clamping\n * to a tiny same-signed `w` sends it far off-screen instead, which is where it\n * belongs and is a number the caller can keep doing arithmetic with. Without\n * this, one degenerate corner turns an anchor set into `Infinity`/`NaN` and\n * takes the selection box, the hit test and any layout reading it with it.\n */\nconst MIN_W = 1e-6;\nfunction safeW(w: number): number {\n if (w > MIN_W || w < -MIN_W) return w;\n return w < 0 ? -MIN_W : MIN_W;\n}\n\n/** @internal The identity transform — maps every point to itself. */\nexport function identity(): Matrix2D {\n return { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };\n}\n\n/** @internal Pure translation by (tx, ty). */\nexport function translation(tx: number, ty: number): Matrix2D {\n return { a: 1, b: 0, c: 0, d: 1, e: tx, f: ty };\n}\n\n/**\n * `m1 · m2` — the transform that applies `m2` first, then `m1`. Composing an\n * ancestor with a descendant (`ancestor.multiply(descendant)`) yields the\n * descendant's world transform.\n *\n * Two affine matrices take the six-member path they always did — that is every\n * composition in a scene with no 3D in it, once per node per parent per frame —\n * and the general 3×3 product runs only when one side actually carries a\n * perspective row.\n */\n/** @internal */\nexport function multiply(m1: Matrix2D, m2: Matrix2D): Matrix2D {\n if (isProjective(m1) || isProjective(m2)) return multiplyProjective(m1, m2);\n return {\n a: m1.a * m2.a + m1.c * m2.b,\n b: m1.b * m2.a + m1.d * m2.b,\n c: m1.a * m2.c + m1.c * m2.d,\n d: m1.b * m2.c + m1.d * m2.d,\n e: m1.a * m2.e + m1.c * m2.f + m1.e,\n f: m1.b * m2.e + m1.d * m2.f + m1.f,\n };\n}\n\n/** The full 3×3 product, rows `[a c e] [b d f] [g h i]`. See {@link multiply}. */\nfunction multiplyProjective(m1: Matrix2D, m2: Matrix2D): Matrix2D {\n const g1 = m1.g ?? 0, h1 = m1.h ?? 0, i1 = m1.i ?? 1;\n const g2 = m2.g ?? 0, h2 = m2.h ?? 0, i2 = m2.i ?? 1;\n return {\n a: m1.a * m2.a + m1.c * m2.b + m1.e * g2,\n c: m1.a * m2.c + m1.c * m2.d + m1.e * h2,\n e: m1.a * m2.e + m1.c * m2.f + m1.e * i2,\n b: m1.b * m2.a + m1.d * m2.b + m1.f * g2,\n d: m1.b * m2.c + m1.d * m2.d + m1.f * h2,\n f: m1.b * m2.e + m1.d * m2.f + m1.f * i2,\n g: g1 * m2.a + h1 * m2.b + i1 * g2,\n h: g1 * m2.c + h1 * m2.d + i1 * h2,\n i: g1 * m2.e + h1 * m2.f + i1 * i2,\n };\n}\n\n/** @internal Map a point through the transform. */\nexport function applyToPoint(m: Matrix2D, p: Vector2): Vector2 {\n const x = m.a * p.x + m.c * p.y + m.e;\n const y = m.b * p.x + m.d * p.y + m.f;\n if (!isProjective(m)) return { x, y };\n const w = safeW((m.g ?? 0) * p.x + (m.h ?? 0) * p.y + (m.i ?? 1));\n return { x: x / w, y: y / w };\n}\n\n/**\n * The inverse transform, or `null` when `m` is singular (a zero scale collapses\n * the plane, so no inverse exists). Used to map a viewport-space point back into\n * a node's local space for hit testing.\n */\n/** @internal */\nexport function invert(m: Matrix2D): Matrix2D | null {\n if (isProjective(m)) return invertProjective(m);\n const det = m.a * m.d - m.b * m.c;\n if (det === 0 || !Number.isFinite(det)) return null;\n const inv = 1 / det;\n return {\n a: m.d * inv,\n b: -m.b * inv,\n c: -m.c * inv,\n d: m.a * inv,\n e: (m.c * m.f - m.d * m.e) * inv,\n f: (m.b * m.e - m.a * m.f) * inv,\n };\n}\n\n/**\n * The inverse of a homography — the adjugate over the determinant, written out\n * in this module's row naming. A projective inverse is still a homography, which\n * is what lets picking keep mapping a viewport point back into a node's local\n * space with nothing but {@link applyToPoint} once the node is tilted.\n */\nfunction invertProjective(m: Matrix2D): Matrix2D | null {\n const { a, b, c, d, e, f } = m;\n const g = m.g ?? 0, h = m.h ?? 0, i = m.i ?? 1;\n // Cofactors of the 3×3 | a c e | / | b d f | / | g h i |.\n const A = d * i - f * h;\n const C = f * g - b * i;\n const E = b * h - d * g;\n const det = a * A + c * C + e * E;\n if (det === 0 || !Number.isFinite(det)) return null;\n const inv = 1 / det;\n return {\n a: A * inv,\n c: (e * h - c * i) * inv,\n e: (c * f - e * d) * inv,\n b: C * inv,\n d: (a * i - e * g) * inv,\n f: (e * b - a * f) * inv,\n g: E * inv,\n h: (c * g - a * h) * inv,\n i: (a * d - c * b) * inv,\n };\n}\n\n/**\n * The viewport transform a camera scope pushes, in canvas (y-down) space — a\n * literal transcription of `RenderContext2D.beginCamera`:\n *\n * translate(vx, vy) · rotate(-heading) · scale(zoom) · translate(-lookAt.x, +lookAt.y)\n *\n * `lookAt` is a y-up world point, hence the sign flip on its y. `vx`/`vy` are the\n * viewport centre the camera's callers pass (`layoutBounds.x`, `-layoutBounds.y`).\n * Kept next to {@link nodeLocalMatrix} so the two stay in step with the renderer.\n */\n/** @internal */\nexport function cameraMatrix(\n vx: number, vy: number, lookAt: Vector2, zoom: number, heading: number,\n): Matrix2D {\n const rad = (-heading * Math.PI) / 180;\n const cos = Math.cos(rad);\n const sin = Math.sin(rad);\n // rotate(-heading) · scale(zoom), the same clockwise canvas convention as\n // nodeLocalMatrix's R·S block.\n const a = zoom * cos;\n const b = zoom * sin;\n const c = zoom * -sin;\n const d = zoom * cos;\n // Fold the trailing translate(-lookAt.x, +lookAt.y) into e/f.\n const tx = -lookAt.x;\n const ty = lookAt.y;\n return { a, b, c, d, e: vx + a * tx + c * ty, f: vy + b * tx + d * ty };\n}\n\n/**\n * Build the local transform for a node, matching the renderer's\n * `RenderContext2D.transform` exactly (canvas y-down space):\n * `T(cx + pivotX, cy + pivotY) · R(deg) · S(scale) · T(-pivotX, -pivotY)`.\n *\n * @param cx Canvas-space x of the node's layout-cell lookAt.\n * @param cy Canvas-space y of the node's layout-cell origin (y-down).\n * @param rotation Rotation in degrees, clockwise (canvas convention).\n * @param scale Uniform scale factor.\n * @param pivotX Pivot offset in pixels, x.\n * @param pivotY Pivot offset in pixels, y (canvas y-down).\n */\n/** @internal */\nexport function nodeLocalMatrix(\n cx: number, cy: number, rotation: number, scale: number, pivotX: number, pivotY: number,\n): Matrix2D {\n const rad = (rotation * Math.PI) / 180;\n const cos = Math.cos(rad);\n const sin = Math.sin(rad);\n // R(deg) · S(scale): clockwise rotation in canvas (y-down) is\n // | cos -sin | · | s 0 | = | s·cos -s·sin |\n // | sin cos | | 0 s | | s·sin s·cos |\n const a = scale * cos;\n const b = scale * sin;\n const c = scale * -sin;\n const d = scale * cos;\n // Fold the pivot translations into e/f:\n // T(cx+pivotX, cy+pivotY) · (RS) · T(-pivotX, -pivotY)\n return {\n a, b, c, d,\n e: cx + pivotX - (a * pivotX + c * pivotY),\n f: cy + pivotY - (b * pivotX + d * pivotY),\n };\n}\n\n/**\n * The out-of-plane half of a node's transform — the mirrors, the two extra\n * rotation axes, the push along z and the perspective divide that makes them\n * read as depth rather than as squashing. See {@link nodeProjectedMatrix}.\n */\n/** @internal */\nexport interface Projection3D {\n /** Tilt about the horizontal axis, degrees. Positive tips the top away. */\n rotationX: number;\n /** Tilt about the vertical axis, degrees. Positive swings the right edge away. */\n rotationY: number;\n /**\n * In-plane rotation belonging to the 3D block, degrees clockwise — the Z axis\n * of `Rx · Ry · Rz`.\n *\n * A prop of its own rather than a second name for the node's `rotation`, and\n * that is a deliberate separation: `rotation` is the node's **shape** — it\n * turns the box, the selection outline turns with it, and handles follow —\n * while this is part of the projection, which is paint. The two compose (a\n * Z rotation is a Z rotation, so they add), but they are two independent\n * numbers and editing one never moves the other.\n */\n rotationZ: number;\n /** Push along the view axis in px, applied after the rotations. Inert without `perspective`. */\n depth: number;\n /** Viewer distance in px. `0` is no perspective at all — a parallel projection. */\n perspective: number;\n /** Mirror across the node's vertical centre line. */\n flipHorizontal: boolean;\n /** Mirror across the node's horizontal centre line. */\n flipVertical: boolean;\n}\n\n/** @internal Every field of a {@link Projection3D} at rest — the plain 2D node. */\nexport const NO_PROJECTION_3D: Projection3D = {\n rotationX: 0,\n rotationY: 0,\n rotationZ: 0,\n depth: 0,\n perspective: 0,\n flipHorizontal: false,\n flipVertical: false,\n};\n\n/**\n * Whether `p` asks for anything {@link nodeLocalMatrix} cannot already express.\n * The gate in front of every projective path in the engine: a scene with no 3D\n * in it keeps the six-number matrix, the decomposed `translate/rotate/scale`\n * render path, and the affine `multiply` it always had.\n */\n/** @internal */\nexport function hasProjection3D(p: Projection3D): boolean {\n return (\n p.rotationX !== 0 ||\n p.rotationY !== 0 ||\n p.rotationZ !== 0 ||\n p.flipHorizontal ||\n p.flipVertical ||\n (p.perspective !== 0 && p.depth !== 0)\n );\n}\n\n/**\n * Whether a plane carrying this projection has turned its back on the viewer —\n * the test behind `backfaceVisible`.\n *\n * Read off the tilt alone. The plane's normal starts at `(0,0,1)` and comes out\n * of `Rx·Ry` with a z of `cos(rotationX)·cos(rotationY)`; the in-plane rotation\n * can't change which way it points, and neither, deliberately, can a *mirror*.\n * CSS derives the answer from the whole accumulated matrix, where a `scaleX(-1)`\n * inverts orientation and hides the element — which is a surprising way to lose\n * a node you only meant to flip. Here a flip is a flip and a turn is a turn.\n */\n/** @internal */\nexport function facesAway(rotationX: number, rotationY: number): boolean {\n const rad = Math.PI / 180;\n return Math.cos(rotationX * rad) * Math.cos(rotationY * rad) < 0;\n}\n\n/**\n * A node's local transform with the out-of-plane half folded in — the same space\n * and the same pivot convention as {@link nodeLocalMatrix}, which this reduces to\n * exactly when {@link hasProjection3D} is false.\n *\n * The composition, innermost first:\n *\n * `T(pivot) · P(perspective) · Tz(depth) · Rx · Ry · Rz(rotationZ + rotation) · S(scale) · T(-pivot) · F(flip)`\n *\n * — everything about the pivot except the mirrors, which reflect about the\n * node's own centre so that flipping cannot move the node (see `F` below),\n *\n * which is CSS's own order for `rotateX(a) rotateY(b) rotateZ(c)` — the in-plane\n * rotation innermost, so that adding a tilt never changes what the node's own\n * `rotation` already meant.\n *\n * The Z angle is the **sum** of the two in-plane rotations the node carries, and\n * they stay two: `rotation` turns the node's *shape* — its box turns with it, and\n * so does anything reading that box — while {@link Projection3D.rotationZ} is\n * part of the projection, which is paint (see `Node2D._localMatrix`). Summing them\n * is not a coupling but the definition of composing two rotations about one axis;\n * neither number moves when the other is edited.\n *\n * The content is planar — every point enters with `z = 0` — so the whole thing\n * collapses to a 3×3 homography over `(x, y, 1)` rather than needing a 4×4 and a\n * separate divide step. The projected z survives only as the perspective row.\n *\n * @param cx Canvas-space x of the node's positioned centre.\n * @param cy Canvas-space y of the node's positioned centre (y-down).\n * @param rotation In-plane rotation in degrees, clockwise (the Z axis).\n * @param scale Uniform scale factor.\n * @param pivotX Pivot offset from the centre in px, x.\n * @param pivotY Pivot offset from the centre in px, y (canvas y-down).\n * @param p The out-of-plane fields.\n */\n/** @internal */\nexport function nodeProjectedMatrix(\n cx: number, cy: number, rotation: number, scale: number, pivotX: number, pivotY: number,\n p: Projection3D,\n): Matrix2D {\n if (!hasProjection3D(p)) {\n return nodeLocalMatrix(cx, cy, rotation, scale, pivotX, pivotY);\n }\n const rad = Math.PI / 180;\n const ca = Math.cos(p.rotationX * rad), sa = Math.sin(p.rotationX * rad);\n const cb = Math.cos(p.rotationY * rad), sb = Math.sin(p.rotationY * rad);\n // The two in-plane rotations compose into one angle — see the note above.\n const cz = (rotation + p.rotationZ) * rad;\n const cc = Math.cos(cz), sc = Math.sin(cz);\n\n // The two columns of Rx·Ry·Rz that a z = 0 point can reach, scaled.\n const A = cb * cc * scale;\n const C = -cb * sc * scale;\n const B = (sa * sb * cc + ca * sc) * scale;\n const D = (ca * cc - sa * sb * sc) * scale;\n // The row that would have been the projected z, had we kept one.\n const G = (sa * sc - ca * sb * cc) * scale;\n const H = (ca * sb * sc + sa * cc) * scale;\n\n // Perspective: a point at depth z lands at x/w with w = 1 - z/perspective.\n // No perspective means a parallel projection — z is simply dropped, w stays\n // 1, and the result is affine (which is also why `depth` alone does nothing).\n const invP = p.perspective !== 0 ? 1 / p.perspective : 0;\n const g = -G * invP;\n const h = -H * invP;\n // The z the pivot itself sits at: -(G·pivotX + H·pivotY) is what the shift to\n // pivot-relative coordinates leaves in the z row, and `depth` is the push\n // along it, applied after the tilt (so it moves the whole tilted plane).\n const i = 1 - (p.depth - (G * pivotX + H * pivotY)) * invP;\n\n // Numerators about the pivot, then the trailing translate folded in. A\n // translate composes onto a homography as `+ t·w`, hence the g/h/i terms.\n const tx = cx + pivotX;\n const ty = cy + pivotY;\n\n // The mirrors, applied **innermost and about the node's own centre** — a\n // final column negation, which is what `M · diag(fx, fy, 1)` comes to.\n //\n // Not about the pivot, unlike everything else here, and that is the whole\n // point: a flip is an in-place reflection. Composing it with the pivot the\n // way CSS's `scaleX(-1)` does means a node hinged anywhere but its middle\n // *swings* when you flip it — its position readout changes, its corner\n // handles land somewhere else, and the gesture stops meaning \"mirror this\"\n // and starts meaning \"mirror this and move it\". Every design tool flips\n // about the selection's own centre for that reason. Written as a column\n // scale rather than a `T(c)·F·T(-c)` sandwich because that is what one\n // reduces to here — the local frame is already centred on the node — which\n // leaves `e`/`f`/`i` untouched and makes \"a flip cannot move the node\" a\n // property of the arithmetic rather than a thing to remember.\n const fx = p.flipHorizontal ? -1 : 1;\n const fy = p.flipVertical ? -1 : 1;\n return {\n a: (A + tx * g) * fx,\n c: (C + tx * h) * fy,\n e: -(A * pivotX + C * pivotY) + tx * i,\n b: (B + ty * g) * fx,\n d: (D + ty * h) * fy,\n f: -(B * pivotX + D * pivotY) + ty * i,\n g: g * fx,\n h: h * fy,\n i,\n };\n}\n", "import { lerpNumber } from \"@/tween/lerp\";\nimport type { Matrix2D, Projection3D } from \"./matrix2d\";\nimport type { Vector2 } from \"./vector2\";\n\n/**\n * The maths of a 2.5D space: flat nodes placed in one 3D frame and seen through\n * a single orbiting camera, rather than each projecting through a perspective of\n * its own (see {@link import(\"./matrix2d\").nodeProjectedMatrix}).\n *\n * Everything here works in the space root's canvas frame — x right, y **down**,\n * z toward the viewer, the frame `nodeProjectedMatrix` already tilts nodes in —\n * so a node's transform is the same rotation block with the perspective divide\n * lifted out and applied once, by the camera, to the whole scene.\n */\n\n/** A point a camera is aimed at. `z` is depth, toward the viewer, as a node's `depth` is. */\nexport interface LookAt extends Vector2 {\n z?: number;\n}\n\n/** Lerp a {@link LookAt}, leaving `z` off when neither end has one so a flat camera stays two numbers. */\nexport function lerpLookAt(from: LookAt, to: LookAt, t: number): LookAt {\n const out: LookAt = { x: lerpNumber(from.x, to.x, t), y: lerpNumber(from.y, to.y, t) };\n if (from.z !== undefined || to.z !== undefined) out.z = lerpNumber(from.z ?? 0, to.z ?? 0, t);\n return out;\n}\n\n/**\n * A space root's camera for one frame.\n *\n * `orbit`/`elevation` mean what they mean on `Camera3D` (`render3d/camera.ts`,\n * `resolveCameraPlacement`): orbit 0 is head-on, a positive orbit moves the\n * camera toward +x, a positive elevation lifts it. `perspective` is the camera's\n * distance from `lookAt` at `dolly: 0`, CSS's convention, so the focus plane\n * draws 1:1; `0` is a parallel projection. `zoom` and `heading` apply after the\n * projection, which makes them lens zoom and roll exactly.\n */\n/** @internal */\nexport interface SpaceCamera {\n perspective: number;\n orbit: number;\n elevation: number;\n dolly: number;\n /** Authored y-up, like every other scene point. */\n lookAt: LookAt;\n zoom: number;\n heading: number;\n /** The viewport centre in the root's canvas frame. */\n viewportX: number;\n viewportY: number;\n}\n\n/** Row-major 3×4 affine transform: `[r00 r01 r02 tx, r10 r11 r12 ty, r20 r21 r22 tz]`. */\n/** @internal */\nexport type Affine3 = readonly number[];\n\n/** @internal */\nexport const IDENTITY_AFFINE3: Affine3 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];\n\n/** @internal `a · b` — applies `b` first, the same order as `matrix2d`'s `multiply`. */\nexport function multiplyAffine3(a: Affine3, b: Affine3): Affine3 {\n const out = new Array<number>(12);\n for (let r = 0; r < 3; r++) {\n const a0 = a[r * 4], a1 = a[r * 4 + 1], a2 = a[r * 4 + 2], a3 = a[r * 4 + 3];\n out[r * 4] = a0 * b[0] + a1 * b[4] + a2 * b[8];\n out[r * 4 + 1] = a0 * b[1] + a1 * b[5] + a2 * b[9];\n out[r * 4 + 2] = a0 * b[2] + a1 * b[6] + a2 * b[10];\n out[r * 4 + 3] = a0 * b[3] + a1 * b[7] + a2 * b[11] + a3;\n }\n return out;\n}\n\n/**\n * A node's transform in its parent's 3D frame — {@link import(\"./matrix2d\").nodeProjectedMatrix}\n * without the perspective, which in a space belongs to the camera:\n *\n * `T(cx + pivotX, cy + pivotY, depth) · Rx · Ry · Rz(rotation + rotationZ) · S(scale) · T(-pivot) · F(flip)`\n *\n * `p.perspective` is ignored. The scale is uniform in all three axes, so a\n * scaled group scales the depth its children sit at too.\n */\n/** @internal */\nexport function nodeSpaceMatrix(\n cx: number, cy: number, rotation: number, scale: number, pivotX: number, pivotY: number,\n p: Projection3D,\n): Affine3 {\n const rad = Math.PI / 180;\n const ca = Math.cos(p.rotationX * rad), sa = Math.sin(p.rotationX * rad);\n const cb = Math.cos(p.rotationY * rad), sb = Math.sin(p.rotationY * rad);\n const cz = (rotation + p.rotationZ) * rad;\n const cc = Math.cos(cz), sc = Math.sin(cz);\n\n const r00 = cb * cc * scale, r01 = -cb * sc * scale, r02 = sb * scale;\n const r10 = (sa * sb * cc + ca * sc) * scale, r11 = (ca * cc - sa * sb * sc) * scale, r12 = -sa * cb * scale;\n const r20 = (sa * sc - ca * sb * cc) * scale, r21 = (ca * sb * sc + sa * cc) * scale, r22 = ca * cb * scale;\n\n // Mirrors negate the two in-plane columns only, about the node's own centre —\n // the same in-place reflection `nodeProjectedMatrix` makes.\n const fx = p.flipHorizontal ? -1 : 1;\n const fy = p.flipVertical ? -1 : 1;\n return [\n r00 * fx, r01 * fy, r02, cx + pivotX - (r00 * pivotX + r01 * pivotY),\n r10 * fx, r11 * fy, r12, cy + pivotY - (r10 * pivotX + r11 * pivotY),\n r20 * fx, r21 * fy, r22, p.depth - (r20 * pivotX + r21 * pivotY),\n ];\n}\n\n/**\n * The camera's view of the root frame: `T(0, 0, dolly) · R(camera)ᵀ · T(-lookAt)`.\n *\n * Built from the camera's own axes rather than from a look-at basis, so there is\n * no pole to clamp: an elevation past 90° keeps turning rather than snapping to\n * an arbitrary roll.\n */\n/** @internal */\nexport function spaceViewMatrix(cam: SpaceCamera): Affine3 {\n const rad = Math.PI / 180;\n const sa = Math.sin(cam.orbit * rad), ca = Math.cos(cam.orbit * rad);\n const se = Math.sin(cam.elevation * rad), ce = Math.cos(cam.elevation * rad);\n // Rows: the camera's right, screen-down and toward-camera axes.\n const r0 = ca, r1 = 0, r2 = -sa;\n const d0 = sa * se, d1 = ce, d2 = ca * se;\n const f0 = sa * ce, f1 = -se, f2 = ca * ce;\n const tx = cam.lookAt.x, ty = -cam.lookAt.y, tz = cam.lookAt.z ?? 0;\n return [\n r0, r1, r2, -(r0 * tx + r1 * ty + r2 * tz),\n d0, d1, d2, -(d0 * tx + d1 * ty + d2 * tz),\n f0, f1, f2, -(f0 * tx + f1 * ty + f2 * tz) + cam.dolly,\n ];\n}\n\n/**\n * Project a view-space transform onto the screen: the homography that maps a\n * node's local `(x, y, 1)` to the root's canvas, perspective divide and the\n * camera's zoom and roll included.\n *\n * At rest — no orbit, elevation, dolly or `lookAt.z`, and a node with no depth\n * or tilt — this is exactly `cameraMatrix · local`, which is what makes turning\n * a space on invisible until something moves in depth.\n */\n/** @internal */\nexport function spaceScreenMatrix(cam: SpaceCamera, view: Affine3): Matrix2D {\n const invP = cam.perspective > 0 ? 1 / cam.perspective : 0;\n const wx = -view[8] * invP;\n const wy = -view[9] * invP;\n const w0 = 1 - view[11] * invP;\n\n const rad = (-cam.heading * Math.PI) / 180;\n const k = cam.zoom;\n const c00 = k * Math.cos(rad), c01 = -k * Math.sin(rad);\n const c10 = k * Math.sin(rad), c11 = k * Math.cos(rad);\n const vx = cam.viewportX, vy = cam.viewportY;\n\n const m: Matrix2D = {\n a: c00 * view[0] + c01 * view[4] + vx * wx,\n c: c00 * view[1] + c01 * view[5] + vx * wy,\n e: c00 * view[3] + c01 * view[7] + vx * w0,\n b: c10 * view[0] + c11 * view[4] + vy * wx,\n d: c10 * view[1] + c11 * view[5] + vy * wy,\n f: c10 * view[3] + c11 * view[7] + vy * w0,\n };\n // A parallel projection stays affine, so it keeps the six-number fast paths.\n if (invP !== 0) {\n m.g = wx;\n m.h = wy;\n m.i = w0;\n }\n return m;\n}\n\n/** A node's box in view space: what sorting, culling and the backface test read. */\n/** @internal */\nexport interface SpacePlane {\n /** The four corners, `x, y, z` each, top-left clockwise. */\n corners: readonly number[];\n cx: number;\n cy: number;\n cz: number;\n /** Unit normal, pointing out of the node's front. */\n nx: number;\n ny: number;\n nz: number;\n}\n\n/**\n * `box` — the node's ink, centred and y-down in its local frame — through `view`.\n *\n * The normal is the transform's z column, which a mirror never touches: a flip\n * reflects the node without turning it around, so it cannot show its back.\n */\n/** @internal */\nexport function spacePlane(view: Affine3, box: { x: number; y: number; width: number; height: number }): SpacePlane {\n const hw = box.width / 2, hh = box.height / 2;\n const us = [box.x - hw, box.x + hw, box.x + hw, box.x - hw];\n const vs = [box.y - hh, box.y - hh, box.y + hh, box.y + hh];\n const corners = new Array<number>(12);\n for (let i = 0; i < 4; i++) {\n const u = us[i], v = vs[i];\n corners[i * 3] = view[0] * u + view[1] * v + view[3];\n corners[i * 3 + 1] = view[4] * u + view[5] * v + view[7];\n corners[i * 3 + 2] = view[8] * u + view[9] * v + view[11];\n }\n const nl = Math.hypot(view[2], view[6], view[10]) || 1;\n return {\n corners,\n cx: view[0] * box.x + view[1] * box.y + view[3],\n cy: view[4] * box.x + view[5] * box.y + view[7],\n cz: view[8] * box.x + view[9] * box.y + view[11],\n nx: view[2] / nl,\n ny: view[6] / nl,\n nz: view[10] / nl,\n };\n}\n\n/**\n * Below this `w` a point is at or behind the camera. Not zero: a point just in\n * front of the lens projects so far out that float32 path maths loses it,\n * and at 1/100 the layer is already magnified a hundredfold — well past the edge\n * of any frame.\n */\nconst NEAR_W = 0.01;\n\n/** Within this fraction of edge-on, a plane projects to a sliver narrower than a pixel. */\nconst EDGE_ON = 1e-3;\n\n/**\n * How `plane` sits relative to the camera: `side` is positive when the camera\n * is in front of it, `edgeOn` when the camera lies (almost) in its plane.\n */\n/** @internal */\nexport function cameraSide(cam: SpaceCamera, plane: SpacePlane): { side: number; edgeOn: boolean } {\n if (cam.perspective > 0) {\n const dx = -plane.cx, dy = -plane.cy, dz = cam.perspective - plane.cz;\n const side = plane.nx * dx + plane.ny * dy + plane.nz * dz;\n return { side, edgeOn: Math.abs(side) <= EDGE_ON * Math.hypot(dx, dy, dz) };\n }\n return { side: plane.nz, edgeOn: Math.abs(plane.nz) <= EDGE_ON };\n}\n\n/** How much of `plane` is in front of the camera. A parallel projection has no near plane. */\n/** @internal */\nexport function nearCoverage(cam: SpaceCamera, plane: SpacePlane): \"all\" | \"some\" | \"none\" {\n if (cam.perspective <= 0) return \"all\";\n let inFront = 0;\n for (let i = 0; i < 4; i++) {\n if (1 - plane.corners[i * 3 + 2] / cam.perspective > NEAR_W) inFront++;\n }\n return inFront === 4 ? \"all\" : inFront === 0 ? \"none\" : \"some\";\n}\n\n/**\n * The part of `box` (local, y-down) that lies in front of the camera under the\n * homography `screen`, as a polygon in the same frame — or `null` when none of\n * it does. `margin` grows the box first, so a shadow or stroke spilling past the\n * node's ink is not cut along its edge.\n */\n/** @internal */\nexport function nearCutPolygon(\n screen: Matrix2D,\n box: { x: number; y: number; width: number; height: number },\n margin: number,\n): Vector2[] | null {\n const g = screen.g ?? 0, h = screen.h ?? 0, i = screen.i ?? 1;\n const hw = box.width / 2 + margin, hh = box.height / 2 + margin;\n const square: Vector2[] = [\n { x: box.x - hw, y: box.y - hh },\n { x: box.x + hw, y: box.y - hh },\n { x: box.x + hw, y: box.y + hh },\n { x: box.x - hw, y: box.y + hh },\n ];\n const w = (p: Vector2) => g * p.x + h * p.y + i - NEAR_W;\n const out: Vector2[] = [];\n for (let k = 0; k < square.length; k++) {\n const a = square[k], b = square[(k + 1) % square.length];\n const wa = w(a), wb = w(b);\n if (wa >= 0) out.push(a);\n if ((wa >= 0) !== (wb >= 0)) {\n const t = wa / (wa - wb);\n out.push({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });\n }\n }\n return out.length >= 3 ? out : null;\n}\n\n/** Two points closer than this in view space (px) count as touching. */\nconst SIDE_EPS = 0.01;\n\n/**\n * Which side of `a`'s plane `b` lies on, as seen from the camera:\n * `1` in front (toward the camera), `-1` behind, `0` straddling it or lying in\n * it. `camSide` is `a`'s {@link cameraSide}.\n */\nfunction sideOf(a: SpacePlane, b: SpacePlane, camSide: number): number {\n let front = 0, back = 0;\n for (let i = 0; i < 4; i++) {\n const d = a.nx * (b.corners[i * 3] - a.cx) + a.ny * (b.corners[i * 3 + 1] - a.cy) + a.nz * (b.corners[i * 3 + 2] - a.cz);\n if (d > SIDE_EPS) front++;\n else if (d < -SIDE_EPS) back++;\n }\n if (front === 0 && back === 0) return 0;\n const facing = camSide > 0 ? 1 : -1;\n if (back === 0) return facing;\n if (front === 0) return -facing;\n return 0;\n}\n\n/** Squared distance from the camera: larger is farther. */\nfunction farness(cam: SpaceCamera, p: SpacePlane): number {\n if (cam.perspective > 0) return p.cx * p.cx + p.cy * p.cy + (cam.perspective - p.cz) ** 2;\n return -p.cz;\n}\n\n/**\n * `-1` when `a` must paint before `b`, `1` after, `0` when either order is right\n * — coplanar siblings, which keep their authored order.\n *\n * A plane test first, since it is exact for anything that does not intersect:\n * whichever node lies wholly on the camera's side of the other's plane is in\n * front. Parallel layers — the whole of a parallax stack — always resolve here,\n * and so do coplanar ones, as a tie. Only planes that cut through each other fall\n * back to the distance of their centres, and no painter's order is right for\n * those anyway.\n */\nfunction compareInSpace(cam: SpaceCamera, a: SpacePlane, b: SpacePlane): number {\n const ca = cameraSide(cam, a);\n if (!ca.edgeOn) {\n const s = sideOf(a, b, ca.side);\n if (s !== 0) return s > 0 ? -1 : 1;\n if (isCoplanar(a, b)) return 0;\n }\n const cb = cameraSide(cam, b);\n if (!cb.edgeOn) {\n const s = sideOf(b, a, cb.side);\n if (s !== 0) return s > 0 ? 1 : -1;\n }\n const fa = farness(cam, a), fb = farness(cam, b);\n return fa === fb ? 0 : fa > fb ? -1 : 1;\n}\n\nfunction isCoplanar(a: SpacePlane, b: SpacePlane): boolean {\n for (let i = 0; i < 4; i++) {\n const d = a.nx * (b.corners[i * 3] - a.cx) + a.ny * (b.corners[i * 3 + 1] - a.cy) + a.nz * (b.corners[i * 3 + 2] - a.cz);\n if (Math.abs(d) > SIDE_EPS) return false;\n }\n return true;\n}\n\n/** A stage's camera as its props state it — what a host reads off the root row. */\nexport interface SpaceCameraProps {\n perspective: number;\n orbit: number;\n elevation: number;\n dolly: number;\n lookAt: LookAt;\n zoom: number;\n heading: number;\n}\n\n/** A point in a space, y-up like every scene point, `z` toward the viewer. */\nexport interface SpacePoint {\n x: number;\n y: number;\n z: number;\n}\n\nfunction rootCamera(props: SpaceCameraProps): SpaceCamera {\n return { ...props, viewportX: 0, viewportY: 0 };\n}\n\n/**\n * The space's camera maths for a host drawing over the picture — a gizmo\n * aiming the camera, a guide marking where it looks — so it asks the renderer's\n * own arithmetic rather than keeping a copy that could drift from it. Points are\n * in viewport space: origin at the centre, y-up.\n */\nexport const space3dOps = {\n lerpLookAt,\n\n /** Where scene point `point` lands in the viewport through `camera`, or `null` behind the lens. */\n project(camera: SpaceCameraProps, point: LookAt): Vector2 | null {\n const cam = rootCamera(camera);\n const v = spaceViewMatrix(cam);\n const x = point.x, y = -point.y, z = point.z ?? 0;\n const vx = v[0] * x + v[1] * y + v[2] * z + v[3];\n const vy = v[4] * x + v[5] * y + v[6] * z + v[7];\n const vz = v[8] * x + v[9] * y + v[10] * z + v[11];\n const w = cam.perspective > 0 ? 1 - vz / cam.perspective : 1;\n if (w <= NEAR_W) return null;\n const rad = (-cam.heading * Math.PI) / 180;\n const px = (cam.zoom * vx) / w, py = (cam.zoom * vy) / w;\n return {\n x: Math.cos(rad) * px - Math.sin(rad) * py,\n y: -(Math.sin(rad) * px + Math.cos(rad) * py),\n };\n },\n\n /**\n * The displacement at the camera's focus — in the plane facing it through\n * `lookAt` — that moves the picture there by `vector`. The inverse of a pan:\n * a hand dragging the picture by `vector` moves `lookAt` by minus this.\n */\n focusVector(camera: SpaceCameraProps, vector: Vector2): SpacePoint {\n const cam = rootCamera(camera);\n const rad = (-cam.heading * Math.PI) / 180;\n const k = cam.zoom || 1;\n const cx = vector.x, cy = -vector.y;\n const px = (Math.cos(rad) * cx + Math.sin(rad) * cy) / k;\n const py = (-Math.sin(rad) * cx + Math.cos(rad) * cy) / k;\n // A focus pushed nearer by the dolly draws larger, so it moves less for the same drag.\n const w = cam.perspective > 0 ? 1 - cam.dolly / cam.perspective : 1;\n const v = spaceViewMatrix(cam);\n const ux = px * w, uy = py * w;\n // The view's first two rows are the camera's right and screen-down axes.\n return {\n x: ux * v[0] + uy * v[4],\n y: -(ux * v[1] + uy * v[5]),\n z: ux * v[2] + uy * v[6],\n };\n },\n};\n\n/** Past this many siblings the pairwise order costs more than it is worth, and the centres decide. */\nconst PAIRWISE_LIMIT = 96;\n\n/**\n * The order to paint siblings in, far to near, as indices into `planes`.\n *\n * Pairwise {@link compareInSpace} relations become edges, and a stable\n * topological sort that always takes the lowest ready index keeps `layerOrder`\n * wherever the geometry has no opinion. A cycle — three planes each overlapping\n * the next, which no painter's order can draw — is broken at its farthest node.\n */\n/** @internal */\nexport function spacePaintOrder(cam: SpaceCamera, planes: readonly SpacePlane[]): number[] {\n const n = planes.length;\n if (n > PAIRWISE_LIMIT) {\n return planes\n .map((_, i) => i)\n .sort((a, b) => farness(cam, planes[b]) - farness(cam, planes[a]) || a - b);\n }\n\n const after: number[][] = Array.from({ length: n }, () => []);\n const blockers = new Array<number>(n).fill(0);\n for (let i = 0; i < n; i++) {\n for (let j = i + 1; j < n; j++) {\n const r = compareInSpace(cam, planes[i], planes[j]);\n if (r < 0) { after[i].push(j); blockers[j]++; }\n else if (r > 0) { after[j].push(i); blockers[i]++; }\n }\n }\n\n const order: number[] = [];\n const done = new Array<boolean>(n).fill(false);\n while (order.length < n) {\n let next = -1;\n for (let i = 0; i < n; i++) {\n if (!done[i] && blockers[i] === 0) { next = i; break; }\n }\n if (next === -1) {\n let far = -Infinity;\n for (let i = 0; i < n; i++) {\n if (done[i]) continue;\n const f = farness(cam, planes[i]);\n if (f > far) { far = f; next = i; }\n }\n }\n done[next] = true;\n order.push(next);\n for (const j of after[next]) blockers[j]--;\n }\n return order;\n}\n", "import { lerpNumber } from \"@/tween/lerp\";\nimport type { AttributeOps } from \"@/attributes/shared/operators\";\n\n/** Width and height in pixels. */\nexport interface Size2D {\n width: number;\n height: number;\n}\n\n/**\n * The {@link Size2D} attribute's op set: `lerp` interpolates `width`/`height`\n * independently. `expand` fills the `size` shorthand into `width`/`height` on a\n * props-like object, in place. `size` is sugar for \"the same value on both\n * axes\"; explicit `width`/`height` take precedence over it (same precedence as\n * `insetsOps.resolve`'s side-vs-shorthand rule), so `{ size: 200, width: 100 }`\n * keeps `width: 100` and only fills in `height: 200`. No-op when `size` is\n * absent. The reactive-binding form (`size: () => SizeInput`) is supported —\n * both axes are bound to the same callback, re-evaluated independently per axis.\n */\nexport const size2DOps: AttributeOps<Size2D, Size2D> & { expand(props: Record<string, unknown>): void } = {\n resolve: (value) => value,\n lerp: (from, to, t) => ({ width: lerpNumber(from.width, to.width, t), height: lerpNumber(from.height, to.height, t) }),\n expand: (props) => {\n if (props.size === undefined) return;\n if (props.width === undefined) props.width = props.size;\n if (props.height === undefined) props.height = props.size;\n },\n};\n\n/**\n * Sizing behavior for a node dimension.\n * - `\"fill\"`: expand to fill available space from the parent\n * - `\"hug\"`: shrink to fit the node's own content\n */\n/** @internal */\nexport type SizeType = \"fill\" | \"hug\";\n\n/** A dimension can be specified as a behavior keyword or a fixed pixel value. */\n/** @internal */\nexport type SizeInput = SizeType | number;\n\n/**\n * The dimension-keyword `SizeInput` attribute's op set — `width`/`height`'s.\n * `lerp` interpolates two numbers; a keyword on either end hard-switches at t=1.\n * `resolveLayout` turns a `SizeInput` into a concrete number for layout, given\n * the space available and the size contents would need; `isAuto` reports\n * whether a dimension needs layout to resolve at all (a keyword) as opposed to\n * being a fixed number.\n */\nexport const sizeInputOps: AttributeOps<SizeInput, SizeInput> & {\n resolveLayout(input: SizeInput, availableSize: number, contentSize: number): number;\n isAuto(input: SizeInput): boolean;\n} = {\n resolve: (value) => value,\n lerp: (from, to, t) => {\n if (typeof from === \"number\" && typeof to === \"number\") {\n return lerpNumber(from, to, t);\n }\n return t === 1 ? to : from;\n },\n resolveLayout: (input, availableSize, contentSize) => {\n if (typeof input === \"number\") return input;\n if (input === \"fill\") return availableSize;\n if (input === \"hug\") return contentSize;\n return availableSize;\n },\n isAuto: (input) => typeof input !== \"number\",\n};\n", "/**\n * Every text operation, on one object.\n *\n * `textOps` was already the text attribute's `resolve`/`lerp` pair; it now also\n * carries what a `TextStyle` needs — the preset lookup, the merge every\n * text-default channel is built on, a whole style's resolve/lerp pair — and span\n * flattening, the shape `pathOps` has.\n *\n * The two cascades built on these are deliberately not here. A node's\n * (`applyTextDefaults`) lives beside `DefaultTextStyle` and a drawn op's\n * (`applyGraphicsTextDefaults`) beside `draw()`: each belongs to its channel, not\n * to the style.\n */\nimport type { AttributeOps } from \"@/attributes/shared/operators\";\nimport { fillOps } from \"@/attributes/shape/fill/registry\";\nimport type { FillResolved } from \"@/attributes/shape/fill/union\";\nimport { getTypographyPreset } from \"@/attributes/shape/fill/color/parser\";\nimport { strokeOps, type StrokeResolved } from \"@/attributes/shape/stroke/stroke\";\nimport { shadowOps, type ShadowResolved } from \"@/attributes/shape/shadow/shadow\";\nimport { lerpNumber } from \"@/tween/lerp\";\nimport type { ResolvedTextSpan, TextCase, TextShapingKey, TextSpan, TextStyle } from \"./types\";\n\n/** Every key a {@link TextStyle} can set. */\nexport const TEXT_STYLE_KEYS = [\n 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle',\n 'letterSpacing', 'lineHeight', 'textAlign', 'fill', 'stroke', 'shadow',\n] as const satisfies readonly (keyof TextStyle)[];\n\n/**\n * The keys a drawn `text`/`richText` op can inherit. `fill`/`stroke`/`shadow` are\n * absent because in a `Graphics2D` they are group-scoped ops, not per-shape\n * slots: defaulting one would change which shapes the group's paint covers.\n */\nexport const TEXT_SHAPING_KEYS = [\n 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle',\n 'letterSpacing', 'lineHeight', 'textAlign',\n] as const satisfies readonly TextShapingKey[];\n\n/** A style that sets nothing. Frozen and shared, so the empty case allocates nothing. */\nexport const EMPTY_TEXT_STYLE: TextStyle = Object.freeze({});\n\n\n/** The text attribute's operations beyond `resolve`/`lerp`. */\nexport interface TextOps {\n // ── Styles ─────────────────────────────────────────────────────────────\n /** A `theme.typography` preset (case-insensitive), or {@link EMPTY_TEXT_STYLE} when none is registered. */\n preset(name: string): TextStyle;\n /** The keys `over` sets, laid onto `base`. Returns `base` itself when `over` sets nothing. */\n mergeStyle(base: TextStyle, over: TextStyle | undefined): TextStyle;\n /** `style ?? previous` per field, paints resolved. Idempotent, like every mapper. */\n resolveStyle(style: TextStyle | undefined, previous: TextStyle): TextStyle;\n /**\n * Interpolate two font sizes. `'autofit'` is a mode, not a magnitude, so it\n * steps at the midpoint; two numbers interpolate. The rule {@link lerpStyle}\n * applies to its `fontSize`, for a node's own `fontSize` property to share.\n */\n lerpFontSize(a: number | \"autofit\" | undefined, b: number | \"autofit\" | undefined, t: number): number | \"autofit\" | undefined;\n /** Interpolate two resolved styles; categorical and one-sided fields step at the midpoint. */\n lerpStyle(from: TextStyle, to: TextStyle, t: number): TextStyle;\n /** A style as `Text` constructor props: unset keys dropped, the family falling back to the host's. */\n styleProps(style: TextStyle): Record<string, unknown>;\n\n // ── Spans ──────────────────────────────────────────────────────────────\n /** A span tree flattened against `base`: its text-bearing spans, in document order. */\n flatten(spans: readonly TextSpan[], base: Omit<ResolvedTextSpan, \"text\">): ResolvedTextSpan[];\n\n // ── Case ───────────────────────────────────────────────────────────────\n /**\n * `text` recased, **at its own length**: a character whose case mapping\n * would add characters (`ß` → `SS`) keeps its own form, because run offsets,\n * selections and caret slots all index the string as typed.\n */\n applyCase(text: string, textCase: TextCase): string;\n}\n\n\nexport const textOps: AttributeOps<string, string> & TextOps = {\n // A string needs no normalization.\n resolve: (value) => value,\n lerp,\n\n preset,\n mergeStyle,\n resolveStyle,\n lerpStyle,\n lerpFontSize,\n styleProps,\n\n flatten,\n\n applyCase,\n};\n\n\n/**\n * Types and untypes: the common prefix and suffix hold still while `from`'s\n * differing middle shrinks away and `to`'s grows in.\n */\nfunction lerp(from: string, to: string, t: number): string {\n if (t <= 0) return from;\n if (t >= 1) return to;\n\n let pre = 0;\n const maxPre = Math.min(from.length, to.length);\n while (pre < maxPre && from.charCodeAt(pre) === to.charCodeAt(pre)) pre++;\n\n let suf = 0;\n const maxSuf = Math.min(from.length - pre, to.length - pre);\n while (\n suf < maxSuf &&\n from.charCodeAt(from.length - 1 - suf) === to.charCodeAt(to.length - 1 - suf)\n ) suf++;\n\n const removeLen = from.length - pre - suf;\n const addLen = to.length - pre - suf;\n const totalLen = removeLen + addLen;\n if (totalLen === 0) return to;\n\n const prefix = from.substring(0, pre);\n const suffix = from.substring(from.length - suf);\n const split = removeLen / totalLen;\n\n if (t < split) {\n const localT = split === 0 ? 1 : t / split;\n const midLen = Math.round(removeLen * (1 - localT));\n return prefix + from.substring(pre, pre + midLen) + suffix;\n }\n const localT = split === 1 ? 1 : (t - split) / (1 - split);\n const midLen = Math.round(addLen * localT);\n return prefix + to.substring(pre, pre + midLen) + suffix;\n}\n\n// Read per call rather than cached, so a `setTheme` between frames needs no invalidation.\nfunction preset(name: string): TextStyle {\n return (getTypographyPreset(name) as TextStyle | undefined) ?? EMPTY_TEXT_STYLE;\n}\n\nfunction mergeStyle(base: TextStyle, over: TextStyle | undefined): TextStyle {\n let out: Record<string, unknown> | null = null;\n for (const key of TEXT_STYLE_KEYS) {\n const value = over?.[key];\n if (value !== undefined) (out ??= { ...base })[key] = value;\n }\n return (out as TextStyle | null) ?? base;\n}\n\nfunction resolveStyle(style: TextStyle | undefined, previous: TextStyle): TextStyle {\n const s = style ?? {};\n return {\n fontFamily: s.fontFamily ?? previous.fontFamily,\n fontSize: s.fontSize ?? previous.fontSize,\n fontWeight: s.fontWeight ?? previous.fontWeight,\n fontStyle: s.fontStyle ?? previous.fontStyle,\n letterSpacing: s.letterSpacing ?? previous.letterSpacing,\n lineHeight: s.lineHeight ?? previous.lineHeight,\n textAlign: s.textAlign ?? previous.textAlign,\n fill: fillOps.resolve(s.fill ?? previous.fill ?? []),\n stroke: strokeOps.resolve(s.stroke ?? previous.stroke ?? []),\n shadow: shadowOps.resolve(s.shadow ?? previous.shadow ?? []),\n };\n}\n\nfunction lerpStyle(from: TextStyle, to: TextStyle, t: number): TextStyle {\n return {\n fontFamily: t < 0.5 ? from.fontFamily : to.fontFamily,\n fontSize: lerpFontSize(from.fontSize, to.fontSize, t),\n fontWeight: lerpOptionalNumber(from.fontWeight, to.fontWeight, t),\n fontStyle: t < 0.5 ? from.fontStyle : to.fontStyle,\n letterSpacing: lerpOptionalNumber(from.letterSpacing, to.letterSpacing, t),\n lineHeight: lerpOptionalNumber(from.lineHeight, to.lineHeight, t),\n textAlign: t < 0.5 ? from.textAlign : to.textAlign,\n fill: fillOps.lerp(from.fill as FillResolved[], to.fill as FillResolved[], t),\n stroke: strokeOps.lerp(from.stroke as StrokeResolved[], to.stroke as StrokeResolved[], t),\n shadow: shadowOps.lerp(from.shadow as ShadowResolved[], to.shadow as ShadowResolved[], t),\n };\n}\n\n// Spread onto a node, an `undefined` key is stored as a value rather than read as\n// unset, so unset keys are dropped. The base is a fresh object per call because\n// `mergeStyle` returns it as-is when `style` sets nothing, and a frozen\n// `EMPTY_TEXT_STYLE` would then be handed out as props.\n//\n// `fontFamily` is dropped along with the rest rather than backfilled from\n// `hostTextFamily()`. Writing it here turned the *component's* own theme into an\n// author-set prop, and `applyTextDefaults` skips every key the props already\n// carry — so a chart axis reached the renderer holding the host family, or `\"\"`\n// when no host had declared one, and the document's `<DefaultTextStyle>` and\n// `theme.typography.default` never got a look in. Leaving it unset puts a\n// component's text on the same cascade as an author's, with the host family\n// where it belongs: last, in `requireFontFamily`.\nfunction styleProps(style: TextStyle): Record<string, unknown> {\n return mergeStyle({}, style) as Record<string, unknown>;\n}\n\nfunction flatten(spans: readonly TextSpan[], base: Omit<ResolvedTextSpan, \"text\">): ResolvedTextSpan[] {\n const out: ResolvedTextSpan[] = [];\n const walk = (span: TextSpan, inherited: Omit<ResolvedTextSpan, \"text\">): void => {\n const merged = {\n fontFamily: span.fontFamily ?? inherited.fontFamily,\n fontSize: span.fontSize ?? inherited.fontSize,\n fontWeight: span.fontWeight ?? inherited.fontWeight,\n fontStyle: span.fontStyle ?? inherited.fontStyle,\n letterSpacing: span.letterSpacing ?? inherited.letterSpacing,\n fill: span.fill != null ? fillOps.resolve(span.fill) : inherited.fill,\n stroke: span.stroke != null ? strokeOps.resolve(span.stroke) : inherited.stroke,\n };\n if (span.text) out.push({ text: span.text, ...merged });\n for (const child of span.children ?? []) walk(child, merged);\n };\n for (const span of spans) walk(span, base);\n return out;\n}\n\n// A letter, digit or apostrophe continues a word, so `don't` and `3rd` keep\n// their second halves as typed while `well-known` becomes `Well-Known`.\nconst WORD_CHAR = /[\\p{L}\\p{N}'\\u2019]/u;\n\nfunction applyCase(text: string, textCase: TextCase): string {\n if (textCase !== 'upper' && textCase !== 'lower' && textCase !== 'title') return text;\n let out = \"\";\n let prev = \"\";\n for (const ch of text) {\n const recase = textCase === 'upper' || (textCase === 'title' && !WORD_CHAR.test(prev));\n const mapped = textCase === 'lower' ? ch.toLowerCase() : recase ? ch.toUpperCase() : ch;\n out += mapped.length === ch.length ? mapped : ch;\n prev = ch;\n }\n return out;\n}\n\n// `\"autofit\"` is a mode, not a magnitude.\nfunction lerpFontSize(\n a: number | \"autofit\" | undefined,\n b: number | \"autofit\" | undefined,\n t: number,\n): number | \"autofit\" | undefined {\n if (typeof a === \"number\" && typeof b === \"number\") return lerpNumber(a, b, t);\n return t < 0.5 ? a : b;\n}\n\n// Defaulting the missing side to 0 would animate a weight down to nothing on its way to \"unset\".\nfunction lerpOptionalNumber(a: number | undefined, b: number | undefined, t: number): number | undefined {\n if (a == null || b == null) return t < 0.5 ? a : b;\n return lerpNumber(a, b, t);\n}\n", "import { TweenFn } from \"@/props/host\";\n\nexport interface PropOptions<Ext, Int> {\n /** Lerp the *internal* (post-mapper) value during `to()`. Each step is stored as it returns, not mapped again, so a prop that must hold a range under an overshooting ease clamps here too. */\n tween?: TweenFn<Int>;\n /** Converts the external input into the internal stored value. Receives the previous internal value as the second arg when available. */\n mapper?: (ext: Ext, prev?: Int) => Int;\n}\n\n\nexport interface PropertyMeta {\n key: string;\n default?: unknown;\n options?: PropOptions<any, any>;\n /** How a host edits this prop — see {@link PropertyEditor}. */\n editor?: PropertyEditor;\n /** @deprecated Nothing sets it: the engine withdraws no property. Kept so a host that tests it still compiles. */\n withdrawn?: boolean;\n}\n\n/**\n * What a host needs to draw a control for a property.\n *\n * Declared **on the property**, because that is the thing it edits. A node type\n * used to describe its controls in a separate list — a `fields` array beside the\n * class, or a manifest beside the package — and a list of props next to a class\n * of props is the shape that drifts: rename one and nothing says the other is\n * now describing something that no longer exists.\n *\n * Nothing here is read while rendering. A frame is identical whether a prop\n * declares a range or not; this exists so an editor has one place to ask.\n */\nexport interface PropertyEditor {\n /**\n * The control to draw. Inferred when absent — a typed entry knows its\n * own (`Types.color` is a colour), and a plain `property` reads it off\n * the default's type.\n */\n kind?: string;\n /** Bounds and granularity for a numeric control. */\n min?: number;\n max?: number;\n step?: number;\n /** What the number means, for a host that labels it — `\"°\"`, `\"s\"`, `\"×\"`. */\n unit?: string;\n /** The choices, for an enum. */\n options?: readonly string[];\n /** Whether a document may tween it. Defaults to true. */\n animatable?: boolean;\n /**\n * The controls *inside* an object-valued prop.\n *\n * An axis config or a theme is one property holding several editable values,\n * and a host draws them as a group. Declaring them here keeps them attached\n * to the prop they belong to rather than flattened into a list that has to\n * name its own parent.\n */\n properties?: Record<string, PropertyEditor>;\n /** Whatever a control needs that this vocabulary does not name. */\n [option: string]: unknown;\n}\n\n/** Symbol used to store property metadata on class prototypes. */\nexport const PROPERTY_META = Symbol(\"propertyMeta\");\n\n/**\n * Every `property` on an instance's class, inherited included, ordered base →\n * subclass so `initProps` applies them in declaration order. A subclass that\n * redeclares a key replaces the inherited declaration whole — default, mapper,\n * tween and editor — at the position the base gave it.\n */\nexport function getPropertyMeta(instance: object): PropertyMeta[] {\n return mostDerived<PropertyMeta>(instance, PROPERTY_META);\n}\n\n/**\n * The per-key declarations stored under `symbol` along `instance`'s prototype\n * chain: base first, one entry per key, the most-derived declaration of each.\n */\nexport function mostDerived<M extends { key: string }>(instance: object, symbol: symbol): M[] {\n const chain: object[] = [];\n let proto = Object.getPrototypeOf(instance);\n while (proto && proto !== Object.prototype) {\n chain.unshift(proto);\n proto = Object.getPrototypeOf(proto);\n }\n const result: M[] = [];\n const at = new Map<string, number>();\n for (const p of chain) {\n if (!Object.prototype.hasOwnProperty.call(p, symbol)) continue;\n for (const m of (p as Record<symbol, M[]>)[symbol]) {\n const i = at.get(m.key);\n if (i === undefined) {\n at.set(m.key, result.length);\n result.push(m);\n } else {\n result[i] = m;\n }\n }\n }\n return result;\n}\n\n/**\n * A registration for one member of a node class: what `property(...)` and\n * `command(...)` return, applied to the class's prototype under the member's\n * key by {@link declareMembers}.\n */\nexport type MemberRegistration = (target: object, key: string) => void;\n\n/**\n * Registers properties and commands on a node class, in the order given.\n *\n * Core's own base classes (`Node`, `Node2D`, `Node3D`, …) declare their props\n * as `declare` fields and register them here, right after the class body.\n * Order is meaningful: {@link getPropertyMeta} lists properties in\n * registration order, which is the order `Registry.describe` hands a host's\n * inspector, so a new entry goes where it should appear.\n *\n * @example\n * ```ts\n * class Dial extends Node2D<DialProps> {\n * declare level: number;\n * turn(args: CommandArgs<{ by: number }>) { … }\n * }\n * declareMembers(Dial, {\n * level: property({ default: 0 }),\n * turn: command({ args: [\"by\"] }),\n * });\n * ```\n *\n * Node types outside core are components (`component2d`), which do this for\n * their `props` and `commands` themselves.\n */\nexport function declareMembers<C extends abstract new (...args: never[]) => object>(\n ctor: C,\n members: { [K in keyof InstanceType<C> & string]?: MemberRegistration },\n): void {\n for (const [key, register] of Object.entries(members) as [string, MemberRegistration][]) {\n register(ctor.prototype as object, key);\n }\n}\n\n/**\n * Declares a property on a `Node` subclass: applied to the prototype under the\n * property's key, directly or through {@link declareMembers}. Redeclaring an\n * inherited key overrides it; see {@link getPropertyMeta}.\n *\n * @example\n * ```ts\n * declareMembers(Glow, {\n * radius: property({ default: 0 }),\n * fill: property({ mapper: fillOps.resolve, tween: fillOps.lerp }),\n * });\n * ```\n *\n * The `default` value is used when the corresponding key is absent from the\n * constructor `props` object. The `mapper` / `tween` options are forwarded\n * directly to `applyProp()`.\n */\nexport function property<Ext = any, Int = Ext>(opts?: {\n default?: Ext;\n mapper?: (ext: Ext, prev?: Int) => Int;\n tween?: TweenFn<Int>;\n} & PropertyEditor) {\n return function (target: object, propertyKey: string | symbol): void {\n const key = propertyKey as string;\n // `default`, `mapper` and `tween` drive the prop slot; everything else is\n // the editor's, and is carried rather than interpreted.\n const { default: fallback, mapper, tween, ...editor } = opts ?? {};\n const meta: PropertyMeta = {\n key,\n default: fallback,\n options: (mapper != null || tween != null)\n ? { mapper: mapper as ((ext: any) => any) | undefined, tween: tween as TweenFn<any> | undefined }\n : undefined,\n ...(Object.keys(editor).length > 0 ? { editor: editor as PropertyEditor } : {}),\n };\n\n // Store metadata on the class prototype (own property so getPropertyMeta\n // can distinguish each class's own entries from inherited ones).\n if (!Object.prototype.hasOwnProperty.call(target, PROPERTY_META)) {\n (target as any)[PROPERTY_META] = [];\n }\n const list: PropertyMeta[] = (target as any)[PROPERTY_META];\n if (!list.some(m => m.key === key)) {\n list.push(meta);\n }\n };\n}\n", "import type { SlotObserver } from \"./observer\";\n\n/**\n * A captured state of a {@link PropSlot}: the thunk it was bound to, or the\n * plain value it held. Produced by {@link PropSlot.snapshot} and consumed by\n * {@link PropSlot.restoreFrom}.\n */\n/** @internal */\nexport interface PropSnapshot<T> {\n value: T;\n /** Present only for a bound slot; restoring one re-binds rather than freezing it. */\n fn?: () => T;\n}\n\n/**\n * @internal The observer every slot reports to, or `null` — which is every frame of\n * playback, so the hot path pays one null check. Installed by `observeSlots`.\n */\nexport let _observer: SlotObserver | null = null;\n\n/** @internal Only this module can reassign the binding. Returns the observer it replaced. */\nexport function _setObserver(observer: SlotObserver | null): SlotObserver | null {\n const previous = _observer;\n _observer = observer;\n return previous;\n}\n\n/**\n * The storage behind one `property`: a plain value, or a thunk evaluated on\n * every read.\n *\n * There is no dependency graph and nothing to invalidate. A bound slot\n * recomputes when it is asked, which is what makes a document expression\n * (`\"=4[g]+3\"`), an author's `width={() => …}` and an alignment binding reading\n * a box written mid-layout all correct without anything declaring an edge. The\n * cache-and-invalidate version of this could only get the last one right by\n * observing the write, and paid for it everywhere: a `peek()`/`get()` split at\n * every write path, so a read taken inside whatever computation happened to be\n * running did not register an edge with no business existing.\n *\n * The bet is that recomputing is cheaper than tracking. Bindings here are\n * arithmetic over a handful of reads, and a frame's draw dwarfs all of them.\n */\nexport class PropSlot<T> {\n private _value: T;\n private _fn: (() => T) | null = null;\n private _running = false;\n\n /** `_host` and `_name` only label the slot for an observer — see `slotLabel`. */\n constructor(\n initial: T,\n readonly _host: { readonly id: string } | null = null,\n readonly _name: string = \"\",\n ) {\n this._value = initial;\n }\n\n get(): T {\n // Before the re-entrancy check, so a binding's own reads are recorded\n // under whatever read it.\n if (_observer !== null) _observer.read(this);\n // A binding that reads its own slot re-enters here mid-evaluation —\n // `bind(() => mapper(ext(), slot.get()))` is how a mapper is handed the\n // previous value. It gets the last settled one instead of recursing.\n if (!this._fn || this._running) return this._value;\n this._running = true;\n try {\n return (this._value = this._fn());\n } finally {\n this._running = false;\n }\n }\n\n set(value: T): void {\n if (_observer !== null) _observer.write(this);\n this._fn = null;\n this._value = value;\n }\n\n bind(fn: () => T): void {\n if (_observer !== null) _observer.write(this);\n this._fn = fn;\n }\n\n /** Freeze a bound slot at what it currently computes. */\n unbind(): void {\n if (!this._fn) return;\n if (_observer !== null) _observer.write(this);\n this._value = this.get();\n this._fn = null;\n }\n\n isBound(): boolean {\n return this._fn !== null;\n }\n\n snapshot(): PropSnapshot<T> {\n return this._fn ? { value: this.get(), fn: this._fn } : { value: this._value };\n }\n\n restoreFrom(snap: PropSnapshot<T>): void {\n if (snap.fn) this.bind(snap.fn);\n else this.set(snap.value);\n }\n\n /** Releases the bound closure and the value slot. The slot is inert after this. */\n dispose(): void {\n this._fn = null;\n this._value = undefined as unknown as T;\n }\n}\n", "import { clamp01 } from \"@/util/clamp\";\nimport { EasingFunction } from \"@/tween/ease/type\";\nimport { Steppable, TweenStepper } from \"@/tween/stepper\";\nimport { Command } from \"./command\";\n\n/**\n * Interface a node (or other host) implements to be driven by {@link toCommand}.\n *\n * `_prepareStep` resolves one tween into a flat, mutation-driving\n * {@link TweenStepper} — the same primitive both the flat `parallel` fast path\n * and the command's own evaluation are built from.\n */\nexport interface AnimationTarget<P> {\n _prepareStep(props: Partial<P>, duration: number, easing?: EasingFunction): TweenStepper;\n}\n\n/**\n * The {@link Command} `node.to(...)` returns: one tween on one target, and\n * nothing else.\n *\n * **Single, not chainable.** `to()` used to return a builder whose own `to()`\n * appended another step and returned `this`, so `node.to(a, 1).to(b, 1)` read as\n * a sequence. Sequencing is now a property of the timeline — a command carries\n * its own `at`, so \"after this one\" is `at + duration` — and one command shape\n * means a host reading a `Command` off a node knows exactly what it holds.\n *\n * Implements {@link Command} (a host can ask what it looks like at a time) and\n * {@link Steppable} (the flat driver).\n *\n * `at` and `_stepper` each keep their **own** prepared stepper: preparing is\n * what snapshots the tween's `from` (it reads the live target), so two drivers\n * must never fight over one mutable stepper.\n */\nclass ToCommand<P> implements Command<P>, Steppable {\n private atPrepared: TweenStepper | null = null;\n\n constructor(\n private readonly target: AnimationTarget<P>,\n private readonly props: Partial<P>,\n readonly duration: number,\n private readonly easing?: EasingFunction,\n ) { }\n\n /**\n * The props this command writes at normalized `t`. Applied as a side effect\n * (direct cell writes through the prepared stepper, exactly like\n * `driveCommand`) rather than returned — a tween may carry a custom tween\n * function or a mapped prop, and only the target's own `_prepareStep` knows\n * how to apply those correctly.\n */\n at(t: number): Partial<P> {\n if (!this.atPrepared) this.atPrepared = this.prepare();\n this.atPrepared.seek(clamp01(t) * this.duration);\n return {};\n }\n\n _stepper(): TweenStepper {\n return this.prepare();\n }\n\n private prepare(): TweenStepper {\n return this.target._prepareStep(this.props, this.duration, this.easing);\n }\n}\n\n/** Build the {@link Command} `node.to(...)` returns. */\nexport function toCommand<P>(\n target: AnimationTarget<P>,\n props: Partial<P>,\n duration: number,\n easing?: EasingFunction,\n): Command<P> {\n return new ToCommand<P>(target, props, duration, easing);\n}\n", "/**\n * Repetition, as data: how many times a command runs and which way each pass\n * goes.\n *\n * A loop is a **placement** property, the same kind of thing as `at` and\n * `duration` — it says when the command is running, never what it does. That is\n * why it lives out here rather than in any one command's args: the wrapper goes\n * *around* a built `Command`, so `to`, `fillTo`, `countTo` and a custom\n * `command()` nobody has written yet all loop by the same code, with nothing to\n * forward and nothing to forget.\n *\n * And it stays seekable. A looped command is still a pure function of its own\n * normalized time — `at(t)` maps `t` onto a pass and asks the inner command for\n * that pass's frame — so scrubbing into the fourth repetition costs the same as\n * scrubbing into the first, which is the whole reason commands are values here.\n */\n\nimport { clamp01 } from \"@/util/clamp\";\n\n/**\n * Which way a pass runs.\n *\n * `alternate` is the reason this is three values rather than a boolean: a\n * bounce — out and back — is one command with two passes, not two commands whose\n * `at`s have to be kept in step by hand.\n */\nexport type LoopDirection = \"normal\" | \"reverse\" | \"alternate\";\n\n/**\n * How a command repeats. Absent on a command is \"runs once\".\n */\nexport interface LoopSpec {\n /** Absent is `\"normal\"`. */\n direction?: LoopDirection;\n /**\n * How many times to repeat **after** the first pass: `0` is no repeat (the\n * same as no loop at all), `3` plays four passes, and `null` repeats for as\n * long as there is clip left to fill.\n *\n * Repeats rather than total passes so that the value reads as what the word\n * says — \"repeat twice\" is `2` — and so that the no-op is `0` rather than a\n * `1` that looks like it should do something.\n */\n count: number | null;\n}\n\n/** Total passes: repeats plus the first one, or `Infinity` for an unlimited loop. */\nexport function loopPasses(loop: LoopSpec): number {\n return loop.count === null ? Infinity : Math.max(0, Math.floor(loop.count)) + 1;\n}\n\n/** Whether a loop changes anything: an unlimited one always does, a counted one only past zero. */\nexport function loopRepeats(loop: LoopSpec | undefined): loop is LoopSpec {\n return loop !== undefined && (loop.count === null || loop.count >= 1);\n}\n\n/**\n * Seconds a looped command occupies.\n *\n * `fill` is what an unlimited loop is given to cover — the clip's remaining time,\n * where a timeline places one. An unlimited loop does not *define* a length the\n * way a counted one does: a background that turns forever should fill the scene\n * it is in, not stretch it, so `documentDuration` counts one pass of it and this\n * stretches it to whatever that came to.\n */\nexport function loopSpan(loop: LoopSpec, duration: number, fill = duration): number {\n if (duration <= 0) return duration;\n if (loop.count === null) return Math.max(duration, fill);\n return duration * loopPasses(loop);\n}\n\n/**\n * Where in one pass `elapsed` lands, as normalized time for the inner command.\n *\n * Past the last pass of a counted loop it holds at that pass's end rather than\n * wrapping to the start — the same rule a finished command follows everywhere\n * else, and what keeps the value a loop leaves behind the value the next command\n * tweens from.\n */\nexport function loopPhase(loop: LoopSpec, elapsed: number, duration: number): number {\n if (duration <= 0) return 1;\n const passes = loopPasses(loop);\n const capped = Math.min(Math.max(elapsed, 0) / duration, passes);\n // `passes - 1` holds the final pass at its end instead of rolling over to a\n // pass that does not exist. `Infinity - 1` is still `Infinity`, so an\n // unlimited loop is never capped.\n const index = Math.min(Math.floor(capped), passes - 1);\n const t = clamp01(capped - index);\n switch (loop.direction ?? \"normal\") {\n case \"reverse\": return 1 - t;\n case \"alternate\": return index % 2 === 0 ? t : 1 - t;\n default: return t;\n }\n}\n", "import { clamp01 } from \"@/util/clamp\";\nimport { EasingFunction } from \"./ease/type\";\nimport { loopPasses, loopPhase, loopSpan, type LoopSpec } from \"./loop\";\nimport { LerpFunction } from \"./lerp\";\nimport { Steppable, TweenStepper } from \"./stepper\";\n\n/**\n * A named animation, as a value: `at(t)` is a pure function of normalized time,\n * so a host can ask what frame N looks like without replaying frames 0..N-1.\n *\n * `at` is only pure once *built* — a factory reads the node's current props to\n * fix its start value, so a host evaluating out of order must build commands in\n * timeline order, leaving each node in the state the previous command left it.\n */\nexport interface Command<P = Record<string, unknown>> extends Steppable {\n readonly duration: number;\n at(t: number): Partial<P>;\n}\n\n/**\n * The single argument a `command()` method takes: its own params under `data`,\n * plus shared timing. One object (not positional args) so a manifest can read a\n * command's shape off `T` directly.\n *\n * `duration`/`data` are optional for a command with a synchronous mode\n * (`restore`, `addChildAt`) or nothing to carry (`restore`).\n *\n * `R` differs from `T` when `data` is loose author input (`Fill`) but `lerp`\n * operates on its resolved form (`FillResolved[]`).\n */\nexport interface CommandArgs<T = Record<string, unknown>, R = T> {\n data?: T;\n duration?: number;\n easing?: EasingFunction;\n lerp?: LerpFunction<R>;\n}\n\nconst SETTLES = Symbol(\"settles\");\n\n/**\n * Mark a command whose `at` reads nothing but what it captured when it was built\n * and does nothing but write prop slots, its end values all at `at(1)`. A\n * timeline may then hold it finished by writing those end values instead of\n * running it — see `document/settled-index`.\n */\nexport function settling<C extends { at(t: number): unknown }>(command: C): C {\n (command as unknown as Record<symbol, boolean>)[SETTLES] = true;\n return command;\n}\n\nexport function settles(command: { at(t: number): unknown }): boolean {\n return (command as unknown as Record<symbol, boolean>)[SETTLES] === true;\n}\n\n/** True when `x` is a {@link Command} rather than a plain object. */\nexport function isCommand(x: unknown): x is Command {\n return typeof (x as Command)?.at === \"function\"\n && typeof (x as Command)?.duration === \"number\";\n}\n\n/** What a {@link Command} writes its evaluated props onto. */\nexport interface CommandTarget<P> {\n set(props: Partial<P>): void;\n}\n\n/** Build a {@link Command} from a pure `t → props` function. `easing` is applied inside, so `at` itself takes raw normalized time. */\nexport function makeCommand<P>(\n target: CommandTarget<P>,\n at: (t: number) => Partial<P>,\n duration: number,\n easing?: EasingFunction,\n): Command<P> {\n const value = (t: number): Partial<P> => at(easing ? easing(clamp01(t)) : clamp01(t));\n return fromValue(target, duration, value);\n}\n\n/**\n * A {@link Command} whose product is a side effect rather than props — for state\n * a `set()` can't reach (a private field, an array element).\n *\n * `apply` must be a pure function of `t`: it can run for any `t`, any number of\n * times, in any order. Accumulating (`x += …`) instead of assigning from `t`\n * looks right forwards and drifts the instant anything scrubs.\n */\nexport function driveCommand(\n duration: number,\n apply: (t: number) => void,\n easing?: EasingFunction,\n): Command<Record<string, never>> {\n const sink: CommandTarget<Record<string, never>> = { set: () => { } };\n return makeCommand(sink, (t) => {\n apply(t);\n return {};\n }, duration, easing);\n}\n\n/**\n * Repeat `command`, as one seekable {@link Command} that lasts for every pass.\n *\n * Wrapping rather than a parameter on each command is what makes this work for\n * every command there is: the inner one is asked for the frame at a pass-local\n * `t`, so it never learns it is being repeated, and its easing applies per pass\n * — which is what \"three bounces\" means, rather than one ease stretched over\n * three of them.\n *\n * `fill` is the seconds an unlimited loop (`count: null`) may cover; it defaults\n * to a single pass, since a command built outside a timeline has no clip to fill.\n * A stamp (`duration === 0`) is returned untouched: there is no pass to repeat.\n */\nexport function loopCommand<P>(command: Command<P>, loop: LoopSpec, fill?: number): Command<P> {\n const one = command.duration;\n if (one <= 0 || loopPasses(loop) <= 1) return command;\n const duration = loopSpan(loop, one, fill);\n const value = (t: number): Partial<P> => command.at(loopPhase(loop, clamp01(t) * duration, one));\n\n return {\n duration,\n at: value,\n _stepper(): TweenStepper {\n let elapsed = 0;\n return {\n seek: (e: number) => {\n elapsed = e;\n value(e / duration);\n },\n advance: (dt: number): boolean => {\n elapsed += dt;\n const done = elapsed >= duration;\n value(done ? 1 : elapsed / duration);\n return done;\n },\n };\n },\n };\n}\n\n/**\n * Run `commands` one after another as a single seekable {@link Command}.\n *\n * A finished child holds at `at(1)` rather than being dropped, so a prop\n * written early keeps its value once its step ends.\n */\nexport function commandSequence<P>(\n target: CommandTarget<P>,\n ...commands: Command<P>[]\n): Command<P> {\n const duration = commands.reduce((sum, c) => sum + c.duration, 0);\n\n return fromValue(target, duration, (t) => {\n const elapsed = t * duration;\n const props: Partial<P> = {};\n let cursor = 0;\n for (const command of commands) {\n if (elapsed < cursor) break;\n const local = command.duration > 0 ? (elapsed - cursor) / command.duration : 1;\n Object.assign(props, command.at(clamp01(local)));\n cursor += command.duration;\n }\n return props;\n });\n}\n\n/** Run `commands` together as one {@link Command}, ending when the longest does. Later commands win on a shared prop. */\nexport function commandParallel<P>(\n target: CommandTarget<P>,\n ...commands: Command<P>[]\n): Command<P> {\n const duration = commands.reduce((max, c) => Math.max(max, c.duration), 0);\n\n return fromValue(target, duration, (t) => {\n const elapsed = t * duration;\n const props: Partial<P> = {};\n for (const command of commands) {\n const local = command.duration > 0 ? elapsed / command.duration : 1;\n Object.assign(props, command.at(clamp01(local)));\n }\n return props;\n });\n}\n\n/** Wrap a pure `t → props` function into the full {@link Command} surface. */\nfunction fromValue<P>(\n target: CommandTarget<P>,\n duration: number,\n value: (t: number) => Partial<P>,\n): Command<P> {\n const progress = (elapsed: number): number => (duration > 0 ? elapsed / duration : 1);\n\n return {\n duration,\n // Writes as well as returns. A host evaluating a timeline calls `at(t)`\n // and discards what comes back — `ToCommand` has always applied its step\n // as a side effect, and a `Command` built from a `t → props` function\n // that only *described* its frame was silently inert everywhere a\n // document is seeked, while behaving correctly under `_stepper`.\n at(t: number): Partial<P> {\n const props = value(t);\n target.set(props);\n return props;\n },\n\n _stepper(): TweenStepper {\n let elapsed = 0;\n return {\n seek: (e: number) => {\n elapsed = e;\n target.set(value(progress(e)));\n },\n advance: (dt: number): boolean => {\n elapsed += dt;\n const done = elapsed >= duration;\n target.set(value(done ? 1 : progress(elapsed)));\n return done;\n },\n };\n },\n };\n}\n", "import type { PropSlot } from \"@/props/slot\";\n\n/**\n * Snapshots the current numeric property values on `target` for the keys\n * present in `to`, then returns a lerp callback that writes interpolated values\n * back each frame.\n *\n * The snapshot is taken at call time, so invoke this immediately before the\n * animation starts (not lazily) to capture the correct `from` state.\n *\n * @param target - The object whose properties will be animated.\n * @param to - Desired end values keyed by property name. Keys with\n * `undefined` values are ignored.\n * @returns A function `(t: number) => void` that writes `lerp(from, to, t)`\n * for each key. `t` must already be eased by the caller.\n */\n/** @internal */\nexport function prepareNumericTween<T extends object>(\n target: T,\n to: Partial<Record<keyof T, number>>,\n): (t: number) => void {\n const keys = (Object.keys(to) as (keyof T)[]).filter((k) => to[k] !== undefined);\n const from = new Array<number>(keys.length);\n const end = new Array<number>(keys.length);\n for (let i = 0; i < keys.length; i++) {\n from[i] = (target as any)[keys[i]] as number;\n end[i] = to[keys[i]] as number;\n }\n return (t: number) => {\n for (let i = 0; i < keys.length; i++) {\n (target as any)[keys[i]] = from[i] + (end[i] - from[i]) * t;\n }\n };\n}\n\n/**\n * Like {@link prepareNumericTween}, but bypasses property setters and writes\n * directly to the backing {@link PropSlot}s.\n *\n * Skipping the setter avoids the mapper-lookup and `_writeProp` indirection on\n * every frame step. Only valid for numeric properties whose `end` is already in\n * stored space — the caller is responsible for resolving the slots, mapping the\n * destination and capturing the `from`/`end` values before calling this.\n *\n * - `cells[i]` — the slot for the i-th animated property.\n * - `from[i]` — start value for that property.\n * - `end[i]` — end value for that property.\n *\n * The arrays are captured by the returned closure and reused each step, so the\n * per-frame cost is one `slot.set(number)` per property with no allocation.\n */\n/** @internal */\nexport function prepareNumericCellTween(\n cells: PropSlot<number>[],\n from: number[],\n end: number[],\n): (t: number) => void {\n return (t: number) => {\n for (let i = 0; i < cells.length; i++) {\n cells[i].set(from[i] + (end[i] - from[i]) * t);\n }\n };\n}\n", "/**\n * Typed context tokens for passing inherited data down the node tree —\n * analogous to React's `createContext` / `useContext`, but resolved over the\n * scene-node tree rather than a render tree.\n *\n * A {@link Context} is an opaque token carrying a phantom type `T` and a\n * default value. Providers attach a value for a token to the {@link ContextMap}\n * pushed to their descendants; a descendant reads the nearest ancestor's value\n * (or the token's default) via `node.useContext(token)`.\n *\n * Mirrors the {@link createRef} factory style: a small typed helper rather than\n * a class the author has to instantiate.\n */\nexport interface Context<T> {\n /** Identity used as the map key. Unique per `createContext` call. */\n readonly id: symbol;\n /** Value returned by `useContext` when no ancestor provides this token. */\n readonly defaultValue: T;\n /** Optional label, surfaced on the symbol for debugging. */\n readonly name?: string;\n}\n\n/**\n * Create a typed context token.\n *\n * @example\n * ```ts\n * const Money = createContext<number>(0, \"money\");\n * // provide: <Provider context={Money} value={500}>…</Provider>\n * // consume: init() { const m = this.useContext(Money); } // m: number\n * ```\n */\nexport function createContext<T>(defaultValue: T, name?: string): Context<T> {\n return { id: Symbol(name ?? \"context\"), defaultValue, name };\n}\n\n/**\n * An immutable, layered token→value map carried down the node tree. Each\n * provider derives a child map from its parent's via {@link with}, overriding a\n * single token — so a deeper provider naturally shadows a shallower one\n * (nearest-ancestor-wins) without any stack bookkeeping.\n */\nexport class ContextMap {\n private constructor(private readonly entries: ReadonlyMap<symbol, unknown>) { }\n\n /** The empty map — every token resolves to its own default. */\n static readonly EMPTY = new ContextMap(new Map());\n\n /** Return a new map identical to this one but with `ctx` set to `value`. */\n with<T>(ctx: Context<T>, value: T): ContextMap {\n const next = new Map(this.entries);\n next.set(ctx.id, value);\n return new ContextMap(next);\n }\n\n /** Resolve `ctx`'s value, falling back to its default when unset. */\n get<T>(ctx: Context<T>): T {\n return this.entries.has(ctx.id) ? (this.entries.get(ctx.id) as T) : ctx.defaultValue;\n }\n}\n", "import { PropSlot } from \"./slot\";\n\n/** @internal */\nexport type TweenFn<T> = (from: T, to: T, t: number) => T;\n\n/**\n * The slots behind an object's `property`-declared fields, plus the per-field\n * metadata `set()` and `to()` route through.\n *\n * One object rather than three loose maps on the host, because the host is a\n * `Node` and every public field it carries is published API. Grouping them\n * means a node exposes one internal name instead of three, and gives the thing\n * a name a reader can look up.\n *\n * @internal\n */\nexport interface PropCells {\n /** Field → its live slot. Present for every registered prop. */\n slots: Map<string, PropSlot<any>>;\n /** Field → how it interpolates, for props a numeric lerp cannot cover. */\n tweens?: Map<string, TweenFn<any>>;\n /** Field → external prop value to internal slot value, for fields that need it. */\n mappers?: Map<string, (ext: any, prev?: any) => any>;\n}\n\n/** @internal */\nexport interface PropHost {\n /** See {@link PropCells}. Absent until the first prop is registered, and\n * cleared by `dispose()`. */\n __cells?: PropCells;\n}\n\n/** @internal */\nexport function getPropSlot(obj: PropHost, name: string): PropSlot<any> | undefined {\n return obj.__cells?.slots.get(name);\n}\n\n/** The host's slots, created on first use. @internal */\nexport function ensureCells(obj: PropHost): PropCells {\n return obj.__cells ??= { slots: new Map() };\n}\n", "import { mostDerived, type PropertyEditor } from \"@/attributes/properties/decorator\";\n\n/**\n * Marks a method as a command: a named, parameterised animation a host can\n * offer, place on a timeline and store by name. Metadata only.\n *\n * ```ts\n * class Chart extends Node2D<ChartProps> {\n * showSeries({ data, duration = 1, easing }: CommandArgs<{ index: number }>): Command<ChartProps> { … }\n * }\n * declareMembers(Chart, { showSeries: command({ args: [\"index\"] }) });\n * ```\n *\n * `args` maps a stored command's `params` object onto `data`'s keys — see\n * {@link CommandMeta.args}. Every command takes one {@link CommandArgs}\n * argument rather than positional params, so a manifest can read its shape\n * off `T` directly.\n */\n\n/** One argument a command takes, in the same vocabulary a property uses ({@link PropertyEditor}) — a range, an enum, a unit. A bare string is a name with nothing else to say. */\nexport interface CommandArgDescriptor extends PropertyEditor {\n /** The key under a `CommandSpec`'s `params` this is read from. */\n key: string;\n default?: unknown;\n}\n\nexport type CommandArg = string | CommandArgDescriptor;\n\n/** Symbol under which `command` metadata is stored on class prototypes. */\nexport const COMMAND_META = Symbol(\"commandMeta\");\n\nexport interface CommandMeta {\n /** The key a host stores and dispatches on: the method name unless `command({ key })` renamed it. */\n key: string;\n /** The method, which dispatching {@link key} calls. */\n method: string;\n /** Display name; built-ins leave this unset and localize by {@link key} instead. */\n name?: string;\n /**\n * Keys of `params` that become `data`'s fields, in a document. Written here\n * rather than derived from the method's own parameter names, which a\n * minifier mangles and which don't match the document vocabulary anyway\n * (`data`/`duration`/`easing`, not `index` or `wobble`).\n */\n args?: readonly CommandArg[];\n /**\n * Brings its target in: a timeline holds its first frame from the moment\n * the target could first show it, so the resting node never flashes up\n * ahead of it. The hold window is in `docs/timeline.md`.\n */\n entrance?: boolean;\n}\n\nexport interface CommandOptions {\n /** Publishes the method under another key, for a name the method cannot take (a prop, an inherited method). */\n key?: string;\n name?: string;\n args?: readonly CommandArg[];\n entrance?: boolean;\n}\n\n/**\n * Every `command` on an instance's class, inherited included, base → subclass.\n * A subclass that redeclares a key replaces the inherited declaration — method,\n * name and args — at the position the base gave it.\n */\nexport function getCommandMeta(instance: object): CommandMeta[] {\n return mostDerived<CommandMeta>(instance, COMMAND_META);\n}\n\n/** See the module docblock. */\nexport function command(options?: CommandOptions) {\n return function (target: object, propertyKey: string | symbol): void {\n const method = propertyKey as string;\n const key = options?.key ?? method;\n if (!Object.prototype.hasOwnProperty.call(target, COMMAND_META)) {\n (target as Record<symbol, unknown>)[COMMAND_META] = [];\n }\n const list = (target as Record<symbol, unknown>)[COMMAND_META] as CommandMeta[];\n if (list.some(m => m.key === key)) return;\n list.push({\n key,\n method,\n ...(options?.name ? { name: options.name } : {}),\n ...(options?.args ? { args: options.args } : {}),\n ...(options?.entrance ? { entrance: true } : {}),\n });\n };\n}\n", "import { _setObserver, type PropSlot } from \"./slot\";\n\n/**\n * What the slots touched inside {@link observeSlots} are reported to.\n *\n * Reads and writes are recorded rather than declared: a dependency is whatever a\n * computation actually touched, bindings included, so nothing has to annotate a\n * prop as mattering to anyone.\n */\nexport interface SlotObserver {\n read(slot: PropSlot<unknown>): void;\n write(slot: PropSlot<unknown>): void;\n /** A node's clock was read — a result that depends on it is not a function of slots alone. */\n clock?(host: { readonly id: string }): void;\n}\n\n/** The {@link PropSlot._name} of `Node2D`'s laid-out box. */\nexport const LAYOUT_SLOT = \"layoutBounds\";\n/** A document variable's slot is named this plus the variable id. */\nexport const VAR_PREFIX = \"var:\";\n/** A timeline node's presence pseudo-slot is named this plus the node id. */\nexport const PRESENCE_PREFIX = \"presence:\";\n/** A node's child list and parent link, as a pseudo-slot on that node. */\nexport const STRUCTURE_SLOT = \"structure\";\n\n/** Run `fn` with every slot read and write reported to `observer`. An inner scope shadows an outer one. */\nexport function observeSlots<T>(observer: SlotObserver, fn: () => T): T {\n const previous = _setObserver(observer);\n try {\n return fn();\n } finally {\n _setObserver(previous);\n }\n}\n\n/** Run `fn` with nothing observing, inside a scope that is. */\nexport function unobserved<T>(fn: () => T): T {\n const previous = _setObserver(null);\n try {\n return fn();\n } finally {\n _setObserver(previous);\n }\n}\n\n/** `\"card.x\"` for a node's prop, the bare name for a hostless slot (`\"var:g\"`). */\nexport function slotLabel(slot: PropSlot<unknown>): string {\n return slot._host ? `${slot._host.id}.${slot._name}` : slot._name;\n}\n", "import { TweenStepper } from \"./stepper\";\nimport type { Command } from \"./command\";\n\n/**\n * An animation that occupies its duration and writes nothing.\n *\n * What a command on an **unmounted** node becomes. A node that is not in the\n * tree has no box, no surface and no timeline, so a tween on it has nothing to\n * be a tween *of* — but it still has a duration, and the timeline slot it was\n * placed in is entitled to have that duration pass. Returning a real command of\n * the right length keeps the scene's timing intact where throwing would abort\n * the pass and where returning nothing would silently shorten it.\n *\n * The failure this turns into a no-op is a real one — animating a node the\n * author forgot to `add` — and it reads as \"nothing moved\", which is what the\n * author sees on screen anyway.\n */\nexport function inertCommand<P>(target: object, duration: number): Command<P> {\n void target;\n return {\n duration,\n at: () => ({}) as Partial<P>,\n _stepper: () => inertStepper(duration),\n };\n}\n\n/** The {@link TweenStepper} half of {@link inertCommand}: runs its clock, writes nothing. */\nexport function inertStepper(duration: number): TweenStepper {\n let elapsed = 0;\n return {\n seek: (e: number) => { elapsed = e; },\n advance: (dt: number): boolean => {\n elapsed += dt;\n return elapsed >= duration;\n },\n };\n}\n", "import { PropSlot, PropSnapshot } from \"@/props/slot\";\nimport { ensureCells, PropHost, TweenFn } from \"@/props/host\";\nimport { EasingFunction } from \"@/tween/ease/type\";\nimport { driveCommand, type Command } from \"@/tween/command\";\nimport { TweenStepper } from \"@/tween/stepper\";\nimport { PropOptions } from \"@/attributes/properties/decorator\";\n\n/**\n * Companion implementation of {@link Node2D}'s property machinery and its\n * save/restore state stack. The bodies live here as free functions over a\n * narrow {@link ReactiveHost} so `node.ts` keeps only thin delegators (and the\n * hot-path `set`/`_writeProp`, which stay inline on the class). Mirrors the\n * existing `getPropSlot(host, name)` pattern in `props/host.ts`.\n */\n\n/**\n * The slice of a {@link Node2D} these helpers touch: the {@link PropHost} maps\n * plus the internal write/tween seams. `_writeProp` and `_prepareStep` remain\n * methods on `Node2D`; the helpers call back through them so subclass behaviour\n * and the inline hot path are preserved.\n */\n/** @internal */\nexport interface ReactiveHost extends PropHost {\n readonly id: string;\n _writeProp(field: string, value: unknown): void;\n _prepareStep(to: Record<string, unknown>, duration: number, easing?: EasingFunction): TweenStepper;\n /** LIFO stack of save() snapshot layers; owned as an instance field on Node2D. */\n _stateStack: Map<string, PropSnapshot<any>>[];\n}\n\n/**\n * Create the {@link PropSlot} + accessor for a freshly-declared prop and register\n * its tween/mapper metadata. Extracted from `Node2D._registerProp`; defines the\n * getter/setter on `host` so writes route through `host._writeProp`\n * (mapper-aware, binding-aware).\n */\n/** @internal */\nexport function registerProp<Int>(host: ReactiveHost, field: string, options?: PropOptions<any, Int>): void {\n const slot = new PropSlot<Int>(undefined as unknown as Int, host, field);\n const cells = ensureCells(host);\n cells.slots.set(field, slot);\n if (options?.tween) {\n (cells.tweens ??= new Map()).set(field, options.tween as TweenFn<any>);\n }\n if (options?.mapper) {\n (cells.mappers ??= new Map()).set(field, options.mapper as (ext: any, prev?: any) => any);\n }\n Object.defineProperty(host, field, {\n get: () => slot.get(),\n set: (value: any) => host._writeProp(field, value),\n enumerable: true,\n configurable: true,\n });\n}\n\n/**\n * Apply (or re-apply) a prop's initial value plus optional tween/mapper. A first\n * call creates the cell via {@link registerProp}; a subsequent call for the same\n * field reuses the cell and only refines its tween/mapper (so a subclass can\n * override a parent default without losing the cell or its bindings), then\n * writes the value. Extracted from `Node2D.applyProp`.\n */\n/** @internal */\nexport function applyProp<Ext, Int = Ext>(\n host: ReactiveHost,\n field: string,\n initial: Ext | (() => Ext) | undefined,\n options?: PropOptions<Ext, Int>,\n): void {\n const existing = host.__cells?.slots.get(field);\n if (!existing) {\n registerProp<Int>(host, field, options);\n } else if (options) {\n // Allow subclasses to refine tween/mapper on an inherited field.\n if (options.tween) {\n (ensureCells(host).tweens ??= new Map()).set(field, options.tween as TweenFn<any>);\n }\n if (options.mapper) {\n (ensureCells(host).mappers ??= new Map()).set(field, options.mapper as (ext: any, prev?: any) => any);\n }\n }\n host._writeProp(field, initial);\n}\n\n/** Snapshot every registered prop's current value/binding into a plain object. */\n/** @internal */\nexport function collectProperties(host: ReactiveHost): Record<string, any> {\n const result: Record<string, any> = {};\n if (host.__cells) {\n for (const key of host.__cells.slots.keys()) {\n result[key] = (host as any)[key];\n }\n }\n return result;\n}\n\n// ---- State stack (save / restore) -----------------------------------------\n\n/**\n * Every declared prop of a node, captured as the value **or binding** its slot\n * holds — see {@link Node2D.captureProps}, which is the public way to make one.\n *\n * Keyed by prop name. Opaque on purpose: what a slot holds is the *mapped*,\n * internal form, and reading it out to write back through `set` is exactly the\n * round-trip a layer exists to avoid.\n */\nexport type PropLayer = Map<string, PropSnapshot<any>>;\n\n/** Snapshot every prop slot (value or binding) into a fresh layer. */\n/** @internal */\nexport function captureLayer(host: ReactiveHost): PropLayer {\n const layer: PropLayer = new Map();\n const slots = host.__cells?.slots;\n if (!slots) return layer;\n for (const [key, slot] of slots) {\n layer.set(key, slot.snapshot());\n }\n return layer;\n}\n\n/** Push a snapshot of every prop slot (value or binding) onto the stack. */\n/** @internal */\nexport function saveState(host: ReactiveHost): void {\n if (!host.__cells) return;\n host._stateStack.push(captureLayer(host));\n}\n\n/** Pop the top snapshot layer, or `undefined` if the stack is empty. */\n/** @internal */\nexport function popState(host: ReactiveHost): PropLayer | undefined {\n return host._stateStack.pop();\n}\n\n/** Instantly reapply a snapshot layer to every captured slot. */\n/** @internal */\nexport function applySnapshotLayer(host: ReactiveHost, layer: PropLayer): void {\n const slots = host.__cells?.slots;\n if (!slots) return;\n for (const [key, snap] of layer) {\n slots.get(key)?.restoreFrom(snap);\n }\n}\n\n/**\n * Animated restore: tween the numeric / custom-tweenable props toward their\n * saved resolved values, then reapply the full snapshot so bindings are\n * restored (not frozen at the tween's landing value) and non-tweened props snap.\n *\n * A {@link Command} rather than a generator: `_prepareStep`'s stepper already\n * drives the tween as a pure function of elapsed time, so `driveCommand` wraps\n * it directly and fires the snapshot reapply exactly at `t === 1` — the same\n * \"commit at the end, restore what came before below it\" shape\n * `packages/components/code`'s `runTransition` uses.\n *\n * `_prepareStep` is called **lazily, on the command's first evaluation**, not\n * when this function runs — it snapshots each prop's `from` off the *live*\n * node, and a generator's body (what this replaces) never ran a line until the\n * caller's first `.next()` either. Building it eagerly would snapshot whatever\n * the node happened to hold at `restore()`-call time instead of at first-drive\n * time, which can differ if the caller does more to the node in between.\n */\n/** @internal */\nexport function restoreAnimated(\n host: ReactiveHost,\n layer: PropLayer | undefined,\n duration: number,\n easing?: EasingFunction,\n): Command<Record<string, never>> {\n let stepper: TweenStepper | null = null;\n\n return driveCommand(duration, (t) => {\n if (!stepper) {\n // `to()` reads each snapshot's resolved `value` (correct even for a\n // bound slot), so the node animates back to where it *was*.\n const target: Record<string, unknown> = {};\n if (layer) {\n for (const [key, snap] of layer) {\n target[key] = snap.value;\n }\n }\n stepper = host._prepareStep(target, duration);\n }\n stepper.seek(t * duration);\n if (layer && t >= 1) applySnapshotLayer(host, layer);\n }, easing);\n}\n", "/**\n * A node's place on the scene's clock, read via `node.time`.\n *\n * Advanced once per frame by `Node.attach`, and consumed by motion sampling,\n * the render context's `elapsed`, and anything a node's own `tick()` derives\n * from time.\n *\n * `creation` is seeded on the node's **first** advance rather than at\n * construction, so `elapsed` measures how long a node has been *in the scene* —\n * which is what an entrance animation, a video's playhead and a per-node\n * dissolve all actually mean. A node built during the generator's third second\n * and added then reads `elapsed === 0` on its first frame.\n */\nexport interface NodeTime {\n /** Seconds since the clip started. */\n readonly total: number;\n /** The clip time at which this node was first advanced. */\n readonly creation: number;\n /** How long this node has existed: `total - creation`. */\n readonly elapsed: number;\n}\n\n/**\n * The writable form the runtime advances. Nodes hand out {@link NodeTime}, which\n * is the same shape with every field read-only.\n *\n * @internal\n */\nexport interface MutableNodeTime {\n total: number;\n creation: number;\n elapsed: number;\n /** Whether {@link advanceNodeTime} has seeded `creation` yet. */\n started: boolean;\n}\n\n/** The zeroed holder a node keeps for its lifetime. @internal */\nexport function createNodeTime(): MutableNodeTime {\n return { total: 0, creation: 0, elapsed: 0, started: false };\n}\n\n/** Advance `time` to `total` clip-seconds, seeding `creation` on first tick. @internal */\nexport function advanceNodeTime(time: MutableNodeTime, total: number): void {\n if (!time.started) {\n time.creation = total;\n time.started = true;\n }\n time.total = total;\n time.elapsed = total - time.creation;\n}\n", "import { _observer, PropSlot } from \"@/props/slot\";\nimport { STRUCTURE_SLOT } from \"@/props/observer\";\nimport { PropHost, type PropCells } from \"@/props/host\";\nimport { EasingFunction } from \"@/tween/ease/type\";\nimport { toCommand } from \"@/tween/to-command\";\nimport { makeCommand, type Command, type CommandArgs, type CommandTarget } from \"@/tween/command\";\nimport { prepareNumericCellTween } from \"@/tween/prepare\";\nimport { inertCommand, inertStepper } from \"@/tween/inert\";\nimport { TweenStepper } from \"@/tween/stepper\";\nimport { RefTarget } from \"@/util/reference\";\nimport { Context, ContextMap } from \"@/util/context\";\nimport { AssetCatalog } from \"@/assets/catalog\";\nimport type { AssetScope } from \"@/assets/scope\";\nimport { declareMembers, getPropertyMeta, PropOptions } from \"@/attributes/properties/decorator\";\nimport {\n applyProp,\n applySnapshotLayer,\n collectProperties,\n popState,\n restoreAnimated,\n saveState,\n} from \"./node-reactive\";\nimport type { PropLayer } from \"./node-reactive\";\nimport { advanceNodeTime, createNodeTime, type MutableNodeTime, type NodeTime } from \"@/components/trees/node/node-time\";\nimport type { PropInputs } from \"@/attributes/properties/inputs\";\nimport { command } from \"@/tween/command-decorator\";\n\nexport type { NodeTime } from \"@/components/trees/node/node-time\";\nexport type { PropInput, PropInputs } from \"@/attributes/properties/inputs\";\n\n/** Which scene graph a node belongs to. See {@link Node.dimension}. */\nexport type NodeDimension = \"2d\" | \"3d\" | \"audio\";\n\n/** Where a node of each dimension is allowed to live, for the mismatch error. */\nconst HOSTS_OF: Record<NodeDimension, string> = {\n \"2d\": \"2D nodes go in the 2D tree, or inside a Canvas3D as a HUD over its scene.\",\n \"3d\": \"Put 3D nodes inside a Canvas3D, which is the one node that holds both.\",\n audio: \"Put audio nodes under an AudioBus, or directly on the scene root.\",\n};\n\nexport interface NodeMetadata<T extends Node> {\n /**\n * Handle written with this node at construction. Typed as {@link RefTarget}\n * rather than `Reference<T>` so a ref declared as one of `T`'s *supertypes*\n * is accepted (`createRef<Node2D>()` on a `<Rect>`) — see the note there\n * for why that direction is the sound one.\n */\n ref?: RefTarget<T>;\n}\n\nexport type NodeConfig<T extends Node, P> = PropInputs<P> & NodeMetadata<T>;\n\n/**\n * Everything {@link Node.attach} needs to put a subtree into a live scene.\n *\n * The three things tree membership supplies, and the only three: what assets are\n * available, what context the ancestors provide, and where the playhead is.\n */\nexport interface AttachScope {\n /** Metadata for the assets this scene may declare. */\n assets: AssetCatalog;\n /** The token map the parent provides to this node. */\n context: ContextMap;\n /** Clip-relative time, in seconds. */\n time: number;\n}\n\n/**\n * A `children` child: a single {@link Node}, an arbitrarily-nested array of\n * children, or a falsy value. Nesting is allowed so `.map()` results can be\n * dropped straight in as a child, and falsy values are allowed so\n * `condition && Rect({ … })` works — the constructor flattens\n * (`.flat(Infinity)`) and filters out everything but `Node` instances.\n */\nexport type NodeChildren = Node | false | null | undefined | NodeChildren[];\n\n/**\n * The props every node has, in either dimension.\n *\n * Deliberately tiny. Everything that reads as \"a box on a page\" — `x`/`y`,\n * `width`/`height`, `padding`, `flex`, anchors, `opacity` — lives on\n * {@link Node2DProps}, and everything that reads as \"a thing in space\" —\n * `position`, `quaternion`, `castShadow` — lives on `Node3DProps`, because a\n * prop that means nothing for half the tree is worse than no prop at all.\n */\nexport interface NodeProps {\n children: NodeChildren;\n /**\n * Seeds {@link Node.id}. A document's `NodeSpec.id` supplies it — see\n * `Registry.instantiate` — so an instantiated node answers to the identity\n * its row was authored under. Left out, the node falls back to a UUID, which\n * is what every hand-written `new Rect({…})` and component call gets.\n */\n id?: string;\n /**\n * The handle a node is *referenced by*, as against {@link NodeProps.id},\n * which addresses it. `\"=[card.x]\"` in any prop reads the `x` of the node\n * keyed `card` — see `NodeSpec.key`.\n *\n * Optional and never generated — a node has one only because an author wrote\n * one, which is what makes it safe to point a formula at — and unique per\n * document, which `document/validate.ts` enforces.\n */\n key?: string;\n}\n\n/**\n * The dimension-agnostic base of the scene graph: tree, identity, reactive\n * properties, commands, context, clock, asset declaration, teardown. Nothing\n * about *where* a node is or *how* it draws — that's {@link Node2D} / `Node3D`.\n * They meet only at `Canvas3D`; mixing them anywhere else throws (see\n * {@link acceptsChild}).\n *\n * Subclasses call {@link initProps} from their own constructor rather than the\n * base doing it: a subclass's field initializers only run *after* `super()`\n * returns, so applying `property` defaults any earlier would write into cells\n * that don't exist yet.\n */\nexport abstract class Node<P extends NodeProps = NodeProps> implements PropHost {\n /**\n * Which scene graph this node belongs to.\n *\n * A getter rather than a field so it is answerable from the prototype during\n * construction, before any subclass field initializer has run.\n */\n abstract get dimension(): NodeDimension;\n\n /** The trees this type takes children from, answerable from the prototype as {@link dimension} is. */\n get _childTrees(): readonly NodeDimension[] {\n return [this.dimension];\n }\n\n constructor(props?: NodeConfig<any, P>) {\n // Retain the raw props (see _props doc) so a provider's provideContext can\n // read which keys the author passed. Captured before any default\n // application so it reflects exactly what the author passed. The object is\n // retained by reference, so a subclass expanding prop sugar in place\n // afterwards (`size`, `transform3D`) is reflected here too.\n this._props = props;\n // Neither is a property: identity does not tween, so neither has any\n // business in the table `set()`, `to()` and the baseline restore walk\n // iterate.\n const identity = props as { id?: string; key?: string } | undefined;\n this.key = identity?.key;\n // Nullish, never falsy: `\"\"` is the scene root's real id, not a missing\n // one (`checkRootShape` in document/validate.ts defines the root as the\n // row holding it), and a UUID in its place would have the host's tree\n // report a root no document row mentions.\n this.id = identity?.id ?? crypto.randomUUID();\n }\n\n /** See {@link NodeProps.key}. */\n key?: string;\n\n private _hidden = false;\n private _locked = false;\n\n /**\n * Hidden by the editor — no paint, no pick, no layout slot. See\n * {@link NodeEditorState.hidden}.\n */\n get hidden(): boolean {\n return this._hidden;\n }\n\n /** Locked by the editor — unpickable, but drawn. See {@link NodeEditorState.locked}. */\n get locked(): boolean {\n return this._locked;\n }\n\n /**\n * @internal — written only by `applyEditorStates`, which owns both flags for\n * the whole tree. Not a setter pair, so a caller cannot set one and leave the\n * other holding a previous frame's answer.\n */\n _setEditorState(hidden: boolean, locked: boolean): void {\n this._hidden = hidden;\n this._locked = locked;\n }\n\n /**\n * Fire the `ref` and apply every declared property, reading\n * initial values from `props`.\n *\n * Called by the concrete constructor ({@link Node2D}'s, `Node3D`'s) rather\n * than by this one, because a subclass's field initializers run *after*\n * `super()` returns: doing this here would apply props while the cells those\n * props write into are still `undefined`.\n */\n protected initProps(props?: NodeConfig<any, P>): void {\n if (props?.ref) {\n props.ref(this as any);\n }\n\n // Apply every declared property, reading initial values from props.\n for (const meta of getPropertyMeta(this)) {\n const propsVal = props ? (props as any)[meta.key] : undefined;\n const initial = propsVal !== undefined ? propsVal : meta.default;\n this.applyProp(meta.key, initial, meta.options);\n }\n }\n\n /**\n * Adopt the `children` prop. Called by the concrete constructor after its own\n * defaults are in place, so a child never lands in a tree whose parent has not\n * finished sizing itself.\n */\n protected adoptChildrenProp(props?: NodeConfig<any, P>): void {\n if (props && (props as any).children) {\n const raw = Array.isArray((props as any).children) ? (props as any).children : [(props as any).children];\n const flat = (raw as unknown[]).flat(Infinity)\n .filter((c: unknown): c is Node => c instanceof Node);\n if (flat.length > 0) this._addChildren(flat);\n }\n }\n\n /**\n * Whether `child` may be adopted by this node.\n *\n * A node holds children of its own dimension; the places the trees meet are\n * `Canvas3D`, which takes 2D and 3D, and `Canvas2D`, which takes 2D and\n * audio. Both partition what they accept. Rejecting the mix here rather than\n * letting it through is deliberate: a `Box3D` parented to a `Rect` would be\n * silently skipped by both the layout walk and the 3D walk, and would simply\n * never appear.\n */\n protected acceptsChild(child: Node): boolean {\n return child.dimension === this.dimension;\n }\n\n /** Throw if `child` cannot go here: by its tree, by what this node takes, or by where the child says it goes. */\n protected assertAcceptsChild(child: Node): void {\n if (!this.acceptsChild(child)) {\n const why = child.dimension === this.dimension ? this._childRule() : HOSTS_OF[child.dimension];\n throw new TypeError(`${this.className} (${this.dimension}) cannot hold ${child.className} (${child.dimension}).${why ? ` ${why}` : \"\"}`);\n }\n const refusal = child._parentRefusal(this);\n if (refusal) throw new TypeError(refusal);\n }\n\n /** What this node takes, for the error when it refuses a child of its own tree. */\n protected _childRule(): string {\n return \"\";\n }\n\n /** Why this node cannot go inside `parent`, or `null`: only a node that names its parents refuses one. */\n _parentRefusal(_parent: Node): string | null {\n return null;\n }\n\n private _assets: AssetCatalog | null = null;\n protected _parent: Node | null = null;\n\n /**\n * Whether this node is in a live scene tree. Gates measure/layout/render,\n * asset declaration and every command — checked at the handful of places\n * the framework dispatches from, not per method.\n */\n private _mounted = false;\n\n /** See {@link _mounted}. */\n get mounted(): boolean {\n return this._mounted;\n }\n\n get parent(): Node | null {\n if (_observer !== null) _observer.read(this._structureSlot());\n return this._parent;\n }\n\n get assets(): AssetCatalog {\n if (!this._assets) throw new Error(\"Assets not bound — this node is not attached to a scene. See Node.attach().\");\n return this._assets;\n }\n\n /** Token→value map pushed down from ancestor providers, bound by {@link attach}. */\n private _context: ContextMap = ContextMap.EMPTY;\n /** True once {@link attach} has reached this node. */\n private _contextBound = false;\n\n /** Raw constructor props, retained so {@link provideContext} can see which keys were explicitly passed. Kept through {@link dispose} so a reused instance re-derives context on the next attach. */\n protected _props?: NodeConfig<any, P>;\n\n /** Read the nearest ancestor provider's value for `ctx` (or its default). */\n useContext<T>(ctx: Context<T>): T {\n return this._context.get(ctx);\n }\n\n /** Assigned in the constructor — see {@link NodeProps.id}. */\n readonly id: string;\n\n /**\n * The slots behind this node's `property` fields. See {@link PropCells}.\n *\n * @internal — the authoring surface is the declared props themselves, plus\n * `set()`/`to()`/`captureProps()`.\n */\n __cells?: PropCells;\n\n protected _children: Node[] = [];\n\n /**\n * Flatten a constructor's raw `children` prop into the `Node` instances it\n * contains, without mutating or adding them — the same normalisation the\n * constructor applies before adding them, exposed standalone so\n * {@link applyDefaultSize} overrides can inspect children's own resolved\n * `width`/`height` *before* they're attached (children are constructed,\n * defaults and all, before being passed in as props).\n */\n protected static flattenChildrenProp(props: { children?: unknown } | undefined): Node[] {\n const childProp = props ? props.children : undefined;\n if (!childProp) return [];\n const raw = Array.isArray(childProp) ? childProp : [childProp];\n return (raw as unknown[]).flat(Infinity).filter((c: unknown): c is Node => c instanceof Node);\n }\n\n // ---- Reactive properties ----------------------------------------------\n\n /**\n * Declare a prop on this node. Creates a {@link PropSlot}-backed accessor\n * for `field`, applies an initial value (callback → binding; otherwise\n * constant), and registers optional tween/mapper metadata used by `set()`\n * and `to()`.\n *\n * Subsequent calls for the same field reuse the existing slot and act as\n * a value assignment, so subclasses can override a parent's default by\n * calling applyProp again without losing the slot or its bindings.\n */\n protected applyProp<Ext, Int = Ext>(\n field: string,\n initial: Ext | (() => Ext) | undefined,\n options?: PropOptions<Ext, Int>,\n ): void {\n applyProp(this, field, initial, options);\n }\n\n /** @internal Hot-path prop write (mapper- and binding-aware). Public-but-underscored like `_prepareStep` so reactive companions in this directory can call it; not part of the authoring surface. */\n _writeProp(field: string, value: unknown): void {\n if (value === undefined) return;\n const slot = this.__cells?.slots.get(field);\n if (!slot) return;\n const mapper = this.__cells?.mappers?.get(field);\n if (typeof value === \"function\") {\n const extFn = value as () => any;\n if (mapper) {\n // A binding that reads `undefined` — a node reference to a node that is\n // not there — leaves the prop as a node built without it, and never\n // reaches the mapper, which holds the shape the prop's readers go through.\n let unset: { value: unknown } | undefined;\n slot.bind(() => {\n const read = extFn();\n return read === undefined\n ? (unset ??= { value: this._unsetValue(field, mapper) }).value\n : mapper(read, slot.get());\n });\n } else {\n slot.bind(extFn);\n }\n } else {\n slot.set(mapper ? mapper(value, slot.get()) : value);\n }\n }\n\n get properties(): P {\n return collectProperties(this) as P;\n }\n\n /**\n * This node's **class** name, for a message or a host's type column. Not an\n * authored identity — those are {@link id} and {@link key}, and nothing in\n * the document model is called a name any more. Nor is it the registry key a\n * document writes in `NodeSpec.type`: a minifier is free to rename a class.\n */\n get className(): string {\n return this.constructor.name;\n }\n\n set(props: { [K in keyof P]?: P[K] | (() => P[K]) }): void {\n const slots = this.__cells?.slots;\n if (!slots) return;\n // Iterate the caller's keys (usually 1–3) rather than every registered\n // prop (15+): set() runs in the per-frame hot path. Only keys backed by\n // a slot are written; unknown keys are ignored — which is also what\n // lets a subclass distribute its own sugar (2D's `size`, `transform3D`)\n // into real keys and then delegate here.\n for (const key in props) {\n const val = (props as any)[key];\n if (val !== undefined && slots.has(key)) this._writeProp(key, val);\n }\n }\n\n to<D extends Partial<P> = Partial<P>>(args: CommandArgs<D> & { duration: number }): Command<P> {\n return toCommand<P>(this, args.data ?? {}, args.duration, args.easing);\n }\n\n /**\n * Build a {@link Command} from a pure function of normalized time — an\n * animation this node can be *evaluated* at, not only run through. The pair\n * to {@link to}, for the built-in commands whose values at `t` are not a prop\n * list, and what a component command's timeline lowers to.\n *\n * Snapshot whatever the animation starts from *outside* `at`: reading a prop\n * inside it would re-read the value the command is itself writing.\n */\n protected command<Props = P>(\n at: (t: number) => Partial<Props>,\n duration: number = 1,\n easing?: EasingFunction,\n ): Command<Props> {\n if (!this._mounted) return inertCommand<Props>(this, duration);\n return makeCommand<Props>(\n this as unknown as CommandTarget<Props>,\n at,\n duration,\n easing,\n );\n }\n\n /**\n * Resolve a single `to()` step into a flat {@link TweenStepper} — all the\n * per-key setup (mapper, numeric-vs-custom routing) happens once here, then\n * `advance(dt)` is allocation-free. Used by both a chain's iterator path and\n * the batched `parallel` path.\n *\n * A subclass with positional sugar of its own (2D's `size` and anchors)\n * expands `to` in place and then delegates here.\n */\n _prepareStep(to: Partial<P>, duration: number, easing?: EasingFunction): TweenStepper {\n if (!this._mounted) return inertStepper(duration);\n // A tween runs in stored space, so the destination is mapped once, here,\n // and every step after it is a stored value written to the slot as it is.\n // Writing a step through the setter would map it a second time, which only\n // an idempotent mapper survives.\n const numCells: PropSlot<number>[] = [];\n const numFrom: number[] = [];\n const numEnd: number[] = [];\n const customLerps: Array<(t: number) => void> = [];\n const stringSnaps: Array<[PropSlot<string>, string]> = [];\n\n for (const key of Object.keys(to)) {\n const slot = this.__cells?.slots.get(key);\n if (!slot) continue;\n const extVal = (to as any)[key];\n const mapper = this.__cells?.mappers?.get(key);\n const targetVal = mapper ? mapper(extVal, (this as any)[key]) : extVal;\n const tweenFn = this.__cells?.tweens?.get(key);\n if (tweenFn) {\n const from = (this as any)[key];\n customLerps.push((t) => {\n slot.set(tweenFn(from, targetVal, t));\n });\n } else if (typeof targetVal === 'number') {\n numCells.push(slot as PropSlot<number>);\n numFrom.push((this as any)[key] as number);\n numEnd.push(targetVal as number);\n } else if (typeof targetVal === 'string') {\n stringSnaps.push([slot as PropSlot<string>, targetVal]);\n }\n }\n\n const lerp = prepareNumericCellTween(numCells, numFrom, numEnd);\n const hasCustom = customLerps.length > 0;\n const hasSnaps = stringSnaps.length > 0;\n\n const apply = (t: number): void => {\n const easedT = easing ? easing(t) : t;\n lerp(easedT);\n if (hasCustom) for (const fn of customLerps) fn(easedT);\n // A discrete prop has nothing between its endpoints, so it snaps at\n // the end rather than interpolating. Applied here rather than only in\n // `advance` because a `seek` past the end has, by definition, reached\n // that end — leaving it out meant `seek(duration)` and running to\n // `duration` produced different nodes, and only the second was right.\n if (hasSnaps && t >= 1) for (const [slot, val] of stringSnaps) slot.set(val);\n };\n\n let elapsed = 0;\n return {\n // Tracks `elapsed`, so a seek and a subsequent advance agree about\n // where the tween is. Without it, seeking forward then advancing\n // rewound to `dt`.\n seek: (e: number) => {\n elapsed = e;\n apply(duration > 0 ? Math.min(e / duration, 1) : 1);\n },\n advance: (dt: number): boolean => {\n elapsed += dt;\n if (elapsed < duration) {\n apply(elapsed / duration);\n return false;\n }\n apply(1);\n return true;\n },\n };\n }\n\n /** What a node constructed without `field` holds: its declared default, through the mapper. */\n private _unsetValue(field: string, mapper: (ext: any, prev?: any) => any): unknown {\n const declared = getPropertyMeta(this).find((meta) => meta.key === field)?.default;\n const initial = typeof declared === \"function\" ? declared() : declared;\n return initial === undefined ? undefined : mapper(initial, undefined);\n }\n\n // ---- State stack (save / restore) -------------------------------------\n // A per-node LIFO stack of property snapshots, mirroring Motion Canvas's\n // node.save()/restore(). `save()` pushes a snapshot of every declared prop;\n // `restore()` pops the most recent one and either snaps to it (no duration)\n // or tweens the numeric props back to it over `duration`.\n\n /** @internal LIFO stack of save() snapshot layers. Underscore-internal so the prop companion can read it; not authoring surface. */\n _stateStack: PropLayer[] = [];\n\n /**\n * Push a snapshot of this node's current state onto its save stack.\n *\n * Every reactive prop (`x`, `y`, `scale`, `opacity`, `fill`, …) is captured,\n * preserving reactive bindings — a prop bound to `() => other().x` is saved\n * as the binding, not just its resolved value, so {@link restore} re-binds\n * it rather than freezing the value. Calls stack: each `save()` pushes a new\n * layer, and each {@link restore} pops the most recent one.\n *\n * @example\n * node.save();\n * node.moveTo({ data: { x: 200, y: 0 }, duration: 1 });\n * node.restore({ duration: 1 }); // animate back to where it was saved\n */\n save(): void {\n saveState(this);\n }\n\n /**\n * Pop the most recent {@link save} snapshot and roll this node back to it.\n *\n * Called with no `duration` (or `0`), every prop is reapplied instantly —\n * plain values are set, reactive bindings are re-bound. Called with a\n * positive `duration`, the numeric props (and any with a custom `tween`)\n * animate toward their saved values over that many seconds; once the tween\n * finishes the full snapshot is reapplied, which re-binds any reactive props\n * and snaps non-tweenable props (e.g. strings) to their saved values.\n *\n * A no-op (returns immediately) if there is nothing on the stack.\n */\n restore(): void;\n restore(args: CommandArgs<Record<string, never>> & { duration: number }): Command<Record<string, never>>;\n restore(args?: CommandArgs<Record<string, never>>): void | Command<Record<string, never>> {\n const layer = popState(this);\n const duration = args?.duration;\n if (duration === undefined || duration <= 0) {\n if (layer) applySnapshotLayer(this, layer);\n return;\n }\n return restoreAnimated(this, layer, duration, args?.easing);\n }\n\n // ---- Clock ------------------------------------------------------------\n\n protected _time: MutableNodeTime = createNodeTime();\n\n /** This node's place on the scene clock. See {@link NodeTime}. */\n public get time(): NodeTime {\n if (_observer !== null) _observer.clock?.(this);\n return this._time;\n }\n\n /**\n * Advance **this node's** clock to `total` clip-seconds and sample its\n * derived render state.\n *\n * Per-node, not per-subtree: {@link attach} already recurses, so a recursive\n * advance here would re-advance every descendant once per ancestor.\n *\n * Sampling happens here, not at render: this runs on every advanced frame in\n * every playback path (forward, scrub, precomp), whereas `render` runs only\n * for displayed frames. Sampling per-frame is what makes velocity correct on\n * the first frame after a scrub/rewind, where sampling only at render time\n * read zero. The advance loop runs before `generator.next()` (so audio\n * scheduling in generator bodies reads the right time), which means x/y here\n * still hold the previous frame's value — velocity therefore trails the\n * rendered position by one frame. That lag is constant and identical forward\n * vs. scrub, and imperceptible for motion blur.\n */\n private _advanceOwnTime(total: number): void {\n advanceNodeTime(this._time, total);\n this._sample();\n }\n\n /**\n * Sample this node's own derived render state for the current frame. Nothing\n * to derive in the general case; {@link Node2D} samples its motion here.\n *\n * @internal The per-node half of `sampleTree` — a walk, not a node method.\n */\n _sample(): void { }\n\n /**\n * Record this node's current position as the motion history's previous\n * frame, stamped `at`, deriving no velocity.\n *\n * @internal The per-node half of `primeMotionTree`.\n */\n _primeMotion(at: number): void { }\n\n // ---- Attachment -------------------------------------------------------\n\n /**\n * Put this subtree into the scene: mark it mounted, bind the asset catalog\n * and inherited context, advance its clock to `scope.time`.\n *\n * Safe and cheap to call every frame — an unchanged catalog/context\n * short-circuits, and {@link resolveContext} fires only on first attach.\n *\n * @internal Driven by `ClipInstance` per frame, and by {@link add} for a mid-frame subtree.\n */\n attach(scope: AttachScope): void {\n const first = !this._mounted;\n this._mounted = true;\n\n if (this._assets !== scope.assets) this._assets = scope.assets;\n\n const next = this.provideContext(scope.context);\n // Unchanged map, already bound, and not this instance's first attach ⇒\n // the whole subtree already holds `next` and the walk below would be pure\n // repetition of the context half. The time half still has to run.\n const contextChanged = !this._contextBound || this._context !== next;\n if (contextChanged) {\n this._context = next;\n this._contextBound = true;\n }\n if (first) this.resolveContext(next);\n\n this._advanceOwnTime(scope.time);\n\n if (this._children.length === 0) return;\n const childScope = next === scope.context ? scope : { ...scope, context: next };\n for (const child of this._children) child.attach(childScope);\n }\n\n /**\n * Take this subtree out of the scene. Not a teardown — props/children/bindings\n * stay, so it can be attached elsewhere (`reparent`). {@link dispose} tears down.\n *\n * @internal Driven by {@link remove}/{@link clear}.\n */\n detach(): void {\n if (!this._mounted) return;\n this._mounted = false;\n for (const child of this._children) child.detach();\n }\n\n /** The scope this node was last attached with, for handing to a late child. */\n private _currentScope(): AttachScope | null {\n return this._assets && this._contextBound\n ? { assets: this._assets, context: this._context, time: this._time.total }\n : null;\n }\n\n /** Attach `child` if this node is itself attached; otherwise leave it for the walk. */\n /** @internal Shared with `Node2D.addChildAt`, which splices rather than pushes. */\n protected _attachChild(child: Node): void {\n if (!this._mounted) return;\n const scope = this._currentScope();\n if (scope) child.attach(scope);\n }\n\n // ---- Context lifecycle ------------------------------------------------\n\n /**\n * Apply inherited context **values** to this node, once, after it's linked\n * into the tree and ancestor providers have resolved: a component's\n * `inherit` entries. Runs exactly once per instance.\n */\n protected resolveContext(ctx: ContextMap): void { }\n\n /**\n * The {@link ContextMap} handed to descendants: a component's `provide`\n * adds its tokens. The base passes the parent's map through unchanged.\n */\n protected provideContext(parent: ContextMap): ContextMap {\n return parent;\n }\n\n /**\n * Bind `node`'s asset catalog, context and clock without making it a child —\n * for a node used purely as a pixel source (`Tex.surface`), laid out on\n * demand rather than sitting in the tree.\n */\n protected attachDetached(node: Node): void {\n const scope = this._currentScope();\n if (scope) node.attach(scope);\n }\n\n /**\n * Declare what this node draws from its props and inherited context alone —\n * never `layoutBounds` or the clock. The runtime records what this reads and\n * calls it again only when one of those props is written, so anything else it\n * depends on is a change nobody will ask about.\n */\n declareAssets(assets: AssetScope): void { }\n\n get children(): Node[] {\n if (_observer !== null) _observer.read(this._structureSlot());\n return this._children;\n }\n\n /**\n * Every child, both dimensions, unfiltered — unlike {@link children}, which\n * a {@link Node2D} filters to its own kind. Used where index has to match\n * the authored tree (picking), since filtering would renumber it.\n */\n get _allChildren(): readonly Node[] {\n if (_observer !== null) _observer.read(this._structureSlot());\n return this._children;\n }\n\n /**\n * Add children — a node, an array, or a nested mix; falsy entries\n * (`cond && node`) are dropped. A child of the other dimension throws —\n * see {@link acceptsChild}.\n */\n add(child: NodeChildren): void {\n if (child instanceof Node) {\n this._addChild(child);\n return;\n }\n const flat = Node.flattenChildrenProp({ children: child });\n if (flat.length > 0) this._addChildren(flat);\n }\n\n /** Remove children — same shapes as {@link add}. Not a child of this one is a no-op. */\n remove(child: NodeChildren): void {\n if (child instanceof Node) {\n this._removeChild(child);\n return;\n }\n for (const node of Node.flattenChildrenProp({ children: child })) {\n this._removeChild(node);\n }\n }\n\n /** Remove every child, detaching each (see {@link remove}). */\n clear(): void {\n for (const child of this._children) {\n if (_observer !== null) this._structureChanged(child);\n child._parent = null;\n child.detach();\n }\n this._children.length = 0;\n }\n\n /**\n * Insert `child` at `index` among this node's children.\n *\n * On {@link Node} rather than {@link Node2D} because it is tree machinery —\n * `ClipTimeline.syncPresence` reaches for it on whatever a spec's\n * `parentId` names, which since audio joined the graph is not always a 2D\n * node. `Node2D` overrides it for the animated insert, which measures the\n * child off-tree and so needs a laid-out one.\n */\n addChildAt(args: CommandArgs<{ child: Node; index: number }>): void | Command<Record<string, never>> {\n const { child, index } = args.data as { child: Node; index: number };\n this.assertAcceptsChild(child);\n this._insertChildAt(child, index);\n }\n\n /** @internal Shared with `Node2D.addChildAt`'s instant branch. */\n protected _insertChildAt(child: Node, index: number): void {\n if (_observer !== null) this._structureChanged(child);\n this._children.splice(index, 0, child);\n child._parent = this;\n this._attachChild(child);\n }\n\n /**\n * @internal The pseudo-slot {@link children} and {@link parent} report to an\n * observer. Allocated on first observation, so a tree nobody observes carries none.\n */\n _structureSlot(): PropSlot<null> {\n return this._structure ??= new PropSlot<null>(null, this, STRUCTURE_SLOT);\n }\n\n /** @internal Report a child entering or leaving this node — its parent link changes with it. Call only while observed. */\n _structureChanged(child: Node | null): void {\n _observer!.write(this._structureSlot());\n if (child) _observer!.write(child._structureSlot());\n }\n\n private _structure: PropSlot<null> | null = null;\n\n private _addChild(child: Node): void {\n this.assertAcceptsChild(child);\n if (_observer !== null) this._structureChanged(child);\n this._children.push(child);\n child._parent = this;\n this._attachChild(child);\n }\n\n private _addChildren(children: Node[]): void {\n for (const child of children) this.assertAcceptsChild(child);\n if (_observer !== null) for (const child of children) this._structureChanged(child);\n this._children.push(...children);\n for (const child of children) child._parent = this;\n for (const child of children) this._attachChild(child);\n }\n\n private _removeChild(child: Node): void {\n const i = this._children.indexOf(child);\n if (i < 0) return;\n if (_observer !== null) this._structureChanged(child);\n const [removed] = this._children.splice(i, 1);\n if (removed) {\n removed._parent = null;\n removed.detach();\n }\n }\n\n dispose(): void {\n if (this.__cells) {\n for (const slot of this.__cells.slots.values()) {\n slot.dispose();\n }\n }\n this.__cells = undefined;\n this._assets = null;\n this._mounted = false;\n // _props is retained (authored identity) so provideContext still works after reuse.\n this._context = ContextMap.EMPTY;\n this._contextBound = false;\n }\n}\n\ndeclareMembers(Node, {\n to: command(),\n restore: command(),\n addChildAt: command({ args: [\"child\", \"index\"] }),\n});\n", "import type { AssetType } from \"./record\";\n\n/**\n * A frame reached for an asset that was never loaded.\n *\n * This is the counterweight to declared asset tracking. A node states what it\n * needs from `Node.declareAssets`; if it\n * misses something, the renderer finds nothing when it goes to paint. The old\n * inference pass could not really get this wrong — it discovered assets *from*\n * the draw calls, so anything drawn was by construction requested — and the\n * fills were written to match: a missing decode returned `false` and the layer\n * was quietly skipped.\n *\n * Under declarations that leniency is the wrong default. A skipped layer is a\n * frame that renders *almost* right, with a photo missing or a heading in the\n * fallback face, on a node that may only appear seconds in and only on a cold\n * load. Throwing turns a silent visual gap into a located failure: during precomp\n * it is caught per scene and surfaces as a `BuildError` in the errors panel, and\n * at playback it stops the frame rather than shipping a wrong one.\n *\n * It means \"declared but not loaded, or never declared\". It deliberately does\n * **not** cover a *time-varying* miss — a video frame the decode window has not\n * reached yet is an asset that loaded fine, and `warmPendingVideo` already exists\n * to settle those; those paths still paint the nearest decoded frame.\n */\nexport class AssetNotLoadedError extends Error {\n readonly assetType: AssetType;\n readonly src: string;\n /** The innermost drawing node, stamped by `Node2D.render` on the way out. */\n nodeId?: string;\n\n constructor(assetType: AssetType, src: string, hint?: string) {\n super(`${assetType} asset \"${src}\" is not loaded. ` + (hint ?? declareHint(assetType)));\n this.name = \"AssetNotLoadedError\";\n this.assetType = assetType;\n this.src = src;\n }\n}\n\n/** How to declare an asset of `assetType`: the scope method, or a command's sound. */\nfunction declareHint(assetType: AssetType): string {\n if (assetType === \"audio\") return \"Play it from a command (`timeline.sound(...)`), so the asset timeline loads it before this frame draws.\";\n return `Declare it from the node's declareAssets() (e.g. assets.${assetType}(...)), so the asset timeline loads it before this frame draws.`;\n}\n", "import type { Size2D, SizeInput } from \"@/attributes/layout/size\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport type { SizeConstraints } from \"./constraints\";\nimport type { LayoutItem } from \"./types\";\n\n/** An item's size under `constraints` — through its own `measure` when it has one. */\nexport function measureItem(\n item: LayoutItem,\n constraints: SizeConstraints,\n measurer: MeasureContext2D | undefined,\n): Size2D {\n if (item.measure) {\n const size = item.measure(constraints, measurer);\n return { width: size.width ?? 0, height: size.height ?? 0 };\n }\n return {\n width: extentOf(item.width, constraints.maxWidth),\n height: extentOf(item.height, constraints.maxHeight),\n };\n}\n\nfunction extentOf(input: SizeInput, available: number | undefined): number {\n if (typeof input === \"number\") return input;\n return input === \"fill\" ? available ?? 0 : 0;\n}\n", "import { clamp } from \"@/util/clamp\";\nimport type { Size2D } from \"@/attributes/layout/size\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport type { BoxBounds } from \"./bounds\";\nimport type { SizeConstraints } from \"./constraints\";\nimport type { FlowLine, FlowMeasure, FlowSpace, GapSize, LayoutItem } from \"./types\";\nimport { measureItem } from \"./item\";\n\ntype RunMeasure = Pick<FlowMeasure, \"sizes\" | \"lines\" | \"gapScales\" | \"hug\">;\n\n/**\n * Measures an unwrapped run, as one line: fixed items first, then `fill` items\n * share what is left of the main axis by `flex`.\n */\nexport function measureRun(\n items: readonly LayoutItem[],\n horizontal: boolean,\n gap: GapSize,\n space: FlowSpace,\n measurer: MeasureContext2D | undefined,\n): RunMeasure {\n const main = horizontal ? \"width\" : \"height\";\n const cross = horizontal ? \"height\" : \"width\";\n const hugsMain = (horizontal ? space.hugWidth : space.hugHeight) === true;\n const hugsCross = (horizontal ? space.hugHeight : space.hugWidth) === true;\n const bounded: SizeConstraints = { maxWidth: space.width, maxHeight: space.height };\n\n const n = items.length;\n const sizes: Size2D[] = new Array(n);\n const gapScales = items.map((item) => sanitizeGapScale(item.gapScale));\n // Weighted rather than a flat `n - 1`, so an item collapsing mid insert/remove\n // gives back exactly one gap wherever it sits. All weights 1 is `gap * (n - 1)`.\n const totalGap = gap === \"auto\" ? 0 : gap * Math.max(0, gapScales.reduce((sum, w) => sum + w, 0) - 1);\n\n // Fixed-main items first. On a hugging cross axis, `fill`-cross items wait:\n // what they fill is the deepest of these.\n let fixedMain = 0;\n let deepest = 0;\n for (let i = 0; i < n; i++) {\n if (items[i][main] === \"fill\" || (hugsCross && items[i][cross] === \"fill\")) continue;\n sizes[i] = measureItem(items[i], bounded, measurer);\n fixedMain += sizes[i][main];\n if (sizes[i][cross] > deepest) deepest = sizes[i][cross];\n }\n const fillCross = hugsCross ? deepest : space[cross];\n if (hugsCross) {\n for (let i = 0; i < n; i++) {\n if (items[i][main] === \"fill\" || items[i][cross] !== \"fill\") continue;\n const size = measureItem(items[i], bounded, measurer);\n sizes[i] = withCross(size, fillCross, horizontal);\n fixedMain += size[main];\n }\n }\n\n const free = Math.max(0, space[main] - totalGap - fixedMain);\n let flexSum = 0;\n for (const item of items) if (item[main] === \"fill\") flexSum += sanitizeFlex(item.flex);\n\n for (let i = 0; i < n; i++) {\n const item = items[i];\n if (item[main] !== \"fill\") continue;\n let share: number;\n let size: Size2D;\n if (hugsMain) {\n size = measureFillOnHugAxis(item, horizontal, space, measurer);\n share = size[main];\n } else {\n share = flexSum > 0 ? free * sanitizeFlex(item.flex) / flexSum : 0;\n size = measureItem(item, horizontal\n ? { maxWidth: share, maxHeight: space.height }\n : { maxWidth: space.width, maxHeight: share }, measurer);\n }\n const depth = item[cross] === \"fill\" ? fillCross : size[cross];\n sizes[i] = horizontal ? { width: share, height: depth } : { width: depth, height: share };\n }\n\n let extent = totalGap;\n let depth = 0;\n for (const size of sizes) {\n extent += size[main];\n if (size[cross] > depth) depth = size[cross];\n }\n return {\n sizes,\n lines: n > 0 ? [{ start: 0, end: n, cross: depth }] : [],\n gapScales,\n hug: horizontal ? { width: extent, height: depth } : { width: depth, height: extent },\n };\n}\n\n/**\n * A `fill`-main item on a main axis the container hugs. There is nothing to\n * share on such an axis — Figma disallows `fill` there — so the item measures\n * unconstrained along it, like a hug item. A bare `fill` leaf echoes that back as\n * Infinity, which would take the container's hug size with it; it collapses to 0\n * instead. Shared by {@link measureRun} and {@link measureWrap}, so a run hugs to\n * the same size whether or not it wraps.\n */\nfunction measureFillOnHugAxis(\n item: LayoutItem,\n horizontal: boolean,\n space: FlowSpace,\n measurer: MeasureContext2D | undefined,\n): Size2D {\n const size = measureItem(item, horizontal\n ? { maxWidth: Infinity, maxHeight: space.height }\n : { maxWidth: space.width, maxHeight: Infinity }, measurer);\n const main = horizontal ? \"width\" : \"height\";\n return Number.isFinite(size[main]) ? size : { ...size, [main]: 0 };\n}\n\n/**\n * Measures a wrapped run: every item at its natural size, broken greedily into\n * lines that fit the main axis. Two rules differ from {@link measureRun}, both\n * Figma's:\n *\n * - **A hugging main axis does not wrap** — there is nothing to break against.\n * - **`fill` on the main axis is not divided.** Which line an item lands on is\n * what this pass decides, so it measures to the whole main axis and takes a\n * line to itself. (On a hugging main axis there is no line to break and no\n * extent to fill, so it measures as {@link measureRun} measures it.)\n * Cross-axis `fill` stretches to its own line rather than the whole stack, the\n * only reading that survives a reflow.\n */\nexport function measureWrap(\n items: readonly LayoutItem[],\n horizontal: boolean,\n gap: GapSize,\n crossGap: number,\n space: FlowSpace,\n measurer: MeasureContext2D | undefined,\n): RunMeasure {\n const main = horizontal ? \"width\" : \"height\";\n const cross = horizontal ? \"height\" : \"width\";\n const hugsMain = (horizontal ? space.hugWidth : space.hugHeight) === true;\n const limit = hugsMain ? Infinity : space[main];\n // Flat, not gapScale-weighted: placement spaces the lines this breaks, and a\n // weighting across a break would put the two out of step. An animated insert\n // in a wrapped run slides instead of collapsing its gap.\n const step = gap === \"auto\" ? 0 : gap;\n const bounded: SizeConstraints = { maxWidth: space.width, maxHeight: space.height };\n // A `fill` item on a hugging main axis measures as it does unwrapped (see\n // `measureFillOnHugAxis`): the full extent is what a *bounded* axis offers it,\n // and a hugging one offers none.\n const sizes = items.map((item) => hugsMain && item[main] === \"fill\"\n ? measureFillOnHugAxis(item, horizontal, space, measurer)\n : measureItem(item, bounded, measurer));\n\n const lines: FlowLine[] = [];\n let widest = 0;\n let stack = 0;\n let start = 0;\n while (start < sizes.length) {\n // A line always takes at least one item, so an over-long one overflows its\n // own line rather than being pushed onto an empty one forever.\n let end = start + 1;\n let extent = sizes[start][main];\n while (end < sizes.length && extent + step + sizes[end][main] <= limit) {\n extent += step + sizes[end][main];\n end++;\n }\n // A line's thickness is its deepest item, not counting the ones that fill\n // the cross axis — what they fill is the answer being computed.\n let depth = 0;\n for (let i = start; i < end; i++) {\n if (items[i][cross] !== \"fill\" && sizes[i][cross] > depth) depth = sizes[i][cross];\n }\n for (let i = start; i < end; i++) {\n if (items[i][cross] === \"fill\") sizes[i] = withCross(sizes[i], depth, horizontal);\n }\n lines.push({ start, end, cross: depth });\n if (extent > widest) widest = extent;\n stack += depth;\n start = end;\n }\n stack += crossGap * Math.max(0, lines.length - 1);\n return {\n sizes,\n lines,\n gapScales: sizes.map(() => 1),\n hug: horizontal ? { width: widest, height: stack } : { width: stack, height: widest },\n };\n}\n\n/**\n * Places a run's lines in the content box, centre-relative and y-up. Positions\n * are worked out in reading order — from the main axis's start edge (left, or\n * top) and the cross axis's (top, or left) — and converted once, at the end.\n */\nexport function placeRun(\n sizes: readonly Size2D[],\n lines: readonly FlowLine[],\n gapScales: readonly number[],\n horizontal: boolean,\n gap: GapSize,\n crossGap: number,\n align: Vector2,\n inner: Size2D,\n): BoxBounds[] {\n const main = horizontal ? \"width\" : \"height\";\n const cross = horizontal ? \"height\" : \"width\";\n // `align` is y-up and a run reads top-down, so y's fraction is flipped.\n const mainFraction = horizontal ? (1 + align.x) / 2 : (1 - align.y) / 2;\n const crossFraction = horizontal ? (1 - align.y) / 2 : (1 + align.x) / 2;\n\n let stack = crossGap * Math.max(0, lines.length - 1);\n for (const line of lines) stack += line.cross;\n let lineStart = crossFraction * (inner[cross] - stack);\n\n const boxes: BoxBounds[] = new Array(sizes.length);\n for (const line of lines) {\n const count = line.end - line.start;\n let extent = 0;\n let weight = 0;\n for (let i = line.start; i < line.end; i++) {\n extent += sizes[i][main];\n weight += gapScales[i];\n }\n\n let gapAfter: (i: number) => number;\n let lead = 0;\n if (gap === \"auto\") {\n // Spread within each line, so a short last line is as loose as the full ones.\n const spread = count > 1 ? Math.max(0, inner[main] - extent) / (count - 1) : 0;\n gapAfter = () => spread;\n extent += spread * (count - 1);\n } else {\n // A boundary takes the mean of its neighbours' weights, so the run spans\n // `gap * (Σweight − 1)` — what measureRun reserved. That leaves half a gap\n // over for a collapsing first item, which hangs before the visible run so\n // the content edge holds still at any alignment.\n const weightAt = (i: number): number => (i < line.end ? gapScales[i] : 1);\n gapAfter = (i) => gap * (gapScales[i] + weightAt(i + 1)) / 2;\n extent += gap * Math.max(0, weight - 1);\n lead = gap * (1 - gapScales[line.start]) / 2;\n }\n\n let at = mainFraction * (inner[main] - extent) - lead;\n for (let i = line.start; i < line.end; i++) {\n const size = sizes[i];\n const across = lineStart + crossFraction * (line.cross - size[cross]);\n boxes[i] = fromReadingOrder(horizontal ? at : across, horizontal ? across : at, size, inner);\n at += size[main] + gapAfter(i);\n }\n lineStart += line.cross + crossGap;\n }\n return boxes;\n}\n\n// From a top-left corner in the content box (y-down) to the content box's centre, y-up.\nfunction fromReadingOrder(left: number, top: number, size: Size2D, inner: Size2D): BoxBounds {\n return {\n x: left + size.width / 2 - inner.width / 2,\n y: inner.height / 2 - top - size.height / 2,\n width: size.width,\n height: size.height,\n };\n}\n\nfunction withCross(size: Size2D, depth: number, horizontal: boolean): Size2D {\n return horizontal ? { width: size.width, height: depth } : { width: depth, height: size.height };\n}\n\nfunction sanitizeFlex(value: number | undefined): number {\n if (value == null) return 1;\n return Number.isFinite(value) && value >= 0 ? value : 1;\n}\n\n// Clamped so an eased tween overshooting 0 ↔ 1 can't push a gap negative or past full.\nfunction sanitizeGapScale(value: number | undefined): number {\n if (value == null) return 1;\n return Number.isFinite(value) ? clamp(value, 0, 1) : 1;\n}\n", "import type { Size2D } from \"@/attributes/layout/size\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport type { BoxBounds } from \"./bounds\";\nimport type { FlowSpace, LayoutItem } from \"./types\";\nimport { measureItem } from \"./item\";\n\n/** Every item measured against the whole content box; the content is the largest of them. */\nexport function measureFreeform(\n items: readonly LayoutItem[],\n space: FlowSpace,\n measurer: MeasureContext2D | undefined,\n): { sizes: Size2D[]; hug: Size2D } {\n const constraints = { maxWidth: space.width, maxHeight: space.height };\n const sizes: Size2D[] = [];\n const hug = { width: 0, height: 0 };\n for (const item of items) {\n const size = measureItem(item, constraints, measurer);\n sizes.push(size);\n if (size.width > hug.width) hug.width = size.width;\n if (size.height > hug.height) hug.height = size.height;\n }\n return { sizes, hug };\n}\n\n/**\n * Each item aligned in the content box, centre-relative and y-up. Slack is\n * clamped at 0, so an item larger than the box stays centred on it.\n */\nexport function placeFreeform(sizes: readonly Size2D[], inner: Size2D, align: Vector2): BoxBounds[] {\n return sizes.map((size) => ({\n x: align.x * Math.max(0, inner.width - size.width) / 2,\n y: align.y * Math.max(0, inner.height - size.height) / 2,\n width: size.width,\n height: size.height,\n }));\n}\n", "import type { Size2D } from \"@/attributes/layout/size\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport type { BoxBounds } from \"./bounds\";\nimport type { SizeConstraints } from \"./constraints\";\nimport type { FlowSpace, LayoutItem } from \"./types\";\nimport { measureItem } from \"./item\";\n\n/**\n * Measures a grid: `columns` equal tracks across the width, and rows sized to\n * their content — or, when the height is bounded, divided equally so a\n * `fill`-height item has a share to fill. Each item's cell comes back from the\n * content box's top-left, y-down.\n */\nexport function measureGrid(\n items: readonly LayoutItem[],\n columns: number,\n columnGap: number,\n rowGap: number,\n space: FlowSpace,\n measurer: MeasureContext2D | undefined,\n): { sizes: Size2D[]; cells: BoxBounds[]; hug: Size2D } {\n const count = Math.max(1, Math.round(columns));\n const track = Math.max(0, (space.width - columnGap * (count - 1)) / count);\n const placements = autoPlace(items, count);\n const rowCount = placements.reduce((max, p) => Math.max(max, p.row + p.rowSpan), 0);\n\n const bounded = space.hugHeight !== true && rowCount > 0;\n const equalRow = bounded ? Math.max(0, (space.height - rowGap * (rowCount - 1)) / rowCount) : 0;\n const rows = new Array<number>(rowCount).fill(equalRow);\n\n const sizes = items.map((item, i) => {\n const p = placements[i];\n const width = span(track, p.colSpan, columnGap);\n const constraints: SizeConstraints = bounded\n ? { maxWidth: width, maxHeight: span(equalRow, p.rowSpan, rowGap) }\n : { maxWidth: width };\n const size = measureItem(item, constraints, measurer);\n // Bounded rows are already equal, and content may not grow one past its share.\n if (!bounded) grow(rows, p.row, p.rowSpan, size.height, rowGap);\n return size;\n });\n\n const tops: number[] = [];\n let top = 0;\n for (const height of rows) {\n tops.push(top);\n top += height + rowGap;\n }\n const cells = placements.map((p) => ({\n x: p.col * (track + columnGap),\n y: tops[p.row] ?? 0,\n width: span(track, p.colSpan, columnGap),\n height: spannedRows(rows, p.row, p.rowSpan, rowGap),\n }));\n const height = rows.reduce((sum, h) => sum + h, 0) + rowGap * Math.max(0, rowCount - 1);\n return { sizes, cells, hug: { width: space.width, height } };\n}\n\n/** Each item's cell, clamped to the content box, centre-relative and y-up. */\nexport function placeGrid(cells: readonly BoxBounds[], inner: Size2D): BoxBounds[] {\n return cells.map((cell) => ({\n x: cell.x + cell.width / 2 - inner.width / 2,\n y: inner.height / 2 - cell.y - cell.height / 2,\n width: Math.min(cell.width, inner.width),\n height: Math.min(cell.height, inner.height),\n }));\n}\n\n// Left to right, wrapping when a span would overflow the columns. An item with\n// both `column` and `row` is placed there, 1-based, and left out of the flow.\nfunction autoPlace(items: readonly LayoutItem[], columns: number) {\n const placements: { col: number; row: number; colSpan: number; rowSpan: number }[] = [];\n const taken: boolean[][] = [];\n const isFree = (row: number, col: number, colSpan: number, rowSpan: number): boolean => {\n for (let r = 0; r < rowSpan; r++) {\n for (let c = 0; c < colSpan; c++) {\n if (taken[row + r]?.[col + c]) return false;\n }\n }\n return true;\n };\n const take = (row: number, col: number, colSpan: number, rowSpan: number): void => {\n for (let r = 0; r < rowSpan; r++) {\n taken[row + r] ??= [];\n for (let c = 0; c < colSpan; c++) taken[row + r][col + c] = true;\n }\n };\n\n let row = 0;\n let col = 0;\n for (const item of items) {\n const colSpan = Math.min(item.colSpan ?? 1, columns);\n const rowSpan = item.rowSpan ?? 1;\n if (item.column !== undefined && item.row !== undefined) {\n take(item.row - 1, item.column - 1, colSpan, rowSpan);\n placements.push({ col: item.column - 1, row: item.row - 1, colSpan, rowSpan });\n continue;\n }\n for (;;) {\n if (col + colSpan > columns) {\n row++;\n col = 0;\n }\n if (isFree(row, col, colSpan, rowSpan)) break;\n col++;\n }\n take(row, col, colSpan, rowSpan);\n placements.push({ col, row, colSpan, rowSpan });\n col += colSpan;\n }\n return placements;\n}\n\n// Content-sized rows grow to fit an item; a spanning item puts whatever its rows\n// are short of into the first of them.\nfunction grow(rows: number[], row: number, rowSpan: number, height: number, gap: number): void {\n if (rowSpan === 1) {\n if (height > rows[row]) rows[row] = height;\n return;\n }\n const short = height - spannedRows(rows, row, rowSpan, gap);\n if (short > 0) rows[row] += short;\n}\n\nfunction span(track: number, count: number, gap: number): number {\n return track * count + gap * (count - 1);\n}\n\nfunction spannedRows(rows: readonly number[], from: number, count: number, gap: number): number {\n let height = gap * (count - 1);\n for (let r = from; r < from + count; r++) height += rows[r] ?? 0;\n return height;\n}\n", "/**\n * Every layout operation, on one object — for the node tree, and for anything a\n * node lays out itself, like a row of `Graphics2D` shapes inside `renderSelf`.\n *\n * It takes plain data and returns boxes, and writes to nothing it is handed: a\n * node keeps its own measure between passes. Its `resolve`/`lerp` pair is the\n * `flow` prop's, which is how a tween between two modes lives in the prop's value\n * and a seek that restores the prop restores the blend with it.\n *\n * Boxes are centred on the content box and y-up — the space `Graphics2D` draws\n * in. `Node2D` converts once, where it hands a box to a child.\n *\n * Each method is the module function of the same name.\n */\nimport { alignmentOps } from \"@/attributes/layout/alignment\";\nimport { insetsOps, type InsetsResolved } from \"@/attributes/layout/insets\";\nimport { sizeInputOps, type Size2D, type SizeInput } from \"@/attributes/layout/size\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { AttributeOps } from \"@/attributes/shared/operators\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport { lerpNumber } from \"@/tween/lerp\";\nimport type { BoxBounds } from \"./bounds\";\nimport type { SizeConstraints } from \"./constraints\";\nimport { measureRun, measureWrap, placeRun } from \"./flex\";\nimport { measureFreeform, placeFreeform } from \"./freeform\";\nimport { measureGrid, placeGrid } from \"./grid\";\nimport type { FlowMeasure, FlowMode, FlowResolved, FlowSettings, FlowSpace, LayoutItem } from \"./types\";\n\n/** The `flow` attribute's operations beyond `resolve`/`lerp`. */\nexport interface FlowOps {\n // ── Arranging ──────────────────────────────────────────────────────────\n /**\n * Lay `items` out in a box of `box`'s size, inset by `settings.padding`.\n * Boxes come back centred on `box` and y-up. Pass a `measurer` when an item\n * measures text.\n */\n arrange<I extends LayoutItem>(\n settings: FlowSettings, items: readonly I[], box: Size2D, measurer?: MeasureContext2D,\n ): BoxBounds[];\n /** The first half of `arrange`: each item's size, and the extent a hugging container wraps. */\n measure<I extends LayoutItem>(\n settings: FlowSettings, items: readonly I[], space: FlowSpace, measurer?: MeasureContext2D,\n ): FlowMeasure<I>;\n /** The second half: each item's box in a content box of `inner`'s size. */\n place(measure: FlowMeasure, settings: FlowSettings, inner: Size2D): BoxBounds[];\n /** Whether `measure` still holds for a content box of `inner`'s size. */\n reusable(measure: FlowMeasure, inner: Size2D): boolean;\n /**\n * Where `settings` would put one more item of `size` in a content box of\n * `inner`'s size, centred and y-up like `place`; `null` when they arrange\n * their items in a run or a grid, where the slot depends on the others.\n */\n freeSlot(settings: FlowSettings, inner: Size2D, size: Size2D): BoxBounds | null;\n\n // ── Sizing a container ─────────────────────────────────────────────────\n /** The content box a `width` × `height` container measures its items in. */\n contentBox(\n sizing: Pick<LayoutItem, \"width\" | \"height\">, constraints: SizeConstraints, padding: InsetsResolved,\n ): FlowSpace;\n /** The container's own size, given the `hug` extent its items came to. */\n size(\n sizing: Pick<LayoutItem, \"width\" | \"height\">, constraints: SizeConstraints, padding: InsetsResolved, hug: Size2D,\n ): Size2D;\n\n // ── Diagnostics ────────────────────────────────────────────────────────\n /** What is wrong with a run laid out in a box of `box`'s size, or `null`. */\n collapsedRun(measure: FlowMeasure, box: Size2D): string | null;\n}\n\nconst CENTRE: Vector2 = { x: 0, y: 0 };\n\nfunction arrange<I extends LayoutItem>(\n settings: FlowSettings, items: readonly I[], box: Size2D, measurer?: MeasureContext2D,\n): BoxBounds[] {\n const inner = insetsOps.insetBounds(box.width, box.height, insetsOps.resolve(settings.padding ?? 0));\n const boxes = place(measure(settings, items, inner, measurer), settings, inner);\n // `insetBounds` offsets the content box y-down; the boxes are y-up.\n return boxes.map((b) => ({ x: b.x + inner.x, y: b.y - inner.y, width: b.width, height: b.height }));\n}\n\nfunction measure<I extends LayoutItem>(\n settings: FlowSettings, items: readonly I[], space: FlowSpace, measurer?: MeasureContext2D,\n): FlowMeasure<I> {\n const flow = settings.flow ?? \"freeform\";\n if (typeof flow === \"string\") return measureMode(flow, settings, items, space, measurer);\n const from = measureMode(flow.from, settings, items, space, measurer);\n const to = measureMode(flow.to, settings, items, space, measurer);\n return { ...to, hug: lerpSize(from.hug, to.hug, flow.t), from, t: flow.t };\n}\n\nfunction place(measure: FlowMeasure, settings: FlowSettings, inner: Size2D): BoxBounds[] {\n const to = placeMode(measure, settings, inner);\n const from = measure.from;\n if (!from) return to;\n const fromBoxes = placeMode(from, settings, inner);\n const t = measure.t ?? 1;\n return to.map((box, i) => ({\n x: lerpNumber(fromBoxes[i].x, box.x, t),\n y: lerpNumber(fromBoxes[i].y, box.y, t),\n width: lerpNumber(fromBoxes[i].width, box.width, t),\n height: lerpNumber(fromBoxes[i].height, box.height, t),\n }));\n}\n\n// Yoga's rule: reuse on an axis laid out at the size it was measured in, or — on\n// an axis that hugs — at exactly what it hugged. Anything else, a parent laid this\n// out at a size it did not measure it for, and the measure is stale.\nfunction reusable(measure: FlowMeasure, inner: Size2D): boolean {\n const { space, hug } = measure;\n return fits(inner.width, space.width, space.hugWidth, hug.width)\n && fits(inner.height, space.height, space.hugHeight, hug.height);\n}\n\nfunction contentBox(\n sizing: Pick<LayoutItem, \"width\" | \"height\">, constraints: SizeConstraints, padding: InsetsResolved,\n): FlowSpace {\n const width = outerFor(sizing.width, constraints.maxWidth);\n const height = outerFor(sizing.height, constraints.maxHeight);\n const inner = insetsOps.insetBounds(width, height, padding);\n return {\n width: inner.width,\n height: inner.height,\n hugWidth: sizing.width === \"hug\",\n hugHeight: sizing.height === \"hug\",\n };\n}\n\nfunction size(\n sizing: Pick<LayoutItem, \"width\" | \"height\">, constraints: SizeConstraints, padding: InsetsResolved, hug: Size2D,\n): Size2D {\n const hugged = insetsOps.outsetSize(hug.width, hug.height, padding);\n return {\n width: sizing.width === \"hug\" ? hugged.width : outerFor(sizing.width, constraints.maxWidth),\n height: sizing.height === \"hug\" ? hugged.height : outerFor(sizing.height, constraints.maxHeight),\n };\n}\n\n/**\n * A run laid out in a box of length 0 on its main axis, with items that have a\n * size. Always a bug, and a quiet one: a run is placed from the box's centre, so\n * its first item's leading edge lands on the centre and everything after follows —\n * content displaced by half a box it does not visibly have, which reads as \"the\n * scene loaded at 0,0\" rather than as a layout fault. A box holding only collapsed\n * items is legitimately empty: an animated insert or remove mid-flight.\n */\nfunction collapsedRun(measure: FlowMeasure, box: Size2D): string | null {\n if (measure.mode !== \"horizontal\" && measure.mode !== \"vertical\") return null;\n if ((measure.mode === \"horizontal\" ? box.width : box.height) > 0) return null;\n const sized = measure.sizes.filter((s) => s.width > 0 || s.height > 0).length;\n if (sized === 0) return null;\n return `is laying out ${sized} sized child${sized === 1 ? \"\" : \"ren\"} in a run of length 0 `\n + `(${box.width}×${box.height}, ${measure.mode}). `\n + `They will be positioned from its centre rather than its leading edge.`;\n}\n\n// A `from` that is itself a blend — a tween built mid-blend — starts from where it was heading.\nfunction lerp(from: FlowResolved, to: FlowResolved, t: number): FlowResolved {\n const a = typeof from === \"string\" ? from : from.to;\n const b = typeof to === \"string\" ? to : to.to;\n return t >= 1 || a === b ? b : { from: a, to: b, t };\n}\n\nfunction measureMode<I extends LayoutItem>(\n mode: FlowMode, settings: FlowSettings, items: readonly I[], space: FlowSpace, measurer: MeasureContext2D | undefined,\n): FlowMeasure<I> {\n if (mode === \"freeform\") return { mode, items, space, ...measureFreeform(items, space, measurer) };\n if (mode === \"grid\") {\n const grid = measureGrid(items, settings.columns ?? 1, mainGap(settings), crossGap(settings), space, measurer);\n return { mode, items, space, ...grid };\n }\n const horizontal = mode === \"horizontal\";\n const run = settings.wrap\n ? measureWrap(items, horizontal, settings.gap ?? 0, crossGap(settings), space, measurer)\n : measureRun(items, horizontal, settings.gap ?? 0, space, measurer);\n return { mode, items, space, ...run };\n}\n\nfunction placeMode(measure: FlowMeasure, settings: FlowSettings, inner: Size2D): BoxBounds[] {\n if (measure.mode === \"grid\") return placeGrid(measure.cells ?? [], inner);\n const align = alignOf(settings);\n if (measure.mode === \"freeform\") return placeFreeform(measure.sizes, inner, align);\n return placeRun(\n measure.sizes, measure.lines ?? [], measure.gapScales ?? [], measure.mode === \"horizontal\",\n settings.gap ?? 0, crossGap(settings), align, inner,\n );\n}\n\nfunction freeSlot(settings: FlowSettings, inner: Size2D, size: Size2D): BoxBounds | null {\n if ((settings.flow ?? \"freeform\") !== \"freeform\") return null;\n return placeFreeform([size], inner, alignOf(settings))[0];\n}\n\n// A container stores `align` resolved, so only a named key needs resolving here.\nfunction alignOf(settings: FlowSettings): Vector2 {\n const align = settings.align;\n if (align === undefined) return CENTRE;\n return typeof align === \"string\" ? alignmentOps.resolve(align) : align;\n}\n\nfunction mainGap(settings: FlowSettings): number {\n const gap = settings.gap ?? 0;\n return gap === \"auto\" ? 0 : gap;\n}\n\nfunction crossGap(settings: FlowSettings): number {\n return settings.crossGap ?? mainGap(settings);\n}\n\n// A hugging axis measures its items against all the room it could have.\nfunction outerFor(input: SizeInput, max: number | undefined): number {\n const available = max ?? 0;\n return input === \"hug\" ? available : sizeInputOps.resolveLayout(input, available, 0);\n}\n\nfunction lerpSize(from: Size2D, to: Size2D, t: number): Size2D {\n return { width: lerpNumber(from.width, to.width, t), height: lerpNumber(from.height, to.height, t) };\n}\n\nfunction fits(laid: number, measured: number, hugs: boolean | undefined, hugged: number): boolean {\n return near(laid, measured) || (hugs === true && near(laid, hugged));\n}\n\nfunction near(a: number, b: number): boolean {\n if (a === b) return true;\n if (!Number.isFinite(a) || !Number.isFinite(b)) return false;\n return Math.abs(a - b) <= 1e-6 * Math.max(1, Math.abs(a), Math.abs(b));\n}\n\nexport const flowOps: AttributeOps<FlowMode, FlowResolved> & FlowOps = {\n resolve: (value) => value,\n lerp,\n\n arrange,\n measure,\n place,\n reusable,\n freeSlot,\n\n contentBox,\n size,\n\n collapsedRun,\n};\n", "import { lerpNumber } from \"@/tween/lerp\";\nimport type { AttributeOps } from \"@/attributes/shared/operators\";\n\n/**\n * A 3D point or offset. The 3D counterpart to core's {@link Vector2}\n * (`attributes/layout/vector2.ts`), kept structurally identical so the same\n * plain-object idiom works in both dimensions.\n */\nexport interface Vector3 {\n x: number;\n y: number;\n z: number;\n}\n\n/**\n * Loose forms accepted anywhere a {@link Vector3} is expected:\n *\n * - an object — `{ x: 1, y: 2, z: 3 }`\n * - a 3-tuple — `[1, 2, 3]`\n * - a scalar, broadcast to all three axes — `0` means the origin, `2` means\n * `{ x: 2, y: 2, z: 2 }` (handy for uniform scale and `lookAt: 0`)\n */\nexport type Vector3Input = Vector3 | readonly [number, number, number] | number;\n\nconst ZERO: Vector3 = { x: 0, y: 0, z: 0 };\n\n/** Normalize any {@link Vector3Input} to a concrete {@link Vector3}. */\nexport function resolveVector3(input: Vector3Input | undefined): Vector3 {\n if (input === undefined) return { ...ZERO };\n if (typeof input === \"number\") return { x: input, y: input, z: input };\n if (Array.isArray(input)) return { x: input[0] ?? 0, y: input[1] ?? 0, z: input[2] ?? 0 };\n const v = input as Vector3;\n return { x: v.x ?? 0, y: v.y ?? 0, z: v.z ?? 0 };\n}\n\n/**\n * Component-wise lerp between two positions. `t=0` returns `from`, `t=1`\n * returns `to`.\n *\n * Pass this as a prop's `tween` so 3D vectors actually animate:\n * `property({ default: …, tween: lerpVector3 })` — or a `Types.vector3` entry,\n * which carries it already. Without one `to()` **leaves the prop alone**, having\n * nothing to interpolate two vectors with.\n */\nexport function lerpVector3(from: Vector3, to: Vector3, t: number): Vector3 {\n return {\n x: lerpNumber(from.x, to.x, t),\n y: lerpNumber(from.y, to.y, t),\n z: lerpNumber(from.z, to.z, t),\n };\n}\n\n/** The `Vector3` attribute's op set — a 3D position or scale. */\nexport const vector3Ops: AttributeOps<Vector3Input, Vector3> = {\n resolve: (value) => resolveVector3(value),\n lerp: lerpVector3,\n};\n\n/**\n * Map an optional {@link Vector3Input}: an unset prop stays unset (a thunk that\n * returns `undefined` included) instead of resolving to the origin, which would\n * turn \"no aim\" into \"aim at the origin\".\n */\nexport function resolveOptionalVector3(input: Vector3Input | undefined): Vector3 | undefined {\n return input === undefined ? undefined : resolveVector3(input);\n}\n\n/**\n * Lerp for a vector prop that may be unset — a node's `lookAt`, a camera's or\n * light's `target`.\n *\n * With no start value there is nothing to blend from. `unset: \"origin\"` treats it\n * as the origin, which is what the renderer uses for `target`; `unset: \"snap\"`\n * holds it unset and swaps at the end, which is the only honest reading for\n * `lookAt` (an unset `lookAt` is \"do not aim\", not \"aim at the origin\"). A `to`\n * that ends unset leaves the start value in place, as every other prop does.\n */\nexport function lerpOptionalVector3(\n from: Vector3 | undefined,\n to: Vector3 | undefined,\n t: number,\n unset: \"origin\" | \"snap\",\n): Vector3 | undefined {\n if (to === undefined) return from;\n if (from !== undefined) return lerpVector3(from, to, t);\n if (unset === \"origin\") return lerpVector3(ZERO, to, t);\n return t >= 1 ? to : from;\n}\n\n/** The order Euler angles are applied in. Matches three's own naming. */\nexport type EulerOrder = \"XYZ\" | \"YXZ\" | \"ZXY\" | \"ZYX\" | \"YZX\" | \"XZY\";\n\n/**\n * An Euler rotation in **degrees**, to match the engine's 2D `rotation`.\n * The renderer converts to radians — authors never write `Math.PI`.\n */\nexport interface Euler3 extends Vector3 {\n order?: EulerOrder;\n}\n\n/**\n * Component-wise lerp of two Euler rotations, in degrees. `order` is discrete,\n * so it snaps at the halfway point rather than blending.\n *\n * Euler interpolation gimbals near the poles and takes the \"wrong\" path for\n * rotations past 180°. For a tumble, hold a {@link Quaternion} prop and use\n * {@link slerpQuaternion} instead.\n */\nexport function lerpEuler3(from: Euler3, to: Euler3, t: number): Euler3 {\n return {\n x: lerpNumber(from.x, to.x, t),\n y: lerpNumber(from.y, to.y, t),\n z: lerpNumber(from.z, to.z, t),\n order: t < 0.5 ? from.order : to.order,\n };\n}\n\n/** The `Euler3` attribute's op set — a rotation in degrees, per axis. */\nexport const euler3Ops: AttributeOps<Vector3Input | Euler3, Euler3> = {\n resolve: (input) => {\n const v = resolveVector3(input as Vector3Input);\n const order = (input as Euler3)?.order;\n return order ? { ...v, order } : v;\n },\n lerp: lerpEuler3,\n};\n\n/** A rotation as a unit quaternion. */\nexport interface Quaternion {\n x: number;\n y: number;\n z: number;\n w: number;\n}\n\n/** The identity rotation. */\nexport const IDENTITY_QUATERNION: Quaternion = { x: 0, y: 0, z: 0, w: 1 };\n\n/**\n * Shortest-arc spherical linear interpolation — the correct tween for a\n * quaternion. A component-wise lerp is *not* correct: it leaves the unit\n * hypersphere, so the rotation speed varies and the result needs renormalizing.\n *\n * Negates `to` when the pair points away from each other (`dot < 0`) so the\n * rotation always takes the short way round; falls back to a normalized linear\n * blend when the two are nearly parallel and `sin(theta)` would underflow.\n */\nexport function slerpQuaternion(from: Quaternion, to: Quaternion, t: number): Quaternion {\n let { x, y, z, w } = to;\n let dot = from.x * x + from.y * y + from.z * z + from.w * w;\n\n // Both q and -q describe the same rotation; pick the nearer representative.\n if (dot < 0) {\n x = -x; y = -y; z = -z; w = -w;\n dot = -dot;\n }\n\n // Nearly parallel — slerp's sin(theta) denominator underflows, and a linear\n // blend is indistinguishable at this angle anyway.\n if (dot > 0.9995) {\n return normalizeQuaternion({\n x: lerpNumber(from.x, x, t),\n y: lerpNumber(from.y, y, t),\n z: lerpNumber(from.z, z, t),\n w: lerpNumber(from.w, w, t),\n });\n }\n\n const theta = Math.acos(dot);\n const sinTheta = Math.sin(theta);\n const a = Math.sin((1 - t) * theta) / sinTheta;\n const b = Math.sin(t * theta) / sinTheta;\n\n return {\n x: from.x * a + x * b,\n y: from.y * a + y * b,\n z: from.z * a + z * b,\n w: from.w * a + w * b,\n };\n}\n\n/** Scale a quaternion back to unit length. Returns identity for a zero quat. */\nexport function normalizeQuaternion(q: Quaternion): Quaternion {\n const length = Math.hypot(q.x, q.y, q.z, q.w);\n if (length === 0) return { ...IDENTITY_QUATERNION };\n return { x: q.x / length, y: q.y / length, z: q.z / length, w: q.w / length };\n}\n\n/** Convert an {@link Euler3} (degrees) to a {@link Quaternion}. */\nexport function quaternionFromEuler(euler: Euler3): Quaternion {\n const half = Math.PI / 360; // deg → rad, then halved for the half-angle form\n const cx = Math.cos(euler.x * half), sx = Math.sin(euler.x * half);\n const cy = Math.cos(euler.y * half), sy = Math.sin(euler.y * half);\n const cz = Math.cos(euler.z * half), sz = Math.sin(euler.z * half);\n\n switch (euler.order ?? \"XYZ\") {\n case \"YXZ\":\n return {\n x: sx * cy * cz + cx * sy * sz,\n y: cx * sy * cz - sx * cy * sz,\n z: cx * cy * sz - sx * sy * cz,\n w: cx * cy * cz + sx * sy * sz,\n };\n case \"ZXY\":\n return {\n x: sx * cy * cz - cx * sy * sz,\n y: cx * sy * cz + sx * cy * sz,\n z: cx * cy * sz + sx * sy * cz,\n w: cx * cy * cz - sx * sy * sz,\n };\n case \"ZYX\":\n return {\n x: sx * cy * cz - cx * sy * sz,\n y: cx * sy * cz + sx * cy * sz,\n z: cx * cy * sz - sx * sy * cz,\n w: cx * cy * cz + sx * sy * sz,\n };\n case \"YZX\":\n return {\n x: sx * cy * cz + cx * sy * sz,\n y: cx * sy * cz + sx * cy * sz,\n z: cx * cy * sz - sx * sy * cz,\n w: cx * cy * cz - sx * sy * sz,\n };\n case \"XZY\":\n return {\n x: sx * cy * cz - cx * sy * sz,\n y: cx * sy * cz - sx * cy * sz,\n z: cx * cy * sz + sx * sy * cz,\n w: cx * cy * cz + sx * sy * sz,\n };\n case \"XYZ\":\n default:\n return {\n x: sx * cy * cz + cx * sy * sz,\n y: cx * sy * cz - sx * cy * sz,\n z: cx * cy * sz + sx * sy * cz,\n w: cx * cy * cz - sx * sy * sz,\n };\n }\n}\n\n/** The `Quaternion` attribute's op set: resolve is the identity, lerp shortest-arc slerps. */\nexport const quaternionOps: AttributeOps<Quaternion, Quaternion> = {\n resolve: (value) => value,\n lerp: slerpQuaternion,\n};\n", "import type { RectState } from \"./descriptors/rect\";\nimport type { EllipseState } from \"./descriptors/ellipse\";\nimport type { PathState } from \"./descriptors/path\";\nimport type { LineState } from \"./descriptors/line\";\nimport type { PolygonState } from \"./descriptors/polygon\";\nimport type { PolygramState } from \"./descriptors/polygram\";\nimport type { ShapeAlignmentInput } from \"./descriptors/shape\";\nimport { PathBuilder } from \"./descriptors/path-builder\";\n\n/**\n * The shape ops a {@link Clip} can record — the same geometry primitives a\n * {@link Graphics2D} can draw, minus text/image (which have no clippable outline).\n * Each carries the partial descriptor state for that shape.\n */\nexport type ClipShapeOp =\n | { kind: \"rect\"; state: Partial<RectState> & ShapeAlignmentInput }\n | { kind: \"ellipse\"; state: Partial<EllipseState> & ShapeAlignmentInput }\n | { kind: \"path\"; state: Partial<PathState> }\n | { kind: \"line\"; state: Partial<LineState> }\n | { kind: \"polygon\"; state: Partial<PolygonState> & ShapeAlignmentInput }\n | { kind: \"polygram\"; state: Partial<PolygramState> & ShapeAlignmentInput };\n\n/**\n * A single recorded op in a {@link Clip}. Shape ops add geometry to the clip\n * region; `cut` subtracts the last-declared shape from the ones before it. The\n * renderer replays this list into a single clip path via\n * `RenderContext2D.beginClip()`.\n */\nexport type ClipOp = ClipShapeOp | { kind: \"cut\" };\n\n/**\n * A renderer-agnostic, chainable clip-region builder — `Graphics2D` for clipping.\n *\n * `Clip` records a sequence of shape declarations (and optional `cut()`s) that\n * the renderer unions into a single clip path. Multiple shapes combine, so a\n * clip can be any compound silhouette, not just a single rect or ellipse:\n *\n * const c = new Clip()\n * .rect({ width: 200, height: 120, cornerRadius: 16 })\n * .ellipse({ x: 80, width: 60, height: 60 }) // unions with the rect\n * .ellipse({ x: -80, width: 40, height: 40 })\n * .cut(); // punches the last hole\n * ctx.beginClip(c);\n * ...draw clipped content...\n * ctx.endClip();\n *\n * A `Clip` carries no paint — it's purely the outline. It's what a shape\n * returns from `clipSelf()` to describe both its `clip` boundary and the\n * silhouette its backdrop effects (blur, magnify, …) are confined to, so a\n * single definition drives every clip the node needs.\n */\nexport class Clip {\n private _ops: ClipOp[] = [];\n\n // ─── Shapes ──────────────────────────────────────────────────────────────\n\n rect(state: Partial<RectState> & ShapeAlignmentInput): this {\n this._ops.push({ kind: \"rect\", state });\n return this;\n }\n\n ellipse(state: Partial<EllipseState> & ShapeAlignmentInput): this {\n this._ops.push({ kind: \"ellipse\", state });\n return this;\n }\n\n /** Add a vector path to the clip region, from a `PathState` or a `PathBuilder`. */\n path(state: Partial<PathState> | PathBuilder): this {\n const resolved = state instanceof PathBuilder ? state.toPathState() : state;\n this._ops.push({ kind: \"path\", state: resolved });\n return this;\n }\n\n line(state: Partial<LineState>): this {\n this._ops.push({ kind: \"line\", state });\n return this;\n }\n\n polygon(state: Partial<PolygonState> & ShapeAlignmentInput): this {\n this._ops.push({ kind: \"polygon\", state });\n return this;\n }\n\n polygram(state: Partial<PolygramState> & ShapeAlignmentInput): this {\n this._ops.push({ kind: \"polygram\", state });\n return this;\n }\n\n // ─── Compositing ─────────────────────────────────────────────────────────\n\n /**\n * Use the last-declared shape as a cutter: union the shapes before it and\n * subtract that last shape, punching a hole in the clip region. Mirrors\n * {@link Graphics2D.cut}.\n */\n cut(): this {\n this._ops.push({ kind: \"cut\" });\n return this;\n }\n\n // ─── Consumption ─────────────────────────────────────────────────────────\n\n /** The recorded ops, in order. Consumed by `RenderContext2D.beginClip()`. */\n ops(): readonly ClipOp[] {\n return this._ops;\n }\n\n /** True when no shape op has been recorded — the clip region is empty. */\n isEmpty(): boolean {\n return !this._ops.some((op) => op.kind !== \"cut\");\n }\n}\n", "import { TweenFn } from \"@/props/host\";\nimport { property } from \"./decorator\";\n\nimport { type Fill } from \"@/attributes/shape/fill/chain\";\nimport { FillResolved } from \"@/attributes/shape/fill/union\";\nimport { fillOps } from \"@/attributes/shape/fill/registry\";\n\nimport { type Effect, effectsOps } from \"@/attributes/shape/effects/chain\";\nimport { NodeEffect } from \"@/attributes/shape/effects/union\";\n\nimport { Insets, InsetsResolved, insetsOps } from \"@/attributes/layout/insets\";\nimport { Alignment, alignmentOps } from \"@/attributes/layout/alignment\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport { flowOps } from \"@/layout/ops\";\nimport type { FlowMode, FlowResolved } from \"@/layout/types\";\n\nimport { type AudioEffectsInput } from \"@/attributes/audio/effects/chain\";\nimport { audioEffectsOps } from \"@/attributes/audio/effects/registry\";\nimport { AudioEffect } from \"@/attributes/audio/effects/union\";\nimport { type Param, audioParamOps } from \"@/attributes/audio/ramp\";\n\nimport {\n quaternionOps, lerpOptionalVector3, resolveOptionalVector3,\n type Quaternion, type Vector3, type Vector3Input,\n} from \"@/render3d/vector3\";\n\n/**\n * Attribute-typed variants of `property`, for the props the tree bases declare\n * themselves (`Node2D`, `Node3D`, `NodeAudio`, the root `Canvas2D`).\n *\n * A rich attribute (a fill, an effect chain, an inset) is only declarative and\n * tweenable because its `property` carries the matching *mapper* (loose author\n * input → resolved value) and *tween* (how the resolved value interpolates) —\n * together, an `AttributeOps` (`attributes/shared/operators.ts`). These pre-bake\n * each pair: `fillProperty()` is exactly\n * `property({ default: [], mapper: fillOps.resolve, tween: fillOps.lerp, kind: \"fills\" })`.\n * A component declares the same pairs as state entries (`Types.fill`, …).\n */\ninterface AttributePropOptions<Ext, Int> {\n /** Initial value, used when the constructor `props` object omits the key. */\n default?: Ext;\n /** Override the attribute's built-in external → internal mapper. */\n mapper?: (ext: Ext, prev?: Int) => Int;\n /** Override the attribute's built-in lerp for `to()`. */\n tween?: TweenFn<Int>;\n}\n\n/**\n * Build one attribute-typed `property` from its canonical {@link AttributeOps}.\n *\n * `fallback` is a factory rather than a value so array/object defaults aren't a\n * single instance shared by every property declared through it. An **explicit**\n * `default: undefined` means \"this prop has no default\" and is honoured as such.\n */\nfunction attributeProperty<Ext, Int>(\n fallback: () => Ext,\n mapper?: (ext: Ext, prev?: Int) => Int,\n tween?: TweenFn<Int>,\n /** The control a host draws for this attribute, when it is not the default. */\n kind?: string,\n) {\n return (opts?: AttributePropOptions<Ext, Int> & { kind?: string }) =>\n property<Ext, Int>({\n default: opts && \"default\" in opts ? opts.default : fallback(),\n mapper: opts?.mapper ?? mapper,\n tween: opts?.tween ?? tween,\n ...(opts?.kind ?? kind ? { kind: opts?.kind ?? kind } : {}),\n });\n}\n\n/** A fill-layer property: a CSS string, a fill prop object, a `Fills` chain, or an array of them, lerped layer by layer. */\nexport const fillProperty = attributeProperty<Fill, FillResolved[]>(() => [], fillOps.resolve, fillOps.lerp, \"fills\");\n\n/** An effect-chain property — the `effects` prop's op set. */\nexport const effectsProperty = attributeProperty<Effect, NodeEffect[]>(() => [], effectsOps.resolve, effectsOps.lerp, \"effects\");\n\n/** An edge-inset property: scalar, symmetric or per-edge, tweened per edge. */\nexport const insetsProperty = attributeProperty<Insets, InsetsResolved>(() => 0, insetsOps.resolve, insetsOps.lerp, \"insets\");\n\n/**\n * An alignment property: a named position (`'center'`, `'topLeft'`, …) resolved\n * to a per-axis {@link Vector2} in `[-1, 1]`, tweened as a vector so\n * `'centerLeft' → 'centerRight'` slides.\n */\nexport const alignmentProperty = attributeProperty<Alignment, Vector2>(() => \"center\", alignmentOps.resolve, alignmentOps.lerp, \"alignment\");\n\n/**\n * A layout-mode property. Mid-tween it holds both modes and how far along, so\n * restoring the prop — which is what a seek does — restores the blend with it.\n */\nexport const flowProperty = attributeProperty<FlowMode, FlowResolved>(() => \"freeform\", undefined, flowOps.lerp);\n\n/**\n * A 3D point that may be unset: a node's `lookAt`. It defaults to unset (not to\n * the origin), stays unset when a binding returns `undefined`, and tweens with\n * `to()` — from `unset`'s reading of an unset start (see {@link lerpOptionalVector3}).\n */\nexport function optionalVector3Property(unset: \"origin\" | \"snap\") {\n return property<Vector3Input | undefined, Vector3 | undefined>({\n default: undefined,\n mapper: resolveOptionalVector3,\n tween: (from, to, t) => lerpOptionalVector3(from, to, t, unset),\n kind: \"vector3\",\n });\n}\n\n/** A rotation as a unit quaternion, interpolated with shortest-arc slerp. */\nexport const quaternionProperty = attributeProperty<Quaternion, Quaternion>(\n () => ({ x: 0, y: 0, z: 0, w: 1 }), undefined, quaternionOps.lerp, \"quaternion\",\n);\n\n/**\n * An audio level — a gain, a pan position, anything a clip or a bus schedules.\n *\n * `Param`, not `number`, because an `AudioRequest` is a schedule record built\n * once during precomp: a per-frame prop write would be read on whichever frame\n * happened to create the request and then never again. A `Ramp` *is* the\n * automation lane, which is why the tween interpolates between whole ramps.\n */\nexport const audioParamProperty = attributeProperty<Param, Param>(() => 0, undefined, audioParamOps.lerp, \"audioParam\");\n\n/**\n * An audio effect chain — the `effects` prop's op set.\n *\n * Without it a chain is an object-valued prop, and `Node._prepareStep` drops\n * those silently: the tween would run its duration and write nothing.\n */\nexport const audioEffectsProperty = attributeProperty<AudioEffectsInput, AudioEffect[]>(\n () => [], audioEffectsOps.resolve, audioEffectsOps.lerp, \"audioEffects\",\n);\n", "import { NodeRenderState } from \"@/render/render-context2d\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\n\n/**\n * Companion for {@link Node2D}'s clock advance and per-frame motion sampling. The\n * reactive prop reads (x/y/rotation/scale) stay in Node2D's thin `_sampleMotion`\n * wrapper; the backward-difference math lives here as a pure function over the\n * reused scratch state — no per-frame allocation (the {@link MotionHistory}\n * holder is created once per node at construction).\n */\n\n/** Largest frame delta we trust for a velocity estimate (seconds). Larger gaps (scrub/seek) read as \"unknown\". */\n/** @internal */\nexport const MAX_MOTION_DT = 0.2;\n\n/**\n * Per-node rolling history for the backward-difference velocity estimate.\n * Allocated once with the node (mirrors the reused `_renderState` scratch), then\n * mutated in place by {@link sampleMotion} each frame.\n */\n/** @internal */\nexport interface MotionHistory {\n prevPos: Vector2 | null;\n prevTime: number;\n prevRotation: number;\n prevScale: number;\n}\n\n/**\n * Record the current position as the history's previous frame, **without**\n * deriving a velocity from it.\n *\n * The seam a driven scene primes through. A generator scene walks time forward\n * one `dt` at a time, so its history is always the frame before and\n * {@link sampleMotion}'s backward difference is a property of the timeline. A\n * driven scene doesn't walk at all — it jumps straight to whatever frame is\n * asked for — so differencing against \"wherever the playhead last was\" makes\n * velocity a property of *how the viewer got here*: scrub quickly and a static\n * node smears, hold still on the same frame and it doesn't, step backward and it\n * reads zero. Priming with the position one frame earlier is what makes the\n * answer depend on the frame alone.\n */\n/** @internal */\nexport function primeMotion(\n history: MotionHistory,\n x: number,\n y: number,\n rotation: number,\n scale: number,\n at: number,\n): void {\n if (!history.prevPos) history.prevPos = { x, y };\n else { history.prevPos.x = x; history.prevPos.y = y; }\n history.prevTime = at;\n history.prevRotation = rotation;\n history.prevScale = scale;\n}\n\n/** Create the zeroed history holder a node keeps for its lifetime. */\n/** @internal */\nexport function createMotionHistory(): MotionHistory {\n return { prevPos: null, prevTime: 0, prevRotation: 0, prevScale: 1 };\n}\n\n/**\n * Compute this frame's motion (velocity/direction/speed/angular/scale) into the\n * reused `state` as a backward difference against `history`, then roll the\n * history forward. Velocity is `0`/`{0,0}` when no trustworthy delta exists —\n * the first frame, or after a non-monotonic time jump (only `0 < dt <= MAX` is\n * trusted, so a scrub that resets the clock reads as \"unknown\" rather than a\n * spurious huge velocity). `x`/`y` are the world position (y-down) the caller\n * resolved from `layoutBounds + x` / `layoutBounds - y`. Layout-dependent fields\n * (`rects`/`elapsed`) are filled in later, at draw time.\n */\n/** @internal */\nexport function sampleMotion(\n state: NodeRenderState,\n history: MotionHistory,\n x: number,\n y: number,\n rotation: number,\n scale: number,\n now: number,\n): void {\n const dt = now - history.prevTime;\n const prev = history.prevPos;\n if (prev && dt > 0 && dt <= MAX_MOTION_DT) {\n const vx = (x - prev.x) / dt;\n const vy = (y - prev.y) / dt;\n state.dt = dt;\n state.velocity.x = vx;\n state.velocity.y = vy;\n state.speed = Math.hypot(vx, vy);\n state.direction = (Math.atan2(vy, vx) * 180) / Math.PI;\n state.angularVelocity = (rotation - history.prevRotation) / dt;\n state.scaleVelocity = (scale - history.prevScale) / dt;\n } else {\n state.dt = 0;\n state.velocity.x = 0;\n state.velocity.y = 0;\n state.speed = 0;\n state.direction = 0;\n state.angularVelocity = 0;\n state.scaleVelocity = 0;\n }\n\n if (!prev) history.prevPos = { x, y };\n else { prev.x = x; prev.y = y; }\n history.prevTime = now;\n history.prevRotation = rotation;\n history.prevScale = scale;\n}\n", "import { EasingFunction } from \"@/tween/ease/type\";\nimport { commandParallel, commandSequence, driveCommand, type Command } from \"@/tween/command\";\nimport { SizeConstraints } from \"@/layout/constraints\";\nimport type { Node2D, Node2DProps } from \"./node2d\";\n\n/**\n * Measure `child`'s natural size **without attaching it to `parent`** — so the\n * measurement never perturbs the parent's layout (siblings don't shift for a\n * frame). Uses the constraints + scope the parent retained from its last measure\n * pass; returns `null` if the parent hasn't been measured yet (nothing on screen\n * to reflow against), so the caller can fall back. Reads `parent.lastMeasure` —\n * internal layout state the lifecycle helpers are the\n * intended in-directory consumer of.\n */\nfunction measureDetached(parent: Node2D, child: Node2D): { width: number; height: number } | null {\n const pass = parent.lastMeasure;\n const scope = pass?.measurer;\n // The scope (text measurement) is the essential input and is only present once\n // the parent has been laid out; without it we can't size a hug child off-tree.\n if (!scope) return null;\n // The parent's own constraints bound the child; fall back to its laid-out box,\n // then to an unbounded space — a hug child shrink-wraps regardless, so a\n // generous ceiling is fine.\n const constraints: SizeConstraints = pass?.constraints ?? {\n maxWidth: parent.measuredWidth || Number.MAX_SAFE_INTEGER,\n maxHeight: parent.measuredHeight || Number.MAX_SAFE_INTEGER,\n };\n const size = child.measure(constraints, scope);\n return { width: size.width ?? 0, height: size.height ?? 0 };\n}\n\n/**\n * Companion for {@link Node2D}'s animated child-management methods. The sync\n * variants (add/remove/clear/addChildAt/\n * removeChildAt) stay inline on Node2D — each is a 3–5 line method that mutates\n * `_children`/`_parent` and calls `bindAssets`/`bindChildContext`, so there is\n * no body worth moving. These are the animated overloads, returned as\n * {@link Command}s built from `child.to(...)` composed with\n * {@link commandSequence}/{@link commandParallel} — the same choreography\n * primitives a node's own multi-step commands use.\n *\n * Each command's setup (measuring the child, collapsing it, attaching/\n * detaching/reparenting) runs **lazily, once, on the command's first\n * evaluation** rather than when the function below is called — mirroring the\n * generator these replaced, whose body didn't run a single line until the\n * caller's first `.next()`. That laziness is load-bearing: a caller often does\n * `const cmd = parent.addChildAt(child, i, dur); /* lay the parent out here *\\/\n * driveCmd(cmd)`, relying on the parent having a fresh `lastMeasure` by the time\n * the hug/fill measurement in {@link addChildAtAnimated} actually runs. Doing\n * that measurement eagerly — when this function is called, not when the\n * command is first driven — reads whatever scope the parent happened to have\n * at call time, which is often none at all.\n *\n * The container's `gap` is handled by the per-child `gapScale` prop these helpers\n * tween in parallel with the child's box (see {@link addChildAtAnimated}); the\n * flex layout (`flex.ts`) folds each child's `gapScale` into its gap budget, so\n * the gap opens/closes in lockstep with the size instead of popping. No helper\n * here needs to know the parent's axis or gap value.\n */\n\n/**\n * Fraction of an insert/remove's `duration` spent on the size + gap motion; the\n * remainder is the opacity fade. Splitting the two sequentially (grow → fade in,\n * fade out → shrink) keeps the fading child from overlapping siblings that are\n * still sliding: room is opened while it's invisible, then it fades in already in\n * place (and mirror-image on remove). The size phase gets the larger share since\n * it's the dominant motion and the fade only needs to read as a quick finish.\n */\nconst SIZE_PHASE = 0.7;\n\n/**\n * Animated `addChildAt`: insert the child at `index` **already collapsed to 0**,\n * then grow it in — fading opacity up and expanding its box from 0 → its natural\n * size so the surrounding siblings **slide over to make room** rather than\n * jumping. The mirror of {@link removeChildAtAnimated} (which pins to the\n * measured size and shrinks to 0).\n *\n * A numeric-sized axis has its target size in hand up front. A `\"hug\"`/`\"fill\"`\n * axis does not — its size is only known once laid out — so we measure the child\n * **detached** (via {@link measureDetached}, using the parent's retained\n * constraints + scope) *before* attaching it. That keeps the child out of the\n * parent's layout flow while we size it, so the siblings never see it at full\n * width for a frame — no reflow flash. The child is then added at 0 and the tween\n * grows it to that measured size. Because the tween needs *numeric* endpoints\n * (a string size only snaps, it can't interpolate), the original size token is\n * restored once the command reaches its end so the child resumes normal reflow.\n *\n * If the parent hasn't been measured yet (no retained scope — nothing is on\n * screen to reflow against), a non-numeric axis simply can't be pre-measured;\n * it falls back to its authored token and fades in without a width tween.\n */\nexport function addChildAtAnimated(\n parent: Node2D,\n child: Node2D,\n index: number,\n duration: number,\n easing?: EasingFunction,\n): Command<Record<string, never>> {\n let animation: Command<Node2DProps> | null = null;\n let isNumericW = false;\n let isNumericH = false;\n let origW: Node2DProps[\"width\"];\n let origH: Node2DProps[\"height\"];\n\n const setup = (): Command<Node2DProps> => {\n const targetOpacity = child.opacity;\n // Remember the authored size tokens so a hug/fill axis can be restored\n // after the numeric grow-in tween finishes.\n origW = child.width;\n origH = child.height;\n isNumericW = typeof origW === \"number\";\n isNumericH = typeof origH === \"number\";\n\n // Pre-measure any non-numeric axis while the child is still detached, so\n // sizing it can't shift the parent's existing children for a frame.\n const detached = isNumericW && isNumericH ? null : measureDetached(parent, child);\n\n // Resolve each axis' grow-to target: a numeric axis uses its authored\n // size; a hug/fill axis uses the detached measurement (or gives up the\n // width tween if the parent isn't measured yet).\n const tweenW = isNumericW || detached !== null;\n const tweenH = isNumericH || detached !== null;\n const targetW = isNumericW ? (origW as number) : (detached?.width ?? 0);\n const targetH = isNumericH ? (origH as number) : (detached?.height ?? 0);\n\n // Collapse the axes we can tween to 0 before inserting, so the child\n // enters taking no room and the siblings hold their positions.\n // `gapScale: 0` also suppresses the gap this child would add, so the\n // flanking gap opens from 0 rather than snapping in the instant it\n // attaches.\n child.set({\n opacity: 0,\n gapScale: 0,\n ...(tweenW ? { width: 0 } : {}),\n ...(tweenH ? { height: 0 } : {}),\n } as Partial<Node2DProps>);\n parent.addChildAt({ data: { child, index } });\n\n const sizeProps: Partial<Node2DProps> = {};\n if (tweenW) sizeProps.width = targetW;\n if (tweenH) sizeProps.height = targetH;\n // Two sequential phases so the fading-in child never overlaps siblings\n // that are still sliding: first open the box and the flanking gap\n // (opacity held at 0, so nothing is visible while the space is being\n // made), then fade the now-placed child in. `gapScale` 0 → 1 tracks the\n // size so siblings slide over continuously instead of jumping by `gap`.\n const grow = duration * SIZE_PHASE;\n const fade = duration - grow;\n return commandSequence<Node2DProps>(\n child,\n commandParallel<Node2DProps>(\n child,\n child.to({ data: sizeProps, duration: grow, easing }),\n child.to({ data: { gapScale: 1 } as Partial<Node2DProps>, duration: grow, easing }),\n ),\n child.to({ data: { opacity: targetOpacity } as Partial<Node2DProps>, duration: fade, easing }),\n );\n };\n\n return driveCommand(duration, (t) => {\n if (!animation) animation = setup();\n animation.at(t);\n if (t >= 1) {\n // Restore any hug/fill token so the child reflows naturally from\n // here on; the tween already landed the axis on its measured pixel\n // size, so this is seamless.\n const restore: Partial<Node2DProps> = {};\n if (!isNumericW) restore.width = origW;\n if (!isNumericH) restore.height = origH;\n if (!isNumericW || !isNumericH) child.set(restore as Partial<Node2DProps>);\n }\n });\n}\n\n/**\n * Animated `removeChildAt`: fade+size the child out, then detach it.\n *\n * The child stays in the tree — animating out — until the command reaches its\n * end (`t === 1`), matching the \"insert\"/\"remove\" seekability\n * `packages/components/code` established: a host asking for a time before the\n * end sees the child still present, mid-fade; only reaching the end detaches it.\n * Seeking back below the end after having reached it re-attaches the child at\n * its original index, so the animation stays a function of `t` in both\n * directions rather than a one-way commit.\n */\nexport function removeChildAtAnimated(\n parent: Node2D,\n index: number,\n duration: number,\n easing?: EasingFunction,\n): Command<Record<string, never>> {\n let child: Node2D | null = null;\n let animation: Command<Node2DProps> | null = null;\n let setupDone = false;\n\n const setup = (): void => {\n setupDone = true;\n // Out of range: nothing to animate — `child`/`animation` stay null, and\n // every apply() below becomes a no-op.\n if (index < 0 || index >= parent.children.length) return;\n child = parent.children[index];\n\n // Pin to current rendered size so the shrink reflows siblings in the\n // parent layout.\n const lw = child.measuredWidth;\n const lh = child.measuredHeight;\n child.set({ width: lw, height: lh } as Partial<Node2DProps>);\n\n // Mirror of the insert: fade the child out first (box held at full\n // size, so it doesn't overlap siblings mid-fade), then collapse the\n // box and close the gap. `gapScale` 1 → 0 tracks the shrink so the gap\n // closes continuously.\n const fade = duration * (1 - SIZE_PHASE);\n const shrink = duration - fade;\n animation = commandSequence<Node2DProps>(\n child,\n child.to({ data: { opacity: 0 } as Partial<Node2DProps>, duration: fade, easing }),\n commandParallel<Node2DProps>(\n child,\n child.to({ data: { width: 0, height: 0 } as Partial<Node2DProps>, duration: shrink, easing }),\n child.to({ data: { gapScale: 0 } as Partial<Node2DProps>, duration: shrink, easing }),\n ),\n );\n };\n\n return driveCommand(duration, (t) => {\n if (!setupDone) setup();\n if (!animation || !child) return;\n const done = t >= 1;\n if (!done && child.parent !== parent) {\n // Seeking back into the animation after it had reached the end —\n // the child is what's animating out, so put it back.\n parent.addChildAt({ data: { child, index: Math.min(index, parent.children.length) } });\n }\n animation.at(t);\n if (done) {\n parent.remove(child);\n // The child is detached now, so its 0 gapScale no longer affects any\n // layout — but the same node can be re-added later (scenes reuse\n // refs), and a plain (non-animated) addChild wouldn't reset it.\n // Restore the default so a stale 0 can't silently swallow a gap on\n // re-insert.\n child.set({ gapScale: 1 } as Partial<Node2DProps>);\n }\n });\n}\n\n/**\n * Animated `reparent`: fade+size the node out of its current parent, then\n * reparent it and fade+size it in. The handoff happens at the animation's\n * midpoint (`t === 0.5`) — seeking across it in either direction moves the node\n * between parents to match, the same bidirectional membership rule\n * {@link removeChildAtAnimated} uses.\n */\nexport function reparentAnimated(\n node: Node2D,\n newParent: Node2D,\n duration: number,\n easing?: EasingFunction,\n): Command<Record<string, never>> {\n const half = duration / 2;\n let animation: Command<Node2DProps> | null = null;\n let oldParent: Node2D | null = null;\n\n const setup = (): Command<Node2DProps> => {\n const targetOpacity = node.opacity;\n oldParent = node.parent;\n\n // Pin to current rendered size so exit shrink reflows the old parent.\n const lw = node.measuredWidth;\n const lh = node.measuredHeight;\n node.set({ width: lw, height: lh } as Partial<Node2DProps>);\n\n // Exit the old parent (fade out, then collapse the box + gap) over the\n // first half, then enter the new one (open the box + gap, then fade\n // in) over the second — one flat sequence, so evaluating any `t` walks\n // and settles every phase before it first. That is what makes the\n // *enter* tweens' `from` correct even when a driven host asks for a\n // time straight into the enter half without ever having evaluated the\n // exit half first: `commandSequence` re-settles every prior phase on\n // each call, so by the time an enter tween's `from` is lazily\n // snapshotted (its own first evaluation), the exit phase has already\n // collapsed the node to the state enter grows from.\n const exitFade = half * (1 - SIZE_PHASE);\n const exitShrink = half - exitFade;\n const enterGrow = half * SIZE_PHASE;\n const enterFade = half - enterGrow;\n return commandSequence<Node2DProps>(\n node,\n node.to({ data: { opacity: 0 } as Partial<Node2DProps>, duration: exitFade, easing }),\n commandParallel<Node2DProps>(\n node,\n node.to({ data: { width: 0, height: 0 } as Partial<Node2DProps>, duration: exitShrink, easing }),\n node.to({ data: { gapScale: 0 } as Partial<Node2DProps>, duration: exitShrink, easing }),\n ),\n commandParallel<Node2DProps>(\n node,\n node.to({ data: { width: lw, height: lh } as Partial<Node2DProps>, duration: enterGrow, easing }),\n node.to({ data: { gapScale: 1 } as Partial<Node2DProps>, duration: enterGrow, easing }),\n ),\n node.to({ data: { opacity: targetOpacity } as Partial<Node2DProps>, duration: enterFade, easing }),\n );\n };\n\n return driveCommand(duration, (t) => {\n if (!animation) animation = setup();\n const elapsed = t * duration;\n const inNewParent = elapsed >= half;\n if (inNewParent && node.parent !== newParent) {\n if (oldParent) oldParent.remove(node);\n newParent.add(node);\n } else if (!inNewParent && node.parent !== oldParent) {\n newParent.remove(node);\n if (oldParent) oldParent.add(node);\n }\n animation.at(t);\n });\n}\n", "import { Alignment } from \"@/attributes/layout/alignment\";\n\n/**\n * The out-of-plane transform as one bag — the shorthand form of the individual\n * `rotationX` / `rotationY` / `depth` / `perspective` / `backfaceVisible` /\n * `flipHorizontal` / `flipVertical` / `transformOrigin` props on {@link Node2D}.\n *\n * Sugar, and only sugar: {@link expandTransform3D} writes each field onto the\n * prop it names before anything reads either, the same way `size` becomes\n * `width`/`height`. That keeps one storage location per value — so a tween of\n * `transform3D.rotationY` and a tween of `rotationY` are the same tween, and a\n * scene can mix the two forms without either shadowing the other.\n *\n * Named `NodeTransform3D` rather than `Transform3D`, which `render3d` already\n * uses for the placement of an object in a *real* 3D scene. These are two\n * different things and the names had to say so: this one tilts a flat node the\n * way a browser tilts a `<div>`, that one puts a mesh in a world with lights in it.\n */\nexport interface NodeTransform3D {\n /** Tilt about the horizontal axis, degrees. Positive tips the top away. */\n rotationX?: number;\n /** Tilt about the vertical axis, degrees. Positive swings the right edge away. */\n rotationY?: number;\n /** In-plane rotation belonging to the 3D block, degrees. Separate from the node's own `rotation`. */\n rotationZ?: number;\n /** Push along the view axis in px (CSS `translateZ`). Inert without `perspective`. */\n depth?: number;\n /** Viewer distance in px. `0` (default) is a parallel projection — no perspective. */\n perspective?: number;\n /** Whether the node still paints once it has turned past edge-on. Default `true`. */\n backfaceVisible?: boolean;\n /** Mirror across the vertical centre line (CSS `scaleX(-1)`). */\n flipHorizontal?: boolean;\n /** Mirror across the horizontal centre line (CSS `scaleY(-1)`). */\n flipVertical?: boolean;\n /** The point the whole transform turns about — CSS `transform-origin`. Defaults to the node's `pivot`. */\n origin?: Alignment;\n}\n\n/** The prop each {@link NodeTransform3D} field expands to. `origin` is the one rename. */\nconst TRANSFORM_3D_KEYS: ReadonlyArray<[keyof NodeTransform3D, string]> = [\n [\"rotationX\", \"rotationX\"],\n [\"rotationY\", \"rotationY\"],\n [\"rotationZ\", \"rotationZ\"],\n [\"depth\", \"depth\"],\n [\"perspective\", \"perspective\"],\n [\"backfaceVisible\", \"backfaceVisible\"],\n [\"flipHorizontal\", \"flipHorizontal\"],\n [\"flipVertical\", \"flipVertical\"],\n [\"origin\", \"transformOrigin\"],\n];\n\n/**\n * Expand the `transform3D` shorthand onto the individual props, in place. An\n * explicitly-named prop in the same object wins over the bag's field, matching\n * `size`-vs-`width` and `padding`-vs-`paddingLeft`; a `transform3D` given as a\n * whole-bag callback is left alone, since there is no per-field value to\n * distribute. No-op when the key is absent, which is nearly always.\n */\n/** @internal */\nexport function expandTransform3D(props: Record<string, unknown>): void {\n const bag = props.transform3D;\n if (bag === undefined || bag === null || typeof bag !== \"object\") return;\n const source = bag as Record<string, unknown>;\n for (const [field, prop] of TRANSFORM_3D_KEYS) {\n const value = source[field];\n if (value !== undefined && props[prop] === undefined) props[prop] = value;\n }\n}\n", "import { Vector2 } from \"@/attributes/layout/vector2\";\nimport {\n Matrix2D,\n NO_PROJECTION_3D,\n applyToPoint,\n nodeProjectedMatrix,\n type Projection3D,\n} from \"@/attributes/layout/matrix2d\";\n\n/**\n * Companion for {@link Node2D}'s transform/anchor/world-space math. The reactive\n * prop reads (x/y/rotation/scale/pivot/layoutBounds) and the parent-chain walk\n * stay in Node2D's getters; the pure geometry lives here. Reuses the matrix\n * primitives in `attributes/layout/matrix2d.ts`.\n */\n\n/**\n * Rotate a centered offset `(ox, oy)` (y-up) by `rotationDeg` (clockwise) and\n * translate by the node's `(x, y)`, giving a parent-relative anchor point. Fast\n * path for the un-rotated case. Drives the local anchor getters.\n */\n/** @internal */\nexport function rotateOffset(x: number, y: number, rotationDeg: number, ox: number, oy: number): Vector2 {\n if (rotationDeg === 0) return { x: x + ox, y: y + oy };\n const rad = (rotationDeg * Math.PI) / 180;\n const cos = Math.cos(rad);\n const sin = Math.sin(rad);\n // Canvas rotation is clockwise; in y-up space that means\n // x' = cos*ox + sin*oy, y' = -sin*ox + cos*oy.\n return {\n x: x + cos * ox + sin * oy,\n y: y - sin * ox + cos * oy,\n };\n}\n\n/**\n * This node's local transform in canvas (y-down) space, matching the matrix the\n * renderer pushes in `applyTransform`. `cx`/`cy` are the positioned centre\n * (`layoutBounds + x`, `layoutBounds - y`); `pivot` is the resolved normalised pivot.\n *\n * `projection` carries the out-of-plane half (mirrors, tilt, depth, perspective)\n * and defaults to none, in which case this is the plain six-number affine matrix\n * it has always been.\n *\n * Both consumers of a node's transform go through here — `Node2D._localMatrix`\n * (and so `worldMatrix`, `global`, and picking) and `Node2D.applyTransform` (and so\n * the renderer) — so there is one definition of the arithmetic rather than two\n * that agree by inspection. They differ in exactly one argument: the renderer\n * passes the projection and the geometry does not, because the mirrors and the\n * tilt are paint rather than shape. See `Node2D._localMatrix`.\n */\n/** @internal */\nexport function localMatrix(\n cx: number,\n cy: number,\n rotation: number,\n scale: number,\n pivot: Vector2,\n width: number,\n height: number,\n projection: Projection3D = NO_PROJECTION_3D,\n): Matrix2D {\n const pivotX = pivot.x * (width / 2);\n const pivotY = -pivot.y * (height / 2);\n return nodeProjectedMatrix(cx, cy, rotation, scale, pivotX, pivotY, projection);\n}\n\n/** The nine world-space anchor points produced by mapping centered y-up offsets through `m`. */\n/** @internal */\nexport interface WorldAnchors {\n center: Vector2;\n topLeft: Vector2;\n topRight: Vector2;\n bottomLeft: Vector2;\n bottomRight: Vector2;\n topCenter: Vector2;\n bottomCenter: Vector2;\n centerLeft: Vector2;\n centerRight: Vector2;\n}\n\n/**\n * Map this node's centered y-up offsets through the world matrix `m`, returning\n * the nine world-space anchor points (y-up). The matrix works in canvas (y-down)\n * space, so y is flipped in and back out. `halfW`/`halfH` are half the node's\n * layout size.\n */\n/** @internal */\nexport function worldAnchors(m: Matrix2D, halfW: number, halfH: number): WorldAnchors {\n const at = (ox: number, oy: number): Vector2 => {\n const p = applyToPoint(m, { x: ox, y: -oy });\n return { x: p.x, y: -p.y };\n };\n return {\n center: at(0, 0),\n topLeft: at(-halfW, halfH),\n topRight: at(halfW, halfH),\n bottomLeft: at(-halfW, -halfH),\n bottomRight: at(halfW, -halfH),\n topCenter: at(0, halfH),\n bottomCenter: at(0, -halfH),\n centerLeft: at(-halfW, 0),\n centerRight: at(halfW, 0),\n };\n}\n", "import { identity, invert, multiply, type Matrix2D } from \"@/attributes/layout/matrix2d\";\nimport {\n cameraSide,\n multiplyAffine3,\n nearCoverage,\n nearCutPolygon,\n spacePaintOrder,\n spacePlane,\n spaceScreenMatrix,\n spaceViewMatrix,\n type Affine3,\n type SpaceCamera,\n type SpacePlane,\n} from \"@/attributes/layout/space3d\";\nimport { Clip } from \"@/render/clip\";\nimport { PathBuilder } from \"@/render/descriptors/path-builder\";\nimport type { Node2D } from \"./node2d\";\n\n/**\n * Companion for {@link Node2D}'s 2.5D space: where a node sits in one for a\n * frame, and the order a space's siblings paint in. The renderer and picking\n * both build frames through here, so a box drawn around a node cannot disagree\n * with where it was painted.\n */\n\n/** Where one node sits in a space for one frame. */\n/** @internal */\nexport interface SpaceFrame {\n /** The node the space is seen from — whose camera it is. */\n readonly root: Node2D;\n readonly camera: SpaceCamera;\n /** This node's local frame → view space. */\n readonly view: Affine3;\n /** This node's local frame → the root's canvas: the whole projection. */\n readonly screen: Matrix2D;\n /** What this node's scope leaves on the canvas, relative to the root's: `screen`, or its parent's when it pushes nothing. */\n readonly pushed: Matrix2D;\n /** What the node concats in `applyTransform`: the parent's `pushed` undone, then `screen`. */\n readonly local: Matrix2D;\n /** No tilt and no depth: the node lies in its parent's plane. */\n readonly flat: boolean;\n readonly plane: SpacePlane;\n /**\n * False when the node is edge-on or wholly behind the camera, so it has\n * nothing of its own to draw — and no usable matrix to push, which is why its\n * children, placed by their own frames, are still drawn.\n */\n readonly paints: boolean;\n readonly facesAway: boolean;\n /** Confines the node's own paint to what is in front of the lens, while the lens is passing through it. */\n readonly nearCut: Clip | null;\n}\n\nconst IDENTITY: Matrix2D = identity();\n\n/** The frame a space root hands its children: the camera over the root's own plane. */\n/** @internal */\nexport function spaceRootFrame(root: Node2D, camera: SpaceCamera): SpaceFrame {\n const view = spaceViewMatrix(camera);\n return {\n root,\n camera,\n view,\n screen: spaceScreenMatrix(camera, view),\n pushed: IDENTITY,\n local: IDENTITY,\n flat: true,\n plane: spacePlane(view, { x: 0, y: 0, width: 0, height: 0 }),\n paints: false,\n facesAway: false,\n nearCut: null,\n };\n}\n\n/** `child`'s frame, placed in `parent`'s. */\n/** @internal */\nexport function spaceChildFrame(parent: SpaceFrame, child: Node2D): SpaceFrame {\n const own = child._spaceMatrix();\n const view = multiplyAffine3(parent.view, own);\n const camera = parent.camera;\n const screen = spaceScreenMatrix(camera, view);\n const box = inkBox(child);\n const plane = spacePlane(view, box);\n const { side, edgeOn } = cameraSide(camera, plane);\n const coverage = nearCoverage(camera, plane);\n\n let local = IDENTITY;\n let paints = !edgeOn && coverage !== \"none\";\n if (paints) {\n if (parent.pushed === IDENTITY) {\n local = screen;\n } else {\n const undo = invert(parent.pushed);\n if (undo) local = multiply(undo, screen);\n else paints = false;\n }\n }\n\n return {\n root: parent.root,\n camera,\n view,\n screen,\n pushed: paints ? screen : parent.pushed,\n local,\n flat: own[2] === 0 && own[6] === 0 && own[8] === 0 && own[9] === 0 && own[11] === 0,\n plane,\n paints,\n facesAway: !edgeOn && side < 0,\n nearCut: paints && coverage === \"some\" ? nearCutClip(screen, box) : null,\n };\n}\n\n/**\n * The frame `node` is placed by, or `null` when it is in no space — the walk\n * picking takes, where the renderer threads frames down as it goes.\n *\n * A node is in a space when some ancestor opens one and every node between the\n * two hands its children on through {@link Node2D._rendersChildrenInSpace};\n * a mask or a nested camera flattens its subtree into its own plane instead.\n */\n/** @internal */\nexport function spaceFrameOf(node: Node2D): SpaceFrame | null {\n const chain: Node2D[] = [];\n for (let n: Node2D | null = node.parent; n; n = n.parent) {\n const camera = n._spaceCamera();\n if (camera) {\n let frame = spaceRootFrame(n, camera);\n for (let i = chain.length - 1; i >= 0; i--) frame = spaceChildFrame(frame, chain[i]);\n return spaceChildFrame(frame, node);\n }\n if (!n._rendersChildrenInSpace()) return null;\n chain.push(n);\n }\n return null;\n}\n\n/** The frame `parent` passes its children, whether it is a space root or a node inside one. */\n/** @internal */\nexport function spaceFrameForChildren(parent: Node2D): SpaceFrame | null {\n const camera = parent._spaceCamera();\n if (camera) return spaceRootFrame(parent, camera);\n if (!parent._rendersChildrenInSpace()) return null;\n return spaceFrameOf(parent);\n}\n\n/**\n * The order `children` paint in, far to near, as indices. Siblings that all lie\n * in their parent's plane need no test and keep their authored order.\n */\n/** @internal */\nexport function spaceChildOrder(frames: readonly SpaceFrame[]): number[] {\n if (frames.length < 2 || frames.every((f) => f.flat)) return frames.map((_, i) => i);\n return spacePaintOrder(frames[0].camera, frames.map((f) => f.plane));\n}\n\n/** The node's ink in its own frame, centred and y-down — the frame its matrices map from. */\nfunction inkBox(node: Node2D): { x: number; y: number; width: number; height: number } {\n const b = node._localBounds();\n return { x: b.x, y: -b.y, width: b.width, height: b.height };\n}\n\n/**\n * Grown past the ink by this much, plus half the box: a shadow, a stroke or a\n * glow spilling past a node must not be cut along its edge while the lens is\n * passing through it.\n */\nconst NEAR_CUT_MARGIN = 128;\n\nfunction nearCutClip(screen: Matrix2D, box: { x: number; y: number; width: number; height: number }): Clip | null {\n const polygon = nearCutPolygon(screen, box, Math.max(box.width, box.height) / 2 + NEAR_CUT_MARGIN);\n if (!polygon) return null;\n // Path commands are authored y-up; the polygon is in the node's y-down frame.\n const path = new PathBuilder().moveTo(polygon[0].x, -polygon[0].y);\n for (let i = 1; i < polygon.length; i++) path.lineTo(polygon[i].x, -polygon[i].y);\n // A symmetric frame keeps the path where it was drawn rather than centring it on its own box.\n const reach = Math.max(...polygon.map((p) => Math.max(Math.abs(p.x), Math.abs(p.y))));\n return new Clip().path(path.close().toPathState({ centerBounds: [-reach, -reach, reach, reach] }));\n}\n", "import { RenderContext2D, SpaceRects } from \"@/render/render-context2d\";\nimport { Clip } from \"@/render/clip\";\nimport { BoxBounds } from \"@/layout/bounds\";\nimport { NodeEffect } from \"@/attributes/shape/effects/union\";\nimport { backdropEffects, foregroundShaderEffects } from \"@/attributes/shape/effects/backdrop\";\n\n/**\n * The **pure, leaf** pieces of {@link Node2D}'s render pipeline: they take\n * resolved inputs and the `ctx`, never call back into the node, so the\n * orchestration on the class reads without the scope bookkeeping.\n */\n\n/**\n * Reference rect for fills with `space:'parent'`, expressed in this node's local\n * space (origin = this node's positioned centre, y-down). The viewport\n * (`space:'global'`) is resolved by the renderer. Rotation/scale of this node\n * are not folded in — the rect is the axis-aligned parent box, which is what\n * gradients expect. Returns `{}` for a root node (no parent).\n */\n/** @internal */\nexport function computeSpaceRects(\n parentRect: BoxBounds | undefined,\n thisRect: BoxBounds,\n x: number,\n y: number,\n): SpaceRects {\n if (!parentRect) return {};\n // This node's local origin within the parent's space.\n const ox = thisRect.x + x;\n const oy = thisRect.y - y;\n return {\n parent: {\n left: -parentRect.width / 2 - ox,\n top: -parentRect.height / 2 - oy,\n right: parentRect.width / 2 - ox,\n bottom: parentRect.height / 2 - oy,\n },\n };\n}\n\n/**\n * Apply backdrop effects (any `mode:\"backdrop\"` effect — blur, grayscale, …;\n * plus magnify and backdrop shader) beneath the node, clipped to its silhouette,\n * before the node's own content is drawn — so what's underneath is\n * filtered/warped while the node's own edges stay sharp. A no-op when there are\n * no backdrop effects or no silhouette `clip` to confine them to.\n */\n/** @internal */\nexport function applyBackdropEffects(\n ctx: RenderContext2D,\n effects: NodeEffect[],\n clip: Clip | null,\n width: number,\n height: number,\n): void {\n const backdrop = backdropEffects(effects);\n if (backdrop.length === 0) return;\n if (!clip || clip.isEmpty()) return;\n\n // Clip to the silhouette first so the backdrop passes are confined to the\n // node; the renderer opens its backdrop layers within that clip.\n ctx.beginClip(clip);\n ctx.beginEffects(backdrop, \"backdrop\", width, height);\n ctx.endEffects();\n ctx.endClip();\n}\n\n/**\n * Run `body` inside the node's `foreground` effect scope (posterize wrapping\n * bulge), so those shader effects warp/band everything it paints: the inner\n * half of `renderContentWithEffects`, whose backdrop pass runs before this.\n * Skipped when there are none, so the begin/end calls match.\n */\n/** @internal */\nexport function applyContentEffectScope(\n ctx: RenderContext2D,\n effects: NodeEffect[],\n width: number,\n height: number,\n body: () => void,\n): void {\n const foreground = foregroundShaderEffects(effects);\n const hasForeground = foreground.length > 0;\n if (hasForeground) ctx.beginEffects(foreground, \"foreground\", width, height);\n body();\n if (hasForeground) ctx.endEffects();\n}\n", "import { _observer, PropSlot } from \"@/props/slot\";\nimport { LAYOUT_SLOT } from \"@/props/observer\";\nimport { EasingFunction } from \"@/tween/ease/type\";\nimport { type Command, type CommandArgs } from \"@/tween/command\";\nimport { TweenStepper } from \"@/tween/stepper\";\nimport type { AssetScope } from \"@/assets/scope\";\nimport { AssetNotLoadedError } from \"@/assets/errors\";\nimport { declareMembers, property } from \"@/attributes/properties/decorator\";\nimport { effectsProperty, insetsProperty, alignmentProperty } from \"@/attributes/properties/typed\";\nimport { createMotionHistory, MotionHistory, sampleMotion, primeMotion } from \"./node-motion\";\nimport { addChildAtAnimated, removeChildAtAnimated, reparentAnimated } from \"./node-lifecycle\";\n\nimport type { NodeEffect } from \"@/attributes/shape/effects/union\";\nimport type { NodeBlendMode } from \"@/attributes/shape/fill/blend\";\nimport { BoxBounds } from \"@/layout/bounds\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport { Alignment, alignmentOps } from \"@/attributes/layout/alignment\";\nimport type { WorldTransform } from \"@/attributes/layout/world-transform\";\nimport { Node, type NodeConfig, type NodeDimension, type NodeProps } from \"@/components/trees/node/node\";\nimport {\n applyToPoint,\n facesAway,\n hasProjection3D,\n invert,\n Matrix2D,\n multiply,\n type Projection3D,\n} from \"@/attributes/layout/matrix2d\";\nimport { expandTransform3D, type NodeTransform3D } from \"@/attributes/layout/transform3d\";\nimport { multiplyAffine3, nodeSpaceMatrix, type Affine3, type SpaceCamera } from \"@/attributes/layout/space3d\";\nimport { localMatrix, rotateOffset, worldAnchors } from \"./node-transform\";\nimport { spaceChildFrame, spaceChildOrder, spaceRootFrame, type SpaceFrame } from \"./node-space\";\nimport {\n applyBackdropEffects as applyBackdropEffectsImpl,\n applyContentEffectScope,\n computeSpaceRects,\n} from \"./node-render\";\nimport { SizeConstraints } from \"@/layout/constraints\";\nimport { NodeRenderState, RenderContext2D, RenderPass2D, SpaceRects } from \"@/render/render-context2d\";\nimport { Clip } from \"@/render/clip\";\nimport { TransformState } from \"@/render/descriptors/transform\";\nimport { command } from \"@/tween/command-decorator\";\nimport { PathBuilder } from \"@/render/descriptors/path-builder\";\nimport type { PathData } from \"@/render/descriptors/path\";\nimport { pathOps } from \"@/attributes/shape/path/ops\";\nimport { Size2D, SizeInput, size2DOps, sizeInputOps } from \"@/attributes/layout/size\";\nimport { Effect } from \"@/attributes/shape/effects/chain\";\nimport { Insets, InsetsResolved, insetsOps } from \"@/attributes/layout/insets\";\nimport { lerpPerspective } from \"@/tween/lerp\";\nimport { MeasureContext2D } from \"@/render/measure-context\";\nimport { flowOps } from \"@/layout/ops\";\nimport type { FlowMeasure, FlowSettings } from \"@/layout/types\";\n\n/**\n * Stand-in for a node's reference rects when the context never reads them.\n * Shared and empty — `computeSpaceRects` returns the same shape for a node with\n * no parent, so consumers already handle it.\n */\nconst NO_SPACE_RECTS: SpaceRects = {};\n\n/** The node centre in the normalised `[-1, 1]` alignment space — `pivot`'s own default. */\nconst ORIGIN_2D: Vector2 = { x: 0, y: 0 };\n\n/**\n * Where a parent puts a child beyond the box it laid it out in: the turn, size,\n * tilt, depth and fade of a slot in an arrangement — a ring of cards, tiles on a\n * sphere. Applied about the box's centre and *before* the child's own\n * transform, so the child's `x`/`y`/`rotation`/`scale`, and every command on\n * them, keep working relative to the slot.\n *\n * Answered by the parent ({@link Node2D._placementOf}) rather than written onto\n * the child, so a child moved to another parent cannot carry a stale slot, and\n * read by the renderer, picking and `global` alike, so a selection box lands on\n * the pixels.\n */\nexport interface ChildPlacement {\n /** In-plane turn, degrees clockwise. */\n readonly rotation: number;\n readonly scale: number;\n /** Tilt, degrees — as the child's own `rotationX`/`rotationY`. */\n readonly rotationX: number;\n readonly rotationY: number;\n /** Push toward the viewer, px. Only a space gives it perspective. */\n readonly depth: number;\n /** Multiplies the child's own opacity. */\n readonly opacity: number;\n}\n\n/**\n * A parent's own coordinates for where its children sit — the units of a graph,\n * say. Position only: a child keeps its size, turn and scale, so a label on a\n * plot follows the plot's range without being stretched by it.\n *\n * Answered by the parent ({@link Node2D._planeOf}) for the reasons a slot is,\n * and read by the renderer, picking, `global` and `moveTo({ target })` alike.\n */\nexport interface ChildPlane {\n /** A child's `x`/`y` as a pixel offset, y-up, from the centre of its layout box. */\n toOffset(x: number, y: number): Vector2;\n /** The inverse: the `x`/`y` that put a child at that offset. */\n toCoords(x: number, y: number): Vector2;\n}\n\n/**\n * A point of a node an editor can drag to set one of its `Vector2` props: the\n * two ends of an arrow. `at` is in the node's own frame, y-up from its origin,\n * the frame {@link Node2D._localBounds} is in.\n */\nexport interface NodeHandle {\n readonly prop: string;\n readonly at: Vector2;\n}\n\nconst NO_HANDLES: readonly NodeHandle[] = [];\n\n// Filled per call and read synchronously by the matrix builders, like `_projectionScratch`.\nconst SLOT_PROJECTION: Projection3D = {\n rotationX: 0, rotationY: 0, rotationZ: 0, depth: 0, perspective: 0,\n flipHorizontal: false, flipVertical: false,\n};\n\nfunction slotProjection(placement: ChildPlacement): Projection3D {\n SLOT_PROJECTION.rotationX = placement.rotationX;\n SLOT_PROJECTION.rotationY = placement.rotationY;\n SLOT_PROJECTION.depth = placement.depth;\n return SLOT_PROJECTION;\n}\n\n/** No settings: centred freeform, which is how a plain node arranges its children. */\nconst DEFAULT_FLOW: FlowSettings = Object.freeze({});\n\n/** Where a node last placed its children, and by what flow: see {@link Node2D._childSpace}. */\nexport interface ChildSpace {\n readonly settings: FlowSettings;\n readonly inner: BoxBounds;\n}\n\nconst NO_CONTENT: Size2D = { width: 0, height: 0 };\n\n// WorldTransform, PropInput, and PropInputs now live in dedicated\n// modules (see imports above) and are re-exported below so existing\n// `from \".../node2d\"` imports keep resolving.\nexport { Node } from \"@/components/trees/node/node\";\nexport type { NodeChildren, NodeConfig, NodeMetadata, NodeDimension, NodeProps } from \"@/components/trees/node/node\";\nexport type { WorldTransform } from \"@/attributes/layout/world-transform\";\nexport type { PropInput, PropInputs } from \"@/attributes/properties/inputs\";\n\n/**\n * The camera props a node pushes around its children — the three inputs\n * `RenderContext2D.beginCamera` takes beyond the viewport rect. See\n * {@link Node2D._cameraScope}.\n */\n/** @internal */\nexport interface CameraScope {\n /** World point (y-up) the viewport centres on — what the camera is aimed at. */\n lookAt: Vector2;\n /** Uniform zoom factor. */\n zoom: number;\n /** Viewport rotation in degrees; the renderer applies it as `rotate(-heading)`. */\n heading: number;\n}\n\nexport interface Node2DProps extends NodeProps {\n x: number; // 0 is center, negative is left, positive is right\n y: number; // 0 is center, negative is down, positive is up\n width: SizeInput;\n height: SizeInput;\n /**\n * Per-child weight for the gap this node contributes to its parent's flex\n * run, `[0, 1]`. See the property's own note — set it to collapse a child\n * without the surrounding gap popping.\n */\n gapScale: number;\n /**\n * Sets `width` and `height` to the same value in one go. Pure sugar: at\n * construction time, an author-facing `size` is expanded into `width`/\n * `height` before either is applied. Explicit `width` or `height` takes\n * precedence over `size` (mirroring `padding`'s side-vs-shorthand rule),\n * so `{ size: 200, width: 100 }` yields `width: 100, height: 200`.\n * Reactive bindings and `to()`/`set()` targets both work the same as\n * `width`/`height` — `size: 'fill'`, `size: () => ...`, or\n * `node.to({ size: 300 }, 0.5)` are all valid.\n */\n size: SizeInput;\n scale: number;\n rotation: number;\n opacity: number;\n /** Layer blend mode. `'pass-through'` (default) does not isolate the node — its opacity scales each child/fill while they blend against the backdrop. Any other mode isolates the node and blends its flattened result against the backdrop. */\n blend: NodeBlendMode;\n effects: Effect;\n /** Inner spacing between this node's edges and its content/children. */\n padding: Insets;\n /** When true, content drawn outside this node's outline is clipped away (see {@link Node2D.clipSelf}). */\n clip: boolean;\n /**\n * Pivot point for rotation and scale. Either a **named alignment** (`'center'`,\n * `'topRight'`, `'bottomLeft'`, … — the node `align` vocabulary) or an explicit\n * {@link Vector2}: `(0,0)`=center, `(-1,1)`=top-left, `(1,-1)`=bottom-right. Set\n * automatically when an alignment *positioning* prop is used.\n */\n pivot: Alignment;\n\n // ---- Mirrors and the third dimension -----------------------------------\n // A node is a flat plane, and these are the CSS transform functions that\n // still apply to one: the two mirrors, the two out-of-plane rotations, a\n // push along the view axis and the perspective that makes it read as depth.\n // `rotation` supplies the Z axis (see `transform3D` for why there is no\n // `rotationZ` beside it), and every one of them turns about `pivot` — or\n // about `transformOrigin`, where that is set.\n\n /**\n * Mirror the node (and its whole subtree) across its vertical centre line.\n * The same thing CSS's `scaleX(-1)` is: text reads backwards, a left-pointing\n * arrow points right, and nothing about the node's box or its layout moves.\n */\n flipHorizontal: boolean;\n /** Mirror across the horizontal centre line — CSS's `scaleY(-1)`. See {@link flipHorizontal}. */\n flipVertical: boolean;\n /** Tilt about the horizontal axis, in **degrees**. Positive tips the top edge away from the viewer. */\n rotationX: number;\n /** Tilt about the vertical axis, in **degrees**. Positive swings the right edge away from the viewer. */\n rotationY: number;\n /**\n * In-plane rotation belonging to the 3D transform, in **degrees** clockwise —\n * the Z axis of the `rotateX · rotateY · rotateZ` block.\n *\n * **Not a second name for {@link rotation}.** The two are independent numbers\n * and editing one never moves the other. What separates them is which side of\n * the geometry/paint line they fall on: `rotation` turns the node's *shape*,\n * so its box turns with it and everything reading that box follows, while\n * this is part of the projection, which is paint (see `Node2D._localMatrix`).\n * Turning a node with `rotation` turns its selection outline; turning it with\n * `rotationZ` spins the picture inside a box that stays where it was.\n *\n * They compose the only way two rotations about one axis can — they add.\n */\n rotationZ: number;\n /**\n * Push along the view axis, in px — CSS's `translateZ`. Positive brings the\n * node toward the viewer, so it projects larger.\n *\n * **Inert without {@link perspective}.** With no perspective the projection is\n * parallel and z is simply dropped, exactly as in CSS: there is no viewpoint\n * for a thing to be nearer to.\n */\n depth: number;\n /**\n * Distance from the viewer to the plane the node sits in, in px. `0` (the\n * default) is no perspective at all — a parallel projection, where a tilt\n * squashes the node evenly rather than making its far edge recede.\n *\n * Smaller is more dramatic: the node subtends more of the field of view, so\n * the convergence is stronger. Somewhere around 800–1500 reads like a page\n * on a desk; a few hundred reads like a wide-angle lens.\n *\n * Declared per node rather than inherited from an ancestor, which is where\n * CSS puts it. A scene graph has no viewport element to hang it on, and a\n * node that carries its own is one that can be handed around, nested and\n * animated without its depth depending on where it was dropped.\n */\n perspective: number;\n /**\n * Whether the node still paints once it has turned past edge-on and is\n * showing its back — CSS's `backface-visibility`, defaulted the CSS way\n * (`visible`).\n *\n * Set it `false` for the card-flip: two nodes back to back, one at\n * `rotationY: 0` and one at `180`, each hidden exactly while the other faces\n * out. The test is the tilt alone (see `facesAway`) — a {@link flipHorizontal}\n * mirrors the node without turning it around, so it does not hide it.\n */\n backfaceVisible: boolean;\n /**\n * The point every rotation, scale and mirror turns about — CSS's\n * `transform-origin`, in the same `[-1, 1]` vocabulary as {@link pivot}\n * (a named alignment, or a {@link Vector2} where `(0,0)` is the centre).\n *\n * Unset (the default) it *is* the pivot, so a node keeps turning about\n * whatever its alignment positioning gave it and nothing changes. Set, it wins\n * for the whole transform rather than for the 3D half of it — one origin, the\n * way CSS has one. A second origin that only some of the rotations respected\n * would produce a picture nobody could predict.\n */\n transformOrigin: Alignment;\n /**\n * All of the above in one bag — construction sugar, expanded into the\n * individual props before anything reads them (exactly as {@link size} is\n * expanded into `width`/`height`), so `set()`, `to()` and reactive callbacks\n * all behave identically whichever form is used.\n *\n * ```ts\n * Rect({ transform3D: { rotationX: 45, rotationY: -17, perspective: 900 } })\n * card().to({ transform3D: { rotationY: 180 } }, 0.8)\n * ```\n *\n * `rotationZ` is the block's own in-plane rotation and is **not** the node's\n * {@link rotation} under another name — see its note for what separates them.\n */\n transform3D: NodeTransform3D;\n\n // ---- Alignment-based positioning -----------------------------------------\n // Pass any one of these instead of (or in addition to) x/y.\n // The node will reactively offset itself so the named alignment lands at the\n // given scene-space position. Callbacks are supported and re-evaluated\n // whenever the referenced value or this node's layout changes.\n center: Vector2 | (() => Vector2);\n topLeft: Vector2 | (() => Vector2);\n topRight: Vector2 | (() => Vector2);\n bottomLeft: Vector2 | (() => Vector2);\n bottomRight: Vector2 | (() => Vector2);\n topCenter: Vector2 | (() => Vector2);\n bottomCenter: Vector2 | (() => Vector2);\n centerLeft: Vector2 | (() => Vector2);\n centerRight: Vector2 | (() => Vector2);\n\n /**\n * Proportional share of the free space along the parent's main axis,\n * relative to sibling `fill` children (like Flutter's `Expanded(flex:)`).\n * Only meaningful when this node fills the main axis — in a row that's\n * `width:'fill'`, in a column `height:'fill'`. Two siblings with `flex` 2\n * and 1 split the free space 2:1. Defaults to 1. Specifying `flex` without\n * an explicit `width`/`height` defaults both to `'fill'`.\n */\n flex: number;\n\n // ---- Grid placement (only read by a parent whose `flow` is 'grid') -------\n /** 1-based column index for explicit grid placement. Undefined = auto-placed. */\n column: number;\n /** 1-based row index for explicit grid placement. Undefined = auto-placed. */\n row: number;\n /** How many grid columns this child spans. Default 1. */\n colSpan: number;\n /** How many grid rows this child spans. Default 1. */\n rowSpan: number;\n}\n\n/**\n * The 2D tree's base: what every `component2d` lowers onto, and the scene root\n * ({@link Canvas2D}). It wires together three systems:\n *\n * **Properties** — each declared prop is backed by a {@link PropSlot}, which\n * holds either a value or a thunk. {@link set} updates props imperatively, and\n * a callback `() => expr` binds one to a derived value.\n *\n * **Tweening** — `to({ data, duration, easing })` returns a {@link Command}\n * that animates props to target values, evaluable at a time via `at(t)`.\n * `moveTo`, `fadeTo`, `rotateTo`, `scaleTo` and the rest wrap it.\n *\n * **Layout** — `measure()` is called top-down to resolve sizes, then\n * `layout()` places the node in its allocated `BoxBounds` and its children in\n * its content box.\n *\n * ### Built-in visual props\n * | prop | default | unit / notes |\n * |-----------|----------|---------------------------------------|\n * | `x` | 0 | horizontal offset in scene pixels |\n * | `y` | 0 | vertical offset (positive = up) |\n * | `width` | `'fill'` | `SizeInput`: px, `'fill'`, `'auto'` |\n * | `height` | `'fill'` | same |\n * | `size` | — | sugar: sets `width` and `height` together |\n * | `scale` | 1 | uniform scale factor |\n * | `rotate` | 0 | degrees, clockwise |\n * | `opacity` | 1 | 0–1 |\n * | `blend` | `'pass-through'` | layer blend mode (`NodeBlendMode`) |\n * | `effects` | [] | post-process / blend effects |\n * | `padding` | 0 | inner spacing, all four edges |\n */\nexport class Node2D<P extends Node2DProps = Node2DProps> extends Node<P> {\n get dimension(): NodeDimension { return \"2d\"; }\n\n /**\n * This node's parent, when that parent is itself 2D.\n *\n * A `Node2D` can only ever be adopted by another `Node2D` (see\n * {@link Node.acceptsChild}), so this is `null` only for a detached node or\n * the root — but it is typed honestly rather than cast, because the base\n * tree holds both dimensions.\n */\n protected get parent2D(): Node2D | null {\n const parent = this._parent;\n return parent instanceof Node2D ? parent : null;\n }\n\n /**\n * This node's parent, narrowed to the 2D tree.\n *\n * Only a `Node2D` can adopt a `Node2D` (see {@link Node.acceptsChild}), so\n * this never hides a real parent — it just spares every 2D caller a cast.\n */\n override get parent(): Node2D | null {\n if (_observer !== null) _observer.read(this._structureSlot());\n return this.parent2D;\n }\n\n /**\n * This node's children **in the 2D tree**.\n *\n * `Canvas3D` is the one node that holds both dimensions, and its `Node3D`\n * children are not part of the 2D tree — they describe a scene it paints,\n * not boxes it lays out — so they are reached through its own accessor\n * instead. Every other node's list is already 2D, and this returns the live\n * array untouched in that case rather than allocating a copy per read.\n */\n override get children(): Node2D[] {\n if (_observer !== null) _observer.read(this._structureSlot());\n const all = this._children;\n for (let i = 0; i < all.length; i++) {\n if (!(all[i] instanceof Node2D)) {\n return all.filter((c): c is Node2D => c instanceof Node2D);\n }\n }\n return all as Node2D[];\n }\n\n constructor(props?: NodeConfig<any, P>) {\n super(props);\n\n // Expand the `size` and `transform3D` sugar into the props they name\n // before anything reads either — in place, so the single object `super()`\n // retained as `_props` already carries the expanded values.\n if (props) {\n size2DOps.expand(props as Record<string, unknown>);\n expandTransform3D(props as Record<string, unknown>);\n }\n\n // Fires the ref, adopts the seed, and applies every `property` default.\n // Deferred to here rather than run by `super()` because the cells those\n // props write into are this class's own fields, and a subclass's field\n // initializers only run once `super()` has returned.\n this.initProps(props);\n\n // Specifying `flex` signals intent to fill the parent's main axis, so an\n // unspecified width/height defaults to 'fill' (flex is a no-op on a\n // fixed/hug axis) and skips the has-children default below.\n if (props && (props as any).flex !== undefined) {\n if (props.width === undefined) this.applyProp(\"width\", \"fill\", { tween: sizeInputOps.lerp });\n if (props.height === undefined) this.applyProp(\"height\", \"fill\", { tween: sizeInputOps.lerp });\n } else {\n this.applyDefaultSize(props);\n }\n\n // Alignment-based positioning: validate, derive pivot, bind x/y. The pivot\n // and centre offset math lives in alignmentOps (shared with the\n // `to()` path); here we use its reactive binding form.\n if (props) {\n alignmentOps.validateProps(props as Record<string, unknown>);\n const alignmentKey = alignmentOps.findKey(props as Record<string, unknown>);\n if (alignmentKey) {\n const raw = (props as any)[alignmentKey] as Vector2 | (() => Vector2);\n const getTarget: () => Vector2 = typeof raw === 'function' ? raw : () => raw;\n const { pivot, x, y } = alignmentOps.bindTarget(alignmentKey, getTarget, () => this._layoutBounds.get());\n this._writeProp('pivot', pivot);\n this._writeProp('x', x);\n this._writeProp('y', y);\n }\n }\n\n this.adoptChildrenProp(props);\n }\n\n /**\n * The 2D half of `set()`: `size` and `transform3D` are sugar with no slot of\n * their own, so they are distributed into the props that do have one before\n * the generic write loop runs.\n */\n override set(props: { [K in keyof P]?: P[K] | (() => P[K]) }): void {\n // `size` has no slot of its own — it's sugar written straight to\n // width/height (explicit width/height in the same call still wins).\n const sizeVal = (props as any).size;\n // Same for `transform3D`, but expanded up front rather than after the\n // loop: its fields are real props, so distributing them into `props`\n // first means the generic loop writes them like any other key. Only the\n // present-and-an-object case allocates, which is the rare one.\n if ((props as any).transform3D !== undefined) {\n props = { ...props };\n expandTransform3D(props as Record<string, unknown>);\n }\n super.set(props);\n if (sizeVal !== undefined) {\n if ((props as any).width === undefined) this._writeProp('width', sizeVal);\n if ((props as any).height === undefined) this._writeProp('height', sizeVal);\n }\n }\n\n /**\n * The 2D half of `_prepareStep`: expand the positional sugar into the props\n * that actually have cells, then let the base resolve the step.\n *\n * `to` is mutated in place, so the base sees the expanded target — which is\n * why this can run entirely before `super`.\n */\n override _prepareStep(to: Partial<P>, duration: number, easing?: EasingFunction): TweenStepper {\n // `size` has no slot of its own — expand it into width/height targets\n // before anchor validation and the per-key tween setup below see it.\n // `transform3D` is sugar in the same way, so it expands here too and its\n // fields tween individually, exactly as if they had been named directly.\n size2DOps.expand(to as Record<string, unknown>);\n expandTransform3D(to as Record<string, unknown>);\n\n // `pivot`: an explicit, transient origin for *this step's* rotation and\n // scale — `moveTo`/`rotateTo`/`scaleTo`'s own option (see their object-form\n // overloads below), or just as well a bare key on a `to()` target. Not a\n // real prop — nothing on the node holds a value named `pivot` that a tween\n // interpolates — so it's read and stripped before anything else here (the\n // alignment validation included) ever sees it.\n const explicitPivot = (to as { pivot?: Alignment }).pivot;\n if (explicitPivot !== undefined) delete (to as { pivot?: Alignment }).pivot;\n\n alignmentOps.validateProps(to as Record<string, unknown>);\n\n // If an alignment key is in the tween target, resolve it to x/y targets and\n // set the transform origin (one-shot form of the shared alignment math in\n // alignmentOps).\n const alignmentKey = alignmentOps.findKey(to as Record<string, unknown>);\n if (alignmentKey) {\n const raw = (to as any)[alignmentKey] as Vector2;\n const { pivot, x, y } = alignmentOps.resolveTargetOnce(alignmentKey, this._layoutBounds.get(), raw);\n // Was `this._writeProp('pivot', pivot)`. `pivot` is the node's\n // *permanent* rotation/scale origin — set once, reactively, at\n // construction (see `alignmentOps.bindTarget`) from whichever alignment prop\n // positions it there. A *tween's* target used to overwrite that\n // permanent value with its own alignment every time one was used to\n // state a position, which means a `moveTo` aligned differently from\n // the node quietly re-pointed every rotation that ran after it.\n // `transformOrigin` (see its own doc) is the right prop for this\n // instead: it wins for the whole transform without being the node's\n // one true pivot. An explicit `pivot` given on this same step (via\n // `moveTo`/`rotateTo`/`scaleTo`'s object form) overrides the\n // alignment-derived value in turn — the point a position is stated\n // against and the point a rotation turns about are two different\n // questions once a step can state them separately.\n this._writeProp('transformOrigin', explicitPivot !== undefined ? alignmentOps.resolve(explicitPivot) : pivot);\n (to as any).x = x;\n (to as any).y = y;\n } else if (explicitPivot !== undefined) {\n this._writeProp('transformOrigin', alignmentOps.resolve(explicitPivot));\n }\n\n return super._prepareStep(to, duration, easing);\n }\n\n /**\n * A component's paint entries declare themselves, so only a node painting\n * something its attributes do not describe has anything to add.\n */\n override declareAssets(assets: AssetScope): void {\n assets.effects(this.effects as NodeEffect[]);\n }\n\n /** Sample this node's own derived render state for the current frame. */\n override _sample(): void {\n this._sampleMotion();\n }\n\n /**\n * Record this node's current position as the motion history's previous\n * frame, stamped `at`, deriving no velocity — see the base's note.\n */\n override _primeMotion(at: number): void {\n const r = this.layoutBounds;\n const o = this._offset();\n primeMotion(\n this._motionHistory,\n (r?.x ?? 0) + o.x,\n (r?.y ?? 0) - o.y,\n this.rotation,\n this.scale,\n at,\n );\n }\n\n // ---- Visual properties ------------------------------------------------\n\n declare x: number;\n declare y: number;\n declare width: SizeInput;\n declare height: SizeInput;\n declare scale: number;\n declare rotation: number;\n declare opacity: number;\n declare blend: NodeBlendMode;\n declare effects: Effect;\n declare padding: Insets;\n\n declare readonly pivot: Alignment;\n\n // ---- Mirrors and the third dimension -----------------------------------\n // See the matching entries on Node2DProps for what each one means. The\n // angles and depth are plain numeric cells, so they tween like x/y/rotation\n // do; the booleans snap at the end of a tween the way every other discrete\n // cell does. `perspective` is the one exception — see {@link lerpPerspective}.\n\n /** Mirror across the vertical centre line. See {@link Node2DProps.flipHorizontal}. */\n declare flipHorizontal: boolean;\n /** Mirror across the horizontal centre line. See {@link Node2DProps.flipVertical}. */\n declare flipVertical: boolean;\n /** Tilt about the horizontal axis, degrees. See {@link Node2DProps.rotationX}. */\n declare rotationX: number;\n /** Tilt about the vertical axis, degrees. See {@link Node2DProps.rotationY}. */\n declare rotationY: number;\n /** The 3D block's in-plane rotation, degrees — distinct from {@link rotation}. See {@link Node2DProps.rotationZ}. */\n declare rotationZ: number;\n /** Push along the view axis, px. See {@link Node2DProps.depth}. */\n declare depth: number;\n /**\n * Viewer distance in px; `0` is a parallel projection. See\n * {@link Node2DProps.perspective}.\n *\n * Tweened in reciprocal space ({@link lerpPerspective}), not linearly: the\n * renderer's own projection math varies with `1/perspective`, so a plain\n * lerp of the raw distance sweeps through the near-zero numbers next to\n * \"off\" and flashes an exaggerated, near-degenerate projection right at the\n * start of a `0 → n` tween (or the end of an `n → 0` one) before settling\n * to the depth actually asked for.\n */\n declare perspective: number;\n /** Whether the node paints while showing its back. See {@link Node2DProps.backfaceVisible}. */\n declare backfaceVisible: boolean;\n /**\n * The point the transform turns about, overriding {@link pivot}. See\n * {@link Node2DProps.transformOrigin}.\n *\n * `undefined` until set — that absence *is* \"follow the pivot\", which no\n * default value could say, since every alignment is a real point including the\n * centre. Same shape as the `column`/`row` cells above. Declared with a plain\n * `property` rather than `alignmentProperty()` for exactly that reason: that one\n * folds a missing `default` back onto `'center'`.\n */\n declare transformOrigin: Alignment | undefined;\n\n /** When true, content drawn by this node's children is clipped to its outline (see {@link clipSelf}). */\n declare clip: boolean;\n\n declare flex: number;\n /**\n * Per-child weight for the flex gap this node contributes to its parent's\n * main axis, in `[0, 1]`. Default `1` = a full gap on each side (normal\n * layout). Driven `0 → 1` (insert) / `1 → 0` (remove) by the animated\n * `addChildAt`/`removeChildAt` overloads so the surrounding gap opens/closes\n * in lockstep with the child's box instead of popping — see\n * {@link addChildAtAnimated}. Read only by flex containers off their\n * children.\n *\n * Rarely set by hand, but it has to be *settable*: a host collapsing a child\n * in place rather than removing it — which is what makes a show/hide a value\n * a time can produce instead of an effect that has to have run — needs the\n * gap to close with it. Declared on {@link Node2DProps} for that reason; it\n * used to be reachable only through a cast, which is why the lifecycle\n * helpers carry one.\n */\n declare gapScale: number;\n declare column: number | undefined;\n declare row: number | undefined;\n declare colSpan: number;\n declare rowSpan: number;\n\n private readonly _layoutBounds = new PropSlot<BoxBounds>({ x: 0, y: 0, width: 0, height: 0 }, this, LAYOUT_SLOT);\n\n /**\n * The size limits and the measurer threaded through this node's last\n * {@link measure} pass.\n *\n * Retained so off-tree work can measure a not-yet-attached child *in\n * isolation* — the animated child-insert in `node-lifecycle.ts` needs a hug\n * child's natural size without putting it in this node's flow first, or the\n * siblings shift for a frame. Undefined until this node is first measured.\n *\n * One object rather than two loose fields, because the two are only ever\n * useful together and were previously reached through a\n * `{ constraints?; _lastScope? }` structural cast from two other modules —\n * a cast that would have gone on compiling through any rename.\n *\n * @internal\n */\n lastMeasure?: { constraints: SizeConstraints; measurer: MeasureContext2D };\n\n /**\n * The box the last layout pass allocated this node: its size, and where it\n * sits in its parent's space (canvas y-down).\n *\n * Reactive — a read inside a binding is tracked, so a prop bound to another\n * node's box re-evaluates when that box moves.\n *\n * **Public, and a single member.** It used to be a `protected layoutRect`\n * plus a public `measuredRect` alias that existed only so the picking walk\n * could reach it — and, in practice, a `(node as any).layoutRect` cast in\n * every test that needed a box. Two names for one value, one of them\n * reachable only by lying to the compiler, is worse than the thing\n * `protected` was buying. Writing it is still {@link setLayoutBounds}, which\n * is where the layout engine's invariants live.\n */\n get layoutBounds(): BoxBounds { return this._layoutBounds.get(); }\n\n /**\n * {@link flattenChildrenProp}, narrowed to the children this node will\n * actually lay out — a 3D or audio child sits in the same `children` prop but\n * takes no part in 2D layout, so it can't inform the size defaults either.\n */\n protected static flowChildrenProp(props: { children?: unknown } | undefined): Node2D[] {\n return Node2D.flattenChildrenProp(props).filter((c): c is Node2D => c instanceof Node2D);\n }\n\n /**\n * True if any of `children` requests `\"fill\"` on `axis` — the signal a\n * component's size default reads to decide whether hugging on that axis\n * would strand the child with no space to fill into.\n */\n protected static hasFillChild(children: Node2D[], axis: \"width\" | \"height\"): boolean {\n return children.some((c) => (axis === \"width\" ? c.width : c.height) === \"fill\");\n }\n\n /**\n * Default for `width`/`height`: hug-to-content when the node is given\n * children, fill-the-parent when it's empty. Called once from the\n * constructor (skipped when `flex` is set, since that already implies\n * 'fill'); `component2d` replaces it with the component rule.\n */\n protected applyDefaultSize(props?: NodeConfig<any, P>): void {\n const hasChildren = Node2D.flowChildrenProp(props).length > 0;\n const defaultSize = hasChildren ? \"hug\" : \"fill\";\n if (!props || props.width === undefined) this.applyProp(\"width\", defaultSize, { tween: sizeInputOps.lerp });\n if (!props || props.height === undefined) this.applyProp(\"height\", defaultSize, { tween: sizeInputOps.lerp });\n }\n\n // ---- Motion helpers ---------------------------------------------------\n //\n // Each returns the `Command` it delegates to rather than wrapping it in\n // anything, because the wrapper would discard the thing worth having: a\n // `Command` can be *evaluated* at a time, and anything that merely advances\n // can only be run to one.\n\n /**\n * Animate `x`/`y` to the given position, along `path`, or onto another node.\n * `pivot` (optional) sets {@link Node2DProps.transformOrigin} — the point\n * later rotate/scale turn about — independent of the node's own permanent\n * {@link pivot}, and it carries forward like any other prop until something\n * restates it.\n *\n * `path` replaces the destination rather than qualifying it — stating both is\n * an error, since the path's own end is where the move ends — and the node\n * walks it by **arc length**, so easing shapes the travel rather than the\n * curve's parameter. Its coordinates *are* `x`/`y` values, in the same y-up\n * space a `PathCommand[]` is authored in library-wide: the path says where\n * the node is at `t`, not how far it has come from wherever the previous\n * command left it.\n *\n * `target` is a node id and `targetAnchor` the point of its box to land on\n * (centre when absent), resolved when the command is built — so moving the\n * target re-aims the move with nothing to re-author, and a target absent at\n * that moment leaves the node where it is. Like `path`, it replaces `x`/`y`.\n * Given a `path` as well, the path is turned and scaled about its own start\n * until its end lands on the target, which is exact where the two already\n * agree and keeps the curve's shape where the target has since moved.\n *\n * @example\n * node.moveTo({ data: { x: 200, y: 100, pivot: 'topRight' }, duration: 0.5 });\n * node.moveTo({ data: { path: new PathBuilder().arc({ width: 600, startAngle: 180, sweep: -180 }) }, duration: 2 });\n * node.moveTo({ data: { target: 'card', targetAnchor: 'topRight' }, duration: 1 });\n */\n moveTo(\n args: CommandArgs<{\n x?: number;\n y?: number;\n path?: PathData | PathBuilder;\n target?: string;\n targetAnchor?: Alignment;\n pivot?: Alignment;\n }> & { duration: number },\n ): Command<P> {\n const { path, target, targetAnchor, ...destination } = args.data ?? {};\n const positioned = destination.x !== undefined || destination.y !== undefined;\n const aimed = typeof target === \"string\" && target !== \"\";\n if (aimed && positioned) {\n throw new Error(\n \"moveTo takes a `target` or an `x`/`y` destination, not both — the target's anchor is where the move ends.\",\n );\n }\n const aim = aimed ? this._pointOnNode(target, targetAnchor) : null;\n if (path === undefined || path === null) {\n return this.to({ data: { ...destination, ...aim } as Partial<P>, duration: args.duration, easing: args.easing });\n }\n if (positioned) {\n throw new Error(\n \"moveTo takes a `path` or an `x`/`y` destination, not both — the path's own end is where the move ends.\",\n );\n }\n const sampler = pathOps.sampler(path instanceof PathBuilder ? path.toCommands() : path);\n const { length } = sampler;\n const first = sampler.frameAt(0);\n const last = sampler.frameAt(length);\n const fit = aim && first && last ? pathOps.endFit(first, last, aim) : null;\n const origin = destination.pivot;\n return this.command<P>((t) => {\n const frame = sampler.frameAt(length * t);\n // A degenerate path has no point to be at, so the move writes\n // nothing rather than collapsing the node onto the origin.\n if (!frame) return {} as Partial<P>;\n const point = fit ? fit(frame) : frame;\n const at = { x: point.x, y: point.y } as Partial<P>;\n if (origin !== undefined) (at as { transformOrigin?: Alignment }).transformOrigin = origin;\n return at;\n }, args.duration, args.easing);\n }\n\n /** Animate `opacity` to the target value, in `[0, 1]`. */\n fadeTo(args: CommandArgs<{ opacity: number }> & { duration: number }): Command<P> {\n return this.to({ data: args.data as Partial<P>, duration: args.duration, easing: args.easing });\n }\n\n /**\n * Animate `rotation` to the target angle (degrees, clockwise). `pivot`\n * (optional) behaves as in {@link moveTo}.\n *\n * @example\n * node.rotateTo({ data: { rotation: 180, pivot: 'topRight' }, duration: 0.6 });\n */\n rotateTo(args: CommandArgs<{ rotation: number; pivot?: Alignment }> & { duration: number }): Command<P> {\n return this.to({ data: args.data as Partial<P>, duration: args.duration, easing: args.easing });\n }\n\n /**\n * Animate `scale` to the target factor. `pivot` (optional) behaves as in\n * {@link moveTo}.\n *\n * @example\n * node.scaleTo({ data: { scale: 2, pivot: 'topRight' }, duration: 0.4 });\n */\n scaleTo(args: CommandArgs<{ scale: number; pivot?: Alignment }> & { duration: number }): Command<P> {\n return this.to({ data: args.data as Partial<P>, duration: args.duration, easing: args.easing });\n }\n\n /**\n * Animate the box: `width`, `height` and `padding`, whichever are given.\n * A size keyword (`'fill'`, `'hug'`) snaps; a number interpolates.\n *\n * @example\n * node.layoutTo({ data: { width: 640, height: 360 }, duration: 0.5 });\n */\n layoutTo(args: CommandArgs<{ width?: SizeInput; height?: SizeInput; padding?: Insets }> & { duration: number }): Command<P> {\n return this.to({ data: _stated(args.data) as Partial<P>, duration: args.duration, easing: args.easing });\n }\n\n /**\n * Swell to `factor` times the node's size and settle back: a nudge of the\n * eye toward it. It ends as it began, so nothing after it needs restating.\n *\n * @example\n * node.pulse({ data: { factor: 1.3 }, duration: 0.6 });\n */\n pulse(args: CommandArgs<{ factor?: number }> & { duration: number }): Command<P> {\n const rest = this.scale;\n const factor = args.data?.factor ?? 1.2;\n return this.command<P>(\n (t) => ({ scale: rest * (1 + (factor - 1) * Math.sin(Math.PI * t)) }) as Partial<P>,\n args.duration,\n args.easing,\n );\n }\n\n /**\n * Rock about the node's own turn, `angle` degrees each way for `turns`\n * swings, building up and dying away. It ends as it began.\n *\n * @example\n * node.wiggle({ data: { angle: 10, turns: 4 }, duration: 0.8 });\n */\n wiggle(args: CommandArgs<{ angle?: number; turns?: number }> & { duration: number }): Command<P> {\n const rest = this.rotation;\n const angle = args.data?.angle ?? 8;\n const turns = args.data?.turns ?? 3;\n return this.command<P>(\n (t) => ({ rotation: rest + angle * Math.sin(2 * Math.PI * turns * t) * Math.sin(Math.PI * t) }) as Partial<P>,\n args.duration,\n args.easing,\n );\n }\n\n /** Animate the `effects` stack to another one. */\n effectTo(args: CommandArgs<{ effects: Effect }> & { duration: number }): Command<P> {\n return this.to({ data: _stated(args.data) as Partial<P>, duration: args.duration, easing: args.easing });\n }\n\n // ---- Layout queries ---------------------------------------------------\n\n get measuredWidth(): number {\n return this.layoutBounds.width;\n }\n\n get measuredHeight(): number {\n return this.layoutBounds.height;\n }\n\n // ---- Alignment points ----------------------------------------------------\n // All getters read `layoutBounds` and the x/y/rotation props, and a bound prop\n // recomputes on every read — so a callback built from them is always current.\n\n /** Rotate offset (ox, oy) by this node's rotation (degrees clockwise) around the node center. */\n private _rotateOffset(ox: number, oy: number): Vector2 {\n const o = this._offset();\n return rotateOffset(o.x, o.y, this.rotation, ox, oy);\n }\n\n /** Center of the node — equivalent to its x/y position (0,0 is the center of the layout cell). */\n get center(): Vector2 {\n const o = this._offset();\n return { x: o.x, y: o.y };\n }\n\n get topLeft(): Vector2 {\n const r = this.layoutBounds;\n return this._rotateOffset(-r.width / 2, r.height / 2);\n }\n\n get topRight(): Vector2 {\n const r = this.layoutBounds;\n return this._rotateOffset(r.width / 2, r.height / 2);\n }\n\n get bottomLeft(): Vector2 {\n const r = this.layoutBounds;\n return this._rotateOffset(-r.width / 2, -r.height / 2);\n }\n\n get bottomRight(): Vector2 {\n const r = this.layoutBounds;\n return this._rotateOffset(r.width / 2, -r.height / 2);\n }\n\n get topCenter(): Vector2 {\n const r = this.layoutBounds;\n return this._rotateOffset(0, r.height / 2);\n }\n\n get bottomCenter(): Vector2 {\n const r = this.layoutBounds;\n return this._rotateOffset(0, -r.height / 2);\n }\n\n get centerLeft(): Vector2 {\n const r = this.layoutBounds;\n return this._rotateOffset(-r.width / 2, 0);\n }\n\n get centerRight(): Vector2 {\n const r = this.layoutBounds;\n return this._rotateOffset(r.width / 2, 0);\n }\n\n // ---- Global (world-space) transform -----------------------------------\n // The local alignment getters above are relative to this node's *parent*; their\n // global counterparts below fold in the full ancestor chain so a node can be\n // aligned to another regardless of where each sits in the tree:\n // new Rect({ x: () => other().global.x, y: () => other().global.y })\n // Each read walks this node's and every ancestor's live\n // layout/x/y/rotation/scale/pivot props, so a binding over them stays current.\n\n /**\n * This node's local transform in canvas (y-down) space — position, rotation,\n * scale, about its origin. Composed with the parent chain by\n * {@link worldMatrix}, and the matrix every world-space *reading* of the node\n * comes from: {@link global}, `runtime/node-picking.ts`, and so any editor\n * overlay drawn on top of a scene.\n *\n * **It is flat, deliberately, and the renderer's is not.** A node that\n * mirrors or tilts ({@link Node2DProps.rotationX}, {@link Node2DProps.perspective},\n * {@link Node2DProps.flipHorizontal}, …) is *painted* through a projected\n * matrix, but goes on measuring, reporting and hit-testing as the upright\n * rectangle it was — see {@link applyTransform}.\n *\n * That is a choice, not an oversight. Everything that reads a node's box\n * reads it to put a handle on: a selection outline, a resize grip, a rotation\n * dial, `other.global.topRight` as an alignment target. Those all mean\n * something on a rectangle and stop meaning it on a trapezoid — a \"width\"\n * handle on a foreshortened edge does not correspond to any number, and a\n * corner that has swung behind the viewer has no screen position at all.\n * Letting the projection through would make the tilt a thing that quietly\n * breaks every other tool in the editor; keeping the geometry flat makes it\n * exactly what it looks like, a way of drawing the node.\n */\n /** @internal Composed with the camera scopes in between by `runtime/node-picking.ts`. */\n _localMatrix(): Matrix2D {\n const r = this.layoutBounds;\n const slot = this._slotMatrix();\n const { x: ox, y: oy } = this._offset();\n if (slot) {\n return multiply(slot, localMatrix(\n ox, -oy, this.rotation, this.scale, this._transformOrigin(),\n r?.width ?? 0, r?.height ?? 0,\n ));\n }\n const cx = (r?.x ?? 0) + ox;\n const cy = (r?.y ?? 0) - oy;\n // The accessor stores the resolved normalised pivot via the mapper.\n // No projection: see the note above for why a node's *geometry* stays\n // flat while its paint does not.\n return localMatrix(\n cx, cy, this.rotation, this.scale, this._transformOrigin(),\n r?.width ?? 0, r?.height ?? 0,\n );\n }\n\n /** @internal The slot {@link _placementOf} puts this node in, from its parent. */\n _placement(): ChildPlacement | null {\n return this.parent2D?._placementOf(this) ?? null;\n }\n\n /**\n * The slot this node places `child` in beyond its layout box, or `null` —\n * the default — when the box says it all. A layout that turns, scales or\n * fades each of its children answers here, and the renderer, picking and\n * `global` all follow. See {@link ChildPlacement}.\n */\n /** @internal */\n _placementOf(_child: Node2D): ChildPlacement | null {\n return null;\n }\n\n /**\n * The coordinates `child`'s `x`/`y` are in, or `null` — the default — when\n * they are pixels. A `null` child asks for one that is not here yet: where\n * a host would drop or paste it. See {@link ChildPlane}.\n */\n /** @internal */\n _planeOf(_child: Node2D | null): ChildPlane | null {\n return null;\n }\n\n /**\n * Where its own layout would centre a child of `size` that is not here yet,\n * y-down from its centre, or `null` when it arranges its children in a run\n * or a grid (the run decides) or has not laid any out.\n */\n /** @internal */\n _slotFor(size: Size2D): Vector2 | null {\n const space = this._childSpace;\n const box = space ? flowOps.freeSlot(space.settings, space.inner, size) : null;\n return space && box ? { x: space.inner.x + box.x, y: space.inner.y - box.y } : null;\n }\n\n /**\n * Where its centre sits from the point its `x`/`y` place, in its parent's\n * frame, y-down, at `rotation` and `scale`: what turning or scaling about an\n * off-centre pivot adds.\n */\n /** @internal */\n _centreShift(rotation = this.rotation, scale = this.scale): Vector2 {\n const r = this.layoutBounds;\n const own = localMatrix(0, 0, rotation, scale, this._transformOrigin(), r?.width ?? 0, r?.height ?? 0);\n return applyToPoint(own, { x: 0, y: 0 });\n }\n\n /** The points an editor may drag on this node, where they sit now; none by default. See {@link NodeHandle}. */\n /** @internal */\n _handles(): readonly NodeHandle[] {\n return NO_HANDLES;\n }\n\n /** The value `prop` takes for its handle to sit at `at`, in this node's own frame; `null` when it has none. */\n /** @internal */\n _handleValue(_prop: string, _at: Vector2): Vector2 | null {\n return null;\n }\n\n private readonly _offsetScratch: Vector2 = { x: 0, y: 0 };\n\n /**\n * This node's `x`/`y` as the pixel offset its parent sees. Every position\n * read goes through here, which is what keeps paint, picking and `global`\n * agreeing under a {@link ChildPlane}. The result is reused: read it at once.\n */\n /** @internal */\n _offset(): Vector2 {\n const plane = this.parent2D?._planeOf(this);\n if (plane) return plane.toOffset(this.x, this.y);\n const o = this._offsetScratch;\n o.x = this.x;\n o.y = this.y;\n return o;\n }\n\n /**\n * The flat part of this node's slot, as the frame its own `x`/`y` move in —\n * the layout box's centre, turned and scaled by the slot. `null` when it has\n * no slot. With `paint`, the slot's tilt as well, which only paint sees.\n */\n /** @internal Also the plane `runtime/node-picking.ts` drags a placed node across. */\n _slotMatrix(paint = false): Matrix2D | null {\n const slot = this._placement();\n if (!slot) return null;\n const r = this.layoutBounds;\n return localMatrix(\n r?.x ?? 0, r?.y ?? 0, slot.rotation, slot.scale, ORIGIN_2D, 0, 0,\n paint ? slotProjection(slot) : undefined,\n );\n }\n\n /** @internal {@link _slotMatrix} in a space, where the slot's tilt and depth are geometry. */\n _slotAffine(): Affine3 | null {\n const slot = this._placement();\n if (!slot) return null;\n const r = this.layoutBounds;\n return nodeSpaceMatrix(r?.x ?? 0, r?.y ?? 0, slot.rotation, slot.scale, 0, 0, slotProjection(slot));\n }\n\n /**\n * The point this node's transform turns about, normalised: `transformOrigin`\n * where one is set, the alignment-derived `pivot` otherwise. One resolution,\n * read by {@link _localMatrix} and {@link applyTransform} alike.\n */\n private _transformOrigin(): Vector2 {\n return (this.transformOrigin as Vector2 | undefined) ?? (this.pivot as Vector2);\n }\n\n // Reused for the same reason `_transformScratch` is: `_localMatrix` runs once\n // per ancestor per `global` read, and the two functions that take a\n // Projection3D read it synchronously and never retain it.\n private readonly _projectionScratch: Projection3D = {\n rotationX: 0, rotationY: 0, rotationZ: 0, depth: 0, perspective: 0,\n flipHorizontal: false, flipVertical: false,\n };\n\n /**\n * This node's out-of-plane fields, gathered for the matrix builders — and for\n * the backface test. A space root overrides it, because its 3D props aim the\n * camera rather than turn the root.\n */\n protected _projection(): Projection3D {\n const p = this._projectionScratch;\n p.rotationX = this.rotationX;\n p.rotationY = this.rotationY;\n p.rotationZ = this.rotationZ;\n p.depth = this.depth;\n p.perspective = this.perspective;\n p.flipHorizontal = this.flipHorizontal;\n p.flipVertical = this.flipVertical;\n return p;\n }\n\n /** @internal This node's transform in its parent's 3D frame, when it is inside a space. See `node-space.ts`. */\n _spaceMatrix(): Affine3 {\n const r = this.layoutBounds;\n const width = r?.width ?? 0;\n const height = r?.height ?? 0;\n const origin = this._transformOrigin();\n const slot = this._slotAffine();\n const { x: ox, y: oy } = this._offset();\n if (slot) {\n return multiplyAffine3(slot, nodeSpaceMatrix(\n ox, -oy, this.rotation, this.scale,\n origin.x * (width / 2), -origin.y * (height / 2),\n this._projection(),\n ));\n }\n return nodeSpaceMatrix(\n (r?.x ?? 0) + ox, (r?.y ?? 0) - oy, this.rotation, this.scale,\n origin.x * (width / 2), -origin.y * (height / 2),\n this._projection(),\n );\n }\n\n /**\n * This node's full transform in canvas (y-down) world space — the product of\n * every ancestor's local matrix from the root down to this node. Walks the\n * live parent chain on every call, reading each node's transform props.\n */\n protected worldMatrix(): Matrix2D {\n const local = this._localMatrix();\n const parent = this.parent2D;\n return parent ? multiply(parent.worldMatrix(), local) : local;\n }\n\n /**\n * Resolved world-space transform — the same alignment points and metrics as the\n * local getters (`center`, `topRight`, `rotation`, …) but folded through the\n * full ancestor chain, so values are absolute scene coordinates rather than\n * parent-relative ones. See {@link WorldTransform}. Every field is reactive.\n *\n * @example\n * // Read another node's absolute corner, regardless of its parent:\n * const p = other.global.topRight; // world-space {x, y}\n *\n * ### Reading vs. placing\n * `global` is for *reading* world coordinates. `x`/`y` (and the alignment props)\n * are **parent-relative**, so assigning a world value to them does not by\n * itself place this node in world space — it offsets it from this node's own\n * parent. To land exactly on another node regardless of either parent,\n * subtract this node's parent's world contribution:\n *\n * @example\n * // Place this node's origin exactly on `other`, any parent:\n * new Rect({\n * x: () => other.global.x - (myParent.global.x),\n * y: () => other.global.y - (myParent.global.y),\n * });\n *\n * When both nodes share the same parent origin (e.g. both at the scene root),\n * `x: () => other.global.x` already lands on target with no compensation.\n */\n get global(): WorldTransform {\n const r = this.layoutBounds;\n const anchors = worldAnchors(this.worldMatrix(), (r?.width ?? 0) / 2, (r?.height ?? 0) / 2);\n\n // Accumulate ancestor rotation/scale/opacity up the chain (rotation sums,\n // scale and opacity multiply — all match the renderer's nested transforms\n // and its pass-through alpha fold).\n let rotation = 0;\n let scale = 1;\n let opacity = 1;\n for (let n: Node2D | null = this; n; n = n.parent2D) {\n const slot = n._placement();\n rotation += n.rotation + (slot?.rotation ?? 0);\n scale *= n.scale * (slot?.scale ?? 1);\n opacity *= n.opacity * (slot?.opacity ?? 1);\n }\n\n return {\n x: anchors.center.x,\n y: anchors.center.y,\n ...anchors,\n rotation,\n scale,\n opacity,\n };\n }\n\n /**\n * The `x`/`y` that put this node on `anchor` of the node `id` names, in this\n * tree — or `null` when there is no such 2D node here right now.\n */\n private _pointOnNode(id: string, anchor: Alignment | undefined): Vector2 | null {\n const target = findNode2D(this, id);\n if (!target) return null;\n\n const a = alignmentOps.resolve(anchor ?? \"center\");\n const box = target.layoutBounds;\n const world = applyToPoint(target.worldMatrix(), {\n x: a.x * ((box?.width ?? 0) / 2),\n y: -a.y * ((box?.height ?? 0) / 2),\n });\n const parent = this.parent2D;\n const toParent = parent ? invert(parent.worldMatrix()) : null;\n if (parent && !toParent) return null;\n const local = toParent ? applyToPoint(toParent, world) : world;\n const own = this.layoutBounds;\n const x = local.x - (own?.x ?? 0);\n const y = (own?.y ?? 0) - local.y;\n return parent?._planeOf(this)?.toCoords(x, y) ?? { x, y };\n }\n\n // `child` typed to the shared base because that is what a tree holds; the\n // guard below rejects a `Node3D` before it can land in a tree that would\n // never draw it. Registered as a command on {@link Node}, which owns the instant insert.\n override addChildAt(args: CommandArgs<{ child: Node; index: number }> & { duration?: undefined }): void;\n override addChildAt(args: CommandArgs<{ child: Node; index: number }> & { duration: number }): Command<Record<string, never>>;\n override addChildAt(args: CommandArgs<{ child: Node; index: number }>): void | Command<Record<string, never>> {\n const { child, index } = args.data as { child: Node; index: number };\n this.assertAcceptsChild(child);\n if (args.duration === undefined) {\n this._insertChildAt(child, index);\n return;\n }\n // Past the guard, so this is a 2D child: the animated insert measures it\n // off-tree, which only a laid-out node can do.\n return addChildAtAnimated(this, child as Node2D, index, args.duration, args.easing);\n }\n\n removeChildAt(args: CommandArgs<{ index: number }> & { duration?: undefined }): Node2D | null;\n removeChildAt(args: CommandArgs<{ index: number }> & { duration: number }): Command<Record<string, never>>;\n removeChildAt(args: CommandArgs<{ index: number }>): (Node2D | null) | Command<Record<string, never>> {\n const index = (args.data as { index: number }).index;\n if (args.duration === undefined) {\n if (index < 0 || index >= this._children.length) return null;\n if (_observer !== null) this._structureChanged(this._children[index]);\n const [removed] = this._children.splice(index, 1);\n if (removed) {\n (removed as Node2D)._parent = null;\n removed.detach();\n }\n return (removed as Node2D) ?? null;\n }\n return removeChildAtAnimated(this, index, args.duration, args.easing);\n }\n\n // ---- Rendering --------------------------------------------------------\n\n // Reused each frame so applyTransform doesn't allocate a fresh descriptor\n // per node per frame. ctx.transform reads it synchronously and never retains\n // it, so a single mutated instance is safe.\n private readonly _transformScratch: TransformState = {\n x: 0, y: 0, width: 0, height: 0,\n scale: 1, rotation: 0, opacity: 1, blend: 'pass-through',\n effects: [], pivot: { x: 0, y: 0 },\n };\n\n // ---- Motion sampling --------------------------------------------------\n // Per-node motion (velocity/direction/speed/angular/scale) is sampled once\n // per frame from ellapse() (see its call site) as a backward difference\n // against the previous frame. Sampling every advanced frame — not just\n // rendered ones — is what keeps velocity correct through a scrub/rewind,\n // which advances through frames without rendering them. Because ellapse()\n // runs before the frame's generator.next(), x/y here hold the *previous*\n // frame's value, so the velocity trails the rendered position by one frame;\n // the lag is constant and identical forward vs. scrub. Layout-dependent\n // fields (rects) can't be resolved here — layout hasn't run for advanced-\n // but-unrendered frames — so renderState() fills those in at draw time,\n // leaving the motion fields untouched.\n\n /** Rolling history for the backward-difference velocity estimate. Allocated once (not per frame); mutated in place by {@link _sampleMotion}. */\n private readonly _motionHistory: MotionHistory = createMotionHistory();\n\n /** Reused per-node state handed to `ctx.begin()` (mirrors `_transformScratch`). */\n private readonly _renderState: NodeRenderState = {\n id: this.id,\n rects: {},\n elapsed: 0,\n dt: 0,\n velocity: { x: 0, y: 0 },\n direction: 0,\n speed: 0,\n angularVelocity: 0,\n scaleVelocity: 0,\n };\n\n /**\n * Compute this frame's motion (velocity/direction/speed/angular/scale) into\n * {@link _renderState} as a backward difference against the previous frame,\n * and roll the history forward. Velocity is `0`/`{0,0}` when no trustworthy\n * delta exists — the first frame, or after a non-monotonic time jump (only\n * `0 < dt <= MAX` is trusted, so a scrub that resets the clock reads as\n * \"unknown\" rather than a spurious huge velocity). The world position\n * matches {@link applyTransform} (`layoutBounds + x`, `layoutBounds - y`,\n * y-down). Called via {@link _sample} every frame; layout-dependent fields\n * (`rects`/`elapsed`) are filled in by {@link renderState} at draw time.\n */\n protected _sampleMotion(): void {\n // Resolve the reactive world position (y-down, matching applyTransform);\n // the backward-difference math lives in sampleMotion (no per-frame alloc).\n const r = this.layoutBounds;\n const o = this._offset();\n const x = (r?.x ?? 0) + o.x;\n const y = (r?.y ?? 0) - o.y;\n sampleMotion(this._renderState, this._motionHistory, x, y, this.rotation, this.scale, this._time.total);\n }\n\n /**\n * Push this node's transform (position, scale, rotate, opacity, effects).\n *\n * The decomposed fields are the whole story for a node in its own plane, and\n * that path is untouched: the backend translates, rotates and scales exactly\n * as it always has. A node that mirrors or tilts hands over a precomposed\n * {@link TransformState.matrix} instead, built by the same `localMatrix`\n * {@link _localMatrix} calls — with the out-of-plane half switched on.\n *\n * **This is the one place that half is applied.** The mirrors and the tilt\n * are paint, not geometry: the node goes on measuring and hit-testing as the\n * upright rectangle it was, and only what is drawn is projected. See\n * {@link _localMatrix} for why.\n */\n protected applyTransform(ctx: RenderContext2D): void {\n const r = this.layoutBounds;\n const s = this._transformScratch;\n const { x: ox, y: oy } = this._offset();\n s.x = (r?.x ?? 0) + ox;\n s.y = (r?.y ?? 0) - oy;\n s.width = r?.width ?? 0;\n s.height = r?.height ?? 0;\n s.scale = this.scale;\n s.rotation = this.rotation;\n s.opacity = this.opacity;\n s.blend = this.blend;\n s.effects = this.effects as NodeEffect[];\n s.pivot = this._transformOrigin();\n const slotOpacity = this._placement()?.opacity;\n if (slotOpacity !== undefined) s.opacity *= slotOpacity;\n const frame = this._spaceFrame;\n const slot = frame ? null : this._slotMatrix(true);\n if (frame) {\n s.matrix = frame.local;\n } else if (slot) {\n s.matrix = multiply(slot, localMatrix(\n ox, -oy, s.rotation, s.scale, s.pivot, s.width, s.height, this._projection(),\n ));\n } else {\n const projection = this._projection();\n s.matrix = hasProjection3D(projection)\n ? localMatrix(s.x, s.y, s.rotation, s.scale, s.pivot, s.width, s.height, projection)\n : undefined;\n }\n ctx.transform(s);\n }\n\n /** What the node paints under its children, between the transform push and the children render: the root's fill. */\n protected renderSelf(ctx: RenderContext2D): void { }\n\n /** What the node paints over its children, clipped to its silhouette: the root's overlay. */\n protected renderOverlay(ctx: RenderContext2D): void { }\n\n /**\n * This node's outline as a {@link Clip}: the boundary `clip` confines its\n * children to, and the silhouette its backdrop effects are confined to.\n * `null` (the default) is no outline, so its children render unclipped and\n * it gets no backdrop effects. A component answers with the shape its\n * `render` paints.\n */\n protected clipSelf(): Clip | null { return null; }\n\n /**\n * The camera scope this node pushes around its **children** (`beginCamera`),\n * or `null` when it pushes none. Only {@link Canvas2D} and a component whose\n * `render` opens a camera answer, each non-null exactly when it actually\n * opens one — so a consumer can reproduce the renderer's transform *and* its\n * viewport clip without knowing which types have a camera.\n *\n * Read by `runtime/node-picking.ts`: a camera is applied at render time only,\n * so it is not part of {@link worldMatrix}, and a node's on-screen box would\n * be offset without it. `@internal`.\n */\n /** @internal */\n _cameraScope(): CameraScope | null { return null; }\n\n /**\n * The camera this node opens a 2.5D space with, or `null` when it opens none.\n * Only a space root overrides it: its children, and theirs, are then placed\n * in one 3D frame and seen through this camera. See `node-space.ts`.\n */\n /** @internal */\n _spaceCamera(): SpaceCamera | null { return null; }\n\n /**\n * Whether this node hands its children on into the space it sits in. False\n * for a node that composites its children itself — a mask, a boolean, a\n * nested camera — which flattens its subtree into its own plane, where the\n * per-node 3D rules apply again. Picking reads it; the renderer gets the same\n * answer because such a node never reaches the base {@link renderChildren}.\n */\n /** @internal */\n _rendersChildrenInSpace(): boolean { return true; }\n\n /** @internal Set by the parent for the length of this node's render while it is inside a space. */\n _spaceFrame: SpaceFrame | null = null;\n\n /**\n * Whether the renderer confines this node's children to its own box — either\n * because `clip` is set *and* the node has an outline to clip to (a bare\n * `clip` with no {@link clipSelf} is a no-op, see {@link applyClip}), or\n * because it opens a camera scope, which clips to the viewport rect.\n *\n * Read by `runtime/node-picking.ts`: a point outside a confining node cannot\n * hit anything inside it, so the whole subtree is skipped. `@internal`.\n */\n /** @internal */\n _confinesChildren(): boolean {\n if (this._cameraScope() !== null) return true;\n if (!this.clip) return false;\n const clip = this.clipSelf();\n return clip !== null && !clip.isEmpty();\n }\n\n /**\n * Whether `local` — a point in this node's local space (centred on the node,\n * y-up, rotation and scale already removed) — is inside the node, within\n * `tolerance` scene units of its edge.\n *\n * The default is the layout box, which is the right answer for containers,\n * text, and media: their box *is* their extent. A component narrows it to\n * the outline its `render` paints.\n *\n * `tolerance` is grab-slop, applied outward. An editor passes its\n * zoom-corrected pixel slop so the grab area stays constant on screen\n * regardless of preview zoom.\n */\n protected hitTestSelf(local: Vector2, tolerance: number): boolean {\n const b = this._localBounds();\n return Math.abs(local.x - b.x) <= b.width / 2 + tolerance\n && Math.abs(local.y - b.y) <= b.height / 2 + tolerance;\n }\n\n /**\n * The extent of this node's ink in its own local space — what an editor draws\n * a selection box around, and the region the default {@link hitTestSelf}\n * grabs.\n *\n * The returned {@link BoxBounds} is **y-up and relative to the node's own\n * centre**: `x`/`y` are where the ink's centre sits relative to the node,\n * normally `(0, 0)`. That is a different space from `layoutBounds`, which is\n * the same type but canvas y-down and relative to the parent — see\n * `BoxBounds`, which deliberately does not encode a space.\n *\n * Defaults to the layout box, centred on the node, which is right for every\n * node whose drawing fills its cell. It is a separate seam from the layout\n * rect because for some nodes the two genuinely differ: a boolean group or\n * a mask is drawn where its children's ink is, which can be both a different\n * size *and* off-centre from its own cell. A component's `bounds` answers\n * here, fixing the box and the grab region together without perturbing layout.\n */\n /** @internal */\n _localBounds(): BoxBounds {\n return { x: 0, y: 0, width: this.measuredWidth, height: this.measuredHeight };\n }\n\n /** @internal Dispatch seam so `node-picking.ts` can reach the protected override. */\n _hitTestSelf(local: Vector2, tolerance: number): boolean {\n return this.hitTestSelf(local, tolerance);\n }\n\n /**\n * Open `clipSelf()`'s outline as a clip scope, confining whatever is drawn\n * until the matching `ctx.endClip()` to the shape. Returns `true` when a\n * clip was actually opened (so the caller knows to close it) and `false`\n * when the node has no outline (the default).\n */\n protected applyClip(ctx: RenderContext2D): boolean {\n const clip = this.clipSelf();\n if (!clip || clip.isEmpty()) return false;\n ctx.beginClip(clip);\n return true;\n }\n\n /**\n * Apply backdrop effects (any `mode: \"backdrop\"` effect — blur, grayscale, …;\n * plus magnify and backdrop shader) beneath this node, clipped to its\n * silhouette, before the node's own content is drawn — so the content\n * underneath is filtered/warped while the node's own edges stay sharp. One\n * backdrop effect scope, confined to the silhouette clip, runs the lot; the\n * renderer routes each effect to a filter or shader pass. A no-op for nodes\n * without a {@link clipSelf} outline (there's no silhouette to confine to).\n */\n private applyBackdropEffects(ctx: RenderContext2D): void {\n const effects = this.effects as NodeEffect[];\n // Bail before building the silhouette. `applyBackdropEffectsImpl` returns\n // immediately when there are no backdrop effects, but by then `clipSelf()`\n // has already allocated a Clip and its op list for a node that will never\n // use it — and a node with no effects at all is the overwhelmingly common\n // case, so that allocation was pure waste on nearly every node, every frame.\n if (effects.length === 0) return;\n applyBackdropEffectsImpl(ctx, effects, this.clipSelf(), this.layoutBounds?.width ?? 0, this.layoutBounds?.height ?? 0);\n }\n\n /**\n * Run `body` (this node's own painting + children) inside the node's effect\n * scopes, so effects behave identically however a node draws. The caller\n * has already pushed the node's transform ({@link applyTransform}).\n * Outermost-first: {@link applyBackdropEffects} beneath the node, confined\n * to its {@link clipSelf} silhouette, then a `foreground` effect scope\n * capturing everything `body` paints.\n */\n protected renderContentWithEffects(ctx: RenderContext2D, body: () => void): void {\n this.applyBackdropEffects(ctx);\n applyContentEffectScope(ctx, this.effects as NodeEffect[], this.layoutBounds?.width ?? 0, this.layoutBounds?.height ?? 0, body);\n }\n\n protected renderChildren(ctx: RenderPass2D): void {\n // A node opening a space of its own flattens its subtree into its own\n // plane, whatever space it sits in — the same answer picking's\n // `spaceFrameOf` gives, which asks for a camera before anything else.\n const camera = this._spaceCamera();\n if (camera) {\n this._renderInSpace(ctx, spaceRootFrame(this, camera));\n return;\n }\n const frame = this._spaceFrame;\n if (frame) {\n this._renderInSpace(ctx, frame);\n return;\n }\n for (const child of this._children) if (child instanceof Node2D) child.render(ctx);\n }\n\n /**\n * Paint the children placed in `frame`, far to near rather than in authored\n * order — each with its frame set for exactly the length of its own render,\n * so a node reached any other way (a mask's children, a `Tex.surface`\n * source) draws flat.\n */\n /** @internal A space root opens its space through this. */\n protected _renderInSpace(ctx: RenderPass2D, frame: SpaceFrame): void {\n const children: Node2D[] = [];\n for (const child of this._children) if (child instanceof Node2D) children.push(child);\n const frames = children.map((child) => spaceChildFrame(frame, child));\n // Order is invisible to a walk that only discovers assets.\n const order = ctx.drawsVisibleOnly ? spaceChildOrder(frames) : frames.map((_, i) => i);\n for (const i of order) {\n const child = children[i];\n child._spaceFrame = frames[i];\n try {\n child.render(ctx);\n } finally {\n child._spaceFrame = null;\n }\n }\n }\n\n /** Run `paint` confined to `cut` — the part of the node in front of the lens — when there is one. */\n private _paintInFront(ctx: RenderContext2D, cut: Clip | null, paint: () => void): void {\n if (!cut) {\n paint();\n return;\n }\n ctx.beginClip(cut);\n try {\n paint();\n } finally {\n ctx.endClip();\n }\n }\n\n /**\n * This node's per-frame render state, resolved for the scope {@link render}\n * is about to open.\n *\n * Motion was already sampled when the clock advanced; only the\n * layout-dependent fields are filled in here, where layout is current.\n */\n private renderState(ctx: RenderContext2D): NodeRenderState {\n const s = this._renderState;\n // Skipped for contexts that never resolve a `space:'parent'` fill — the\n // precomp pass walks every node's render every frame purely to discover\n // assets, and this is an object allocation per node per frame that nothing\n // there would ever read.\n s.rects = ctx.readsSpaceRects ? this._spaceRects() : NO_SPACE_RECTS;\n s.elapsed = this._time.elapsed;\n return s;\n }\n\n /**\n * Reference rects for fills with `space:'parent'`, expressed in this node's\n * local space (origin = this node's positioned centre, y-down to match the\n * canvas). The viewport (`space:'global'`) is resolved by the renderer, which\n * knows the surface size. Rotation/scale of this node are not folded in —\n * the rect is the axis-aligned parent box, which is what gradients expect.\n */\n protected _spaceRects(): SpaceRects {\n const o = this._offset();\n return computeSpaceRects(this.parent2D?.layoutBounds, this.layoutBounds, o.x, o.y);\n }\n\n /**\n * Draw this node and its subtree: the skip checks, then this node's draw\n * scope around {@link renderContent}.\n *\n * Takes a {@link RenderPass2D} rather than a bare {@link RenderContext2D}\n * because opening this node's draw scope is *this* method's job; what it\n * calls is handed the narrower surface, so nothing below can open one.\n */\n render(ctx: RenderPass2D): void {\n // Not in the tree ⇒ no box, no surface, nothing to draw.\n if (!this.mounted) return;\n // A subtree at zero opacity paints nothing, so on a context that only\n // draws what can be seen there is no reason to walk it. Not a niche case:\n // a chart carries a full second axis at `opacity: 0` purely to reserve a\n // gutter, and every cross-fade spends its first and last frames here.\n //\n // `drawsVisibleOnly` is false on the tracking walk, which must still\n // descend — an invisible node's font and images have to be discovered or\n // they will not have loaded by the time it fades in. See the flag's doc.\n if (ctx.drawsVisibleOnly && this.opacity * (this._placement()?.opacity ?? 1) <= 0) return;\n // Hidden by the editor. Same exemption as the two checks around it: the\n // tracking walk still descends, or a node hidden and shown again would\n // come back before its fonts and images had been discovered.\n if (ctx.drawsVisibleOnly && this.hidden) return;\n // A node that has turned past edge-on and declines to show its back\n // paints nothing either — same reasoning, same walk skipped, and the same\n // exemption for the tracking pass, which still has to discover the assets\n // of a card that is currently face-down and will be face-up in a moment.\n // In a space the camera decides which way a node faces, not its own tilt.\n const frame = this._spaceFrame;\n if (ctx.drawsVisibleOnly && !this.backfaceVisible && this._facesAway(frame)) return;\n // Edge-on or behind the lens, a node whose children lie in its own plane\n // has nothing anywhere to show.\n if (ctx.drawsVisibleOnly && frame && !frame.paints && !this._rendersChildrenInSpace()) return;\n\n try {\n ctx.begin(this.renderState(ctx));\n try {\n this.renderContent(ctx);\n } finally {\n ctx.end();\n }\n } catch (error) {\n // The innermost node claims it, so the runtime can learn the segment against the node that drew.\n if (error instanceof AssetNotLoadedError) error.nodeId ??= this.id;\n throw error;\n }\n }\n\n /**\n * Everything this node paints: its transform, its effect envelope, its own\n * drawing, its children and its overlay. A component's `render` replaces it,\n * keeping every guard {@link render} performs above it.\n */\n protected renderContent(ctx: RenderPass2D): void {\n this.applyTransform(ctx);\n const frame = this._spaceFrame;\n // Edge-on or behind the lens: nothing of its own to draw and no plane to\n // draw it on, but its children are placed by frames of their own.\n if (frame && !frame.paints) {\n this.renderChildren(ctx);\n return;\n }\n const cut = frame?.nearCut ?? null;\n this.renderContentWithEffects(ctx, () => {\n this._paintInFront(ctx, cut, () => this.renderSelf(ctx));\n // Confine children to this node's outline. Built once from clipSelf();\n // skipped when the node has no outline (clipped === false) so the\n // endClip() below stays balanced.\n const clipped = this.clip && this.applyClip(ctx);\n this.renderChildren(ctx);\n if (clipped) ctx.endClip();\n this._paintInFront(ctx, cut, () => this.renderOverlay(ctx));\n });\n }\n\n /** Whether the node shows its back — to the space's camera when it is in one, else by its own tilt. */\n private _facesAway(frame: SpaceFrame | null): boolean {\n if (frame) return frame.facesAway;\n const p = this._projection();\n return facesAway(p.rotationX, p.rotationY);\n }\n\n // ---- Layout -----------------------------------------------------------\n\n /** What {@link measure} hands {@link layoutChildren} within a pass; consumed there. */\n private _flowMeasure: FlowMeasure<Node2D> | null = null;\n\n /**\n * The content box its children were last placed in, y-down from this\n * node's centre, and the flow that placed them: what {@link _slotFor}\n * answers from. A component's flow layout records it too (`Flow.layout`).\n */\n /** @internal */\n _childSpace: ChildSpace | null = null;\n private _flowWarned = false;\n\n /**\n * Record this node's allocated bounds without touching children.\n *\n * Compared field by field, because every caller builds a fresh object literal,\n * so identity always differs — including on every frame of a node that is\n * simply sitting still. Skipping the write keeps the object stable for the\n * aliasing reason below.\n */\n protected setLayoutBounds(rect: BoxBounds): void {\n const current = this._layoutBounds.get();\n if (\n current.x === rect.x\n && current.y === rect.y\n && current.width === rect.width\n && current.height === rect.height\n ) return;\n // Stores the *new* object rather than mutating the old one in place:\n // `layoutBounds` is handed out by `get()` to its public reader, to\n // `computeSpaceRects` and to bound anchor computations, and mutating it\n // under them would be an aliasing change none of them could see coming.\n this._layoutBounds.set(rect);\n }\n\n /**\n * The children this node lays out itself — its 2D children, minus the hidden\n * ones. Every measure and layout pass in a container iterates *this*, not\n * `children`.\n *\n * Returns the live array untouched in the common case, so an ordinary tree\n * allocates nothing per pass.\n */\n flowChildren(): Node2D[] {\n const children = this._children;\n // Only a hidden child — or a 3D child under a `Canvas3D` — can leave the\n // flow, and both are rare enough to be worth checking for before\n // allocating.\n let i = 0;\n for (; i < children.length; i++) {\n const child = children[i];\n if (!(child instanceof Node2D) || child.hidden) break;\n }\n if (i === children.length) return children as Node2D[];\n // A hidden child gives up its cell *and* its gap — `display: none`, not\n // `visibility: hidden`. Leaving the slot would put a hole in a row\n // wherever someone folded a layer away.\n return children.filter((c): c is Node2D => c instanceof Node2D && !c.hidden);\n }\n\n /**\n * The inset children are laid out within. A node with a stroke to clear adds\n * the part of it that intrudes (see `Paint.inset`).\n */\n effectivePadding(): InsetsResolved {\n return this.padding as InsetsResolved;\n }\n\n /**\n * How this node arranges its children: centred freeform. The root answers\n * with its own layout props; a component lays its children out with `Flow`.\n */\n protected flowArrangement(): FlowSettings {\n return DEFAULT_FLOW;\n }\n\n /** Record `rect`, then place the flow children in it — see {@link layoutChildren}. */\n layout(rect: BoxBounds, scope: MeasureContext2D): void {\n this.setLayoutBounds(rect);\n this.layoutChildren(rect, scope);\n }\n\n /**\n * Place the flow children in `rect`'s content box by {@link flowArrangement}.\n *\n * Reuses what {@link measure} found when the box is the one it measured in —\n * or, on an axis that hugs, exactly what it hugged — and measures again\n * otherwise: a parent laying this node out at a size it did not measure it\n * for would leave the children arranged for the wrong box.\n */\n protected layoutChildren(rect: BoxBounds, scope: MeasureContext2D): void {\n const pending = this._flowMeasure;\n this._flowMeasure = null;\n const inner = insetsOps.insetBounds(rect.width, rect.height, this.effectivePadding());\n const settings = this.flowArrangement();\n this._childSpace = { settings, inner };\n const children = this.flowChildren();\n if (children.length === 0) return;\n\n const measured = pending && flowOps.reusable(pending, inner)\n ? pending\n : flowOps.measure(settings, children, {\n width: inner.width,\n height: inner.height,\n hugWidth: this.width === \"hug\",\n hugHeight: this.height === \"hug\",\n }, scope);\n\n // The boxes are y-up from the content box's centre; a layout rect is y-down\n // from this node's.\n const boxes = flowOps.place(measured, settings, inner);\n for (let i = 0; i < boxes.length; i++) {\n const box = boxes[i];\n measured.items[i].layout(\n { x: inner.x + box.x, y: inner.y - box.y, width: box.width, height: box.height },\n scope,\n );\n }\n\n if (this._flowWarned) return;\n const warning = flowOps.collapsedRun(measured, rect);\n if (warning === null) return;\n this._flowWarned = true;\n console.warn(`[motionscript] \"${this.className}\" ${warning}`);\n }\n\n /**\n * Resolve `width`/`height`, measuring the flow children by\n * {@link flowArrangement}: a `'hug'` axis wraps what they come to, plus this\n * node's padding. What it finds is kept for {@link layoutChildren}.\n *\n * Only flow children are measured: a canvas-pinned child is sized against the\n * canvas, so hugging it would shrink-wrap a box this node never contains.\n */\n measure(constraints: SizeConstraints, scope: MeasureContext2D): Partial<Size2D> {\n this.lastMeasure = { constraints, measurer: scope };\n const padding = this.effectivePadding();\n const children = this.flowChildren();\n if (children.length === 0) {\n this._flowMeasure = null;\n return flowOps.size(this, constraints, padding, NO_CONTENT);\n }\n const space = flowOps.contentBox(this, constraints, padding);\n const measured = flowOps.measure(this.flowArrangement(), children, space, scope);\n this._flowMeasure = measured;\n return flowOps.size(this, constraints, padding, measured.hug);\n }\n\n // ---- Reparenting ------------------------------------------------------\n\n reparent(args: CommandArgs<{ newParent: Node2D }> & { duration?: undefined }): void;\n reparent(args: CommandArgs<{ newParent: Node2D }> & { duration: number }): Command<Record<string, never>>;\n reparent(args: CommandArgs<{ newParent: Node2D }>): void | Command<Record<string, never>> {\n const newParent = (args.data as { newParent: Node2D }).newParent;\n if (args.duration === undefined) {\n const old = this.parent;\n if (old) old.remove(this);\n newParent.add(this);\n return;\n }\n return reparentAnimated(this, newParent, args.duration, args.easing);\n }\n\n}\n\ndeclareMembers(Node2D, {\n x: property({ default: 0 }),\n y: property({ default: 0 }),\n width: property({ default: 'fill', tween: sizeInputOps.lerp }),\n height: property({ default: 'fill', tween: sizeInputOps.lerp }),\n scale: property({ default: 1 }),\n rotation: property({ default: 0 }),\n opacity: property({ default: 1 }),\n blend: property({ default: 'pass-through' }),\n effects: effectsProperty(),\n padding: insetsProperty(),\n pivot: alignmentProperty(),\n flipHorizontal: property({ default: false }),\n flipVertical: property({ default: false }),\n rotationX: property({ default: 0 }),\n rotationY: property({ default: 0 }),\n rotationZ: property({ default: 0 }),\n depth: property({ default: 0 }),\n perspective: property({ default: 0, tween: lerpPerspective }),\n backfaceVisible: property({ default: true }),\n transformOrigin: property<Alignment | undefined, Vector2 | undefined>({\n default: undefined,\n // `null` is unset too: a document read back from JSON has no `undefined`.\n mapper: (v) => (v == null ? undefined : alignmentOps.resolve(v)),\n // Tweening *into* an origin from \"no origin set\" starts where it ends —\n // there is no point to travel from, and snapping to the target's own\n // start is the one reading that isn't an invented one.\n tween: (from, to, t) => alignmentOps.lerp(from ?? to ?? ORIGIN_2D, to ?? ORIGIN_2D, t),\n }),\n clip: property({ default: false }),\n flex: property({ default: 1 }),\n gapScale: property({ default: 1 }),\n column: property({ default: undefined }),\n row: property({ default: undefined }),\n colSpan: property({ default: 1 }),\n rowSpan: property({ default: 1 }),\n\n moveTo: command({\n args: [\n \"x\",\n \"y\",\n { key: \"path\", kind: \"path\" },\n { key: \"target\", kind: \"nodeRef\" },\n { key: \"targetAnchor\", kind: \"alignment\" },\n ],\n }),\n fadeTo: command({ args: [\"opacity\"] }),\n rotateTo: command({ args: [\"rotation\"] }),\n scaleTo: command({ args: [\"scale\"] }),\n layoutTo: command({ args: [{ key: \"width\", kind: \"size\" }, { key: \"height\", kind: \"size\" }, { key: \"padding\", kind: \"insets\" }] }),\n pulse: command({ args: [{ key: \"factor\", kind: \"number\", min: 0, step: 0.05, unit: \"×\", default: 1.2 }] }),\n wiggle: command({\n args: [\n { key: \"angle\", kind: \"number\", min: 0, unit: \"°\", default: 8 },\n { key: \"turns\", kind: \"number\", min: 1, step: 1, default: 3 },\n ],\n }),\n effectTo: command({ args: [{ key: \"effects\", kind: \"effects\" }] }),\n removeChildAt: command({ args: [\"index\"] }),\n reparent: command({ args: [\"newParent\"] }),\n});\n\n/** A command's `data` without the arguments a document left out, which arrive as `undefined` and must not be tweened to. */\nfunction _stated<T extends object>(data: T | undefined): Partial<T> {\n const stated: Partial<T> = {};\n for (const key in data) {\n if (data[key] !== undefined) stated[key] = data[key];\n }\n return stated;\n}\n\n/** The 2D node `id` names anywhere in the tree `from` is in, or `null`. */\nexport function findNode2D(from: Node, id: string): Node2D | null {\n let root = from;\n while (root.parent) root = root.parent;\n return findUnder(root, id);\n}\n\nfunction findUnder(at: Node, id: string): Node2D | null {\n if (at.id === id) return at instanceof Node2D ? at : null;\n for (const child of at._allChildren) {\n const found = findUnder(child, id);\n if (found) return found;\n }\n return null;\n}\n\n/**\n * Where `node`'s frame sits in `host`'s, wherever each is in the tree: its\n * centre as an offset (y-up) from `host`'s, and its turn and scale relative to it.\n */\nexport function frameIn(host: Node2D, node: Node2D): Vector2 & Pick<WorldTransform, \"rotation\" | \"scale\"> {\n const there = node.global;\n const here = host.global;\n const inverse = here.scale === 0 ? 0 : 1 / here.scale;\n const offset = rotateOffset(0, 0, -here.rotation, (there.x - here.x) * inverse, (there.y - here.y) * inverse);\n return { x: offset.x, y: offset.y, rotation: there.rotation - here.rotation, scale: there.scale * inverse };\n}\n", "import { declareMembers, property } from \"@/attributes/properties/decorator\";\nimport { audioEffectsProperty, audioParamProperty } from \"@/attributes/properties/typed\";\nimport { type AudioEffectsInput } from \"@/attributes/audio/effects/chain\";\nimport type { AudioEffect } from \"@/attributes/audio/effects/union\";\nimport type { Param } from \"@/attributes/audio/ramp\";\nimport type { AudioTransition } from \"@/attributes/audio/transition\";\nimport type { AudioBusStop } from \"@/attributes/audio/request\";\nimport type { NodeSpan } from \"@/document/types\";\nimport { Node, type NodeConfig, type NodeDimension, type NodeProps } from \"@/components/trees/node/node\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport type { TweenStepper } from \"@/tween/stepper\";\n\nexport interface NodeAudioProps extends NodeProps {\n /** Linear gain. 1 leaves the signal alone, 0 silences it. */\n volume: Param;\n /** Stereo position: -1 hard left, 0 centre, +1 hard right. */\n pan: Param;\n /** Silence this node and, on a bus, everything under it. */\n mute: boolean;\n /** Effects applied in array order, index 0 closest to the source. */\n effects: AudioEffectsInput;\n /** A fade over its first `duration` seconds, on top of `volume`. */\n transitionIn: AudioTransition | undefined;\n /** A fade over its last `duration` seconds, on top of `volume`. */\n transitionOut: AudioTransition | undefined;\n}\n\n/**\n * The third scene graph: things that make sound.\n *\n * Sibling to `Node2D` and `Node3D`, and thin for the same reason they are thick\n * — a node that makes sound has no box and no place in space, so it inherits the\n * tree, identity, props, commands, context and clock from {@link Node} and adds\n * only what every audible thing has: a level, a position in the stereo field, a\n * mute, an effect chain, and how it enters and leaves.\n *\n * Two concrete kinds, and no more: `SoundNode` is a leaf that plays a file, and\n * `AudioBus` is a group that everything beneath it feeds. That is the whole\n * vocabulary of a mixer, and it is deliberately the same shape as the visual\n * trees — a group node and a drawing node — because the thing being described is\n * the same: what exists, and what is under what.\n *\n * ### Levels are ramps, not tweens\n *\n * `volume` and `pan` are {@link Param}, so a fade is a ramp (`ramp(1, 0, 1)`)\n * or a `transitionOut` rather than a `to()`. That is not a\n * limitation being worked around, it is what the two mechanisms mean: a tween\n * writes a prop once per *frame*, while sound is scheduled once, ahead of\n * time, and then runs at 48 kHz. A per-frame write reaches the graph on the one\n * frame that built the request and never again — so a `to({ volume })` would\n * read as animated on the timeline and render flat. `_prepareStep` refuses it\n * instead.\n */\nexport class NodeAudio<P extends NodeAudioProps = NodeAudioProps> extends Node<P> {\n get dimension(): NodeDimension { return \"audio\"; }\n\n declare volume: Param;\n declare pan: Param;\n declare mute: boolean;\n declare effects: AudioEffectsInput;\n declare transitionIn: AudioTransition | undefined;\n declare transitionOut: AudioTransition | undefined;\n\n constructor(props?: NodeConfig<any, P>) {\n super(props);\n // Deferred to here rather than run by `super()`: a subclass's field\n // initializers only run once `super()` has returned, so applying props\n // any earlier would write into cells that do not exist yet.\n this.initProps(props);\n this.adoptChildrenProp(props);\n }\n\n /** This node's children in the audio tree. */\n get childrenAudio(): NodeAudio[] {\n return this._allChildren.filter((c): c is NodeAudio => c instanceof NodeAudio);\n }\n\n /**\n * This bus's identity in the platform's graph: one chain, which everything\n * under it feeds.\n *\n * The authored id, and the structural path for a bus built in code rather\n * than from a document row. Neither answer alone works, and being wrong is\n * silent either way — the string reaches `AssetManager.stableKey`, so one\n * that changes re-fetches and re-schedules every clip on the bus. A document\n * row's id is fixed for the document's life, while its child index moves as\n * `syncPresence` adds and removes siblings; a code-built bus has no authored\n * id, but its parent builds it in the same slot every time.\n *\n * @internal\n */\n get _busId(): string {\n const authored = this._props?.id;\n return `bus:${typeof authored === \"string\" ? authored : structuralPathOf(this)}`;\n }\n\n /**\n * Refuse a tween on a level, naming the curve that does work.\n *\n * Loud rather than silent because the failure is otherwise invisible: the\n * command runs its full duration, the timeline draws a bar, and the render\n * is at one flat level. See the class docblock for why the two mechanisms\n * cannot agree.\n */\n override _prepareStep(to: Partial<P>, duration: number, easing?: EasingFunction): TweenStepper {\n for (const key of TWEEN_REFUSED) {\n if (!(key in to)) continue;\n throw new TypeError(\n `${this.className}: \"${key}\" cannot be tweened — an audio param is scheduled once, ` +\n `not written per frame, so a tween on it would render flat. Automate it with a ` +\n `ramp instead: ${key}: ramp(1, 0, 1), or transitionOut: { duration: 1 }.`,\n );\n }\n return super._prepareStep(to, duration, easing);\n }\n}\n\ndeclareMembers(NodeAudio, {\n volume: audioParamProperty({ default: 1 }),\n pan: audioParamProperty({ default: 0 }),\n mute: property({ default: false }),\n effects: audioEffectsProperty(),\n transitionIn: property({ default: undefined }),\n transitionOut: property({ default: undefined }),\n});\n\nconst TWEEN_REFUSED = [\"volume\", \"pan\", \"speed\"] as const;\n\n/**\n * The buses a node feeds, **source-adjacent first**.\n *\n * Walks up the audio ancestors only: the walk stops at the first non-audio\n * parent, which is the `Canvas2D` scene root, because a scene root is not a bus\n * — it has no level of its own and nothing to mix.\n */\nexport function busPathOf(node: NodeAudio, spanOf: SpanOf): AudioBusStop[] | undefined {\n const stops: AudioBusStop[] = [];\n let parent = node.parent;\n while (parent instanceof NodeAudio) {\n stops.push(stopOf(parent, spanOf));\n parent = parent.parent;\n }\n return stops.length > 0 ? stops : undefined;\n}\n\n/** {@link busPathOf}, with `bus` itself as the first stop. */\nexport function busPathTo(bus: NodeAudio, spanOf: SpanOf): AudioBusStop[] {\n return [stopOf(bus, spanOf), ...(busPathOf(bus, spanOf) ?? [])];\n}\n\n/** When a node is in the tree, in clip seconds: the span a bus stop carries. */\nexport type SpanOf = (node: Node) => Readonly<NodeSpan>;\n\n/**\n * The bus in `from`'s scene with node id `id`, or `null`.\n *\n * What lets something outside the audio tree feed a bus — a `Video`, whose audio\n * is welded to its picture and so cannot be parented under one. It names the bus\n * by the same id a `SoundNode` under that bus writes in its `parentId`, because\n * it is asking the same question: which bus. A `key` would be a second\n * vocabulary for it, and an optional one.\n */\nexport function findBusById(from: Node, id: string): NodeAudio | null {\n let root: Node = from;\n while (root.parent) root = root.parent;\n return searchBus(root, id);\n}\n\nfunction searchBus(node: Node, id: string): NodeAudio | null {\n if (node instanceof NodeAudio && node.id === id) return node;\n for (const child of node._allChildren) {\n const found = searchBus(child, id);\n if (found) return found;\n }\n return null;\n}\n\n/** One bus, flattened to the plain data a platform builds its chain from. */\nfunction stopOf(bus: NodeAudio, spanOf: SpanOf): AudioBusStop {\n const effects = bus.effects as unknown as AudioEffect[];\n const span = spanOf(bus);\n return {\n id: bus._busId,\n volume: bus.volume,\n pan: bus.pan,\n mute: bus.mute,\n ...(effects.length > 0 ? { effects } : {}),\n ...(bus.transitionIn ? { transitionIn: bus.transitionIn } : {}),\n ...(bus.transitionOut ? { transitionOut: bus.transitionOut } : {}),\n startAt: span.start,\n endAt: span.end,\n };\n}\n\n/**\n * A node's child-index path from the root of its tree, joined with \".\".\n *\n * The same identity `nodePath` gives the runtime, computed bottom-up because a\n * node declaring its audio knows its parents and not its index in a\n * walk. Stable across a rebuild for an unchanged tree, which is the property\n * both a bus id and a clip's request id need.\n */\nexport function structuralPathOf(node: Node): string {\n const parts: string[] = [];\n let current: Node | null = node;\n while (current) {\n const parent: Node | null = current.parent;\n if (!parent) break;\n parts.push(String(parent._allChildren.indexOf(current)));\n current = parent;\n }\n return parts.reverse().join(\".\");\n}\n", "import { declareMembers, property } from \"@/attributes/properties/decorator\";\nimport { optionalVector3Property, quaternionProperty } from \"@/attributes/properties/typed\";\nimport {\n resolveVector3,\n type Euler3, type EulerOrder, type Quaternion, type Vector3, type Vector3Input,\n} from \"@/render3d/vector3\";\nimport type { RenderContext3D } from \"@/render3d/render-context3d\";\nimport { Scene3D } from \"@/render3d/scene3d\";\nimport { declare3DResources } from \"@/render3d/tracking\";\nimport type { AssetScope } from \"@/assets/scope\";\nimport type { Shadow3D, Transform3D } from \"@/render3d/transform\";\nimport { Node, type NodeConfig, type NodeDimension, type NodeProps } from \"@/components/trees/node/node\";\nimport type { Command, CommandArgs } from \"@/tween/command\";\nimport { command } from \"@/tween/command-decorator\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport type { TweenStepper } from \"@/tween/stepper\";\n\nexport interface Node3DProps extends NodeProps {\n /** Position in the parent's local space. A scalar sets all three axes. */\n position: Vector3Input;\n /** Position on one axis. The same names 2D uses, one dimension over. */\n x: number;\n y: number;\n z: number;\n /**\n * Euler rotation in **degrees**, matching 2D `rotation`. Ignored when\n * {@link quaternion} is set.\n */\n rotation: Vector3Input | Euler3;\n /** Rotation about one axis, in **degrees**. Same names as 2D's. */\n rotationX: number;\n rotationY: number;\n rotationZ: number;\n /** The order the Euler axes are applied in. Default `\"XYZ\"`. */\n rotationOrder: EulerOrder;\n /**\n * Rotation as a unit quaternion. Wins over {@link rotation} — use it for\n * tumbles where Euler interpolation would gimbal.\n */\n quaternion: Quaternion;\n /** Per-axis scale; a scalar scales uniformly. Default 1. */\n scale: Vector3Input;\n scaleX: number;\n scaleY: number;\n scaleZ: number;\n /**\n * World-space point to orient toward, applied after {@link position}. Wins\n * over both {@link rotation} and {@link quaternion}.\n */\n lookAt: Vector3Input | undefined;\n /** Hide without removing — the cached renderer object stays alive. */\n visible: boolean;\n /**\n * Shadow participation. Default `true`, so turning shadows on for the scene\n * turns them on. Pass `false` to opt out, or `\"cast\"`/`\"receive\"` for one half.\n */\n shadow: Shadow3D;\n /** Draw-order override, for tuning transparent sorting. */\n renderOrder: number;\n}\n\n/**\n * A 3D parent's own coordinates for where its children sit: the units of a\n * graph, say. Position only, as a `ChildPlane` is in 2D: a child keeps its\n * size, turn and scale. Answered by the parent ({@link Node3D._spaceOf}, or\n * `Canvas3D._spaceOf` for a child of the viewport itself).\n */\nexport interface ChildSpace3D {\n /** A child's `x`/`y`/`z` as a point in the parent's local space. */\n toLocal(x: number, y: number, z: number): Vector3;\n}\n\n/** A parent that may place its 3D children in coordinates of its own: a `Node3D`, or a 3D viewport. */\ninterface SpaceHolder3D {\n _spaceOf(child: Node3D | null): ChildSpace3D | null;\n}\n\n/**\n * The coordinates `node`'s parent places it by, or `null` when they are the\n * parent's local space. The parent may be a 3D node or the viewport holding it.\n */\n/** @internal */\nexport function parentSpaceOf(node: Node3D): ChildSpace3D | null {\n const parent = node.parent as Partial<SpaceHolder3D> | null;\n return typeof parent?._spaceOf === \"function\" ? parent._spaceOf(node) : null;\n}\n\n/** The three axis props each vector prop distributes into, in order. */\nconst VECTOR_SUGAR: Readonly<Record<string, readonly [string, string, string]>> = {\n position: [\"x\", \"y\", \"z\"],\n rotation: [\"rotationX\", \"rotationY\", \"rotationZ\"],\n scale: [\"scaleX\", \"scaleY\", \"scaleZ\"],\n};\n\n/**\n * A thing in 3D space — the root of the 3D scene graph.\n *\n * The sibling of {@link Node2D}: same tree, same props, same `to()`/`set()`/\n * `save()`/`restore()`, same refs, context and per-node clock, all inherited from\n * {@link Node}. What differs is the only thing that genuinely differs between the\n * two — how a node is placed and how it draws. There is no `width`, no `padding`,\n * no anchor and no flex here, because none of them mean anything for a mesh; a 3D\n * node's whole placement is its transform.\n *\n * Canvas3D({\n * children: [\n * Camera3D({ orbit: 30, elevation: 18, distance: 6 }),\n * AmbientLight3D({ intensity: 0.4 }),\n * Group3D({ ref: rig, children: [Box3D({ width: 2, cornerRadius: 0.15, fill: \"tomato\" })] }),\n * ],\n * })\n *\n * rig().to({ data: { rotationY: 360, y: 1 }, duration: 2 });\n *\n * ── Axes are scalars, and vectors are sugar over them ─────────────────────────\n * `x`, `y`, `z`, `rotationX/Y/Z` and `scaleX/Y/Z` are the real props, and they\n * are named exactly what 2D names them. `position`, `rotation` and `scale` are\n * distributed into those three, the way `Node2D` already distributes `size` into\n * `width`/`height` — so both spellings tween identically and there is one source\n * of truth for where a node is. That is what makes `to({ y: 3 })` work: with a\n * single vector prop it would have had nothing to interpolate on the other two\n * axes, which is exactly the trap that made every 3D scene restate coordinates it\n * did not mean to change.\n *\n * A `Node3D` only ever lives under a `Canvas3D` — the one node that holds both\n * dimensions. Parenting one to a `Rect` throws rather than silently drawing\n * nothing (see {@link Node.acceptsChild}). Every 3D node type is a\n * `component3d`, which lowers onto this class and draws from its `render`.\n */\nexport class Node3D<P extends Node3DProps = Node3DProps> extends Node<P> {\n get dimension(): NodeDimension { return \"3d\"; }\n\n declare x: number;\n declare y: number;\n declare z: number;\n\n declare rotationX: number;\n declare rotationY: number;\n declare rotationZ: number;\n declare rotationOrder: EulerOrder;\n\n declare quaternion: Quaternion;\n\n declare scaleX: number;\n declare scaleY: number;\n declare scaleZ: number;\n\n declare lookAt: Vector3Input | undefined;\n declare visible: boolean;\n declare shadow: Shadow3D;\n declare renderOrder: number;\n\n constructor(props?: NodeConfig<any, P>) {\n super(props);\n // Distributed before `initProps`, which only ever applies keys that are\n // registered props — a `position` left in the bag would be dropped.\n this.initProps(distributeVectors(props) as NodeConfig<any, P>);\n this.adoptChildrenProp(props);\n }\n\n /** Animate the position, whichever axes are given; the rest stay where they are. */\n moveTo(args: CommandArgs<{ x?: number; y?: number; z?: number }> & { duration: number }): Command<P> {\n return this.to({ data: stated(args.data) as Partial<P>, duration: args.duration, easing: args.easing });\n }\n\n /** Animate the Euler rotation, in degrees, whichever axes are given. */\n rotateTo(\n args: CommandArgs<{ rotationX?: number; rotationY?: number; rotationZ?: number }> & { duration: number },\n ): Command<P> {\n return this.to({ data: stated(args.data) as Partial<P>, duration: args.duration, easing: args.easing });\n }\n\n /** Animate the scale: `scale` on every axis, and any axis given beside it on that one. */\n scaleTo(\n args: CommandArgs<{ scale?: number; scaleX?: number; scaleY?: number; scaleZ?: number }> & { duration: number },\n ): Command<P> {\n return this.to({ data: stated(args.data) as Partial<P>, duration: args.duration, easing: args.easing });\n }\n\n /** This node's position, composed from the axis props. */\n get position(): Vector3 {\n return { x: this.x, y: this.y, z: this.z };\n }\n set position(value: Vector3Input) {\n this.set({ position: value } as never);\n }\n\n /** This node's Euler rotation in degrees, composed from the axis props. */\n get rotation(): Euler3 {\n return { x: this.rotationX, y: this.rotationY, z: this.rotationZ, order: this.rotationOrder };\n }\n set rotation(value: Vector3Input | Euler3) {\n this.set({ rotation: value } as never);\n }\n\n /** This node's scale, composed from the axis props. */\n get scale(): Vector3 {\n return { x: this.scaleX, y: this.scaleY, z: this.scaleZ };\n }\n set scale(value: Vector3Input) {\n this.set({ scale: value } as never);\n }\n\n /**\n * Distribute the vector sugar into axis props, then write as usual.\n *\n * Same shape as `Node2D.set`'s handling of `size`, and for the same reason:\n * `position` has no slot of its own, so it has to become three writes\n * before the generic loop runs. An explicitly stated axis in the same call\n * wins over the vector, which is what lets `{ position: p, y: 0 }` mean what\n * it reads like.\n */\n override set(props: { [K in keyof P]?: P[K] | (() => P[K]) }): void {\n super.set(distributeVectors(props) as typeof props);\n }\n\n /**\n * The tween half of the same rule. Expanded here rather than in the command\n * so `to({ position: [...] })` and `to({ x, y, z })` produce identical\n * steppers — one interpolating path, whichever way it was written.\n */\n override _prepareStep(to: Partial<P>, duration: number, easing?: EasingFunction): TweenStepper {\n return super._prepareStep(distributeVectors(to) as Partial<P>, duration, easing);\n }\n\n /**\n * This node's placement, as the renderer's own vocabulary.\n *\n * Sampled fresh every frame from the prop slots, so a tween moves the object\n * without anything here caching state between frames.\n *\n * `quaternion` is only emitted when it has been set away from identity: it\n * wins over `rotation` in a {@link Transform3D}, so always sending it would\n * make `rotation` silently do nothing.\n */\n protected transform3D(): Transform3D {\n const quaternion = this.quaternion as unknown as Quaternion;\n const identityQuaternion =\n quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;\n const space = parentSpaceOf(this);\n return {\n position: space ? space.toLocal(this.x, this.y, this.z) : this.position,\n rotation: this.rotation,\n quaternion: identityQuaternion ? undefined : quaternion,\n scale: this.scale,\n lookAt: this.lookAt,\n visible: this.visible,\n shadow: this.shadow,\n renderOrder: this.renderOrder,\n };\n }\n\n /**\n * The coordinates `child`'s `x`/`y`/`z` are in, or `null` (the default) when\n * they are this node's local space. A `null` child is one not here yet.\n */\n /** @internal */\n _spaceOf(_child: Node3D | null): ChildSpace3D | null {\n return null;\n }\n\n /**\n * The transform that goes on this node's *group* — the scope its children\n * nest inside. Defaults to this node's own placement, which is right for\n * everything that lives at its own origin.\n *\n * A camera answers identity and places itself instead: three aims a\n * camera's -Z at `lookAt` but a plain group's +Z, so hanging a camera's\n * placement on its group would point the shot backwards.\n */\n protected groupTransform(): Transform3D {\n return this.transform3D();\n }\n\n /**\n * Draw this node's own contribution to the scene — a `ctx.draw(graphics3D)`\n * for something with geometry, a `ctx.light(...)` for a light, nothing at all\n * for a plain {@link Group3D}. Children are recorded after it, nested inside\n * this node's transform.\n */\n protected renderSelf(ctx: RenderContext3D): void { }\n\n /**\n * Record this node and its subtree into `ctx`.\n *\n * An invisible node still opens its scope: `visible: false` is a renderer-side\n * flag on a live object rather than a removal, which is what lets a node be\n * hidden and shown again without its GPU resources being rebuilt. Skipping the\n * walk here would instead sweep the whole subtree out of the cache.\n */\n render(ctx: RenderContext3D): void {\n // The editor's flag folds into `visible` rather than adding a second one:\n // the 3D side already has exactly this concept, honoured by the picking\n // walk, and two flags meaning \"do not show this\" would be two places to\n // ask. Still opens its scope — see the note above on why an invisible\n // node keeps its cached renderer object.\n if (this.hidden) {\n ctx.begin({ id: this.id, transform: { ...this.groupTransform(), visible: false } });\n ctx.end();\n return;\n }\n ctx.begin({ id: this.id, transform: this.groupTransform() });\n this.renderSelf(ctx);\n for (const child of this._children) {\n if (child instanceof Node3D) child.render(ctx);\n }\n ctx.end();\n }\n\n /**\n * What {@link renderSelf} records, never {@link render}: the placement lives on\n * the group scope, so moving a node does not change what it declares.\n */\n declareAssets(assets: AssetScope): void {\n if (this.renderSelf === Node3D.prototype.renderSelf) return;\n const scene = new Scene3D();\n this.renderSelf(scene);\n declare3DResources(scene, assets);\n }\n}\n\ndeclareMembers(Node3D, {\n x: property({ default: 0 }),\n y: property({ default: 0 }),\n z: property({ default: 0 }),\n rotationX: property({ default: 0 }),\n rotationY: property({ default: 0 }),\n rotationZ: property({ default: 0 }),\n rotationOrder: property({ default: \"XYZ\" }),\n quaternion: quaternionProperty(),\n scaleX: property({ default: 1 }),\n scaleY: property({ default: 1 }),\n scaleZ: property({ default: 1 }),\n lookAt: optionalVector3Property(\"snap\"),\n visible: property({ default: true }),\n shadow: property({ default: true }),\n renderOrder: property({ default: 0 }),\n\n moveTo: command({ args: [\"x\", \"y\", \"z\"] }),\n rotateTo: command({ args: [\"rotationX\", \"rotationY\", \"rotationZ\"] }),\n scaleTo: command({\n args: [{ key: \"scale\", kind: \"number\", min: 0, step: 0.05, unit: \"×\" }, \"scaleX\", \"scaleY\", \"scaleZ\"],\n }),\n});\n\n/**\n * Expand `position`/`rotation`/`scale` in a prop bag into their axis props.\n *\n * Returns the bag untouched when it names none of them, so the common write path\n * allocates nothing. A **binding** expands into three bindings that each resolve\n * the vector and take one component — so `position={() => lift()}` stays a\n * binding, and one thunk driving all three axes is still read once per axis per\n * frame rather than being frozen at bind time.\n */\nfunction distributeVectors<T extends object>(props: T | undefined): T | undefined {\n if (!props) return props;\n\n let out: Record<string, unknown> | undefined;\n\n for (const key in VECTOR_SUGAR) {\n const value = (props as Record<string, unknown>)[key];\n if (value === undefined) continue;\n\n out ??= { ...(props as Record<string, unknown>) };\n delete out[key];\n\n const axes = VECTOR_SUGAR[key];\n\n if (typeof value === \"function\") {\n const read = value as () => Vector3Input;\n for (let i = 0; i < 3; i++) {\n const axis = axes[i];\n if (out[axis] !== undefined) continue;\n out[axis] = () => componentOf(resolveVector3(read()), i);\n }\n continue;\n }\n\n const vector = resolveVector3(value as Vector3Input);\n for (let i = 0; i < 3; i++) {\n const axis = axes[i];\n if (out[axis] === undefined) out[axis] = componentOf(vector, i);\n }\n\n // `order` rides on an Euler and has nowhere else to go.\n if (key === \"rotation\") {\n const order = (value as Euler3).order;\n if (order !== undefined && out.rotationOrder === undefined) out.rotationOrder = order;\n }\n }\n\n return (out as T) ?? props;\n}\n\n/** `data` without the keys left unstated, so a tween never aims an axis at `undefined`. */\nfunction stated<T extends object>(data: T | undefined): Partial<T> {\n const out: Partial<T> = {};\n for (const key in data) if (data[key] !== undefined) out[key] = data[key];\n return out;\n}\n\nfunction componentOf(vector: Vector3, index: number): number {\n return index === 0 ? vector.x : index === 1 ? vector.y : vector.z;\n}\n", "import type { NodeTypeDescriptor } from \"./node-descriptor\";\n\n/** Symbol under which `node` metadata is stored on a class prototype. */\nexport const NODE_META = Symbol(\"nodeMeta\");\n\n/**\n * Declare a node class's document key — and nothing else.\n *\n * **It does not register.** Registration happens when the class is handed to a\n * `Registry` (`new Engine(platform, { nodes: [Blob] })`), because a registry is\n * a value an engine owns rather than a table the module graph writes into. A\n * declaration that registered made the *order modules happened to be imported in*\n * part of the engine's state: whichever host loaded first won the key, a second\n * engine in the same process inherited a vocabulary it never asked for, and a\n * class that was merely imported was already registered whether or not anything\n * meant to offer it.\n *\n * What is left is a declaration, read back by {@link getNodeDescriptor}. A\n * component factory makes it for the class it generates (`component2d({ key })`);\n * a hand-written class makes it itself:\n *\n * ```ts\n * class Blob extends Node2D<BlobProps> {\n * declare readonly wobble: number;\n * wobbleTo(args: CommandArgs<{ wobble: number }>) { … }\n * }\n * declareMembers(Blob, {\n * wobble: property({ default: 0.4 }),\n * wobbleTo: command({ args: [\"wobble\"] }),\n * });\n * node(\"blob\")(Blob);\n *\n * const registry = new Registry({ nodes: [Blob] });\n * // { \"type\": \"blob\", \"props\": { \"wobble\": 0.4 } }\n * ```\n *\n * The full form declares everything a host needs to *offer* the type — the\n * shelves it sits on, how it lays children out, what a freshly placed one is\n * seeded with — which is what a component package used to restate in a\n * `manifest.json` beside a class nothing checked it against:\n *\n * ```ts\n * node({\n * key: \"lineChart\",\n * forkable: true,\n * layout: { children: \"freeform\", acceptsChildren: true },\n * seed: { width: 760, height: 460 },\n * })(LineChart);\n * ```\n *\n * None of it is read while rendering — see {@link NodeTypeDescriptor}.\n *\n * **The key is written out, not taken from the class name.** A minifier is free\n * to rename `Blob` to `o`, and the key is what stored documents contain — so a\n * derived one would work in development and silently rewrite every document's\n * vocabulary in a production bundle. It is public API, and spelled like it.\n */\nexport function node(type: string | NodeTypeDescriptor) {\n // Deliberately looser than `NodeConstructor`, which takes a bare\n // `Record<string, unknown>`: a real node class declares its own props type,\n // and requiring assignability would reject exactly the classes this exists\n // for.\n return function <T extends new (...args: never[]) => object>(ctor: T): T {\n const descriptor: NodeTypeDescriptor = typeof type === \"string\" ? { key: type } : type;\n (ctor.prototype as Record<symbol, unknown>)[NODE_META] = descriptor;\n return ctor;\n };\n}\n\n/**\n * What `node` declared on this exact class, or `undefined`.\n *\n * Own prototype only, deliberately: a subclass inherits its parent's methods but\n * not its identity, and a `Card extends Rect` that answered to `\"rect\"` would\n * collide with the real one the moment both were registered.\n */\nexport function getNodeDescriptor(ctor: new (...args: never[]) => object): NodeTypeDescriptor | undefined {\n const proto = ctor.prototype as Record<symbol, unknown> | undefined;\n if (!proto || !Object.prototype.hasOwnProperty.call(proto, NODE_META)) return undefined;\n return proto[NODE_META] as NodeTypeDescriptor;\n}\n", "import { TransformState } from \"./transform\";\nimport { AlignmentKey, Alignment, alignmentOps } from \"@/attributes/layout/alignment\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { NodeBlendMode } from \"@/attributes/shape/fill/blend\";\n\n/**\n * Per-shape descriptor state. Shapes carry geometry and a *local* transform\n * (`rotation`/`scale` baked into the path before it joins the union) but **not**\n * layer effects: effects are applied to the whole drawn union via\n * {@link Graphics2D.effects}, not per shape. So `ShapeState` omits\n * `TransformState.effects` (which remains for node-level transforms).\n */\nexport interface ShapeState extends Omit<TransformState, \"effects\" | \"pivot\"> {\n /**\n * @deprecated Not drawn. A shape has no layer of its own, so a per-shape alpha\n * does nothing; use `Graphics2D.opacity()` for the whole group, or the node's\n * own opacity. The renderer warns once when one is given.\n */\n opacity: number;\n /**\n * @deprecated Not drawn, for the same reason as {@link ShapeState.opacity}; use\n * the node's own `blend`. The renderer warns once when one is given.\n */\n blend?: NodeBlendMode;\n start: number;\n end: number;\n /**\n * Pivot for the shape's local rotation/scale. Widened from a `Vector2` to an\n * {@link Alignment} so a shape can pivot about a **named alignment**\n * (`.rect({ pivot: 'topRight' })`) as well as an explicit `Vector2`.\n * `with*Descriptor` normalises it to a `Vector2` (via {@link resolveShapePivot}),\n * so the resolved state the renderer reads always carries a concrete pivot.\n */\n pivot: Alignment;\n}\n\n/**\n * Normalise a per-shape `pivot` input to a `Vector2`. Resolves a named alignment\n * (`'topRight'`, …) to its normalised `[-1, 1]` pivot and passes an explicit\n * `Vector2` through. Idempotent — safe to call on already-resolved state — so\n * both `with*Descriptor` and the renderer can call it. Defaults to centre when\n * the pivot is absent.\n */\nexport function resolveShapePivot(pivot: Alignment | undefined): Vector2 {\n return alignmentOps.resolve(pivot ?? { x: 0, y: 0 });\n}\n\n// ─── Cardinal-alignment positioning ──────────────────────────────────────────\n// A shape can be positioned by a named alignment instead of its centre `x`/`y`,\n// exactly like a node: `.rect({ topRight: { x, y }, width, height })` places the\n// rect so its top-right corner lands at that point. The nine names share the node\n// `align` vocabulary (`center`, `topLeft`, …). Targets are in the same y-UP author\n// space as `x`/`y` (the renderer flips to canvas), so `topRight` is the visually\n// top-right corner. Like a node, using an alignment also sets the shape's `pivot`\n// to that alignment, so a subsequent per-shape `rotation`/`scale` turns about the\n// pinned corner.\n\n/** The cardinal-alignment positioning props a shape descriptor accepts (input-only;\n * they don't appear on the resolved `*State`). Pass at most one, and not together\n * with `x`, `y`, or `pivot`. Each value is the y-up point the named alignment lands on. */\nexport interface ShapeAlignmentInput {\n center?: Vector2;\n topLeft?: Vector2;\n topRight?: Vector2;\n bottomLeft?: Vector2;\n bottomRight?: Vector2;\n topCenter?: Vector2;\n bottomCenter?: Vector2;\n centerLeft?: Vector2;\n centerRight?: Vector2;\n}\n\n/** The nine alignment keys, in the node `align` vocabulary. */\nexport const SHAPE_ALIGNMENT_KEYS: AlignmentKey[] = [\n \"center\", \"topLeft\", \"topRight\", \"bottomLeft\", \"bottomRight\",\n \"topCenter\", \"bottomCenter\", \"centerLeft\", \"centerRight\",\n];\n\n/**\n * Validate a shape descriptor's alignment usage — mirrors `alignmentOps.validateProps`,\n * extended to also reject `x`/`y` (a shape positioned by an alignment cannot also set\n * its centre). Throws if more than one alignment is set, or an alignment is combined with\n * `pivot`, `x`, or `y`. `x`/`y`/`pivot` may freely combine with each other.\n */\nexport function validateShapeAlignmentProps(descriptor: Record<string, unknown>): void {\n const present = SHAPE_ALIGNMENT_KEYS.filter(k => descriptor[k] !== undefined);\n if (present.length > 1) {\n throw new Error(`Cannot set multiple shape alignment props at once: ${present.join(\", \")}`);\n }\n if (present.length === 1) {\n const conflict = ([\"pivot\", \"x\", \"y\"] as const).find(k => descriptor[k] !== undefined);\n if (conflict) {\n throw new Error(`Cannot set both shape alignment prop '${present[0]}' and '${conflict}' at the same time`);\n }\n }\n}\n\n/**\n * Drop the input-only alignment keys from a descriptor, so a `{ ...descriptor }`\n * spread doesn't leak them onto the resolved `*State` (the resolved x/y/pivot\n * already carry the alignment's effect). Returns a shallow copy without those keys.\n */\nexport function stripShapeAlignmentKeys<T extends object>(descriptor: T): Omit<T, keyof ShapeAlignmentInput> {\n const out = { ...descriptor } as Record<string, unknown>;\n for (const k of SHAPE_ALIGNMENT_KEYS) delete out[k];\n return out as Omit<T, keyof ShapeAlignmentInput>;\n}\n\n/**\n * Resolve a shape descriptor's positioning into a concrete centre `x`/`y` and\n * `pivot` (all in y-up author space), handling the cardinal-alignment shorthand.\n *\n * When an alignment is present its normalised pivot `a` (in `[-1, 1]`, y-up) is mapped\n * onto the shape's own `width`×`height` box: the centre that lands the named alignment\n * on `target` is `centre = target − a · (size / 2)`, and `pivot` is set to `a`\n * (matching `Node2D`'s auto-pivot). Otherwise `x`/`y`/`pivot` pass through unchanged —\n * `pivot` alone never repositions the shape here, since this same function re-runs\n * on already-resolved state (`with*Descriptor` is called again from\n * `BaseShape.resolveState`) and re-deriving an offset from an already-resolved\n * `pivot` would double-apply it. The `pivot` + plain `x`/`y` shorthand ({@link\n * resolvePivotPosition}) bakes its offset in exactly once, before this function\n * ever sees the descriptor, precisely to preserve that idempotency.\n *\n * Idempotent in the no-alignment case; safe to call more than once per descriptor\n * resolve. Validates via {@link validateShapeAlignmentProps} first.\n */\nexport function resolveShapeAlignment(\n descriptor: Partial<ShapeState> & ShapeAlignmentInput,\n width: number,\n height: number,\n): { x: number; y: number; pivot: Alignment } {\n validateShapeAlignmentProps(descriptor as Record<string, unknown>);\n\n const alignmentKey = SHAPE_ALIGNMENT_KEYS.find(k => (descriptor as Record<string, unknown>)[k] !== undefined);\n if (alignmentKey) {\n const target = (descriptor as Record<string, Vector2>)[alignmentKey];\n const a = alignmentOps.resolve(alignmentKey); // normalised [-1,1], y-up\n return {\n x: target.x - a.x * (width / 2),\n y: target.y - a.y * (height / 2),\n pivot: a,\n };\n }\n\n return {\n x: descriptor.x ?? 0,\n y: descriptor.y ?? 0,\n pivot: descriptor.pivot ?? { x: 0, y: 0 },\n };\n}\n\n/**\n * Fold a plain `pivot` + `x`/`y` into an equivalent resolved centre, so\n * `{ x, y, pivot: 'topRight' }` lands the top-right corner at `(x, y)` — the same\n * place `{ topRight: { x, y } }` would — instead of `x`/`y` always positioning the\n * centre regardless of `pivot`. Uses the same `centre = target − a · (size / 2)`\n * formula as the alignment shorthand.\n *\n * Must run exactly once, on the raw author-facing descriptor, **before**\n * {@link resolveShapeAlignment} ever sees it (i.e. in `flipPositionY`, not inside\n * `with*Descriptor`, which `BaseShape.resolveState` calls a second time on\n * already-resolved state — re-running this there would double the offset, since\n * the output below is indistinguishable from a plain `x`/`y`/`pivot` descriptor).\n * A no-op when an alignment shorthand is already present (validated downstream) or\n * `pivot` is centre/absent.\n */\nexport function resolvePivotPosition<T extends Partial<ShapeState> & ShapeAlignmentInput>(\n descriptor: T,\n width: number,\n height: number,\n): T {\n const alignmentKey = SHAPE_ALIGNMENT_KEYS.find(k => (descriptor as Record<string, unknown>)[k] !== undefined);\n if (alignmentKey || descriptor.pivot === undefined) return descriptor;\n\n const a = alignmentOps.resolve(descriptor.pivot); // normalised [-1,1], y-up\n if (a.x === 0 && a.y === 0) return descriptor;\n\n const target = { x: descriptor.x ?? 0, y: descriptor.y ?? 0 };\n return {\n ...descriptor,\n x: target.x - a.x * (width / 2),\n y: target.y - a.y * (height / 2),\n pivot: a,\n };\n}\n", "import { RectCornerRadius } from \"@/attributes/shape/corners/corner-radius\";\nimport { RectCornerStyle } from \"@/attributes/shape/corners/corner-style\";\nimport { ShapeAlignmentInput, ShapeState, resolveShapeAlignment, resolveShapePivot, stripShapeAlignmentKeys } from \"./shape\";\n\n\nexport interface RectState extends ShapeState {\n width: number;\n height: number;\n // Accepts loose input or an already-resolved value (both are part of\n // RectCornerRadius/RectCornerStyle): the node resolves via its property\n // mapper, and the renderer re-resolves idempotently.\n cornerRadius: RectCornerRadius;\n cornerStyle: RectCornerStyle;\n}\n\nexport function withRectDescriptor(descriptor: Partial<RectState> & ShapeAlignmentInput): RectState {\n const width = descriptor.width ?? 0;\n const height = descriptor.height ?? 0;\n const { x, y, pivot } = resolveShapeAlignment(descriptor, width, height);\n return {\n ...stripShapeAlignmentKeys(descriptor),\n opacity: descriptor.opacity ?? 1,\n rotation: descriptor.rotation ?? 0,\n scale: descriptor.scale ?? 1,\n x,\n y,\n start: descriptor.start ?? 0,\n end: descriptor.end ?? 1,\n pivot: resolveShapePivot(pivot),\n\n width,\n height,\n cornerRadius: descriptor.cornerRadius ?? 0,\n cornerStyle: descriptor.cornerStyle ?? \"rounded\",\n };\n}\n", "import { ShapeAlignmentInput, ShapeState, resolveShapeAlignment, resolveShapePivot, stripShapeAlignmentKeys } from \"./shape\";\nexport interface EllipseState extends ShapeState {\n width: number;\n height: number;\n ratio: number;\n sweep: number;\n startAngle: number;\n}\n\nexport function withEllipseDescriptor(descriptor: Partial<EllipseState> & ShapeAlignmentInput): EllipseState {\n const width = descriptor.width ?? 0;\n const height = descriptor.height ?? 0;\n const { x, y, pivot } = resolveShapeAlignment(descriptor, width, height);\n return {\n ...stripShapeAlignmentKeys(descriptor),\n opacity: descriptor.opacity ?? 1,\n rotation: descriptor.rotation ?? 0,\n scale: descriptor.scale ?? 1,\n x,\n y,\n start: descriptor.start ?? 0,\n end: descriptor.end ?? 1,\n pivot: resolveShapePivot(pivot),\n\n width,\n height,\n ratio: descriptor.ratio ?? 0,\n sweep: descriptor.sweep ?? 360,\n startAngle: descriptor.startAngle ?? 0,\n };\n}", "import { CornerStyle } from \"@/attributes/shape/corners/corner-style\";\nimport { ShapeAlignmentInput, ShapeState, resolveShapeAlignment, resolveShapePivot, stripShapeAlignmentKeys } from \"./shape\";\n\nexport interface PolygonState extends ShapeState {\n width: number;\n height: number;\n sides: number;\n /** Vertex rounding radius in pixels (applied uniformly to every vertex). */\n cornerRadius: number;\n /** Vertex shape: `'rounded'` (circular arc) or `'angled'` (chamfer). */\n cornerStyle: CornerStyle;\n}\n\nexport function withPolygonDescriptor(descriptor: Partial<PolygonState> & ShapeAlignmentInput): PolygonState {\n const width = descriptor.width ?? 0;\n const height = descriptor.height ?? 0;\n const { x, y, pivot } = resolveShapeAlignment(descriptor, width, height);\n return {\n ...stripShapeAlignmentKeys(descriptor),\n opacity: descriptor.opacity ?? 1,\n rotation: descriptor.rotation ?? 0,\n scale: descriptor.scale ?? 1,\n x,\n y,\n start: descriptor.start ?? 0,\n end: descriptor.end ?? 1,\n pivot: resolveShapePivot(pivot),\n\n width,\n height,\n sides: descriptor.sides ?? 5,\n cornerRadius: descriptor.cornerRadius ?? 0,\n cornerStyle: descriptor.cornerStyle ?? \"rounded\",\n };\n}\n", "import { CornerStyle } from \"@/attributes/shape/corners/corner-style\";\nimport { ShapeAlignmentInput, ShapeState, resolveShapeAlignment, resolveShapePivot, stripShapeAlignmentKeys } from \"./shape\";\n\nexport interface PolygramState extends ShapeState {\n width: number;\n height: number;\n sides: number;\n ratio: number;\n /** Vertex rounding radius in pixels (applied uniformly to every vertex). */\n cornerRadius: number;\n /** Vertex shape: `'rounded'` (circular arc) or `'angled'` (chamfer). */\n cornerStyle: CornerStyle;\n}\n\nexport function withPolygramDescriptor(descriptor: Partial<PolygramState> & ShapeAlignmentInput): PolygramState {\n const width = descriptor.width ?? 0;\n const height = descriptor.height ?? 0;\n const { x, y, pivot } = resolveShapeAlignment(descriptor, width, height);\n return {\n ...stripShapeAlignmentKeys(descriptor),\n opacity: descriptor.opacity ?? 1,\n rotation: descriptor.rotation ?? 0,\n scale: descriptor.scale ?? 1,\n x,\n y,\n start: descriptor.start ?? 0,\n end: descriptor.end ?? 1,\n pivot: resolveShapePivot(pivot),\n\n width,\n height,\n sides: descriptor.sides ?? 5,\n ratio: descriptor.ratio ?? 0.5,\n cornerRadius: descriptor.cornerRadius ?? 0,\n cornerStyle: descriptor.cornerStyle ?? \"rounded\",\n };\n}\n", "import { Vector2 } from \"@/attributes/layout/vector2\";\nimport { ShapeState, resolveShapePivot } from \"./shape\";\n\nexport interface LineState extends ShapeState {\n points: Vector2[];\n radius: number;\n closed: boolean;\n}\n\nexport function withLineDescriptor(descriptor: Partial<LineState>): LineState {\n return {\n opacity: descriptor.opacity ?? 1,\n rotation: descriptor.rotation ?? 0,\n scale: descriptor.scale ?? 1,\n x: descriptor.x ?? 0,\n y: descriptor.y ?? 0,\n start: descriptor.start ?? 0,\n end: descriptor.end ?? 1,\n width: descriptor.width ?? 0,\n height: descriptor.height ?? 0,\n pivot: resolveShapePivot(descriptor.pivot),\n\n points: descriptor.points ?? [],\n radius: descriptor.radius ?? 0,\n closed: descriptor.closed ?? false,\n };\n}\n", "import { Vector2 } from \"@/attributes/layout/vector2\";\nimport { Clip, ClipOp, ClipShapeOp } from \"./clip\";\nimport { withRectDescriptor } from \"./descriptors/rect\";\nimport { withEllipseDescriptor } from \"./descriptors/ellipse\";\nimport { withPolygonDescriptor } from \"./descriptors/polygon\";\nimport { withPolygramDescriptor } from \"./descriptors/polygram\";\nimport { withLineDescriptor } from \"./descriptors/line\";\nimport { cornerRadiusOps } from \"@/attributes/shape/corners/corner-radius\";\n\n/**\n * Point-in-region tests for {@link Clip}, used by node hit testing so a click\n * follows a shape's silhouette rather than its bounding box.\n *\n * Geometry only — no renderer — because a `Clip` is a declarative\n * record of primitives rather than a built path. That is what lets hit testing\n * live in `core` and share one outline definition with clipping and backdrop\n * effects: a shape declares its outline once, in `clipSelf()`, and both the\n * pixels and the grab region derive from it.\n *\n * Every point and every descriptor coordinate here is in **y-up author space**\n * (the space `Graphics2D`/`Clip` descriptors are written in; the renderer flips to\n * canvas y-down at draw time — see `flipPositionY`). Angles follow from that:\n * `startAngle`/`sweep` measure counter-clockwise from +x.\n */\n\n/** Guard against divide-by-zero on collapsed geometry. */\nconst EPS = 1e-9;\n\n/**\n * Whether `point` falls inside the region a {@link Clip} describes, within\n * `tolerance` scene units of its edge.\n *\n * Shape ops union; a `cut` subtracts the immediately preceding shape from\n * everything declared before it, mirroring how the renderer replays the op list.\n * `tolerance` widens each shape outward — including a cutter, which therefore\n * takes a slightly larger bite, keeping the test forgiving in both directions\n * rather than making a hole's rim unpickable.\n */\nexport function containsClip(clip: Clip, point: Vector2, tolerance = 0): boolean {\n return containsOps(clip.ops(), point, tolerance);\n}\n\n/** {@link containsClip} over a raw op list. */\nexport function containsOps(ops: readonly ClipOp[], point: Vector2, tolerance = 0): boolean {\n let inside = false;\n // The shape immediately preceding the current position, held back so a\n // following `cut` can subtract it instead of unioning it.\n let pending: ClipShapeOp | null = null;\n\n const flush = (): void => {\n if (pending && containsShape(pending, point, tolerance)) inside = true;\n pending = null;\n };\n\n for (const op of ops) {\n if (op.kind === \"cut\") {\n // The pending shape is the cutter: it never joins the union, and it\n // punches whatever was accumulated before it.\n if (pending && containsShape(pending, point, tolerance)) inside = false;\n pending = null;\n continue;\n }\n flush();\n pending = op;\n }\n flush();\n return inside;\n}\n\n/**\n * Dispatch one shape op to its own containment test, after undoing the shape's\n * local rotation/scale about its pivot — mirroring `BaseShape.applyShapeTransform`,\n * which bakes that same transform into the drawn path.\n */\nfunction containsShape(op: ClipShapeOp, point: Vector2, tolerance: number): boolean {\n switch (op.kind) {\n case \"rect\": {\n const s = withRectDescriptor(op.state);\n const p = toShapeLocal(point, s, s.width, s.height);\n return p !== null && containsRect(p, s.width, s.height, cornerRadiusOps.resolve(s.cornerRadius), tolerance);\n }\n case \"ellipse\": {\n const s = withEllipseDescriptor(op.state);\n const p = toShapeLocal(point, s, s.width, s.height);\n return p !== null && containsEllipse(p, s.width, s.height, s.ratio, s.sweep, s.startAngle, tolerance);\n }\n case \"polygon\": {\n const s = withPolygonDescriptor(op.state);\n const p = toShapeLocal(point, s, s.width, s.height);\n return p !== null && containsPolyline(p, polygonVertices(s.width, s.height, s.sides), true, tolerance);\n }\n case \"polygram\": {\n const s = withPolygramDescriptor(op.state);\n const p = toShapeLocal(point, s, s.width, s.height);\n return p !== null && containsPolyline(p, polygramVertices(s.width, s.height, s.sides, s.ratio), true, tolerance);\n }\n case \"line\": {\n const s = withLineDescriptor(op.state);\n const p = toShapeLocal(point, s, s.width, s.height);\n if (p === null || s.points.length === 0) return false;\n // As a clip region a polyline is filled with its contour implicitly\n // closed, whether or not `closed` was set — so test the enclosed area\n // first, then fall back to the band around the stroke itself.\n if (s.points.length >= 3 && containsPolyline(p, s.points, true, tolerance)) return true;\n return nearPolyline(p, s.points, s.closed, tolerance);\n }\n case \"path\": {\n // An arbitrary Bézier winding test is not worth carrying, and no\n // built-in shape emits a `path` clip — only a hand-built `Clip` can.\n // Fall back to the declared box.\n const s = op.state;\n const local = { x: point.x - (s.x ?? 0), y: point.y - (s.y ?? 0) };\n return containsRect(local, s.width ?? 0, s.height ?? 0, cornerRadiusOps.resolve(0), tolerance);\n }\n }\n}\n\n/** The positioning fields every shape descriptor resolves to. */\ninterface ShapePlacement {\n x: number;\n y: number;\n rotation: number;\n scale: number;\n pivot: unknown;\n}\n\n/**\n * Map `point` out of the shape's own `x`/`y`/`rotation`/`scale` (about its\n * pivot) and into the shape's un-transformed, centred frame. Returns `null` when\n * the scale is zero — the shape has collapsed and encloses nothing.\n */\nfunction toShapeLocal(point: Vector2, s: ShapePlacement, width: number, height: number): Vector2 | null {\n if (s.scale === 0) return null;\n const pivot = s.pivot as Vector2;\n // Pivot is normalised [-1, 1] about the shape centre, y-up here (the\n // renderer negates its y because it works in canvas space).\n const px = pivot.x * (width / 2);\n const py = pivot.y * (height / 2);\n // Relative to the pivot, in the parent's (unrotated) frame.\n const dx = point.x - (s.x + px);\n const dy = point.y - (s.y + py);\n // Undo the clockwise rotation: in y-up space the forward map is\n // (cos·x + sin·y, -sin·x + cos·y), so the inverse swaps the sine signs.\n const rad = (s.rotation * Math.PI) / 180;\n const cos = Math.cos(rad);\n const sin = Math.sin(rad);\n const rx = (cos * dx - sin * dy) / s.scale;\n const ry = (sin * dx + cos * dy) / s.scale;\n // Back to centre-relative: the pivot sits (px, py) from the centre.\n return { x: rx + px, y: ry + py };\n}\n\n// ─── Primitives ──────────────────────────────────────────────────────────────\n\ninterface Corners4 { topLeft: number; topRight: number; bottomRight: number; bottomLeft: number }\n\n/**\n * Axis-aligned box centred on the origin, with per-corner rounding. A corner is\n * only excluded when the point sits beyond that corner's quarter-circle, so a\n * plain rect (all radii 0) reduces to the box test exactly. `cornerStyle` is not\n * consulted: an `'angled'` chamfer cuts strictly inside the arc, so testing the\n * arc over-estimates by a sliver — the forgiving direction for a grab test.\n */\nfunction containsRect(p: Vector2, width: number, height: number, radius: Corners4, tolerance: number): boolean {\n const halfW = width / 2 + tolerance;\n const halfH = height / 2 + tolerance;\n if (Math.abs(p.x) > halfW || Math.abs(p.y) > halfH) return false;\n\n // Pick the corner the point is nearest and test its arc. Radii are clamped\n // the way any rounded-rect rasteriser clamps them: never past half the side.\n const maxR = Math.min(width, height) / 2;\n const r = Math.min(\n maxR,\n p.x <= 0\n ? (p.y >= 0 ? radius.topLeft : radius.bottomLeft)\n : (p.y >= 0 ? radius.topRight : radius.bottomRight),\n );\n if (r <= 0) return true;\n\n // Centre of that corner's arc, then the usual \"outside the quarter-circle\"\n // check — which only bites inside the corner square itself.\n const sx = Math.sign(p.x || 1);\n const sy = Math.sign(p.y || 1);\n const dx = p.x - sx * (width / 2 - r);\n const dy = p.y - sy * (height / 2 - r);\n if (Math.sign(dx || 1) !== sx || Math.sign(dy || 1) !== sy) return true;\n return dx * dx + dy * dy <= (r + tolerance) * (r + tolerance);\n}\n\n/**\n * Ellipse, honouring the same `ratio`/`sweep`/`startAngle` family the renderer\n * draws (see `EllipseShape.buildSVGPath`), so the grab region is the region that\n * was actually painted:\n *\n * - `ratio` ≤ 0 → solid disk, or a wedge for a partial sweep\n * - 0 < `ratio` < 1 → annulus / annular sector (the hole is not hittable)\n * - `ratio` ≥ 1 → the band has collapsed to the bare outer curve, so only\n * points near that curve hit\n */\nfunction containsEllipse(\n p: Vector2, width: number, height: number,\n ratio: number, sweep: number, startAngle: number,\n tolerance: number,\n): boolean {\n const rx = width / 2;\n const ry = height / 2;\n if (rx <= 0 || ry <= 0) return false;\n\n const clamped = Math.max(0, Math.min(1, ratio));\n const full = Math.abs(sweep) >= 360;\n\n // Outside the outer curve (grown by tolerance) can never hit.\n if (norm(p, rx + tolerance, ry + tolerance) > 1) return false;\n\n if (clamped > 0) {\n const inner = norm(p, Math.max(EPS, rx * clamped - tolerance), Math.max(EPS, ry * clamped - tolerance));\n if (inner < 1) return false;\n }\n\n if (full) return true;\n return withinSweep(Math.atan2(p.y / ry, p.x / rx) * (180 / Math.PI), startAngle, sweep, p, tolerance);\n}\n\n/** Normalised radius of `p` on an ellipse of half-axes `rx`/`ry` (1 = on the curve). */\nfunction norm(p: Vector2, rx: number, ry: number): number {\n return Math.hypot(p.x / rx, p.y / ry);\n}\n\n/**\n * Whether `angleDeg` lies within the arc `[startAngle, startAngle + sweep]`,\n * with `tolerance` converted to angular slack at the point's own radius so\n * grab-slop widens the wedge's straight edges too. Handles negative sweeps.\n */\nfunction withinSweep(\n angleDeg: number, startAngle: number, sweep: number,\n p: Vector2, tolerance: number,\n): boolean {\n const lo = sweep >= 0 ? startAngle : startAngle + sweep;\n const span = Math.abs(sweep);\n // Near the centre every angle is within tolerance of the wedge.\n const radius = Math.hypot(p.x, p.y);\n if (radius <= tolerance) return true;\n const slack = tolerance > 0 ? (tolerance / Math.max(radius, EPS)) * (180 / Math.PI) : 0;\n let delta = (angleDeg - lo) % 360;\n if (delta < 0) delta += 360;\n // Accept the wrap-around side within slack as well.\n return delta <= span + slack || delta >= 360 - slack;\n}\n\n/**\n * Vertices of a regular polygon inscribed in `width`×`height`, y-up author\n * space. The renderer starts at the top vertex and steps clockwise in canvas\n * space; in y-up that is `+π/2` stepping negative.\n */\nexport function polygonVertices(width: number, height: number, sides: number): Vector2[] {\n const n = Math.max(3, Math.round(sides));\n const rx = width / 2;\n const ry = height / 2;\n const step = (2 * Math.PI) / n;\n const out: Vector2[] = [];\n for (let i = 0; i < n; i++) {\n const a = Math.PI / 2 - i * step;\n out.push({ x: rx * Math.cos(a), y: ry * Math.sin(a) });\n }\n return out;\n}\n\n/** Vertices of a star polygon: outer radius 1 alternating with inner radius `ratio`. */\nexport function polygramVertices(width: number, height: number, sides: number, ratio: number): Vector2[] {\n const n = Math.max(3, Math.round(sides));\n const r = Math.max(0, Math.min(1, ratio));\n const rx = width / 2;\n const ry = height / 2;\n const step = Math.PI / n;\n const out: Vector2[] = [];\n for (let i = 0; i < n * 2; i++) {\n const a = Math.PI / 2 - i * step;\n const k = i % 2 === 0 ? 1 : r;\n out.push({ x: rx * k * Math.cos(a), y: ry * k * Math.sin(a) });\n }\n return out;\n}\n\n/**\n * Even-odd crossing test against a polygon, widened by `tolerance`: a point just\n * outside an edge still counts. `closed` also closes the last→first segment for\n * the tolerance band.\n */\nfunction containsPolyline(p: Vector2, verts: readonly Vector2[], closed: boolean, tolerance: number): boolean {\n if (verts.length >= 3 && pointInPolygon(p, verts)) return true;\n return tolerance > 0 && nearPolyline(p, verts, closed, tolerance);\n}\n\n/** Even-odd crossing test against a closed polygon. No tolerance band. */\nexport function pointInPolygon(p: Vector2, verts: readonly Vector2[]): boolean {\n if (verts.length < 3) return false;\n let inside = false;\n for (let i = 0, j = verts.length - 1; i < verts.length; j = i++) {\n const a = verts[i];\n const b = verts[j];\n if ((a.y > p.y) !== (b.y > p.y) && p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x) {\n inside = !inside;\n }\n }\n return inside;\n}\n\n/** Whether `p` is within `tolerance` of any segment of the polyline. */\nexport function nearPolyline(p: Vector2, pts: readonly Vector2[], closed: boolean, tolerance: number): boolean {\n if (pts.length === 0) return false;\n if (pts.length === 1) return Math.hypot(p.x - pts[0].x, p.y - pts[0].y) <= tolerance;\n const last = closed ? pts.length : pts.length - 1;\n for (let i = 0; i < last; i++) {\n if (distanceToSegment(p, pts[i], pts[(i + 1) % pts.length]) <= tolerance) return true;\n }\n return false;\n}\n\n/** Shortest distance from `p` to the segment `a`–`b`. */\nexport function distanceToSegment(p: Vector2, a: Vector2, b: Vector2): number {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const lenSq = dx * dx + dy * dy;\n if (lenSq <= EPS) return Math.hypot(p.x - a.x, p.y - a.y);\n let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq;\n t = t < 0 ? 0 : t > 1 ? 1 : t;\n return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));\n}\n", "/**\n * Every type the expression module names, in one place.\n *\n * The vocabulary is small and worth seeing at once, because the whole module is\n * four representations and the steps between them:\n *\n * a prop value ──▶ \"=4[g]+3\" ──▶ ExpressionNode ──▶ () => unknown\n * at any depth the marked the AST, per a prop binding\n * (walk) string dialect (parse) (compile)\n *\n * The `=` appears in exactly one of those steps. It marks a *document prop* as a\n * formula, which is recognition, not grammar — `=` is not a legal character in\n * any dialect — so the walk strips it and the parser never sees one.\n */\n\n/** Thrown for a formula that cannot be parsed or whose reference resolves to nothing. */\nexport class ExpressionError extends Error {\n /** The formula as the parser received it: no marker, and no surrounding prop. */\n readonly source: string;\n /** Character offset into {@link source}, or `-1` when the whole thing is at fault. */\n readonly position: number;\n /** Where in the props bag it was written, JSON-Pointer style, when known. */\n readonly path?: string;\n\n constructor(message: string, source: string, position = -1, path?: string) {\n const where = position >= 0 ? ` (at character ${position + 1} of \"${source}\")` : ` (in \"${source}\")`;\n super(`${message}${where}${path ? ` at ${path}` : \"\"}`);\n this.name = \"ExpressionError\";\n this.source = source;\n this.position = position;\n this.path = path;\n }\n}\n\n// ── The syntax tree ──────────────────────────────────────────────────────────\n\nexport type BinaryOp = \"+\" | \"-\" | \"*\" | \"/\" | \"%\" | \"^\";\n\n/** One node of a parsed formula. Kept public so a host can lint or rewrite one. */\nexport type ExpressionNode =\n | { kind: \"const\"; value: number }\n | { kind: \"ref\"; name: string }\n | { kind: \"unary\"; op: \"-\"; operand: ExpressionNode }\n | { kind: \"binary\"; op: BinaryOp; left: ExpressionNode; right: ExpressionNode }\n | { kind: \"call\"; name: string; args: ExpressionNode[] };\n\n/** A formula, parsed. Resolver-free, so it can be checked without a scene. */\nexport interface ParsedExpression {\n /** The formula's text as the parser received it — no marker. */\n readonly source: string;\n readonly root: ExpressionNode;\n /** Names it reads, de-duplicated, in first-seen order. */\n readonly refs: readonly string[];\n /**\n * True when the formula is exactly one reference and nothing else.\n *\n * The passthrough case: the document's compiled binding returns the\n * variable's value untouched rather than coercing it to a number, which is\n * what lets a variable hold a colour, a `Vector2` or any other prop value.\n * A dialect whose references are bare identifiers sets it for a lone\n * variable too (`\"x\"`), where it means nothing — only the document's\n * compiler reads it.\n */\n readonly passthrough: boolean;\n}\n\n// ── Dialects ─────────────────────────────────────────────────────────────────\n\n/** What the parser needs to know about a function. What it *does* is the back end's. */\nexport interface FnArity {\n /** Minimum and maximum argument count; `Infinity` for variadic. */\n arity: [number, number];\n}\n\n/**\n * One language over the shared grammar.\n *\n * The grammar is fixed — precedence, implicit multiplication, right-associative\n * `^`, the scientific-notation rule — and everything a language is free to\n * disagree about is here. That is what lets the document's `sin` be degrees and\n * a function plot's be radians without two parsers: the trig unit is a property\n * of a table, not of the grammar.\n */\nexport interface ExpressionDialect {\n /** Names callable as `f(…)`, and how many arguments each takes. */\n functions: Record<string, FnArity>;\n /** Bare identifiers that are values. Folded at parse time, so one can never also be a reference. */\n constants: Record<string, number>;\n /**\n * How a reference is spelled. `\"bracket\"` is `[id]`, and is the only mode in\n * which `[` is a legal character; `\"bare\"` makes any identifier that is not a\n * call or a constant a reference.\n */\n refs: \"bracket\" | \"bare\";\n /** What an identifier that resolves to nothing says. The document points at `[id]`; a plot does not. */\n unknownName(name: string): string;\n}\n\n// ── Compilation ──────────────────────────────────────────────────────────────\n\n/**\n * Resolves a name to a read function, or `undefined` when nothing in the\n * document declares it. The read is what the compiled binding calls, once per\n * evaluation of the prop it drives.\n */\nexport type VariableResolver = (name: string) => (() => unknown) | undefined;\n\n/**\n * A prop value, compiled: either a plain value or the binding an expression\n * somewhere inside it produced.\n */\nexport type CompiledValue =\n | { dynamic: false; value: unknown }\n | { dynamic: true; read: () => unknown };\n\n/** A props bag, split into what a constructor can take and what has to be bound. */\nexport interface CompiledProps {\n /**\n * Props with no expression in them.\n *\n * Handed to the node's constructor as-is. A bound prop is deliberately\n * *absent* here rather than present as a placeholder: a node's constructor\n * reads its raw props to decide things like a default size, and a\n * placeholder would answer those questions with a lie.\n */\n literal: Record<string, unknown>;\n /** Field → binding, applied with `node.set()` once the variables exist. */\n bindings: Record<string, () => unknown>;\n /** True when {@link CompiledProps.bindings} has anything in it. */\n hasBindings: boolean;\n}\n\n/** One expression found in a document, and where. */\nexport interface ExpressionSite {\n /** JSON-Pointer-style path, matching `ValidationIssue.path`. */\n path: string;\n /** The raw prop value, `=` and all. */\n source: string;\n}\n", "/**\n * The one scanner and the one grammar, plus the document's own dialect.\n *\n * There were two of each — this module's, and the function-plot language in\n * `@motionscript/math` — and they agreed on every rule they documented while\n * disagreeing on the parts nobody wrote down. Plot scanned `1.2.3` as a single\n * token, which `Number` turned into a `NaN` that parsed, compiled and rendered\n * an entirely invisible surface with no diagnostic anywhere. It treated `\\r` as\n * an unexpected character, so a pasted CRLF equation failed. It checked no arity\n * on its variadic functions, so `atan2(1)` was a silent `NaN`.\n *\n * What the two genuinely disagree about is a *table*: which functions exist,\n * whether `sin` takes degrees or radians, and how a reference is spelled. That\n * is {@link ExpressionDialect}, and it is the only thing this file is\n * parameterized by.\n *\n * Precedence is the ordinary arithmetic one, with `^` right-associative and\n * **implicit multiplication** between adjacent primaries — which is what makes\n * `4[g]+3` mean what it reads as. Note `unary` sits *above* `power`, so `-2^2`\n * is `-4` as in maths, and the exponent parses as a unary so `2^3^2` is 512 and\n * `2^-3` is legal.\n */\nimport { ExpressionError } from \"./types\";\nimport type { BinaryOp, ExpressionDialect, ExpressionNode, FnArity, ParsedExpression } from \"./types\";\n\nconst DEG = Math.PI / 180;\n\ninterface DocumentFn extends FnArity {\n apply(args: number[]): number;\n}\n\n/**\n * The document's function library.\n *\n * Deliberately small and closed: an expression is stored in a document and\n * evaluated by whatever version of the library opens it later, so every name\n * here is as much a public contract as an exported symbol. Trig is in **degrees**\n * because every other angle in the library is.\n */\nexport const DOCUMENT_FUNCTIONS: Record<string, DocumentFn> = {\n abs: { arity: [1, 1], apply: (a) => Math.abs(a[0]) },\n sign: { arity: [1, 1], apply: (a) => Math.sign(a[0]) },\n sqrt: { arity: [1, 1], apply: (a) => Math.sqrt(a[0]) },\n floor: { arity: [1, 1], apply: (a) => Math.floor(a[0]) },\n ceil: { arity: [1, 1], apply: (a) => Math.ceil(a[0]) },\n round: { arity: [1, 2], apply: (a) => (a.length > 1 && a[1] !== 0 ? Math.round(a[0] / a[1]) * a[1] : Math.round(a[0])) },\n min: { arity: [1, Infinity], apply: (a) => Math.min(...a) },\n max: { arity: [1, Infinity], apply: (a) => Math.max(...a) },\n clamp: { arity: [3, 3], apply: (a) => Math.min(Math.max(a[0], a[1]), a[2]) },\n mod: { arity: [2, 2], apply: (a) => ((a[0] % a[1]) + a[1]) % a[1] },\n pow: { arity: [2, 2], apply: (a) => a[0] ** a[1] },\n log: { arity: [1, 2], apply: (a) => (a.length > 1 ? Math.log(a[0]) / Math.log(a[1]) : Math.log(a[0])) },\n exp: { arity: [1, 1], apply: (a) => Math.exp(a[0]) },\n mix: { arity: [3, 3], apply: (a) => a[0] + (a[1] - a[0]) * a[2] },\n smoothstep: {\n arity: [3, 3],\n apply: (a) => {\n if (Number.isNaN(a[0]) || Number.isNaN(a[1]) || Number.isNaN(a[2])) return NaN;\n // Equal edges: a step at the edge, like `step` — no divide by zero.\n if (a[0] === a[1]) return a[2] < a[0] ? 0 : 1;\n const t = Math.min(Math.max((a[2] - a[0]) / (a[1] - a[0]), 0), 1);\n return t * t * (3 - 2 * t);\n },\n },\n step: { arity: [2, 2], apply: (a) => (Number.isNaN(a[0]) || Number.isNaN(a[1]) ? NaN : a[1] < a[0] ? 0 : 1) },\n sin: { arity: [1, 1], apply: (a) => Math.sin(a[0] * DEG) },\n cos: { arity: [1, 1], apply: (a) => Math.cos(a[0] * DEG) },\n tan: { arity: [1, 1], apply: (a) => Math.tan(a[0] * DEG) },\n asin: { arity: [1, 1], apply: (a) => Math.asin(a[0]) / DEG },\n acos: { arity: [1, 1], apply: (a) => Math.acos(a[0]) / DEG },\n atan: { arity: [1, 1], apply: (a) => Math.atan(a[0]) / DEG },\n atan2: { arity: [2, 2], apply: (a) => Math.atan2(a[0], a[1]) / DEG },\n hypot: { arity: [2, Infinity], apply: (a) => Math.hypot(...a) },\n};\n\n/** Bare identifiers that are values rather than calls. */\nconst DOCUMENT_CONSTANTS: Record<string, number> = {\n pi: Math.PI,\n tau: Math.PI * 2,\n e: Math.E,\n};\n\n/** The language a `\"=…\"` prop is written in. */\nexport const DOCUMENT_DIALECT: ExpressionDialect = {\n functions: DOCUMENT_FUNCTIONS,\n constants: DOCUMENT_CONSTANTS,\n refs: \"bracket\",\n unknownName: (name) =>\n `unknown name \"${name}\" — a variable is referenced as \"[${name}]\"; ` +\n `bare names are the constants ${sortedKeys(DOCUMENT_CONSTANTS).join(\", \")}`,\n};\n\n/** Sorted, so a message or a completion list is stable. */\nexport function sortedKeys(table: Record<string, unknown>): string[] {\n return Object.keys(table).sort();\n}\n\n// ── Scanner ──────────────────────────────────────────────────────────────────\n\ntype TokenKind = \"number\" | \"ref\" | \"ident\" | \"op\" | \"(\" | \")\" | \",\" | \"end\";\n\ninterface Token {\n kind: TokenKind;\n /** The identifier, operator or reference name. Empty for numbers. */\n text: string;\n /** Parsed value, for numbers. */\n value: number;\n pos: number;\n}\n\nconst OPERATORS = new Set([\"+\", \"-\", \"*\", \"/\", \"%\", \"^\"]);\n\nfunction isDigit(ch: string | undefined): boolean {\n return ch !== undefined && ch >= \"0\" && ch <= \"9\";\n}\n\nfunction tokenize(source: string, dialect: ExpressionDialect): Token[] {\n const tokens: Token[] = [];\n let i = 0;\n\n while (i < source.length) {\n const ch = source[i];\n\n if (ch === \" \" || ch === \"\\t\" || ch === \"\\n\" || ch === \"\\r\") {\n i++;\n continue;\n }\n\n if (isDigit(ch) || (ch === \".\" && isDigit(source[i + 1]))) {\n const start = i;\n while (isDigit(source[i])) i++;\n if (source[i] === \".\") {\n i++;\n while (isDigit(source[i])) i++;\n }\n if (source[i] === \"e\" || source[i] === \"E\") {\n const mark = i;\n i++;\n if (source[i] === \"+\" || source[i] === \"-\") i++;\n if (isDigit(source[i])) {\n while (isDigit(source[i])) i++;\n } else {\n // `2e` followed by something else is `2` times the identifier\n // `e`, not a malformed exponent.\n i = mark;\n }\n }\n // A second `.` ends a number that has already had one. Both parsers\n // this replaces got here differently and both got it wrong: one\n // scanned `1.2.3` as a single token that `Number` turned into a\n // silent `NaN`, the other split it into `1.2 * 0.3`. Neither is\n // anything anyone wrote on purpose.\n if (source[i] === \".\") throw new ExpressionError('unexpected character \".\"', source, i);\n tokens.push({ kind: \"number\", text: \"\", value: Number(source.slice(start, i)), pos: start });\n continue;\n }\n\n // `[` is legal only where a reference is spelled with one, so a plot\n // equation gets \"unexpected character\" here rather than failing later\n // with a message about variable references it has never heard of.\n if (ch === \"[\" && dialect.refs === \"bracket\") {\n const start = i;\n const end = source.indexOf(\"]\", i + 1);\n if (end === -1) throw new ExpressionError(\"unclosed `[` — a variable reference is written `[id]`\", source, start);\n const name = source.slice(i + 1, end).trim();\n if (name.length === 0) throw new ExpressionError(\"empty variable reference `[]`\", source, start);\n if (name.includes(\"[\")) throw new ExpressionError(\"variable references cannot nest\", source, start);\n tokens.push({ kind: \"ref\", text: name, value: 0, pos: start });\n i = end + 1;\n continue;\n }\n\n if (/[A-Za-z_]/.test(ch)) {\n const start = i;\n while (i < source.length && /[A-Za-z0-9_]/.test(source[i])) i++;\n tokens.push({ kind: \"ident\", text: source.slice(start, i), value: 0, pos: start });\n continue;\n }\n\n if (OPERATORS.has(ch)) {\n tokens.push({ kind: \"op\", text: ch, value: 0, pos: i++ });\n continue;\n }\n if (ch === \"(\" || ch === \")\" || ch === \",\") {\n tokens.push({ kind: ch as TokenKind, text: ch, value: 0, pos: i++ });\n continue;\n }\n\n throw new ExpressionError(`unexpected character \"${ch}\"`, source, i);\n }\n\n tokens.push({ kind: \"end\", text: \"\", value: 0, pos: source.length });\n return tokens;\n}\n\n// ── Grammar ──────────────────────────────────────────────────────────────────\n\n/**\n * Parse a formula against a dialect.\n *\n * `source` is the formula alone — the document's `=` is stripped by the walk\n * that recognised it, because the marker is not part of any grammar.\n */\nexport function parse(source: string, dialect: ExpressionDialect = DOCUMENT_DIALECT): ParsedExpression {\n if (source.trim().length === 0) throw new ExpressionError(\"empty expression\", source);\n\n const tokens = tokenize(source, dialect);\n const refs: string[] = [];\n let index = 0;\n\n const peek = (): Token => tokens[index];\n const next = (): Token => tokens[index++];\n\n const addRef = (name: string): ExpressionNode => {\n if (!refs.includes(name)) refs.push(name);\n return { kind: \"ref\", name };\n };\n\n /** True when the token can begin a primary — the test implicit `*` turns on. */\n const startsPrimary = (t: Token): boolean =>\n t.kind === \"number\" || t.kind === \"ref\" || t.kind === \"ident\" || t.kind === \"(\";\n\n function parseAdditive(): ExpressionNode {\n let left = parseMultiplicative();\n for (;;) {\n const t = peek();\n if (t.kind === \"op\" && (t.text === \"+\" || t.text === \"-\")) {\n next();\n left = { kind: \"binary\", op: t.text, left, right: parseMultiplicative() };\n continue;\n }\n return left;\n }\n }\n\n function parseMultiplicative(): ExpressionNode {\n let left = parseUnary();\n for (;;) {\n const t = peek();\n if (t.kind === \"op\" && (t.text === \"*\" || t.text === \"/\" || t.text === \"%\")) {\n next();\n left = { kind: \"binary\", op: t.text as BinaryOp, left, right: parseUnary() };\n continue;\n }\n // `4[g]`, `2(x+1)`, `[a][b]`, `2pi` — juxtaposition is multiplication.\n if (startsPrimary(t)) {\n left = { kind: \"binary\", op: \"*\", left, right: parseUnary() };\n continue;\n }\n return left;\n }\n }\n\n function parseUnary(): ExpressionNode {\n const t = peek();\n if (t.kind === \"op\" && (t.text === \"-\" || t.text === \"+\")) {\n next();\n const operand = parseUnary();\n return t.text === \"-\" ? { kind: \"unary\", op: \"-\", operand } : operand;\n }\n return parsePower();\n }\n\n function parsePower(): ExpressionNode {\n const base = parsePrimary();\n const t = peek();\n if (t.kind === \"op\" && t.text === \"^\") {\n next();\n // Right-associative, and binding tighter than unary minus on its\n // right: `2^-1` is a half, not an error.\n return { kind: \"binary\", op: \"^\", left: base, right: parseUnary() };\n }\n return base;\n }\n\n function parseCall(name: string, pos: number): ExpressionNode {\n // Own keys only: `toString(1)` must be an unknown function, not a lookup\n // that finds `Object.prototype`'s.\n const def = Object.hasOwn(dialect.functions, name) ? dialect.functions[name] : undefined;\n if (!def) {\n throw new ExpressionError(\n `unknown function \"${name}\" — available: ${sortedKeys(dialect.functions).join(\", \")}`,\n source, pos,\n );\n }\n const args: ExpressionNode[] = [];\n if (peek().kind !== \")\") {\n for (;;) {\n args.push(parseAdditive());\n if (peek().kind !== \",\") break;\n next();\n }\n }\n const close = next();\n if (close.kind !== \")\") throw new ExpressionError(`expected \\`)\\` closing ${name}(`, source, close.pos);\n\n const [min, max] = def.arity;\n if (args.length < min || args.length > max) {\n const want = max === Infinity ? `at least ${min}` : min === max ? `${min}` : `${min}–${max}`;\n // Singular only when `want` names the number one (`1`, `at least 1`), never for a range.\n const plural = (max === Infinity || min === max) && min === 1 ? \"\" : \"s\";\n throw new ExpressionError(\n `${name}() takes ${want} argument${plural}, got ${args.length}`,\n source, pos,\n );\n }\n return { kind: \"call\", name, args };\n }\n\n function parsePrimary(): ExpressionNode {\n const t = next();\n switch (t.kind) {\n case \"number\":\n return { kind: \"const\", value: t.value };\n case \"ref\":\n return addRef(t.text);\n case \"(\": {\n const inner = parseAdditive();\n const close = next();\n if (close.kind !== \")\") throw new ExpressionError(\"expected `)`\", source, close.pos);\n return inner;\n }\n case \"ident\": {\n if (peek().kind === \"(\") {\n next();\n return parseCall(t.text, t.pos);\n }\n // A constant is folded here, before a bare identifier can become\n // a reference — so a dialect's constant name can never also be\n // one of its free variables.\n const constant = Object.hasOwn(dialect.constants, t.text) ? dialect.constants[t.text] : undefined;\n if (constant !== undefined) return { kind: \"const\", value: constant };\n if (dialect.refs === \"bare\") return addRef(t.text);\n throw new ExpressionError(dialect.unknownName(t.text), source, t.pos);\n }\n default:\n throw new ExpressionError(\n t.kind === \"end\" ? \"expression ends early\" : `unexpected \"${t.text}\"`,\n source, t.pos,\n );\n }\n }\n\n const root = parseAdditive();\n const trailing = peek();\n if (trailing.kind !== \"end\") throw new ExpressionError(`unexpected \"${trailing.text}\"`, source, trailing.pos);\n\n return { source, root, refs, passthrough: root.kind === \"ref\" };\n}\n", "/**\n * The document's back end: an {@link ExpressionNode} tree into the binding a\n * `PropSlot` takes.\n *\n * The tree is compiled into closures once rather than walked per read — the\n * difference matters on a scene where a hundred props read the same variable\n * every frame. A dialect with a different target compiles the same AST its own\n * way; `@motionscript/math` emits `(x, y) => number` from this one, and shares\n * the front end rather than this file.\n */\nimport { DOCUMENT_FUNCTIONS } from \"./parse\";\nimport { ExpressionError } from \"./types\";\nimport type { ExpressionNode, ParsedExpression, VariableResolver } from \"./types\";\n\n/**\n * Coerce a variable's value into the number arithmetic needs.\n *\n * A number is itself, a boolean is `1` or `0`, and a string is what `Number`\n * reads from it (`\"5\"` is 5, `\"0x10\"` is 16) unless it is empty after trimming,\n * which is `NaN`. Anything else — `null`, `undefined`, an object — is `NaN`\n * too. That is the intent: a `width` of `NaN` is visible in the first frame,\n * where a silent `0` looks like a deliberate collapse and gets debugged as a\n * layout problem, and `Number(\"\")` is exactly that silent zero.\n */\nfunction toNumber(value: unknown): number {\n if (typeof value === \"number\") return value;\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (typeof value === \"string\") return value.trim() === \"\" ? NaN : Number(value);\n return NaN;\n}\n\n/**\n * `path` is where in the props bag the formula was written, so a reference to\n * something undeclared names the prop and not just the formula.\n */\nexport function compile(parsed: ParsedExpression, resolve: VariableResolver, path?: string): () => unknown {\n const readOf = (name: string): (() => unknown) => {\n const read = resolve(name);\n if (!read) {\n throw new ExpressionError(\n `\"${name}\" resolves to nothing in this document — a reference names a variable ` +\n `(declared with a \"variable\" command), a constant (a \\`constants\\` row), or another ` +\n `node's prop as \"[key.prop]\" (\\`key\\` on that node's row)`,\n parsed.source, -1, path,\n );\n }\n return read;\n };\n\n // A lone `[x]` hands the value over untouched: see `passthrough`.\n if (parsed.passthrough) return readOf((parsed.root as { name: string }).name);\n\n const emit = (node: ExpressionNode): (() => number) => {\n switch (node.kind) {\n case \"const\": {\n const { value } = node;\n return () => value;\n }\n case \"ref\": {\n const read = readOf(node.name);\n return () => toNumber(read());\n }\n case \"unary\": {\n const operand = emit(node.operand);\n return () => -operand();\n }\n case \"binary\": {\n const left = emit(node.left);\n const right = emit(node.right);\n switch (node.op) {\n case \"+\": return () => left() + right();\n case \"-\": return () => left() - right();\n case \"*\": return () => left() * right();\n case \"/\": return () => left() / right();\n case \"%\": return () => left() % right();\n case \"^\": return () => left() ** right();\n }\n break;\n }\n case \"call\": {\n const { apply } = DOCUMENT_FUNCTIONS[node.name];\n const args = node.args.map(emit);\n return () => apply(args.map((a) => a()));\n }\n }\n throw new ExpressionError(\"unsupported expression node\", parsed.source, -1, path);\n };\n\n return emit(parsed.root);\n}\n", "/**\n * Recognition, and the one walk over an authored prop value.\n *\n * There were two walks — one compiling, one collecting — with the same three\n * cases and different leaves, and they had already drifted: the compiling one\n * read `Object.keys`, the collecting one `for…in`. Neither carried a path, so an\n * `ExpressionError` from a formula nested inside a `fill` array named the\n * formula and left the reader to find which prop it was written in.\n *\n * One recursion now, parameterized by what to do with a string. `bind` returns a\n * replacement, so containers are rebuilt around it; `collect` returns its input,\n * so nothing is rebuilt and the result is thrown away.\n */\nimport { compile } from \"./compile\";\nimport { parse } from \"./parse\";\nimport type { CompiledProps, CompiledValue, ExpressionSite, VariableResolver } from \"./types\";\n\n/**\n * True when a value is a formula rather than a string.\n *\n * `\"==\"` is the escape, so `\"==total\"` is the literal `\"=total\"` and not an\n * expression; a bare `\"=\"` is likewise just that string. Both are handled by\n * {@link unescape}, which every literal path runs values through.\n */\nexport function isSource(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 1 && value[0] === \"=\" && value[1] !== \"=\";\n}\n\n/** Strip the escape from a literal string that begins with `=`. `\"==x\"` → `\"=x\"`. */\nexport function unescape(value: string): string {\n return value.startsWith(\"==\") ? value.slice(1) : value;\n}\n\n/** What the walk does with each string it reaches. Returns the value to put back. */\ntype StringHandler = (source: string, path: string) => CompiledValue;\n\nconst STATIC = (value: unknown): CompiledValue => ({ dynamic: false, value });\n\n/**\n * Visit every string in an authored value, at any depth.\n *\n * An expression is recognised at any depth, not just as a whole prop, because\n * half the props worth driving are compound: `{\"origin\": {\"x\": \"=[g]\", \"y\": 0}}`,\n * `{\"fill\": [\"#111\", {\"type\": \"solid\", \"color\": \"=[c]\"}]}`. A container holding\n * one is rebuilt on each recompute; a container holding none is passed through\n * **by identity**, so a scene that uses no expressions allocates nothing and\n * compares equal to the document it came from.\n */\nfunction walk(value: unknown, path: string, onString: StringHandler): CompiledValue {\n if (typeof value === \"string\") return onString(value, path);\n\n if (Array.isArray(value)) {\n const parts = value.map((v, i) => walk(v, `${path}[${i}]`, onString));\n if (parts.some((p) => p.dynamic)) {\n return { dynamic: true, read: () => parts.map((p) => (p.dynamic ? p.read() : p.value)) };\n }\n // Rebuild only if a leaf actually changed, so the common case keeps the\n // document's own array.\n const rebuilt = parts.map((p) => (p as { value: unknown }).value);\n return STATIC(rebuilt.every((v, i) => v === value[i]) ? value : rebuilt);\n }\n\n if (isPlainObject(value)) {\n const keys = Object.keys(value);\n const parts = keys.map((k) => walk(value[k], `${path}.${k}`, onString));\n if (parts.some((p) => p.dynamic)) {\n return {\n dynamic: true,\n read: () => {\n const out: Record<string, unknown> = {};\n keys.forEach((k, i) => {\n const part = parts[i];\n out[k] = part.dynamic ? part.read() : part.value;\n });\n return out;\n },\n };\n }\n if (!parts.some((p, i) => (p as { value: unknown }).value !== value[keys[i]])) return STATIC(value);\n const rebuilt: Record<string, unknown> = {};\n keys.forEach((k, i) => { rebuilt[k] = (parts[i] as { value: unknown }).value; });\n return STATIC(rebuilt);\n }\n\n return STATIC(value);\n}\n\n/** Compile one authored prop value: a plain value, or the binding it produced. */\nexport function bind(value: unknown, resolve: VariableResolver, path = \"props\"): CompiledValue {\n return walk(value, path, (source, at) =>\n isSource(source)\n // The `=` is the document's marker, not the grammar's — strip it here\n // and the parser never sees one.\n ? { dynamic: true, read: compile(parse(source.slice(1)), resolve, at) }\n : STATIC(unescape(source)));\n}\n\n/** Compile a whole props bag. See {@link CompiledProps}. */\nexport function bindProps(\n props: Record<string, unknown> | undefined,\n resolve: VariableResolver,\n path = \"props\",\n): CompiledProps {\n const literal: Record<string, unknown> = {};\n const bindings: Record<string, () => unknown> = {};\n let hasBindings = false;\n\n for (const key of Object.keys(props ?? {})) {\n const compiled = bind(props![key], resolve, `${path}.${key}`);\n if (compiled.dynamic) {\n bindings[key] = compiled.read;\n hasBindings = true;\n } else {\n literal[key] = compiled.value;\n }\n }\n return { literal, bindings, hasBindings };\n}\n\n/**\n * Find every expression inside an authored value, at any depth.\n *\n * Used by the validator, which checks that each one parses and names a declared\n * variable — the two failures worth catching before anything is built.\n */\nexport function collect(value: unknown, path: string): ExpressionSite[] {\n const out: ExpressionSite[] = [];\n walk(value, path, (source, at) => {\n if (isSource(source)) out.push({ path: at, source });\n return STATIC(source);\n });\n return out;\n}\n\n/** A bracketed reference. The grammar has no string literals, so a `[` is always one. */\nconst REF = /\\[([^[\\]]+)\\]/g;\n\n/**\n * Rewrite the references inside every expression in an authored value.\n *\n * `rename` sees each reference as written (`\"fade\"`, `\"card.x\"`) and returns its\n * replacement, or `undefined` to keep it. What a host moving a subtree between\n * documents needs when ids or keys change on the way; a value with nothing to\n * rewrite comes back **by identity**, the same as {@link bind}'s static path.\n */\nexport function renameRefs<T>(value: T, rename: (ref: string) => string | undefined): T {\n const result = walk(value, \"\", (source) => {\n if (!isSource(source)) return STATIC(source);\n return STATIC(source.replace(REF, (whole, ref: string) => {\n // The parser trims a reference's name (`[ g ]` reads `g`), so the callback sees it trimmed too.\n const next = rename(ref.trim());\n return next === undefined ? whole : `[${next}]`;\n }));\n });\n return (result as { value: T }).value;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n", "/**\n * Every expression operation, on one object.\n *\n * The same shape `pathOps` has, for the same reason — one value to import, and a\n * call site one grep from its implementation. Unlike `pathOps`, `insetsOps` and\n * the rest, this is **not** an `AttributeOps`: an expression is not an attribute,\n * has no `resolve`/`lerp` pair, and nothing in `attributes/properties/typed.ts`\n * builds a property from it. Only the naming convention transfers.\n *\n * Behind it is one grammar. There were two — this one and the function-plot\n * language in `@motionscript/math` — agreeing on every rule they documented and\n * disagreeing everywhere they hadn't. The pipeline is now:\n *\n * a prop value ── bind/collect ──▶ \"=4[g]+3\" ── parse ──▶ ExpressionNode\n * (one walk) the marker │\n * stripped here ▼\n * compile ──▶ () => unknown\n *\n * A dialect chooses the function library and how a reference is spelled, so\n * `sin` can be degrees here and radians in a plot without a second parser.\n */\nimport { DOCUMENT_DIALECT, parse, sortedKeys } from \"./parse\";\nimport { compile } from \"./compile\";\nimport { bind, bindProps, collect, isSource, renameRefs, unescape } from \"./walk\";\nimport type {\n CompiledProps, CompiledValue, ExpressionDialect, ExpressionSite,\n ParsedExpression, VariableResolver,\n} from \"./types\";\n\n/** {@link parse}, tolerating the `=` a raw prop value still carries. */\nfunction parseSource(source: string, dialect: ExpressionDialect = DOCUMENT_DIALECT): ParsedExpression {\n return parse(isSource(source) ? source.slice(1) : source, dialect);\n}\n\nexport interface ExpressionOps {\n // ── Recognition ────────────────────────────────────────────────────────\n /** True for a formula. `\"==\"` escapes a literal string starting with `=`. */\n isSource(value: unknown): value is string;\n /** Strip that escape: `\"==x\"` → `\"=x\"`. Everything else passes through. */\n unescape(value: string): string;\n\n // ── Reading ────────────────────────────────────────────────────────────\n /** Parse a formula, with or without its leading `=`. Throws `ExpressionError`. */\n parse(source: string, dialect?: ExpressionDialect): ParsedExpression;\n /** {@link ExpressionOps.parse} without throwing — the shape a validator wants. */\n tryParse(source: string, dialect?: ExpressionDialect): { expression: ParsedExpression } | { error: string };\n\n // ── Binding ────────────────────────────────────────────────────────────\n /** A parsed formula into the binding a `PropSlot` takes. */\n compile(parsed: ParsedExpression, resolve: VariableResolver, path?: string): () => unknown;\n /** One authored prop value: a plain value, or the binding an expression inside it produced. */\n bind(value: unknown, resolve: VariableResolver, path?: string): CompiledValue;\n /** A whole props bag, split into what a constructor can take and what has to be bound. */\n bindProps(props: Record<string, unknown> | undefined, resolve: VariableResolver, path?: string): CompiledProps;\n\n // ── Inspecting ─────────────────────────────────────────────────────────\n /** Every expression inside an authored value, with a JSON-Pointer-style path. */\n collect(value: unknown, path: string): ExpressionSite[];\n /** Rewrite the `[ref]`s inside every expression in a value; `undefined` keeps one. */\n renameRefs<T>(value: T, rename: (ref: string) => string | undefined): T;\n /** Every function name, for a host offering completion. Sorted. */\n functions(): string[];\n /** Every constant name, for a host offering completion. Sorted. */\n constants(): string[];\n /** The language a document's props are written in. */\n readonly dialect: ExpressionDialect;\n}\n\nexport const expressionOps: ExpressionOps = {\n isSource,\n unescape,\n\n parse: parseSource,\n tryParse: (source, dialect) => {\n try {\n return { expression: parseSource(source, dialect) };\n } catch (e) {\n return { error: e instanceof Error ? e.message : String(e) };\n }\n },\n\n compile,\n bind,\n bindProps,\n\n collect,\n renameRefs,\n functions: () => sortedKeys(DOCUMENT_DIALECT.functions),\n constants: () => sortedKeys(DOCUMENT_DIALECT.constants),\n dialect: DOCUMENT_DIALECT,\n};\n", "import { expressionOps } from \"./expression/ops\";\nimport type { Registry } from \"./registry\";\n\n/**\n * How a node type's props changed since documents first named it — declared by\n * a component spec's `renamed`, `deprecated` and `migrate`, applied to a row's\n * props whenever one is built, and callable by a host rewriting stored rows.\n *\n * Unlike a document migration this has no version to go by: a row stored a year\n * ago and one stored today pass through the same rules, so every rule has to\n * leave a current value alone.\n */\nexport interface PropEvolution {\n /** Old key → the entry it became. A row setting both keeps the new one. */\n readonly renamed: Readonly<Record<string, string>>;\n /** Entry → why it is deprecated and what to use instead. It still works. */\n readonly deprecated: Readonly<Record<string, string>>;\n /**\n * Key → a value hook. Keyed by an old key from {@link renamed}, it converts\n * only what was stored under that key (a unit change rides on a rename);\n * keyed by an entry, it runs on every stored value and must hand a current\n * one back unchanged. `undefined` drops the prop back to its default.\n */\n readonly migrate: Readonly<Record<string, (value: unknown) => unknown>>;\n}\n\n/** One prop a migration touched, or one a row still sets that is deprecated. */\nexport interface PropNote {\n prop: string;\n message: string;\n}\n\nexport interface PropMigration {\n /** The props given, when nothing changed; a new object otherwise. */\n props: Record<string, unknown>;\n changes: PropNote[];\n deprecated: PropNote[];\n}\n\nconst PROP_EVOLUTION = Symbol(\"propEvolution\");\n\n/** @internal Record `evolution` on a node class; a component factory does this for its generated class. */\nexport function declarePropEvolution(ctor: abstract new (...args: never[]) => object, evolution: PropEvolution): void {\n (ctor.prototype as Record<symbol, unknown>)[PROP_EVOLUTION] = evolution;\n}\n\n/** @internal What {@link declarePropEvolution} recorded on this exact class. */\nexport function propEvolutionOf(ctor: abstract new (...args: never[]) => object): PropEvolution | undefined {\n const proto = ctor.prototype as Record<symbol, unknown> | undefined;\n if (!proto || !Object.prototype.hasOwnProperty.call(proto, PROP_EVOLUTION)) return undefined;\n return proto[PROP_EVOLUTION] as PropEvolution;\n}\n\n/**\n * Bring a stored row's props up to what `type` declares today: old keys\n * renamed, values migrated, deprecated props reported. A type this registry\n * does not know, or one that never changed, hands `props` back as it is.\n *\n * Applies equally to a `to`/`set` command's args, which are a props diff.\n * An expression is moved by a rename but handed to no value hook: a formula's\n * result cannot be converted by rewriting it, so it is noted and left as written.\n */\nexport function migrateNodeProps(registry: Registry, type: string, props: Record<string, unknown>): PropMigration {\n const ctor = registry.node(type)?.ctor;\n const evolution = ctor ? propEvolutionOf(ctor) : undefined;\n return evolution ? applyPropEvolution(evolution, props) : { props, changes: [], deprecated: [] };\n}\n\n/** @internal {@link migrateNodeProps} once the type's rules are in hand. */\nexport function applyPropEvolution(evolution: PropEvolution, props: Record<string, unknown>): PropMigration {\n const changes: PropNote[] = [];\n const deprecated: PropNote[] = [];\n let out: Record<string, unknown> | null = null;\n const write = () => (out ??= { ...props });\n const isExpression = (value: unknown) => expressionOps.collect(value, \"\").length > 0;\n\n const convert = (key: string, value: unknown, at: string): unknown => {\n const hook = evolution.migrate[key];\n if (!hook || value === undefined) return value;\n if (isExpression(value)) {\n changes.push({ prop: at, message: `\"${at}\" is an expression, so its value was left as written.` });\n return value;\n }\n return hook(value);\n };\n\n for (const [from, to] of Object.entries(evolution.renamed)) {\n if (!Object.hasOwn(props, from)) continue;\n const target = write();\n const value = convert(from, props[from], from);\n delete target[from];\n if (props[to] !== undefined) {\n changes.push({ prop: from, message: `\"${from}\" was renamed \"${to}\", which the row also sets; the old value was dropped.` });\n continue;\n }\n if (value === undefined) delete target[to];\n else target[to] = value;\n changes.push({ prop: from, message: `\"${from}\" was renamed \"${to}\".` });\n }\n\n for (const key of Object.keys(evolution.migrate)) {\n if (Object.hasOwn(evolution.renamed, key)) continue;\n const current = (out ?? props)[key];\n if (current === undefined) continue;\n const next = convert(key, current, key);\n if (next === current) continue;\n const target = write();\n if (next === undefined) delete target[key];\n else target[key] = next;\n changes.push({ prop: key, message: next === undefined ? `\"${key}\" was dropped back to its default.` : `\"${key}\" was migrated.` });\n }\n\n for (const [key, message] of Object.entries(evolution.deprecated)) {\n if ((out ?? props)[key] !== undefined) deprecated.push({ prop: key, message });\n }\n return { props: out ?? props, changes, deprecated };\n}\n", "import { EMPTY_TEXT_STYLE, TEXT_SHAPING_KEYS, textOps } from \"@/attributes/text/ops\";\nimport type { ResolvedTextSpan, TextShapingKey, TextStyle } from \"@/attributes/text/types\";\nimport { Graphics2D, type GraphicsOp, type GraphicsShapeOp } from \"./graphics2d\";\n\n/** The recorded `text` op, state and all. */\ntype TextOp = Extract<GraphicsShapeOp, { kind: \"text\" }>;\n/** The recorded `richText` op, state and all. */\ntype RichTextOp = Extract<GraphicsShapeOp, { kind: \"richText\" }>;\n\n/**\n * The span-level half of {@link TEXT_SHAPING_KEYS}. A `richText` op carries its\n * typography per span rather than on the shape, so a default has to be filled in\n * span by span — except `lineHeight`/`textAlign`, which lay the block out as a\n * whole and so live on the op itself.\n */\nconst SPAN_KEYS = [\n 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'letterSpacing',\n] as const satisfies readonly TextShapingKey[];\n\n/** The `richText` op's own layout keys — the ones that aren't per-span. */\nconst RICHTEXT_BLOCK_KEYS = [\n 'lineHeight', 'textAlign',\n] as const satisfies readonly TextShapingKey[];\n\n/**\n * `graphics` with `style` filled into every `text`/`richText` op that left a\n * shaping field unset — the drawn-text half of `<DefaultTextStyle>`.\n *\n * A `Text` node inherits defaults through the context channel, once, at bind\n * time (`applyTextDefaults`); a raw `Graphics2D` has no node to bind, so it\n * inherits here instead, at draw time, from the scope it is drawn in. Called\n * from `RenderContext2D.draw`, so a custom node's `ctx.draw(...)`, an offscreen\n * rasterization and the precomp pass's asset walk all see the same resolved op\n * list — which is what makes an inherited font actually *load* rather than\n * merely be asked for.\n *\n * A key counts as unset only when it is `undefined`: an op that names a value\n * always wins, exactly as an author-set prop beats an inherited one on a node.\n * Returns `graphics` itself when nothing changes, which is the common case (the\n * scene sets no defaults, or every op already names its own).\n */\nexport function applyGraphicsTextDefaults(graphics: Graphics2D, style: TextStyle): Graphics2D {\n // Not gated on `style` alone any more: an op naming a `variant` has\n // something to inherit even in a scope that sets nothing, so the walk has to\n // happen either way. The lazy copy below is what keeps that cheap.\n const ambient = hasShapingDefaults(style) ? style : EMPTY_TEXT_STYLE;\n\n const ops = graphics.ops();\n let next: GraphicsOp[] | null = null;\n for (let i = 0; i < ops.length; i++) {\n const op = ops[i];\n if (op.kind !== \"text\" && op.kind !== \"richText\") continue;\n const effective = effectiveStyle(op.state.variant, ambient);\n if (!hasShapingDefaults(effective)) continue;\n const patched = op.kind === \"text\"\n ? patchText(op, effective)\n : patchRichText(op, effective);\n if (!patched) continue;\n // Copy lazily: an op list with nothing to fill in keeps its identity, so\n // a fully-specified Text node allocates nothing on the way through.\n if (!next) next = ops.slice();\n next[i] = patched;\n }\n return next ? graphics._withOps(next) : graphics;\n}\n\n/**\n * The defaults one op inherits: its `variant`'s preset laid over the enclosing\n * scope's.\n *\n * That order is the node ladder one level down — an explicit value beats a\n * variant beats an inherited `<DefaultTextStyle>` — and it is why the merge is\n * here rather than in the caller: the ambient scope is per *subtree* while a\n * variant is per *op*, so they cannot be flattened before the walk.\n */\nfunction effectiveStyle(variant: string | undefined, ambient: TextStyle): TextStyle {\n return textOps.mergeStyle(ambient, variant ? textOps.preset(variant) : undefined);\n}\n\n/** Does `style` set anything a drawn text op could inherit? */\nfunction hasShapingDefaults(style: TextStyle): boolean {\n for (const key of TEXT_SHAPING_KEYS) {\n if (style[key] !== undefined) return true;\n }\n return false;\n}\n\nfunction patchText(op: TextOp, style: TextStyle): TextOp | null {\n const state = fillUnset(op.state, style, TEXT_SHAPING_KEYS);\n return state ? { kind: \"text\", state: state as TextOp[\"state\"] } : null;\n}\n\nfunction patchRichText(op: RichTextOp, style: TextStyle): RichTextOp | null {\n let state = fillUnset(op.state, style, RICHTEXT_BLOCK_KEYS);\n const spans = patchSpans(op.state.spans, style);\n if (spans) state = { ...(state ?? op.state), spans };\n return state ? { kind: \"richText\", state: state as RichTextOp[\"state\"] } : null;\n}\n\n/** The spans with defaults filled in, or `null` when none needed any. */\nfunction patchSpans(\n spans: ResolvedTextSpan[] | undefined,\n style: TextStyle,\n): ResolvedTextSpan[] | null {\n if (!spans || spans.length === 0) return null;\n // A span has no autofit mode — it is a run inside a block, sized by the\n // block — so an inherited `'autofit'` is skipped rather than written through\n // as a bad number.\n const spanStyle = style.fontSize === \"autofit\" ? { ...style, fontSize: undefined } : style;\n let next: ResolvedTextSpan[] | null = null;\n for (let i = 0; i < spans.length; i++) {\n const patched = fillUnset(spans[i], spanStyle, SPAN_KEYS);\n if (patched) (next ??= spans.slice())[i] = patched as unknown as ResolvedTextSpan;\n }\n return next;\n}\n\n/** A copy of `target` with each of `keys` it leaves `undefined` taken from `style`, or `null` when none needed filling. */\nfunction fillUnset(target: object, style: TextStyle, keys: readonly TextShapingKey[]): Record<string, unknown> | null {\n const current = target as Record<string, unknown>;\n let out: Record<string, unknown> | null = null;\n for (const key of keys) {\n if (current[key] !== undefined) continue;\n const value = style[key];\n if (value === undefined) continue;\n (out ??= { ...current })[key] = value;\n }\n return out;\n}\n", "import { Graphics2D } from \"./graphics2d\";\nimport type { Clip } from \"./clip\";\nimport type { RenderIssue } from \"./render-issue\";\nimport type { TransformState } from \"./descriptors/transform\";\nimport type { FontStyle, TextStyle } from \"@/attributes/text/types\";\nimport type { Size2D } from \"@/attributes/layout/size\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { MaskOptions } from \"@/attributes/mask/mask\";\nimport type { BooleanOperation } from \"@/attributes/mask/boolean\";\nimport { TextState } from \"./descriptors/text\";\nimport { TextBlockLayout } from \"./text-layout\";\nimport { EMPTY_TEXT_STYLE, textOps } from \"@/attributes/text/ops\";\nimport { applyGraphicsTextDefaults } from \"./text-defaults\";\nimport type { NodeRenderState, RasterizedSurface, RenderContext2D, RenderPass2D, SpaceRects, EffectTarget } from \"./render-context2d\";\nimport type { NodeEffect } from \"@/attributes/shape/effects/union\";\n\n/**\n * The base every {@link RenderContext2D} backend extends.\n *\n * It owns the parts of a render context that are the *same* whatever is being\n * rasterized — the text-default stack, the node scope stack, disposal — plus\n * the host-facing half of the surface (`execute`, `screenshot`, `unmount`),\n * which the {@link RenderContext2D} interface deliberately leaves out because a\n * node has no business driving a render pass from inside one.\n *\n * **`draw` is final by convention.** It resolves the ambient text defaults onto\n * the op list and hands the result to {@link drawGraphics}, which is where a\n * backend does its actual drawing. Owning that step here rather than in each\n * backend is what keeps the real renderer and the precomp asset walk agreeing\n * on which font an under-specified `text` op shapes with: a family that one\n * resolves and the other does not is a font that never loads and glyphs that\n * never paint.\n */\nexport abstract class CanvasRenderContext2D implements RenderPass2D {\n abstract measureText(text: string, fontSize: number, fontFamily: string, fontWeight?: number, letterSpacing?: number, fontStyle?: FontStyle): Size2D;\n\n // ---- Inherited text-style defaults ------------------------------------\n // `<DefaultTextStyle>` reaches a `Text`/`RichText` node through the context\n // map, applied once when the node binds. A raw `Graphics2D` has no node to\n // bind, so it inherits the same defaults here instead — pushed around a\n // subtree's draw scope, and folded into each `text`/`richText` op by\n // `draw()`. Same vocabulary (`TextStyle`), same precedence, two channels.\n\n /**\n * Defaults in effect for the current draw scope, innermost last. Each entry\n * is **already merged** onto the one below it (see {@link pushTextStyle}), so\n * the top of the stack is the effective style and reading it costs nothing.\n */\n private readonly textStyleStack: TextStyle[] = [];\n\n /** See {@link RenderContext2D.pushTextStyle}. */\n pushTextStyle(style: TextStyle | null): void {\n this.textStyleStack.push(style === null ? EMPTY_TEXT_STYLE : textOps.mergeStyle(this.defaultTextStyle, style));\n }\n\n /** Close the innermost scope opened by {@link pushTextStyle}. */\n popTextStyle(): void {\n this.textStyleStack.pop();\n }\n\n /**\n * The text-style defaults in effect right now — the innermost\n * {@link pushTextStyle} scope, or the project's `theme.typography.default`\n * when no scope is open.\n *\n * Carries all ten {@link TEXT_STYLE_KEYS}, but only the shaping ones reach a\n * `Graphics2D` op; see `TEXT_SHAPING_KEYS` for why `fill`/`stroke`/`shadow`\n * stay a node-level concern.\n */\n get defaultTextStyle(): TextStyle {\n return this.textStyleStack[this.textStyleStack.length - 1] ?? textOps.preset(\"default\");\n }\n\n /** See {@link RenderContext2D.draw}. Final by convention — override {@link drawGraphics}. */\n draw(graphics: Graphics2D): void {\n this.drawGraphics(applyGraphicsTextDefaults(graphics, this.defaultTextStyle));\n }\n\n /** Paint a `Graphics2D` whose text ops have already been resolved against the\n * ambient defaults. Backends implement this instead of {@link draw}. */\n protected abstract drawGraphics(graphics: Graphics2D): void;\n\n /**\n * See {@link RenderContext2D.layoutTextBlock}. Concrete rather than abstract,\n * and `null` by default, so a backend that has no need to report glyph\n * positions is unaffected — the only thing it gives up is on-canvas text\n * editing in a host built on it.\n */\n layoutTextBlock(state: Partial<TextState>): TextBlockLayout | null {\n return null;\n }\n\n /** Stack of node ids currently being drawn, innermost last. */\n protected currentNodeStack: string[] = [];\n\n /** Returns the id of the innermost node currently being drawn. */\n protected currentNodeId(): string {\n if (this.currentNodeStack.length === 0) {\n throw new Error(\"No current node in context\");\n }\n\n return this.currentNodeStack[this.currentNodeStack.length - 1];\n }\n\n /** Remove all renderer-side resources for the current node (called on unmount). */\n abstract unmount(): void;\n\n private _disposed = false;\n /** `true` after `dispose()` — the context must not be used after this point. */\n isDisposed(): boolean {\n return this._disposed;\n }\n dispose(): void {\n this._disposed = true;\n }\n\n /**\n * Execute `callback`, which issues shape/paint calls, and flush the result\n * to the underlying render target (canvas, SVG document, etc.). A callback\n * that throws still throws, and the next pass starts from a clean context.\n */\n abstract execute(callback: () => void): void;\n /**\n * What the frames since the last call drew without failing but not as the\n * document says (a blend mode the backend lacks, a shader that does not\n * compile, a lost GPU device), once per kind, feature and node. The\n * playback controller reports them as render errors; an export hands them\n * to its `onIssue`. A bare string is a `shader` issue.\n */\n takeRenderIssues(): Array<RenderIssue | string> {\n return [];\n }\n /** Capture the current frame as a base-64 PNG data URL, or `undefined` if unsupported. */\n abstract screenshot(): string | undefined;\n\n abstract transform(state: Partial<TransformState>): RenderContext2D;\n\n abstract beginBoolean(op: BooleanOperation): void;\n abstract endBoolean(): void;\n\n abstract beginMask(options?: MaskOptions): void;\n abstract applyMask(): void;\n abstract endMask(): void;\n\n abstract beginClip(clip: Clip): void;\n abstract endClip(): void;\n\n /** See {@link RenderContext2D.beginEffects}. No-op by default. */\n beginEffects(effects: NodeEffect[], target: EffectTarget, width: number, height: number): void { }\n endEffects(): void { }\n\n /** See {@link RenderContext2D.rasterize}. Returns `null` by default. */\n rasterize(\n width: number,\n height: number,\n draw: () => void,\n pixelRatio?: number,\n ): RasterizedSurface | null {\n return null;\n }\n\n abstract beginCamera(viewport: { x: number; y: number; width: number; height: number }, lookAt: Vector2, zoom: number, heading: number): void;\n abstract endCamera(): void;\n\n /**\n * Per-node render state for each node on the draw stack, in push order\n * (innermost last). Kept parallel to `currentNodeStack` so fills with\n * `space: 'parent'` can resolve their reference rect and so\n * motion-driven effects can read the current node's velocity.\n */\n protected renderStateStack: NodeRenderState[] = [];\n\n /** See {@link RenderContext2D.readsSpaceRects}. */\n readonly readsSpaceRects: boolean = true;\n\n /** See {@link RenderContext2D.drawsVisibleOnly}. */\n readonly drawsVisibleOnly: boolean = true;\n\n /** See {@link RenderPass2D.begin}. */\n begin(state: NodeRenderState): void {\n this.currentNodeStack.push(state.id);\n this.renderStateStack.push(state);\n }\n\n /** Close the innermost node draw scope opened by `begin()`. */\n end(): void {\n this.currentNodeStack.pop();\n this.renderStateStack.pop();\n }\n\n /** Reference rects for the node currently being drawn (parent / viewport). */\n protected currentSpaceRects(): SpaceRects {\n return this.renderStateStack[this.renderStateStack.length - 1]?.rects ?? {};\n }\n\n /** Full render state (incl. velocity) for the node currently being drawn, if any. */\n protected currentRenderState(): NodeRenderState | undefined {\n return this.renderStateStack[this.renderStateStack.length - 1];\n }\n\n /**\n * Close every node and text-style scope still open. A backend calls this\n * when a pass ends, so a pass that threw cannot leave the next one inside\n * its scopes.\n */\n protected _resetScopes(): void {\n this.textStyleStack.length = 0;\n this.currentNodeStack.length = 0;\n this.renderStateStack.length = 0;\n }\n}\n", "import type { RenderContext2D } from \"./render-context2d\";\nimport { CanvasRenderContext2D } from \"./canvas-render-context2d\";\nimport { Graphics2D } from \"./graphics2d\";\nimport { Clip } from \"./clip\";\nimport { TransformState } from \"./descriptors/transform\";\nimport { BooleanOperation } from \"@/attributes/mask/boolean\";\nimport { MaskOptions } from \"@/attributes/mask/mask\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { Size2D } from \"@/attributes/layout/size\";\n\n/** Shared, since nothing here measures anything and no caller mutates it. */\nconst ZERO_SIZE: Size2D = { width: 0, height: 0 };\n\n/**\n * A `RenderContext2D` that runs a render pass and rasterizes nothing.\n *\n * Every hook is inert, but the *walk* is real: `render()` recurses, `draw()`\n * still applies text defaults, and a subtree handed to\n * {@link rasterize} is still entered. So this exercises the same\n * traversal, ordering and skip rules a backend would see, without needing one.\n *\n * It exists for tests and for a host that wants to drive a scene's structure\n * without pixels. It is deliberately **not** an asset-discovery pass: assets are\n * declared by nodes (see `Node.declareAssets`), not\n * inferred from what a walk happens to paint. A context that quietly collected\n * them on the side is exactly the coupling that made a font impossible to load\n * before the layout that named it.\n */\nexport class NullRenderContext extends CanvasRenderContext2D {\n /**\n * Parent-space rects cost a resolution pass per node and nothing here reads\n * them, so skip it — this walk is about which nodes are visited, not where\n * they land.\n */\n override readonly readsSpaceRects = false;\n\n protected drawGraphics(graphics: Graphics2D): void { }\n\n measureText(): Size2D {\n return ZERO_SIZE;\n }\n\n unmount(): void { }\n\n execute(callback: () => void): void {\n callback();\n }\n\n screenshot(): string | undefined {\n return undefined;\n }\n\n /** Nothing is rasterized, but the subtree is still walked. */\n override rasterize(width: number, height: number, draw: () => void): null {\n draw();\n return null;\n }\n\n transform(state: Partial<TransformState>): RenderContext2D {\n return this;\n }\n\n beginBoolean(op: BooleanOperation): void { }\n endBoolean(): void { }\n\n beginMask(_options?: MaskOptions): void { }\n applyMask(): void { }\n endMask(): void { }\n\n beginClip(clip: Clip): void { }\n endClip(): void { }\n\n beginCamera(\n _viewport: { x: number; y: number; width: number; height: number },\n _centerOn: Vector2,\n _zoom: number,\n _heading: number,\n ): void { }\n endCamera(): void { }\n}\n", "import { Clip } from \"@/render/clip\";\nimport type { Graphics2D } from \"@/render/graphics2d\";\n\n/** The outline a shape's ops describe, as a clip: what `clip: true` cuts children to and picking tests against. */\nexport function clipOf(shape: Graphics2D): Clip {\n const clip = new Clip();\n for (const op of shape.ops()) {\n switch (op.kind) {\n case \"rect\": clip.rect(op.state); break;\n case \"ellipse\": clip.ellipse(op.state); break;\n case \"path\": clip.path(op.state); break;\n case \"line\": clip.line(op.state); break;\n case \"polygon\": clip.polygon(op.state); break;\n case \"polygram\": clip.polygram(op.state); break;\n case \"cut\": clip.cut(); break;\n default: break;\n }\n }\n return clip;\n}\n", "import type { Node } from \"@/components/trees/node/node\";\nimport { getCommandMeta } from \"@/tween/command-decorator\";\nimport { driveCommand, settles, settling, type Command, type CommandArgs } from \"@/tween/command\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport type { NodeView, Piece, PieceData, SoundOptions, Timeline } from \"@/components/factory/api\";\nimport type { ComponentHost } from \"@/components/factory/views\";\n\nconst piece = (data: PieceData): Piece => ({ _piece: data });\n\n/** What a command is handed for one placement: its args and timing, and the builders for its pieces. */\nexport function makeTimeline(args: object, duration: number, easing: EasingFunction | undefined, node: NodeView): Timeline<any, any> {\n return {\n args,\n duration,\n easing,\n node,\n tween: (targets) => piece({ kind: \"tween\", targets: targets as Record<string, unknown> }),\n animate: (frame, options) => piece({ kind: \"animate\", frame: frame as (t: number) => Record<string, unknown>, eased: options?.eased !== false }),\n ease: (t) => (easing ? easing(t) : t),\n sound: (src, options) => piece({ kind: \"sound\", src, options: options ?? {} }),\n wait: (seconds) => piece({ kind: \"wait\", seconds }),\n together: (pieces) => piece({ kind: \"together\", pieces }),\n sequence: (pieces) => piece({ kind: \"sequence\", pieces }),\n stagger: (pieces, options) => piece({ kind: \"stagger\", pieces, overlap: options?.overlap ?? 0 }),\n };\n}\n\n/** A sound a command plays, in seconds from the command's start; `until` absent plays to its own end. */\nexport interface CommandSound {\n readonly at: number;\n readonly until: number | undefined;\n readonly src: string;\n readonly options: SoundOptions;\n}\n\n/** A built piece: how long it lasts, the frame it writes `elapsed` seconds in, whether that only tweens slots, and its sounds. */\ninterface Timed {\n readonly duration: number;\n readonly settles: boolean;\n readonly sounds: readonly CommandSound[];\n apply(elapsed: number): void;\n}\n\nconst SILENT: readonly CommandSound[] = [];\n\n/**\n * A leaf, built and run to its end at once, so the piece after it reads where\n * it finished — the rule the timeline already keeps between whole commands.\n */\nfunction leaf(command: Command<Record<string, unknown>>, duration: number, pure = true): Timed {\n command.at(1);\n return { duration, settles: pure, sounds: SILENT, apply: (elapsed) => command.at(duration > 0 ? elapsed / duration : 1) };\n}\n\nfunction placed(parts: readonly Timed[], offsets: readonly number[]): Timed {\n const duration = parts.reduce((max, part, i) => Math.max(max, offsets[i] + part.duration), 0);\n return {\n duration,\n settles: parts.every((part) => part.settles),\n sounds: parts.flatMap((part, i) => part.sounds.map((s) => ({\n ...s, at: s.at + offsets[i], until: s.until === undefined ? undefined : s.until + offsets[i],\n }))),\n apply(elapsed) {\n // A part that hasn't started writes nothing: what came before it stands.\n for (let i = 0; i < parts.length; i++) {\n if (elapsed < offsets[i]) continue;\n parts[i].apply(Math.min(elapsed - offsets[i], parts[i].duration));\n }\n },\n };\n}\n\n/** A piece built against the tree as the pieces before it left it, spread over `duration`. */\nfunction timedOf(host: ComponentHost, p: Piece, duration: number, easing: EasingFunction | undefined): Timed {\n const data = p._piece;\n switch (data.kind) {\n case \"tween\":\n return leaf(host.to({ data: data.targets, duration, easing }) as Command<Record<string, unknown>>, duration);\n case \"animate\":\n return leaf(host._animate(data.frame, duration, data.eased ? easing : undefined) as Command<Record<string, unknown>>, duration);\n case \"child\":\n return leaf((data.node as Node).to({ data: data.targets, duration, easing }) as Command<Record<string, unknown>>, duration);\n case \"run\": {\n // Any command of the child's, so it settles only if that one does.\n const run = runCommand(data.node as Node, data.name, data.args, duration, easing);\n return leaf(run, duration, settles(run));\n }\n case \"wait\":\n return { duration: data.seconds, settles: true, sounds: SILENT, apply: () => { } };\n case \"sound\":\n // Scheduled ahead of time, not written per frame: the clip's audio reads it off the built command.\n return { duration: 0, settles: true, sounds: data.src ? [{ at: 0, until: undefined, src: data.src, options: data.options }] : SILENT, apply: () => { } };\n case \"together\": {\n const parts = data.pieces.map((part) => timedOf(host, part, duration, easing));\n return placed(parts, parts.map(() => 0));\n }\n case \"sequence\": {\n // Untimed pieces share what fixed `wait`s leave of the span.\n const fixed = data.pieces.reduce((sum, part) => sum + (part._piece.kind === \"wait\" ? part._piece.seconds : 0), 0);\n const flexible = data.pieces.filter((part) => part._piece.kind !== \"wait\").length;\n const each = flexible > 0 ? Math.max(0, duration - fixed) / flexible : 0;\n const parts: Timed[] = [];\n const offsets: number[] = [];\n let cursor = 0;\n for (const part of data.pieces) {\n const timed = timedOf(host, part, each, easing);\n parts.push(timed);\n offsets.push(cursor);\n cursor += timed.duration;\n }\n return placed(parts, offsets);\n }\n case \"stagger\": {\n const n = data.pieces.length;\n if (n === 0) return { duration, settles: true, sounds: SILENT, apply: () => { } };\n const step = 1 - Math.min(1, Math.max(0, data.overlap));\n // n pieces, each `each` long, started `each * step` apart, span the command exactly.\n const each = duration / (1 + (n - 1) * step);\n const parts = data.pieces.map((part) => timedOf(host, part, each, easing));\n return placed(parts, parts.map((_, i) => i * each * step));\n }\n }\n}\n\nfunction runCommand(node: Node, name: string, args: object | undefined, duration: number, easing: EasingFunction | undefined): Command<Record<string, unknown>> {\n const meta = getCommandMeta(node).find((m) => m.key === name);\n const method = meta ? (node as unknown as Record<string, unknown>)[meta.method] : undefined;\n if (typeof method !== \"function\") throw new Error(`${node.className} has no command \"${name}\".`);\n const built = (method as (args: CommandArgs) => unknown).call(node, { data: (args ?? {}) as Record<string, unknown>, duration, easing });\n if (!built || typeof built !== \"object\" || !(\"at\" in built)) throw new Error(`${node.className}.${name} did not return a command.`);\n return built as Command<Record<string, unknown>>;\n}\n\nconst SOUNDS = new WeakMap<object, { readonly host: Node; readonly sounds: readonly CommandSound[] }>();\n\n/** The sounds a built command plays, and the node playing them. */\nexport function commandSoundsOf(command: object): { readonly host: Node; readonly sounds: readonly CommandSound[] } | undefined {\n return SOUNDS.get(command);\n}\n\n/** The command a component's function returned, as the timeline places it. */\nexport function commandOf(host: ComponentHost, p: Piece, duration: number, easing: EasingFunction | undefined): Command<Record<string, unknown>> {\n // A lone tween is the engine's own `to`, exactly as a class's command would return it.\n if (p._piece.kind === \"tween\") return settling(host.to({ data: p._piece.targets, duration, easing }) as Command<Record<string, unknown>>);\n const timed = timedOf(host, p, duration, easing);\n const command = driveCommand(duration, (t) => timed.apply(t * duration)) as unknown as Command<Record<string, unknown>>;\n // A sound is cut when its command ends; a command with no length lets it play out.\n const sounds = timed.sounds.map((s) => (s.until === undefined && duration > 0 ? { ...s, until: duration } : s));\n if (sounds.length > 0) SOUNDS.set(command, { host, sounds });\n return timed.settles ? settling(command) : command;\n}\n", "import type { PropertyEditor } from \"@/attributes/properties/decorator\";\nimport type { TweenFn } from \"@/props/host\";\nimport type { Context } from \"@/util/context\";\n\n/**\n * Where an entry takes its value when the author left it unset: from the\n * context its ancestors provide (`use`), given what was set (`given`). Read on\n * the node's first attach. `undefined` keeps the default.\n */\nexport type Inherit = (use: <T>(context: Context<T>) => T, given: Readonly<Record<string, unknown>>) => unknown;\n\n/** What a state entry is at runtime: the `property` options it lowers onto, plus whether it is private. */\nexport interface TypeDef {\n /** Loose author form; mapped on construction. A function here is a factory, called once per node. */\n readonly default: unknown;\n readonly mapper?: (ext: any, prev?: any) => unknown;\n readonly tween?: TweenFn<any>;\n readonly editor: PropertyEditor;\n readonly private: boolean;\n readonly inherit?: Inherit;\n}\n\nexport const TYPE_DEF = \"_def\";\n\nexport function isTypeLike(value: unknown): value is { readonly _def: TypeDef } {\n return (typeof value === \"object\" || typeof value === \"function\") && value !== null && TYPE_DEF in value;\n}\n\n/** A literal state entry (`value: 0`, `label: 'Hi'`, `on: true`) as the Type it stands for. */\nexport function defOf(entry: unknown): TypeDef {\n if (isTypeLike(entry)) return entry._def;\n switch (typeof entry) {\n case \"number\": return { default: entry, editor: { kind: \"number\" }, private: false };\n case \"string\": return { default: entry, editor: { kind: \"text\" }, private: false };\n case \"boolean\": return { default: entry, editor: { kind: \"boolean\" }, private: false };\n default: throw new TypeError(`A state entry is a Types.* value, a number, a string or a boolean; got ${String(entry)}.`);\n }\n}\n", "import type { Size2D } from \"@/attributes/layout/size\";\nimport type { SizeConstraints } from \"@/layout/constraints\";\nimport type { Node2D, CameraScope } from \"@/components/trees/2d/node2d\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport type { Graphics2D } from \"@/render/graphics2d\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport type { RenderPass2D } from \"@/render/render-context2d\";\nimport type { Clip } from \"@/render/clip\";\nimport { NullRenderContext } from \"@/render/null-render-context\";\nimport { Graphics2D as GraphicsClass } from \"@/render/graphics2d\";\nimport { frameIn, Node2D as Node2DClass } from \"@/components/trees/2d/node2d\";\nimport { Node3D } from \"@/components/trees/three/node3d\";\nimport { Scene3D } from \"@/render3d/scene3d\";\nimport type { BooleanOperation } from \"@/attributes/mask/boolean\";\nimport type { MaskOptions } from \"@/attributes/mask/mask\";\nimport type { ChildBoundsMode } from \"@/components/trees/2d/group-bounds\";\nimport type { SpaceCamera } from \"@/attributes/layout/space3d\";\nimport type { TextStyle } from \"@/attributes/text/types\";\nimport type { MergePaint, ChildView, Clock, Component, Element, FontSpec, Max, Measurer, NodeFrame, NodeView, Piece, RenderContext2D } from \"@/components/factory/api\";\nimport { clipOf } from \"@/components/factory/clip-of\";\n\n/**\n * What a render did with its children beyond drawing them: composited them\n * (the ink bounds that leaves), looked at them through a camera, or stood them\n * in a 2.5D space. Picking and the space machinery read it between frames.\n */\nexport interface Composite {\n readonly bounds?: ChildBoundsMode;\n readonly camera?: CameraScope;\n readonly space?: SpaceCamera;\n /** The scene its 3D children were rendered into: what picking projects through. */\n readonly scene?: Scene3D;\n}\n\n/** The node a view stands for: how the engine's own modules (`Paint`, `Flow`) reach past the public surface. */\nexport const NODE = Symbol(\"componentNode\");\n\n/** What a generated node exposes to its views and modules. Never part of the authoring surface. */\nexport interface ComponentHost extends Node2D {\n _renderOwnChildren(pass: RenderPass2D): void;\n _animate(frame: (t: number) => Record<string, unknown>, duration: number, easing: unknown): unknown;\n _lastShape: Graphics2D | null;\n /** The composite its last render or probe declared; `undefined` before either. */\n _record: Composite | null | undefined;\n}\n\n// ---- the pass in progress -------------------------------------------------\n\n/**\n * Measure and layout run synchronously, one node at a time, so the node being\n * laid out and its measurer are a single slot rather than state on every view.\n */\ninterface Pass {\n readonly node: Node2D;\n readonly scope: MeasureContext2D;\n readonly room: Max;\n readonly sizes: Map<Node2D, Size2D>;\n}\n\nlet pass: Pass | null = null;\n\nexport function withPass<T>(node: Node2D, scope: MeasureContext2D, room: Max, run: () => T): T {\n const outer = pass;\n pass = { node, scope, room, sizes: new Map() };\n try {\n return run();\n } finally {\n pass = outer;\n }\n}\n\nconst decided = new WeakSet<Node2D>();\n\n/** An engine module sized this node itself in this measure: its factory reports the size as it stands. */\nexport function markDecided(node: Node2D): void {\n decided.add(node);\n}\n\nexport function takeDecided(node: Node2D): boolean {\n return decided.delete(node);\n}\n\nexport function currentPass(): Pass {\n if (!pass) throw new Error(\"A component's measure or layout helper ran outside a measure or layout pass.\");\n return pass;\n}\n\nfunction measureChild(node: Node2D, max: Max): Size2D {\n const p = currentPass();\n const constraints: SizeConstraints = { maxWidth: max.width, maxHeight: max.height };\n const measured = node.measure(constraints, p.scope);\n const size = { width: measured.width ?? 0, height: measured.height ?? 0 };\n p.sizes.set(node, size);\n return size;\n}\n\n// ---- child views ------------------------------------------------------------\n\nconst childViews = new WeakMap<Node2D, ChildViewImpl>();\n\n/** A child as its parent's fields see it. One per child node, reused every frame. */\nclass ChildViewImpl implements ChildView {\n readonly [NODE]: Node2D;\n readonly state: never;\n\n constructor(node: Node2D) {\n this[NODE] = node;\n // The node's own accessors are its resolved values; a proxy keeps a parent from writing through them.\n this.state = new Proxy(node, {\n set: () => { throw new TypeError(\"A child's state is read-only to its parent; animate it with a command.\"); },\n }) as never;\n }\n\n get id(): string { return this[NODE].id; }\n get key(): never { return (keyOf(this[NODE]) ?? this[NODE].className) as never; }\n\n get size(): Size2D {\n // Outside a pass (a command being built), the size it was last laid out at, as a command's own node reports.\n if (!pass) {\n const box = this[NODE].layoutBounds;\n return { width: box?.width ?? 0, height: box?.height ?? 0 };\n }\n return pass.sizes.get(this[NODE]) ?? measureChild(this[NODE], pass.room);\n }\n\n get children(): readonly ChildView[] {\n const node = this[NODE] as Node2D & { _commandChildren?(): readonly ChildView[] };\n return node._commandChildren ? node._commandChildren() : node.children.map(childView);\n }\n\n measure(max: Max): Size2D {\n return measureChild(this[NODE], max);\n }\n\n to(targets: object): Piece {\n return { _piece: { kind: \"child\", node: this[NODE], targets: targets as Record<string, unknown> } };\n }\n\n run(name: string, args?: object): Piece {\n return { _piece: { kind: \"run\", node: this[NODE], name, args } };\n }\n}\n\nexport function childView(node: Node2D | Node): ChildView {\n let view = childViews.get(node as Node2D);\n if (!view) childViews.set(node as Node2D, view = new ChildViewImpl(node as Node2D));\n return view as unknown as ChildView;\n}\n\nexport function nodeOfView(view: ChildView<any>): Node2D {\n return (view as unknown as ChildViewImpl)[NODE];\n}\n\nconst nodeViews = new WeakMap<Node, WeakMap<Node, NodeViewImpl>>();\n\nconst NO_FRAME: NodeFrame = { x: 0, y: 0, rotation: 0, scale: 1 };\n\n/** A node outside a component's own children (an ancestor, a referenced node), as one reader's fields read it. */\nclass NodeViewImpl implements NodeView {\n readonly [NODE]: Node;\n readonly state: never;\n\n constructor(node: Node, readonly reader: Node) {\n this[NODE] = node;\n // A component's state as its own fields read it: a reference of its own is a view from where it stands.\n // Anything else it has (a 2D node's cardinal points) reads off the node.\n const fields = (node as { _view?: object })._view ?? node;\n this.state = new Proxy(fields, {\n get: (target, key) => {\n // Its constructor is the node's: what a host asks to tell what kind of node it reads.\n if (key === \"constructor\") return node.constructor;\n if (key in target) return Reflect.get(target, key);\n const value = Reflect.get(node, key) as unknown;\n // A method of the node runs on the node, not on this read-only view.\n return typeof value === \"function\" ? (value as (...args: unknown[]) => unknown).bind(node) : value;\n },\n set: () => { throw new TypeError(\"Another node's state is read-only to a component; animate it with a command.\"); },\n }) as never;\n }\n\n get id(): string { return this[NODE].id; }\n get key(): never { return (keyOf(this[NODE] as Node2D) ?? this[NODE].className) as never; }\n\n get size(): Size2D {\n const node = this[NODE];\n const box = node instanceof Node2DClass ? node.layoutBounds : undefined;\n return { width: box?.width ?? 0, height: box?.height ?? 0 };\n }\n\n get frame(): NodeFrame {\n const node = this[NODE];\n return node instanceof Node2DClass && this.reader instanceof Node2DClass ? frameIn(this.reader, node) : NO_FRAME;\n }\n}\n\n/** `node` as `reader` sees it. One view per pair. */\nexport function nodeView(node: Node, reader: Node): NodeView {\n let byReader = nodeViews.get(node);\n if (!byReader) nodeViews.set(node, byReader = new WeakMap());\n let view = byReader.get(reader);\n if (!view) byReader.set(reader, view = new NodeViewImpl(node, reader));\n return view;\n}\n\nexport function nodeOfNodeView(view: NodeView): Node {\n return (view as unknown as NodeViewImpl)[NODE];\n}\n\nconst found = new WeakMap<Node, Map<string, Node>>();\n\n/** The node with `id` in `reader`'s scene, as `reader` sees it, or `null`. Remembered per reader while it stays in the scene. */\nexport function referenced(reader: Node, id: unknown): NodeView | null {\n if (typeof id !== \"string\" || id === \"\") return null;\n let known = found.get(reader);\n let node = known?.get(id);\n if (!node || node.id !== id || rootOf(node) !== rootOf(reader)) {\n node = findIn(rootOf(reader), id) ?? undefined;\n if (!node) {\n known?.delete(id);\n return null;\n }\n if (!known) found.set(reader, known = new Map());\n known.set(id, node);\n }\n return nodeView(node, reader);\n}\n\nfunction rootOf(node: Node): Node {\n let at = node;\n while (at.parent) at = at.parent;\n return at;\n}\n\nfunction findIn(at: Node, id: string): Node | null {\n if (at.id === id) return at;\n for (const child of at._allChildren) {\n const hit = findIn(child, id);\n if (hit) return hit;\n }\n return null;\n}\n\nlet keyOf: (node: Node2D) => string | undefined = () => undefined;\n/** Set by the factory module, which owns the node descriptors. */\nexport function setKeyLookup(lookup: (node: Node2D) => string | undefined): void {\n keyOf = lookup;\n}\n\n// ---- state views ------------------------------------------------------------\n\n/**\n * One prototype of getters per component, so a node's `state` is a single\n * object made once: every read goes straight to the node's own slot, and a\n * frame allocates nothing to hand its fields their values.\n */\nexport interface ViewShape {\n readonly proto: object;\n /** Own, so `{ ...state }` copies every entry; the getters themselves are shared. */\n readonly entries: PropertyDescriptorMap;\n}\n\nexport function stateViewPrototype(keys: readonly string[], references: ReadonlySet<string> = new Set()): ViewShape {\n const entries: PropertyDescriptorMap = {};\n for (const key of keys) {\n entries[key] = references.has(key)\n ? { get(this: { [NODE]: Node }) { return referenced(this[NODE], (this[NODE] as unknown as Record<string, unknown>)[key]); }, enumerable: true }\n : { get(this: { [NODE]: object }) { return (this[NODE] as Record<string, unknown>)[key]; }, enumerable: true };\n }\n const proto = {};\n // The children of the node's own tree, as its commands see them too.\n Object.defineProperty(proto, \"children\", {\n get(this: { [NODE]: { _commandChildren(): readonly ChildView[] } }) { return this[NODE]._commandChildren(); },\n enumerable: false,\n });\n return { proto, entries };\n}\n\nexport function stateView(shape: ViewShape, node: object): object {\n const view = Object.create(shape.proto) as { [NODE]: object };\n Object.defineProperties(view, shape.entries);\n view[NODE] = node;\n return view;\n}\n\n/** A command's `state`: where it starts, so a frame function reading it never sees its own writes. */\nexport function snapshot(view: object): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key in view) out[key] = (view as Record<string, unknown>)[key];\n return out;\n}\n\n// ---- measurer and render context --------------------------------------------\n\nexport class MeasurerImpl implements Measurer {\n max: Max = {};\n scope: MeasureContext2D | null = null;\n\n constructor(readonly host: Node) { }\n\n get time(): Clock {\n return this.host.time;\n }\n\n text(text: string, font: FontSpec): Size2D {\n if (!this.scope) throw new Error(\"measurer.text was called outside measure.\");\n return this.scope.measureText(text, font.fontSize, font.fontFamily, font.fontWeight, font.letterSpacing);\n }\n}\n\n/** Reused every frame: `pass` and `cut` are rewritten before each render. */\nexport class RenderContextImpl implements RenderContext2D {\n pass: RenderPass2D | null = null;\n /** The near-plane cut a 2.5D space puts in front of this node's own paint. */\n cut: Clip | null = null;\n\n /**\n * `probing`: `render` runs only to find the shape it paints (for clip and\n * picking outside a frame), so nothing is drawn and no child is visited.\n */\n constructor(readonly host: ComponentHost, readonly probing = false) { }\n\n get size(): Size2D {\n const box = this.host.layoutBounds;\n return { width: box?.width ?? 0, height: box?.height ?? 0 };\n }\n\n get time(): Clock {\n return this.host.time;\n }\n\n draw(graphics: Graphics2D | readonly Graphics2D[] | null | undefined): void {\n if (!graphics || this.probing) return;\n const out = this.target();\n if (Array.isArray(graphics)) for (const g of graphics) out.draw(g);\n else out.draw(graphics as Graphics2D);\n }\n\n children(): void {\n if (this.probing) return;\n // Drawn plainly, so a space or composite the last frame declared no longer holds for them.\n if (!this.composite) this.host._record = null;\n this.host._renderOwnChildren(this.target());\n }\n\n /** What this render has declared so far. Its host's record follows at once, so the children it draws see it. */\n composite: Composite | null = null;\n\n private _declare(composite: Composite): void {\n this.composite = { ...this.composite, ...composite };\n if (!this.probing) this.host._record = this.composite;\n }\n\n mask(options: MaskOptions): void {\n this._declare({ bounds: \"first\" });\n if (this.probing) return;\n const out = this.target();\n const [stencil, ...content] = this.host.children;\n if (!stencil) return;\n if (content.length === 0) {\n stencil.render(out);\n return;\n }\n out.beginMask({ mode: options.mode, inverted: options.inverted });\n stencil.render(out);\n out.applyMask();\n for (const child of content) child.render(out);\n out.endMask();\n }\n\n merge(op: BooleanOperation, paint: MergePaint): void {\n this._declare({ bounds: op === \"subtract\" ? \"first\" : op === \"intersect\" ? \"intersect\" : \"union\" });\n if (this.probing) return;\n const out = this.target();\n out.beginBoolean(op);\n for (const child of this.host._allChildren) if (child instanceof Node2DClass) child.render(out);\n out.endBoolean();\n // A drawing with no shape of its own paints the merged outline.\n out.draw(new GraphicsClass().shadow(paint.shadow).fill(paint.fill));\n if (paint.overlay && (paint.overlay as unknown[]).length > 0) out.draw(new GraphicsClass().fill(paint.overlay));\n out.draw(new GraphicsClass().stroke(paint.stroke));\n }\n\n /** Your children, through a camera viewing your box: aimed at `lookAt`, zoomed, turned by `heading`. */\n camera(scope: CameraScope): void {\n this._declare({ camera: scope });\n if (this.probing) return;\n const out = this.target();\n const rect = this.host.layoutBounds;\n out.beginCamera({ x: rect?.x ?? 0, y: -(rect?.y ?? 0), width: rect?.width ?? 0, height: rect?.height ?? 0 }, scope.lookAt, scope.zoom, scope.heading);\n for (const child of this.host._allChildren) if (child instanceof Node2DClass) child.render(out);\n out.endCamera();\n }\n\n /** Your 3D children, rendered in order into a new scene. */\n scene3D(): Scene3D {\n const scene = new Scene3D();\n for (const child of this.host._allChildren) if (child instanceof Node3D) child.render(scene);\n this._declare({ scene });\n return scene;\n }\n\n /** Your children, standing in one 2.5D space seen by `camera`, drawn far to near. */\n space(camera: SpaceCamera): void {\n this._declare({ space: camera });\n if (!this.probing) this.host._renderOwnChildren(this.target());\n }\n\n textStyle(style: TextStyle | null, body: () => void): void {\n if (this.probing) return body();\n const out = this.target();\n out.pushTextStyle(style);\n try {\n body();\n } finally {\n out.popTextStyle();\n }\n }\n\n clip(shape: Graphics2D, body: () => void): void {\n if (this.probing) return body();\n const outline = clipOf(shape);\n // No outline is no clip, as a node with no `clipSelf` confines nothing.\n if (outline.isEmpty()) return body();\n const out = this.target();\n out.beginClip(outline);\n try {\n body();\n } finally {\n out.endClip();\n }\n }\n\n /** An ancestor stands this node in a space: one opens it, and nothing between them flattens. */\n get inSpace(): boolean {\n for (let at = this.host.parent; at; at = at.parent) {\n if (!(at instanceof Node2DClass)) return false;\n if (at._spaceCamera()) return true;\n if (!at._rendersChildrenInSpace()) return false;\n }\n return false;\n }\n\n ancestor<K extends string, S, C>(component: Component<K, S, C, any, any, any>): NodeView<Element<K, S, C>> | null {\n for (let at = this.host.parent; at; at = at.parent) {\n if (at instanceof component.node) return nodeView(at, this.host) as unknown as NodeView<Element<K, S, C>>;\n }\n return null;\n }\n\n /** Paint `body` in front of the space's near plane, as `Node2D` does for its own paint. */\n inFront(body: () => void): void {\n if (this.probing) return;\n const out = this.target();\n if (!this.cut) {\n body();\n return;\n }\n out.beginClip(this.cut);\n try {\n body();\n } finally {\n out.endClip();\n }\n }\n\n target(): RenderPass2D {\n if (this.probing) return PROBE_PASS;\n if (!this.pass) throw new Error(\"A component's render context was used outside render.\");\n return this.pass;\n }\n}\n\n/** Where a probe's scoped calls (a clip, a camera) land: a pass that draws nothing. */\nconst PROBE_PASS: RenderPass2D = new NullRenderContext();\n\nexport function internalsOf(ctx: RenderContext2D): RenderContextImpl {\n if (!(ctx instanceof RenderContextImpl)) throw new TypeError(\"Paint.draw takes the render context its render field was given.\");\n return ctx;\n}\n", "import type { Disposer } from \"@/assets/record\";\nimport type { AssetScope } from \"@/assets/scope\";\nimport { getPropertyMeta, property, type PropertyMeta } from \"@/attributes/properties/decorator\";\nimport type { FillResolved } from \"@/attributes/shape/fill/union\";\nimport type { ShadowResolved } from \"@/attributes/shape/shadow/shadow\";\nimport type { StrokeResolved } from \"@/attributes/shape/stroke/stroke\";\nimport { node } from \"@/document/node-decorator\";\nimport { declarePropEvolution } from \"@/document/prop-evolution\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport { settling, type Command, type CommandArgs } from \"@/tween/command\";\nimport { command, type CommandArg } from \"@/tween/command-decorator\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport type { ContextMap } from \"@/util/context\";\nimport type { ChildView, Loader, Provided, StateSpec } from \"@/components/factory/api\";\nimport { commandOf, makeTimeline } from \"@/components/factory/timeline\";\nimport { defOf, isTypeLike, type TypeDef } from \"@/components/factory/type-def\";\nimport { nodeOfView, nodeView, snapshot, stateView, stateViewPrototype, type ViewShape } from \"@/components/factory/views\";\n\n/**\n * What every factory does, whatever tree it builds for: declare the state on a\n * generated subclass of the tree's base, publish the commands, run the\n * `children` builder, provide and inherit context, and declare assets. Each\n * factory adds only its own tree's hooks on top.\n */\n\n/** The fields every factory takes. */\nexport interface CoreSpec {\n readonly key: string;\n readonly state?: StateSpec;\n readonly defaults?: Record<string, unknown>;\n readonly renamed?: Readonly<Record<string, string>>;\n readonly deprecated?: Readonly<Record<string, string>>;\n readonly migrate?: Readonly<Record<string, (value: unknown) => unknown>>;\n readonly commands?: Record<string, unknown>;\n readonly children?: (state: never) => unknown;\n readonly provide?: (state: never, inherited: <T>(context: { readonly id: symbol; readonly defaultValue: T }) => T) => readonly Provided[];\n readonly load?: (loader: Loader, state: never) => void;\n /** `[]` takes none; `null` (the default) anything of its tree; components, or `\"2d\"`/`\"3d\"`/`\"audio\"`, only those. */\n readonly allowedChildren?: readonly unknown[] | null;\n /** The components it goes only inside; unsaid, wherever its tree allows. */\n readonly allowedParents?: readonly unknown[];\n}\n\n/** A spec, resolved against the base it lowers onto. */\nexport interface Lowering {\n readonly spec: CoreSpec;\n readonly entries: Map<string, TypeDef>;\n readonly defaults: Record<string, unknown>;\n readonly builtIn: ReadonlyMap<string, PropertyMeta>;\n readonly view: ViewShape;\n /** Built-in entries whose default a factory applies itself (a 2D size), not by redeclaring the property. */\n readonly ownsDefault: ReadonlySet<string>;\n}\n\ntype NodeBase = abstract new (...args: any[]) => Node;\n\nexport function lowering(spec: CoreSpec, Base: NodeBase, ownsDefault: ReadonlySet<string> = new Set()): Lowering {\n const builtIn = new Map(getPropertyMeta(Object.create(Base.prototype as object)).map((m) => [m.key, m]));\n const entries = new Map<string, TypeDef>(Object.entries(spec.state ?? {}).map(([k, e]) => [k, defOf(e)]));\n const defaults = (spec.defaults ?? {}) as Record<string, unknown>;\n // A default for an own entry is that entry's default; for a built-in one, a redeclaration.\n for (const [key, value] of Object.entries(defaults)) {\n if (typeof value === \"function\") continue;\n const own = entries.get(key);\n if (own) entries.set(key, { ...own, default: value });\n else if (!builtIn.has(key)) throw new TypeError(`${spec.key}: \"defaults.${key}\" names no entry.`);\n }\n checkEvolution(spec, (key) => entries.has(key) || builtIn.has(key));\n // A reference entry holds an id; its fields read a view of the node it names.\n const references = new Set([...entries].filter(([, def]) => def.editor.kind === \"nodeRef\").map(([key]) => key));\n return { spec, entries, defaults, builtIn, view: stateViewPrototype([...builtIn.keys(), ...entries.keys()], references), ownsDefault };\n}\n\nexport function factoryDefault(def: TypeDef): unknown {\n return typeof def.default === \"function\" ? (def.default as () => unknown)() : def.default;\n}\n\n/** The members every generated node has, whatever its tree. */\nexport interface ComponentNode extends Node {\n _view: object;\n /** How many nodes the `children` builder made. */\n _built: number;\n _commandChildren(): readonly ChildView[];\n _animate(frame: (t: number) => Record<string, unknown>, duration: number, easing: unknown): unknown;\n}\n\n/** The base every tree's generated class extends: `Base` with the spec's state, context, assets and children. */\nexport function componentBase<T extends NodeBase>(Base: T, l: Lowering): T & (abstract new (...args: any[]) => ComponentNode) {\n const { spec: s, entries, defaults } = l;\n\n abstract class Componentized extends (Base as unknown as abstract new (...args: any[]) => Node) implements Partial<ComponentNode> {\n declare _view: object;\n declare _built: number;\n declare _assembling: boolean;\n declare _provided: { parent: ContextMap; values: readonly Provided[]; map: ContextMap } | undefined;\n\n constructor(...args: any[]) {\n const props = args[0] as Record<string, unknown> | undefined;\n const given = s.children ? props?.children : undefined;\n super(s.children && props ? { ...props, children: undefined } : props);\n this._view = stateView(l.view, this);\n this._built = 0;\n\n for (const [key, def] of entries) {\n if (def.private) this.applyProp(key, factoryDefault(def), { mapper: def.mapper, tween: def.tween });\n else if (typeof def.default === \"function\" && props?.[key] === undefined) this._writeProp(key, factoryDefault(def));\n }\n let built: Readonly<Record<string, unknown>> | undefined;\n for (const [key, value] of Object.entries(defaults)) {\n if (typeof value === \"function\" && props?.[key] === undefined) {\n const asBuilt = (built ??= Object.freeze({ ...props }));\n this._writeProp(key, () => (value as (state: object, given: object) => unknown)(this._view, asBuilt));\n }\n }\n\n if (s.children) {\n // Live, like the field state, so a binding the builder writes reads the node as it changes.\n const builderState = stateView(l.view, this);\n const authored = [given ?? []].flat(Infinity).filter(Boolean);\n if (s.allowedChildren != null) for (const child of authored) this.assertAcceptsChild(child as Node);\n Object.defineProperty(builderState, \"children\", { value: authored });\n const built = [s.children(builderState as never)].flat(Infinity).filter(Boolean) as Node[];\n this._assembling = true;\n try {\n for (const part of built) this.add(part);\n } finally {\n this._assembling = false;\n }\n this._built = built.length;\n }\n }\n\n /** Each entry the author left unset that inherits takes what its ancestors provide, once, on first attach. */\n protected override resolveContext(ctx: ContextMap): void {\n super.resolveContext(ctx);\n const given = (this._props ?? {}) as Record<string, unknown>;\n const self = this as unknown as Record<string, unknown>;\n for (const [key, def] of entries) {\n if (!def.inherit || given[key] !== undefined) continue;\n const value = def.inherit((context) => ctx.get(context), given);\n if (value !== undefined) self[key] = value;\n }\n }\n\n protected override provideContext(parent: ContextMap): ContextMap {\n if (!s.provide) return super.provideContext(parent);\n const provided = s.provide(this._view as never, (context) => parent.get(context as never));\n // The same map while nothing changed, so the subtree isn't re-bound every attach.\n const memo = this._provided;\n if (memo && memo.parent === parent && memo.values.length === provided.length\n && memo.values.every((p, i) => p.context === provided[i].context && p.value === provided[i].value)) return memo.map;\n let map = parent;\n for (const { context, value } of provided) if (map.get(context) !== value) map = map.with(context, value);\n this._provided = { parent, values: provided, map };\n return map;\n }\n\n override declareAssets(assets: AssetScope): void {\n super.declareAssets(assets);\n const self = this as unknown as Record<string, unknown>;\n for (const [key, def] of entries) declareEntry(assets, def.editor.kind ?? \"\", self[key]);\n if (s.load) s.load(loaderOf(assets), this._view as never);\n }\n\n protected override acceptsChild(child: Node): boolean {\n const allowed = s.allowedChildren;\n if (allowed === undefined || allowed === null || (this._assembling && allowed.length === 0)) return super.acceptsChild(child);\n return allowed.some((rule) => matches(child, rule));\n }\n\n protected override _childRule(): string {\n const allowed = s.allowedChildren;\n if (!allowed) return super._childRule();\n return allowed.length === 0 ? \"It takes no children.\" : `It takes only ${namesOf(allowed)}.`;\n }\n\n override _parentRefusal(parent: Node): string | null {\n const allowed = s.allowedParents;\n if (!allowed || allowed.some((rule) => matches(parent, rule))) return null;\n return `${this.className} goes only inside ${namesOf(allowed)}, not ${parent.className}.`;\n }\n\n /** The children a command's builders see: none, unless the tree says which. */\n _commandChildren(): readonly ChildView[] {\n return [];\n }\n\n _animate(frame: (t: number) => Record<string, unknown>, duration: number, easing: unknown) {\n return this.command(frame, duration, easing as EasingFunction | undefined);\n }\n }\n return Componentized as unknown as T & (abstract new (...args: any[]) => ComponentNode);\n}\n\ntype CommandFn = (timeline: unknown, state: unknown, children: unknown) => never;\n\n/**\n * Declare the state and commands on the generated class, register its key, and\n * hand back the component value.\n */\nexport function finishComponent(Generated: abstract new (...args: any[]) => Node, l: Lowering): object {\n const { spec: s, entries, defaults, builtIn } = l;\n Object.defineProperty(Generated, \"name\", { value: pascal(s.key) });\n const proto = Generated.prototype as unknown as Record<string, unknown>;\n // A node is a context provider by overriding these: only one that provides, or inherits, keeps them.\n if (!s.provide) deleteUpTo(proto, \"provideContext\");\n if (![...entries.values()].some((def) => def.inherit)) deleteUpTo(proto, \"resolveContext\");\n if (s.allowedChildren === undefined || s.allowedChildren === null) {\n deleteUpTo(proto, \"acceptsChild\");\n deleteUpTo(proto, \"_childRule\");\n }\n if (!s.allowedParents) deleteUpTo(proto, \"_parentRefusal\");\n const allowed = s.allowedChildren;\n if (allowed) {\n const trees = [...new Set(allowed.map((rule) => (typeof rule === \"string\"\n ? rule\n : (Object.create((rule as { node: { prototype: object } }).node.prototype) as Node).dimension)))];\n Object.defineProperty(proto, \"_childTrees\", { get: () => trees, configurable: true });\n }\n\n for (const [key, def] of entries) {\n if (def.private) continue;\n property({ default: typeof def.default === \"function\" ? undefined : def.default, mapper: def.mapper, tween: def.tween, ...def.editor })(proto, key);\n }\n for (const [key, value] of Object.entries(defaults)) {\n if (entries.has(key) || l.ownsDefault.has(key) || typeof value === \"function\") continue;\n const inherited = builtIn.get(key)!;\n property({ default: value, mapper: inherited.options?.mapper, tween: inherited.options?.tween, ...inherited.editor })(proto, key);\n }\n\n const base = Object.getPrototypeOf(Object.getPrototypeOf(proto)) as object;\n for (const [key, entry] of Object.entries(s.commands ?? {})) {\n // Commands have their own namespace: a key a node already uses (`remove`, `to`) publishes through another method name.\n const method = key in base ? `_command_${key}` : key;\n let args: CommandArg[] | undefined;\n const entrance = typeof entry === \"object\" && (entry as { entrance?: boolean }).entrance === true;\n if (typeof entry === \"function\") {\n proto[method] = function (this: ComponentNode, cmd: CommandArgs & { duration?: number } = {}): Command<Record<string, unknown>> {\n const duration = cmd.duration ?? 0;\n const timeline = makeTimeline({}, duration, cmd.easing, nodeView(this, this));\n const piece = (entry as CommandFn)(timeline, snapshot(this._view), this._commandChildren());\n return commandOf(this as never, piece, duration, cmd.easing);\n };\n } else {\n const { args: declared, run, easing: ownEasing } = entry as { args: readonly string[] | StateSpec; run?: CommandFn; easing?: EasingFunction };\n if (Array.isArray(declared)) {\n const names = declared as readonly string[];\n for (const name of names) {\n if (!entries.has(name) && !builtIn.has(name)) throw new TypeError(`${s.key}.${key}: args names \"${name}\", which is no entry.`);\n }\n // Each arg is its entry: what a host shows for it is what the entry means.\n args = names.map((name) => ({ key: name, ...(entries.get(name)?.editor ?? builtIn.get(name)?.editor ?? {}) }));\n proto[method] = function (this: Node, cmd: CommandArgs & { duration?: number } = {}) {\n const data = argsRecord(cmd.data, names);\n const stated: Record<string, unknown> = {};\n for (const name of names) if (data[name] !== undefined) stated[name] = data[name];\n return settling(this.to({ data: stated as never, duration: cmd.duration ?? 0, easing: cmd.easing ?? ownEasing }));\n };\n } else {\n const own = declared as StateSpec;\n args = Object.entries(own).map(([k, e]) => {\n const def = defOf(e);\n return { key: k, default: isTypeLike(e) ? factoryDefault(def) : e, ...def.editor };\n });\n proto[method] = function (this: ComponentNode, cmd: CommandArgs & { duration?: number } = {}) {\n const duration = cmd.duration ?? 0;\n const easing = cmd.easing ?? ownEasing;\n const timeline = makeTimeline(resolveArgs(own, cmd.data), duration, easing, nodeView(this, this));\n const piece = run!(timeline, snapshot(this._view), this._commandChildren());\n return commandOf(this as never, piece, duration, easing);\n };\n }\n }\n command({ key, ...(args ? { args } : {}), ...(entrance ? { entrance } : {}) })(proto, method);\n }\n\n if (s.renamed || s.deprecated || s.migrate) {\n declarePropEvolution(Generated, { renamed: s.renamed ?? {}, deprecated: s.deprecated ?? {}, migrate: s.migrate ?? {} });\n }\n node({ key: s.key })(Generated as never);\n return componentValue(s.key, Generated as unknown as new (props?: Record<string, unknown>) => object);\n}\n\n/** A rename lands on an entry from a key that is none; a deprecation and a hook name what is there to evolve. */\nfunction checkEvolution(spec: CoreSpec, isEntry: (key: string) => boolean): void {\n for (const [from, to] of Object.entries(spec.renamed ?? {})) {\n if (isEntry(from)) throw new TypeError(`${spec.key}: \"renamed.${from}\" is still an entry; a renamed key must be gone.`);\n if (!isEntry(to)) throw new TypeError(`${spec.key}: \"renamed.${from}\" names \"${to}\", which is no entry.`);\n }\n for (const key of Object.keys(spec.deprecated ?? {})) {\n if (!isEntry(key)) throw new TypeError(`${spec.key}: \"deprecated.${key}\" names no entry.`);\n }\n for (const key of Object.keys(spec.migrate ?? {})) {\n if (!isEntry(key) && !Object.hasOwn(spec.renamed ?? {}, key)) {\n throw new TypeError(`${spec.key}: \"migrate.${key}\" names neither an entry nor a renamed key.`);\n }\n }\n}\n\n/** Remove the generated override of `name`, wherever between the class and its base it sits. */\nfunction deleteUpTo(proto: Record<string, unknown>, name: string): void {\n for (let at: Record<string, unknown> | null = proto; at; at = Object.getPrototypeOf(at) as Record<string, unknown> | null) {\n if (Object.prototype.hasOwnProperty.call(at, name)) {\n delete at[name];\n return;\n }\n }\n}\n\n/**\n * What a factory hands back: call it (`Rect({...})`) or `new` it, either way a\n * node of the generated class, which is also what `instanceof` tests.\n */\nexport function componentValue(key: string, Generated: new (props?: Record<string, unknown>) => object): object {\n const make = function (props?: object) {\n return new Generated(props as Record<string, unknown>);\n };\n make.prototype = Generated.prototype;\n Object.defineProperty(make, \"name\", { value: Generated.name });\n return Object.assign(make, {\n key,\n node: Generated,\n is: (child: unknown) => nodeOfView(child as never) instanceof Generated,\n });\n}\n\nfunction pascal(key: string): string {\n return key.replace(/(^|[-_ ])(\\w)/g, (_, _sep, c: string) => c.toUpperCase());\n}\n\n/** Whether `node` is of `rule`: a component, or a whole tree by name. */\nfunction matches(node: Node, rule: unknown): boolean {\n return typeof rule === \"string\"\n ? node.dimension === rule\n : node instanceof (rule as { node: abstract new (...args: never[]) => unknown }).node;\n}\n\nfunction namesOf(rules: readonly unknown[]): string {\n const names = rules.map((rule) => (typeof rule === \"string\" ? `any ${rule.toUpperCase()} node` : (rule as { node: { name: string } }).node.name));\n return names.length === 1 ? names[0] : `${names.slice(0, -1).join(\", \")} or ${names.at(-1)}`;\n}\n\n/** One document arg: the bare value from a paint command, or the args record from the registry. */\nfunction argsRecord(data: unknown, names: readonly string[]): Record<string, unknown> {\n if (names.length === 1) {\n const plain = typeof data === \"object\" && data !== null && !Array.isArray(data) && Object.getPrototypeOf(data) === Object.prototype;\n if (!(plain && names[0] in (data as object))) return { [names[0]]: data };\n }\n return (data ?? {}) as Record<string, unknown>;\n}\n\nfunction resolveArgs(spec: StateSpec, data: unknown): Record<string, unknown> {\n const given = (data ?? {}) as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const key in spec) {\n const def = defOf(spec[key]);\n const value = given[key] === undefined ? factoryDefault(def) : given[key];\n out[key] = def.mapper ? def.mapper(value) : value;\n }\n return out;\n}\n\nfunction declareEntry(assets: AssetScope, kind: string, value: unknown): void {\n if (value === undefined || value === null || value === \"\") return;\n switch (kind) {\n case \"fills\": return assets.fill(value as FillResolved[]);\n case \"strokes\": for (const stroke of value as StrokeResolved[]) assets.fill(stroke.fill); return;\n case \"shadows\": for (const shadow of value as ShadowResolved[]) assets.fill(shadow.fill); return;\n case \"image\": return assets.image(value as string);\n case \"video\": return assets.video(value as string);\n case \"font\": return assets.font(value as string);\n }\n}\n\n/** One wrapper per load function: the scope warns when a key's second declaration hands it a different one. */\nconst tasks = new WeakMap<() => Promise<unknown>, () => Promise<void | Disposer>>();\n\nfunction taskOf(load: () => Promise<unknown>): () => Promise<void | Disposer> {\n let task = tasks.get(load);\n if (!task) {\n task = async () => {\n const loaded = await load();\n return typeof loaded === \"function\" ? (loaded as Disposer) : undefined;\n };\n tasks.set(load, task);\n }\n return task;\n}\n\nfunction loaderOf(assets: AssetScope): Loader {\n return {\n font: (family, weight) => assets.font(family, weight),\n image: (src) => assets.image(src),\n video: (src, trim) => assets.video(src, trim),\n task: (key, load, options) => assets.loader(key, taskOf(load), { gate: options?.before === \"layout\" ? \"layout\" : \"render\" }),\n fill: (fills) => assets.fill(fills),\n };\n}\n", "import { Node2D } from \"@/components/trees/2d/node2d\";\nimport { BoxBounds } from \"@/layout/bounds\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport { multiply, translation } from \"@/attributes/layout/matrix2d\";\nimport { worldAnchors } from \"@/components/trees/2d/node-transform\";\n\n/**\n * The ink extent of a node whose drawing is made **out of its children** rather\n * than out of a box of its own — a {@link BooleanGroup}, a {@link MaskGroup}.\n *\n * Both of those classes report their layout cell as their bounds by default,\n * and for both that cell is a fiction: nothing is drawn at its edges, nothing\n * is grabbable there, and it does not move when the parts inside it do. An\n * editor drawing a selection box around one is drawing a rectangle that has no\n * relationship to the pixels — which is exactly what {@link Node2D._localBounds}\n * exists to fix, and the reason it is a separate seam from `measure()`: the box\n * moves, the layout does not.\n *\n * ## Why an op decides the answer\n *\n * A bounding box is the one thing about a boolean result you *can* work out\n * without running the boolean. For a union it is even exact —\n * `bounds(A ∪ B) = bounds(A) ∪ bounds(B)` — and the same union is the honest\n * answer for `exclude`, whose result is a subset of it and whose parts are all\n * still there to be seen. The other two shrink instead: subtracting can only\n * ever cut into the first child, and an intersection lives inside every child\n * at once. So each mode below states which of those it is, and the result is a\n * *superset* of the true silhouette for `subtract`/`intersect` and exact for\n * the other two — never a box the drawing spills out of, which is the failure\n * that would matter.\n *\n * ## Why this composes with a resize that scales the children\n *\n * An editor can resize one of these nodes by scaling every child about the\n * corner the drag holds still, and that gesture is only\n * coherent if the box it is dragging follows the parts by the same factor. It\n * does, for all three modes: an axis-aligned scale about a point commutes with\n * union and intersection alike, so scaling every child by `k` scales the answer\n * here by exactly `k`. Neither half has to know about the other.\n */\nexport type ChildBoundsMode =\n /** Every child's ink, together — `union` and `exclude`. */\n | \"union\"\n /** The first child's ink alone — `subtract`'s base, and a mask's stencil. */\n | \"first\"\n /** Where every child's ink overlaps — `intersect`. */\n | \"intersect\";\n\n/** Min/max in the node's own local space, y-up, relative to its centre. */\ninterface Span {\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n}\n\n/**\n * The four corners of `child`'s ink, in its **parent's** local space (y-up,\n * relative to the parent's centre).\n *\n * The same two-step `nodeBox` makes: shift the child's matrix onto the ink's own\n * centre (the matrix is canvas y-down and the bounds are y-up, hence the sign),\n * then read the corners off it. That is what makes this correct for a child that\n * is rotated, scaled, or whose ink is off-centre.\n */\nfunction inkCorners(child: Node2D): Vector2[] {\n const b = child._localBounds();\n const local = child._localMatrix();\n const m =\n b.x === 0 && b.y === 0 ? local : multiply(local, translation(b.x, -b.y));\n const a = worldAnchors(m, b.width / 2, b.height / 2);\n return [a.topLeft, a.topRight, a.bottomRight, a.bottomLeft];\n}\n\n/** The axis-aligned span of a point set, or `null` for an empty one. */\nfunction spanOf(points: Vector2[]): Span | null {\n if (points.length === 0) return null;\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const p of points) {\n if (p.x < minX) minX = p.x;\n if (p.x > maxX) maxX = p.x;\n if (p.y < minY) minY = p.y;\n if (p.y > maxY) maxY = p.y;\n }\n return { minX, minY, maxX, maxY };\n}\n\nfunction toBounds(span: Span): BoxBounds {\n return {\n x: (span.minX + span.maxX) / 2,\n y: (span.minY + span.maxY) / 2,\n width: span.maxX - span.minX,\n height: span.maxY - span.minY,\n };\n}\n\n/**\n * The extent of `node`'s children's ink in `node`'s own local space, or `null`\n * when there is nothing to measure — no children, or an `intersect` whose parts\n * don't overlap at all.\n *\n * `null` is the caller's cue to keep the layout cell: a node with no children\n * has nothing else to offer, and an empty intersection draws nothing anywhere,\n * so a box round the parts would be a box round a shape that isn't there. The\n * cell at least stays in one place and stays grabbable, which is what a node you\n * need to put another child into has to be.\n */\nexport function childInkBounds(\n node: Node2D,\n mode: ChildBoundsMode\n): BoxBounds | null {\n const children = node.children;\n if (children.length === 0) return null;\n\n if (mode === \"first\") {\n const span = spanOf(inkCorners(children[0]));\n return span ? toBounds(span) : null;\n }\n\n if (mode === \"union\") {\n const span = spanOf(children.flatMap(inkCorners));\n return span ? toBounds(span) : null;\n }\n\n let span: Span | null = null;\n for (const child of children) {\n const next = spanOf(inkCorners(child));\n if (!next) return null;\n span = span\n ? {\n minX: Math.max(span.minX, next.minX),\n minY: Math.max(span.minY, next.minY),\n maxX: Math.min(span.maxX, next.maxX),\n maxY: Math.min(span.maxY, next.maxY),\n }\n : next;\n // The parts have stopped overlapping — nothing is drawn, so there is no\n // box to draw. See the header.\n if (span.minX > span.maxX || span.minY > span.maxY) return null;\n }\n return span ? toBounds(span) : null;\n}\n", "import { sizeInputOps } from \"@/attributes/layout/size\";\nimport type { FlowMode } from \"@/layout/types\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport { getNodeDescriptor } from \"@/document/node-decorator\";\nimport type { BoxBounds } from \"@/layout/bounds\";\nimport type { SizeConstraints } from \"@/layout/constraints\";\nimport { flowOps } from \"@/layout/ops\";\nimport { Node2D, type ChildPlacement, type ChildPlane, type CameraScope, type NodeHandle } from \"@/components/trees/2d/node2d\";\nimport type { Clip } from \"@/render/clip\";\nimport { containsClip } from \"@/render/clip-contains\";\nimport type { Graphics2D } from \"@/render/graphics2d\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport type { RenderPass2D } from \"@/render/render-context2d\";\nimport type { Allowed, Box2DState, ChildView, Component, Element, LayoutBox, Merge, Placement2D, Spec2D, StateSpec } from \"@/components/factory/api\";\nimport { clipOf } from \"@/components/factory/clip-of\";\nimport { componentBase, finishComponent, lowering, type CoreSpec } from \"@/components/factory/factory\";\nimport {\n childView, MeasurerImpl, RenderContextImpl, setKeyLookup, withPass, takeDecided, type ComponentHost, type Composite,\n} from \"@/components/factory/views\";\nimport { childInkBounds } from \"@/components/trees/2d/group-bounds\";\nimport type { SpaceCamera } from \"@/attributes/layout/space3d\";\nimport { NO_PROJECTION_3D, type Projection3D } from \"@/attributes/layout/matrix2d\";\nimport type { ChildSpace3D } from \"@/components/trees/three/node3d\";\nimport type { Scene3D } from \"@/render3d/scene3d\";\n\n\nconst NO_INSETS = { left: 0, right: 0, top: 0, bottom: 0 };\nconst SIZE_KEYS = new Set([\"width\", \"height\"]);\n\nsetKeyLookup((n) => getNodeDescriptor(n.constructor as new () => object)?.key);\n\ntype AnySpec = Spec2D<string, any, any, any, any, any>;\n\nfunction slotOf(p: Placement2D): ChildPlacement | null {\n if (p.rotation === undefined && p.scale === undefined && p.opacity === undefined\n && p.depth === undefined && p.rotationX === undefined && p.rotationY === undefined) return null;\n return {\n rotation: p.rotation ?? 0, scale: p.scale ?? 1, opacity: p.opacity ?? 1,\n depth: p.depth ?? 0, rotationX: p.rotationX ?? 0, rotationY: p.rotationY ?? 0,\n };\n}\n\n/**\n * A 2D component: laid out in a box, drawn with `Graphics2D`. Lowers the spec\n * onto a generated `Node2D` subclass, so a registry, a document and a host see\n * an ordinary node type.\n */\nexport function component2d<\n const K extends string,\n const S extends StateSpec = {},\n const C = {},\n const A extends Allowed = null,\n const B extends Element = never,\n>(spec: Spec2D<K, Merge<Box2DState, S>, S, C, A, B>): Component<K, Merge<Box2DState, S>, C, A> {\n const s = spec as unknown as AnySpec;\n const l = lowering(s as unknown as CoreSpec, Node2D, SIZE_KEYS);\n const { defaults } = l;\n const flows = l.entries.has(\"flow\");\n\n class Generated extends componentBase(Node2D, l) implements ComponentHost {\n _lastShape: Graphics2D | null = null;\n declare _measurer: MeasurerImpl;\n declare _ctx: RenderContextImpl;\n declare _probe: RenderContextImpl | undefined;\n declare _record: Composite | null | undefined;\n declare _slots: Map<Node2D, ChildPlacement> | null;\n declare _planes: Map<Node2D, ChildPlane> | null;\n declare _box: LayoutBox | null;\n\n constructor(props?: Record<string, unknown>) {\n super(props);\n this._measurer = new MeasurerImpl(this);\n this._ctx = new RenderContextImpl(this);\n this._slots = null;\n this._planes = null;\n this._box = null;\n // A node made of other nodes hugs them, unless told otherwise; `flex` already said fill.\n if (this._built > 0 && props?.flex === undefined) {\n for (const axis of SIZE_KEYS) {\n if (props?.[axis] === undefined && defaults[axis] === undefined) this.applyProp(axis, \"hug\", { tween: sizeInputOps.lerp });\n }\n }\n }\n\n /**\n * Hug what it was given, fill when given nothing, and fill a main axis a\n * child fills, so a hugging parent doesn't leave that child no room: the\n * rule shapes have today. A `defaults` size replaces it.\n */\n protected override applyDefaultSize(props?: Record<string, unknown>): void {\n const given = Node2D.flowChildrenProp(props);\n const flow = (props?.flow as FlowMode | undefined) ?? \"freeform\";\n // A flow container fills where a child fills, as shapes do; anything else hugs or fills, as `Node2D` does.\n const main = flows\n ? { width: flow !== \"vertical\", height: flow === \"vertical\" || flow === \"freeform\" }\n : { width: false, height: false };\n for (const axis of [\"width\", \"height\"] as const) {\n if (props?.[axis] !== undefined) continue;\n const declared = defaults[axis];\n const value = declared !== undefined && typeof declared !== \"function\" ? declared\n : given.length === 0 || (main[axis] && Node2D.hasFillChild(given, axis)) ? \"fill\" : \"hug\";\n this.applyProp(axis, value, { tween: sizeInputOps.lerp });\n }\n }\n\n override measure(constraints: SizeConstraints, scope: MeasureContext2D) {\n if (!s.measure) return super.measure(constraints, scope);\n this.lastMeasure = { constraints, measurer: scope };\n const m = this._measurer;\n m.max = { width: constraints.maxWidth, height: constraints.maxHeight };\n m.scope = scope;\n const natural = withPass(this, scope, m.max, () => s.measure!(m, this._view as never, this.flowChildren().map(childView) as never));\n // An engine module may have sized the node itself (text reports its own height even when it fills).\n if (takeDecided(this)) return natural;\n // The engine applies width and height: `hug` keeps the natural size, a number or `fill` replaces it.\n return flowOps.size(this, constraints, NO_INSETS, natural);\n }\n\n protected override layoutChildren(rect: BoxBounds, scope: MeasureContext2D): void {\n if (!s.layout) return super.layoutChildren(rect, scope);\n const children = this.flowChildren();\n const box: LayoutBox = { x: 0, y: 0, width: rect.width, height: rect.height, time: this.time };\n this._box = box;\n // A layout that places children by `Flow` records where a new one would go; any other leaves none.\n this._childSpace = null;\n const placements = withPass(this, scope, { width: rect.width, height: rect.height },\n () => s.layout!(box, this._view as never, children.map(childView) as never));\n let slots: Map<Node2D, ChildPlacement> | null = null;\n let planes: Map<Node2D, ChildPlane> | null = null;\n placements.forEach((p, i) => {\n const child = children[i];\n if (!child) return;\n child.layout({ x: p.x, y: 0 - p.y, width: p.width, height: p.height }, scope);\n const slot = slotOf(p);\n if (slot) (slots ??= new Map()).set(child, slot);\n if (p.plane) (planes ??= new Map()).set(child, p.plane);\n });\n this._slots = slots;\n this._planes = planes;\n }\n\n override _placementOf(child: Node2D): ChildPlacement | null {\n return this._slots?.get(child) ?? super._placementOf(child);\n }\n\n override _planeOf(child: Node2D | null): ChildPlane | null {\n if (child) return this._planes?.get(child) ?? null;\n const box = this._box ?? { x: 0, y: 0, width: this.layoutBounds?.width ?? 0, height: this.layoutBounds?.height ?? 0, time: this.time };\n return s.plane ? s.plane(box, this._view as never) : null;\n }\n\n protected override renderContent(pass: RenderPass2D): void {\n if (!s.render) return super.renderContent(pass);\n this.applyTransform(pass);\n const frame = this._spaceFrame;\n // Edge-on or behind the lens: nothing of its own to draw, but its children have frames of their own.\n if (frame && !frame.paints) {\n this.renderChildren(pass);\n return;\n }\n const ctx = this._ctx;\n ctx.pass = pass;\n ctx.cut = frame?.nearCut ?? null;\n ctx.composite = null;\n try {\n this.renderContentWithEffects(pass, () => s.render!(ctx, this._view as never));\n } finally {\n ctx.pass = null;\n ctx.cut = null;\n // A render that stopped compositing clears the record; one that composites set it as it went.\n this._record = ctx.composite;\n }\n }\n\n /** The outline `render` paints now, found by running it with nothing drawn: picking and backdrop effects read it. */\n protected override clipSelf(): Clip | null {\n this._probeRender();\n return this._lastShape ? clipOf(this._lastShape) : null;\n }\n\n // What `render` does with the children, read from its last run: these are asked every frame,\n // so they never re-run it. Before its first frame, one probe answers.\n\n /** A composite, or a camera, paints its children into its own plane: none of them stands in a space. */\n override _rendersChildrenInSpace(): boolean {\n const r = this._observed();\n return !(r?.bounds || r?.camera) && super._rendersChildrenInSpace();\n }\n\n override _localBounds(): BoxBounds {\n const bounds = this._observed()?.bounds;\n return (bounds && childInkBounds(this, bounds)) ?? super._localBounds();\n }\n\n override _cameraScope(): CameraScope | null {\n return this._observed()?.camera ?? super._cameraScope();\n }\n\n override _spaceCamera(): SpaceCamera | null {\n return this._observed()?.space ?? super._spaceCamera();\n }\n\n /** A space's root is the space's frame, not a plane tilted in it. */\n protected override _projection(): Projection3D {\n return this._observed()?.space ? NO_PROJECTION_3D : super._projection();\n }\n\n /** A render that builds a 3D scene views one: picking projects its 3D children through it. */\n _isViewport3D(): boolean {\n return this._observed()?.scene !== undefined;\n }\n\n /** The scene `render` builds now, built afresh. */\n _scene3D(): Scene3D | null {\n return this._probeRender()?.scene ?? null;\n }\n\n _observed(): Composite | null {\n if (this._record === undefined) this._probeRender();\n return this._record ?? null;\n }\n\n /** Run `render` drawing nothing: the outline it paints, and what it does with the children. */\n _probeRender(): Composite | null {\n if (!s.render) return (this._record = null);\n const probe = (this._probe ??= new RenderContextImpl(this, true));\n this._lastShape = null;\n probe.composite = null;\n s.render(probe, this._view as never);\n return (this._record = probe.composite);\n }\n\n protected override hitTestSelf(local: Vector2, tolerance: number): boolean {\n const clip = this.clipSelf();\n if (!clip || clip.isEmpty()) return super.hitTestSelf(local, tolerance);\n return containsClip(clip, local, tolerance);\n }\n\n _renderOwnChildren(pass: RenderPass2D): void {\n this.renderChildren(pass);\n }\n\n override _commandChildren(): readonly ChildView[] {\n return this.flowChildren().map(childView);\n }\n }\n\n const proto = Generated.prototype as unknown as Record<string, unknown>;\n if (s.handles) {\n const handles = Object.entries(s.handles);\n const sizeOf = (node: Node2D) => ({ width: node.layoutBounds?.width ?? 0, height: node.layoutBounds?.height ?? 0 });\n proto._handles = function (this: Generated): readonly NodeHandle[] {\n const out: NodeHandle[] = [];\n for (const [prop, handle] of handles) {\n const at = handle.at(this._view as never, sizeOf(this));\n if (at) out.push({ prop, at });\n }\n return out;\n };\n proto._handleValue = function (this: Generated, prop: string, at: Vector2): Vector2 | null {\n const handle = s.handles![prop];\n if (!handle) return null;\n return handle.value ? handle.value(at, this._view as never, sizeOf(this)) : { x: at.x, y: at.y };\n };\n }\n if (s.bounds) {\n const bounds = s.bounds;\n proto._localBounds = function (this: Generated): BoxBounds {\n return bounds({ width: this.layoutBounds?.width ?? 0, height: this.layoutBounds?.height ?? 0 }, this._view as never);\n };\n }\n if (s.space) {\n const space = s.space;\n // The coordinates its 3D children stand in: read where each child places itself, and by picking.\n (Generated.prototype as unknown as { _spaceOf: () => ChildSpace3D | null })._spaceOf = function (this: Generated) {\n return space(this._view as never);\n };\n }\n\n return finishComponent(Generated, l) as unknown as Component<K, Merge<Box2DState, S>, C, A>;\n}\n", "import { alignmentOps, type Alignment } from \"@/attributes/layout/alignment\";\nimport { insetsOps, type InsetsProps, type InsetsResolved } from \"@/attributes/layout/insets\";\nimport { sizeInputOps, type SizeInput } from \"@/attributes/layout/size\";\nimport { vector2Ops, type Vector2 } from \"@/attributes/layout/vector2\";\nimport type { PropertyEditor } from \"@/attributes/properties/decorator\";\nimport { cornerRadiusOps, type CornerRadiusResolved, type RectCornerRadius } from \"@/attributes/shape/corners/corner-radius\";\nimport { cornerStyleOps, type CornerStyleResolved, type RectCornerStyle } from \"@/attributes/shape/corners/corner-style\";\nimport { effectsOps, type Effect } from \"@/attributes/shape/effects/chain\";\nimport type { NodeEffect } from \"@/attributes/shape/effects/union\";\nimport type { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { Color, NormalizedColor } from \"@/attributes/shape/fill/color/parser\";\nimport { colorOps } from \"@/attributes/shape/fill/lerp\";\nimport { fillOps } from \"@/attributes/shape/fill/registry\";\nimport type { FillResolved } from \"@/attributes/shape/fill/union\";\nimport { pathOps } from \"@/attributes/shape/path/ops\";\nimport { shadowOps, type Shadow, type ShadowResolved } from \"@/attributes/shape/shadow/shadow\";\nimport { strokeOps, type Stroke, type StrokeResolved } from \"@/attributes/shape/stroke/stroke\";\nimport { textOps } from \"@/attributes/text/ops\";\nimport type { TweenFn } from \"@/props/host\";\nimport type { PathData } from \"@/render/descriptors/path\";\nimport type { AnyType, InOf, Inputs, NodeView, OutOf, StateSpec, Type, Values } from \"@/components/factory/api\";\nimport { defOf, type Inherit, type TypeDef } from \"@/components/factory/type-def\";\n\nexport interface EntryOptions {\n /** Not in documents or calls; only commands write it. A seek restores it like any entry. */\n readonly private?: boolean;\n /** `false`: `to` switches it rather than moving it. */\n readonly animatable?: boolean;\n /** Where it comes from when the author leaves it unset: what an ancestor provides. */\n readonly inherit?: Inherit;\n}\n\nexport interface NumberOptions extends EntryOptions {\n readonly min?: number;\n readonly max?: number;\n readonly step?: number;\n readonly unit?: string;\n /** Shown multiplied by this: `100` with `unit: \"%\"` for a 0–1 fraction. */\n readonly scale?: number;\n}\n\nexport interface TextOptions extends EntryOptions {\n /** `to` types the text out instead of switching at the end. */\n readonly typing?: boolean;\n /** It holds lines, not a label. */\n readonly multiline?: boolean;\n}\n\ntype PrivateOf<O> = O extends { readonly private: true } ? true : false;\n\n/** An attribute type: usable bare (`Types.fill`) or called with a default (`Types.fill('red')`). */\nexport interface Attribute<In, Out> extends Type<In, Out, false> {\n <const O extends EntryOptions = {}>(initial?: In, options?: EntryOptions & O): Type<In, Out, PrivateOf<O>>;\n}\n\nfunction make<In, Out, P extends boolean>(def: TypeDef): Type<In, Out, P> {\n return { _def: def } as Type<In, Out, P>;\n}\n\n/** The editor half of an options object: what the value means, never how an app shows it. */\nfunction meaning(kind: string, options: object | undefined, extra?: PropertyEditor): PropertyEditor {\n const { private: _private, typing: _typing, inherit: _inherit, ...rest } = (options ?? {}) as Record<string, unknown>;\n return { kind, ...extra, ...rest };\n}\n\nfunction attribute<In, Out>(\n kind: string, fallback: In, mapper?: (ext: any, prev?: any) => Out, tween?: TweenFn<Out>,\n): Attribute<In, Out> {\n const base: TypeDef = { default: fallback, mapper, tween, editor: { kind }, private: false };\n const call = <const O extends EntryOptions = {}>(initial?: In, options?: EntryOptions & O): Type<In, Out, PrivateOf<O>> =>\n make({ ...base, default: initial === undefined ? base.default : initial, editor: meaning(kind, options), private: options?.private === true, inherit: options?.inherit });\n return Object.assign(call, { _def: base }) as unknown as Attribute<In, Out>;\n}\n\nfunction defaultsOf(shape: StateSpec): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key in shape) out[key] = defOf(shape[key]).default;\n return out;\n}\n\n/**\n * What a state entry can be. Each lowers onto the `property` options of the\n * attribute it names, so a Type and a typed property are the same pair.\n */\nexport const Types = {\n number<const O extends NumberOptions = {}>(initial = 0, options?: NumberOptions & O): Type<number, number, PrivateOf<O>> {\n return make({ default: initial, editor: meaning(\"number\", options), private: options?.private === true, inherit: options?.inherit });\n },\n text<const O extends TextOptions = {}>(initial = \"\", options?: TextOptions & O): Type<string, string, PrivateOf<O>> {\n return make({ default: initial, tween: options?.typing ? textOps.lerp : undefined, editor: meaning(\"text\", options), private: options?.private === true, inherit: options?.inherit });\n },\n boolean<const O extends EntryOptions = {}>(initial = false, options?: EntryOptions & O): Type<boolean, boolean, PrivateOf<O>> {\n return make({ default: initial, editor: meaning(\"boolean\", options), private: options?.private === true, inherit: options?.inherit });\n },\n oneOf<const V extends readonly string[], const O extends EntryOptions = {}>(\n values: V, options?: EntryOptions & O & { readonly default?: V[number] },\n ): Type<V[number], V[number], PrivateOf<O>> {\n const { default: initial, ...rest } = options ?? ({} as O & { default?: V[number] });\n return make({ default: initial ?? values[0], editor: meaning(\"enum\", rest, { options: values }), private: options?.private === true, inherit: options?.inherit });\n },\n\n fill: attribute<Fill, FillResolved[]>(\"fills\", [], fillOps.resolve, fillOps.lerp),\n stroke: attribute<Stroke, StrokeResolved[]>(\"strokes\", [], strokeOps.resolve, strokeOps.lerp),\n shadow: attribute<Shadow, ShadowResolved[]>(\"shadows\", [], shadowOps.resolve, shadowOps.lerp),\n effects: attribute<Effect, NodeEffect[]>(\"effects\", [], effectsOps.resolve, effectsOps.lerp),\n color: attribute<Color, NormalizedColor>(\"color\", \"black\", colorOps.resolve, colorOps.lerp),\n cornerRadius: attribute<RectCornerRadius, CornerRadiusResolved>(\"cornerRadius\", 0, cornerRadiusOps.resolve, cornerRadiusOps.lerp),\n cornerStyle: attribute<RectCornerStyle, CornerStyleResolved>(\"cornerStyle\", \"rounded\", cornerStyleOps.resolve, cornerStyleOps.lerp),\n path: attribute<PathData, PathData>(\"path\", \"\", undefined, pathOps.lerp),\n insets: attribute<InsetsProps, InsetsResolved>(\"insets\", 0, insetsOps.resolve, insetsOps.lerp),\n alignment: attribute<Alignment, Vector2>(\"alignment\", \"center\", alignmentOps.resolve, alignmentOps.lerp),\n vector2: attribute<Vector2, Vector2>(\"vector2\", { x: 0, y: 0 }, undefined, vector2Ops.lerp),\n size: attribute<SizeInput, SizeInput>(\"size\", \"fill\", undefined, sizeInputOps.lerp),\n\n /** A point in the component's own frame: an editor can drag it. */\n point<const O extends EntryOptions = {}>(initial: Vector2 = { x: 0, y: 0 }, options?: EntryOptions & O): Type<Vector2, Vector2, PrivateOf<O>> {\n return make({ default: initial, tween: vector2Ops.lerp, editor: meaning(\"point\", options), private: options?.private === true, inherit: options?.inherit });\n },\n list<const T extends AnyType, const O extends EntryOptions = {}>(item: T, options?: EntryOptions & O): Type<InOf<T>[], OutOf<T>[], PrivateOf<O>> {\n return make({ default: () => [], editor: meaning(\"list\", options, { item: item._def.editor }), private: options?.private === true, inherit: options?.inherit });\n },\n object<const S extends StateSpec>(shape: S): Type<Inputs<S>, Values<S>> {\n return make({ default: () => defaultsOf(shape), editor: { kind: \"object\" }, private: false });\n },\n custom<In, Out = In, const O extends EntryOptions = {}>(initial: In, options?: EntryOptions & O & {\n readonly resolve?: (value: In) => Out;\n readonly lerp?: (from: Out, to: Out, t: number) => Out;\n /** What the value is, when a host can't tell from the default (`\"vector2\"`), and its parts. */\n readonly kind?: string;\n readonly properties?: PropertyEditor[\"properties\"];\n }): Type<In, Out, PrivateOf<O>> {\n const { resolve, lerp, private: _private, inherit: _inherit, ...rest } = options ?? ({} as NonNullable<typeof options>);\n // No kind of its own: a host reads one off the default, as for a bare `property`.\n return make({ default: initial, mapper: resolve, tween: lerp, editor: rest as PropertyEditor, private: options?.private === true, inherit: options?.inherit });\n },\n image: (src = \"\"): Type<string> => make({ default: src, editor: { kind: \"image\" }, private: false }),\n video: (src = \"\"): Type<string> => make({ default: src, editor: { kind: \"video\" }, private: false }),\n audio: (src = \"\"): Type<string> => make({ default: src, editor: { kind: \"audio\" }, private: false }),\n font: (family = \"\"): Type<string> => make({ default: family, editor: { kind: \"font\" }, private: false }),\n /** Another node, by id: a document holds the id, and a field reads a view of that node (or `null`). */\n nodeRef: (initial = \"\"): Type<string, NodeView | null> => make({ default: initial, editor: { kind: \"nodeRef\", animatable: false }, private: false }),\n /** A seed for deterministic randomness: procedural motion stays a function of time. */\n seed: (initial = 1): Type<number> => make({ default: initial, editor: { kind: \"seed\" }, private: false }),\n};\n", "import type { Size2D } from \"@/attributes/layout/size\";\nimport type { CornerRadiusResolved, RectCornerRadius } from \"@/attributes/shape/corners/corner-radius\";\nimport type { CornerStyleResolved, RectCornerStyle } from \"@/attributes/shape/corners/corner-style\";\nimport { Graphics2D } from \"@/render/graphics2d\";\nimport type { Values } from \"@/components/factory/api\";\nimport { Types, type Attribute } from \"@/components/factory/types\";\n\n// Typed out so the declarations name what the corners take by their own modules: a kit's emit reaches those through the sdk.\nexport const state: { cornerRadius: Attribute<RectCornerRadius, CornerRadiusResolved>; cornerStyle: Attribute<RectCornerStyle, CornerStyleResolved> } = {\n cornerRadius: Types.cornerRadius,\n cornerStyle: Types.cornerStyle,\n};\n\n/** A rectangle the size of the box, with these corners. */\nexport function rect(size: Size2D, s: Values<typeof state>): Graphics2D {\n return new Graphics2D().rect({ width: size.width, height: size.height, cornerRadius: s.cornerRadius, cornerStyle: s.cornerStyle });\n}\n", "import type { Alignment } from \"@/attributes/layout/alignment\";\nimport type { InsetsResolved } from \"@/attributes/layout/insets\";\nimport { insetsOps } from \"@/attributes/layout/insets\";\nimport type { Size2D } from \"@/attributes/layout/size\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { BoxBounds } from \"@/layout/bounds\";\nimport { flowOps } from \"@/layout/ops\";\nimport type { FlowMeasure, FlowMode, FlowResolved, FlowSettings, GapSize } from \"@/layout/types\";\nimport type { Node2D } from \"@/components/trees/2d/node2d\";\nimport type { ChildView, Measurer, Placement2D, Values } from \"@/components/factory/api\";\nimport { Types, type Attribute } from \"@/components/factory/types\";\nimport { currentPass, nodeOfView } from \"@/components/factory/views\";\n\n/** The Rect layout engine: freeform, runs, wrapped runs and grids. */\nexport const state = {\n flow: Types.custom<FlowMode, FlowResolved>(\"freeform\", { lerp: flowOps.lerp }),\n gap: Types.custom<GapSize>(0),\n wrap: false,\n crossGap: Types.custom<number | undefined>(undefined),\n columns: Types.number(1),\n // Typed out so the declarations name Alignment by its own module: a kit's emit reaches it through the sdk.\n align: Types.alignment as Attribute<Alignment, Vector2>,\n};\n\nexport type FlowState = Values<typeof state> & {\n readonly padding: InsetsResolved;\n readonly width: import(\"@/attributes/layout/size\").SizeInput;\n readonly height: import(\"@/attributes/layout/size\").SizeInput;\n};\n\nconst NO_CONTENT: Size2D = { width: 0, height: 0 };\n\n/** The measure a container took, kept for its layout in the same pass (as `Node2D` keeps its own). */\nconst pending = new WeakMap<Node2D, FlowMeasure<Node2D>>();\n\nfunction padded(s: FlowState, inset: InsetsResolved | undefined): InsetsResolved {\n const p = s.padding;\n if (!inset) return p;\n return { left: p.left + inset.left, right: p.right + inset.right, top: p.top + inset.top, bottom: p.bottom + inset.bottom };\n}\n\n/** `inset` is room the children must clear beyond `padding`: a stroke, say. */\nexport function measure(measurer: Measurer, s: FlowState, children: readonly ChildView<any>[], inset?: InsetsResolved): Size2D {\n const { node, scope } = currentPass();\n const padding = padded(s, inset);\n const constraints = { maxWidth: measurer.max.width, maxHeight: measurer.max.height };\n if (children.length === 0) {\n pending.delete(node);\n return flowOps.size(s, constraints, padding, NO_CONTENT);\n }\n const space = flowOps.contentBox(s, constraints, padding);\n const measured = flowOps.measure(s as FlowSettings, children.map(nodeOfView), space, scope);\n pending.set(node, measured);\n return flowOps.size(s, constraints, padding, measured.hug);\n}\n\nexport function layout(box: BoxBounds, s: FlowState, children: readonly ChildView<any>[], inset?: InsetsResolved): readonly Placement2D[] {\n const { node, scope } = currentPass();\n const kept = pending.get(node);\n pending.delete(node);\n const inner = insetsOps.insetBounds(box.width, box.height, padded(s, inset));\n // Where a child that is not here yet would land: a host dropping one in asks.\n node._childSpace = { settings: { flow: s.flow, align: s.align }, inner };\n if (children.length === 0) return [];\n const measured = kept && flowOps.reusable(kept, inner)\n ? kept\n : flowOps.measure(s as FlowSettings, children.map(nodeOfView), {\n width: inner.width, height: inner.height, hugWidth: s.width === \"hug\", hugHeight: s.height === \"hug\",\n }, scope);\n // `place` answers y-up from the content box's centre; a placement is y-up from the component's.\n return flowOps.place(measured, s as FlowSettings, inner).map((b) => ({\n x: inner.x + b.x, y: b.y - inner.y, width: b.width, height: b.height,\n }));\n}\n", "import type { CommandsSpec, Kids, Piece, StateSpec, Values } from \"@/components/factory/api\";\n\n/**\n * A command as a module exports it: checked against the module's own state\n * where it is written, then loose about the state it is run with, so it fits\n * any component that spreads the module's state in.\n */\ntype Portable<A> =\n A extends readonly unknown[] ? { readonly args: A; readonly run?: undefined }\n : unknown extends A ? (timeline: any, state: any, children: any) => Piece\n : { readonly args: A; run(timeline: any, state: any, children: any): Piece };\n\n/** A module's commands, typed against the state it exports. */\nexport function commandsFor<const S extends StateSpec, const C>(\n state: S,\n commands: CommandsSpec<C, S, Values<S>, Kids>,\n): { readonly [N in keyof C]: Portable<C[N]> } {\n return commands as never;\n}\n", "import type { InsetsResolved } from \"@/attributes/layout/insets\";\nimport type { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { FillResolved } from \"@/attributes/shape/fill/union\";\nimport type { ShadowResolved } from \"@/attributes/shape/shadow/shadow\";\nimport type { StrokeResolved } from \"@/attributes/shape/stroke/stroke\";\nimport type { GraphicsOp, Graphics2D } from \"@/render/graphics2d\";\nimport type { RenderContext2D, Values } from \"@/components/factory/api\";\nimport { clipOf } from \"@/components/factory/clip-of\";\nimport { commandsFor } from \"@/components/factory/commands-for\";\nimport { Types } from \"@/components/factory/types\";\nimport { internalsOf } from \"@/components/factory/views\";\n\nconst FRACTION = { min: 0, max: 1, step: 0.01, scale: 100, unit: \"%\" } as const;\n\n/** Fill, stroke and shadow for anything with a shape, and the commands that move them. */\nexport const state = {\n fill: Types.fill,\n stroke: Types.stroke,\n shadow: Types.shadow,\n overlay: Types.fill,\n start: Types.number(0, FRACTION),\n end: Types.number(1, FRACTION),\n};\n\nexport const commands = commandsFor(state, {\n fillTo: { args: [\"fill\"] },\n strokeTo: { args: [\"stroke\"] },\n shadowTo: { args: [\"shadow\"] },\n overlayTo: { args: [\"overlay\"] },\n progressTo: { args: [\"start\", \"end\"] },\n /** A stretch of the outline travels along it, and leaves it as it was. */\n flash: {\n args: { portion: Types.number(0.25, { ...FRACTION, min: 0.01 }) },\n run: (timeline, s) => {\n const rest = { start: s.start, end: s.end };\n const portion = Math.min(1, Math.max(0.01, timeline.args.portion));\n return timeline.animate((t) => {\n if (t <= 0 || t >= 1) return rest;\n const head = t * (1 + portion);\n return { start: Math.max(0, head - portion), end: Math.min(1, head) };\n });\n },\n },\n});\n\n/** What `draw` reads; a component that spreads `Paint.state` without `overlay` passes as it is. */\nexport type PaintState = Omit<Values<typeof state>, \"overlay\"> & { readonly overlay?: readonly FillResolved[]; readonly clip: boolean };\n\nexport interface DrawOptions {\n /** Paint with this instead of `state.fill` (a video frame under it, a 3D scene over it). */\n readonly fill?: Fill;\n /** Draw the children some other way (through a camera, in a space). Default: `ctx.children()`. */\n readonly children?: () => void;\n /**\n * What `clip` confines the children to and picking tests, when it isn't the\n * shape drawn: a path's box, or `null` for none (then picking takes the box).\n */\n readonly clipShape?: Graphics2D | null;\n /** Draw the overlay some other way (masked by a picture), from the trimmed shape. Default: the shape filled with `overlay`. */\n readonly overlay?: (base: Graphics2D) => Graphics2D | null;\n}\n\nconst TRIMMED = new Set<GraphicsOp[\"kind\"]>([\"rect\", \"ellipse\", \"path\", \"line\", \"polygon\", \"polygram\"]);\n\nfunction trimmed(shape: Graphics2D, start: number, end: number): Graphics2D {\n return shape._withOps(shape.ops().map((op) => (TRIMMED.has(op.kind)\n ? { ...op, state: { ...(op as { state: object }).state, start, end } } as GraphicsOp\n : op)));\n}\n\n/** A fresh copy to paint: a `Graphics2D` records into itself, and each paint needs the bare shape. */\nfunction copy(shape: Graphics2D): Graphics2D {\n return shape._withOps([...shape.ops()]);\n}\n\n/** A shadow is cast by the stroke when nothing visible fills the shape. */\nfunction castsShadowFromStroke(state: PaintState): boolean {\n if ((state.shadow as ShadowResolved[]).length === 0) return false;\n return !(state.fill as FillResolved[]).some((layer) => (layer.opacity ?? 1) > 0);\n}\n\n/**\n * Shadow and fill, then the children (clipped to the shape when `clip` is set),\n * then overlay and stroke, all trimmed by `start`/`end`: the paint order every\n * shape has, in one function.\n */\nexport function draw(ctx: RenderContext2D, s: PaintState, shape: Graphics2D | null, options: DrawOptions = {}): void {\n const c = internalsOf(ctx);\n const out = c.target();\n const confining = options.clipShape === undefined ? shape : options.clipShape;\n c.host._lastShape = confining;\n if (c.probing) {\n // Children drawn some other way may declare a camera or a space: the probe needs to see that.\n options.children?.();\n return;\n }\n const base = shape ? trimmed(shape, s.start, s.end) : null;\n\n c.inFront(() => {\n if (base) out.draw(copy(base).shadow(s.shadow).fill(options.fill ?? s.fill));\n });\n\n const outline = s.clip && confining ? clipOf(confining) : null;\n const clipped = outline !== null && !outline.isEmpty();\n if (clipped) out.beginClip(outline);\n if (options.children) options.children();\n else ctx.children();\n if (clipped) out.endClip();\n\n c.inFront(() => {\n if (!base) return;\n if (s.overlay && s.overlay.length > 0) {\n const overlay = options.overlay ? options.overlay(copy(base)) : copy(base).fill(s.overlay as FillResolved[]);\n if (overlay) out.draw(overlay);\n }\n const stroke = s.stroke as StrokeResolved[];\n if (stroke.length === 0) return;\n out.draw(castsShadowFromStroke(s) ? copy(base).shadow(s.shadow).stroke(stroke) : copy(base).stroke(stroke));\n });\n}\n\n/** How far the stroke reaches inside the shape, so children clear it. The widest stroke wins, not the sum. */\nexport function inset(s: Values<typeof state>): InsetsResolved {\n let extra = 0;\n for (const stroke of s.stroke as StrokeResolved[]) {\n const intrusion = stroke.weight * (1 - stroke.align) / 2;\n if (intrusion > extra) extra = intrusion;\n }\n return { left: extra, right: extra, top: extra, bottom: extra };\n}\n", "import type { Size2D } from \"@/attributes/layout/size\";\nimport type { CornerStyle } from \"@/attributes/shape/corners/corner-style\";\nimport { pathOps } from \"@/attributes/shape/path/ops\";\nimport { shapeOutlinePixels, type ShapeOutlineKind, type ShapeOutlineOptions } from \"@/components/builtins/geometry/shape-outline\";\nimport type { PathData } from \"@/render/descriptors/path\";\nimport { Graphics2D } from \"@/render/graphics2d\";\n\n/** Each outline a built-in shape paints, from its box and its own entries. `Paint.draw` trims and paints it. */\n\nexport function ellipse(size: Size2D, s: { readonly startAngle: number; readonly sweep: number; readonly ratio: number }): Graphics2D {\n return new Graphics2D().ellipse({ width: size.width, height: size.height, startAngle: s.startAngle, sweep: s.sweep, ratio: s.ratio });\n}\n\nexport interface PolygonShape {\n readonly sides: number;\n readonly cornerRadius: number;\n readonly cornerStyle: CornerStyle;\n}\n\nexport function polygon(size: Size2D, s: PolygonShape): Graphics2D {\n return new Graphics2D().polygon({ width: size.width, height: size.height, sides: s.sides, cornerRadius: s.cornerRadius, cornerStyle: s.cornerStyle });\n}\n\nexport function polygram(size: Size2D, s: PolygonShape & { readonly ratio: number }): Graphics2D {\n return new Graphics2D().polygram({\n width: size.width, height: size.height, sides: s.sides, ratio: s.ratio, cornerRadius: s.cornerRadius, cornerStyle: s.cornerStyle,\n });\n}\n\n/** The box, as a shape: what a path clips its children to. */\nexport function box(size: Size2D): Graphics2D {\n return new Graphics2D().rect({ x: 0, y: 0, width: size.width, height: size.height });\n}\n\n/** Path data in the unit space of the box (y up), drawn at the box's size. */\nexport function unitPath(size: Size2D, data: PathData): Graphics2D {\n const { width: w, height: h } = size;\n return new Graphics2D().path({\n data: pathOps.anchorCommands(pathOps.anchors(data), (p) => ({ x: p.x * w, y: -p.y * h })),\n centerBounds: [-w / 2, -h / 2, w / 2, h / 2],\n });\n}\n\n/** Path data at face value, centred on its own bounds. */\nexport function facePath(data: PathData): Graphics2D {\n const b = pathOps.bounds(data);\n return new Graphics2D().path({ data, centerBounds: b ? [b.minX, b.minY, b.maxX, b.maxY] : undefined });\n}\n\n/** A named outline (triangle, star, …) fitted to the box. */\nexport function outline(kind: ShapeOutlineKind, size: Size2D, options: Omit<ShapeOutlineOptions, \"width\" | \"height\">): Graphics2D {\n const { width: w, height: h } = size;\n return new Graphics2D().path({\n data: pathOps.anchorCommands(shapeOutlinePixels(kind, { ...options, width: w, height: h }), (p) => ({ x: p.x, y: -p.y })),\n centerBounds: [-w / 2, -h / 2, w / 2, h / 2],\n });\n}\n\n/** A rect's corners, to spread in (`...Shapes.corners`), and the rect they round. */\nexport { state as corners, rect } from \"@/components/modules/corners\";\n", "import { lerpVector2, type Vector2 } from \"@/attributes/layout/vector2\";\nimport { Node2D } from \"@/components/trees/2d/node2d\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport type { RenderContext2D, Values } from \"@/components/factory/api\";\nimport { commandsFor } from \"@/components/factory/commands-for\";\nimport { Types } from \"@/components/factory/types\";\nimport { internalsOf, nodeOfNodeView } from \"@/components/factory/views\";\n\n/** Where a 2D camera looks: a point, a zoom and a heading, or a node below it to follow. */\nexport const state = {\n zoom: Types.number(1, { min: 0.01, step: 0.1, unit: \"×\" }),\n lookAt: Types.custom<Vector2>({ x: 0, y: 0 }, { lerp: lerpVector2, kind: \"vector2\", properties: { x: { kind: \"number\" }, y: { kind: \"number\" } } }),\n heading: Types.number(0, { step: 1, unit: \"°\" }),\n follow: Types.nodeRef(),\n};\n\nexport const commands = commandsFor(state, {\n zoomTo: { args: [\"zoom\"] },\n panTo: { args: [\"lookAt\"] },\n headingTo: { args: [\"heading\"] },\n});\n\ntype AimState = Values<typeof state>;\n\n/** The point the camera centres on: `lookAt`, offset from the followed node when there is one below it. */\nexport function aim(ctx: RenderContext2D, s: AimState): Vector2 {\n const target = s.follow;\n if (!target) return s.lookAt;\n const node = nodeOfNodeView(target);\n if (!(node instanceof Node2D) || !within(node, internalsOf(ctx).host)) return s.lookAt;\n const at = target.frame;\n return { x: at.x + s.lookAt.x, y: at.y + s.lookAt.y };\n}\n\n/** The children, through this camera. */\nexport function camera(ctx: RenderContext2D, s: AimState): void {\n ctx.camera({ lookAt: aim(ctx, s), zoom: s.zoom, heading: s.heading });\n}\n\nfunction within(node: Node, ancestor: Node): boolean {\n for (let at = node.parent; at; at = at.parent) if (at === ancestor) return true;\n return false;\n}\n", "import type { FontStyle, TextAlign, TextDecoration, VerticalAlign } from \"@/attributes/text/types\";\nimport { FillResolved } from \"@/attributes/shape/fill/union\";\nimport { StrokeResolved } from \"@/attributes/shape/stroke/stroke\";\nimport { PathData } from \"./path\";\nimport { ShapeAlignmentInput, ShapeState, resolveShapeAlignment, resolveShapePivot, stripShapeAlignmentKeys } from \"./shape\";\nimport { hostTextFamily } from \"@/components/builtins/text/text-defaults\";\n\n/**\n * The size a segmented block's pieces shape at on an `'autofit'` node: the\n * size the layout probes with, since no single piece can be asked for the\n * size the block settles on.\n */\nexport const AUTOFIT_PROBE_SIZE = 100;\n\n/**\n * One contiguous piece of a Text node split at run boundaries. Pieces\n * carry their effective shaping inputs (`text` plus the five font fields) and\n * draw-time overrides applied per shaped run: `opacity` folded into the paint\n * alpha, an optional `fill`/`stroke` override (falls back to the node's when\n * omitted), and a transform applied about the run's centered position.\n *\n * Present only when a Text node has styled runs or a reveal window; otherwise\n * the node renders as a single string with no segments.\n *\n * **Every shaping field is stated, none inherited at draw time.** `fontFamily`,\n * `fontSize` and `fontStyle` joined `fontWeight` and `letterSpacing` here so a\n * run can change its *face* and not only its weight — which is\n * what an editor built on this needs to offer per-character styling at all. The\n * paragraph builder already takes all five per run (it is what `RichText` sets),\n * so the cost of the three is a wider segment and nothing else.\n *\n * They are optional only so an older caller's segments still lay out: absent\n * means \"the node's own\", resolved where the paragraph is built rather than\n * left for the renderer to guess.\n */\nexport interface TextSegment {\n text: string;\n /** Override family for this piece; falls back to the node's when undefined. */\n fontFamily?: string;\n /** Override size for this piece; falls back to the node's when undefined. */\n fontSize?: number;\n /** Override slant for this piece; falls back to the node's when undefined. */\n fontStyle?: FontStyle;\n fontWeight: number;\n letterSpacing: number;\n /** Override decoration for this piece; falls back to the node's when undefined. */\n textDecoration?: TextDecoration;\n opacity: number;\n x: number;\n y: number;\n scale: number;\n rotation: number;\n /** Override fill for this piece; falls back to the node's fill when undefined. */\n fill?: FillResolved[];\n /** Override stroke for this piece; falls back to the node's stroke when undefined. */\n stroke?: StrokeResolved[];\n}\n\n/**\n * Whether `segment` only *styles* its characters — no transform of its own.\n *\n * The caret model can describe a segmented block exactly as long as this holds\n * of every piece: differently-styled runs are still one paragraph, laid out and\n * measured together, so the shaper's own rects for each character are where the glyphs\n * are. A piece that is *moved*, turned or scaled about its own centre is not in\n * that paragraph's space any more, and a slot measured from it would point at\n * where the character would have been. See `textBlockLayout`, which is the one\n * caller and turns a false here into \"no caret model for this shape\".\n */\nexport function isStyleOnlySegment(segment: TextSegment): boolean {\n return segment.x === 0 && segment.y === 0\n && segment.scale === 1 && segment.rotation === 0;\n}\n\nexport interface TextState extends ShapeState {\n text: string;\n /**\n * A named typography preset to shape against — `theme.typography`'s key, the\n * same one a `Text` node's `variant` prop selects.\n *\n * A node reads its variant once, at bind; a drawn op has no bind step, so it\n * is resolved at draw alongside the inherited defaults (see\n * `applyGraphicsTextDefaults`). It sits *between* the two: above the\n * enclosing `<DefaultTextStyle>`, below anything the op states itself.\n *\n * Optional, and unresolved names are ignored rather than an error — a scene\n * that renames a preset should lose the styling, not fail to draw.\n */\n variant?: string;\n fontSize: number | 'autofit';\n fontFamily: string;\n fontWeight: number;\n fontStyle: FontStyle;\n letterSpacing: number;\n lineHeight: number;\n textAlign: TextAlign;\n /** Where the block sits in a box taller or shorter than it; only a `height` gives it one. */\n verticalAlign: VerticalAlign;\n textDecoration: TextDecoration;\n wrap: boolean;\n minFontSize: number;\n width: number;\n height: number;\n /**\n * Per-piece overrides when the node has styled runs. When set,\n * the renderer shapes these pieces together (one paragraph) and paints each\n * shaped run with its piece's overrides instead of the node's single fill.\n */\n segments?: TextSegment[];\n /**\n * When set, the text is wrapped around this path (text-on-path) instead of\n * laid out as straight lines: each glyph is positioned and rotated to follow\n * the path, centered on its baseline, and glyphs past the path end are\n * clipped. Mutually exclusive with `segments` in v1.\n */\n path?: PathData | null;\n}\n\n\n/**\n * The family this text is set in — the last rung of the cascade, and the only\n * one that can refuse.\n *\n * It used to fall back to `\"Arial\"`, which is the wrong shape of answer for a\n * renderer whose whole job is that the picture is the one that was asked for:\n * substituting a face the *engine* picked produces text in a typeface the author\n * never chose, at metrics they never measured, in a frame that looks finished,\n * and hides a font that was never declared and so never loaded.\n *\n * What it falls back to instead is {@link hostTextFamily} — a face the\n * **application** named, once, at its composition root, out of the fonts it\n * actually vendors. That is a different bargain: a host that ships a typeface\n * registers it in every manifest, so a chart axis that nobody styled comes out\n * in it and paints glyphs, while the engine still refuses to invent a face of\n * its own. A host that declares nothing gets the error below, which is the right\n * answer for a headless render whose fonts all come from a manifest.\n *\n * By the time an op reaches here the whole ladder above has been walked — the op\n * or prop itself, a `variant` preset, the enclosing `<DefaultTextStyle>`, then\n * the theme's `default` typography preset — so this is only ever reached when\n * every one of them was silent. The message names them because \"no font family\"\n * is not actionable and \"set one on the text, on a DefaultTextStyle, or as the\n * theme's default preset\" is.\n *\n * Exported so the **measure** path enforces the same policy from the same\n * definition. Shaping a paragraph to measure it happens before any op is\n * validated, and the shaper reads `.length` off every family name — so text with no\n * family used to die inside the wasm with `Cannot read properties of undefined`,\n * naming no scene, node or prop, while the identical case at draw time produced\n * the message above. One policy, two verdicts, and the useless one came first.\n */\nexport function requireFontFamily(descriptor: { fontFamily?: string; text?: string }): string {\n const family = descriptor.fontFamily;\n if (typeof family === \"string\" && family !== \"\") return family;\n const host = hostTextFamily();\n if (host !== \"\") return host;\n const text = descriptor.text ? ` drawing \"${descriptor.text.slice(0, 32)}\"` : \"\";\n throw new Error(\n `Text${text} has no fontFamily. Set one on the text itself, on an `\n + `enclosing <DefaultTextStyle>, or as the theme's \\`default\\` typography `\n + `preset — there is no fallback face.`,\n );\n}\n\nexport function withTextDescriptor(descriptor: Partial<TextState> & ShapeAlignmentInput): TextState {\n const width = descriptor.width ?? 0;\n const height = descriptor.height ?? 0;\n const { x, y, pivot } = resolveShapeAlignment(descriptor, width, height);\n return {\n ...stripShapeAlignmentKeys(descriptor),\n opacity: descriptor.opacity ?? 1,\n rotation: descriptor.rotation ?? 0,\n scale: descriptor.scale ?? 1,\n x,\n y,\n start: descriptor.start ?? 0,\n end: descriptor.end ?? 1,\n pivot: resolveShapePivot(pivot),\n text: descriptor.text ?? \"\",\n fontSize: descriptor.fontSize ?? 48,\n fontFamily: requireFontFamily(descriptor),\n fontWeight: descriptor.fontWeight ?? 400,\n fontStyle: descriptor.fontStyle ?? 'normal',\n letterSpacing: descriptor.letterSpacing ?? 0,\n lineHeight: descriptor.lineHeight ?? 0,\n textAlign: descriptor.textAlign ?? 'center',\n verticalAlign: descriptor.verticalAlign ?? 'center',\n textDecoration: descriptor.textDecoration ?? 'none',\n wrap: descriptor.wrap ?? false,\n minFontSize: descriptor.minFontSize ?? 12,\n width: descriptor.width ?? 0,\n height: descriptor.height ?? 0,\n segments: descriptor.segments,\n path: descriptor.path ?? null,\n };\n}\n", "import type { Size2D } from \"@/attributes/layout/size\";\nimport type { ShadowResolved } from \"@/attributes/shape/shadow/shadow\";\nimport type { StrokeResolved } from \"@/attributes/shape/stroke/stroke\";\nimport type { Node2D } from \"@/components/trees/2d/node2d\";\nimport {\n declareGlyphAssets, declareRichAssets, measureGlyphs, measureRich, richState, textState,\n type RichValues, type TextSource, type TextValues,\n} from \"@/components/builtins/text/text-layout\";\nimport type { TextState } from \"@/render/descriptors/text\";\nimport { Graphics2D } from \"@/render/graphics2d\";\nimport type { Loader, Measurer, RenderContext2D } from \"@/components/factory/api\";\nimport { currentPass, internalsOf, markDecided } from \"@/components/factory/views\";\n\n/**\n * Glyphs: measured, drawn and loaded by the shared functions in `components/builtins/text/text-layout.ts`.\n * `source` is where the string comes from: a `text` entry, a formatted number.\n */\n\nexport type { TextSource, TextValues, RichValues };\n\ntype Painted = { readonly shadow: unknown; readonly fill: unknown; readonly stroke: unknown };\n\n/** The block's own size, which a filling text still reports, so a hugging ancestor sees its content. */\nexport function measure(measurer: Measurer, s: TextValues, source: TextSource): Size2D {\n const { node, scope } = currentPass();\n markDecided(node);\n return measureGlyphs(s, source, { maxWidth: measurer.max.width, maxHeight: measurer.max.height }, scope);\n}\n\nconst drawn = new WeakMap<Node2D, { readonly s: TextValues; readonly source: TextSource }>();\n\n/** The glyphs, shadow and fill, then the children, then the stroke. A styled piece paints itself, so the node's own paint steps aside. */\nexport function draw(ctx: RenderContext2D, s: TextValues & Painted, source: TextSource): void {\n const c = internalsOf(ctx);\n drawn.set(c.host, { s, source });\n if (c.probing) return;\n const out = c.target();\n const state = textState(s, source, c.host.layoutBounds);\n const segmented = state.segments != null;\n c.inFront(() => {\n const g = new Graphics2D().text(state).shadow(s.shadow as ShadowResolved[]);\n if (!segmented) g.fill(s.fill as never);\n out.draw(g);\n });\n ctx.children();\n c.inFront(() => {\n const stroke = s.stroke as StrokeResolved[];\n if (stroke.length === 0 || segmented) return;\n out.draw(new Graphics2D().text(state).stroke(stroke));\n });\n}\n\nexport function load(loader: Loader, s: TextValues, source: TextSource): void {\n declareGlyphAssets(s, source, loader);\n}\n\n/** What a node drew its glyphs as, for a host's caret geometry. `null` for a node that draws none. */\nexport function textStateOf(node: Node2D): Partial<TextState> | null {\n const last = drawn.get(node);\n return last ? textState(last.s, last.source, node.layoutBounds) : null;\n}\n\nexport function measureRichText(measurer: Measurer, s: RichValues): Size2D {\n const { scope } = currentPass();\n return measureRich(s, { maxWidth: measurer.max.width, maxHeight: measurer.max.height }, scope);\n}\n\nexport function drawRichText(ctx: RenderContext2D, s: RichValues): void {\n const c = internalsOf(ctx);\n if (c.probing) return;\n const out = c.target();\n c.inFront(() => out.draw(new Graphics2D().richText(richState(s, c.host.layoutBounds))));\n ctx.children();\n}\n\nexport function loadRichText(loader: Loader, s: RichValues): void {\n declareRichAssets(s, loader);\n}\n", "import type { AssetScope } from \"@/assets/scope\";\nimport type { Size2D, SizeInput } from \"@/attributes/layout/size\";\nimport type { FillResolved } from \"@/attributes/shape/fill/union\";\nimport { pathOps } from \"@/attributes/shape/path/ops\";\nimport type { StrokeResolved } from \"@/attributes/shape/stroke/stroke\";\nimport { textOps } from \"@/attributes/text/ops\";\nimport type {\n FontStyle, ResolvedTextRun, ResolvedTextSpan, TextAlign, TextCase, TextDecoration, TextSpan, VerticalAlign,\n} from \"@/attributes/text/types\";\nimport type { RichTextState } from \"@/render/descriptors/richtext\";\nimport type { SizeConstraints } from \"@/layout/constraints\";\nimport type { PathData } from \"@/render/descriptors/path\";\nimport type { TextSegment, TextState } from \"@/render/descriptors/text\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport { AUTOFIT_PROBE_SIZE } from \"@/render/descriptors/text\";\n\n/**\n * Setting a string in a face: measuring the block, cutting it into styled\n * pieces, and the descriptor it draws as. Plain functions over resolved values,\n * behind the components' `TextLayout` module.\n */\n\n/** The shaping fields a glyph node reads, resolved. */\nexport interface TextValues {\n readonly fontFamily: string;\n readonly fontSize: number | \"autofit\";\n readonly fontWeight: number;\n readonly fontStyle: FontStyle;\n readonly letterSpacing: number;\n readonly lineHeight: number;\n readonly textAlign: TextAlign;\n readonly verticalAlign: VerticalAlign;\n readonly textDecoration: TextDecoration;\n readonly textCase: TextCase;\n readonly minFontSize: number;\n readonly fill: unknown;\n readonly stroke: unknown;\n readonly start: number;\n readonly end: number;\n readonly width: SizeInput;\n readonly height: SizeInput;\n}\n\n/** Where the string comes from, and what styles parts of it. */\nexport interface TextSource {\n readonly text: string;\n readonly wraps: boolean;\n /** The path the glyphs ride, for text-on-path. */\n readonly glyphPath: PathData | null;\n /** Stretches a document styles apart from the node: `Text`'s `runs`. */\n readonly runs: readonly ResolvedTextRun[];\n}\n\nexport function casedText(s: TextValues, src: TextSource): string {\n return textOps.applyCase(src.text, s.textCase);\n}\n\n/** The block's size: hugged to its glyphs, filled across, and its own height even when it fills, so a hugging ancestor sees its content. */\nexport function measureGlyphs(s: TextValues, src: TextSource, constraints: SizeConstraints, scope: MeasureContext2D): Size2D {\n // Text-on-path: the visual extent is the path's bounding box, not a text\n // line box. Size the node to the path (node-local coords, like Path).\n if (src.glyphPath != null) {\n const { width, height } = pathOps.size(src.glyphPath);\n const wm = s.width;\n const hm = s.height;\n return {\n width: typeof wm === \"number\" ? wm : wm === \"hug\" ? width : (constraints.maxWidth ?? width),\n height: typeof hm === \"number\" ? hm : hm === \"hug\" ? height : (constraints.maxHeight ?? height),\n };\n }\n\n const measureFontSize = s.fontSize === \"autofit\" ? 16 : s.fontSize;\n const paragraphs = casedText(s, src).split(\"\\n\");\n\n // A styled run changes the box, which is why measuring cannot read the\n // node's five font fields and stop there: one word set two sizes up makes\n // the line taller and the block wider. So when runs are styled the\n // intrinsic size is summed across the pieces, each in its own style.\n const styled = textSegments(s, src);\n const lineStyles = styled === null\n ? null\n : measureStyledLines(styled, {\n fontFamily: s.fontFamily,\n fontSize: measureFontSize,\n fontStyle: s.fontStyle,\n fontWeight: s.fontWeight,\n letterSpacing: s.letterSpacing,\n });\n\n const lineH = measureFontSize * s.lineHeight;\n const intrinsicW = lineStyles\n ? Math.max(...lineStyles.map(line => line.runs.reduce(\n (w, run) => w + scope.measureText(run.text, run.fontSize, run.fontFamily, run.fontWeight, run.letterSpacing, run.fontStyle).width,\n 0,\n )))\n : Math.max(...paragraphs.map(l => scope.measureText(l, measureFontSize, s.fontFamily, s.fontWeight, s.letterSpacing, s.fontStyle).width));\n\n const wm = s.width;\n const hm = s.height;\n const resolvedW = typeof wm === \"number\" ? wm : wm === \"hug\" ? intrinsicW : constraints.maxWidth ?? 0;\n\n // When wrap is on and the box has a finite width narrower than the text,\n // height needs to account for the extra lines produced by wrapping. Each\n // line is as tall as its tallest run.\n const wraps = src.wraps && resolvedW > 0;\n const lineSizes = lineStyles === null\n ? null\n : wraps\n ? wrappedLineSizes(lineStyles, resolvedW, scope)\n : lineStyles.map(line => Math.max(...line.runs.map(run => run.fontSize)));\n const intrinsicH = lineSizes\n ? lineSizes.reduce((h, size) => h + size * s.lineHeight, 0)\n : (wraps\n ? paragraphs.reduce((n, p) => n + countWrappedLines(p, resolvedW, measureFontSize, s.fontFamily, s.fontWeight, scope, s.letterSpacing, s.fontStyle), 0)\n : paragraphs.length) * lineH;\n\n return { width: resolvedW, height: typeof hm === \"number\" ? hm : intrinsicH };\n}\n\n/**\n * The string cut at every style boundary, each piece styled by the runs over\n * it, the later winning. Also folds in the Write On reveal window. `null` when neither is\n * active, so rendering keeps its single-op path; and always `null` on a path,\n * where the string is laid along it as one run.\n */\nexport function textSegments(s: TextValues, src: TextSource): TextSegment[] | null {\n if (src.glyphPath != null) return null;\n const runs = src.runs.filter(r => r.end > r.start);\n const text = casedText(s, src);\n if (text.length === 0) return null;\n\n // Write On: a glyph has no path to trim, so `start`/`end` are a\n // character-reveal window instead: opacity over a range of characters.\n const hasReveal = s.start > 0 || s.end < 1;\n if (runs.length === 0 && !hasReveal) return null;\n\n // A hard cut at whole characters, one at a time, the way DaVinci's Write On does.\n const revealStart = Math.round(s.start * text.length);\n const revealEnd = Math.round(s.end * text.length);\n\n // `'autofit'` settles on a size the block is measured into, which no single\n // piece can be asked for, so pieces shape at the probe size.\n const nodeFontSize = typeof s.fontSize === \"number\" ? s.fontSize : AUTOFIT_PROBE_SIZE;\n const fill = s.fill as FillResolved[];\n const stroke = s.stroke as StrokeResolved[];\n\n const cuts = new Set<number>([0, text.length]);\n for (const run of runs) { cuts.add(run.start); cuts.add(run.end); }\n if (hasReveal) {\n cuts.add(revealStart);\n cuts.add(revealEnd);\n }\n const points = [...cuts].filter(c => c >= 0 && c <= text.length).sort((a, b) => a - b);\n\n const segments: TextSegment[] = [];\n for (let i = 0; i < points.length - 1; i++) {\n const start = points[i];\n const end = points[i + 1];\n if (end <= start) continue;\n\n // Every shaping field is stated, so the paragraph builder and the caret\n // read a piece the same way.\n const seg: TextSegment = {\n text: text.slice(start, end),\n fontFamily: s.fontFamily,\n fontSize: nodeFontSize,\n fontStyle: s.fontStyle,\n fontWeight: s.fontWeight,\n letterSpacing: s.letterSpacing,\n textDecoration: s.textDecoration,\n opacity: 1,\n x: 0,\n y: 0,\n scale: 1,\n rotation: 0,\n fill,\n stroke,\n };\n\n for (const run of runs) {\n if (start < run.start || end > run.end) continue;\n if (run.fontFamily !== undefined) seg.fontFamily = run.fontFamily;\n if (run.fontSize !== undefined) seg.fontSize = run.fontSize;\n if (run.fontStyle !== undefined) seg.fontStyle = run.fontStyle;\n if (run.fontWeight !== undefined) seg.fontWeight = run.fontWeight;\n if (run.letterSpacing !== undefined) seg.letterSpacing = run.letterSpacing;\n if (run.textDecoration !== undefined) seg.textDecoration = run.textDecoration;\n if (run.fill !== undefined) seg.fill = run.fill;\n if (run.stroke !== undefined) seg.stroke = run.stroke;\n }\n\n if (hasReveal && !(start >= revealStart && end <= revealEnd)) seg.opacity = 0;\n segments.push(seg);\n }\n return segments;\n}\n\n/** The descriptor the block draws as, in a box of `size`. Picking's caret geometry reads the same one. */\nexport function textState(s: TextValues, src: TextSource, size: Size2D | undefined): Partial<TextState> {\n return {\n text: casedText(s, src),\n fontSize: s.fontSize,\n fontFamily: s.fontFamily,\n fontWeight: s.fontWeight,\n fontStyle: s.fontStyle,\n letterSpacing: s.letterSpacing,\n lineHeight: s.lineHeight,\n textAlign: s.textAlign,\n verticalAlign: s.verticalAlign,\n textDecoration: s.textDecoration,\n wrap: src.wraps,\n minFontSize: s.minFontSize,\n width: size?.width ?? 0,\n height: size?.height ?? 0,\n segments: textSegments(s, src) ?? undefined,\n path: src.glyphPath,\n };\n}\n\n/**\n * The node's own face, plus whatever a piece sets in another, and the pieces'\n * paints. Naming a family here is what lets it load before layout, rather than\n * being discovered by measuring against the fallback face.\n */\nexport function declareGlyphAssets(s: TextValues, src: TextSource, assets: Pick<AssetScope, \"font\" | \"fill\">): void {\n // Nothing may name a family at all; an `undefined` key is not a font to load.\n if (s.fontFamily) assets.font(s.fontFamily, s.fontWeight);\n for (const segment of textSegments(s, src) ?? []) {\n const family = segment.fontFamily ?? s.fontFamily;\n if (family) assets.font(family, segment.fontWeight);\n assets.fill(segment.fill ?? []);\n for (const stroke of segment.stroke ?? []) assets.fill(stroke.fill);\n }\n}\n\n/** One shaped piece of a line, as measuring needs it: its text and the face it is set in. */\ninterface StyledRun {\n text: string;\n fontFamily: string;\n fontSize: number;\n fontStyle: FontStyle;\n fontWeight: number;\n letterSpacing: number;\n}\n\n/** The segments as lines of runs, split at every newline; an empty line keeps the node's own face. */\nfunction measureStyledLines(segments: TextSegment[], fallback: Omit<StyledRun, \"text\">): { runs: StyledRun[] }[] {\n const lines: { runs: StyledRun[] }[] = [{ runs: [] }];\n for (const segment of segments) {\n const style: Omit<StyledRun, \"text\"> = {\n fontFamily: segment.fontFamily ?? fallback.fontFamily,\n fontSize: segment.fontSize ?? fallback.fontSize,\n fontStyle: segment.fontStyle ?? fallback.fontStyle,\n fontWeight: segment.fontWeight,\n letterSpacing: segment.letterSpacing,\n };\n const parts = segment.text.split(\"\\n\");\n for (let i = 0; i < parts.length; i++) {\n if (i > 0) lines.push({ runs: [] });\n lines[lines.length - 1].runs.push({ text: parts[i], ...style });\n }\n }\n for (const line of lines) {\n if (line.runs.length === 0) line.runs.push({ ...fallback, text: \"\" });\n }\n return lines;\n}\n\n/** Each wrapped line's tallest run, breaking at whitespace the way the paragraph builder does. */\nfunction wrappedLineSizes(lines: { runs: StyledRun[] }[], maxWidth: number, scope: MeasureContext2D): number[] {\n const sizes: number[] = [];\n for (const line of lines) {\n const tokens: { width: number; size: number; space: boolean }[] = [];\n for (const run of line.runs) {\n for (const part of run.text.split(/(\\s+)/)) {\n if (part.length === 0) continue;\n const space = /^\\s+$/.test(part);\n const width = scope.measureText(part, run.fontSize, run.fontFamily, run.fontWeight, run.letterSpacing, run.fontStyle).width;\n const last = tokens[tokens.length - 1];\n if (last && !last.space && !space) {\n last.width += width;\n last.size = Math.max(last.size, run.fontSize);\n } else {\n tokens.push({ width, size: run.fontSize, space });\n }\n }\n }\n if (tokens.length === 0) {\n sizes.push(Math.max(...line.runs.map(run => run.fontSize)));\n continue;\n }\n let lineW = tokens[0].width;\n let size = tokens[0].size;\n for (const token of tokens.slice(1)) {\n if (lineW + token.width <= maxWidth) {\n lineW += token.width;\n size = Math.max(size, token.size);\n } else {\n sizes.push(size);\n lineW = token.space ? 0 : token.width;\n size = token.space ? 0 : token.size;\n }\n }\n sizes.push(size > 0 ? size : Math.max(...line.runs.map(run => run.fontSize)));\n }\n return sizes;\n}\n\nfunction countWrappedLines(\n paragraph: string,\n maxWidth: number,\n fontSize: number,\n fontFamily: string,\n fontWeight: number,\n scope: MeasureContext2D,\n letterSpacing = 0,\n fontStyle: FontStyle = \"normal\",\n): number {\n if (paragraph.length === 0) return 1;\n if (scope.measureText(paragraph, fontSize, fontFamily, fontWeight, letterSpacing, fontStyle).width <= maxWidth) return 1;\n const words = paragraph.split(/(\\s+)/).filter(w => w.length > 0);\n let lines = 1;\n let lineW = 0;\n for (const word of words) {\n const w = scope.measureText(word, fontSize, fontFamily, fontWeight, letterSpacing, fontStyle).width;\n if (lineW === 0) {\n lineW = w;\n } else if (lineW + w <= maxWidth) {\n lineW += w;\n } else {\n lines++;\n lineW = /^\\s+$/.test(word) ? 0 : w;\n }\n }\n return lines;\n}\n\n/** What a rich-text node reads: spans, and the face they inherit from. */\nexport interface RichValues {\n readonly spans: readonly TextSpan[];\n readonly fontFamily: string;\n readonly fontSize: number;\n readonly fontWeight: number;\n readonly fontStyle: FontStyle;\n readonly letterSpacing: number;\n readonly lineHeight: number;\n readonly textAlign: TextAlign;\n readonly fill: unknown;\n readonly stroke: unknown;\n readonly width: SizeInput;\n readonly height: SizeInput;\n}\n\n/** Every span flattened to a run, each field it leaves unset taken from the node. */\nexport function richRuns(s: RichValues): ResolvedTextSpan[] {\n return textOps.flatten(s.spans, {\n fontFamily: s.fontFamily,\n fontSize: s.fontSize,\n fontWeight: s.fontWeight,\n fontStyle: s.fontStyle,\n letterSpacing: s.letterSpacing,\n fill: s.fill as FillResolved[],\n stroke: s.stroke as StrokeResolved[],\n });\n}\n\n/** Lines broken only at `\\n`, each as tall as its tallest run; an empty node keeps one line of its own size. */\nexport function measureRich(s: RichValues, constraints: SizeConstraints, scope: MeasureContext2D): Size2D {\n let lineW = 0;\n let maxLineH = 0;\n let totalW = 0;\n let totalH = 0;\n const finishLine = () => {\n if (lineW > totalW) totalW = lineW;\n totalH += maxLineH;\n lineW = 0;\n maxLineH = 0;\n };\n for (const run of richRuns(s)) {\n const lh = run.fontSize * s.lineHeight;\n const segments = run.text.split(\"\\n\");\n for (let i = 0; i < segments.length; i++) {\n if (i > 0) finishLine();\n lineW += scope.measureText(segments[i], run.fontSize, run.fontFamily, run.fontWeight, run.letterSpacing, run.fontStyle).width;\n if (lh > maxLineH) maxLineH = lh;\n }\n }\n finishLine();\n if (totalH === 0) totalH = s.fontSize * s.lineHeight;\n const wm = s.width;\n const hm = s.height;\n return {\n width: typeof wm === \"number\" ? wm : wm === \"hug\" ? totalW : constraints.maxWidth ?? 0,\n height: typeof hm === \"number\" ? hm : hm === \"hug\" ? totalH : constraints.maxHeight ?? 0,\n };\n}\n\nexport function richState(s: RichValues, size: Size2D | undefined): Partial<RichTextState> {\n return { spans: richRuns(s), lineHeight: s.lineHeight, textAlign: s.textAlign, width: size?.width ?? 0, height: size?.height ?? 0 };\n}\n\nexport function declareRichAssets(s: RichValues, assets: Pick<AssetScope, \"font\" | \"fill\">): void {\n for (const run of richRuns(s)) {\n if (run.fontFamily) assets.font(run.fontFamily, run.fontWeight);\n assets.fill(run.fill);\n for (const stroke of run.stroke) assets.fill(stroke.fill);\n }\n}\n", "import { createContext } from \"@/util/context\";\nimport type { TextStyle } from \"@/attributes/text/types\";\n\n/**\n * Built-in context tokens. These are ordinary {@link createContext} tokens —\n * the same primitive authors use for their own data — so the theme/text-style/\n * seed channels and user-defined context all travel one uniform path down the\n * node tree.\n */\n\n/** Inherited text-style defaults (set by `<DefaultTextStyle>`). */\nexport const TextStyleToken = createContext<TextStyle>({}, \"text-style\");\n\n/** Inherited theme map (set by `<ThemeProvider theme={…}>`). */\nexport const ThemeToken = createContext<Record<string, unknown>>({}, \"theme\");\n\n/** Arbitrary inherited data bag (set by `<ThemeProvider data={…}>`). */\nexport const DataToken = createContext<Record<string, unknown>>({}, \"data\");\n\n/** Inherited default seed (set by `<ThemeProvider seed={…}>`). Consumed by\n * author code today; a follow-up wires it into per-node randomness. */\nexport const SeedToken = createContext<string | number | undefined>(undefined, \"seed\");\n", "/** The types of the component factories. */\nimport type { Alignment } from \"@/attributes/layout/alignment\";\nimport type { InsetsProps, InsetsResolved } from \"@/attributes/layout/insets\";\nimport type { Size2D, SizeInput } from \"@/attributes/layout/size\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { Effect } from \"@/attributes/shape/effects/chain\";\nimport type { NodeEffect } from \"@/attributes/shape/effects/union\";\nimport type { NodeBlendMode } from \"@/attributes/shape/fill/blend\";\nimport type { BoxBounds } from \"@/layout/bounds\";\nimport type { PropInputs } from \"@/attributes/properties/inputs\";\nimport type { CameraScope, ChildPlane, Node2D, Node2DProps } from \"@/components/trees/2d/node2d\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport type { SpaceCamera } from \"@/attributes/layout/space3d\";\nimport type { TextStyle } from \"@/attributes/text/types\";\nimport type { AudioEffectsInput } from \"@/attributes/audio/effects/chain\";\nimport type { Param } from \"@/attributes/audio/ramp\";\nimport type { AudioTransition } from \"@/attributes/audio/transition\";\nimport type { AudioEffect } from \"@/attributes/audio/effects/union\";\nimport type { Context } from \"@/util/context\";\nimport type { RefTarget } from \"@/util/reference\";\nimport type { Command } from \"@/tween/command\";\nimport type { Graphics2D } from \"@/render/graphics2d\";\nimport type { BooleanOperation } from \"@/attributes/mask/boolean\";\nimport type { MaskOptions } from \"@/attributes/mask/mask\";\nimport type { FillResolved } from \"@/attributes/shape/fill/union\";\nimport type { ShadowResolved } from \"@/attributes/shape/shadow/shadow\";\nimport type { StrokeResolved } from \"@/attributes/shape/stroke/stroke\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport type { TypeDef } from \"@/components/factory/type-def\";\nimport type { Color } from \"@/attributes/shape/fill/color/parser\";\nimport type { ChildSpace3D, Node3D } from \"@/components/trees/three/node3d\";\nimport type { CameraData3D } from \"@/render3d/camera\";\nimport type { Graphics3D } from \"@/render3d/graphics3d\";\nimport type { Scene3D } from \"@/render3d/scene3d\";\nimport type { LightData3D } from \"@/render3d/light\";\nimport type { EnvironmentData3D, FogData3D } from \"@/render3d/scene-settings\";\nimport type { Shadow3D, Transform3D } from \"@/render3d/transform\";\nimport type { Euler3, EulerOrder, Quaternion, Vector3, Vector3Input } from \"@/render3d/vector3\";\n\n// =============================================================\n// State entries\n// =============================================================\n\ndeclare const typeBrand: unique symbol;\n\n/** A state entry's whole definition: what it accepts, what it resolves to, whether it is private. */\nexport interface Type<In, Out = In, Private extends boolean = false> {\n readonly [typeBrand]?: { readonly in: In; readonly out: Out; readonly private: Private };\n /** @internal The runtime half: default, mapper, tween, meaning. */\n readonly _def: TypeDef;\n}\n\nexport type AnyType = Type<any, any, boolean>;\n/** What a `state` field may hold: a Type, or a plain number, string or boolean default. */\nexport type Entry = AnyType | number | string | boolean;\nexport type StateSpec = { readonly [key: string]: Entry };\n\ntype TypeOf<E> =\n E extends AnyType ? E\n : E extends number ? Type<number>\n : E extends string ? Type<string>\n : E extends boolean ? Type<boolean>\n : never;\nexport type InOf<E> = TypeOf<E> extends Type<infer I, any, any> ? I : never;\nexport type OutOf<E> = TypeOf<E> extends Type<any, infer O, any> ? O : never;\ntype IsPrivate<E> = TypeOf<E> extends Type<any, any, infer P> ? P : false;\ntype IsReadOnly<E> = [InOf<E>] extends [never] ? true : false;\n\n/** The resolved, typed values a field reads. */\nexport type Values<S> = { readonly [K in keyof S]: OutOf<S[K]> };\n/** What a call or document may set: public entries, loose form, or a binding. */\nexport type Inputs<S> = {\n [K in keyof S as IsPrivate<S[K]> extends true ? never : IsReadOnly<S[K]> extends true ? never : K]?:\n InOf<S[K]> | (() => InOf<S[K]>);\n};\n/** What a command may write: any entry, public or private, loose form. */\nexport type Writes<S> = {\n [K in keyof S as IsReadOnly<S[K]> extends true ? never : K]?: InOf<S[K]>;\n};\n\n// =============================================================\n// Built-in 2D placement\n// =============================================================\n\nexport interface Box2DState {\n readonly x: Type<number>;\n readonly y: Type<number>;\n readonly width: Type<SizeInput>;\n readonly height: Type<SizeInput>;\n readonly rotation: Type<number>;\n readonly scale: Type<number>;\n readonly opacity: Type<number>;\n readonly pivot: Type<Alignment, Vector2>;\n readonly padding: Type<InsetsProps, InsetsResolved>;\n readonly effects: Type<Effect, NodeEffect[]>;\n readonly blend: Type<NodeBlendMode>;\n readonly clip: Type<boolean>;\n readonly flex: Type<number>;\n readonly rotationX: Type<number>;\n readonly rotationY: Type<number>;\n readonly depth: Type<number>;\n readonly perspective: Type<number>;\n}\n\n/** What every audio component has: its level, its place in the stereo field, and its own effects. */\nexport interface BoxAudioState {\n readonly volume: Type<Param>;\n readonly pan: Type<Param>;\n readonly mute: Type<boolean>;\n readonly effects: Type<AudioEffectsInput, AudioEffect[]>;\n readonly transitionIn: Type<AudioTransition | undefined>;\n readonly transitionOut: Type<AudioTransition | undefined>;\n}\n\ntype BuiltIn2DCommand = \"moveTo\" | \"fadeTo\" | \"rotateTo\" | \"scaleTo\" | \"layoutTo\" | \"effectTo\" | \"pulse\" | \"wiggle\" | \"to\" | \"set\";\n\ntype Merge<P, S> = Omit<P, keyof S> & S;\n\n// =============================================================\n// Elements, components and child views\n// =============================================================\n\ndeclare const elementBrand: unique symbol;\n\n/** What calling a component returns. In this slice, the built node itself. */\nexport interface Element<out K extends string = string, out S = unknown, out C = unknown> {\n readonly [elementBrand]?: { readonly key: K; readonly state: S; readonly commands: C };\n}\n\ntype AnyComponent = Component<string, any, any, any, any, any>;\n/** A whole tree, in `allowedChildren`: any component of it. */\ntype TreeName = \"2d\" | \"3d\" | \"audio\";\ntype Allowed = readonly (AnyComponent | TreeName)[] | null;\n\ntype ElementOf<A> =\n A extends null | undefined ? Element<string, Box2DState, {}>\n : A extends readonly [] ? never\n : A extends readonly (infer M)[] ? (M extends Component<infer K, infer S, infer C, any, any, any> ? Element<K, S, C> : M extends TreeName ? Element : never)\n : never;\n\n/** Any node, in the nested and falsy forms a class's `children` took: what a component allowing whole trees accepts. */\ntype ChildrenOfTrees = Element | Node | false | null | undefined | readonly ChildrenOfTrees[];\n\n/** Any 2D node, in the nested and falsy forms a class's `children` took: what a component allowing anything accepts. */\nexport type Children2D = Element | Node2D | false | null | undefined | readonly Children2D[];\n\ntype ChildrenProp<A> = [ElementOf<A>] extends [never]\n ? { readonly children?: never }\n : A extends null | undefined ? { readonly children?: Children2D }\n : A extends readonly TreeName[] ? { readonly children?: ChildrenOfTrees }\n : { readonly children?: readonly ElementOf<A>[] };\n\n/** Built-in placement a 2D node takes beyond its entries: alignment keys (`center`, `topLeft`…), `transform3D`, `flex`. */\ntype Placement2DProps<S> = PropInputs<Omit<Node2DProps, keyof S | \"children\">>;\n\n/**\n * What every call takes beside its entries: an id, a document key, and a\n * `ref` the node `R` is handed to while it is built, before its props apply.\n * A ref of a supertype of `R` is taken too (see {@link RefTarget}).\n */\ninterface CallMetadata<R> {\n readonly id?: string;\n readonly key?: string;\n readonly ref?: RefTarget<R>;\n}\n\nexport type CallProps<S, A, R = Node2D> = Inputs<S> & Placement2DProps<S> & ChildrenProp<A> & CallMetadata<R>;\n\n/** The node class generated from a spec: what a registry or an engine is handed. */\nexport type NodeClass<S, A, N extends Node = Node2D, P = CallProps<S, A>> = new (props?: P) => N;\n\n/** What a component of a non-2D tree is called with: its entries, children of its tree, an id. */\nexport type TreeCallProps<S, R = Node> = Inputs<S> & CallMetadata<R> & {\n readonly children?: readonly (Element | Node)[];\n};\n\n/** The node a component of state `S` and commands `C` builds on `N`: what `new` returns and a `ref` is handed. */\nexport type BuiltNode<S, C, N extends Node = Node2D> = NodeValues<S, N> & CommandMethods<C, N>;\n\nexport interface Component<K extends string, S, C, A, N extends Node = Node2D, P = CallProps<S, A, BuiltNode<S, C, N>>> {\n (props?: P): Element<K, S, C>;\n /** Builds the same node as a call, typed as the node: for engine code written against a class. */\n new (props?: P): BuiltNode<S, C, N>;\n readonly key: K;\n /** The generated node class: hand it to an engine (`nodes: [Gauge.node]`) or a registry. */\n readonly node: NodeClass<S, A, N, P>;\n /** Narrows a child view: `children.filter(BarSeries.is)`. */\n is(child: ChildView<any>): child is ChildView<Element<K, S, C>>;\n}\n\n/**\n * The node a component builds, as engine code and tests holding one see it: the\n * node, and each entry's resolved value. Authoring code works with `Element`.\n */\nexport type NodeOf<C> = C extends Component<any, infer S, infer M, any, infer N, any> ? BuiltNode<S, M, N> : never;\n/** A command, called on the node as a class's `command` method is. */\nexport type CommandMethods<C, N extends Node = Node2D> = {\n [K in Exclude<keyof C, keyof N>]: (args?: { readonly data?: unknown; readonly duration?: number; readonly easing?: EasingFunction }) => Command<Record<string, unknown>>;\n};\nexport type NodeValues<S, N extends Node = Node2D> =\n (N extends Node2D ? Node2D<Node2DProps & EntryProps<S>> : N) & { -readonly [E in Exclude<keyof S, keyof N>]: OutOf<S[E]> };\n/** Each entry's loose form, as `set` and `to` take it. */\ntype EntryProps<S> = { [E in Exclude<keyof S, keyof Node2DProps>]: InOf<S[E]> };\n\ntype StateOfElement<E> = E extends Element<any, infer S, any> ? S : never;\ntype CommandsOfElement<E> = E extends Element<any, any, infer C>\n ? unknown extends C ? string : (keyof C & string) | BuiltIn2DCommand\n : never;\n\n/** A child, as a parent's fields see it. */\nexport interface ChildView<out E extends Element = Element> {\n readonly id: string;\n readonly key: E extends Element<infer K> ? K : string;\n readonly state: Values<StateOfElement<E>>;\n /** Its size, measured against the room this pass gives it; outside a pass (in a command), the size it was last laid out at. */\n readonly size: Size2D;\n /** Its own children, as it hands them to its fields: how a command reaches parts nested inside a child. */\n readonly children: readonly ChildView[];\n measure(max: Max): Size2D;\n to(targets: Writes<StateOfElement<E>>): Piece;\n run(name: CommandsOfElement<E>, args?: object): Piece;\n}\n\n// =============================================================\n// What the engine hands each field\n// =============================================================\n\nexport interface Max {\n readonly width?: number;\n readonly height?: number;\n}\n\nexport interface FontSpec {\n readonly fontFamily: string;\n readonly fontSize: number;\n readonly fontWeight?: number;\n readonly letterSpacing?: number;\n}\n\nexport interface Measurer {\n readonly max: Max;\n /** The node's clock: a size that changes with time (a spin, a flow) reads it here. */\n readonly time: Clock;\n text(text: string, font: FontSpec): Size2D;\n}\n\nexport interface Clock {\n readonly total: number;\n readonly elapsed: number;\n}\n\n/** What `load` declares: everything that must be in before the node is measured or drawn. */\nexport interface Loader {\n font(family: string, weight?: number | string): void;\n image(src: string): void;\n video(src: string, trim?: { readonly start?: number; readonly end?: number }): void;\n /**\n * Async setup. `before: \"layout\"` holds measuring too (a font engine, MathJax); the default holds only the frame.\n * A function `load` resolves to frees what it loaded when the asset's window is evicted.\n */\n task(key: string, load: () => Promise<unknown>, options?: { readonly before?: \"layout\" | \"render\" }): void;\n /** A paint the component works out itself (a run's fill); paint entries load themselves. */\n fill(fills: FillResolved | readonly FillResolved[]): void;\n}\n\n/** A value a component hands its subtree under a context, which `Types.*({ inherit })` entries read. */\nexport interface Provided<T = unknown> {\n readonly context: Context<T>;\n readonly value: T;\n}\n\nexport function provides<T>(context: Context<T>, value: T): Provided<T> {\n return { context, value };\n}\n\nexport interface RenderContext2D {\n readonly size: Size2D;\n readonly time: Clock;\n draw(graphics: Graphics2D | readonly Graphics2D[] | null | undefined): void;\n /** Draws your children here. */\n children(): void;\n /** Your first child is the stencil; the rest draw through it. */\n mask(options: MaskOptions): void;\n /** Your children become one shape by `op`, painted with `paint`. */\n merge(op: BooleanOperation, paint: MergePaint): void;\n /** Your children through a camera viewing your box. */\n camera(scope: CameraScope): void;\n /** Your children standing in one 2.5D space seen by `camera`, drawn far to near. */\n space(camera: SpaceCamera): void;\n /**\n * Your 3D children rendered into a new scene, for a fill (`Fills.canvas3D`) or\n * more drawing. Picking projects through the same scene.\n */\n scene3D(): Scene3D;\n /** Run `body` with `style` the default for text drawn in it; `null` refuses the inherited style. */\n textStyle(style: TextStyle | null, body: () => void): void;\n /** Run `body` with what it draws confined to `shape`'s outline. */\n clip(shape: Graphics2D, body: () => void): void;\n /**\n * Run `body` as your own paint: standing in a 2.5D space, only what lies in\n * front of the lens shows, as a class's own paint does. `Paint.draw` does this\n * for the paint it draws; a component drawing with `draw` wraps it here.\n */\n inFront(body: () => void): void;\n /** Whether an ancestor already stands you in a 2.5D space, so a space of your own would nest in it. */\n readonly inSpace: boolean;\n /** Your nearest ancestor that `component` built, read-only, or `null` when none is above you. */\n ancestor<K extends string, S, C>(component: Component<K, S, C, any, any, any>): NodeView<Element<K, S, C>> | null;\n}\n\n/** Another node as a component reads it: its id, its resolved state and the size it was laid out at. */\nexport interface NodeView<out E extends Element = Element> {\n readonly id: string;\n readonly key: E extends Element<infer K> ? K : string;\n /** As its own fields read it: a reference entry of its own is a view of that node from where it stands. */\n readonly state: Values<StateOfElement<E>>;\n readonly size: Size2D;\n /** Where it stands in the reader's own frame (y up from the reader's centre): offset, turn and scale. */\n readonly frame: NodeFrame;\n}\n\nexport interface NodeFrame {\n readonly x: number;\n readonly y: number;\n readonly rotation: number;\n readonly scale: number;\n}\n\n/** What a merged shape is painted with: a shape's resolved paint entries. */\nexport interface MergePaint {\n readonly fill: FillResolved[];\n readonly stroke: StrokeResolved[];\n readonly shadow: ShadowResolved[];\n readonly overlay?: FillResolved[];\n}\n\n/** Where a 2D child goes: a box centred on (x, y) from your centre, y up, plus an optional slot transform. */\nexport interface Placement2D {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n readonly rotation?: number;\n readonly scale?: number;\n readonly opacity?: number;\n readonly depth?: number;\n readonly rotationX?: number;\n readonly rotationY?: number;\n /** What the child's own `x`/`y` mean in your units (a graph's): read wherever its position is, by paint, picking and a host's drag. */\n readonly plane?: ChildPlane;\n}\n\n/** Your content box, as `layout` is handed it, and the node's clock for a layout that moves with time. */\nexport interface LayoutBox extends BoxBounds {\n readonly time: Clock;\n}\n\n/** A point an editor can drag to set an entry: where it sits in your frame (y up from your centre), and the value dropping it there gives. */\nexport interface Handle<V> {\n at(state: V, size: Size2D): Vector2 | null;\n /** Where it was dropped, as the entry's value; by default the point itself. */\n value?(at: Vector2, state: V, size: Size2D): Vector2;\n}\n\n// =============================================================\n// Commands\n// =============================================================\n\ndeclare const pieceBrand: unique symbol;\n/** A timed piece of a command. */\nexport interface Piece {\n readonly [pieceBrand]?: true;\n /** @internal */\n readonly _piece: PieceData;\n}\n\n/** @internal */\nexport type PieceData =\n | { readonly kind: \"tween\"; readonly targets: Record<string, unknown> }\n | { readonly kind: \"animate\"; readonly frame: (t: number) => Record<string, unknown>; readonly eased: boolean }\n | { readonly kind: \"wait\"; readonly seconds: number }\n | { readonly kind: \"sound\"; readonly src: string; readonly options: SoundOptions }\n | { readonly kind: \"together\" | \"sequence\"; readonly pieces: readonly Piece[] }\n | { readonly kind: \"stagger\"; readonly pieces: readonly Piece[]; readonly overlap: number }\n | { readonly kind: \"child\"; readonly node: object; readonly targets: Record<string, unknown> }\n | { readonly kind: \"run\"; readonly node: object; readonly name: string; readonly args: object | undefined };\n\n/** How a sound plays: today's `AudioClip` fields, and the bus it feeds when its node isn't one. */\nexport interface SoundOptions {\n readonly trimStart?: number;\n readonly trimEnd?: number;\n readonly loop?: boolean;\n readonly volume?: Param;\n readonly speed?: Param;\n readonly effects?: AudioEffectsInput;\n readonly transitionIn?: AudioTransition;\n readonly transitionOut?: AudioTransition;\n /** Missing from the catalog, it is skipped rather than an error. */\n readonly optional?: boolean;\n /** The id of the bus it feeds. A sound node feeds the buses it sits in. */\n readonly bus?: string;\n /** Ends with its source rather than staying open: a picture's sound, which stops when the picture does. */\n readonly closed?: boolean;\n}\n\nexport interface Timeline<A = {}, S = {}> {\n readonly args: A;\n readonly duration: number;\n readonly easing: EasingFunction | undefined;\n /** The node this command acts on, read-only: its id (a seed), its size. */\n readonly node: NodeView;\n tween(targets: Writes<S>): Piece;\n /** `frame` at each point of the command; `eased: false` hands it linear progress, to ease per part with `ease`. */\n animate(frame: (t: number) => Writes<S>, options?: { readonly eased?: boolean }): Piece;\n /** The command's easing at `t`. */\n ease(t: number): number;\n /** `src` plays from here: cut when the command ends, or to its own end when the command has no length. */\n sound(src: string, options?: SoundOptions): Piece;\n wait(seconds: number): Piece;\n together(pieces: readonly Piece[]): Piece;\n sequence(pieces: readonly Piece[]): Piece;\n stagger(pieces: readonly Piece[], options?: { readonly overlap?: number }): Piece;\n}\n\ntype Kids = readonly ChildView<any>[];\n\nexport type CommandEntry<A, S, V, K> =\n // The names as written, so a module's command fits any state holding those entries.\n | (A extends readonly unknown[] ? { readonly args: A & readonly (keyof Writes<S> & string)[]; readonly run?: undefined; readonly easing?: EasingFunction; readonly entrance?: boolean } : never)\n | ((timeline: Timeline<{}, S>, state: V, children: K) => Piece)\n // `easing`: what the command eases by when its row gives none. `entrance`:\n // the timeline holds its first frame ahead of it (`CommandMeta.entrance`).\n | (A extends readonly unknown[] ? never : { readonly args: A; run(timeline: Timeline<Values<A>, S>, state: V, children: K): Piece; readonly easing?: EasingFunction; readonly entrance?: boolean });\n\nexport type CommandsSpec<C, S, V, K> = { [N in keyof C]: CommandEntry<C[N], S, V, K> };\n\n// =============================================================\n// The 2D factory's fields\n// =============================================================\n\nexport type FieldState<All, A> = Values<All> & { readonly children: readonly ChildView<ElementOf<A>>[] };\nexport type BuilderState<All, A> = Values<All> & { readonly children: readonly ElementOf<A>[] };\ntype OwnKids<A, B> = readonly ChildView<[B] extends [never] ? ElementOf<A> : Extract<B, Element>>[];\n\n/**\n * New defaults for entries, own or built in. A function is a binding: handed the\n * live state, and `given`, what the call or document row set when the node was\n * built (which never changes), for a default derived from those.\n */\nexport type Defaults<All, A> = {\n readonly [E in keyof All]?: InOf<All[E]> | ((state: FieldState<All, A>, given: Readonly<Record<string, unknown>>) => InOf<All[E]>);\n};\n\nexport interface Spec2D<K extends string, All, S, C, A, B> {\n readonly key: K;\n readonly state?: S;\n readonly defaults?: Defaults<All, A>;\n /** Old prop keys a stored row may still carry → the entry each became. */\n readonly renamed?: Readonly<Record<string, string>>;\n /** Entries that still work but should no longer be set: why, and what to use instead. */\n readonly deprecated?: Readonly<Record<string, string>>;\n /** Value hooks by entry, or by an old key in `renamed` to convert only what was stored under it (`migrateNodeProps`). */\n readonly migrate?: Readonly<Record<string, (value: unknown) => unknown>>;\n readonly allowedChildren?: A;\n /** The components it goes only inside; unsaid, wherever its tree allows. A row elsewhere fails its build. */\n readonly allowedParents?: readonly AnyComponent[];\n readonly children?: (state: BuilderState<All, A>) => readonly B[];\n readonly commands?: CommandsSpec<C, All, FieldState<All, A>, OwnKids<A, B>>;\n readonly load?: (loader: Loader, state: FieldState<All, A>) => void;\n /** What the subtree inherits: the nearest provider's value for each context, `inherited` reading what's above. */\n readonly provide?: (state: FieldState<All, A>, inherited: <T>(context: Context<T>) => T) => readonly Provided[];\n readonly measure?: (measurer: Measurer, state: FieldState<All, A>, children: OwnKids<A, B>) => Size2D;\n readonly layout?: (box: LayoutBox, state: FieldState<All, A>, children: OwnKids<A, B>) => readonly Placement2D[];\n /** What a child not added yet would take its `x`/`y` in: where a host drops or pastes one. Layout's `plane` answers for the rest. */\n readonly plane?: (box: LayoutBox, state: FieldState<All, A>) => ChildPlane | null;\n /** Points an editor can drag, by the entry each sets. */\n readonly handles?: { readonly [entry: string]: Handle<FieldState<All, A>> };\n /** Your bounds when they are not your box (a mark's ink): what selection and picking take. */\n readonly bounds?: (size: Size2D, state: FieldState<All, A>) => BoxBounds;\n readonly render?: (ctx: RenderContext2D, state: FieldState<All, A>) => void;\n /** The coordinates your 3D children's `x`, `y`, `z` are in (a graph's units), for a viewport over them. */\n readonly space?: (state: FieldState<All, A>) => ChildSpace3D | null;\n}\n\n/** A sound, or a bus mixing what is in it. It has no box and draws nothing: sound comes from its commands. */\nexport interface SpecAudio<K extends string, All, S, C, A, B> {\n readonly key: K;\n readonly state?: S;\n readonly defaults?: Defaults<All, A>;\n /** Old prop keys a stored row may still carry → the entry each became. */\n readonly renamed?: Readonly<Record<string, string>>;\n /** Entries that still work but should no longer be set: why, and what to use instead. */\n readonly deprecated?: Readonly<Record<string, string>>;\n /** Value hooks by entry, or by an old key in `renamed` to convert only what was stored under it (`migrateNodeProps`). */\n readonly migrate?: Readonly<Record<string, (value: unknown) => unknown>>;\n readonly allowedChildren?: A;\n /** The components it goes only inside; unsaid, wherever its tree allows. A row elsewhere fails its build. */\n readonly allowedParents?: readonly AnyComponent[];\n readonly children?: (state: BuilderState<All, A>) => readonly B[];\n readonly commands?: CommandsSpec<C, All, FieldState<All, A>, Kids>;\n readonly load?: (loader: Loader, state: FieldState<All, A>) => void;\n readonly provide?: (state: FieldState<All, A>, inherited: <T>(context: Context<T>) => T) => readonly Provided[];\n}\n\n// =============================================================\n// The 3D tree\n// =============================================================\n\n/** What every 3D component has: its place, turn and scale, and how the scene shows it. */\nexport interface Transform3DState {\n readonly x: Type<number>;\n readonly y: Type<number>;\n readonly z: Type<number>;\n readonly rotationX: Type<number>;\n readonly rotationY: Type<number>;\n readonly rotationZ: Type<number>;\n readonly rotationOrder: Type<EulerOrder>;\n readonly quaternion: Type<Quaternion>;\n readonly scaleX: Type<number>;\n readonly scaleY: Type<number>;\n readonly scaleZ: Type<number>;\n readonly lookAt: Type<Vector3Input | undefined, Vector3 | undefined>;\n readonly visible: Type<boolean>;\n readonly shadow: Type<Shadow3D>;\n readonly renderOrder: Type<number>;\n}\n\n/** A 3D call's vector forms of the axes: `position: [x, y, z]`, `rotation`, `scale` (one number scales all three). */\nexport interface Placement3DProps {\n readonly position?: Vector3Input | (() => Vector3Input);\n readonly rotation?: Vector3Input | Euler3 | (() => Vector3Input | Euler3);\n readonly scale?: Vector3Input | (() => Vector3Input);\n}\n\nexport type CallProps3D<S, R = Node3D> = TreeCallProps<S, R> & Placement3DProps;\n\n/** What a 3D `render` draws into: today's scene calls, with a camera standing where its node stands. */\nexport interface RenderContext3D {\n readonly time: Clock;\n /**\n * `render` runs only so what it draws loads, and nothing is shown: only the\n * materials, models and environment count, so geometry built from data may be skipped.\n */\n readonly declaring: boolean;\n draw(graphics: Graphics3D | null | undefined): void;\n light(light: LightData3D, transform?: Transform3D): void;\n /** The scene's camera, placed by this node's transform. A node that stands one is no group: its children stay in its parent's space. */\n camera(camera: CameraData3D): void;\n fog(fog: FogData3D | Color | null): void;\n environment(environment: EnvironmentData3D | null): void;\n}\n\nexport interface Spec3D<K extends string, All, S, C, A, B> {\n readonly key: K;\n readonly state?: S;\n readonly defaults?: Defaults<All, A>;\n /** Old prop keys a stored row may still carry → the entry each became. */\n readonly renamed?: Readonly<Record<string, string>>;\n /** Entries that still work but should no longer be set: why, and what to use instead. */\n readonly deprecated?: Readonly<Record<string, string>>;\n /** Value hooks by entry, or by an old key in `renamed` to convert only what was stored under it (`migrateNodeProps`). */\n readonly migrate?: Readonly<Record<string, (value: unknown) => unknown>>;\n readonly allowedChildren?: A;\n /** The components it goes only inside; unsaid, wherever its tree allows. A row elsewhere fails its build. */\n readonly allowedParents?: readonly AnyComponent[];\n readonly children?: (state: BuilderState<All, A>) => readonly B[];\n readonly commands?: CommandsSpec<C, All, FieldState<All, A>, Kids>;\n readonly load?: (loader: Loader, state: FieldState<All, A>) => void;\n readonly provide?: (state: FieldState<All, A>, inherited: <T>(context: Context<T>) => T) => readonly Provided[];\n readonly render?: (ctx: RenderContext3D, state: FieldState<All, A>) => void;\n /** The coordinates your 3D children's `x`, `y`, `z` are in (a graph's units): where each lands in yours. */\n readonly space?: (state: FieldState<All, A>) => ChildSpace3D | null;\n}\n\nexport type { Merge, Kids, Allowed, AnyComponent };\n", "import type { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { Shadow } from \"@/attributes/shape/shadow/shadow\";\nimport type { Stroke } from \"@/attributes/shape/stroke/stroke\";\nimport { textOps } from \"@/attributes/text/ops\";\nimport type { FontStyle, TextAlign, TextStyle } from \"@/attributes/text/types\";\nimport { TextStyleToken } from \"@/runtime/builtin-context\";\nimport { provides, type Provided, type Values } from \"@/components/factory/api\";\nimport type { Inherit } from \"@/components/factory/type-def\";\nimport { Types } from \"@/components/factory/types\";\n\n/**\n * The face text is set in, each field taken, when the author leaves it unset,\n * from the cascade: the theme's `default` typography, under the nearest\n * provider's style, under the node's own `variant` preset.\n */\n\nfunction cascade(use: Parameters<Inherit>[0], given: Readonly<Record<string, unknown>>): TextStyle {\n const variant = given.variant as string | undefined;\n return textOps.mergeStyle(\n textOps.mergeStyle(textOps.preset(\"default\"), use(TextStyleToken)),\n variant ? textOps.preset(variant) : undefined,\n );\n}\n\n/** What `key` inherits. `autofit: false` refuses an inherited `'autofit'` size, for a node that can't fit to its box. */\nexport function inherit(key: keyof TextStyle, options: { readonly autofit?: boolean } = {}): Inherit {\n return (use, given) => {\n const value = cascade(use, given)[key];\n return key === \"fontSize\" && value === \"autofit\" && options.autofit === false ? undefined : value;\n };\n}\n\nexport const state = {\n // No default: a face nobody chose is one never declared and never loaded, so the renderer says so.\n fontFamily: Types.custom<string>(undefined as unknown as string, { inherit: inherit(\"fontFamily\") }),\n fontSize: Types.custom<number | \"autofit\">(48, {\n lerp: (a, b, t) => textOps.lerpFontSize(a, b, t) as number | \"autofit\",\n inherit: inherit(\"fontSize\"),\n }),\n fontWeight: Types.number(400, { inherit: inherit(\"fontWeight\") }),\n fontStyle: Types.custom<FontStyle>(\"normal\", { inherit: inherit(\"fontStyle\") }),\n letterSpacing: Types.number(0, { inherit: inherit(\"letterSpacing\") }),\n lineHeight: Types.number(1.2, { inherit: inherit(\"lineHeight\") }),\n textAlign: Types.custom<TextAlign>(\"center\", { inherit: inherit(\"textAlign\") }),\n verticalAlign: Types.oneOf([\"top\", \"center\", \"bottom\"], { default: \"center\" }),\n textDecoration: Types.oneOf([\"none\", \"underline\", \"line-through\"]),\n textCase: Types.oneOf([\"none\", \"upper\", \"lower\", \"title\"]),\n minFontSize: Types.number(12),\n variant: Types.custom<string | undefined>(undefined),\n fill: Types.fill(undefined, { inherit: inherit(\"fill\") }),\n stroke: Types.stroke(undefined, { inherit: inherit(\"stroke\") }),\n shadow: Types.shadow(undefined, { inherit: inherit(\"shadow\") }),\n};\n\n/** The style a provider sets: each field left unset is inherited from above. */\nexport const provided = {\n fontFamily: Types.custom<string | undefined>(undefined),\n fontSize: Types.custom<number | \"autofit\" | undefined>(undefined),\n fontWeight: Types.custom<number | undefined>(undefined),\n fontStyle: Types.custom<FontStyle | undefined>(undefined),\n letterSpacing: Types.custom<number | undefined>(undefined),\n lineHeight: Types.custom<number | undefined>(undefined),\n textAlign: Types.custom<TextAlign | undefined>(undefined),\n fill: Types.custom<Fill | undefined>(undefined),\n stroke: Types.custom<Stroke | undefined>(undefined),\n shadow: Types.custom<Shadow | undefined>(undefined),\n};\n\n/** The subtree's style: the inherited one with this provider's fields laid over it. */\nexport function provide(s: Values<typeof provided>, inherited: <T>(context: { readonly id: symbol; readonly defaultValue: T }) => T): readonly Provided[] {\n return [provides(TextStyleToken, textOps.mergeStyle(inherited(TextStyleToken), s as TextStyle))];\n}\n\n/** This provider's own fields, as the default for text drawn under it. */\nexport function current(s: Values<typeof provided>): TextStyle {\n return textOps.mergeStyle({}, s as TextStyle);\n}\n", "import { NodeAudio } from \"@/components/trees/audio/node-audio\";\nimport type { Allowed, BoxAudioState, BuiltNode, ChildView, Component, Element, Merge, SpecAudio, StateSpec, TreeCallProps } from \"@/components/factory/api\";\nimport { componentBase, finishComponent, lowering, type CoreSpec } from \"@/components/factory/factory\";\nimport { childView } from \"@/components/factory/views\";\n\n/**\n * An audio component: a sound, or a bus mixing the sounds in it. Lowers onto a\n * generated `NodeAudio` subclass. It has no audio field: what it plays comes\n * from its commands' `timeline.sound`.\n */\nexport function componentAudio<\n const K extends string,\n const S extends StateSpec = {},\n const C = {},\n const A extends Allowed = null,\n const B extends Element = never,\n>(spec: SpecAudio<K, Merge<BoxAudioState, S>, S, C, A, B>): Component<K, Merge<BoxAudioState, S>, C, A, NodeAudio, TreeCallProps<Merge<BoxAudioState, S>, BuiltNode<Merge<BoxAudioState, S>, C, NodeAudio>>> {\n const l = lowering(spec as unknown as CoreSpec, NodeAudio);\n\n class Generated extends componentBase(NodeAudio, l) {\n override _commandChildren(): readonly ChildView[] {\n return this.childrenAudio.map(childView);\n }\n }\n\n return finishComponent(Generated, l) as never;\n}\n", "import type { AssetScope } from \"@/assets/scope\";\nimport type { Color } from \"@/attributes/shape/fill/color/parser\";\nimport { getNodeDescriptor } from \"@/document/node-decorator\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport { Node3D, type ChildSpace3D } from \"@/components/trees/three/node3d\";\nimport type { CameraData3D } from \"@/render3d/camera\";\nimport type { Graphics3D } from \"@/render3d/graphics3d\";\nimport type { LightData3D } from \"@/render3d/light\";\nimport type { RenderContext3D as SceneTarget } from \"@/render3d/render-context3d\";\nimport type { EnvironmentData3D, FogData3D } from \"@/render3d/scene-settings\";\nimport { declareEnvironment } from \"@/render3d/tracking\";\nimport type { Transform3D } from \"@/render3d/transform\";\nimport type {\n Allowed, BuiltNode, CallProps3D, ChildView, Clock, Component, Element, Merge, RenderContext3D, Spec3D, StateSpec, Transform3DState,\n} from \"@/components/factory/api\";\nimport { componentBase, finishComponent, lowering, type CoreSpec } from \"@/components/factory/factory\";\nimport { childView, setKeyLookup } from \"@/components/factory/views\";\n\nsetKeyLookup((n) => getNodeDescriptor(n.constructor as new () => object)?.key);\n\ntype AnySpec = Spec3D<string, any, any, any, any, any>;\n\ninterface Host3D extends Node3D {\n _ownTransform(): Transform3D;\n}\n\n/** What a 3D `render` draws into: the scene being built, with a camera placed where its node stands. */\nclass RenderContext3DImpl implements RenderContext3D {\n target: SceneTarget | null = null;\n /** Set when `render` asks for a camera: such a node is no group, and stands its camera instead. */\n camera3D = false;\n environment3D: EnvironmentData3D | null = null;\n declaring = false;\n\n constructor(readonly host: Host3D) { }\n\n get time(): Clock {\n return this.host.time;\n }\n\n draw(graphics: Graphics3D | null | undefined): void {\n if (graphics) this.target?.draw(graphics);\n }\n\n light(light: LightData3D, transform?: Transform3D): void {\n this.target?.light(light, transform);\n }\n\n camera(camera: CameraData3D): void {\n this.camera3D = true;\n this.target?.camera({ ...this.host._ownTransform(), ...camera } as CameraData3D);\n }\n\n fog(fog: FogData3D | Color | null): void {\n this.target?.fog(fog);\n }\n\n environment(environment: EnvironmentData3D | null): void {\n this.environment3D = environment;\n this.target?.environment(environment);\n }\n}\n\n/**\n * A 3D component: placed by its transform, drawn with `Graphics3D`, lights and\n * cameras. Lowers onto a generated `Node3D` subclass; its children render\n * after it, in its space.\n */\nexport function component3d<\n const K extends string,\n const S extends StateSpec = {},\n const C = {},\n const A extends Allowed = null,\n const B extends Element = never,\n>(spec: Spec3D<K, Merge<Transform3DState, S>, S, C, A, B>): Component<K, Merge<Transform3DState, S>, C, A, Node3D, CallProps3D<Merge<Transform3DState, S>, BuiltNode<Merge<Transform3DState, S>, C, Node3D>>> {\n const s = spec as unknown as AnySpec;\n const l = lowering(s as unknown as CoreSpec, Node3D);\n\n class Generated extends componentBase(Node3D, l) implements Host3D {\n declare _ctx3d: RenderContext3DImpl;\n declare _isCamera: boolean | undefined;\n\n constructor(props?: Record<string, unknown>) {\n super(props);\n this._ctx3d = new RenderContext3DImpl(this);\n }\n\n protected override renderSelf(ctx: SceneTarget): void {\n if (!s.render) return;\n const c = this._ctx3d;\n c.target = ctx;\n try {\n s.render(c, this._view as never);\n } finally {\n c.target = null;\n }\n }\n\n /** A node that stands a camera places the camera, not a group: its children stay in the parent's space. */\n protected override groupTransform(): Transform3D {\n return this._rendersCamera() ? {} : super.groupTransform();\n }\n\n _rendersCamera(): boolean {\n if (this._isCamera === undefined) {\n const c = this._ctx3d;\n c.camera3D = false;\n if (s.render) s.render(c, this._view as never);\n this._isCamera = c.camera3D;\n }\n return this._isCamera;\n }\n\n _ownTransform(): Transform3D {\n return this.transform3D();\n }\n\n /** What `render` draws loads itself: its textures and models, and an environment map it sets. */\n override declareAssets(assets: AssetScope): void {\n const c = this._ctx3d;\n c.environment3D = null;\n c.declaring = true;\n try {\n super.declareAssets(assets);\n } finally {\n c.declaring = false;\n }\n declareEnvironment(c.environment3D, assets);\n }\n\n override _commandChildren(): readonly ChildView[] {\n return (this.children as Node[]).filter((c) => c instanceof Node3D).map(childView);\n }\n }\n\n if (s.space) {\n const space = s.space;\n (Generated.prototype as unknown as { _spaceOf: (child: Node3D | null) => ChildSpace3D | null })._spaceOf = function (this: Generated) {\n return space(this._view as never);\n };\n }\n\n return finishComponent(Generated, l) as never;\n}\n", "import { lerpFill3D, resolveFill3D, type Fill3D } from \"@/render3d/fill3d\";\nimport type { Geometry3D } from \"@/render3d/geometry\";\nimport { Graphics3D, resolveMaterialShorthand3D, type MaterialShorthand3D } from \"@/render3d/graphics3d\";\nimport type { Material3D, Shading3D } from \"@/render3d/material\";\nimport type { Texture3D } from \"@/render3d/texture\";\nimport type { Blend3D, Faces3D } from \"@/render3d/transform\";\nimport type { Values } from \"@/components/factory/api\";\nimport { Types } from \"@/components/factory/types\";\nimport { optional, optionalColor } from \"@/components/modules/three-entries\";\n\n/** `Mesh3D`'s surface: a material, or the shorthand entries one is built from. */\nexport const state = {\n material: optional<Material3D | readonly Material3D[]>(),\n fill: Types.custom<Fill3D>(\"white\", { lerp: lerpFill3D }),\n opacity: optional<number>(),\n roughness: optional<number>(),\n metalness: optional<number>(),\n emission: optionalColor(),\n emissionStrength: optional<number>(),\n normalMap: optional<Texture3D>(),\n roughnessMap: optional<Texture3D>(),\n metalnessMap: optional<Texture3D>(),\n aoMap: optional<Texture3D>(),\n alphaMap: optional<Texture3D>(),\n envMapIntensity: optional<number>(),\n wireframe: optional<boolean>(),\n shading: optional<Shading3D>(),\n faces: optional<Faces3D>(),\n vertexColors: optional<boolean>(),\n blend: optional<Blend3D>(),\n unlit: Types.custom(false),\n};\n\ntype MaterialState = Values<typeof state>;\n\nconst SHORTHAND_KEYS = [\n \"opacity\", \"roughness\", \"metalness\",\n \"emission\", \"emissionStrength\", \"normalMap\", \"roughnessMap\",\n \"metalnessMap\", \"aoMap\", \"alphaMap\", \"envMapIntensity\", \"wireframe\",\n \"shading\", \"faces\", \"vertexColors\", \"blend\",\n] as const;\n\n/** The entries that are set, as a material shorthand. */\nexport function shorthand(s: MaterialState): MaterialShorthand3D {\n const out: Record<string, unknown> = {};\n if (s.material !== undefined) out.material = s.material;\n if (s.fill !== undefined) out.fill = s.fill;\n for (const key of SHORTHAND_KEYS) if (s[key] !== undefined) out[key] = s[key];\n if (s.unlit) out.unlit = true;\n return out as MaterialShorthand3D;\n}\n\n/** `geometry` with this surface; nothing without one. */\nexport function mesh(s: MaterialState, geometry: Geometry3D | undefined): Graphics3D {\n const g3 = new Graphics3D();\n if (geometry) g3.mesh(geometry, resolveMaterialShorthand3D(shorthand(s)));\n return g3;\n}\n\n/** The one material instanced copies share: the first, when the shorthand resolves to several. */\nexport function single(s: MaterialState): Material3D {\n const resolved = resolveMaterialShorthand3D(shorthand(s));\n return (Array.isArray(resolved) ? resolved[0] : resolved) as Material3D;\n}\n\nconst POINTS_KEYS = [\"opacity\", \"alphaMap\", \"blend\", \"vertexColors\"] as const;\n\n/** A points material: the given one, or the fill's colour and map with what a point cloud reads. */\nexport function points(s: MaterialState): Material3D {\n if (s.material !== undefined) return (Array.isArray(s.material) ? s.material[0] : s.material) as Material3D;\n const material: Record<string, unknown> = { type: \"points\" };\n const fill = resolveFill3D(s.fill);\n if (fill.color !== undefined) material.color = fill.color;\n if (fill.map !== undefined) material.map = fill.map;\n for (const key of POINTS_KEYS) if (s[key] !== undefined) material[key] = s[key];\n return material as unknown as Material3D;\n}\n", "import type { Color, NormalizedColor } from \"@/attributes/shape/fill/color/parser\";\nimport { colorOps } from \"@/attributes/shape/fill/lerp\";\nimport { lerpOptionalVector3, resolveOptionalVector3, type Vector3, type Vector3Input } from \"@/render3d/vector3\";\nimport type { Type } from \"@/components/factory/api\";\nimport { Types, type EntryOptions } from \"@/components/factory/types\";\n\n/** The 3D tree's entries that start unset: the renderer's own default applies until one is given. */\n\nexport function optional<T>(): Type<T | undefined> {\n return Types.custom<T | undefined>(undefined);\n}\n\n/** A number, unset until given, with a number's hints. */\nexport function optionalNumber<const H extends NumberHints>(hints: H): Type<number | undefined> {\n return Types.custom<number | undefined, number | undefined, H>(undefined, { kind: \"number\", ...hints }) as Type<number | undefined>;\n}\n\ninterface NumberHints extends EntryOptions {\n readonly min?: number;\n readonly max?: number;\n readonly step?: number;\n readonly unit?: string;\n}\n\nexport function optionalColor(): Type<Color | undefined, NormalizedColor | undefined> {\n return Types.custom<Color | undefined, NormalizedColor | undefined>(undefined, {\n resolve: (v) => (v === undefined ? undefined : colorOps.resolve(v)),\n lerp: colorOps.lerp as (from: NormalizedColor | undefined, to: NormalizedColor | undefined, t: number) => NormalizedColor | undefined,\n kind: \"color\",\n });\n}\n\n/** A point, unset until given: tweening from unset starts at the origin, or snaps. */\nexport function optionalVector3(unset: \"origin\" | \"snap\"): Type<Vector3Input | undefined, Vector3 | undefined> {\n return Types.custom<Vector3Input | undefined, Vector3 | undefined>(undefined, {\n resolve: resolveOptionalVector3,\n lerp: (from, to, t) => lerpOptionalVector3(from, to, t, unset),\n kind: \"vector3\",\n });\n}\n\n/** Each of `keys` the state has set: what a scene descriptor takes. */\nexport function defined<T>(s: object, keys: readonly string[]): T {\n const out: Record<string, unknown> = {};\n for (const key of keys) {\n const value = (s as Record<string, unknown>)[key];\n if (value !== undefined) out[key] = value;\n }\n return out as T;\n}\n\n/** `{ type, ...defined(s, keys) }`. */\nexport function stated<T>(type: string, s: object, keys: readonly string[]): T {\n return { type, ...defined<object>(s, keys) } as T;\n}\n", "import type { LoaderFn } from \"@/assets/record\";\nimport { cameraOrbit, lerpColor3D, resolveColor3D } from \"@/attributes/render3d/orbit\";\nimport type { Color, NormalizedColor } from \"@/attributes/shape/fill/color/parser\";\nimport { Fills } from \"@/attributes/shape/fill/chain\";\nimport type { FillResolved } from \"@/attributes/shape/fill/union\";\nimport { gridGeometry3D, type Grid3DOptions } from \"@/components/builtins/three/grid-geometry3d\";\nimport type { BufferGeometry3D } from \"@/render3d/geometry\";\nimport { Graphics3D } from \"@/render3d/graphics3d\";\nimport { warmCanvas3D } from \"@/render3d/resources\";\nimport { resolveShadows3D, type PostEffect3D, type Shadows3D, type ToneMapping3D } from \"@/render3d/scene-settings\";\nimport { Scene3D } from \"@/render3d/scene3d\";\nimport type { Canvas3DFillResolved } from \"@/attributes/shape/fill/implementations/canvas3d\";\nimport { isSurfaceTexture3D, resolveSurfaceSource } from \"@/render3d/texture\";\nimport { forEachTexture3D } from \"@/render3d/walk\";\nimport type { Loader, RenderContext2D, Type, Values } from \"@/components/factory/api\";\nimport { Types } from \"@/components/factory/types\";\nimport { internalsOf } from \"@/components/factory/views\";\nimport * as Corners from \"@/components/modules/corners\";\nimport * as Paint from \"@/components/modules/paint\";\nimport { optional } from \"@/components/modules/three-entries\";\n\n/**\n * A viewport onto its 3D children: the default camera and light rig a scene\n * gets when it has none of its own, the floor grid, and the render settings.\n */\n\nfunction color3D(initial: Color): Type<Color, NormalizedColor> {\n return Types.custom<Color, NormalizedColor>(initial, { resolve: resolveColor3D, lerp: lerpColor3D });\n}\n\nexport const state = {\n orbit: Types.number(35, { step: 1, unit: \"°\" }),\n elevation: Types.number(20, { min: -89, max: 89, step: 1, unit: \"°\" }),\n zoom: Types.number(12, { min: 0.01, step: 0.1 }),\n fov: Types.custom(45),\n ambientIntensity: Types.custom(0.45),\n ambientColor: color3D(\"#ffffff\"),\n keyIntensity: Types.custom(2.4),\n keyColor: color3D(\"#ffffff\"),\n showGrid: Types.custom(false),\n gridSize: Types.custom(40),\n gridDivisions: Types.custom(40),\n gridMajorEvery: Types.custom(5),\n gridColor: color3D(\"#26292f\"),\n gridMajorColor: color3D(\"#363a42\"),\n showAxes: Types.custom(false),\n axisXColor: color3D(\"#c8404f\"),\n axisZColor: color3D(\"#2f6fd0\"),\n gridFade: Types.custom(0.55),\n gridFadeColor: color3D(\"#0b0d12\"),\n maxPixelRatio: Types.custom(2),\n antialias: Types.custom(true),\n shadows: Types.custom<Shadows3D>(false),\n tone: optional<ToneMapping3D>(),\n exposure: optional<number>(),\n post: optional<PostEffect3D | readonly PostEffect3D[]>(),\n};\n\nexport const commands = {\n /** Swing the default camera: only the angles given move. */\n orbitTo: { args: [\"orbit\", \"elevation\", \"zoom\"] as const },\n};\n\ntype ViewState = Values<typeof state> & { readonly fill: FillResolved[] };\n\nconst loadThreeRuntime: LoaderFn = async () => {\n await warmCanvas3D();\n};\n\n/**\n * The 3D runtime, warmed before the first frame, and whatever `extend` draws:\n * pass the `extend` your render hands {@link draw}, so its textures, models and\n * surfaces load before a frame needs them, as a 3D child's own drawing does.\n */\nexport function load(loader: Loader, extend?: (scene: Scene3D) => void): void {\n loader.task(\"three:runtime\", loadThreeRuntime);\n if (!extend) return;\n const scene = new Scene3D();\n extend(scene);\n const fill: Canvas3DFillResolved = { type: \"canvas3D\", scene };\n loader.fill(fill);\n}\n\nconst grids = new WeakMap<object, { readonly key: string; readonly geometry: BufferGeometry3D }>();\n\n/**\n * Your 3D children's scene with this view's settings, its grid, and the default\n * camera and lights where the scene has none; `extend` draws more into it last.\n * `null` when there is nothing to show.\n */\nexport function scene(ctx: RenderContext2D, s: ViewState, extend?: (scene: Scene3D) => void): Scene3D | null {\n const scene = ctx.scene3D();\n const hasChildren = scene.ops().length > 0;\n const shadows = resolveShadows3D(s.shadows);\n if (shadows) scene.shadows(shadows);\n if (s.tone !== undefined || s.exposure !== undefined) scene.tone({ mapping: s.tone, exposure: s.exposure });\n if (s.post !== undefined) scene.post(s.post);\n const fog = scene.fogDescriptor();\n if (fog && fog.color === undefined) {\n const base = baseColor(s.fill);\n if (base !== undefined) scene.fog({ ...fog, color: base });\n }\n if (s.showGrid) {\n scene.draw(new Graphics3D().line({\n geometry: gridOf(internalsOf(ctx).host, s),\n segments: true,\n material: { type: \"lineBasic\", vertexColors: true, toneMapped: false },\n }));\n }\n if (!extend && scene.isEmpty() && !hasChildren) return null;\n if (scene.cameraDescriptor() === null) {\n scene.perspective({ fov: s.fov, orbit: cameraOrbit(s.orbit), elevation: s.elevation, distance: s.zoom });\n }\n if (!scene.ops().some((op) => op.kind === \"light\")) {\n scene\n .light({ type: \"ambient\", intensity: s.ambientIntensity, color: s.ambientColor })\n .light({ type: \"directional\", intensity: s.keyIntensity, color: s.keyColor }, { position: [4, 6, 3] })\n .light({ type: \"directional\", intensity: s.keyIntensity * 0.35, color: s.keyColor }, { position: [-5, -2, -4] });\n }\n extend?.(scene);\n return scene.isEmpty() ? null : scene;\n}\n\n/** The box painted, with the scene as its top fill layer. */\nexport function draw(ctx: RenderContext2D, s: ViewState & Parameters<typeof Paint.draw>[1] & Values<typeof Corners.state>, extend?: (scene: Scene3D) => void): void {\n const built = scene(ctx, s, extend);\n const internals = internalsOf(ctx);\n if (built && !internals.probing) {\n built.assertBalanced();\n // A surface texture draws a detached 2D node: it renders in this node's scope.\n const host = internals.host as unknown as { attachDetached(node: object): void };\n forEachTexture3D(built, (texture) => {\n if (!isSurfaceTexture3D(texture)) return;\n const source = resolveSurfaceSource(texture.source);\n if (source.kind === \"node\") host.attachDetached(source.node);\n });\n }\n const fill = built ? [...s.fill, ...Fills.canvas3D(built, { maxPixelRatio: s.maxPixelRatio, antialias: s.antialias })] : s.fill;\n Paint.draw(ctx, s, Corners.rect(ctx.size, s), { fill: fill as never });\n}\n\nfunction gridOf(host: object, s: ViewState): BufferGeometry3D {\n const options: Grid3DOptions = {\n size: s.gridSize,\n divisions: Math.max(1, Math.round(s.gridDivisions)),\n majorEvery: Math.max(1, Math.round(s.gridMajorEvery)),\n minorColor: s.gridColor,\n majorColor: s.gridMajorColor,\n axisXColor: s.axisXColor,\n axisZColor: s.axisZColor,\n showAxes: s.showAxes,\n fadeTo: fadeColor(s),\n fade: s.gridFade,\n };\n const key = JSON.stringify(options);\n let kept = grids.get(host);\n if (kept?.key !== key) grids.set(host, kept = { key, geometry: gridGeometry3D(options) });\n return kept.geometry;\n}\n\n/** The grid fades into the first visible solid fill, so it melts into the background. */\nfunction fadeColor(s: ViewState): Color {\n for (const layer of s.fill as unknown as readonly ({ type?: string; color?: unknown } | null)[]) {\n if (layer?.type !== \"solid\") continue;\n const color = layer.color;\n if (typeof color === \"string\") return color;\n if (Array.isArray(color) && (color[3] ?? 1) > 0) return color as Color;\n }\n return s.gridFadeColor;\n}\n\nfunction baseColor(fill: readonly FillResolved[]): Color | undefined {\n for (const layer of fill) {\n if (layer && (layer as { type?: string }).type === \"solid\") return (layer as unknown as { color: Color }).color;\n }\n return undefined;\n}\n", "import type { BufferGeometry3D } from \"@/render3d/geometry\";\nimport type { Color } from \"@/attributes/shape/fill/color/parser\";\n\nimport { resolveColor3D } from \"@/attributes/render3d/orbit\"\n\n/** How the ground plane is drawn — the fields the Canvas 3D's schema states. */\nexport interface Grid3DOptions {\n /** Total extent of the grid, in scene units. It spans `±size / 2` on both axes. */\n size: number\n /** How many cells across. One minor line per cell boundary. */\n divisions: number\n /** Every Nth minor line is drawn in {@link majorColor} instead. */\n majorEvery: number\n minorColor: Color\n majorColor: Color\n /** The line through `z = 0`. Red by convention, in every 3D tool there is. */\n axisXColor: Color\n /** The line through `x = 0`. Blue by the same convention. */\n axisZColor: Color\n /** Whether to draw the two axis lines at all. */\n showAxes: boolean\n /**\n * What the far edge fades into — the colour behind the grid.\n *\n * Fading is done by lerping each vertex's *colour* toward this rather than by\n * dropping its alpha, because a vertex colour is RGB and there is nowhere to\n * put a per-vertex alpha in the descriptor (see {@link BufferGeometry3D}). Over\n * an opaque background the two are indistinguishable, and this one costs no\n * blending and no sort order.\n *\n * A {@link Color} rather than a string, because it is read off the node's fill\n * stack now — see `Canvas3DView.fadeColor` — and a resolved paint holds its\n * colour as a normalized tuple.\n */\n fadeTo: Color\n /**\n * How much of the way to the edge the fade has finished, in `[0, 1]`.\n *\n * `0` disables it. Distance is measured radially from the origin rather than\n * per-axis, so the grid dissolves into a disc — which is what stops the four\n * corners from staying visible long after the edges have gone, and is why the\n * horizon in a viewport reads as a horizon rather than as a square table.\n */\n fade: number\n}\n\n/**\n * The ground plane, as one buffer of line segments.\n *\n * **One geometry, not three.** The minor lines, the major lines and the two axes\n * differ only in colour, and colour is a vertex attribute — so drawing them as\n * three ops with three materials would be three draw calls, three cache entries\n * and three chances for the sort order to put an axis under the grid it is\n * supposed to sit in. Baking the colour per vertex makes it one op with\n * `vertexColors: true` on a single unlit material, which is also the only way to\n * get the distance fade at all: it varies *along* each line, and a material's\n * colour is uniform across the primitive it paints.\n *\n * The returned arrays are freshly allocated, so the caller is expected to cache\n * them — see {@link Canvas3DView}, which does, and marks the result\n * `staticData` on the strength of it. Rebuilding this every frame would be\n * ~10k floats of allocation and a full re-upload for a picture that only changes\n * when somebody edits a field.\n */\nexport function gridGeometry3D(options: Grid3DOptions): BufferGeometry3D {\n const { size, divisions, majorEvery, showAxes, fade } = options\n\n const half = size / 2\n const step = size / divisions\n const minor = rgb(options.minorColor)\n const major = rgb(options.majorColor)\n const axisX = rgb(options.axisXColor)\n const axisZ = rgb(options.axisZColor)\n const fadeTo = rgb(options.fadeTo)\n\n const position: number[] = []\n const color: number[] = []\n\n /** One segment, with each end faded by its own distance from the origin. */\n const segment = (\n ax: number,\n az: number,\n bx: number,\n bz: number,\n tint: readonly [number, number, number]\n ): void => {\n // y is a hair above zero for the axes only — see the call sites. Everything\n // here is the same plane otherwise.\n position.push(ax, 0, az, bx, 0, bz)\n pushFaded(color, tint, fadeTo, fadeAt(ax, az, half, fade))\n pushFaded(color, tint, fadeTo, fadeAt(bx, bz, half, fade))\n }\n\n for (let i = 0; i <= divisions; i++) {\n const offset = -half + i * step\n // The index counted from the centre line, so \"every Nth\" is symmetrical\n // about the origin rather than about the grid's far corner — otherwise the\n // major lines drift off-centre on an odd division count.\n const fromCentre = Math.abs(i - divisions / 2)\n const isCentre = Math.abs(offset) < step / 2\n // The centre lines are the axes' own, so they are skipped here when the axes\n // are being drawn and left as ordinary major lines when they are not.\n if (isCentre && showAxes) continue\n\n const tint =\n Number.isInteger(fromCentre) && fromCentre % majorEvery === 0\n ? major\n : minor\n\n segment(offset, -half, offset, half, tint)\n segment(-half, offset, half, offset, tint)\n }\n\n if (showAxes) {\n // The X axis runs along x with z pinned at 0, and vice versa. Same plane as\n // the grid: they replace the two centre lines rather than sitting over them,\n // so there is nothing to z-fight with.\n segment(-half, 0, half, 0, axisX)\n segment(0, -half, 0, half, axisZ)\n }\n\n return {\n type: \"buffer\",\n position: new Float32Array(position),\n color: new Float32Array(color),\n // Nothing here is lit — a grid is emissive by nature — so there are no\n // normals to derive and asking for them would be a wasted pass.\n computeNormals: false,\n // True only because the caller caches: see this module's note.\n staticData: true,\n }\n}\n\n/**\n * How faded a point is, in `[0, 1]`, where 1 is fully the background.\n *\n * Squared falloff rather than linear, because a linear ramp over a plane seen at\n * a shallow angle reads as a hard edge — most of the ramp is compressed into the\n * last few pixels before the horizon. The square spends more of its range near\n * the camera, where the perspective is stretching it back out.\n */\nfunction fadeAt(\n x: number,\n z: number,\n half: number,\n fade: number\n): number {\n if (fade <= 0) return 0\n const distance = Math.hypot(x, z) / half\n const start = 1 - fade\n if (distance <= start) return 0\n const t = Math.min(1, (distance - start) / Math.max(fade, 1e-6))\n return t * t\n}\n\n/** Push one vertex colour, lerped `t` of the way from `tint` toward `fadeTo`. */\nfunction pushFaded(\n out: number[],\n tint: readonly [number, number, number],\n fadeTo: readonly [number, number, number],\n t: number\n): void {\n out.push(\n tint[0] + (fadeTo[0] - tint[0]) * t,\n tint[1] + (fadeTo[1] - tint[1]) * t,\n tint[2] + (fadeTo[2] - tint[2]) * t\n )\n}\n\n/**\n * A colour as the linear RGB triple a vertex attribute holds.\n *\n * `resolveColor3D` gives normalized sRGB; three reads vertex colours as\n * **linear**, so each channel is converted. Skipping this is the classic\n * washed-out-grid bug: an sRGB 0.16 uploaded as linear paints at about 0.4,\n * which is why a grid that should whisper ends up shouting.\n */\nfunction rgb(value: Color): [number, number, number] {\n const [r, g, b] = resolveColor3D(value)\n return [srgbToLinear(r), srgbToLinear(g), srgbToLinear(b)]\n}\n\n/** The sRGB transfer function, inverted. three's own `SRGBToLinear`. */\nfunction srgbToLinear(channel: number): number {\n return channel < 0.04045\n ? channel * 0.0773993808\n : Math.pow(channel * 0.9478672986 + 0.0521327014, 2.4)\n}\n"],
5
+ "mappings": "sIA+BA,SAASA,GAAeC,EAAQ,CAC5B,MAAO,CAAE,QAASA,EAAO,SAAUA,EAAO,WAAYA,EAAO,YAAaA,CAAK,CACnF,CAKA,SAASC,GAAiBC,EAA4BC,EAAc,CAChE,MAAO,CACH,QAASD,EAAE,KAAOC,EAAG,QACrB,SAAUD,EAAE,KAAOC,EAAG,SACtB,WAAYD,EAAE,QAAUC,EAAG,WAC3B,YAAaD,EAAE,QAAUC,EAAG,YAEpC,CAEA,SAASC,GAAiBF,EAA4BC,EAAc,CAChE,MAAO,CACH,QAASD,EAAE,MAAQC,EAAG,QACtB,SAAUD,EAAE,OAASC,EAAG,SACxB,WAAYD,EAAE,MAAQC,EAAG,WACzB,YAAaD,EAAE,OAASC,EAAG,YAEnC,CAUM,SAAUE,GACZL,EACAM,EACAC,EACAC,EAA8B,CAE9B,GAAIA,EAASR,CAAK,EACd,OAAOD,GAAYC,CAAK,EAG5B,IAAMG,EAAiBI,GAAYR,GAAYO,CAAQ,EACjDG,EAAMT,EAIZ,GAAI,YAAaS,GAAO,aAAcA,GAAO,eAAgBA,GAAO,gBAAiBA,EAAK,CACtF,IAAMP,EAAIF,EACV,MAAO,CACH,QAASE,EAAE,SAAWC,EAAG,QACzB,SAAUD,EAAE,UAAYC,EAAG,SAC3B,WAAYD,EAAE,YAAcC,EAAG,WAC/B,YAAaD,EAAE,aAAeC,EAAG,YAEzC,CACA,MAAI,QAASM,GAAO,WAAYA,EACrBR,GAAcD,E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MC,CAAC,EAAG,CAAE,KAAMH,CAAa,CAAE,CACzE,CAEA,SAASW,GAAOO,EAAcf,EAAY,CACtC,IAAMuB,EAAyB,CAC3B,KAAMvB,EAAE,SACR,UAAW,KAAK,IAAI,EAAG,KAAK,MAAMA,EAAE,aAAa,CAAC,EAClD,WAAY,KAAK,IAAI,EAAG,KAAK,MAAMA,EAAE,cAAc,CAAC,EACpD,WAAYA,EAAE,UACd,WAAYA,EAAE,eACd,WAAYA,EAAE,WACd,WAAYA,EAAE,WACd,SAAUA,EAAE,SACZ,OAAQwB,GAAUxB,CAAC,EACnB,KAAMA,EAAE,UAENyB,EAAM,KAAK,UAAUF,CAAO,EAC9BG,EAAO5B,GAAM,IAAIiB,CAAI,EACzB,OAAIW,GAAM,MAAQD,GAAK3B,GAAM,IAAIiB,EAAMW,EAAO,CAAE,IAAAD,EAAK,SAAUE,GAAeJ,CAAO,CAAC,CAAE,EACjFG,EAAK,QAChB,CAGA,SAASF,GAAUxB,EAAY,CAC3B,QAAW4B,KAAS5B,EAAE,KAA2E,CAC7F,GAAI4B,GAAO,OAAS,QAAS,SAC7B,IAAMC,EAAQD,EAAM,MAEpB,GADI,OAAOC,GAAU,UACjB,MAAM,QAAQA,CAAK,IAAMA,EAAM,CAAC,GAAK,GAAK,EAAG,OAAOA,CAC5D,CACA,OAAO7B,EAAE,aACb,CAEA,SAASM,GAAUT,EAA6B,CAC5C,QAAW+B,KAAS/B,EAChB,GAAI+B,GAAUA,EAA4B,OAAS,QAAS,OAAQA,EAAsC,KAGlH",
6
+ "names": ["makeUniform", "value", "fromTopBottom", "v", "fb", "fromLeftRight", "resolveCorners", "fallback", "previous", "isScalar", "obj", "lerpCorners", "from", "to", "t", "lerp", "isUniformCorners", "c", "eq", "cornerRadiusOps", "value", "previous", "resolveCorners", "v", "from", "to", "t", "lerpCorners", "lerpNumber", "isUniformCorners", "cornerStyleOps", "value", "previous", "resolveCorners", "v", "from", "to", "t", "lerpCorners", "f", "g", "isUniformCorners", "lerpCornerScalarStyle", "resolveEffectAxis", "axis", "sameEffectAxis", "a", "b", "av", "bv", "resolveEffectColor", "color", "parseColor", "sameEffectColor", "EFFECT_OPTION_KEYS", "withEffectOptions", "base", "options", "out", "key", "value", "scalarOptions", "arg", "lerpColor", "from", "to", "t", "colorOps", "resolve", "value", "r", "g", "b", "a", "alpha", "byte", "parseColor", "channel", "CENTER", "param", "o", "normalize", "v", "options", "step", "a", "b", "t", "same", "sameVector", "KIND_LERP", "lerpNumber", "lerpColor", "resolveEffectColor", "lerpVector2", "KIND_EQUALS", "sameEffectColor", "sameEffectAxis", "paramLerp", "def", "kind", "fallback", "from", "to", "effectDataOf", "spec", "entries", "lerps", "name", "equals", "derived", "out", "g", "lerp", "custom", "data", "x", "y", "eq", "copyDefault", "value", "buildEffect", "arg", "scalarOptions", "withEffectOptions", "json", "describeSpec", "params", "index", "stored", "optional", "key", "resolveMotionBlurAlignment", "alignment", "motionBlurSpec", "param", "a", "b", "t", "lerpNumber", "lerpVector2", "resolveEffectAxis", "motionBlurEffect", "effectDataOf", "ASCII_CHARSETS", "resolveAsciiCharset", "charset", "asciiSpec", "param", "asciiEffect", "effectDataOf", "BlendModes", "NodeBlendModes", "BLEND_MODE_HASH", "mode", "i", "getBlendModeHash", "blend", "warned", "warnOnce", "scope", "message", "key", "flattenValue", "name", "value", "flat", "out", "entry", "normalizeUniforms", "input", "pairs", "u", "a", "b", "lerpUniformValue", "t", "lerpNumber", "len", "_", "uniformValuesEqual", "v", "i", "lerpUniformRecord", "from", "to", "uniformRecordsEqual", "aKeys", "other", "isWgslShader", "shader", "WGSL_CONTRACT", "shaderContractOf", "blurSpec", "param", "blurEffect", "effectDataOf", "directionalBlurSpec", "param", "directionalBlurEffect", "effectDataOf", "grayscaleSpec", "param", "grayscaleEffect", "effectDataOf", "pixelateSpec", "param", "pixelateEffect", "effectDataOf", "bulgeSpec", "param", "CENTER", "bulgeEffect", "effectDataOf", "magnifySpec", "param", "CENTER", "magnifyEffect", "effectDataOf", "bloomSpec", "param", "bloomEffect", "effectDataOf", "vintageSpec", "param", "vintageEffect", "effectDataOf", "chromaticAberrationSpec", "param", "chromaticAberrationEffect", "effectDataOf", "invertSpec", "param", "invertEffect", "effectDataOf", "scatterSpec", "param", "scatterEffect", "effectDataOf", "posterizeSpec", "param", "posterizeEffect", "effectDataOf", "shaderSpec", "param", "BlendModes", "effect", "contract", "shaderContractOf", "from", "to", "t", "near", "lerpUniformRecord", "normalizeUniforms", "a", "b", "uniformRecordsEqual", "shaderEffect", "effectDataOf", "outlineSpec", "param", "outlineEffect", "effectDataOf", "dropShadowSpec", "param", "dropShadowEffect", "effectDataOf", "vignetteSpec", "param", "vignetteEffect", "effectDataOf", "grainSpec", "param", "grainEffect", "effectDataOf", "sharpenSpec", "param", "sharpenEffect", "effectDataOf", "edgesSpec", "param", "edgesEffect", "effectDataOf", "thresholdSpec", "param", "thresholdEffect", "effectDataOf", "radialBlurSpec", "param", "CENTER", "radialBlurEffect", "effectDataOf", "halftoneSpec", "param", "halftoneEffect", "effectDataOf", "ditherSpec", "param", "ditherEffect", "effectDataOf", "duotoneSpec", "param", "duotoneEffect", "effectDataOf", "curvesSpec", "param", "from", "to", "t", "x", "y", "tx", "ty", "lerpNumber", "a", "b", "i", "curvesEffect", "effectDataOf", "colorAdjustmentSpec", "param", "colorAdjustmentEffect", "effectDataOf", "rgbShiftSpec", "param", "rgbShiftEffect", "effectDataOf", "scanlinesSpec", "param", "scanlinesEffect", "effectDataOf", "blockDisplaceSpec", "param", "blockDisplaceEffect", "effectDataOf", "bitCrushSpec", "param", "bitCrushEffect", "effectDataOf", "streakSpec", "param", "streakEffect", "effectDataOf", "GLOW_RAMP_COLORS", "GLOW_RAMP_STOPS", "glowSpec", "from", "to", "t", "derived", "param", "BlendModes", "a", "b", "c", "i", "lerpColor", "resolveEffectColor", "sameEffectColor", "s", "lerpNumber", "glowEffect", "effectDataOf", "oilPaintSpec", "param", "oilPaintEffect", "effectDataOf", "waveSpec", "param", "CENTER", "waveEffect", "effectDataOf", "twirlSpec", "param", "CENTER", "twirlEffect", "effectDataOf", "progressiveBlurSpec", "param", "CENTER", "progressiveBlurEffect", "effectDataOf", "kaleidoscopeSpec", "param", "CENTER", "kaleidoscopeEffect", "effectDataOf", "glassSpec", "param", "glassEffect", "effectDataOf", "lutSpec", "param", "lutEffect", "effectDataOf", "BUILT_INS", "blurSpec", "blurEffect", "directionalBlurSpec", "directionalBlurEffect", "grayscaleSpec", "grayscaleEffect", "pixelateSpec", "pixelateEffect", "bulgeSpec", "bulgeEffect", "magnifySpec", "magnifyEffect", "bloomSpec", "bloomEffect", "vintageSpec", "vintageEffect", "chromaticAberrationSpec", "chromaticAberrationEffect", "invertSpec", "invertEffect", "scatterSpec", "scatterEffect", "posterizeSpec", "posterizeEffect", "motionBlurSpec", "motionBlurEffect", "shaderSpec", "shaderEffect", "outlineSpec", "outlineEffect", "dropShadowSpec", "dropShadowEffect", "vignetteSpec", "vignetteEffect", "grainSpec", "grainEffect", "sharpenSpec", "sharpenEffect", "edgesSpec", "edgesEffect", "thresholdSpec", "thresholdEffect", "radialBlurSpec", "radialBlurEffect", "halftoneSpec", "halftoneEffect", "ditherSpec", "ditherEffect", "duotoneSpec", "duotoneEffect", "curvesSpec", "curvesEffect", "colorAdjustmentSpec", "colorAdjustmentEffect", "rgbShiftSpec", "rgbShiftEffect", "scanlinesSpec", "scanlinesEffect", "blockDisplaceSpec", "blockDisplaceEffect", "bitCrushSpec", "bitCrushEffect", "asciiSpec", "asciiEffect", "streakSpec", "streakEffect", "glowSpec", "glowEffect", "oilPaintSpec", "oilPaintEffect", "waveSpec", "waveEffect", "twirlSpec", "twirlEffect", "progressiveBlurSpec", "progressiveBlurEffect", "kaleidoscopeSpec", "kaleidoscopeEffect", "glassSpec", "glassEffect", "lutSpec", "lutEffect", "EFFECTS", "spec", "data", "SPECS", "dataFor", "type", "resolveEffect", "effect", "effectSpec", "type", "SPECS", "descriptors", "describeEffect", "spec", "out", "describeSpec", "effectDescriptors", "hasEffect", "dataFor", "effectSurface", "effect", "surface", "declareEffect", "assets", "lerpEffect", "from", "to", "t", "data", "lerped", "source", "key", "EFFECT_OPTION_KEYS", "target", "COMPONENTS", "COLOR_COMPONENTS", "resolveShaderProperties", "pack", "overrides", "out", "id", "property", "supplied", "parts", "componentsOf", "component", "uniform", "value", "warn", "where", "flat", "toUniformValue", "names", "index", "name", "asFinite", "asColor", "asFloats", "g", "b", "a", "parseColor", "v", "point", "warned", "message", "EffectChain", "_EffectChain", "list", "effect", "options", "buildEffect", "blurSpec", "directionalBlurSpec", "pixelateSpec", "grayscaleSpec", "bulgeSpec", "magnifySpec", "bloomSpec", "vintageSpec", "chromaticAberrationSpec", "invertSpec", "scatterSpec", "posterizeSpec", "motionBlurSpec", "outlineSpec", "dropShadowSpec", "vignetteSpec", "lutSpec", "grainSpec", "sharpenSpec", "edgesSpec", "thresholdSpec", "radialBlurSpec", "halftoneSpec", "ditherSpec", "duotoneSpec", "curvesSpec", "mode", "fields", "withEffectOptions", "o", "scalarOptions", "spread", "rgbShiftSpec", "scanlinesSpec", "blockDisplaceSpec", "bitCrushSpec", "asciiSpec", "oilPaintSpec", "streakSpec", "glowSpec", "pack", "source", "uniforms", "resolveShaderProperties", "normalizeUniforms", "base", "waveSpec", "twirlSpec", "progressiveBlurSpec", "kaleidoscopeSpec", "glassSpec", "Effects", "resolveChainEffects", "effects", "resolveAll", "out", "item", "resolveEffect", "i", "resolved", "effectsOps", "from", "to", "t", "maxLen", "result", "a", "b", "lerpEffect", "isBackdropEffect", "effect", "NONE", "backdropEffects", "effects", "foregroundShaderEffects", "e", "effectSurface", "withOptions", "base", "options", "out", "FillChain", "_FillChain", "list", "color", "src", "fit", "crop", "zoom", "anchor", "matrix", "preset", "filters", "common", "timestamp", "playing", "trimStart", "trimEnd", "playStart", "speed", "loop", "duration", "colors", "stops", "start", "end", "center", "radius", "startAngle", "size", "density", "seed", "basis", "octaves", "frequency", "lacunarity", "gain", "offset", "angle", "contrast", "source", "pack", "uniforms", "textures", "values", "resolved", "resolveShaderProperties", "normalizeUniforms", "gap", "strokeWidth", "spacing", "divisions", "subdivisions", "subdivisionWidth", "scene", "maxPixelRatio", "antialias", "Fills", "resolveChainFill", "fill", "item", "DEFAULT_DIVISIONS", "DEFAULT_SUBDIVISIONS", "DEFAULT_STROKE_WIDTH", "MINOR_WIDTH_RATIO", "gridFill", "prop", "raw", "strokeWidth", "parseColor", "a", "b", "t", "lerpNumber", "exposureFilter", "from", "to", "t", "lerpNumber", "a", "b", "blurFilter", "from", "to", "t", "lerpNumber", "a", "b", "grayscaleFilter", "from", "to", "t", "lerpNumber", "a", "b", "alphaFilter", "from", "to", "t", "lerpNumber", "a", "b", "colorMatrixFilter", "from", "to", "t", "v", "i", "lerpNumber", "a", "b", "curvesFilter", "from", "to", "t", "x", "y", "tx", "ty", "lerpNumber", "a", "b", "i", "colorAdjustmentFilter", "from", "to", "t", "lerpNumber", "a", "b", "posterizeTimeFilter", "from", "to", "t", "lerpNumber", "a", "b", "echoFilter", "from", "to", "t", "lerpNumber", "a", "b", "FILTERS", "exposureFilter", "blurFilter", "grayscaleFilter", "alphaFilter", "colorMatrixFilter", "curvesFilter", "colorAdjustmentFilter", "posterizeTimeFilter", "echoFilter", "VIDEO_ONLY", "isPixelFilter", "type", "hasFilter", "hasEffect", "lerpFilter", "from", "to", "t", "data", "lerpEffect", "declareFilter", "filter", "assets", "declareEffect", "filterSurface", "effectSurface", "lerpFilterArray", "from", "to", "t", "maxLen", "result", "a", "b", "lerpFilter", "scalarFilter", "arg", "key", "fromEffect", "chain", "AdjustmentChain", "list", "filter", "Ctor", "options", "radius", "amount", "matrix", "EffectChain", "VideoAdjustmentChain", "fps", "Adjustments", "VideoAdjustments", "ImageFilters", "VideoFilters", "resolveChainAdjustments", "filters", "ALIGNMENTS", "ALIGNMENT_KEYS", "resolveOne", "value", "named", "alignmentOps", "lerpVector2", "props", "present", "k", "alignmentKey", "rect", "target", "a", "getTarget", "getRect", "insetsOps", "value", "previous", "from", "to", "t", "lerpNumber", "outerWidth", "outerHeight", "pad", "innerWidth", "innerHeight", "resolveMediaPreset", "preset", "legacyFilters", "chain", "adjustments", "resolveChainAdjustments", "lerpMediaPreset", "a", "b", "t", "from", "to", "lerpFilterArray", "lerpNumber", "declareMediaPreset", "assets", "adjustment", "declareFilter", "NO_CROP", "CENTER", "resolveImagePlacement", "prop", "insetsOps", "alignmentOps", "lerpImagePlacement", "a", "b", "t", "lerpNumber", "lerpVector2", "imageFill", "crop", "anchor", "preset", "filters", "resolveMediaPreset", "lerpMediaPreset", "fill", "assets", "declareMediaPreset", "resolveVideoTimestamp", "fill", "elapsed", "sourceDuration", "start", "posterizeTimestamp", "rawTimestamp", "played", "sourceTimeFor", "trimEndFor", "hasDuration", "end", "loop", "cycleLength", "rawLoopDuration", "loopDuration", "cycle", "ping", "linear", "timestamp", "posterize", "f", "grid", "videoFill", "crop", "anchor", "preset", "filters", "prop", "resolveImagePlacement", "resolveMediaPreset", "a", "b", "t", "lerpImagePlacement", "lerpNumber", "lerpMediaPreset", "assets", "declareMediaPreset", "PathBuilder", "x", "y", "x1", "y1", "x2", "y2", "rx", "ry", "rotation", "largeArc", "sweep", "arc", "cx", "cy", "from", "resolveArc", "start", "pointOn", "partial", "steps", "step", "direction", "i", "p", "angle", "rad", "SHAPE_KINDS", "Graphics2D", "_Graphics2D", "state", "resolved", "PathBuilder", "fills", "strokes", "shadows", "options", "opacity", "effects", "effectsOps", "rotation", "center", "scale", "op", "ops", "next", "resolveSurfaceSource", "source", "isDataTexture3D", "texture", "isSurfaceTexture3D", "resolveTexture3D", "texture3DSource", "looksLikeAssetPath", "value", "DEFAULT_SIZE", "resolveFill3D", "fill", "options", "looksLikeAssetPath", "entry", "rasterized", "isSurfaceSourceValue", "surfaceFor", "isTextureDescriptor", "isSolidLayer", "source", "width", "height", "Graphics2D", "fillIdentity", "value", "bag", "lerpFill3D", "from", "to", "t", "start", "asPlainColor", "end", "lerpColor", "normalize", "color", "parseColor", "objectIds", "objectCounter", "list", "prototype", "id", "key", "warned", "development", "isDevelopment", "warnInert3D", "key", "message", "inspectDrawable3D", "op", "isDevelopment", "params", "warnInert3D", "materials", "material", "DRAWABLE_KINDS", "TRANSFORM_KEYS", "MATERIAL_SHORTHAND_KEYS", "SHORTHAND_KEYS", "pickTransform", "source", "bag", "out", "key", "resolveMaterialShorthand3D", "material", "fill", "resolveFill3D", "value", "pickGeometry", "type", "Graphics3D", "op", "inspectDrawable3D", "geometry", "transform", "options", "instances", "points", "closed", "segments", "stroke", "opacity", "resolved", "lineBuffer", "paint", "src", "animation", "override", "lineBuffers", "lineRevision", "kept", "holds", "flattenPoints", "i", "point", "v", "buffer", "x", "y", "z", "RenderContext3D", "resolveShadows3D", "value", "Scene3D", "RenderContext3D", "state", "graphics", "ops", "scope", "i", "op", "light", "transform", "camera", "options", "fog", "environment", "warnInert3D", "settings", "resolveShadows3D", "effects", "added", "effect", "DRAWABLE_KINDS", "verb", "canvas3DResourceKey", "kind", "src", "parseCanvas3DResourceKey", "key", "rest", "split", "warmup", "resourceLoader", "registerCanvas3DWarmup", "fn", "registerCanvas3DResourceLoader", "warmCanvas3D", "canvas3DResourceLoader", "hasCanvas3DBackend", "TEXTURE_KEYS", "isTextureLike", "value", "forEachTexture3D", "g3", "visit", "uniforms", "bag", "key", "looksLikeAssetPath", "material", "list", "entry", "op", "Scene3D", "effect", "GRADIENT_TYPES", "isGradientType", "type", "canCoerce", "a", "b", "aColorish", "bColorish", "evenStops", "count", "_", "i", "colorToGradient", "color", "opacity", "blend", "space", "targetType", "stopCount", "n", "colors", "stops", "common", "retypeGradient", "g", "coercePair", "aIsColor", "bIsColor", "grad", "expanded", "ga", "gb", "colorFill", "prop", "parseColor", "a", "b", "t", "lerpNumber", "sampleRamp", "ramp", "position", "colors", "stops", "last", "hi", "lo", "span", "lerpColor", "colorAt", "k", "first", "count", "sameStops", "a", "b", "s", "i", "lerpColorRamp", "t", "c", "own", "n", "x", "y", "toNormalized", "c", "parseColor", "linearGradientFill", "prop", "_", "i", "a", "b", "t", "lerpColorRamp", "lerpVector2", "toNormalized", "c", "parseColor", "radialGradientFill", "prop", "_", "i", "a", "b", "t", "lerpColorRamp", "lerpVector2", "lerpNumber", "toNormalized", "c", "parseColor", "conicGradientFill", "prop", "_", "i", "a", "b", "t", "lerpColorRamp", "lerpVector2", "lerpNumber", "noiseFill", "prop", "raw", "parseColor", "a", "b", "t", "lerpNumber", "toNormalized", "c", "parseColor", "BLACK", "WHITE", "toFrequency", "f", "fractalNoiseFill", "prop", "colors", "_", "i", "a", "b", "t", "lerpVector2", "lerpNumber", "lerpColorRamp", "d", "s", "stripeFill", "prop", "parseColor", "a", "b", "t", "lerpNumber", "DEFAULT_RADIUS", "DEFAULT_SPACING", "dotGridFill", "prop", "raw", "parseColor", "a", "b", "t", "lerpNumber", "MAX_TEXTURES", "resolveTextures", "textures", "out", "texture", "withContract", "shader", "contract", "shaderContractOf", "texturesEqual", "a", "b", "t", "i", "shaderFill", "prop", "normalizeUniforms", "lerpUniformRecord", "uniformRecordsEqual", "fill", "assets", "declare3DResources", "g3", "assets", "forEachTexture3D", "value", "isSurfaceTexture3D", "source", "resolveSurfaceSource", "src", "texture3DSource", "geometry", "declareLoader", "op", "Scene3D", "declareEnvironment", "environment", "hdrKind", "face", "resourceLoads", "kind", "load", "canvas3DResourceLoader", "key", "canvas3DResourceKey", "byKey", "fn", "canvas3DFill", "prop", "a", "b", "t", "fill", "assets", "declare3DResources", "FILLS", "colorFill", "linearGradientFill", "radialGradientFill", "conicGradientFill", "noiseFill", "fractalNoiseFill", "stripeFill", "dotGridFill", "gridFill", "shaderFill", "imageFill", "videoFill", "canvas3DFill", "get", "name", "data", "resolveFill", "prop", "Scene3D", "resolved", "space", "UNSET_MEDIA_FILL", "canLerpFill", "a", "b", "canCoerce", "lerpFill", "t", "clamped", "ca", "cb", "coercePair", "scaleOpacity", "fill", "factor", "declareFill", "assets", "fillOps", "resolveChainFill", "from", "to", "maxLength", "result", "i", "f", "tf", "resolveShadow", "prop", "previous", "fillOps", "lerpShadow", "from", "to", "t", "lerpVector2", "shadowOps", "p", "i", "len", "result", "f", "tf", "resolveStrokeAlign", "align", "fallback", "DEFAULT_CAP_SCALE", "isStrokeMarker", "end", "resolveStrokeCap", "cap", "resolveStrokeEnd", "resolveStrokeJoin", "join", "resolveStroke", "prop", "previous", "dash", "raw", "fillOps", "lerpDashArray", "from", "to", "t", "fArray", "tArray", "len", "result", "i", "fVal", "tVal", "lerpStroke", "strokeOps", "p", "f", "tf", "clamp", "value", "min", "max", "clamp01", "t", "descriptions", "describeEase", "ease", "description", "descriptions", "easeDescription", "DEFAULT_EASE", "PI", "parseConfig", "params", "inMath", "t", "config", "s", "a", "p", "x", "describeConfig", "direction", "linear", "describeEase", "clamp01", "easeIn", "easeOut", "easeInOut", "inOutConfig", "clamp", "value", "min", "max", "curveSegments", "points", "segments", "i", "p0", "p3", "before", "after", "c1", "c2", "bezier", "a", "b", "c", "d", "t", "mt", "curveSegmentT", "segment", "x", "low", "high", "mid", "isEaseCurve", "isFinitePoint", "y", "curveEase", "describeEase", "last", "candidate", "EASE_KINDS", "easeOfSpec", "spec", "lookup", "known", "linear", "easeIn", "easeOut", "easeInOut", "key", "isEaseCurve", "curveEase", "fn", "registered", "STANDARD", "specOfEase", "ease", "description", "easeDescription", "direction", "type", "overshoot", "amplitude", "period", "tuning", "config", "name", "value", "segmentsOf", "RampChain", "_RampChain", "segments", "keysOf", "from", "to", "duration", "options", "specOf", "segment", "ramp", "hold", "ease", "spec", "specOfEase", "previous", "values", "s", "keys", "push", "key", "last", "withEase", "fill", "head", "at", "i", "tail", "before", "sum", "isRamp", "p", "LINEAR", "linear", "resolved", "resolveRamp", "length", "clip", "cached", "crossed", "time", "easeOfSpec", "b", "sampleRamp", "fallback", "span", "lerpNumber", "sampleParam", "staticValue", "first", "paramKey", "lerpParam", "t", "equalsParam", "a", "audioParamOps", "value", "INTEGRATION_STEP", "MAX_CELLS", "speedTables", "speedTableOf", "speed", "sourceLength", "step", "byLength", "cells", "size", "rate", "table", "integrateSpeedToClipTime", "upper", "end", "cell", "sourceTimeAtClipElapsed", "clipElapsed", "lo", "hi", "mid", "scalarParam", "arg", "key", "isRamp", "AudioEffectChain", "_AudioEffectChain", "list", "effect", "options", "value", "frequency", "q", "rate", "depth", "delay", "feedback", "mix", "AudioEffects", "resolveAudioEffects", "effects", "gainEffect", "from", "to", "t", "lerpParam", "a", "b", "equalsParam", "highPassEffect", "from", "to", "t", "lerpParam", "a", "b", "equalsParam", "lowPassEffect", "from", "to", "t", "lerpParam", "a", "b", "equalsParam", "tremoloEffect", "from", "to", "t", "lerpParam", "a", "b", "equalsParam", "echoEffect", "from", "to", "t", "lerpParam", "a", "b", "equalsParam", "BUILT_IN_EFFECTS", "gainEffect", "highPassEffect", "lowPassEffect", "tremoloEffect", "echoEffect", "AudioEffectRegistry", "_AudioEffectRegistry", "type", "data", "from", "to", "t", "maxLen", "result", "i", "b", "audioEffectsOps", "resolveAudioEffects", "isProjective", "m", "MIN_W", "safeW", "w", "identity", "translation", "tx", "ty", "multiply", "m1", "m2", "multiplyProjective", "g1", "h1", "i1", "g2", "h2", "i2", "applyToPoint", "p", "x", "y", "invert", "invertProjective", "det", "inv", "a", "b", "c", "d", "e", "f", "g", "h", "i", "A", "C", "E", "cameraMatrix", "vx", "vy", "lookAt", "zoom", "heading", "rad", "cos", "sin", "nodeLocalMatrix", "cx", "cy", "rotation", "scale", "pivotX", "pivotY", "NO_PROJECTION_3D", "hasProjection3D", "facesAway", "rotationX", "rotationY", "nodeProjectedMatrix", "ca", "sa", "cb", "sb", "cz", "cc", "sc", "B", "D", "G", "H", "invP", "fx", "fy", "lerpLookAt", "from", "to", "t", "out", "lerpNumber", "multiplyAffine3", "a", "b", "out", "a0", "a1", "a2", "a3", "nodeSpaceMatrix", "cx", "cy", "rotation", "scale", "pivotX", "pivotY", "p", "rad", "ca", "sa", "cb", "sb", "cz", "cc", "sc", "r00", "r01", "r02", "r10", "r11", "r12", "r20", "r21", "r22", "fx", "fy", "spaceViewMatrix", "cam", "se", "ce", "r0", "r1", "r2", "d0", "d1", "d2", "f0", "f1", "f2", "tx", "ty", "tz", "spaceScreenMatrix", "view", "invP", "wx", "wy", "w0", "k", "c00", "c01", "c10", "c11", "vx", "vy", "m", "spacePlane", "box", "hw", "hh", "us", "vs", "corners", "i", "u", "v", "nl", "NEAR_W", "EDGE_ON", "cameraSide", "plane", "dx", "dy", "dz", "side", "nearCoverage", "inFront", "nearCutPolygon", "screen", "margin", "g", "h", "square", "w", "wa", "wb", "t", "SIDE_EPS", "sideOf", "camSide", "front", "back", "d", "facing", "farness", "compareInSpace", "s", "isCoplanar", "fa", "fb", "rootCamera", "props", "space3dOps", "lerpLookAt", "camera", "point", "x", "y", "z", "vz", "px", "py", "vector", "ux", "uy", "PAIRWISE_LIMIT", "spacePaintOrder", "planes", "_", "after", "blockers", "j", "r", "order", "done", "next", "far", "f", "size2DOps", "value", "from", "to", "t", "lerpNumber", "props", "sizeInputOps", "input", "availableSize", "contentSize", "TEXT_STYLE_KEYS", "TEXT_SHAPING_KEYS", "EMPTY_TEXT_STYLE", "textOps", "value", "lerp", "preset", "mergeStyle", "resolveStyle", "lerpStyle", "lerpFontSize", "styleProps", "flatten", "applyCase", "from", "to", "t", "pre", "maxPre", "suf", "maxSuf", "removeLen", "addLen", "totalLen", "prefix", "suffix", "split", "localT", "midLen", "name", "getTypographyPreset", "base", "over", "out", "key", "style", "previous", "s", "fillOps", "strokeOps", "shadowOps", "lerpOptionalNumber", "spans", "walk", "span", "inherited", "merged", "child", "WORD_CHAR", "text", "textCase", "prev", "ch", "recase", "mapped", "a", "b", "lerpNumber", "PROPERTY_META", "getPropertyMeta", "instance", "mostDerived", "symbol", "chain", "proto", "result", "at", "p", "m", "i", "declareMembers", "ctor", "members", "key", "register", "property", "opts", "target", "propertyKey", "fallback", "mapper", "tween", "editor", "meta", "list", "_observer", "_setObserver", "observer", "previous", "PropSlot", "initial", "_host", "_name", "value", "fn", "snap", "ToCommand", "target", "props", "duration", "easing", "clamp01", "toCommand", "loopPasses", "loop", "loopRepeats", "loopSpan", "duration", "fill", "loopPhase", "elapsed", "passes", "capped", "index", "t", "clamp01", "SETTLES", "settling", "command", "settles", "isCommand", "x", "makeCommand", "target", "at", "duration", "easing", "fromValue", "t", "clamp01", "driveCommand", "apply", "loopCommand", "loop", "fill", "one", "loopPasses", "loopSpan", "value", "loopPhase", "elapsed", "e", "dt", "done", "commandSequence", "commands", "sum", "c", "props", "cursor", "local", "commandParallel", "max", "progress", "prepareNumericTween", "target", "to", "keys", "k", "from", "end", "t", "i", "prepareNumericCellTween", "cells", "createContext", "defaultValue", "name", "ContextMap", "_ContextMap", "entries", "ctx", "value", "next", "getPropSlot", "obj", "name", "ensureCells", "COMMAND_META", "getCommandMeta", "instance", "mostDerived", "command", "options", "target", "propertyKey", "method", "key", "list", "m", "LAYOUT_SLOT", "VAR_PREFIX", "PRESENCE_PREFIX", "STRUCTURE_SLOT", "observeSlots", "observer", "fn", "previous", "_setObserver", "unobserved", "slotLabel", "slot", "inertCommand", "target", "duration", "inertStepper", "elapsed", "e", "dt", "registerProp", "host", "field", "options", "slot", "PropSlot", "cells", "ensureCells", "value", "applyProp", "initial", "collectProperties", "result", "key", "captureLayer", "layer", "slots", "saveState", "popState", "applySnapshotLayer", "snap", "restoreAnimated", "duration", "easing", "stepper", "driveCommand", "t", "target", "createNodeTime", "advanceNodeTime", "time", "total", "HOSTS_OF", "Node", "_Node", "props", "identity", "hidden", "locked", "meta", "getPropertyMeta", "propsVal", "initial", "flat", "c", "child", "why", "refusal", "_parent", "_observer", "ContextMap", "ctx", "childProp", "field", "options", "applyProp", "value", "slot", "mapper", "extFn", "unset", "read", "collectProperties", "slots", "key", "val", "args", "toCommand", "at", "duration", "easing", "makeCommand", "inertCommand", "to", "inertStepper", "numCells", "numFrom", "numEnd", "customLerps", "stringSnaps", "extVal", "targetVal", "tweenFn", "from", "t", "lerp", "prepareNumericCellTween", "hasCustom", "hasSnaps", "apply", "easedT", "fn", "elapsed", "e", "dt", "declared", "saveState", "layer", "popState", "applySnapshotLayer", "restoreAnimated", "createNodeTime", "total", "advanceNodeTime", "scope", "first", "next", "childScope", "parent", "node", "assets", "index", "PropSlot", "STRUCTURE_SLOT", "children", "i", "removed", "declareMembers", "command", "AssetNotLoadedError", "assetType", "src", "hint", "declareHint", "measureItem", "item", "constraints", "measurer", "size", "extentOf", "input", "available", "measureRun", "items", "horizontal", "gap", "space", "measurer", "main", "cross", "hugsMain", "hugsCross", "bounded", "n", "sizes", "gapScales", "item", "sanitizeGapScale", "totalGap", "sum", "w", "fixedMain", "deepest", "i", "measureItem", "fillCross", "size", "withCross", "free", "flexSum", "sanitizeFlex", "share", "measureFillOnHugAxis", "depth", "extent", "measureWrap", "crossGap", "limit", "step", "lines", "widest", "stack", "start", "end", "placeRun", "align", "inner", "mainFraction", "crossFraction", "line", "lineStart", "boxes", "count", "weight", "gapAfter", "lead", "spread", "weightAt", "at", "across", "fromReadingOrder", "left", "top", "value", "clamp", "measureFreeform", "items", "space", "measurer", "constraints", "sizes", "hug", "item", "size", "measureItem", "placeFreeform", "inner", "align", "measureGrid", "items", "columns", "columnGap", "rowGap", "space", "measurer", "count", "track", "placements", "autoPlace", "rowCount", "max", "p", "bounded", "equalRow", "rows", "sizes", "item", "i", "width", "span", "constraints", "size", "measureItem", "grow", "tops", "top", "height", "cells", "spannedRows", "sum", "h", "placeGrid", "inner", "cell", "taken", "isFree", "row", "col", "colSpan", "rowSpan", "r", "c", "take", "gap", "short", "from", "CENTRE", "arrange", "settings", "items", "box", "measurer", "inner", "insetsOps", "place", "measure", "b", "space", "flow", "measureMode", "from", "to", "lerpSize", "placeMode", "fromBoxes", "t", "i", "lerpNumber", "reusable", "hug", "fits", "contentBox", "sizing", "constraints", "padding", "width", "outerFor", "height", "size", "hugged", "collapsedRun", "sized", "s", "lerp", "a", "mode", "measureFreeform", "grid", "measureGrid", "mainGap", "crossGap", "horizontal", "run", "measureWrap", "measureRun", "placeGrid", "align", "alignOf", "placeFreeform", "placeRun", "freeSlot", "alignmentOps", "gap", "input", "max", "available", "sizeInputOps", "laid", "measured", "hugs", "near", "flowOps", "value", "ZERO", "resolveVector3", "input", "v", "lerpVector3", "from", "to", "t", "lerpNumber", "vector3Ops", "value", "resolveOptionalVector3", "lerpOptionalVector3", "unset", "lerpEuler3", "euler3Ops", "order", "IDENTITY_QUATERNION", "slerpQuaternion", "x", "y", "z", "w", "dot", "normalizeQuaternion", "theta", "sinTheta", "a", "b", "q", "length", "quaternionFromEuler", "euler", "half", "cx", "sx", "cy", "sy", "cz", "sz", "quaternionOps", "Clip", "state", "resolved", "PathBuilder", "op", "attributeProperty", "fallback", "mapper", "tween", "kind", "opts", "property", "fillProperty", "fillOps", "effectsProperty", "effectsOps", "insetsProperty", "insetsOps", "alignmentProperty", "alignmentOps", "flowProperty", "flowOps", "optionalVector3Property", "unset", "resolveOptionalVector3", "from", "to", "t", "lerpOptionalVector3", "quaternionProperty", "quaternionOps", "audioParamProperty", "audioParamOps", "audioEffectsProperty", "audioEffectsOps", "primeMotion", "history", "x", "y", "rotation", "scale", "at", "createMotionHistory", "sampleMotion", "state", "now", "dt", "prev", "vx", "vy", "measureDetached", "parent", "child", "pass", "scope", "constraints", "size", "SIZE_PHASE", "addChildAtAnimated", "index", "duration", "easing", "animation", "isNumericW", "isNumericH", "origW", "origH", "setup", "targetOpacity", "detached", "tweenW", "tweenH", "targetW", "targetH", "sizeProps", "grow", "fade", "commandSequence", "commandParallel", "driveCommand", "t", "restore", "removeChildAtAnimated", "setupDone", "lw", "lh", "shrink", "done", "reparentAnimated", "node", "newParent", "half", "oldParent", "exitFade", "exitShrink", "enterGrow", "enterFade", "inNewParent", "TRANSFORM_3D_KEYS", "expandTransform3D", "props", "bag", "source", "field", "prop", "value", "rotateOffset", "x", "y", "rotationDeg", "ox", "oy", "rad", "cos", "sin", "localMatrix", "cx", "cy", "rotation", "scale", "pivot", "width", "height", "projection", "NO_PROJECTION_3D", "pivotX", "pivotY", "nodeProjectedMatrix", "worldAnchors", "m", "halfW", "halfH", "at", "p", "applyToPoint", "IDENTITY", "identity", "spaceRootFrame", "root", "camera", "view", "spaceViewMatrix", "spaceScreenMatrix", "spacePlane", "spaceChildFrame", "parent", "child", "own", "multiplyAffine3", "screen", "box", "inkBox", "plane", "side", "edgeOn", "cameraSide", "coverage", "nearCoverage", "local", "paints", "undo", "invert", "multiply", "nearCutClip", "spaceFrameOf", "node", "chain", "frame", "spaceFrameForChildren", "spaceChildOrder", "frames", "f", "_", "i", "spacePaintOrder", "b", "NEAR_CUT_MARGIN", "polygon", "nearCutPolygon", "path", "PathBuilder", "reach", "p", "Clip", "computeSpaceRects", "parentRect", "thisRect", "x", "y", "ox", "oy", "applyBackdropEffects", "ctx", "effects", "clip", "width", "height", "backdrop", "backdropEffects", "applyContentEffectScope", "body", "foreground", "foregroundShaderEffects", "hasForeground", "NO_SPACE_RECTS", "ORIGIN_2D", "NO_HANDLES", "SLOT_PROJECTION", "slotProjection", "placement", "DEFAULT_FLOW", "NO_CONTENT", "Node2D", "_Node2D", "Node", "parent", "_observer", "all", "i", "c", "props", "size2DOps", "expandTransform3D", "sizeInputOps", "alignmentOps", "alignmentKey", "raw", "getTarget", "pivot", "x", "y", "sizeVal", "to", "duration", "easing", "explicitPivot", "assets", "at", "r", "o", "primeMotion", "PropSlot", "LAYOUT_SLOT", "children", "axis", "defaultSize", "args", "path", "target", "targetAnchor", "destination", "positioned", "aimed", "aim", "sampler", "pathOps", "PathBuilder", "length", "first", "last", "fit", "origin", "t", "frame", "point", "_stated", "rest", "factor", "angle", "turns", "ox", "oy", "rotateOffset", "slot", "multiply", "localMatrix", "cx", "cy", "_child", "size", "space", "box", "flowOps", "rotation", "scale", "own", "applyToPoint", "_prop", "_at", "plane", "paint", "nodeSpaceMatrix", "p", "width", "height", "multiplyAffine3", "local", "anchors", "worldAnchors", "opacity", "n", "id", "anchor", "findNode2D", "a", "world", "toParent", "invert", "child", "index", "addChildAtAnimated", "removed", "removeChildAtAnimated", "createMotionHistory", "sampleMotion", "ctx", "s", "slotOpacity", "projection", "hasProjection3D", "clip", "tolerance", "b", "effects", "applyBackdropEffects", "body", "applyContentEffectScope", "camera", "spaceRootFrame", "frames", "spaceChildFrame", "order", "spaceChildOrder", "_", "cut", "computeSpaceRects", "error", "AssetNotLoadedError", "clipped", "facesAway", "rect", "current", "scope", "pending", "inner", "insetsOps", "settings", "measured", "boxes", "warning", "constraints", "padding", "newParent", "old", "reparentAnimated", "declareMembers", "property", "effectsProperty", "insetsProperty", "alignmentProperty", "lerpPerspective", "v", "from", "command", "data", "stated", "key", "root", "findUnder", "found", "frameIn", "host", "node", "there", "here", "inverse", "offset", "NodeAudio", "_NodeAudio", "Node", "props", "c", "authored", "structuralPathOf", "to", "duration", "easing", "key", "TWEEN_REFUSED", "declareMembers", "audioParamProperty", "property", "audioEffectsProperty", "busPathOf", "node", "spanOf", "stops", "parent", "stopOf", "busPathTo", "bus", "findBusById", "from", "id", "root", "searchBus", "child", "found", "effects", "span", "parts", "current", "parentSpaceOf", "node", "parent", "VECTOR_SUGAR", "Node3D", "_Node3D", "Node", "props", "distributeVectors", "args", "stated", "value", "to", "duration", "easing", "quaternion", "identityQuaternion", "space", "_child", "ctx", "child", "assets", "scene", "Scene3D", "declare3DResources", "declareMembers", "property", "quaternionProperty", "optionalVector3Property", "command", "out", "key", "axes", "read", "i", "axis", "componentOf", "resolveVector3", "vector", "order", "data", "index", "NODE_META", "node", "type", "ctor", "descriptor", "getNodeDescriptor", "proto", "resolveShapePivot", "pivot", "alignmentOps", "SHAPE_ALIGNMENT_KEYS", "validateShapeAlignmentProps", "descriptor", "present", "k", "conflict", "stripShapeAlignmentKeys", "out", "resolveShapeAlignment", "width", "height", "alignmentKey", "target", "a", "resolvePivotPosition", "withRectDescriptor", "descriptor", "width", "height", "x", "y", "pivot", "resolveShapeAlignment", "stripShapeAlignmentKeys", "resolveShapePivot", "withEllipseDescriptor", "descriptor", "width", "height", "x", "y", "pivot", "resolveShapeAlignment", "stripShapeAlignmentKeys", "resolveShapePivot", "withPolygonDescriptor", "descriptor", "width", "height", "x", "y", "pivot", "resolveShapeAlignment", "stripShapeAlignmentKeys", "resolveShapePivot", "withPolygramDescriptor", "descriptor", "width", "height", "x", "y", "pivot", "resolveShapeAlignment", "stripShapeAlignmentKeys", "resolveShapePivot", "withLineDescriptor", "descriptor", "resolveShapePivot", "EPS", "containsClip", "clip", "point", "tolerance", "containsOps", "ops", "inside", "pending", "flush", "containsShape", "op", "s", "withRectDescriptor", "p", "toShapeLocal", "containsRect", "cornerRadiusOps", "withEllipseDescriptor", "containsEllipse", "withPolygonDescriptor", "containsPolyline", "polygonVertices", "withPolygramDescriptor", "polygramVertices", "withLineDescriptor", "nearPolyline", "local", "width", "height", "pivot", "px", "py", "dx", "dy", "rad", "cos", "sin", "rx", "ry", "radius", "halfW", "halfH", "maxR", "r", "sx", "sy", "ratio", "sweep", "startAngle", "clamped", "full", "norm", "withinSweep", "angleDeg", "lo", "span", "slack", "delta", "sides", "n", "step", "out", "i", "a", "k", "verts", "closed", "pointInPolygon", "j", "b", "pts", "last", "distanceToSegment", "lenSq", "t", "ExpressionError", "message", "source", "position", "path", "where", "DEG", "DOCUMENT_FUNCTIONS", "a", "DOCUMENT_CONSTANTS", "DOCUMENT_DIALECT", "name", "sortedKeys", "table", "OPERATORS", "isDigit", "ch", "tokenize", "source", "dialect", "tokens", "i", "start", "mark", "ExpressionError", "end", "parse", "refs", "index", "peek", "next", "addRef", "startsPrimary", "t", "parseAdditive", "left", "parseMultiplicative", "parseUnary", "operand", "parsePower", "base", "parsePrimary", "parseCall", "pos", "def", "args", "close", "min", "max", "want", "plural", "inner", "constant", "root", "trailing", "toNumber", "value", "compile", "parsed", "resolve", "path", "readOf", "name", "read", "ExpressionError", "emit", "node", "operand", "left", "right", "apply", "DOCUMENT_FUNCTIONS", "args", "a", "isSource", "value", "unescape", "STATIC", "walk", "path", "onString", "parts", "v", "i", "p", "rebuilt", "isPlainObject", "keys", "k", "out", "part", "bind", "resolve", "source", "at", "compile", "parse", "bindProps", "props", "literal", "bindings", "hasBindings", "key", "compiled", "collect", "REF", "renameRefs", "rename", "whole", "ref", "next", "parseSource", "source", "dialect", "DOCUMENT_DIALECT", "parse", "isSource", "expressionOps", "unescape", "e", "compile", "bind", "bindProps", "collect", "renameRefs", "sortedKeys", "PROP_EVOLUTION", "declarePropEvolution", "ctor", "evolution", "propEvolutionOf", "proto", "migrateNodeProps", "registry", "type", "props", "applyPropEvolution", "changes", "deprecated", "out", "write", "isExpression", "value", "expressionOps", "convert", "key", "at", "hook", "from", "to", "target", "current", "next", "message", "SPAN_KEYS", "RICHTEXT_BLOCK_KEYS", "applyGraphicsTextDefaults", "graphics", "style", "ambient", "hasShapingDefaults", "EMPTY_TEXT_STYLE", "ops", "next", "op", "effective", "effectiveStyle", "patched", "patchText", "patchRichText", "variant", "textOps", "key", "TEXT_SHAPING_KEYS", "state", "fillUnset", "spans", "patchSpans", "spanStyle", "i", "target", "keys", "current", "out", "value", "CanvasRenderContext2D", "style", "EMPTY_TEXT_STYLE", "textOps", "graphics", "applyGraphicsTextDefaults", "state", "effects", "target", "width", "height", "draw", "pixelRatio", "ZERO_SIZE", "NullRenderContext", "CanvasRenderContext2D", "graphics", "callback", "width", "height", "draw", "state", "op", "_options", "clip", "_viewport", "_centerOn", "_zoom", "_heading", "clipOf", "shape", "clip", "Clip", "op", "piece", "data", "makeTimeline", "args", "duration", "easing", "node", "targets", "frame", "options", "t", "src", "seconds", "pieces", "SILENT", "leaf", "command", "pure", "elapsed", "placed", "parts", "offsets", "max", "part", "i", "s", "timedOf", "host", "p", "run", "runCommand", "settles", "fixed", "sum", "flexible", "each", "cursor", "timed", "n", "step", "_", "name", "meta", "getCommandMeta", "m", "method", "built", "SOUNDS", "commandSoundsOf", "commandOf", "settling", "driveCommand", "sounds", "TYPE_DEF", "isTypeLike", "value", "defOf", "entry", "NODE", "pass", "withPass", "node", "scope", "room", "run", "outer", "decided", "markDecided", "takeDecided", "currentPass", "measureChild", "max", "p", "constraints", "measured", "size", "childViews", "ChildViewImpl", "keyOf", "box", "childView", "targets", "name", "args", "view", "nodeOfView", "nodeViews", "NO_FRAME", "NodeViewImpl", "reader", "fields", "target", "key", "value", "Node2D", "frameIn", "nodeView", "byReader", "nodeOfNodeView", "found", "referenced", "id", "known", "rootOf", "findIn", "at", "child", "hit", "setKeyLookup", "lookup", "stateViewPrototype", "keys", "references", "entries", "proto", "stateView", "shape", "snapshot", "out", "MeasurerImpl", "host", "text", "font", "RenderContextImpl", "probing", "graphics", "g", "composite", "options", "stencil", "content", "op", "paint", "Graphics2D", "rect", "scene", "Scene3D", "Node3D", "camera", "style", "body", "outline", "clipOf", "component", "PROBE_PASS", "NullRenderContext", "internalsOf", "ctx", "lowering", "spec", "Base", "ownsDefault", "builtIn", "getPropertyMeta", "m", "entries", "k", "e", "defOf", "defaults", "key", "value", "own", "checkEvolution", "references", "def", "stateViewPrototype", "factoryDefault", "componentBase", "l", "s", "Componentized", "args", "props", "given", "stateView", "built", "asBuilt", "builderState", "authored", "child", "part", "ctx", "self", "context", "parent", "provided", "memo", "p", "i", "map", "assets", "declareEntry", "loaderOf", "allowed", "rule", "matches", "namesOf", "frame", "duration", "easing", "finishComponent", "Generated", "pascal", "proto", "deleteUpTo", "trees", "property", "inherited", "base", "entry", "method", "entrance", "cmd", "timeline", "makeTimeline", "nodeView", "piece", "snapshot", "commandOf", "declared", "run", "ownEasing", "names", "name", "data", "argsRecord", "stated", "settling", "isTypeLike", "resolveArgs", "command", "declarePropEvolution", "node", "componentValue", "isEntry", "from", "to", "at", "make", "nodeOfView", "_", "_sep", "c", "rules", "out", "kind", "stroke", "shadow", "tasks", "taskOf", "load", "task", "loaded", "family", "weight", "src", "trim", "options", "fills", "inkCorners", "child", "b", "local", "m", "multiply", "translation", "a", "worldAnchors", "spanOf", "points", "minX", "minY", "maxX", "maxY", "p", "toBounds", "span", "childInkBounds", "node", "mode", "children", "next", "NO_INSETS", "SIZE_KEYS", "setKeyLookup", "n", "getNodeDescriptor", "slotOf", "p", "component2d", "spec", "s", "l", "lowering", "Node2D", "defaults", "flows", "Generated", "componentBase", "props", "MeasurerImpl", "RenderContextImpl", "axis", "sizeInputOps", "given", "flow", "main", "declared", "value", "constraints", "scope", "m", "natural", "withPass", "childView", "takeDecided", "flowOps", "rect", "children", "box", "placements", "slots", "planes", "i", "child", "slot", "pass", "frame", "ctx", "clipOf", "r", "bounds", "childInkBounds", "NO_PROJECTION_3D", "probe", "local", "tolerance", "clip", "containsClip", "proto", "handles", "sizeOf", "node", "out", "prop", "handle", "at", "space", "finishComponent", "make", "def", "meaning", "kind", "options", "extra", "_private", "_typing", "_inherit", "rest", "attribute", "fallback", "mapper", "tween", "base", "initial", "defaultsOf", "shape", "out", "key", "defOf", "Types", "textOps", "values", "fillOps", "strokeOps", "shadowOps", "effectsOps", "colorOps", "cornerRadiusOps", "cornerStyleOps", "pathOps", "insetsOps", "alignmentOps", "vector2Ops", "sizeInputOps", "item", "resolve", "lerp", "src", "family", "corners_exports", "__export", "rect", "state", "state", "Types", "rect", "size", "s", "Graphics2D", "flow_exports", "__export", "layout", "measure", "state", "state", "Types", "flowOps", "NO_CONTENT", "pending", "padded", "s", "inset", "p", "measure", "measurer", "children", "node", "scope", "currentPass", "padding", "constraints", "space", "measured", "nodeOfView", "layout", "box", "kept", "inner", "insetsOps", "b", "commandsFor", "state", "commands", "paint_exports", "__export", "commands", "draw", "inset", "state", "FRACTION", "state", "Types", "commands", "commandsFor", "timeline", "s", "rest", "portion", "t", "head", "TRIMMED", "trimmed", "shape", "start", "end", "op", "copy", "castsShadowFromStroke", "layer", "draw", "ctx", "options", "c", "internalsOf", "out", "confining", "base", "outline", "clipOf", "clipped", "overlay", "stroke", "inset", "extra", "intrusion", "shapes_exports", "__export", "box", "state", "ellipse", "facePath", "outline", "polygon", "polygram", "rect", "unitPath", "ellipse", "size", "s", "Graphics2D", "polygon", "polygram", "box", "unitPath", "data", "w", "h", "pathOps", "p", "facePath", "b", "outline", "kind", "options", "shapeOutlinePixels", "aim_exports", "__export", "aim", "camera", "commands", "state", "state", "Types", "lerpVector2", "commands", "commandsFor", "aim", "ctx", "s", "target", "node", "nodeOfNodeView", "Node2D", "within", "internalsOf", "at", "camera", "ancestor", "AUTOFIT_PROBE_SIZE", "isStyleOnlySegment", "segment", "requireFontFamily", "descriptor", "family", "host", "hostTextFamily", "text", "withTextDescriptor", "width", "height", "x", "y", "pivot", "resolveShapeAlignment", "stripShapeAlignmentKeys", "resolveShapePivot", "text_layout_exports", "__export", "draw", "drawRichText", "load", "loadRichText", "measure", "measureRichText", "textStateOf", "casedText", "s", "src", "textOps", "measureGlyphs", "constraints", "scope", "width", "height", "pathOps", "wm", "hm", "measureFontSize", "paragraphs", "styled", "textSegments", "lineStyles", "measureStyledLines", "lineH", "intrinsicW", "line", "w", "run", "l", "resolvedW", "wraps", "lineSizes", "wrappedLineSizes", "intrinsicH", "h", "size", "n", "p", "countWrappedLines", "runs", "r", "text", "hasReveal", "revealStart", "revealEnd", "nodeFontSize", "AUTOFIT_PROBE_SIZE", "fill", "stroke", "cuts", "points", "c", "a", "b", "segments", "i", "start", "end", "seg", "textState", "declareGlyphAssets", "assets", "segment", "family", "fallback", "lines", "style", "parts", "maxWidth", "sizes", "tokens", "part", "space", "last", "lineW", "token", "paragraph", "fontSize", "fontFamily", "fontWeight", "letterSpacing", "fontStyle", "words", "word", "richRuns", "measureRich", "maxLineH", "totalW", "totalH", "finishLine", "lh", "richState", "declareRichAssets", "measure", "measurer", "s", "source", "node", "scope", "currentPass", "markDecided", "measureGlyphs", "drawn", "draw", "ctx", "c", "internalsOf", "out", "state", "textState", "segmented", "g", "Graphics2D", "stroke", "load", "loader", "declareGlyphAssets", "textStateOf", "last", "measureRichText", "measureRich", "drawRichText", "richState", "loadRichText", "declareRichAssets", "TextStyleToken", "createContext", "ThemeToken", "DataToken", "SeedToken", "provides", "context", "value", "text_style_exports", "__export", "current", "inherit", "provide", "provided", "state", "cascade", "use", "given", "variant", "textOps", "TextStyleToken", "inherit", "key", "options", "value", "state", "Types", "a", "b", "t", "provided", "provide", "s", "inherited", "provides", "current", "componentAudio", "spec", "l", "lowering", "NodeAudio", "Generated", "componentBase", "childView", "finishComponent", "setKeyLookup", "n", "getNodeDescriptor", "RenderContext3DImpl", "host", "graphics", "light", "transform", "camera", "fog", "environment", "component3d", "spec", "s", "l", "lowering", "Node3D", "Generated", "componentBase", "props", "ctx", "c", "assets", "declareEnvironment", "childView", "space", "finishComponent", "material_exports", "__export", "mesh", "points", "shorthand", "single", "state", "optional", "Types", "optionalNumber", "hints", "optionalColor", "v", "colorOps", "optionalVector3", "unset", "resolveOptionalVector3", "from", "to", "t", "lerpOptionalVector3", "defined", "s", "keys", "out", "key", "value", "stated", "type", "state", "optional", "Types", "lerpFill3D", "optionalColor", "SHORTHAND_KEYS", "shorthand", "s", "out", "key", "mesh", "geometry", "g3", "Graphics3D", "resolveMaterialShorthand3D", "single", "resolved", "POINTS_KEYS", "points", "material", "fill", "resolveFill3D", "view3d_exports", "__export", "commands", "draw", "load", "scene", "state", "gridGeometry3D", "options", "size", "divisions", "majorEvery", "showAxes", "fade", "half", "step", "minor", "rgb", "major", "axisX", "axisZ", "fadeTo", "position", "color", "segment", "ax", "az", "bx", "bz", "tint", "pushFaded", "fadeAt", "i", "offset", "fromCentre", "x", "z", "distance", "start", "t", "out", "value", "r", "g", "b", "resolveColor3D", "srgbToLinear", "channel", "color3D", "initial", "Types", "resolveColor3D", "lerpColor3D", "state", "optional", "commands", "loadThreeRuntime", "warmCanvas3D", "load", "loader", "extend", "scene", "Scene3D", "fill", "grids", "ctx", "s", "hasChildren", "shadows", "resolveShadows3D", "fog", "base", "baseColor", "Graphics3D", "gridOf", "internalsOf", "cameraOrbit", "op", "draw", "built", "internals", "host", "forEachTexture3D", "texture", "isSurfaceTexture3D", "source", "resolveSurfaceSource", "Fills", "rect", "options", "fadeColor", "key", "kept", "gridGeometry3D", "layer", "color"]
7
+ }