@revideo/2d 0.1.0

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