@twick/2d 0.14.21 → 0.15.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.
- package/dist/index.cjs +10806 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +4657 -0
- package/dist/index.d.ts +4657 -0
- package/dist/index.js +10768 -0
- package/dist/index.js.map +1 -0
- package/dist/jsx-runtime.d.mts +1 -0
- package/dist/jsx-runtime.d.ts +1 -0
- package/editor/index.css +24 -22
- package/editor/index.css.map +1 -0
- package/editor/index.d.ts +5 -0
- package/editor/index.js +472 -258
- package/editor/index.js.map +1 -1
- package/package.json +54 -27
- package/tsconfig.project.json +3 -2
- package/lib/code/CodeCursor.d.ts +0 -83
- package/lib/code/CodeCursor.d.ts.map +0 -1
- package/lib/code/CodeCursor.js +0 -306
- package/lib/code/CodeDiffer.d.ts +0 -28
- package/lib/code/CodeDiffer.d.ts.map +0 -1
- package/lib/code/CodeDiffer.js +0 -51
- package/lib/code/CodeFragment.d.ts +0 -42
- package/lib/code/CodeFragment.d.ts.map +0 -1
- package/lib/code/CodeFragment.js +0 -72
- package/lib/code/CodeHighlighter.d.ts +0 -71
- package/lib/code/CodeHighlighter.d.ts.map +0 -1
- package/lib/code/CodeHighlighter.js +0 -2
- package/lib/code/CodeMetrics.d.ts +0 -11
- package/lib/code/CodeMetrics.d.ts.map +0 -1
- package/lib/code/CodeMetrics.js +0 -29
- package/lib/code/CodeRange.d.ts +0 -41
- package/lib/code/CodeRange.d.ts.map +0 -1
- package/lib/code/CodeRange.js +0 -179
- package/lib/code/CodeScope.d.ts +0 -16
- package/lib/code/CodeScope.d.ts.map +0 -1
- package/lib/code/CodeScope.js +0 -72
- package/lib/code/CodeSelection.d.ts +0 -6
- package/lib/code/CodeSelection.d.ts.map +0 -1
- package/lib/code/CodeSelection.js +0 -13
- package/lib/code/CodeSignal.d.ts +0 -60
- package/lib/code/CodeSignal.d.ts.map +0 -1
- package/lib/code/CodeSignal.js +0 -194
- package/lib/code/CodeTokenizer.d.ts +0 -8
- package/lib/code/CodeTokenizer.d.ts.map +0 -1
- package/lib/code/CodeTokenizer.js +0 -50
- package/lib/code/DefaultHighlightStyle.d.ts +0 -3
- package/lib/code/DefaultHighlightStyle.d.ts.map +0 -1
- package/lib/code/DefaultHighlightStyle.js +0 -98
- package/lib/code/LezerHighlighter.d.ts +0 -22
- package/lib/code/LezerHighlighter.d.ts.map +0 -1
- package/lib/code/LezerHighlighter.js +0 -89
- package/lib/code/diff.d.ts +0 -31
- package/lib/code/diff.d.ts.map +0 -1
- package/lib/code/diff.js +0 -236
- package/lib/code/extractRange.d.ts +0 -17
- package/lib/code/extractRange.d.ts.map +0 -1
- package/lib/code/extractRange.js +0 -102
- package/lib/code/index.d.ts +0 -14
- package/lib/code/index.d.ts.map +0 -1
- package/lib/code/index.js +0 -14
- package/lib/components/Audio.d.ts +0 -14
- package/lib/components/Audio.d.ts.map +0 -1
- package/lib/components/Audio.js +0 -148
- package/lib/components/Bezier.d.ts +0 -23
- package/lib/components/Bezier.d.ts.map +0 -1
- package/lib/components/Bezier.js +0 -81
- package/lib/components/Circle.d.ts +0 -193
- package/lib/components/Circle.d.ts.map +0 -1
- package/lib/components/Circle.js +0 -178
- package/lib/components/Code.d.ts +0 -231
- package/lib/components/Code.d.ts.map +0 -1
- package/lib/components/Code.js +0 -325
- package/lib/components/CodeBlock.d.ts +0 -133
- package/lib/components/CodeBlock.d.ts.map +0 -1
- package/lib/components/CodeBlock.js +0 -461
- package/lib/components/CubicBezier.d.ts +0 -70
- package/lib/components/CubicBezier.d.ts.map +0 -1
- package/lib/components/CubicBezier.js +0 -81
- package/lib/components/Curve.d.ts +0 -204
- package/lib/components/Curve.d.ts.map +0 -1
- package/lib/components/Curve.js +0 -284
- package/lib/components/Grid.d.ts +0 -76
- package/lib/components/Grid.d.ts.map +0 -1
- package/lib/components/Grid.js +0 -91
- package/lib/components/Icon.d.ts +0 -59
- package/lib/components/Icon.d.ts.map +0 -1
- package/lib/components/Icon.js +0 -58
- package/lib/components/Img.d.ts +0 -118
- package/lib/components/Img.d.ts.map +0 -1
- package/lib/components/Img.js +0 -245
- package/lib/components/Knot.d.ts +0 -90
- package/lib/components/Knot.d.ts.map +0 -1
- package/lib/components/Knot.js +0 -68
- package/lib/components/Latex.d.ts +0 -39
- package/lib/components/Latex.d.ts.map +0 -1
- package/lib/components/Latex.js +0 -101
- package/lib/components/Layout.d.ts +0 -419
- package/lib/components/Layout.d.ts.map +0 -1
- package/lib/components/Layout.js +0 -706
- package/lib/components/Line.d.ts +0 -160
- package/lib/components/Line.d.ts.map +0 -1
- package/lib/components/Line.js +0 -346
- package/lib/components/Media.d.ts +0 -70
- package/lib/components/Media.d.ts.map +0 -1
- package/lib/components/Media.js +0 -493
- package/lib/components/Node.d.ts +0 -836
- package/lib/components/Node.d.ts.map +0 -1
- package/lib/components/Node.js +0 -1317
- package/lib/components/Path.d.ts +0 -20
- package/lib/components/Path.d.ts.map +0 -1
- package/lib/components/Path.js +0 -97
- package/lib/components/Polygon.d.ts +0 -113
- package/lib/components/Polygon.d.ts.map +0 -1
- package/lib/components/Polygon.js +0 -123
- package/lib/components/QuadBezier.d.ts +0 -62
- package/lib/components/QuadBezier.d.ts.map +0 -1
- package/lib/components/QuadBezier.js +0 -76
- package/lib/components/Ray.d.ts +0 -62
- package/lib/components/Ray.d.ts.map +0 -1
- package/lib/components/Ray.js +0 -96
- package/lib/components/Rect.d.ts +0 -114
- package/lib/components/Rect.d.ts.map +0 -1
- package/lib/components/Rect.js +0 -76
- package/lib/components/Rive.d.ts +0 -22
- package/lib/components/Rive.d.ts.map +0 -1
- package/lib/components/Rive.js +0 -117
- package/lib/components/SVG.d.ts +0 -178
- package/lib/components/SVG.d.ts.map +0 -1
- package/lib/components/SVG.js +0 -577
- package/lib/components/Shape.d.ts +0 -40
- package/lib/components/Shape.d.ts.map +0 -1
- package/lib/components/Shape.js +0 -134
- package/lib/components/Spline.d.ts +0 -89
- package/lib/components/Spline.d.ts.map +0 -1
- package/lib/components/Spline.js +0 -256
- package/lib/components/Txt.d.ts +0 -53
- package/lib/components/Txt.d.ts.map +0 -1
- package/lib/components/Txt.js +0 -173
- package/lib/components/TxtLeaf.d.ts +0 -21
- package/lib/components/TxtLeaf.d.ts.map +0 -1
- package/lib/components/TxtLeaf.js +0 -181
- package/lib/components/Video.d.ts +0 -69
- package/lib/components/Video.d.ts.map +0 -1
- package/lib/components/Video.js +0 -342
- package/lib/components/View2D.d.ts +0 -28
- package/lib/components/View2D.d.ts.map +0 -1
- package/lib/components/View2D.js +0 -93
- package/lib/components/index.d.ts +0 -29
- package/lib/components/index.d.ts.map +0 -1
- package/lib/components/index.js +0 -29
- package/lib/components/types.d.ts +0 -17
- package/lib/components/types.d.ts.map +0 -1
- package/lib/components/types.js +0 -2
- package/lib/curves/ArcSegment.d.ts +0 -26
- package/lib/curves/ArcSegment.d.ts.map +0 -1
- package/lib/curves/ArcSegment.js +0 -97
- package/lib/curves/CircleSegment.d.ts +0 -18
- package/lib/curves/CircleSegment.d.ts.map +0 -1
- package/lib/curves/CircleSegment.js +0 -52
- package/lib/curves/CubicBezierSegment.d.ts +0 -18
- package/lib/curves/CubicBezierSegment.d.ts.map +0 -1
- package/lib/curves/CubicBezierSegment.js +0 -55
- package/lib/curves/CurveDrawingInfo.d.ts +0 -11
- package/lib/curves/CurveDrawingInfo.d.ts.map +0 -1
- package/lib/curves/CurveDrawingInfo.js +0 -2
- package/lib/curves/CurvePoint.d.ts +0 -15
- package/lib/curves/CurvePoint.d.ts.map +0 -1
- package/lib/curves/CurvePoint.js +0 -2
- package/lib/curves/CurveProfile.d.ts +0 -7
- package/lib/curves/CurveProfile.d.ts.map +0 -1
- package/lib/curves/CurveProfile.js +0 -2
- package/lib/curves/KnotInfo.d.ts +0 -12
- package/lib/curves/KnotInfo.d.ts.map +0 -1
- package/lib/curves/KnotInfo.js +0 -2
- package/lib/curves/LineSegment.d.ts +0 -16
- package/lib/curves/LineSegment.d.ts.map +0 -1
- package/lib/curves/LineSegment.js +0 -45
- package/lib/curves/Polynomial.d.ts +0 -118
- package/lib/curves/Polynomial.d.ts.map +0 -1
- package/lib/curves/Polynomial.js +0 -259
- package/lib/curves/Polynomial2D.d.ts +0 -22
- package/lib/curves/Polynomial2D.d.ts.map +0 -1
- package/lib/curves/Polynomial2D.js +0 -45
- package/lib/curves/PolynomialSegment.d.ts +0 -39
- package/lib/curves/PolynomialSegment.d.ts.map +0 -1
- package/lib/curves/PolynomialSegment.js +0 -86
- package/lib/curves/QuadBezierSegment.d.ts +0 -17
- package/lib/curves/QuadBezierSegment.d.ts.map +0 -1
- package/lib/curves/QuadBezierSegment.js +0 -49
- package/lib/curves/Segment.d.ts +0 -9
- package/lib/curves/Segment.d.ts.map +0 -1
- package/lib/curves/Segment.js +0 -3
- package/lib/curves/UniformPolynomialCurveSampler.d.ts +0 -43
- package/lib/curves/UniformPolynomialCurveSampler.d.ts.map +0 -1
- package/lib/curves/UniformPolynomialCurveSampler.js +0 -73
- package/lib/curves/createCurveProfileLerp.d.ts +0 -32
- package/lib/curves/createCurveProfileLerp.d.ts.map +0 -1
- package/lib/curves/createCurveProfileLerp.js +0 -351
- package/lib/curves/getBezierSplineProfile.d.ts +0 -12
- package/lib/curves/getBezierSplineProfile.d.ts.map +0 -1
- package/lib/curves/getBezierSplineProfile.js +0 -137
- package/lib/curves/getCircleProfile.d.ts +0 -4
- package/lib/curves/getCircleProfile.d.ts.map +0 -1
- package/lib/curves/getCircleProfile.js +0 -44
- package/lib/curves/getPathProfile.d.ts +0 -3
- package/lib/curves/getPathProfile.d.ts.map +0 -1
- package/lib/curves/getPathProfile.js +0 -128
- package/lib/curves/getPointAtDistance.d.ts +0 -4
- package/lib/curves/getPointAtDistance.d.ts.map +0 -1
- package/lib/curves/getPointAtDistance.js +0 -15
- package/lib/curves/getPolylineProfile.d.ts +0 -4
- package/lib/curves/getPolylineProfile.d.ts.map +0 -1
- package/lib/curves/getPolylineProfile.js +0 -58
- package/lib/curves/getRectProfile.d.ts +0 -4
- package/lib/curves/getRectProfile.d.ts.map +0 -1
- package/lib/curves/getRectProfile.js +0 -57
- package/lib/curves/index.d.ts +0 -17
- package/lib/curves/index.d.ts.map +0 -1
- package/lib/curves/index.js +0 -17
- package/lib/decorators/canvasStyleSignal.d.ts +0 -5
- package/lib/decorators/canvasStyleSignal.d.ts.map +0 -1
- package/lib/decorators/canvasStyleSignal.js +0 -12
- package/lib/decorators/colorSignal.d.ts +0 -2
- package/lib/decorators/colorSignal.d.ts.map +0 -1
- package/lib/decorators/colorSignal.js +0 -9
- package/lib/decorators/compound.d.ts +0 -26
- package/lib/decorators/compound.d.ts.map +0 -1
- package/lib/decorators/compound.js +0 -49
- package/lib/decorators/computed.d.ts +0 -9
- package/lib/decorators/computed.d.ts.map +0 -1
- package/lib/decorators/computed.js +0 -18
- package/lib/decorators/defaultStyle.d.ts +0 -2
- package/lib/decorators/defaultStyle.d.ts.map +0 -1
- package/lib/decorators/defaultStyle.js +0 -14
- package/lib/decorators/filtersSignal.d.ts +0 -13
- package/lib/decorators/filtersSignal.d.ts.map +0 -1
- package/lib/decorators/filtersSignal.js +0 -73
- package/lib/decorators/index.d.ts +0 -11
- package/lib/decorators/index.d.ts.map +0 -1
- package/lib/decorators/index.js +0 -11
- package/lib/decorators/initializers.d.ts +0 -4
- package/lib/decorators/initializers.d.ts.map +0 -1
- package/lib/decorators/initializers.js +0 -27
- package/lib/decorators/nodeName.d.ts +0 -9
- package/lib/decorators/nodeName.d.ts.map +0 -1
- package/lib/decorators/nodeName.js +0 -13
- package/lib/decorators/signal.d.ts +0 -183
- package/lib/decorators/signal.d.ts.map +0 -1
- package/lib/decorators/signal.js +0 -285
- package/lib/decorators/spacingSignal.d.ts +0 -2
- package/lib/decorators/spacingSignal.d.ts.map +0 -1
- package/lib/decorators/spacingSignal.js +0 -15
- package/lib/decorators/vector2Signal.d.ts +0 -9
- package/lib/decorators/vector2Signal.d.ts.map +0 -1
- package/lib/decorators/vector2Signal.js +0 -15
- package/lib/index.d.ts +0 -9
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js +0 -9
- package/lib/jsx-dev-runtime.d.ts +0 -3
- package/lib/jsx-dev-runtime.d.ts.map +0 -1
- package/lib/jsx-dev-runtime.js +0 -3
- package/lib/jsx-runtime.d.ts +0 -12
- package/lib/jsx-runtime.d.ts.map +0 -1
- package/lib/jsx-runtime.js +0 -23
- package/lib/partials/Filter.d.ts +0 -82
- package/lib/partials/Filter.d.ts.map +0 -1
- package/lib/partials/Filter.js +0 -135
- package/lib/partials/Gradient.d.ts +0 -31
- package/lib/partials/Gradient.d.ts.map +0 -1
- package/lib/partials/Gradient.js +0 -63
- package/lib/partials/Pattern.d.ts +0 -13
- package/lib/partials/Pattern.d.ts.map +0 -1
- package/lib/partials/Pattern.js +0 -27
- package/lib/partials/ShaderConfig.d.ts +0 -81
- package/lib/partials/ShaderConfig.d.ts.map +0 -1
- package/lib/partials/ShaderConfig.js +0 -25
- package/lib/partials/index.d.ts +0 -5
- package/lib/partials/index.d.ts.map +0 -1
- package/lib/partials/index.js +0 -5
- package/lib/partials/types.d.ts +0 -35
- package/lib/partials/types.d.ts.map +0 -1
- package/lib/partials/types.js +0 -2
- package/lib/scenes/Scene2D.d.ts +0 -29
- package/lib/scenes/Scene2D.d.ts.map +0 -1
- package/lib/scenes/Scene2D.js +0 -180
- package/lib/scenes/index.d.ts +0 -4
- package/lib/scenes/index.d.ts.map +0 -1
- package/lib/scenes/index.js +0 -4
- package/lib/scenes/makeScene2D.d.ts +0 -5
- package/lib/scenes/makeScene2D.d.ts.map +0 -1
- package/lib/scenes/makeScene2D.js +0 -11
- package/lib/scenes/useScene2D.d.ts +0 -3
- package/lib/scenes/useScene2D.d.ts.map +0 -1
- package/lib/scenes/useScene2D.js +0 -5
- package/lib/tsconfig.build.tsbuildinfo +0 -1
- package/lib/utils/CanvasUtils.d.ts +0 -23
- package/lib/utils/CanvasUtils.d.ts.map +0 -1
- package/lib/utils/CanvasUtils.js +0 -138
- package/lib/utils/diff.d.ts +0 -31
- package/lib/utils/diff.d.ts.map +0 -1
- package/lib/utils/diff.js +0 -97
- package/lib/utils/index.d.ts +0 -3
- package/lib/utils/index.d.ts.map +0 -1
- package/lib/utils/index.js +0 -3
- package/lib/utils/is.d.ts +0 -8
- package/lib/utils/is.d.ts.map +0 -1
- package/lib/utils/is.js +0 -10
- package/lib/utils/makeSignalExtensions.d.ts +0 -4
- package/lib/utils/makeSignalExtensions.d.ts.map +0 -1
- package/lib/utils/makeSignalExtensions.js +0 -20
- package/lib/utils/video/ffmpeg-client.d.ts +0 -5
- package/lib/utils/video/ffmpeg-client.d.ts.map +0 -1
- package/lib/utils/video/ffmpeg-client.js +0 -32
- package/lib/utils/video/mp4-parser-manager.d.ts +0 -3
- package/lib/utils/video/mp4-parser-manager.d.ts.map +0 -1
- package/lib/utils/video/mp4-parser-manager.js +0 -55
- package/lib/utils/video/parser/index.d.ts +0 -2
- package/lib/utils/video/parser/index.d.ts.map +0 -1
- package/lib/utils/video/parser/index.js +0 -2
- package/lib/utils/video/parser/parser.d.ts +0 -21
- package/lib/utils/video/parser/parser.d.ts.map +0 -1
- package/lib/utils/video/parser/parser.js +0 -168
- package/lib/utils/video/parser/sampler.d.ts +0 -16
- package/lib/utils/video/parser/sampler.d.ts.map +0 -1
- package/lib/utils/video/parser/sampler.js +0 -56
- package/lib/utils/video/parser/segment.d.ts +0 -48
- package/lib/utils/video/parser/segment.d.ts.map +0 -1
- package/lib/utils/video/parser/segment.js +0 -239
- package/lib/utils/video/parser/sink.d.ts +0 -9
- package/lib/utils/video/parser/sink.d.ts.map +0 -1
- package/lib/utils/video/parser/sink.js +0 -22
- package/lib/utils/video/parser/utils.d.ts +0 -10
- package/lib/utils/video/parser/utils.d.ts.map +0 -1
- package/lib/utils/video/parser/utils.js +0 -22
- package/src/editor/NodeInspectorConfig.tsx +0 -76
- package/src/editor/PreviewOverlayConfig.tsx +0 -67
- package/src/editor/Provider.tsx +0 -93
- package/src/editor/SceneGraphTabConfig.tsx +0 -81
- package/src/editor/icons/CircleIcon.tsx +0 -7
- package/src/editor/icons/CodeBlockIcon.tsx +0 -8
- package/src/editor/icons/CurveIcon.tsx +0 -7
- package/src/editor/icons/GridIcon.tsx +0 -7
- package/src/editor/icons/IconMap.ts +0 -35
- package/src/editor/icons/ImgIcon.tsx +0 -8
- package/src/editor/icons/LayoutIcon.tsx +0 -9
- package/src/editor/icons/LineIcon.tsx +0 -7
- package/src/editor/icons/NodeIcon.tsx +0 -7
- package/src/editor/icons/RayIcon.tsx +0 -7
- package/src/editor/icons/RectIcon.tsx +0 -7
- package/src/editor/icons/ShapeIcon.tsx +0 -7
- package/src/editor/icons/TxtIcon.tsx +0 -8
- package/src/editor/icons/VideoIcon.tsx +0 -7
- package/src/editor/icons/View2DIcon.tsx +0 -10
- package/src/editor/index.css +0 -0
- package/src/editor/index.ts +0 -17
- package/src/editor/tree/DetachedRoot.tsx +0 -23
- package/src/editor/tree/NodeElement.tsx +0 -74
- package/src/editor/tree/TreeElement.tsx +0 -72
- package/src/editor/tree/TreeRoot.tsx +0 -10
- package/src/editor/tree/ViewRoot.tsx +0 -20
- package/src/editor/tree/index.module.scss +0 -38
- package/src/editor/tree/index.ts +0 -3
- package/src/editor/tsconfig.build.json +0 -5
- package/src/editor/tsconfig.json +0 -12
- package/src/editor/tsdoc.json +0 -4
- package/src/editor/vite-env.d.ts +0 -1
- package/src/lib/code/CodeCursor.ts +0 -445
- package/src/lib/code/CodeDiffer.ts +0 -78
- package/src/lib/code/CodeFragment.ts +0 -97
- package/src/lib/code/CodeHighlighter.ts +0 -75
- package/src/lib/code/CodeMetrics.ts +0 -47
- package/src/lib/code/CodeRange.test.ts +0 -74
- package/src/lib/code/CodeRange.ts +0 -216
- package/src/lib/code/CodeScope.ts +0 -101
- package/src/lib/code/CodeSelection.ts +0 -24
- package/src/lib/code/CodeSignal.ts +0 -327
- package/src/lib/code/CodeTokenizer.ts +0 -54
- package/src/lib/code/DefaultHighlightStyle.ts +0 -98
- package/src/lib/code/LezerHighlighter.ts +0 -113
- package/src/lib/code/diff.test.ts +0 -311
- package/src/lib/code/diff.ts +0 -319
- package/src/lib/code/extractRange.ts +0 -126
- package/src/lib/code/index.ts +0 -13
- package/src/lib/components/Audio.ts +0 -168
- package/src/lib/components/Bezier.ts +0 -105
- package/src/lib/components/Circle.ts +0 -266
- package/src/lib/components/Code.ts +0 -526
- package/src/lib/components/CodeBlock.ts +0 -576
- package/src/lib/components/CubicBezier.ts +0 -112
- package/src/lib/components/Curve.ts +0 -455
- package/src/lib/components/Grid.ts +0 -135
- package/src/lib/components/Icon.ts +0 -96
- package/src/lib/components/Img.ts +0 -319
- package/src/lib/components/Knot.ts +0 -157
- package/src/lib/components/Latex.ts +0 -122
- package/src/lib/components/Layout.ts +0 -1092
- package/src/lib/components/Line.ts +0 -429
- package/src/lib/components/Media.ts +0 -576
- package/src/lib/components/Node.ts +0 -1940
- package/src/lib/components/Path.ts +0 -137
- package/src/lib/components/Polygon.ts +0 -171
- package/src/lib/components/QuadBezier.ts +0 -100
- package/src/lib/components/Ray.ts +0 -125
- package/src/lib/components/Rect.ts +0 -187
- package/src/lib/components/Rive.ts +0 -156
- package/src/lib/components/SVG.ts +0 -797
- package/src/lib/components/Shape.ts +0 -143
- package/src/lib/components/Spline.ts +0 -344
- package/src/lib/components/Txt.test.tsx +0 -81
- package/src/lib/components/Txt.ts +0 -203
- package/src/lib/components/TxtLeaf.ts +0 -205
- package/src/lib/components/Video.ts +0 -461
- package/src/lib/components/View2D.ts +0 -98
- package/src/lib/components/__tests__/children.test.tsx +0 -142
- package/src/lib/components/__tests__/clone.test.tsx +0 -126
- package/src/lib/components/__tests__/generatorTest.ts +0 -28
- package/src/lib/components/__tests__/mockScene2D.ts +0 -45
- package/src/lib/components/__tests__/query.test.tsx +0 -122
- package/src/lib/components/__tests__/state.test.tsx +0 -60
- package/src/lib/components/index.ts +0 -28
- package/src/lib/components/types.ts +0 -35
- package/src/lib/curves/ArcSegment.ts +0 -159
- package/src/lib/curves/CircleSegment.ts +0 -77
- package/src/lib/curves/CubicBezierSegment.ts +0 -78
- package/src/lib/curves/CurveDrawingInfo.ts +0 -11
- package/src/lib/curves/CurvePoint.ts +0 -15
- package/src/lib/curves/CurveProfile.ts +0 -7
- package/src/lib/curves/KnotInfo.ts +0 -10
- package/src/lib/curves/LineSegment.ts +0 -62
- package/src/lib/curves/Polynomial.ts +0 -355
- package/src/lib/curves/Polynomial2D.ts +0 -62
- package/src/lib/curves/PolynomialSegment.ts +0 -124
- package/src/lib/curves/QuadBezierSegment.ts +0 -64
- package/src/lib/curves/Segment.ts +0 -17
- package/src/lib/curves/UniformPolynomialCurveSampler.ts +0 -94
- package/src/lib/curves/createCurveProfileLerp.ts +0 -471
- package/src/lib/curves/getBezierSplineProfile.ts +0 -223
- package/src/lib/curves/getCircleProfile.ts +0 -86
- package/src/lib/curves/getPathProfile.ts +0 -178
- package/src/lib/curves/getPointAtDistance.ts +0 -21
- package/src/lib/curves/getPolylineProfile.test.ts +0 -21
- package/src/lib/curves/getPolylineProfile.ts +0 -89
- package/src/lib/curves/getRectProfile.ts +0 -139
- package/src/lib/curves/index.ts +0 -16
- package/src/lib/decorators/canvasStyleSignal.ts +0 -16
- package/src/lib/decorators/colorSignal.ts +0 -9
- package/src/lib/decorators/compound.ts +0 -72
- package/src/lib/decorators/computed.ts +0 -18
- package/src/lib/decorators/defaultStyle.ts +0 -18
- package/src/lib/decorators/filtersSignal.ts +0 -136
- package/src/lib/decorators/index.ts +0 -10
- package/src/lib/decorators/initializers.ts +0 -32
- package/src/lib/decorators/nodeName.ts +0 -13
- package/src/lib/decorators/signal.test.ts +0 -90
- package/src/lib/decorators/signal.ts +0 -345
- package/src/lib/decorators/spacingSignal.ts +0 -15
- package/src/lib/decorators/vector2Signal.ts +0 -30
- package/src/lib/globals.d.ts +0 -2
- package/src/lib/index.ts +0 -8
- package/src/lib/jsx-dev-runtime.ts +0 -2
- package/src/lib/jsx-runtime.ts +0 -46
- package/src/lib/parse-svg-path.d.ts +0 -14
- package/src/lib/partials/Filter.ts +0 -180
- package/src/lib/partials/Gradient.ts +0 -102
- package/src/lib/partials/Pattern.ts +0 -34
- package/src/lib/partials/ShaderConfig.ts +0 -117
- package/src/lib/partials/index.ts +0 -4
- package/src/lib/partials/types.ts +0 -58
- package/src/lib/scenes/Scene2D.ts +0 -242
- package/src/lib/scenes/index.ts +0 -3
- package/src/lib/scenes/makeScene2D.ts +0 -16
- package/src/lib/scenes/useScene2D.ts +0 -6
- package/src/lib/tsconfig.build.json +0 -5
- package/src/lib/tsconfig.json +0 -10
- package/src/lib/tsdoc.json +0 -4
- package/src/lib/utils/CanvasUtils.ts +0 -306
- package/src/lib/utils/diff.test.ts +0 -453
- package/src/lib/utils/diff.ts +0 -148
- package/src/lib/utils/index.ts +0 -2
- package/src/lib/utils/is.ts +0 -11
- package/src/lib/utils/makeSignalExtensions.ts +0 -30
- package/src/lib/utils/video/declarations.d.ts +0 -1
- package/src/lib/utils/video/ffmpeg-client.ts +0 -50
- package/src/lib/utils/video/mp4-parser-manager.ts +0 -72
- package/src/lib/utils/video/parser/index.ts +0 -1
- package/src/lib/utils/video/parser/parser.ts +0 -257
- package/src/lib/utils/video/parser/sampler.ts +0 -72
- package/src/lib/utils/video/parser/segment.ts +0 -302
- package/src/lib/utils/video/parser/sink.ts +0 -29
- package/src/lib/utils/video/parser/utils.ts +0 -31
- package/src/tsconfig.base.json +0 -19
- package/src/tsconfig.build.json +0 -8
- package/src/tsconfig.json +0 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/index.ts","../src/lib/code/CodeCursor.ts","../src/lib/code/CodeMetrics.ts","../src/lib/code/CodeFragment.ts","../src/lib/code/CodeScope.ts","../src/lib/code/CodeRange.ts","../src/lib/code/CodeSelection.ts","../src/lib/code/diff.ts","../src/lib/code/CodeDiffer.ts","../src/lib/code/CodeSignal.ts","../src/lib/decorators/canvasStyleSignal.ts","../src/lib/utils/CanvasUtils.ts","../src/lib/partials/Filter.ts","../src/lib/partials/Gradient.ts","../src/lib/decorators/computed.ts","../src/lib/decorators/initializers.ts","../src/lib/decorators/signal.ts","../src/lib/utils/makeSignalExtensions.ts","../src/lib/decorators/vector2Signal.ts","../src/lib/decorators/compound.ts","../src/lib/partials/Pattern.ts","../src/lib/utils/is.ts","../src/lib/decorators/colorSignal.ts","../src/lib/decorators/defaultStyle.ts","../src/lib/decorators/filtersSignal.ts","../src/lib/decorators/nodeName.ts","../src/lib/code/CodeTokenizer.ts","../src/lib/code/extractRange.ts","../src/lib/code/DefaultHighlightStyle.ts","../src/lib/code/LezerHighlighter.ts","../src/lib/components/Audio.ts","../src/lib/components/Media.ts","../src/lib/components/Rect.ts","../src/lib/curves/getRectProfile.ts","../src/lib/curves/CircleSegment.ts","../src/lib/curves/Segment.ts","../src/lib/curves/CubicBezierSegment.ts","../src/lib/curves/Polynomial2D.ts","../src/lib/curves/Polynomial.ts","../src/lib/curves/PolynomialSegment.ts","../src/lib/curves/UniformPolynomialCurveSampler.ts","../src/lib/curves/LineSegment.ts","../src/lib/decorators/spacingSignal.ts","../src/lib/components/Curve.ts","../src/lib/curves/getPointAtDistance.ts","../src/lib/components/Shape.ts","../src/lib/components/Layout.ts","../src/lib/components/Node.ts","../src/lib/partials/ShaderConfig.ts","../src/lib/scenes/useScene2D.ts","../src/lib/components/Bezier.ts","../src/lib/components/Circle.ts","../src/lib/curves/getBezierSplineProfile.ts","../src/lib/curves/QuadBezierSegment.ts","../src/lib/curves/getCircleProfile.ts","../src/lib/curves/ArcSegment.ts","../src/lib/components/View2D.ts","../src/lib/curves/getPolylineProfile.ts","../src/lib/components/Code.ts","../src/lib/components/CubicBezier.ts","../src/lib/components/Grid.ts","../src/lib/components/Icon.ts","../src/lib/components/Img.ts","../src/lib/components/Knot.ts","../src/lib/components/Latex.ts","../src/lib/components/Line.ts","../src/lib/curves/createCurveProfileLerp.ts","../src/lib/components/Path.ts","../src/lib/curves/getPathProfile.ts","../src/lib/components/Polygon.ts","../src/lib/components/QuadBezier.ts","../src/lib/components/Ray.ts","../src/lib/components/Rive.ts","../src/lib/components/Spline.ts","../src/lib/components/SVG.ts","../src/lib/utils/diff.ts","../src/lib/components/Txt.ts","../src/lib/components/TxtLeaf.ts","../src/lib/components/Video.ts","../src/lib/utils/video/ffmpeg-client.ts","../src/lib/utils/video/parser/parser.ts","../src/lib/utils/video/parser/sampler.ts","../src/lib/utils/video/parser/sink.ts","../src/lib/utils/video/parser/segment.ts","../src/lib/utils/video/parser/utils.ts","../src/lib/utils/video/mp4-parser-manager.ts","../src/lib/jsx-runtime.ts","../src/lib/scenes/Scene2D.ts","../src/lib/scenes/makeScene2D.ts"],"sourcesContent":["export * from './code';\nexport * from './components';\nexport * from './curves';\nexport * from './decorators';\nexport * from './jsx-runtime';\nexport * from './partials';\nexport * from './scenes';\nexport * from './utils';\n","import type {SerializedVector2} from '@twick/core';\nimport {clampRemap, Color, map, unwrap, Vector2} from '@twick/core';\nimport type {Code} from '../components';\nimport type {CodeFragment} from './CodeFragment';\nimport {parseCodeFragment} from './CodeFragment';\nimport type {CodeHighlighter} from './CodeHighlighter';\nimport type {CodeMetrics} from './CodeMetrics';\nimport type {CodePoint, CodeRange} from './CodeRange';\nimport type {CodeScope} from './CodeScope';\nimport {isCodeScope} from './CodeScope';\nimport {isPointInCodeSelection} from './CodeSelection';\n\nexport interface CodeFragmentDrawingInfo {\n text: string;\n position: Vector2;\n characterSize: Vector2;\n cursor: Vector2;\n fill: string;\n time: number;\n alpha: number;\n}\n\n/**\n * A stateful class for recursively traversing a code scope.\n *\n * @internal\n */\nexport class CodeCursor {\n public cursor = new Vector2();\n public beforeCursor = new Vector2();\n public afterCursor = new Vector2();\n public beforeIndex = 0;\n public afterIndex = 0;\n private context = {} as CanvasRenderingContext2D;\n private monoWidth = 0;\n private maxWidth = 0;\n private lineHeight = 0;\n private fallbackFill = new Color('white');\n private caches: {before: unknown; after: unknown} | null = null;\n private highlighter: CodeHighlighter | null = null;\n private selection: CodeRange[] = [];\n private selectionProgress: number | null = null;\n private globalProgress: number[] = [];\n private fragmentDrawingInfo: CodeFragmentDrawingInfo[] = [];\n private fontHeight = 0;\n private verticalOffset = 0;\n\n public constructor(private readonly node: Code) {}\n\n /**\n * Prepare the cursor for the next traversal.\n *\n * @param context - The context used to measure and draw the code.\n */\n public setupMeasure(context: CanvasRenderingContext2D) {\n const metrics = context.measureText('X');\n this.monoWidth = metrics.width;\n this.fontHeight =\n metrics.fontBoundingBoxDescent + metrics.fontBoundingBoxAscent;\n this.verticalOffset = metrics.fontBoundingBoxAscent;\n this.context = context;\n this.lineHeight = parseFloat(this.node.styles.lineHeight);\n this.cursor = new Vector2();\n this.beforeCursor = new Vector2();\n this.afterCursor = new Vector2();\n this.beforeIndex = 0;\n this.afterIndex = 0;\n this.maxWidth = 0;\n }\n\n public setupDraw(context: CanvasRenderingContext2D) {\n this.setupMeasure(context);\n const fill = this.node.fill();\n this.fallbackFill =\n fill instanceof Color ? (fill as Color) : new Color('white');\n this.caches = this.node.highlighterCache();\n this.highlighter = this.node.highlighter();\n this.selection = this.node.selection();\n this.selectionProgress = this.node.selectionProgress();\n this.fragmentDrawingInfo = [];\n this.globalProgress = [];\n }\n\n /**\n * Measure the desired size of the code scope.\n *\n * @remarks\n * The result can be retrieved with {@link getSize}.\n *\n * @param scope - The code scope to measure.\n */\n public measureSize(scope: CodeScope) {\n const progress = unwrap(scope.progress);\n for (const wrapped of scope.fragments) {\n const possibleFragment = unwrap(wrapped);\n if (isCodeScope(possibleFragment)) {\n this.measureSize(possibleFragment);\n continue;\n }\n if (Array.isArray(possibleFragment)) {\n this.measureSize({\n progress: scope.progress,\n fragments: possibleFragment,\n });\n continue;\n }\n\n const fragment = parseCodeFragment(\n possibleFragment,\n this.context,\n this.monoWidth,\n );\n\n const beforeMaxWidth = this.calculateMaxWidth(fragment.before);\n const afterMaxWidth = this.calculateMaxWidth(fragment.after);\n\n const maxWidth = map(beforeMaxWidth, afterMaxWidth, progress);\n if (maxWidth > this.maxWidth) {\n this.maxWidth = maxWidth;\n }\n\n const beforeEnd = this.calculateWidth(fragment.before);\n const afterEnd = this.calculateWidth(fragment.after);\n this.cursor.x = map(beforeEnd, afterEnd, progress);\n\n if (this.cursor.y === 0) {\n this.cursor.y = 1;\n }\n\n this.cursor.y += map(\n fragment.before.newRows,\n fragment.after.newRows,\n progress,\n );\n }\n }\n\n /**\n * Get the size measured by the cursor.\n */\n public getSize() {\n return {\n x: this.maxWidth * this.monoWidth,\n y: this.cursor.y * this.lineHeight + this.verticalOffset,\n };\n }\n\n /**\n * Get the drawing information created by the cursor.\n */\n public getDrawingInfo() {\n return {\n fragments: this.fragmentDrawingInfo,\n verticalOffset: this.verticalOffset,\n fontHeight: this.fontHeight,\n };\n }\n\n /**\n * Draw the given code scope.\n *\n * @param scope - The code scope to draw.\n */\n public drawScope(scope: CodeScope) {\n const progress = unwrap(scope.progress);\n for (const wrappedFragment of scope.fragments) {\n const possibleFragment = unwrap(wrappedFragment);\n if (isCodeScope(possibleFragment)) {\n this.drawScope(possibleFragment);\n continue;\n }\n if (Array.isArray(possibleFragment)) {\n this.drawScope({\n progress: scope.progress,\n fragments: possibleFragment,\n });\n continue;\n }\n\n const fragment = parseCodeFragment(\n possibleFragment,\n this.context,\n this.monoWidth,\n );\n const timingOffset = 0.8;\n let alpha = 1;\n let offsetY = 0;\n if (fragment.before.content !== fragment.after.content) {\n const mirrored = Math.abs(progress - 0.5) * 2;\n alpha = clampRemap(1, 1 - timingOffset, 1, 0, mirrored);\n\n const scale = progress < 0.5 ? 4 : -4;\n offsetY = map(\n Math.abs(fragment.after.newRows - fragment.before.newRows) / scale,\n 0,\n mirrored,\n );\n }\n\n this.drawToken(fragment, scope, this.cursor.addY(offsetY), alpha);\n\n this.beforeCursor.x = this.calculateWidth(\n fragment.before,\n this.beforeCursor.x,\n );\n this.afterCursor.x = this.calculateWidth(\n fragment.after,\n this.afterCursor.x,\n );\n this.beforeCursor.y += fragment.before.newRows;\n this.afterCursor.y += fragment.after.newRows;\n\n this.beforeIndex += fragment.before.content.length;\n this.afterIndex += fragment.after.content.length;\n\n this.cursor.y += map(\n fragment.before.newRows,\n fragment.after.newRows,\n progress,\n );\n\n const beforeEnd = this.calculateWidth(fragment.before);\n const afterEnd = this.calculateWidth(fragment.after);\n this.cursor.x = map(beforeEnd, afterEnd, progress);\n }\n }\n\n private drawToken(\n fragment: CodeFragment,\n scope: CodeScope,\n offset: SerializedVector2,\n alpha: number,\n ) {\n const progress = unwrap(scope.progress);\n const currentProgress = this.currentProgress();\n if (progress > 0) {\n this.globalProgress.push(progress);\n }\n\n const code = progress < 0.5 ? fragment.before : fragment.after;\n\n let hasOffset = true;\n let width = 0;\n let stringLength = 0;\n let y = 0;\n for (let i = 0; i < code.content.length; i++) {\n let color = this.fallbackFill.serialize();\n let char = code.content.charAt(i);\n const selection: {before: number | null; after: number | null} = {\n before: null,\n after: null,\n };\n\n if (char === '\\n') {\n y++;\n hasOffset = false;\n width = 0;\n stringLength = 0;\n selection.before = null;\n selection.after = null;\n continue;\n }\n\n const beforeHighlight =\n this.caches &&\n this.highlighter?.highlight(this.beforeIndex + i, this.caches.before);\n const afterHighlight =\n this.caches &&\n this.highlighter?.highlight(this.afterIndex + i, this.caches.after);\n\n const highlight = progress < 0.5 ? beforeHighlight : afterHighlight;\n if (highlight) {\n // Handle edge cases where the highlight style changes despite the\n // content being the same. The code doesn't fade in and out so the color\n // has to be interpolated to avoid jarring changes.\n if (\n fragment.before.content === fragment.after.content &&\n beforeHighlight?.color !== afterHighlight?.color\n ) {\n highlight.color = Color.lerp(\n beforeHighlight?.color ?? this.fallbackFill,\n afterHighlight?.color ?? this.fallbackFill,\n progress,\n ).serialize();\n }\n\n if (highlight.color) {\n color = highlight.color;\n }\n\n let skipAhead = 0;\n do {\n if (\n this.processSelection(\n selection,\n skipAhead,\n hasOffset,\n stringLength,\n y,\n )\n ) {\n break;\n }\n\n skipAhead++;\n } while (skipAhead < highlight.skipAhead);\n\n if (skipAhead > 1) {\n char = code.content.slice(i, i + skipAhead);\n }\n\n i += char.length - 1;\n } else {\n this.processSelection(selection, 0, hasOffset, stringLength, y);\n let skipAhead = 1;\n while (\n i < code.content.length - 1 &&\n code.content.charAt(i + 1) !== '\\n'\n ) {\n if (\n this.processSelection(\n selection,\n skipAhead,\n hasOffset,\n stringLength,\n y,\n )\n ) {\n break;\n }\n\n skipAhead++;\n char += code.content.charAt(++i);\n }\n }\n\n let time: number;\n const selectionAfter = selection.after ?? 0;\n const selectionBefore = selection.before ?? 0;\n if (fragment.before.content === '') {\n time = selectionAfter;\n } else if (fragment.after.content === '') {\n time = selectionBefore;\n } else {\n time = map(\n selectionBefore,\n selectionAfter,\n this.selectionProgress ?? currentProgress,\n );\n }\n\n const measure = this.context.measureText(char);\n this.fragmentDrawingInfo.push({\n text: char,\n position: new Vector2(\n (hasOffset ? offset.x + width : width) * this.monoWidth,\n (offset.y + y) * this.lineHeight,\n ),\n cursor: new Vector2(\n hasOffset ? this.beforeCursor.x + stringLength : stringLength,\n this.beforeCursor.y + y,\n ),\n alpha,\n characterSize: new Vector2(\n measure.width / char.length,\n this.fontHeight,\n ),\n fill: color,\n time,\n });\n\n stringLength += char.length;\n width += Math.round(measure.width / this.monoWidth);\n }\n }\n\n private calculateWidth(metrics: CodeMetrics, x = this.cursor.x): number {\n return metrics.newRows === 0 ? x + metrics.lastWidth : metrics.lastWidth;\n }\n\n private calculateMaxWidth(metrics: CodeMetrics, x = this.cursor.x): number {\n return Math.max(this.maxWidth, metrics.maxWidth, x + metrics.firstWidth);\n }\n\n private currentProgress() {\n if (this.globalProgress.length === 0) {\n return 0;\n }\n\n let sum = 0;\n for (const progress of this.globalProgress) {\n sum += progress;\n }\n\n return sum / this.globalProgress.length;\n }\n\n private processSelection(\n selection: {before: number | null; after: number | null},\n skipAhead: number,\n hasOffset: boolean,\n stringLength: number,\n y: number,\n ): boolean {\n let shouldBreak = false;\n let currentSelected = this.isSelected(\n (hasOffset ? this.beforeCursor.x + stringLength : stringLength) +\n skipAhead,\n this.beforeCursor.y + y,\n );\n if (selection.before !== null && selection.before !== currentSelected) {\n shouldBreak = true;\n } else {\n selection.before = currentSelected;\n }\n\n currentSelected = this.isSelected(\n (hasOffset ? this.afterCursor.x + stringLength : stringLength) +\n skipAhead,\n this.afterCursor.y + y,\n true,\n );\n if (selection.after !== null && selection.after !== currentSelected) {\n shouldBreak = true;\n } else {\n selection.after = currentSelected;\n }\n\n return shouldBreak;\n }\n\n private isSelected(x: number, y: number, isAfter?: boolean): number {\n const point: CodePoint = [y, x];\n const maxSelection = isPointInCodeSelection(point, this.selection) ? 1 : 0;\n if (this.node.oldSelection === null || this.selectionProgress === null) {\n return maxSelection;\n }\n\n if (isAfter) {\n return maxSelection;\n }\n\n return isPointInCodeSelection(point, this.node.oldSelection) ? 1 : 0;\n }\n}\n","export interface CodeMetrics {\n content: string;\n newRows: number;\n endColumn: number;\n firstWidth: number;\n maxWidth: number;\n lastWidth: number;\n}\n\nexport function measureString(\n context: CanvasRenderingContext2D,\n monoWidth: number,\n value: string,\n): CodeMetrics {\n const lines = value.split('\\n');\n const lastLine = lines[lines.length - 1];\n const firstWidth = Math.round(\n context.measureText(lines[0]).width / monoWidth,\n );\n let lastWidth = firstWidth;\n let maxWidth = firstWidth;\n\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i];\n const width = Math.round(context.measureText(line).width / monoWidth);\n if (width > maxWidth) {\n maxWidth = width;\n }\n }\n\n if (lines.length > 0) {\n lastWidth = Math.round(context.measureText(lastLine).width / monoWidth);\n }\n\n return {\n content: value,\n newRows: lines.length - 1,\n endColumn: lastLine.length,\n firstWidth,\n maxWidth,\n lastWidth,\n };\n}\n\nexport function isCodeMetrics(value: any): value is CodeMetrics {\n return value?.content !== undefined;\n}\n","import type {CodeMetrics} from './CodeMetrics';\nimport {isCodeMetrics, measureString} from './CodeMetrics';\n\nexport interface CodeFragment {\n before: CodeMetrics;\n after: CodeMetrics;\n}\nexport interface RawCodeFragment {\n before: string;\n after: string;\n}\n\nexport type PossibleCodeFragment =\n | CodeFragment\n | CodeMetrics\n | RawCodeFragment\n | string;\n\nexport function metricsToFragment(value: CodeMetrics): CodeFragment {\n return {\n before: value,\n after: value,\n };\n}\n\nexport function parseCodeFragment(\n value: PossibleCodeFragment,\n context: CanvasRenderingContext2D,\n monoWidth: number,\n): CodeFragment {\n let fragment: CodeFragment;\n if (typeof value === 'string') {\n fragment = metricsToFragment(measureString(context, monoWidth, value));\n } else if (isCodeMetrics(value)) {\n fragment = metricsToFragment(value);\n } else {\n fragment = {\n before:\n typeof value.before === 'string'\n ? measureString(context, monoWidth, value.before)\n : value.before,\n after:\n typeof value.after === 'string'\n ? measureString(context, monoWidth, value.after)\n : value.after,\n };\n }\n\n return fragment;\n}\n\n/**\n * Create a code fragment that represents an insertion of code.\n *\n * @remarks\n * Can be used in conjunction with {@link code.CodeSignalHelpers.edit}.\n *\n * @param code - The code to insert.\n */\nexport function insert(code: string): RawCodeFragment {\n return {\n before: '',\n after: code,\n };\n}\n\n/**\n * Create a code fragment that represents a change from one piece of code to\n * another.\n *\n * @remarks\n * Can be used in conjunction with {@link code.CodeSignalHelpers.edit}.\n *\n * @param before - The code to change from.\n * @param after - The code to change to.\n */\nexport function replace(before: string, after: string): RawCodeFragment {\n return {\n before,\n after,\n };\n}\n\n/**\n * Create a code fragment that represents a removal of code.\n *\n * @remarks\n * Can be used in conjunction with {@link code.CodeSignalHelpers.edit}.\n *\n * @param code - The code to remove.\n */\nexport function remove(code: string): RawCodeFragment {\n return {\n before: code,\n after: '',\n };\n}\n","import type {SignalValue} from '@twick/core';\nimport {unwrap} from '@twick/core';\nimport type {PossibleCodeFragment} from './CodeFragment';\nimport {isCodeMetrics} from './CodeMetrics';\n\nexport interface CodeScope {\n progress: SignalValue<number>;\n fragments: CodeTag[];\n}\n\nexport type PossibleCodeScope = CodeScope | CodeTag[] | string;\n\nexport type CodeTag = SignalValue<PossibleCodeFragment | CodeScope | CodeTag[]>;\n\nexport function CODE(\n strings: TemplateStringsArray,\n ...tags: CodeTag[]\n): CodeTag[] {\n const result: CodeTag[] = [];\n for (let i = 0; i < strings.length; i++) {\n result.push(strings[i]);\n const tag = tags[i];\n if (tag !== undefined) {\n if (Array.isArray(tag)) {\n result.push(...tag);\n } else {\n result.push(tag);\n }\n }\n }\n\n return result;\n}\n\nexport function isCodeScope(value: any): value is CodeScope {\n return value?.fragments !== undefined;\n}\n\nexport function parseCodeScope(value: PossibleCodeScope): CodeScope {\n if (typeof value === 'string') {\n return {\n progress: 0,\n fragments: [value],\n };\n }\n\n if (Array.isArray(value)) {\n return {\n progress: 0,\n fragments: value,\n };\n }\n\n return value;\n}\n\ntype IsAfterPredicate = ((scope: CodeScope) => boolean) | boolean;\n\nexport function resolveScope(\n scope: CodeScope,\n isAfter: IsAfterPredicate,\n): string {\n let code = '';\n const after = typeof isAfter === 'boolean' ? isAfter : isAfter(scope);\n for (const wrapped of scope.fragments) {\n code += resolveCodeTag(wrapped, after, isAfter);\n }\n\n return code;\n}\n\nexport function resolveCodeTag(\n wrapped: CodeTag,\n after: boolean,\n isAfter: IsAfterPredicate = after,\n) {\n const fragment = unwrap(wrapped);\n if (typeof fragment === 'string') {\n return fragment;\n } else if (isCodeScope(fragment)) {\n return resolveScope(fragment, isAfter);\n } else if (isCodeMetrics(fragment)) {\n return fragment.content;\n } else if (Array.isArray(fragment)) {\n return resolveScope(\n {\n progress: 0,\n fragments: fragment,\n },\n isAfter,\n );\n } else {\n return after\n ? typeof fragment.after === 'string'\n ? fragment.after\n : fragment.after.content\n : typeof fragment.before === 'string'\n ? fragment.before\n : fragment.before.content;\n }\n}\n","export type CodePoint = [number, number];\n\nfunction isCodePoint(value: unknown): value is CodePoint {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\nexport type CodeRange = [CodePoint, CodePoint];\n\nexport function isCodeRange(value: unknown): value is CodeRange {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n isCodePoint(value[0]) &&\n isCodePoint(value[1])\n );\n}\n\n/**\n * Create a code range that spans the given lines.\n *\n * @param from - The line from which the range starts.\n * @param to - The line at which the range ends. If omitted, the range will\n * cover only one line.\n */\nexport function lines(from: number, to?: number): CodeRange {\n return [\n [from, 0],\n [to ?? from, Infinity],\n ];\n}\n\n/**\n * Create a code range that highlights the given word.\n *\n * @param line - The line at which the word appears.\n * @param from - The column at which the word starts.\n * @param length - The length of the word. If omitted, the range will cover the\n * rest of the line.\n */\nexport function word(line: number, from: number, length?: number): CodeRange {\n return [\n [line, from],\n [line, from + (length ?? Infinity)],\n ];\n}\n\n/**\n * Create a custom selection range.\n *\n * @param startLine - The line at which the selection starts.\n * @param startColumn - The column at which the selection starts.\n * @param endLine - The line at which the selection ends.\n * @param endColumn - The column at which the selection ends.\n */\nexport function pointToPoint(\n startLine: number,\n startColumn: number,\n endLine: number,\n endColumn: number,\n): CodeRange {\n return [\n [startLine, startColumn],\n [endLine, endColumn],\n ];\n}\n\nexport function isPointInCodeRange(point: CodePoint, range: CodeRange) {\n const [y, x] = point;\n const [[startLine, startColumn], [endLine, endColumn]] = range;\n return (\n ((y === startLine && x >= startColumn) || y > startLine) &&\n ((y === endLine && x < endColumn) || y < endLine)\n );\n}\n\nexport function consolidateCodeRanges(ranges: CodeRange[]): CodeRange[] {\n // Sort by start position\n ranges.sort((a, b) => {\n const lines = b[0][0] - a[0][0];\n // Break ties on start column\n if (lines === 0) {\n return b[0][1] - a[0][1];\n }\n return lines;\n });\n\n const staged: CodeRange[] = [...ranges];\n const results = [];\n while (staged.length > 0) {\n let current = staged.pop();\n if (!current) {\n continue;\n }\n const [[initStartLine, initStartColumn], [initEndLine, initEndColumn]] =\n current;\n\n for (const targetRange of staged) {\n const [\n [targetStartLine, targetStartColumn],\n [targetEndLine, targetEndColumn],\n ] = targetRange;\n if (\n isPointInCodeRange(targetRange[0], current) ||\n isPointInCodeRange(targetRange[1], current)\n ) {\n staged.pop();\n\n let startColumn;\n if (initStartLine === targetStartLine) {\n startColumn = Math.min(initStartColumn, targetStartColumn);\n } else if (initStartLine < targetStartLine) {\n startColumn = initStartColumn;\n } else {\n startColumn = targetStartColumn;\n }\n\n let endColumn;\n if (initEndLine === targetEndLine) {\n endColumn = Math.max(initEndColumn, targetEndColumn);\n } else if (initEndLine > targetEndLine) {\n endColumn = initEndColumn;\n } else {\n endColumn = targetEndColumn;\n }\n // Update the current to the consolidated one and get rid of the\n // remaining instance of the unconsolidated target\n current = [\n [Math.min(initStartLine, targetStartLine), startColumn],\n [Math.max(initEndLine, targetEndLine), endColumn],\n ];\n }\n }\n results.push(current);\n }\n return results;\n}\n\nexport function inverseCodeRange(ranges: CodeRange[]): CodeRange[] {\n if (ranges.length === 0) {\n return [\n [\n [0, 0],\n [Infinity, Infinity],\n ],\n ];\n }\n const firstRange = ranges[0];\n const result: CodeRange[] = [];\n for (let first = 0; first < ranges.length - 1; first++) {\n const range1 = ranges[first];\n const range2 = ranges[first + 1];\n result.push([range1[1], range2[0]]);\n }\n const lastRange = ranges.slice(-1)[0];\n return [\n [[0, 0], firstRange[0]],\n ...result,\n [lastRange[1], [Infinity, Infinity]],\n ];\n}\n\n/**\n * Find all code ranges that match the given pattern.\n *\n * @param code - The code to search in.\n * @param pattern - Either a string or a regular expression to search for.\n * @param limit - An optional limit on the number of ranges to find.\n */\nexport function findAllCodeRanges(\n code: string,\n pattern: string | RegExp,\n limit = Infinity,\n): CodeRange[] {\n if (typeof pattern === 'string') {\n pattern = new RegExp(pattern, 'g');\n }\n\n const matches = code.matchAll(pattern);\n const ranges: CodeRange[] = [];\n let index = 0;\n let line = 0;\n let column = 0;\n\n for (const match of matches) {\n if (match.index === undefined || ranges.length >= limit) {\n continue;\n }\n\n let from: CodePoint = [line, column];\n while (index <= code.length) {\n if (index === match.index) {\n from = [line, column];\n }\n\n if (index === match.index + match[0].length) {\n ranges.push([from, [line, column]]);\n break;\n }\n\n if (code[index] === '\\n') {\n line++;\n column = 0;\n } else {\n column++;\n }\n index++;\n }\n }\n\n return ranges;\n}\n","import type {CodePoint, CodeRange} from './CodeRange';\nimport {isCodeRange, isPointInCodeRange} from './CodeRange';\n\nexport type CodeSelection = CodeRange[];\nexport type PossibleCodeSelection = CodeRange | CodeRange[];\n\nexport function parseCodeSelection(\n value: PossibleCodeSelection,\n): CodeSelection {\n return isCodeRange(value) ? [value] : value;\n}\n\nexport function isPointInCodeSelection(\n point: CodePoint,\n selection: CodeSelection,\n) {\n for (const range of selection) {\n if (isPointInCodeRange(point, range)) {\n return true;\n }\n }\n\n return false;\n}\n","type Subsequence = {\n aIndex: number;\n bIndex: number;\n prev?: Subsequence | undefined;\n};\n\n/**\n * Performs a patience diff on two arrays of strings, returning an object\n * containing the lines that were deleted, inserted, and potentially moved\n * lines. The plus parameter can result in a significant performance hit due\n * to additional Longest Common Substring searches.\n *\n * @param aLines - The original array of strings\n * @param bLines - The new array of strings\n * @param plus - Whether to return the moved lines\n *\n * Adapted from Jonathan \"jonTrent\" Trent's patience-diff algorithm.\n * Types and tests added by Hunter \"hhenrichsen\" Henrichsen.\n *\n * {@link https://github.com/jonTrent/PatienceDiff}\n */\nexport function patienceDiff(\n aLines: string[],\n bLines: string[],\n): {\n lines: {\n line: string;\n aIndex: number;\n bIndex: number;\n }[];\n lineCountDeleted: number;\n lineCountInserted: number;\n} {\n /**\n * Finds all unique values in lines[start...end], inclusive. This\n * function is used in preparation for determining the longest common\n * subsequence.\n *\n * @param lines - The array to search\n * @param start - The starting index (inclusive)\n * @param end - The ending index (inclusive)\n * @returns A map of the unique lines to their index\n */\n function findUnique(lines: string[], start: number, end: number) {\n const lineMap = new Map<string, {count: number; index: number}>();\n for (let i = start; i <= end; i++) {\n const line = lines[i];\n const data = lineMap.get(line);\n if (data) {\n data.count++;\n data.index = i;\n } else {\n lineMap.set(line, {count: 1, index: i});\n }\n }\n\n const newMap = new Map<string, number>();\n for (const [key, value] of lineMap) {\n if (value.count === 1) {\n newMap.set(key, value.index);\n }\n }\n\n return newMap;\n }\n\n /**\n * Finds all the unique common entries between aArray[aStart...aEnd] and\n * bArray[bStart...bEnd], inclusive. This function uses findUnique to pare\n * down the aArray and bArray ranges first, before then walking the\n * comparison between the two arrays.\n *\n *\n * @param aArray - The original array\n * @param aStart - The start of the original array to search\n * @param aEnd - The end of the original array to search, inclusive\n * @param bArray - The new array\n * @param bStart - the start of the new array to search\n * @param bEnd - The end of the new array to search, inclusive\n * @returns a Map, with the key as the common line between aArray and\n * bArray, with the value as an object containing the array indices of the\n * matching uniqe lines.\n */\n function uniqueCommon(\n aArray: string[],\n aStart: number,\n aEnd: number,\n bArray: string[],\n bStart: number,\n bEnd: number,\n ): Map<string, Subsequence> {\n const aUnique = findUnique(aArray, aStart, aEnd);\n const bUnique = findUnique(bArray, bStart, bEnd);\n\n return [...aUnique.entries()].reduce<Map<string, Subsequence>>(\n (paired, [key, value]) => {\n const bIndex = bUnique.get(key);\n if (bIndex !== undefined) {\n paired.set(key, {\n aIndex: value,\n bIndex,\n });\n }\n return paired;\n },\n new Map(),\n );\n }\n\n /**\n * Takes a map from the unique common lines between two arrays and determines\n * the longest common subsequence.\n *\n * @see uniqueCommon\n *\n * @param abMap - The map of unique common lines between two arrays.\n * @returns An array of objects containing the indices of the longest common\n * subsequence.\n */\n function longestCommonSubsequence(\n abMap: Map<string, Subsequence>,\n ): Subsequence[] {\n const jagged: [Subsequence][] = [];\n\n abMap.forEach(value => {\n let i = 0;\n while (jagged[i] && jagged[i].at(-1)!.bIndex < value.bIndex) {\n i++;\n }\n\n if (i > 0) {\n value.prev = jagged[i - 1].at(-1);\n }\n\n if (!jagged[i]) {\n jagged[i] = [value];\n } else {\n jagged[i].push(value);\n }\n });\n\n // Pull out the longest common subsequence\n let lcs: Subsequence[] = [];\n\n if (jagged.length > 0) {\n lcs = [jagged.at(-1)!.at(-1)!];\n let cursor = lcs.at(-1);\n while (cursor?.prev) {\n cursor = cursor.prev;\n lcs.push(cursor);\n }\n }\n\n return lcs.reverse();\n }\n\n /**\n * Keeps track of the aLines that have been deleted, are shared between aLines\n * and bLines, and bLines that have been inserted.\n */\n const result: {\n line: string;\n aIndex: number;\n bIndex: number;\n moved: boolean;\n }[] = [];\n let deleted = 0;\n let inserted = 0;\n\n function addToResult(aIndex: number, bIndex: number) {\n if (bIndex < 0) {\n deleted++;\n } else if (aIndex < 0) {\n inserted++;\n }\n result.push({\n line: 0 <= aIndex ? aLines[aIndex] : bLines[bIndex],\n aIndex,\n bIndex,\n moved: false,\n });\n }\n\n function addSubMatch(\n aStart: number,\n aEnd: number,\n bStart: number,\n bEnd: number,\n ) {\n // Match any lines at the beginning of aLines and bLines.\n while (\n aStart <= aEnd &&\n bStart <= bEnd &&\n aLines[aStart] === bLines[bStart]\n ) {\n addToResult(aStart++, bStart++);\n }\n\n // Match any lines at the end of aLines and bLines, but don't place them\n // in the \"result\" array just yet, as the lines between these matches at\n // the beginning and the end need to be analyzed first.\n const aEndTemp = aEnd;\n while (aStart <= aEnd && bStart <= bEnd && aLines[aEnd] === bLines[bEnd]) {\n aEnd--;\n bEnd--;\n }\n\n // Now, check to determine with the remaining lines in the subsequence\n // whether there are any unique common lines between aLines and bLines.\n //\n // If not, add the subsequence to the result (all aLines having been\n // deleted, and all bLines having been inserted).\n //\n // If there are unique common lines between aLines and bLines, then let's\n // recursively perform the patience diff on the subsequence.\n const uniqueCommonMap = uniqueCommon(\n aLines,\n aStart,\n aEnd,\n bLines,\n bStart,\n bEnd,\n );\n\n if (uniqueCommonMap.size === 0) {\n while (aStart <= aEnd) {\n addToResult(aStart++, -1);\n }\n while (bStart <= bEnd) {\n addToResult(-1, bStart++);\n }\n } else {\n recurseLCS(aStart, aEnd, bStart, bEnd, uniqueCommonMap);\n }\n\n // Finally, let's add the matches at the end to the result.\n while (aEnd < aEndTemp) {\n addToResult(++aEnd, ++bEnd);\n }\n }\n\n /**\n * Finds the longest common subsequence between the arrays\n * aLines[aStart...aEnd] and bLines[bStart...bEnd], inclusive. Then for each\n * subsequence, recursively performs another LCS search (via addSubMatch),\n * until there are none found, at which point the subsequence is dumped to\n * the result.\n *\n * @param aStart - The start of the original array to search\n * @param aEnd - The end of the original array to search, inclusive\n * @param bStart - The start of the new array to search\n * @param bEnd - The end of the new array to search, inclusive\n * @param uniqueCommonMap - A map of the unique common lines between\n * aLines[aStart...aEnd] and bLines[bStart...bEnd], inclusive.\n */\n function recurseLCS(\n aStart: number,\n aEnd: number,\n bStart: number,\n bEnd: number,\n uniqueCommonMap: Map<string, Subsequence> = uniqueCommon(\n aLines,\n aStart,\n aEnd,\n bLines,\n bStart,\n bEnd,\n ),\n ) {\n const lcs = longestCommonSubsequence(uniqueCommonMap);\n\n if (lcs.length === 0) {\n addSubMatch(aStart, aEnd, bStart, bEnd);\n } else {\n if (aStart < lcs[0].aIndex || bStart < lcs[0].bIndex) {\n addSubMatch(aStart, lcs[0].aIndex - 1, bStart, lcs[0].bIndex - 1);\n }\n\n let i;\n for (i = 0; i < lcs.length - 1; i++) {\n addSubMatch(\n lcs[i].aIndex,\n lcs[i + 1].aIndex - 1,\n lcs[i].bIndex,\n lcs[i + 1].bIndex - 1,\n );\n }\n\n if (lcs[i].aIndex <= aEnd || lcs[i].bIndex <= bEnd) {\n addSubMatch(lcs[i].aIndex, aEnd, lcs[i].bIndex, bEnd);\n }\n }\n }\n\n recurseLCS(0, aLines.length - 1, 0, bLines.length - 1);\n\n return {\n lines: result,\n lineCountDeleted: deleted,\n lineCountInserted: inserted,\n };\n}\n\n/**\n * Utility function for debugging patienceDiff.\n *\n * @internal\n */\nexport function printDiff(diff: ReturnType<typeof patienceDiff>) {\n diff.lines.forEach(line => {\n if (line.bIndex < 0) {\n console.log(`- ${line.line}`);\n } else if (line.aIndex < 0) {\n console.log(`+ ${line.line}`);\n } else {\n console.log(` ${line.line}`);\n }\n });\n}\n","import type {CodeScope, CodeTag} from './CodeScope';\nimport {resolveScope} from './CodeScope';\nimport type {CodeTokenizer} from './CodeTokenizer';\nimport {patienceDiff} from './diff';\n\n/**\n * A function that compares two code snippets and returns a list of\n * {@link CodeTag}s describing a transition between them.\n */\nexport type CodeDiffer = (\n /**\n * The original code scope.\n */\n from: CodeScope,\n /**\n * The new code scope.\n */\n to: CodeScope,\n /**\n * The inherited tokenizer to use.\n */\n tokenize: CodeTokenizer,\n) => CodeTag[];\n\n/**\n * Default diffing function utilizing {@link code.patienceDiff}.\n *\n * @param from - The original code scope.\n * @param to - The new code scope.\n * @param tokenize - The inherited tokenizer to use.\n */\nexport function defaultDiffer(\n from: CodeScope,\n to: CodeScope,\n tokenize: CodeTokenizer,\n) {\n const fromString = resolveScope(from, false);\n const toString = resolveScope(to, true);\n\n const diff = patienceDiff(tokenize(fromString), tokenize(toString));\n\n const fragments: CodeTag[] = [];\n let before = '';\n let after = '';\n let lastAdded = false;\n const flush = () => {\n if (before !== '' || after !== '') {\n fragments.push({\n before,\n after,\n });\n before = '';\n after = '';\n }\n };\n\n for (const line of diff.lines) {\n if (line.aIndex === -1) {\n if (after !== '' && !lastAdded) {\n flush();\n }\n lastAdded = true;\n after += line.line;\n } else if (line.bIndex === -1) {\n if (before !== '' && lastAdded) {\n flush();\n }\n lastAdded = false;\n before += line.line;\n } else {\n flush();\n fragments.push(line.line);\n }\n }\n flush();\n\n return fragments;\n}\n","import type {\n Signal,\n SignalValue,\n ThreadGenerator,\n TimingFunction,\n} from '@twick/core';\nimport {\n createSignal,\n deepLerp,\n DependencyContext,\n SignalContext,\n unwrap,\n} from '@twick/core';\nimport {addInitializer, getPropertyMetaOrCreate} from '../decorators';\nimport {defaultDiffer} from './CodeDiffer';\nimport {insert, replace} from './CodeFragment';\nimport type {CodeHighlighter} from './CodeHighlighter';\nimport type {CodePoint, CodeRange} from './CodeRange';\nimport type {CodeScope, CodeTag, PossibleCodeScope} from './CodeScope';\nimport {CODE, parseCodeScope, resolveCodeTag} from './CodeScope';\nimport {defaultTokenize} from './CodeTokenizer';\nimport {extractRange} from './extractRange';\n\ninterface CodeModifier<TOwner> {\n (code: string): TOwner;\n (code: string, duration: number): ThreadGenerator;\n (duration?: number): TagGenerator;\n}\n\ninterface CodeInsert<TOwner> {\n (point: CodePoint, code: string): TOwner;\n (point: CodePoint, code: string, duration: number): ThreadGenerator;\n}\n\ninterface CodeRemove<TOwner> {\n (range: CodeRange): TOwner;\n (range: CodeRange, duration: number): ThreadGenerator;\n}\n\ninterface CodeReplace<TOwner> {\n (range: CodeRange, code: string): TOwner;\n (range: CodeRange, code: string, duration: number): ThreadGenerator;\n}\n\ntype TagGenerator = (\n strings: TemplateStringsArray,\n ...tags: CodeTag[]\n) => ThreadGenerator;\n\nexport interface CodeSignalHelpers<TOwner> {\n edit(duration?: number): TagGenerator;\n append: CodeModifier<TOwner>;\n prepend: CodeModifier<TOwner>;\n insert: CodeInsert<TOwner>;\n remove: CodeRemove<TOwner>;\n replace: CodeReplace<TOwner>;\n}\n\nexport type CodeSignal<TOwner> = Signal<\n PossibleCodeScope,\n CodeScope,\n TOwner,\n CodeSignalContext<TOwner>\n> &\n CodeSignalHelpers<TOwner>;\n\nexport class CodeSignalContext<TOwner>\n extends SignalContext<PossibleCodeScope, CodeScope, TOwner>\n implements CodeSignalHelpers<TOwner>\n{\n private readonly progress = createSignal(0);\n\n public constructor(\n initial: PossibleCodeScope,\n owner: TOwner,\n private readonly highlighter?: SignalValue<CodeHighlighter | null>,\n ) {\n super(initial, deepLerp, owner);\n Object.defineProperty(this.invokable, 'edit', {\n value: this.edit.bind(this),\n });\n Object.defineProperty(this.invokable, 'append', {\n value: this.append.bind(this),\n });\n Object.defineProperty(this.invokable, 'prepend', {\n value: this.prepend.bind(this),\n });\n Object.defineProperty(this.invokable, 'insert', {\n value: this.insert.bind(this),\n });\n Object.defineProperty(this.invokable, 'remove', {\n value: this.remove.bind(this),\n });\n Object.defineProperty(this.invokable, 'replace', {\n value: this.replace.bind(this),\n });\n }\n\n public override *tweener(\n value: SignalValue<PossibleCodeScope>,\n duration: number,\n timingFunction: TimingFunction,\n ): ThreadGenerator {\n let tokenize = defaultTokenize;\n const highlighter = unwrap(this.highlighter);\n if (highlighter) {\n yield (async () => {\n do {\n await DependencyContext.consumePromises();\n highlighter.initialize();\n } while (DependencyContext.hasPromises());\n })();\n tokenize = (input: string) => highlighter.tokenize(input);\n }\n\n this.progress(0);\n this.set({\n progress: this.progress,\n fragments: defaultDiffer(this.get(), this.parse(unwrap(value)), tokenize),\n });\n yield* this.progress(1, duration, timingFunction);\n this.set(value);\n }\n\n public edit(duration: number = 0.6): TagGenerator {\n return (strings, ...tags) =>\n this.editTween(CODE(strings, ...tags), duration);\n }\n\n public append(code: string): TOwner;\n public append(code: string, duration: number): ThreadGenerator;\n public append(duration?: number): TagGenerator;\n public append(\n first: string | number = 0.6,\n duration?: number,\n ): TOwner | ThreadGenerator | TagGenerator {\n if (typeof first === 'string') {\n if (duration === undefined) {\n const current = this.get();\n return this.set({\n progress: 0,\n fragments: [...current.fragments, first],\n });\n } else {\n return this.appendTween(first, duration);\n }\n }\n\n const savedDuration = first;\n return (strings, ...tags) =>\n this.append(resolveCodeTag(CODE(strings, ...tags), true), savedDuration);\n }\n\n public prepend(code: string): TOwner;\n public prepend(code: string, duration: number): ThreadGenerator;\n public prepend(duration?: number): TagGenerator;\n public prepend(\n first: string | number = 0.6,\n duration?: number,\n ): TOwner | ThreadGenerator | TagGenerator {\n if (typeof first === 'string') {\n if (duration === undefined) {\n const current = this.get();\n return this.set({\n progress: 0,\n fragments: [first, ...current.fragments],\n });\n } else {\n return this.prependTween(first, duration);\n }\n }\n\n const savedDuration = first;\n return (strings, ...tags) =>\n this.prepend(resolveCodeTag(CODE(strings, ...tags), true), savedDuration);\n }\n\n public insert(point: CodePoint, code: string): TOwner;\n public insert(\n point: CodePoint,\n code: string,\n duration: number,\n ): ThreadGenerator;\n public insert(\n point: CodePoint,\n code: string,\n duration?: number,\n ): TOwner | ThreadGenerator {\n return this.replace([point, point], code, duration!);\n }\n\n public remove(range: CodeRange): TOwner;\n public remove(range: CodeRange, duration: number): ThreadGenerator;\n public remove(range: CodeRange, duration?: number): TOwner | ThreadGenerator {\n return this.replace(range, '', duration!);\n }\n\n public replace(range: CodeRange, code: string): TOwner;\n public replace(\n range: CodeRange,\n code: string,\n duration: number,\n ): ThreadGenerator;\n public replace(\n range: CodeRange,\n code: string,\n duration?: number,\n ): TOwner | ThreadGenerator {\n if (duration === undefined) {\n const current = this.get();\n const [fragments, index] = extractRange(range, current.fragments);\n fragments[index] = code;\n return this.set({\n progress: current.progress,\n fragments,\n });\n } else {\n return this.replaceTween(range, code, duration);\n }\n }\n\n private *replaceTween(range: CodeRange, code: string, duration: number) {\n let current = this.get();\n const [fragments, index] = extractRange(range, current.fragments);\n const progress = createSignal(0);\n const scope = {\n progress,\n fragments: [replace(fragments[index] as string, code)],\n };\n fragments[index] = scope;\n this.set({\n progress: current.progress,\n fragments,\n });\n\n yield* progress(1, duration);\n\n current = this.get();\n this.set({\n progress: current.progress,\n fragments: current.fragments.map(fragment =>\n fragment === scope ? code : fragment,\n ),\n });\n progress.context.dispose();\n }\n\n private *editTween(value: CodeTag[], duration: number) {\n this.progress(0);\n this.set({\n progress: this.progress,\n fragments: value,\n });\n yield* this.progress(1, duration);\n const current = this.get();\n this.set({\n progress: 0,\n fragments: current.fragments.map(fragment =>\n value.includes(fragment) ? resolveCodeTag(fragment, true) : fragment,\n ),\n });\n }\n\n private *appendTween(value: string, duration: number) {\n let current = this.get();\n const progress = createSignal(0);\n const scope = {\n progress,\n fragments: [insert(value)],\n };\n this.set({\n progress: current.progress,\n fragments: [...current.fragments, scope],\n });\n yield* progress(1, duration);\n current = this.get();\n this.set({\n progress: current.progress,\n fragments: current.fragments.map(fragment =>\n fragment === scope ? value : fragment,\n ),\n });\n progress.context.dispose();\n }\n\n private *prependTween(value: string, duration: number) {\n let current = this.get();\n const progress = createSignal(0);\n const scope = {\n progress,\n fragments: [insert(value)],\n };\n this.set({\n progress: current.progress,\n fragments: [scope, ...current.fragments],\n });\n yield* progress(1, duration);\n current = this.get();\n this.set({\n progress: current.progress,\n fragments: current.fragments.map(fragment =>\n fragment === scope ? value : fragment,\n ),\n });\n progress.context.dispose();\n }\n\n public override parse(value: PossibleCodeScope): CodeScope {\n return parseCodeScope(value);\n }\n\n public override toSignal(): CodeSignal<TOwner> {\n return this.invokable;\n }\n}\n\nexport function codeSignal(): PropertyDecorator {\n return (target: any, key) => {\n const meta = getPropertyMetaOrCreate<PossibleCodeScope>(target, key);\n addInitializer(target, (instance: any) => {\n instance[key] = new CodeSignalContext(\n meta.default ?? [],\n instance,\n ).toSignal();\n });\n };\n}\n","import type {Signal} from '@twick/core';\nimport {Color} from '@twick/core';\nimport type {CanvasStyle, PossibleCanvasStyle} from '../partials';\nimport {canvasStyleParser} from '../utils';\nimport {initial, interpolation, parser, signal} from './signal';\n\nexport type CanvasStyleSignal<T> = Signal<PossibleCanvasStyle, CanvasStyle, T>;\n\nexport function canvasStyleSignal(): PropertyDecorator {\n return (target, key) => {\n signal()(target, key);\n parser(canvasStyleParser)(target, key);\n interpolation(Color.lerp)(target, key);\n initial(null)(target, key);\n };\n}\n","import type {BBox, Spacing} from '@twick/core';\nimport {Color, Vector2} from '@twick/core';\nimport type {CanvasStyle, PossibleCanvasStyle} from '../partials';\nimport {Gradient, Pattern} from '../partials';\n\nexport function canvasStyleParser(style: PossibleCanvasStyle) {\n if (style === null) {\n return null;\n }\n if (style instanceof Gradient) {\n return style;\n }\n if (style instanceof Pattern) {\n return style;\n }\n\n return new Color(style);\n}\n\nexport function resolveCanvasStyle(\n style: CanvasStyle,\n context: CanvasRenderingContext2D,\n): string | CanvasGradient | CanvasPattern {\n if (style === null) {\n return '';\n }\n if (style instanceof Color) {\n return (<Color>style).serialize();\n }\n if (style instanceof Gradient) {\n return style.canvasGradient(context);\n }\n if (style instanceof Pattern) {\n return style.canvasPattern(context) ?? '';\n }\n\n return '';\n}\n\nexport function drawRoundRect(\n context: CanvasRenderingContext2D | Path2D,\n rect: BBox,\n radius: Spacing,\n smoothCorners: boolean,\n cornerSharpness: number,\n) {\n if (\n radius.top === 0 &&\n radius.right === 0 &&\n radius.bottom === 0 &&\n radius.left === 0\n ) {\n drawRect(context, rect);\n return;\n }\n\n const topLeft = adjustRectRadius(radius.top, radius.right, radius.left, rect);\n const topRight = adjustRectRadius(\n radius.right,\n radius.top,\n radius.bottom,\n rect,\n );\n const bottomRight = adjustRectRadius(\n radius.bottom,\n radius.left,\n radius.right,\n rect,\n );\n const bottomLeft = adjustRectRadius(\n radius.left,\n radius.bottom,\n radius.top,\n rect,\n );\n\n if (smoothCorners) {\n const sharpness = (radius: number): number => {\n const val = radius * cornerSharpness;\n return radius - val;\n };\n\n context.moveTo(rect.left + topLeft, rect.top);\n context.lineTo(rect.right - topRight, rect.top);\n\n context.bezierCurveTo(\n rect.right - sharpness(topRight),\n rect.top,\n rect.right,\n rect.top + sharpness(topRight),\n rect.right,\n rect.top + topRight,\n );\n context.lineTo(rect.right, rect.bottom - bottomRight);\n\n context.bezierCurveTo(\n rect.right,\n rect.bottom - sharpness(bottomRight),\n rect.right - sharpness(bottomRight),\n rect.bottom,\n rect.right - bottomRight,\n rect.bottom,\n );\n context.lineTo(rect.left + bottomLeft, rect.bottom);\n\n context.bezierCurveTo(\n rect.left + sharpness(bottomLeft),\n rect.bottom,\n rect.left,\n rect.bottom - sharpness(bottomLeft),\n rect.left,\n rect.bottom - bottomLeft,\n );\n context.lineTo(rect.left, rect.top + topLeft);\n\n context.bezierCurveTo(\n rect.left,\n rect.top + sharpness(topLeft),\n rect.left + sharpness(topLeft),\n rect.top,\n rect.left + topLeft,\n rect.top,\n );\n return;\n }\n\n context.moveTo(rect.left + topLeft, rect.top);\n context.arcTo(rect.right, rect.top, rect.right, rect.bottom, topRight);\n context.arcTo(rect.right, rect.bottom, rect.left, rect.bottom, bottomRight);\n context.arcTo(rect.left, rect.bottom, rect.left, rect.top, bottomLeft);\n context.arcTo(rect.left, rect.top, rect.right, rect.top, topLeft);\n}\n\nexport function adjustRectRadius(\n radius: number,\n horizontal: number,\n vertical: number,\n rect: BBox,\n): number {\n const width =\n radius + horizontal > rect.width\n ? rect.width * (radius / (radius + horizontal))\n : radius;\n const height =\n radius + vertical > rect.height\n ? rect.height * (radius / (radius + vertical))\n : radius;\n\n return Math.min(width, height);\n}\n\nexport function drawRect(\n context: CanvasRenderingContext2D | Path2D,\n rect: BBox,\n) {\n context.rect(rect.x, rect.y, rect.width, rect.height);\n}\n\nexport function fillRect(context: CanvasRenderingContext2D, rect: BBox) {\n context.fillRect(rect.x, rect.y, rect.width, rect.height);\n}\n\nexport function strokeRect(context: CanvasRenderingContext2D, rect: BBox) {\n context.strokeRect(rect.x, rect.y, rect.width, rect.height);\n}\n\nexport function drawPolygon(\n path: CanvasRenderingContext2D | Path2D,\n rect: BBox,\n sides: number,\n) {\n const size = rect.size.scale(0.5);\n for (let i = 0; i <= sides; i++) {\n const theta = (i * 2 * Math.PI) / sides;\n const direction = Vector2.fromRadians(theta).perpendicular;\n const vertex = direction.mul(size);\n if (i === 0) {\n moveTo(path, vertex);\n } else {\n lineTo(path, vertex);\n }\n }\n path.closePath();\n}\n\nexport function drawImage(\n context: CanvasRenderingContext2D,\n image: CanvasImageSource,\n destination: BBox,\n): void;\nexport function drawImage(\n context: CanvasRenderingContext2D,\n image: CanvasImageSource,\n source: BBox,\n destination: BBox,\n): void;\nexport function drawImage(\n context: CanvasRenderingContext2D,\n image: CanvasImageSource,\n first: BBox,\n second?: BBox,\n): void {\n if (second) {\n context.drawImage(\n image,\n first.x,\n first.y,\n first.width,\n first.height,\n second.x,\n second.y,\n second.width,\n second.height,\n );\n } else {\n context.drawImage(image, first.x, first.y, first.width, first.height);\n }\n}\n\nexport function moveTo(\n context: CanvasRenderingContext2D | Path2D,\n position: Vector2,\n) {\n context.moveTo(position.x, position.y);\n}\n\nexport function lineTo(\n context: CanvasRenderingContext2D | Path2D,\n position: Vector2,\n) {\n context.lineTo(position.x, position.y);\n}\n\nexport function arcTo(\n context: CanvasRenderingContext2D | Path2D,\n through: Vector2,\n position: Vector2,\n radius: number,\n) {\n context.arcTo(through.x, through.y, position.x, position.y, radius);\n}\n\nexport function drawLine(\n context: CanvasRenderingContext2D | Path2D,\n points: Vector2[],\n) {\n if (points.length < 2) return;\n moveTo(context, points[0]);\n for (const point of points.slice(1)) {\n lineTo(context, point);\n }\n}\n\nexport function drawPivot(\n context: CanvasRenderingContext2D | Path2D,\n offset: Vector2,\n radius = 8,\n) {\n lineTo(context, offset.addY(-radius));\n lineTo(context, offset.addY(radius));\n lineTo(context, offset);\n lineTo(context, offset.addX(-radius));\n arc(context, offset, radius);\n}\n\nexport function arc(\n context: CanvasRenderingContext2D | Path2D,\n center: Vector2,\n radius: number,\n startAngle = 0,\n endAngle = Math.PI * 2,\n counterclockwise = false,\n) {\n context.arc(\n center.x,\n center.y,\n radius,\n startAngle,\n endAngle,\n counterclockwise,\n );\n}\n\nexport function bezierCurveTo(\n context: CanvasRenderingContext2D | Path2D,\n controlPoint1: Vector2,\n controlPoint2: Vector2,\n to: Vector2,\n) {\n context.bezierCurveTo(\n controlPoint1.x,\n controlPoint1.y,\n controlPoint2.x,\n controlPoint2.y,\n to.x,\n to.y,\n );\n}\n\nexport function quadraticCurveTo(\n context: CanvasRenderingContext2D | Path2D,\n controlPoint: Vector2,\n to: Vector2,\n) {\n context.quadraticCurveTo(controlPoint.x, controlPoint.y, to.x, to.y);\n}\n","import type {SignalValue, SimpleSignal} from '@twick/core';\nimport {createSignal, map, transformScalar} from '@twick/core';\n\n/**\n * All possible CSS filter names.\n *\n * @internal\n */\nexport type FilterName =\n | 'invert'\n | 'sepia'\n | 'grayscale'\n | 'brightness'\n | 'contrast'\n | 'saturate'\n | 'hue'\n | 'blur';\n\n/**\n * Definitions of all possible CSS filters.\n *\n * @internal\n */\nexport const FILTERS: Record<string, Partial<FilterProps>> = {\n invert: {\n name: 'invert',\n },\n sepia: {\n name: 'sepia',\n },\n grayscale: {\n name: 'grayscale',\n },\n brightness: {\n name: 'brightness',\n default: 1,\n },\n contrast: {\n name: 'contrast',\n default: 1,\n },\n saturate: {\n name: 'saturate',\n default: 1,\n },\n hue: {\n name: 'hue-rotate',\n unit: 'deg',\n scale: 1,\n },\n blur: {\n name: 'blur',\n transform: true,\n unit: 'px',\n scale: 1,\n },\n};\n\n/**\n * A unified abstraction for all CSS filters.\n */\nexport interface FilterProps {\n name: string;\n value: SignalValue<number>;\n unit: string;\n scale: number;\n transform: boolean;\n default: number;\n}\n\nexport class Filter {\n public get name() {\n return this.props.name;\n }\n\n public get default() {\n return this.props.default;\n }\n\n public readonly value: SimpleSignal<number, Filter>;\n private readonly props: FilterProps;\n\n public constructor(props: Partial<FilterProps>) {\n this.props = {\n name: 'invert',\n default: 0,\n unit: '%',\n scale: 100,\n transform: false,\n ...props,\n value: props.value ?? props.default ?? 0,\n };\n this.value = createSignal(this.props.value, map, this);\n }\n\n public isActive() {\n return this.value() !== this.props.default;\n }\n\n public serialize(matrix: DOMMatrix): string {\n let value = this.value();\n if (this.props.transform) {\n value = transformScalar(value, matrix);\n }\n\n return `${this.props.name}(${value * this.props.scale}${this.props.unit})`;\n }\n}\n\n/**\n * Create an {@link https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/invert | invert} filter.\n *\n * @param value - The value of the filter.\n */\nexport function invert(value?: SignalValue<number>) {\n return new Filter({...FILTERS.invert, value});\n}\n\n/**\n * Create a {@link https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/sepia | sepia} filter.\n *\n * @param value - The value of the filter.\n */\nexport function sepia(value?: SignalValue<number>) {\n return new Filter({...FILTERS.sepia, value});\n}\n\n/**\n * Create a {@link https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/grayscale | grayscale} filter.\n *\n * @param value - The value of the filter.\n */\nexport function grayscale(value?: SignalValue<number>) {\n return new Filter({...FILTERS.grayscale, value});\n}\n\n/**\n * Create a {@link https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/brightness | brightness} filter.\n *\n * @param value - The value of the filter.\n */\nexport function brightness(value?: SignalValue<number>) {\n return new Filter({...FILTERS.brightness, value});\n}\n\n/**\n * Create a {@link https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/contrast | contrast} filter.\n *\n * @param value - The value of the filter.\n */\nexport function contrast(value?: SignalValue<number>) {\n return new Filter({...FILTERS.contrast, value});\n}\n\n/**\n * Create a {@link https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/saturate | saturate} filter.\n *\n * @param value - The value of the filter.\n */\nexport function saturate(value?: SignalValue<number>) {\n return new Filter({...FILTERS.saturate, value});\n}\n\n/**\n * Create a {@link https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/hue-rotate | hue} filter.\n *\n * @param value - The value of the filter in degrees.\n */\nexport function hue(value?: SignalValue<number>) {\n return new Filter({...FILTERS.hue, value});\n}\n\n/**\n * Create a {@link https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/blur | blur} filter.\n *\n * @param value - The value of the filter in pixels.\n */\nexport function blur(value?: SignalValue<number>) {\n return new Filter({...FILTERS.blur, value});\n}\n","import type {\n PossibleColor,\n PossibleVector2,\n SignalValue,\n SimpleSignal,\n Vector2Signal,\n} from '@twick/core';\nimport {Color, unwrap} from '@twick/core';\nimport {computed} from '../decorators/computed';\nimport {initial, initializeSignals, signal} from '../decorators/signal';\nimport {vector2Signal} from '../decorators/vector2Signal';\n\nexport type GradientType = 'linear' | 'conic' | 'radial';\n\nexport interface GradientStop {\n offset: SignalValue<number>;\n color: SignalValue<PossibleColor>;\n}\n\nexport interface GradientProps {\n type?: SignalValue<GradientType>;\n fromX?: SignalValue<number>;\n fromY?: SignalValue<number>;\n from?: SignalValue<PossibleVector2>;\n toX?: SignalValue<number>;\n toY?: SignalValue<number>;\n to?: SignalValue<PossibleVector2>;\n angle?: SignalValue<number>;\n fromRadius?: SignalValue<number>;\n toRadius?: SignalValue<number>;\n stops?: GradientStop[];\n}\n\nexport class Gradient {\n @initial('linear')\n @signal()\n public declare readonly type: SimpleSignal<GradientType, this>;\n\n @vector2Signal('from')\n public declare readonly from: Vector2Signal<this>;\n\n @vector2Signal('to')\n public declare readonly to: Vector2Signal<this>;\n\n @initial(0)\n @signal()\n public declare readonly angle: SimpleSignal<number, this>;\n @initial(0)\n @signal()\n public declare readonly fromRadius: SimpleSignal<number, this>;\n @initial(0)\n @signal()\n public declare readonly toRadius: SimpleSignal<number, this>;\n @initial([])\n @signal()\n public declare readonly stops: SimpleSignal<GradientStop[], this>;\n\n public constructor(props: GradientProps) {\n initializeSignals(this, props);\n }\n\n @computed()\n public canvasGradient(context: CanvasRenderingContext2D): CanvasGradient {\n let gradient: CanvasGradient;\n switch (this.type()) {\n case 'linear':\n gradient = context.createLinearGradient(\n this.from.x(),\n this.from.y(),\n this.to.x(),\n this.to.y(),\n );\n break;\n case 'conic':\n gradient = context.createConicGradient(\n this.angle(),\n this.from.x(),\n this.from.y(),\n );\n break;\n case 'radial':\n gradient = context.createRadialGradient(\n this.from.x(),\n this.from.y(),\n this.fromRadius(),\n this.to.x(),\n this.to.y(),\n this.toRadius(),\n );\n break;\n }\n\n for (const {offset, color} of this.stops()) {\n gradient.addColorStop(\n unwrap(offset),\n new Color(unwrap(color)).serialize(),\n );\n }\n\n return gradient;\n }\n}\n","import {createComputed} from '@twick/core';\nimport {addInitializer} from './initializers';\n\n/**\n * Create a computed method decorator.\n *\n * @remarks\n * This decorator turns the given method into a computed value.\n * See {@link createComputed} for more information.\n */\nexport function computed(): MethodDecorator {\n return (target: any, key) => {\n addInitializer(target, (instance: any) => {\n const method = Object.getPrototypeOf(instance)[key];\n instance[key] = createComputed(method.bind(instance), instance);\n });\n };\n}\n","const INITIALIZERS = Symbol.for('@twick/2d/decorators/initializers');\n\nexport type Initializer<T> = (instance: T, context?: any) => void;\n\nexport function addInitializer<T>(target: any, initializer: Initializer<T>) {\n if (!target[INITIALIZERS]) {\n target[INITIALIZERS] = [];\n } else if (\n // if one of the prototypes has initializers\n target[INITIALIZERS] &&\n // and it's not the target object itself\n !Object.prototype.hasOwnProperty.call(target, INITIALIZERS)\n ) {\n const base = Object.getPrototypeOf(target);\n target[INITIALIZERS] = [...base[INITIALIZERS]];\n }\n\n target[INITIALIZERS].push(initializer);\n}\n\nexport function initialize(target: any, context?: any) {\n if (target[INITIALIZERS]) {\n try {\n target[INITIALIZERS].forEach((initializer: Initializer<any>) =>\n initializer(target, context),\n );\n } catch (e: any) {\n e.inspect ??= target.key;\n throw e;\n }\n }\n}\n","import type {\n InterpolationFunction,\n SignalValue,\n TimingFunction,\n} from '@twick/core';\nimport {capitalize, deepLerp, SignalContext, useLogger} from '@twick/core';\nimport {makeSignalExtensions} from '../utils/makeSignalExtensions';\nimport {addInitializer, initialize} from './initializers';\n\nexport interface PropertyMetadata<T> {\n default?: T;\n interpolationFunction?: InterpolationFunction<T>;\n parser?: (value: any) => T;\n getter?: () => T;\n setter?: (value: any) => void;\n tweener?: (\n value: T,\n duration: number,\n timingFunction: TimingFunction,\n interpolationFunction: InterpolationFunction<T>,\n ) => void;\n cloneable?: boolean;\n inspectable?: boolean;\n compoundParent?: string;\n compound?: boolean;\n compoundEntries: [string, string][];\n}\n\nconst PROPERTIES = Symbol.for('@twick/2d/decorators/properties');\n\nexport function getPropertyMeta<T>(\n object: any,\n key: string | symbol,\n): PropertyMetadata<T> | null {\n return object[PROPERTIES]?.[key] ?? null;\n}\n\nexport function getPropertyMetaOrCreate<T>(\n object: any,\n key: string | symbol,\n): PropertyMetadata<T> {\n let lookup: Record<string | symbol, PropertyMetadata<T>>;\n if (!object[PROPERTIES]) {\n object[PROPERTIES] = lookup = {};\n } else if (\n object[PROPERTIES] &&\n !Object.prototype.hasOwnProperty.call(object, PROPERTIES)\n ) {\n object[PROPERTIES] = lookup = Object.fromEntries<PropertyMetadata<T>>(\n Object.entries(\n <Record<string | symbol, PropertyMetadata<T>>>object[PROPERTIES],\n ).map(([key, meta]) => [key, {...meta}]),\n );\n } else {\n lookup = object[PROPERTIES];\n }\n\n lookup[key] ??= {\n cloneable: true,\n inspectable: true,\n compoundEntries: [],\n };\n return lookup[key];\n}\n\nexport function getPropertiesOf(\n value: any,\n): Record<string, PropertyMetadata<any>> {\n if (value && typeof value === 'object') {\n return value[PROPERTIES] ?? {};\n }\n\n return {};\n}\n\nexport function initializeSignals(instance: any, props: Record<string, any>) {\n initialize(instance);\n for (const [key, meta] of Object.entries(getPropertiesOf(instance))) {\n const signal = instance[key];\n signal.reset();\n if (props[key] !== undefined) {\n signal(props[key]);\n }\n if (meta.compoundEntries !== undefined) {\n for (const [key, property] of meta.compoundEntries) {\n if (property in props) {\n signal[key](props[property]);\n }\n }\n }\n }\n}\n\n/**\n * Create a signal decorator.\n *\n * @remarks\n * This decorator turns the given property into a signal.\n *\n * The class using this decorator can implement the following methods:\n * - `get[PropertyName]` - A property getter.\n * - `get[PropertyName]` - A property setter.\n * - `tween[PropertyName]` - A tween provider.\n *\n * @example\n * ```ts\n * class Example {\n * \\@property()\n * public declare length: Signal<number, this>;\n * }\n * ```\n */\nexport function signal<T>(): PropertyDecorator {\n return (target: any, key) => {\n // FIXME property metadata is not inherited\n // Consider retrieving it inside the initializer using the instance and not\n // the class.\n const meta = getPropertyMetaOrCreate<T>(target, key);\n addInitializer(target, (instance: any) => {\n let initial: SignalValue<T> = meta.default!;\n const defaultMethod = instance[`getDefault${capitalize(key as string)}`];\n if (defaultMethod) {\n initial = () => defaultMethod.call(instance, meta.default);\n }\n\n const signal = new SignalContext<T, T, any>(\n initial,\n meta.interpolationFunction ?? deepLerp,\n instance,\n meta.parser?.bind(instance),\n makeSignalExtensions(meta, instance, <string>key),\n );\n instance[key] = signal.toSignal();\n });\n };\n}\n\n/**\n * Create an initial signal value decorator.\n *\n * @remarks\n * This decorator specifies the initial value of a property.\n *\n * Must be specified before the {@link signal} decorator.\n *\n * @example\n * ```ts\n * class Example {\n * \\@initial(1)\n * \\@property()\n * public declare length: Signal<number, this>;\n * }\n * ```\n *\n * @param value - The initial value of the property.\n */\nexport function initial<T>(value: T): PropertyDecorator {\n return (target: any, key) => {\n const meta = getPropertyMeta<T>(target, key);\n if (!meta) {\n useLogger().error(`Missing property decorator for \"${key.toString()}\"`);\n return;\n }\n meta.default = value;\n };\n}\n\n/**\n * Create a signal interpolation function decorator.\n *\n * @remarks\n * This decorator specifies the interpolation function of a property.\n * The interpolation function is used when tweening between different values.\n *\n * Must be specified before the {@link signal} decorator.\n *\n * @example\n * ```ts\n * class Example {\n * \\@interpolation(textLerp)\n * \\@property()\n * public declare text: Signal<string, this>;\n * }\n * ```\n *\n * @param value - The interpolation function for the property.\n */\nexport function interpolation<T>(\n value: InterpolationFunction<T>,\n): PropertyDecorator {\n return (target: any, key) => {\n const meta = getPropertyMeta<T>(target, key);\n if (!meta) {\n useLogger().error(`Missing property decorator for \"${key.toString()}\"`);\n return;\n }\n meta.interpolationFunction = value;\n };\n}\n\n/**\n * Create a signal parser decorator.\n *\n * @remarks\n * This decorator specifies the parser of a property.\n * Instead of returning the raw value, its passed as the first parameter to the\n * parser and the resulting value is returned.\n *\n * If the wrapper class has a method called `lerp` it will be set as the\n * default interpolation function for the property.\n *\n * Must be specified before the {@link signal} decorator.\n *\n * @example\n * ```ts\n * class Example {\n * \\@wrapper(Vector2)\n * \\@property()\n * public declare offset: Signal<Vector2, this>;\n * }\n * ```\n *\n * @param value - The wrapper class for the property.\n */\nexport function parser<T>(value: (value: any) => T): PropertyDecorator {\n return (target: any, key) => {\n const meta = getPropertyMeta<T>(target, key);\n if (!meta) {\n useLogger().error(`Missing property decorator for \"${key.toString()}\"`);\n return;\n }\n meta.parser = value;\n };\n}\n\n/**\n * Create a signal wrapper decorator.\n *\n * @remarks\n * This is a shortcut decorator for setting both the {@link parser} and\n * {@link interpolation}.\n *\n * The interpolation function will be set only if the wrapper class has a method\n * called `lerp`, which will be used as said function.\n *\n * Must be specified before the {@link signal} decorator.\n *\n * @example\n * ```ts\n * class Example {\n * \\@wrapper(Vector2)\n * \\@property()\n * public declare offset: Signal<Vector2, this>;\n *\n * // same as:\n * \\@parser(value => new Vector2(value))\n * \\@interpolation(Vector2.lerp)\n * \\@property()\n * public declare offset: Signal<Vector2, this>;\n * }\n * ```\n *\n * @param value - The wrapper class for the property.\n */\nexport function wrapper<T>(\n value: (new (value: any) => T) & {lerp?: InterpolationFunction<T>},\n): PropertyDecorator {\n return (target: any, key) => {\n const meta = getPropertyMeta<T>(target, key);\n if (!meta) {\n useLogger().error(`Missing property decorator for \"${key.toString()}\"`);\n return;\n }\n meta.parser = raw => new value(raw);\n if ('lerp' in value) {\n meta.interpolationFunction ??= value.lerp;\n }\n };\n}\n\n/**\n * Create a cloneable property decorator.\n *\n * @remarks\n * This decorator specifies whether the property should be copied over when\n * cloning the node.\n *\n * By default, any property is cloneable.\n *\n * Must be specified before the {@link signal} decorator.\n *\n * @example\n * ```ts\n * class Example {\n * \\@clone(false)\n * \\@property()\n * public declare length: Signal<number, this>;\n * }\n * ```\n *\n * @param value - Whether the property should be cloneable.\n */\nexport function cloneable<T>(value = true): PropertyDecorator {\n return (target: any, key) => {\n const meta = getPropertyMeta<T>(target, key);\n if (!meta) {\n useLogger().error(`Missing property decorator for \"${key.toString()}\"`);\n return;\n }\n meta.cloneable = value;\n };\n}\n\n/**\n * Create an inspectable property decorator.\n *\n * @remarks\n * This decorator specifies whether the property should be visible in the\n * inspector.\n *\n * By default, any property is inspectable.\n *\n * Must be specified before the {@link signal} decorator.\n *\n * @example\n * ```ts\n * class Example {\n * \\@inspectable(false)\n * \\@property()\n * public declare hiddenLength: Signal<number, this>;\n * }\n * ```\n *\n * @param value - Whether the property should be inspectable.\n */\nexport function inspectable<T>(value = true): PropertyDecorator {\n return (target: any, key) => {\n const meta = getPropertyMeta<T>(target, key);\n if (!meta) {\n useLogger().error(`Missing property decorator for \"${key.toString()}\"`);\n return;\n }\n meta.inspectable = value;\n };\n}\n","import type {SignalExtensions} from '@twick/core';\nimport {capitalize} from '@twick/core';\nimport type {PropertyMetadata} from '../decorators';\n\nexport function makeSignalExtensions<TSetterValue, TValue extends TSetterValue>(\n meta: Partial<PropertyMetadata<TValue>> = {},\n owner?: any,\n name?: string,\n) {\n const extensions: Partial<SignalExtensions<TSetterValue, TValue>> = {};\n\n if (name && owner) {\n const setter = meta.setter ?? owner?.[`set${capitalize(name)}`];\n if (setter) {\n extensions.setter = setter.bind(owner);\n }\n\n const getter = meta.getter ?? owner?.[`get${capitalize(name)}`];\n if (getter) {\n extensions.getter = getter.bind(owner);\n }\n\n const tweener = meta.tweener ?? owner?.[`tween${capitalize(name)}`];\n if (tweener) {\n extensions.tweener = tweener.bind(owner);\n }\n }\n\n return extensions;\n}\n","import type {PossibleVector2, Signal} from '@twick/core';\nimport {Vector2} from '@twick/core';\nimport type {Length} from '../partials';\nimport {compound} from './compound';\nimport {wrapper} from './signal';\n\nexport type Vector2LengthSignal<TOwner> = Signal<\n PossibleVector2<Length>,\n Vector2,\n TOwner\n> & {\n x: Signal<Length, number, TOwner>;\n y: Signal<Length, number, TOwner>;\n};\n\nexport function vector2Signal(\n prefix?: string | Record<string, string>,\n): PropertyDecorator {\n return (target, key) => {\n compound(\n typeof prefix === 'object'\n ? prefix\n : {\n x: prefix ? `${prefix}X` : 'x',\n y: prefix ? `${prefix}Y` : 'y',\n },\n )(target, key);\n wrapper(Vector2)(target, key);\n };\n}\n","import {\n CompoundSignalContext,\n SignalContext,\n deepLerp,\n map,\n modify,\n useLogger,\n} from '@twick/core';\nimport {makeSignalExtensions} from '../utils/makeSignalExtensions';\nimport {addInitializer} from './initializers';\nimport {getPropertyMetaOrCreate} from './signal';\n\n/**\n * Create a compound property decorator.\n *\n * @remarks\n * This decorator turns a given property into a signal consisting of one or more\n * nested signals.\n *\n * @example\n * ```ts\n * class Example {\n * \\@compound({x: 'scaleX', y: 'scaleY'})\n * public declare readonly scale: Signal<Vector2, this>;\n *\n * public setScale() {\n * this.scale({x: 7, y: 3});\n * // same as:\n * this.scale.x(7).scale.y(3);\n * }\n * }\n * ```\n *\n * @param entries - A record mapping the property in the compound object to the\n * corresponding property on the owner node.\n */\nexport function compound(entries: Record<string, string>): PropertyDecorator {\n return (target, key) => {\n const meta = getPropertyMetaOrCreate<any>(target, key);\n meta.compound = true;\n meta.compoundEntries = Object.entries(entries);\n\n addInitializer(target, (instance: any) => {\n if (!meta.parser) {\n useLogger().error(`Missing parser decorator for \"${key.toString()}\"`);\n return;\n }\n\n const initial = meta.default;\n const parser = meta.parser.bind(instance);\n const signalContext = new CompoundSignalContext(\n meta.compoundEntries.map(([key, property]) => {\n const signal = new SignalContext(\n modify(initial, value => parser(value)[key]),\n <any>map,\n instance,\n undefined,\n makeSignalExtensions(undefined, instance, property),\n ).toSignal();\n return [key, signal];\n }),\n parser,\n initial,\n meta.interpolationFunction ?? deepLerp,\n instance,\n makeSignalExtensions(meta, instance, <string>key),\n );\n\n instance[key] = signalContext.toSignal();\n });\n };\n}\n","import type {SimpleSignal} from '@twick/core';\nimport {computed} from '../decorators/computed';\nimport {initial, initializeSignals, signal} from '../decorators/signal';\n\nexport type CanvasRepetition =\n | null\n | 'repeat'\n | 'repeat-x'\n | 'repeat-y'\n | 'no-repeat';\n\nexport interface PatternProps {\n image: CanvasImageSource;\n repetition?: CanvasRepetition;\n}\n\nexport class Pattern {\n @signal()\n public declare readonly image: SimpleSignal<CanvasImageSource, this>;\n @initial(null)\n @signal()\n public declare readonly repetition: SimpleSignal<CanvasRepetition, this>;\n\n public constructor(props: PatternProps) {\n initializeSignals(this, props);\n }\n\n @computed()\n public canvasPattern(\n context: CanvasRenderingContext2D,\n ): CanvasPattern | null {\n return context.createPattern(this.image(), this.repetition());\n }\n}\n","/**\n * Create a predicate that checks if the given object is an instance of the\n * given class.\n *\n * @param klass - The class to check against.\n */\nexport function is<T>(\n klass: new (...args: any[]) => T,\n): (object: any) => object is T {\n return (object): object is T => object instanceof klass;\n}\n","import {Color} from '@twick/core';\nimport {signal, wrapper} from './signal';\n\nexport function colorSignal(): PropertyDecorator {\n return (target, key) => {\n signal()(target, key);\n wrapper(Color)(target, key);\n };\n}\n","import {capitalize} from '@twick/core';\nimport type {Layout} from '../components';\n\nexport function defaultStyle<T>(\n styleName: string,\n parse: (value: string) => T = value => value as T,\n): PropertyDecorator {\n return (target: any, key) => {\n target[`getDefault${capitalize(<string>key)}`] = function (this: Layout) {\n this.requestLayoutUpdate();\n const old = (<any>this.element.style)[styleName];\n (<any>this.element.style)[styleName] = '';\n const ret = parse.call(this, this.styles.getPropertyValue(styleName));\n (<any>this.element.style)[styleName] = old;\n return ret;\n };\n };\n}\n","import type {\n Signal,\n SignalValue,\n SimpleSignal,\n ThreadGenerator,\n TimingFunction,\n} from '@twick/core';\nimport {\n SignalContext,\n all,\n deepLerp,\n easeInOutCubic,\n unwrap,\n} from '@twick/core';\nimport type {FilterName} from '../partials';\nimport {FILTERS, Filter} from '../partials';\nimport {addInitializer} from './initializers';\nimport {getPropertyMetaOrCreate} from './signal';\n\nexport type FiltersSignal<TOwner> = Signal<\n Filter[],\n Filter[],\n TOwner,\n FiltersSignalContext<TOwner>\n> & {\n [K in FilterName]: SimpleSignal<number, TOwner>;\n};\n\nexport class FiltersSignalContext<TOwner> extends SignalContext<\n Filter[],\n Filter[],\n TOwner\n> {\n public constructor(initial: Filter[], owner: TOwner) {\n super(initial, deepLerp, owner);\n\n for (const filter in FILTERS) {\n const props = FILTERS[filter];\n Object.defineProperty(this.invokable, filter, {\n value: (\n newValue?: SignalValue<number>,\n duration?: number,\n timingFunction: TimingFunction = easeInOutCubic,\n ) => {\n if (newValue === undefined) {\n return (\n this.get()\n ?.find(filter => filter.name === props.name)\n ?.value() ??\n props.default ??\n 0\n );\n }\n\n let instance = this.get()?.find(filter => filter.name === props.name);\n if (!instance) {\n instance = new Filter(props);\n this.set([...this.get(), instance]);\n }\n\n if (duration === undefined) {\n instance.value(newValue);\n return this.owner;\n }\n\n return instance.value(newValue, duration, timingFunction);\n },\n });\n }\n }\n\n public override *tweener(\n value: SignalValue<Filter[]>,\n duration: number,\n timingFunction: TimingFunction,\n ): ThreadGenerator {\n const from = this.get();\n const to = unwrap(value);\n\n if (areFiltersCompatible(from, to)) {\n yield* all(\n ...from.map((filter, i) =>\n filter.value(to[i].value(), duration, timingFunction),\n ),\n );\n this.set(to);\n return;\n }\n\n for (const filter of to) {\n filter.value(filter.default);\n }\n\n const toValues = to.map(filter => filter.value.context.raw());\n const partialDuration =\n from.length > 0 && to.length > 0 ? duration / 2 : duration;\n if (from.length > 0) {\n yield* all(\n ...from.map(filter =>\n filter.value(filter.default, partialDuration, timingFunction),\n ),\n );\n }\n this.set(to);\n if (to.length > 0) {\n yield* all(\n ...to.map((filter, index) =>\n filter.value(toValues[index]!, partialDuration, timingFunction),\n ),\n );\n }\n }\n}\n\nexport function filtersSignal(): PropertyDecorator {\n return (target: any, key) => {\n const meta = getPropertyMetaOrCreate<Filter[]>(target, key);\n addInitializer(target, (instance: any) => {\n instance[key] = new FiltersSignalContext(\n meta.default ?? [],\n instance,\n ).toSignal();\n });\n };\n}\n\nfunction areFiltersCompatible(a: Filter[], b: Filter[]) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i].name !== b[i].name) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * @internal\n */\nexport const NODE_NAME = Symbol.for('@twick/2d/nodeName');\n\n/**\n * @internal\n */\nexport function nodeName(name: string) {\n return function (target: any) {\n target.prototype[NODE_NAME] = name;\n };\n}\n","export type CodeTokenizer = (input: string) => string[];\n\n/**\n * Default tokenizer function used by ownerless code signals.\n *\n * @param input - The code to tokenize.\n */\nexport function defaultTokenize(input: string): string[] {\n const tokens: string[] = [];\n let currentToken = '';\n let whitespace = false;\n\n for (const char of input) {\n switch (char) {\n case ' ':\n case '\\t':\n case '\\n':\n if (!whitespace && currentToken !== '') {\n tokens.push(currentToken);\n currentToken = '';\n }\n whitespace = true;\n currentToken += char;\n break;\n case '(':\n case ')':\n case '{':\n case '}':\n case '[':\n case ']':\n if (currentToken !== '') {\n tokens.push(currentToken);\n currentToken = '';\n }\n whitespace = false;\n tokens.push(char);\n break;\n default:\n if (whitespace && currentToken !== '') {\n tokens.push(currentToken);\n currentToken = '';\n }\n whitespace = false;\n currentToken += char;\n break;\n }\n }\n\n if (currentToken !== '') {\n tokens.push(currentToken);\n }\n\n return tokens;\n}\n","import type {CodeRange} from './CodeRange';\nimport type {CodeTag} from './CodeScope';\nimport {resolveCodeTag} from './CodeScope';\n\n/**\n * Transform the fragments to isolate the given range into its own fragment.\n *\n * @remarks\n * This function will try to preserve the original fragments, resolving them\n * only if they overlap with the range.\n *\n * @param range - The range to extract.\n * @param fragments - The fragments to transform.\n *\n * @returns A tuple containing the transformed fragments and the index of the\n * isolated fragment within.\n */\nexport function extractRange(\n range: CodeRange,\n fragments: CodeTag[],\n): [CodeTag[], number] {\n const [from, to] = range;\n let [fromRow, fromColumn] = from;\n let [toRow, toColumn] = to;\n if (fromRow > toRow || (fromRow === toRow && fromColumn > toColumn)) {\n [fromRow, fromColumn] = to;\n [toRow, toColumn] = from;\n }\n\n let currentRow = 0;\n let currentColumn = 0;\n const newFragments: CodeTag[] = [];\n let index = -1;\n let found = false;\n let extracted = '';\n\n for (const fragment of fragments) {\n if (found) {\n newFragments.push(fragment);\n continue;\n }\n\n const resolved = resolveCodeTag(fragment, false);\n const lines = resolved.split('\\n');\n const newRows = lines.length - 1;\n const lastColumn = lines[newRows].length;\n const nextColumn = newRows > 0 ? lastColumn : currentColumn + lastColumn;\n\n if (\n fromRow > currentRow + newRows ||\n (fromRow === currentRow + newRows && fromColumn > nextColumn)\n ) {\n currentRow += newRows;\n currentColumn = nextColumn;\n newFragments.push(fragment);\n continue;\n }\n\n for (let i = 0; i < resolved.length; i++) {\n const char = resolved.charAt(i);\n if (fromRow === currentRow && fromColumn >= currentColumn) {\n if (fromColumn === currentColumn) {\n index = newFragments.length + 1;\n newFragments.push(resolved.slice(0, i), '');\n } else if (char === '\\n') {\n index = newFragments.length + 1;\n newFragments.push(\n resolved.slice(0, i) + ' '.repeat(fromColumn - currentColumn),\n '',\n );\n }\n }\n\n if (index !== -1 && toRow === currentRow && toColumn >= currentColumn) {\n if (toColumn === currentColumn) {\n newFragments.push(resolved.slice(i));\n found = true;\n break;\n }\n\n if (char === '\\n') {\n if (currentColumn < toColumn) {\n extracted += '\\n';\n if (i + 1 < resolved.length) {\n newFragments.push(resolved.slice(i + 1));\n }\n } else {\n newFragments.push(resolved.slice(i));\n }\n found = true;\n break;\n }\n }\n\n if (index !== -1) {\n extracted += char;\n }\n\n if (char === '\\n') {\n currentRow++;\n currentColumn = 0;\n } else {\n currentColumn++;\n }\n }\n\n if (index === -1) {\n newFragments.push(fragment);\n }\n }\n\n if (index === -1) {\n index = newFragments.length + 1;\n const missingRows = fromRow - currentRow;\n const missingColumns =\n missingRows > 0 ? fromColumn : fromColumn - currentColumn;\n newFragments.push(\n '\\n'.repeat(missingRows) + ' '.repeat(missingColumns),\n '',\n );\n }\n\n newFragments[index] = extracted;\n\n return [newFragments, index];\n}\n","import {HighlightStyle} from '@codemirror/language';\nimport {tags as t} from '@lezer/highlight';\n\nexport const DefaultHighlightStyle = HighlightStyle.define([\n {tag: t.keyword, color: '#5e81ac'},\n {\n tag: [t.name, t.deleted, t.character, t.propertyName, t.macroName],\n color: '#88c0d0',\n },\n {tag: [t.variableName], color: '#8fbcbb'},\n {tag: [t.function(t.variableName)], color: '#8fbcbb'},\n {tag: [t.labelName], color: '#81a1c1'},\n {\n tag: [t.color, t.constant(t.name), t.standard(t.name)],\n color: '#5e81ac',\n },\n {tag: [t.definition(t.name), t.separator], color: '#a3be8c'},\n {tag: [t.brace], color: '#8fbcbb'},\n {\n tag: [t.annotation],\n color: '#d30102',\n },\n {\n tag: [t.number, t.changed, t.annotation, t.modifier, t.self, t.namespace],\n color: '#b48ead',\n },\n {\n tag: [t.typeName, t.className],\n color: '#ECEFF4',\n },\n {\n tag: [t.operator, t.operatorKeyword],\n color: '#a3be8c',\n },\n {\n tag: [t.tagName],\n color: '#b48ead',\n },\n {\n tag: [t.squareBracket],\n color: '#ECEFF4',\n },\n {\n tag: [t.angleBracket],\n color: '#ECEFF4',\n },\n {\n tag: [t.attributeName],\n color: '#eceff4',\n },\n {\n tag: [t.regexp],\n color: '#5e81ac',\n },\n {\n tag: [t.quote],\n color: '#b48ead',\n },\n {tag: [t.string], color: '#a3be8c'},\n {\n tag: t.link,\n color: '#a3be8c',\n textDecoration: 'underline',\n textUnderlinePosition: 'under',\n },\n {\n tag: [t.url, t.escape, t.special(t.string)],\n color: '#8fbcbb',\n },\n {tag: [t.meta], color: '#88c0d0'},\n {tag: [t.monospace], color: '#d8dee9', fontStyle: 'italic'},\n {tag: [t.comment], color: '#4c566a', fontStyle: 'italic'},\n {tag: t.strong, fontWeight: 'bold', color: '#5e81ac'},\n {tag: t.emphasis, fontStyle: 'italic', color: '#5e81ac'},\n {tag: t.strikethrough, textDecoration: 'line-through'},\n {tag: t.heading, fontWeight: 'bold', color: '#5e81ac'},\n {tag: t.special(t.heading1), fontWeight: 'bold', color: '#5e81ac'},\n {tag: t.heading1, fontWeight: 'bold', color: '#5e81ac'},\n {\n tag: [t.heading2, t.heading3, t.heading4],\n fontWeight: 'bold',\n color: '#5e81ac',\n },\n {\n tag: [t.heading5, t.heading6],\n color: '#5e81ac',\n },\n {tag: [t.atom, t.bool, t.special(t.variableName)], color: '#d08770'},\n {\n tag: [t.processingInstruction, t.inserted],\n color: '#8fbcbb',\n },\n {\n tag: [t.contentSeparator],\n color: '#ebcb8b',\n },\n {tag: t.invalid, color: '#434c5e', borderBottom: `1px dotted #d30102`},\n]);\n","import type {HighlightStyle} from '@codemirror/language';\nimport type {Parser, SyntaxNode, Tree} from '@lezer/common';\nimport {highlightTree} from '@lezer/highlight';\nimport type {CodeHighlighter, HighlightResult} from './CodeHighlighter';\nimport {DefaultHighlightStyle} from './DefaultHighlightStyle';\n\ninterface LezerCache {\n tree: Tree;\n code: string;\n colorLookup: Map<string, string>;\n}\n\nexport class LezerHighlighter implements CodeHighlighter<LezerCache | null> {\n private static classRegex = /\\.(\\S+).*color:([^;]+)/;\n private readonly classLookup = new Map<string, string>();\n\n public constructor(\n private readonly parser: Parser,\n private readonly style: HighlightStyle = DefaultHighlightStyle,\n ) {\n for (const rule of this.style.module?.getRules().split('\\n') ?? []) {\n const match = rule.match(LezerHighlighter.classRegex);\n if (!match) {\n continue;\n }\n\n const className = match[1];\n const color = match[2].trim();\n this.classLookup.set(className, color);\n }\n }\n\n public initialize(): boolean {\n return true;\n }\n\n public prepare(code: string): LezerCache | null {\n const colorLookup = new Map<string, string>();\n const tree = this.parser.parse(code);\n highlightTree(tree, this.style, (from, to, classes) => {\n const color = this.classLookup.get(classes);\n if (!color) {\n return;\n }\n\n const cursor = tree.cursorAt(from, 1);\n do {\n const id = this.getNodeId(cursor.node);\n colorLookup.set(id, color);\n } while (cursor.next() && cursor.to <= to);\n });\n\n return {\n tree,\n code,\n colorLookup,\n };\n }\n\n public highlight(index: number, cache: LezerCache | null): HighlightResult {\n if (!cache) {\n return {\n color: null,\n skipAhead: 0,\n };\n }\n\n const node = cache.tree.resolveInner(index, 1);\n const id = this.getNodeId(node);\n const color = cache.colorLookup.get(id);\n if (color) {\n return {\n color,\n skipAhead: node.to - index,\n };\n }\n\n let skipAhead = 0;\n if (!node.firstChild) {\n skipAhead = node.to - index;\n }\n\n return {\n color: null,\n skipAhead,\n };\n }\n\n public tokenize(code: string): string[] {\n const tree = this.parser.parse(code);\n const cursor = tree.cursor();\n const tokens: string[] = [];\n let current = 0;\n\n do {\n if (!cursor.node.firstChild) {\n if (cursor.from > current) {\n tokens.push(code.slice(current, cursor.from));\n }\n if (cursor.from < cursor.to) {\n tokens.push(code.slice(cursor.from, cursor.to));\n }\n current = cursor.to;\n }\n } while (cursor.next());\n\n return tokens;\n }\n\n private getNodeId(node: SyntaxNode): string {\n return `${node.from}:${node.to}`;\n }\n}\n","import {DependencyContext, PlaybackState} from '@twick/core';\nimport {computed, nodeName} from '../decorators';\nimport type {MediaProps} from './Media';\nimport {Media} from './Media';\n\n@nodeName('Audio')\nexport class Audio extends Media {\n private static readonly pool: Record<string, HTMLAudioElement> = {};\n\n public constructor(props: MediaProps) {\n super(props);\n }\n\n protected mediaElement(): HTMLAudioElement {\n return this.audio();\n }\n\n protected seekedMedia(): HTMLAudioElement {\n return this.seekedAudio();\n }\n\n protected fastSeekedMedia(): HTMLAudioElement {\n return this.fastSeekedAudio();\n }\n\n @computed()\n protected audio(): HTMLAudioElement {\n const src = this.src();\n \n // Use a temporary key for undefined src to avoid conflicts\n const key = `${this.key}/${src || 'pending'}`;\n \n let audio = Audio.pool[key];\n if (!audio) {\n audio = document.createElement('audio');\n audio.crossOrigin = 'anonymous';\n \n // Only set src if it's valid, otherwise leave it empty\n if (src && src !== 'undefined') {\n audio.src = src;\n }\n \n Audio.pool[key] = audio;\n } else if (src && src !== 'undefined' && audio.src !== src) {\n // Update existing audio element if src has changed and is now valid\n audio.src = src;\n \n // Move audio to correct pool key\n delete Audio.pool[key];\n const newKey = `${this.key}/${src}`;\n Audio.pool[newKey] = audio;\n }\n\n // If src is still undefined, wait for it to become available\n if (!src || src === 'undefined') {\n DependencyContext.collectPromise(\n new Promise<void>(resolve => {\n // Check periodically for valid src\n const checkSrc = () => {\n const currentSrc = this.src();\n if (currentSrc && currentSrc !== 'undefined') {\n resolve();\n } else {\n setTimeout(checkSrc, 10);\n }\n };\n checkSrc();\n }),\n );\n }\n\n const weNeedToWait = this.waitForCanPlayNecessary(audio);\n if (!weNeedToWait) {\n return audio;\n }\n\n DependencyContext.collectPromise(\n new Promise<void>(resolve => {\n this.waitForCanPlay(audio, resolve);\n }),\n );\n\n return audio;\n }\n\n @computed()\n protected seekedAudio(): HTMLAudioElement {\n const audio = this.audio();\n\n audio.addEventListener('ended', () => {\n this.pause();\n });\n\n if (!(this.time() < audio.duration)) {\n this.pause();\n return audio;\n }\n\n const time = this.clampTime(this.time());\n audio.playbackRate = this.playbackRate();\n\n if (!audio.paused) {\n audio.pause();\n }\n\n if (this.lastTime === time) {\n return audio;\n }\n\n this.setCurrentTime(time);\n\n return audio;\n }\n\n @computed()\n protected fastSeekedAudio(): HTMLAudioElement {\n const audio = this.audio();\n\n if (!(this.time() < audio.duration)) {\n this.pause();\n return audio;\n }\n\n const time = this.clampTime(this.time());\n\n audio.playbackRate = this.playbackRate();\n\n if (this.lastTime === time) {\n return audio;\n }\n\n const playing =\n this.playing() && time < audio.duration && audio.playbackRate > 0;\n if (playing) {\n if (audio.paused) {\n DependencyContext.collectPromise(audio.play());\n }\n } else {\n if (!audio.paused) {\n audio.pause();\n }\n }\n if (Math.abs(audio.currentTime - time) > 0.3) {\n this.setCurrentTime(time);\n } else if (!playing) {\n audio.currentTime = time;\n }\n\n return audio;\n }\n\n protected override async draw(context: CanvasRenderingContext2D) {\n // Auto-start playback if Twick is playing but media isn't\n this.autoPlayBasedOnTwick();\n \n const playbackState = this.view().playbackState();\n\n playbackState === PlaybackState.Playing ||\n playbackState === PlaybackState.Presenting\n ? this.fastSeekedAudio()\n : this.seekedAudio();\n\n context.save();\n context.restore();\n\n await this.drawChildren(context);\n }\n}\n","import type {SignalValue, SimpleSignal} from '@twick/core';\nimport {\n DependencyContext,\n PlaybackState,\n clamp,\n isReactive,\n useLogger,\n useThread,\n} from '@twick/core';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport type {RectProps} from './Rect';\nimport {Rect} from './Rect';\n\nexport interface MediaProps extends RectProps {\n src?: SignalValue<string>;\n loop?: SignalValue<boolean>;\n playbackRate?: number;\n volume?: number;\n time?: SignalValue<number>;\n play?: boolean;\n awaitCanPlay?: SignalValue<boolean>;\n allowVolumeAmplificationInPreview?: SignalValue<boolean>;\n}\n\nconst reactivePlaybackRate = `\nThe \\`playbackRate\\` of a \\`Video\\` cannot be reactive.\n\nMake sure to use a concrete value and not a function:\n\n\\`\\`\\`ts wrong\nvideo.playbackRate(() => 7);\n\\`\\`\\`\n\n\\`\\`\\`ts correct\nvideo.playbackRate(7);\n\\`\\`\\`\n\nIf you're using a signal, extract its value before passing it to the property:\n\n\\`\\`\\`ts wrong\nvideo.playbackRate(mySignal);\n\\`\\`\\`\n\n\\`\\`\\`ts correct\nvideo.playbackRate(mySignal());\n\\`\\`\\`\n`;\n\n@nodeName('Media')\nexport abstract class Media extends Rect {\n @initial('')\n @signal()\n public declare readonly src: SimpleSignal<string, this>;\n\n @initial(false)\n @signal()\n public declare readonly loop: SimpleSignal<boolean, this>;\n\n @initial(1)\n @signal()\n public declare readonly playbackRate: SimpleSignal<number, this>;\n\n @initial(0)\n @signal()\n protected declare readonly time: SimpleSignal<number, this>;\n\n @initial(false)\n @signal()\n protected declare readonly playing: SimpleSignal<boolean, this>;\n\n @initial(true)\n @signal()\n protected declare readonly awaitCanPlay: SimpleSignal<boolean, this>;\n\n @initial(false)\n @signal()\n protected declare readonly allowVolumeAmplificationInPreview: SimpleSignal<\n boolean,\n this\n >;\n\n protected declare volume: number;\n\n protected static readonly amplificationPool: Record<\n string,\n {\n audioContext: AudioContext;\n sourceNode: MediaElementAudioSourceNode;\n gainNode: GainNode;\n }\n > = {};\n protected lastTime = -1;\n private isSchedulingPlay = false;\n\n public constructor(props: MediaProps) {\n super(props);\n \n if (!this.awaitCanPlay()) {\n this.scheduleSeek(this.time());\n }\n\n if (props.play) {\n this.play();\n }\n this.volume = props.volume ?? 1;\n // Only set volume immediately if media is ready\n if (!this.awaitCanPlay()) {\n this.setVolume(this.volume);\n }\n }\n \n public isPlaying(): boolean {\n return this.playing();\n }\n\n public getCurrentTime(): number {\n return this.clampTime(this.time());\n }\n\n public getDuration(): number {\n try {\n const mElement = this.mediaElement();\n const isVideo = (mElement instanceof HTMLVideoElement);\n const isAudio = (mElement instanceof HTMLAudioElement);\n return (this.isIOS() && (isVideo || isAudio)) ? 2 /** dummy duration for iOS */ : mElement.duration; \n } catch (error) {\n // If media element is not ready yet, return a default duration\n return 0;\n }\n }\n\n public getVolume(): number {\n return this.volume;\n }\n\n public getUrl(): string {\n try {\n return this.mediaElement().src;\n } catch (error) {\n // If media element is not ready yet, return the src signal value\n return this.src();\n }\n }\n\n public override dispose() {\n // Set playing state to false without trying to access media element\n this.playing(false);\n this.time.save();\n this.remove();\n super.dispose();\n }\n\n @computed()\n public override completion(): number {\n return this.clampTime(this.time()) / this.getDuration();\n }\n\n protected abstract mediaElement(): HTMLMediaElement;\n\n protected abstract seekedMedia(): HTMLMediaElement;\n\n protected abstract fastSeekedMedia(): HTMLMediaElement;\n\n protected abstract override draw(\n context: CanvasRenderingContext2D,\n ): Promise<void>;\n\n protected setCurrentTime(value: number) {\n try {\n const media = this.mediaElement();\n if (media.readyState < 2) return;\n\n media.currentTime = value;\n this.lastTime = value;\n if (media.seeking) {\n DependencyContext.collectPromise(\n new Promise<void>(resolve => {\n const listener = () => {\n resolve();\n media.removeEventListener('seeked', listener);\n };\n media.addEventListener('seeked', listener);\n }),\n );\n }\n } catch (error) {\n // If media element is not ready yet, just update the lastTime\n this.lastTime = value;\n }\n }\n\n public setVolume(volume: number) {\n if (volume < 0) {\n console.warn(\n `volumes cannot be negative - the value will be clamped to 0.`,\n );\n }\n \n // Store the volume value\n this.volume = volume;\n \n try {\n const media = this.mediaElement();\n media.volume = Math.min(Math.max(volume, 0), 1);\n\n if (volume > 1) {\n if (this.allowVolumeAmplificationInPreview()) {\n this.amplify(media, volume);\n return;\n }\n console.warn(\n `you have set the volume of node ${this.key} to ${volume} - your video will be exported with the correct volume, but the browser does not support volumes higher than 1 by default. To enable volume amplification in the preview, set the \"allowVolumeAmplificationInPreview\" of your <Video/> or <Audio/> tag to true. Note that amplification for previews will not work if you use autoplay within the player due to browser autoplay policies: https://developer.chrome.com/blog/autoplay/#webaudio.`,\n );\n }\n } catch (error) {\n // If media element is not ready yet, just store the volume\n // It will be applied when the media becomes available via collectAsyncResources\n }\n }\n\n @computed()\n protected amplify(node: HTMLMediaElement, volume: number) {\n const key = `${this.src()}/${this.key}`;\n\n if (Media.amplificationPool[key]) {\n Media.amplificationPool[key].gainNode.gain.value = volume;\n return;\n }\n\n const audioContext = new AudioContext();\n const sourceNode = audioContext.createMediaElementSource(node);\n const gainNode = audioContext.createGain();\n\n gainNode.gain.value = volume;\n sourceNode.connect(gainNode);\n gainNode.connect(audioContext.destination);\n\n Media.amplificationPool[key] = {audioContext, sourceNode, gainNode};\n\n if (typeof window === 'undefined' || audioContext.state !== 'suspended') {\n return;\n }\n\n // Start audio context after user interation, neccessary due to browser autoplay policies\n const handleInteraction = () => {\n Media.amplificationPool[key].audioContext.resume();\n window.removeEventListener('click', handleInteraction);\n };\n window.addEventListener('click', handleInteraction);\n }\n\n protected setPlaybackRate(playbackRate: number) {\n let value: number;\n if (isReactive(playbackRate)) {\n value = playbackRate();\n useLogger().warn({\n message: 'Invalid value set as the playback rate',\n remarks: reactivePlaybackRate,\n inspect: this.key,\n stack: new Error().stack,\n });\n } else {\n value = playbackRate;\n }\n this.playbackRate.context.setter(value);\n\n if (this.playing()) {\n if (value === 0) {\n this.pause();\n } else {\n const time = useThread().time;\n const start = time();\n const offset = this.time();\n this.time(() => this.clampTime(offset + (time() - start) * value));\n }\n }\n }\n\n protected scheduleSeek(time: number) {\n // Defer the media element access to avoid immediate async property access\n setTimeout(() => {\n try {\n const media = this.mediaElement();\n \n // Use the existing waitForCanPlay method which handles readiness properly\n this.waitForCanPlay(media, () => {\n // Wait until the media is ready to seek again as\n // setting the time before the video doesn't work reliably.\n media.currentTime = time;\n });\n } catch (error) {\n // If media element is not ready yet, retry after a longer delay\n setTimeout(() => this.scheduleSeek(time), 50);\n }\n }, 0);\n }\n\n /**\n * Waits for the canplay event to be fired before calling onCanPlay.\n *\n * If the media is already ready to play, onCanPlay is called immediately.\n * @param onCanPlay - The function to call when the media is ready to play.\n * @returns\n */\n protected waitForCanPlay(media: HTMLMediaElement, onCanPlay: () => void) {\n // Be more strict - require readyState >= 3 (HAVE_FUTURE_DATA) for better reliability\n if (media.readyState >= 3) {\n onCanPlay();\n return;\n }\n \n const onCanPlayWrapper = () => {\n onCanPlay();\n media.removeEventListener('canplay', onCanPlayWrapper);\n media.removeEventListener('canplaythrough', onCanPlayWrapper);\n };\n\n const onError = () => {\n const reason = this.getErrorReason(media.error?.code);\n const srcValue = this.src();\n \n console.log(`ERROR: Error loading video: src=\"${srcValue}\", ${reason}`);\n console.log(`Media element src: \"${media.src}\"`);\n media.removeEventListener('error', onError);\n media.removeEventListener('canplay', onCanPlayWrapper);\n media.removeEventListener('canplaythrough', onCanPlayWrapper);\n };\n\n // Listen for both canplay and canplaythrough events\n media.addEventListener('canplay', onCanPlayWrapper);\n media.addEventListener('canplaythrough', onCanPlayWrapper);\n media.addEventListener('error', onError);\n }\n\n /**\n * Returns true if we should wait for the media to be ready to play.\n */\n protected waitForCanPlayNecessary(media: HTMLMediaElement): boolean {\n if (media.readyState >= 2) {\n return false;\n }\n\n return (\n this.awaitCanPlay() ||\n this.view().playbackState() === PlaybackState.Rendering\n );\n }\n\n public play() {\n console.log('=== Media.play() called ===');\n // Set the playing state first\n this.playing(true);\n \n // Schedule the actual play operation for when media is ready\n this.schedulePlay();\n }\n \n protected schedulePlay() {\n // Prevent recursive calls\n if (this.isSchedulingPlay) {\n return;\n }\n \n this.isSchedulingPlay = true;\n \n // Check if thread context is available before accessing it\n let timeFunction: (() => number) | null = null;\n try {\n const time = useThread().time;\n timeFunction = time;\n } catch (error) {\n // Reset flag and use simple play without thread time\n this.isSchedulingPlay = false;\n this.simplePlay();\n return;\n }\n \n // We need to wait for the media to be ready before we can play it\n // Use a setTimeout to defer the operation and avoid immediate async property access\n setTimeout(() => {\n // Check if we're still supposed to be playing (avoid race conditions)\n const isPlaying = this.playing();\n if (!isPlaying) {\n this.isSchedulingPlay = false;\n return;\n }\n \n // Add another timeout to further defer media element access\n setTimeout(() => {\n try {\n const media = this.mediaElement();\n \n // Always use waitForCanPlay to ensure media is ready\n this.waitForCanPlay(media, () => {\n // Double-check we're still playing before calling actuallyPlay\n if (this.playing() && timeFunction) {\n this.actuallyPlay(media, timeFunction);\n }\n // Reset the flag when done\n this.isSchedulingPlay = false;\n });\n } catch (error) {\n // Reset flag before retry\n this.isSchedulingPlay = false;\n // If media is not ready yet, retry after a longer delay\n setTimeout(() => this.schedulePlay(), 100);\n }\n }, 10);\n }, 0);\n }\n \n private simplePlay() {\n setTimeout(() => {\n try {\n const media = this.mediaElement();\n \n // Guard against undefined src\n if (!media.src || media.src.includes('undefined')) {\n return;\n }\n \n if (media.paused && this.playing()) {\n media.playbackRate = this.playbackRate();\n const playPromise = media.play();\n if (playPromise !== undefined) {\n playPromise.then(() => {\n console.log('Simple play started successfully');\n }).catch(error => {\n if (error.name !== 'AbortError') {\n console.warn('Error in simple play:', error);\n }\n this.playing(false);\n });\n }\n }\n } catch (error) {\n // Stop retries for errors\n return;\n }\n }, 10);\n }\n \n private actuallyPlay(media: HTMLMediaElement, timeFunction: () => number) {\n console.log('=== actuallyPlay called ===');\n console.log('Media element:', media);\n console.log('Media src:', media.src);\n console.log('Media paused:', media.paused);\n console.log('Media readyState:', media.readyState);\n \n // Make sure we're still supposed to be playing\n if (!this.playing()) {\n console.log('Playing state is false, aborting actuallyPlay');\n return;\n }\n \n // Set playback rate on media element\n media.playbackRate = this.playbackRate();\n \n // Ensure the media is ready to play\n if (media.paused) {\n console.log('Media is paused, calling play()');\n // Start playing the media element\n const playPromise = media.play();\n if (playPromise !== undefined) {\n playPromise.then(() => {\n console.log('Media play() promise resolved - should be playing now');\n console.log('Post-play media paused:', media.paused);\n console.log('Post-play media currentTime:', media.currentTime);\n }).catch(error => {\n // Don't warn about AbortError - it's normal when play() is interrupted by pause()\n if (error.name !== 'AbortError') {\n console.warn('Error playing media:', error);\n }\n this.playing(false);\n });\n }\n } else {\n console.log('Media is already playing');\n }\n \n // Set up time synchronization\n const start = timeFunction();\n const offset = media.currentTime;\n \n // Update time signal\n this.time(() => {\n const newTime = this.clampTime(offset + (timeFunction() - start) * this.playbackRate());\n return newTime;\n });\n }\n\n public pause() {\n // Set the playing state first\n this.playing(false);\n this.time.save();\n \n // Try to pause the media element if it's available\n // Use setTimeout to defer access and avoid async property issues\n setTimeout(() => {\n try {\n const media = this.mediaElement();\n media.pause();\n } catch (error) {\n // If media element is not ready yet, just update the state\n // The media won't be playing anyway if it's not ready\n }\n }, 0);\n }\n\n public clampTime(time: number): number {\n const duration = this.getDuration();\n if (this.loop()) {\n time %= duration;\n }\n return clamp(0, duration, time);\n }\n\n protected override collectAsyncResources() {\n super.collectAsyncResources();\n this.seekedMedia();\n // Ensure volume is set when media becomes available\n this.setVolume(this.volume);\n }\n\n protected autoPlayBasedOnTwick() {\n // Auto-start/stop playback based on Twick's playback state\n const playbackState = this.view().playbackState();\n // console.log('autoPlayBasedOnTwick called:', {\n // playbackState,\n // currentlyPlaying: this.playing(),\n // shouldAutoPlay: (playbackState === PlaybackState.Playing || playbackState === PlaybackState.Presenting) && !this.playing(),\n // shouldAutoPause: playbackState === PlaybackState.Paused && this.playing()\n // });\n \n if ((playbackState === PlaybackState.Playing || playbackState === PlaybackState.Presenting) && !this.playing()) {\n console.log('Auto-starting media playback via play() method');\n this.play(); // Call the full play() method instead of just setting playing(true)\n } else if (playbackState === PlaybackState.Paused && this.playing()) {\n console.log('Auto-pausing media playback via pause() method');\n this.pause(); // Call the full pause() method\n }\n }\n\n protected getErrorReason(errCode?: number) {\n let reason;\n switch (errCode) {\n case 1:\n reason = 'MEDIA_ERR_ABORTED';\n break;\n case 2:\n reason = 'MEDIA_ERR_NETWORK. This might be a 404 error.';\n break;\n case 3:\n reason =\n 'MEDIA_ERR_DECODE. This might be an issue with your video file.';\n break;\n case 4:\n reason =\n 'MEDIA_ERR_SRC_NOT_SUPPORTED. If you are sure that the path to the video is correct, this might be a CORS error.';\n break;\n default:\n reason = 'UNKNOWN';\n }\n\n return reason;\n }\n\n // Helper method to check if running on iOS\n protected isIOS(): boolean {\n if (typeof navigator === 'undefined') return false;\n const isIos = /iPad|iPhone|iPod/.test(navigator.userAgent) || \n (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);\n\n return isIos;\n }\n}\n","import type {\n PossibleSpacing,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n SpacingSignal,\n} from '@twick/core';\nimport {BBox} from '@twick/core';\nimport {getRectProfile} from '../curves/getRectProfile';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport {spacingSignal} from '../decorators/spacingSignal';\nimport type {DesiredLength} from '../partials';\nimport {drawRoundRect} from '../utils';\nimport type {CurveProps} from './Curve';\nimport {Curve} from './Curve';\n\nexport interface RectProps extends CurveProps {\n /**\n * {@inheritDoc Rect.radius}\n */\n radius?: SignalValue<PossibleSpacing>;\n\n /**\n * {@inheritDoc Rect.smoothCorners}\n */\n smoothCorners?: SignalValue<boolean>;\n\n /**\n * {@inheritDoc Rect.cornerSharpness}\n */\n cornerSharpness?: SignalValue<number>;\n}\n\n@nodeName('Rect')\nexport class Rect extends Curve {\n /**\n * Rounds the corners of this rectangle.\n *\n * @remarks\n * The value represents the radius of the quarter circle that is used to round\n * the corners. If the value is a number, the same radius is used for all\n * corners. Passing an array of two to four numbers will set individual radii\n * for each corner. Individual radii correspond to different corners depending\n * on the number of values passed:\n *\n * ```ts\n * // top-left-and-bottom-right | top-right-and-bottom-left\n * [10, 30]\n * // top-left | top-right-and-bottom-left | bottom-right\n * [10, 20, 30]\n * // top-left | top-right | bottom-right | bottom-left\n * [10, 20, 30, 40]\n * ```\n *\n * @example\n * One uniform radius:\n * ```tsx\n * <Rect\n * size={320}\n * radius={40}\n * fill={'white'}\n * />\n * ```\n * @example\n * Individual radii for each corner:\n * ```tsx\n * <Rect\n * size={320}\n * radius={[10, 20, 30, 40]}\n * fill={'white'}\n * />\n * ```\n */\n @spacingSignal('radius')\n public declare readonly radius: SpacingSignal<this>;\n\n /**\n * Enables corner smoothing.\n *\n * @remarks\n * This property only affects the way rounded corners are drawn. To control\n * the corner radius use the {@link radius} property.\n *\n * When enabled, rounded corners are drawn continuously using Bézier curves\n * rather than quarter circles. The sharpness of the curve can be controlled\n * with {@link cornerSharpness}.\n *\n * You can read more about corner smoothing in\n * [this article by Nick Lawrence](https://uxplanet.org/ui-ux-design-corner-smoothing-720509d1ae48).\n *\n * @example\n * ```tsx\n * <Rect\n * width={300}\n * height={300}\n * smoothCorners={true}\n * />\n * ```\n */\n @initial(false)\n @signal()\n public declare readonly smoothCorners: SimpleSignal<boolean, this>;\n\n /**\n * Controls the sharpness of {@link smoothCorners}.\n *\n * @remarks\n * This property only affects the way rounded corners are drawn. To control\n * the corner radius use the {@link radius} property.\n *\n * Requires {@link smoothCorners} to be enabled to have any effect.\n * By default, corner sharpness is set to `0.6` which represents a smooth,\n * circle-like rounding. At `0` the edges are squared off.\n *\n * @example\n * ```tsx\n * <Rect\n * size={300}\n * smoothCorners={true}\n * cornerSharpness={0.7}\n * />\n * ```\n */\n @initial(0.6)\n @signal()\n public declare readonly cornerSharpness: SimpleSignal<number, this>;\n\n public constructor(props: RectProps) {\n super(props);\n }\n\n @computed()\n public profile() {\n return getRectProfile(\n this.childrenBBox(),\n this.radius(),\n this.smoothCorners(),\n this.cornerSharpness(),\n );\n }\n\n protected override desiredSize(): SerializedVector2<DesiredLength> {\n return {\n x: this.width.context.getter(),\n y: this.height.context.getter(),\n };\n }\n\n protected override offsetComputedLayout(box: BBox): BBox {\n return box;\n }\n\n protected override childrenBBox(): BBox {\n return BBox.fromSizeCentered(this.computedSize());\n }\n\n protected override getPath(): Path2D {\n if (this.requiresProfile()) {\n return this.curveDrawingInfo().path;\n }\n\n const path = new Path2D();\n const radius = this.radius();\n const smoothCorners = this.smoothCorners();\n const cornerSharpness = this.cornerSharpness();\n const box = BBox.fromSizeCentered(this.size());\n drawRoundRect(path, box, radius, smoothCorners, cornerSharpness);\n\n return path;\n }\n\n protected override getCacheBBox(): BBox {\n return super.getCacheBBox().expand(this.rippleSize());\n }\n\n protected override getRipplePath(): Path2D {\n const path = new Path2D();\n const rippleSize = this.rippleSize();\n const radius = this.radius().addScalar(rippleSize);\n const smoothCorners = this.smoothCorners();\n const cornerSharpness = this.cornerSharpness();\n const box = BBox.fromSizeCentered(this.size()).expand(rippleSize);\n drawRoundRect(path, box, radius, smoothCorners, cornerSharpness);\n\n return path;\n }\n}\n","import type {BBox, Spacing} from '@twick/core';\nimport {Vector2} from '@twick/core';\nimport {adjustRectRadius} from '../utils';\nimport {CircleSegment} from './CircleSegment';\nimport {CubicBezierSegment} from './CubicBezierSegment';\nimport type {CurveProfile} from './CurveProfile';\nimport {LineSegment} from './LineSegment';\nimport type {Segment} from './Segment';\n\nexport function getRectProfile(\n rect: BBox,\n radius: Spacing,\n smoothCorners: boolean,\n cornerSharpness: number,\n): CurveProfile {\n const profile: CurveProfile = {\n arcLength: 0,\n segments: [],\n minSin: 1,\n };\n\n const topLeft = adjustRectRadius(radius.top, radius.right, radius.left, rect);\n const topRight = adjustRectRadius(\n radius.right,\n radius.top,\n radius.bottom,\n rect,\n );\n const bottomRight = adjustRectRadius(\n radius.bottom,\n radius.left,\n radius.right,\n rect,\n );\n const bottomLeft = adjustRectRadius(\n radius.left,\n radius.bottom,\n radius.top,\n rect,\n );\n\n let from = new Vector2(rect.left + topLeft, rect.top);\n let to = new Vector2(rect.right - topRight, rect.top);\n addSegment(profile, new LineSegment(from, to));\n\n from = new Vector2(rect.right, rect.top + topRight);\n to = new Vector2(rect.right, rect.bottom - bottomRight);\n if (topRight > 0) {\n addCornerSegment(\n profile,\n from.addX(-topRight),\n topRight,\n Vector2.down,\n Vector2.right,\n smoothCorners,\n cornerSharpness,\n );\n }\n addSegment(profile, new LineSegment(from, to));\n\n from = new Vector2(rect.right - bottomRight, rect.bottom);\n to = new Vector2(rect.left + bottomLeft, rect.bottom);\n if (bottomRight > 0) {\n addCornerSegment(\n profile,\n from.addY(-bottomRight),\n bottomRight,\n Vector2.right,\n Vector2.up,\n smoothCorners,\n cornerSharpness,\n );\n }\n addSegment(profile, new LineSegment(from, to));\n\n from = new Vector2(rect.left, rect.bottom - bottomLeft);\n to = new Vector2(rect.left, rect.top + topLeft);\n if (bottomLeft > 0) {\n addCornerSegment(\n profile,\n from.addX(bottomLeft),\n bottomLeft,\n Vector2.up,\n Vector2.left,\n smoothCorners,\n cornerSharpness,\n );\n }\n addSegment(profile, new LineSegment(from, to));\n\n from = new Vector2(rect.left + topLeft, rect.top);\n if (topLeft > 0) {\n addCornerSegment(\n profile,\n from.addY(topLeft),\n topLeft,\n Vector2.left,\n Vector2.down,\n smoothCorners,\n cornerSharpness,\n );\n }\n\n return profile;\n}\n\nfunction addSegment(profile: CurveProfile, segment: Segment) {\n profile.segments.push(segment);\n profile.arcLength += segment.arcLength;\n}\n\nfunction addCornerSegment(\n profile: CurveProfile,\n center: Vector2,\n radius: number,\n fromNormal: Vector2,\n toNormal: Vector2,\n smooth: boolean,\n sharpness: number,\n) {\n const from = center.add(fromNormal.scale(radius));\n const to = center.add(toNormal.scale(radius));\n if (smooth) {\n addSegment(\n profile,\n new CubicBezierSegment(\n from,\n from.add(toNormal.scale(sharpness * radius)),\n to.add(fromNormal.scale(sharpness * radius)),\n to,\n ),\n );\n } else {\n addSegment(\n profile,\n new CircleSegment(center, radius, fromNormal, toNormal, false),\n );\n }\n}\n","import {Vector2, clamp} from '@twick/core';\nimport type {CurvePoint} from './CurvePoint';\nimport {Segment} from './Segment';\n\nexport class CircleSegment extends Segment {\n private readonly length: number;\n private readonly angle: number;\n public override readonly points: Vector2[];\n\n public constructor(\n private center: Vector2,\n private radius: number,\n private from: Vector2,\n private to: Vector2,\n private counter: boolean,\n ) {\n super();\n this.angle = Math.acos(clamp(-1, 1, from.dot(to)));\n this.length = Math.abs(this.angle * radius);\n const edgeVector = new Vector2(1, 1).scale(radius);\n this.points = [center.sub(edgeVector), center.add(edgeVector)];\n }\n\n public get arcLength(): number {\n return this.length;\n }\n\n public draw(\n context: CanvasRenderingContext2D | Path2D,\n from: number,\n to: number,\n ): [CurvePoint, CurvePoint] {\n const counterFactor = this.counter ? -1 : 1;\n const startAngle = this.from.radians + from * this.angle * counterFactor;\n const endAngle = this.to.radians - (1 - to) * this.angle * counterFactor;\n\n if (Math.abs(this.angle) > 0.0001) {\n context.arc(\n this.center.x,\n this.center.y,\n this.radius,\n startAngle,\n endAngle,\n this.counter,\n );\n }\n\n const startNormal = Vector2.fromRadians(startAngle);\n const endNormal = Vector2.fromRadians(endAngle);\n\n return [\n {\n position: this.center.add(startNormal.scale(this.radius)),\n tangent: this.counter ? startNormal : startNormal.flipped,\n normal: this.counter ? startNormal.flipped : startNormal,\n },\n {\n position: this.center.add(endNormal.scale(this.radius)),\n tangent: this.counter ? endNormal.flipped : endNormal,\n normal: this.counter ? endNormal.flipped : endNormal,\n },\n ];\n }\n\n public getPoint(distance: number): CurvePoint {\n const counterFactor = this.counter ? -1 : 1;\n const angle = this.from.radians + distance * this.angle * counterFactor;\n\n const normal = Vector2.fromRadians(angle);\n\n return {\n position: this.center.add(normal.scale(this.radius)),\n tangent: this.counter ? normal : normal.flipped,\n normal: this.counter ? normal : normal.flipped,\n };\n }\n}\n","import type {Vector2} from '@twick/core';\nimport type {CurvePoint} from './CurvePoint';\n\nexport abstract class Segment {\n public abstract readonly points: Vector2[];\n\n public abstract draw(\n context: CanvasRenderingContext2D | Path2D,\n start: number,\n end: number,\n move: boolean,\n ): [CurvePoint, CurvePoint];\n\n public abstract getPoint(distance: number): CurvePoint;\n\n public abstract get arcLength(): number;\n}\n","import {Vector2, lazy} from '@twick/core';\nimport {bezierCurveTo} from '../utils';\nimport {Polynomial2D} from './Polynomial2D';\nimport {PolynomialSegment} from './PolynomialSegment';\n\n/**\n * A spline segment representing a cubic Bézier curve.\n */\nexport class CubicBezierSegment extends PolynomialSegment {\n @lazy(() => document.createElementNS('http://www.w3.org/2000/svg', 'path'))\n private static el: SVGPathElement;\n\n public get points(): Vector2[] {\n return [this.p0, this.p1, this.p2, this.p3];\n }\n\n public constructor(\n public readonly p0: Vector2,\n public readonly p1: Vector2,\n public readonly p2: Vector2,\n public readonly p3: Vector2,\n ) {\n super(\n new Polynomial2D(\n p0,\n // 3*(-p0+p1)\n p0.flipped.add(p1).scale(3),\n // 3*p0-6*p1+3*p2\n p0.scale(3).sub(p1.scale(6)).add(p2.scale(3)),\n // -p0+3*p1-3*p2+p3\n p0.flipped.add(p1.scale(3)).sub(p2.scale(3)).add(p3),\n ),\n CubicBezierSegment.getLength(p0, p1, p2, p3),\n );\n }\n\n public split(t: number): [PolynomialSegment, PolynomialSegment] {\n const a = new Vector2(\n this.p0.x + (this.p1.x - this.p0.x) * t,\n this.p0.y + (this.p1.y - this.p0.y) * t,\n );\n const b = new Vector2(\n this.p1.x + (this.p2.x - this.p1.x) * t,\n this.p1.y + (this.p2.y - this.p1.y) * t,\n );\n const c = new Vector2(\n this.p2.x + (this.p3.x - this.p2.x) * t,\n this.p2.y + (this.p3.y - this.p2.y) * t,\n );\n const d = new Vector2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);\n const e = new Vector2(b.x + (c.x - b.x) * t, b.y + (c.y - b.y) * t);\n const p = new Vector2(d.x + (e.x - d.x) * t, d.y + (e.y - d.y) * t);\n\n const left = new CubicBezierSegment(this.p0, a, d, p);\n const right = new CubicBezierSegment(p, e, c, this.p3);\n\n return [left, right];\n }\n\n protected override doDraw(context: CanvasRenderingContext2D | Path2D) {\n bezierCurveTo(context, this.p1, this.p2, this.p3);\n }\n\n protected static getLength(\n p0: Vector2,\n p1: Vector2,\n p2: Vector2,\n p3: Vector2,\n ): number {\n // Let the browser do the work for us instead of calculating the arclength\n // manually.\n CubicBezierSegment.el.setAttribute(\n 'd',\n `M ${p0.x} ${p0.y} C ${p1.x} ${p1.y} ${p2.x} ${p2.y} ${p3.x} ${p3.y}`,\n );\n return CubicBezierSegment.el.getTotalLength();\n }\n}\n","import {BBox, Vector2} from '@twick/core';\n\nimport {Polynomial} from './Polynomial';\n\nexport class Polynomial2D {\n public readonly x: Polynomial;\n public readonly y: Polynomial;\n\n public constructor(c0: Vector2, c1: Vector2, c2: Vector2, c3: Vector2);\n public constructor(c0: Vector2, c1: Vector2, c2: Vector2);\n public constructor(x: Polynomial, y: Polynomial);\n public constructor(\n public readonly c0: Vector2 | Polynomial,\n public readonly c1: Vector2 | Polynomial,\n public readonly c2?: Vector2,\n public readonly c3?: Vector2,\n ) {\n if (c0 instanceof Polynomial) {\n this.x = c0;\n this.y = c1 as Polynomial;\n } else if (c3 !== undefined) {\n this.x = new Polynomial(c0.x, (c1 as Vector2).x, c2!.x, c3.x);\n this.y = new Polynomial(c0.y, (c1 as Vector2).y, c2!.y, c3.y);\n } else {\n this.x = new Polynomial(c0.x, (c1 as Vector2).x, c2!.x);\n this.y = new Polynomial(c0.y, (c1 as Vector2).y, c2!.y);\n }\n }\n\n public eval(t: number, derivative = 0): Vector2 {\n return new Vector2(\n this.x.differentiate(derivative).eval(t),\n this.y.differentiate(derivative).eval(t),\n );\n }\n\n public split(u: number): [Polynomial2D, Polynomial2D] {\n const [xPre, xPost] = this.x.split(u);\n const [yPre, yPost] = this.y.split(u);\n return [new Polynomial2D(xPre, yPre), new Polynomial2D(xPost, yPost)];\n }\n\n public differentiate(n = 1): Polynomial2D {\n return new Polynomial2D(this.x.differentiate(n), this.y.differentiate(n));\n }\n\n public evalDerivative(t: number): Vector2 {\n return this.differentiate().eval(t);\n }\n\n /**\n * Calculate the tight axis-aligned bounds of the curve in the unit interval.\n */\n public getBounds(): BBox {\n const rangeX = this.x.outputRange01();\n const rangeY = this.y.outputRange01();\n return BBox.fromPoints(\n new Vector2(Math.min(...rangeX), Math.max(...rangeY)),\n new Vector2(Math.max(...rangeX), Math.min(...rangeY)),\n );\n }\n}\n","import {clamp} from '@twick/core';\n\n/**\n * A polynomial in the form ax^3 + bx^2 + cx + d up to a cubic polynomial.\n *\n * Source code liberally taken from:\n * https://github.com/FreyaHolmer/Mathfs/blob/master/Runtime/Curves/Polynomial.cs\n */\nexport class Polynomial {\n public readonly c1: number;\n public readonly c2: number;\n public readonly c3: number;\n\n /**\n * Constructs a constant polynomial\n *\n * @param c0 - The constant coefficient\n */\n public static constant(c0: number): Polynomial {\n return new Polynomial(c0);\n }\n\n /**\n * Constructs a linear polynomial\n *\n * @param c0 - The constant coefficient\n * @param c1 - The linear coefficient\n */\n public static linear(c0: number, c1: number): Polynomial {\n return new Polynomial(c0, c1);\n }\n\n /**\n * Constructs a quadratic polynomial\n *\n * @param c0 - The constant coefficient\n * @param c1 - The linear coefficient\n * @param c2 - The quadratic coefficient\n */\n public static quadratic(c0: number, c1: number, c2: number): Polynomial {\n return new Polynomial(c0, c1, c2);\n }\n\n /**\n * Constructs a cubic polynomial\n *\n * @param c0 - The constant coefficient\n * @param c1 - The linear coefficient\n * @param c2 - The quadratic coefficient\n * @param c3 - The cubic coefficient\n */\n public static cubic(\n c0: number,\n c1: number,\n c2: number,\n c3: number,\n ): Polynomial {\n return new Polynomial(c0, c1, c2, c3);\n }\n\n /**\n * The degree of the polynomial\n */\n public get degree(): number {\n if (this.c3 !== 0) {\n return 3;\n } else if (this.c2 !== 0) {\n return 2;\n } else if (this.c1 !== 0) {\n return 1;\n }\n return 0;\n }\n\n /**\n * @param c0 - The constant coefficient\n */\n public constructor(c0: number);\n /**\n * @param c0 - The constant coefficient\n * @param c1 - The linear coefficient\n */\n public constructor(c0: number, c1: number);\n /**\n * @param c0 - The constant coefficient\n * @param c1 - The linear coefficient\n * @param c2 - The quadratic coefficient\n */\n public constructor(c0: number, c1: number, c2: number);\n /**\n * @param c0 - The constant coefficient\n * @param c1 - The linear coefficient\n * @param c2 - The quadratic coefficient\n * @param c3 - The cubic coefficient\n */\n public constructor(c0: number, c1: number, c2: number, c3: number);\n public constructor(\n public readonly c0: number,\n c1?: number,\n c2?: number,\n c3?: number,\n ) {\n this.c1 = c1 ?? 0;\n this.c2 = c2 ?? 0;\n this.c3 = c3 ?? 0;\n }\n\n /**\n * Return the nth derivative of the polynomial.\n *\n * @param n - The number of times to differentiate the polynomial.\n */\n public differentiate(n = 1): Polynomial {\n switch (n) {\n case 0:\n return this;\n case 1:\n return new Polynomial(this.c1, 2 * this.c2, 3 * this.c3, 0);\n case 2:\n return new Polynomial(2 * this.c2, 6 * this.c3, 0, 0);\n case 3:\n return new Polynomial(6 * this.c3, 0, 0, 0);\n default:\n throw new Error('Unsupported derivative');\n }\n }\n\n /**\n * Evaluate the polynomial at the given value t.\n *\n * @param t - The value to sample at\n */\n public eval(t: number): number;\n /**\n * Evaluate the nth derivative of the polynomial at the given value t.\n *\n * @param t - The value to sample at\n * @param derivative - The derivative of the polynomial to sample from\n */\n public eval(t: number, derivative: number): number;\n public eval(t: number, derivative = 0): number {\n if (derivative !== 0) {\n return this.differentiate(derivative).eval(t);\n }\n return this.c3 * (t * t * t) + this.c2 * (t * t) + this.c1 * t + this.c0;\n }\n\n /**\n * Split the polynomial into two polynomials of the same overall shape.\n *\n * @param u - The point at which to split the polynomial.\n */\n public split(u: number): [Polynomial, Polynomial] {\n const d = 1 - u;\n\n const pre = new Polynomial(\n this.c0,\n this.c1 * u,\n this.c2 * u * u,\n this.c3 * u * u * u,\n );\n const post = new Polynomial(\n this.eval(0),\n d * this.differentiate(1).eval(u),\n ((d * d) / 2) * this.differentiate(2).eval(u),\n ((d * d * d) / 6) * this.differentiate(3).eval(u),\n );\n\n return [pre, post];\n }\n\n /**\n * Calculate the roots (values where this polynomial = 0).\n *\n * @remarks\n * Depending on the degree of the polynomial, returns between 0 and 3 results.\n */\n public roots(): number[] {\n switch (this.degree) {\n case 3:\n return this.solveCubicRoots();\n case 2:\n return this.solveQuadraticRoots();\n case 1:\n return this.solveLinearRoot();\n case 0:\n return [];\n default:\n throw new Error(`Unsupported polynomial degree: ${this.degree}`);\n }\n }\n\n /**\n * Calculate the local extrema of the polynomial.\n */\n public localExtrema(): number[] {\n return this.differentiate().roots();\n }\n\n /**\n * Calculate the local extrema of the polynomial in the unit interval.\n */\n public localExtrema01(): number[] {\n const all = this.localExtrema();\n const valids = [];\n for (let i = 0; i < all.length; i++) {\n const t = all[i];\n if (t >= 0 && t <= 1) {\n valids.push(all[i]);\n }\n }\n return valids;\n }\n\n /**\n * Return the output value range within the unit interval.\n */\n public outputRange01(): number[] {\n let range = [this.eval(0), this.eval(1)];\n\n // Expands the minimum or maximum value of the range to contain the given\n // value.\n const encapsulate = (value: number) => {\n if (range[1] > range[0]) {\n range = [Math.min(range[0], value), Math.max(range[1], value)];\n } else {\n range = [Math.min(range[1], value), Math.max(range[0], value)];\n }\n };\n\n this.localExtrema01().forEach(t => encapsulate(this.eval(t)));\n\n return range;\n }\n\n private solveCubicRoots() {\n const a = this.c0;\n const b = this.c1;\n const c = this.c2;\n const d = this.c3;\n\n // First, depress the cubic to make it easier to solve\n const aa = a * a;\n const ac = a * c;\n const bb = b * b;\n const p = (3 * ac - bb) / (3 * aa);\n const q = (2 * bb * b - 9 * ac * b + 27 * aa * d) / (27 * aa * a);\n\n const dpr = this.solveDepressedCubicRoots(p, q);\n\n // We now have the roots of the depressed cubic, now convert back to the\n // normal cubic\n const undepressRoot = (r: number) => r - b / (3 * a);\n switch (dpr.length) {\n case 1:\n return [undepressRoot(dpr[0])];\n case 2:\n return [undepressRoot(dpr[0]), undepressRoot(dpr[1])];\n case 3:\n return [\n undepressRoot(dpr[0]),\n undepressRoot(dpr[1]),\n undepressRoot(dpr[2]),\n ];\n default:\n return [];\n }\n }\n\n private solveDepressedCubicRoots(p: number, q: number): number[] {\n // t³+pt+q = 0\n\n // Triple root - one solution. solve x³+q = 0 => x = cr(-q)\n if (this.almostZero(p)) {\n return [Math.cbrt(-q)];\n }\n\n const TAU = Math.PI * 2;\n const discriminant = 4 * p * p * p + 27 * q * q;\n if (discriminant < 0.00001) {\n // Two or three roots guaranteed, use trig solution\n const pre = 2 * Math.sqrt(-p / 3);\n const acosInner = ((3 * q) / (2 * p)) * Math.sqrt(-3 / p);\n\n const getRoot = (k: number) =>\n pre *\n Math.cos((1 / 3) * Math.acos(clamp(-1, 1, acosInner)) - (TAU / 3) * k);\n\n // If acos hits 0 or TAU/2, the offsets will have the same value,\n // which means we have a double root plus one regular root on our hands\n if (acosInner >= 0.9999) {\n // two roots - one single and one double root\n return [getRoot(0), getRoot(2)];\n }\n\n if (acosInner <= -0.9999) {\n // two roots - one single and one double root\n return [getRoot(1), getRoot(2)];\n }\n\n return [getRoot(0), getRoot(1), getRoot(2)];\n }\n\n if (discriminant > 0 && p < 0) {\n // one root\n const coshInner =\n (1 / 3) *\n Math.acosh(((-3 * Math.abs(q)) / (2 * p)) * Math.sqrt(-3 / p));\n const r = -2 * Math.sign(q) * Math.sqrt(-p / 3) * Math.cosh(coshInner);\n return [r];\n }\n\n if (p > 0) {\n // one root\n const sinhInner =\n (1 / 3) * Math.asinh(((3 * q) / (2 * p)) * Math.sqrt(3 / p));\n const r = -2 * Math.sqrt(p / 3) * Math.sinh(sinhInner);\n return [r];\n }\n\n // no roots\n return [];\n }\n\n private solveQuadraticRoots() {\n const a = this.c2;\n const b = this.c1;\n const c = this.c0;\n const rootContent = b * b - 4 * a * c;\n\n if (this.almostZero(rootContent)) {\n // two equivalent solutions at one point\n return [-b / (2 * a)];\n }\n\n if (rootContent >= 0) {\n const root = Math.sqrt(rootContent);\n // crosses at two points\n const r0 = (-b - root) / (2 * a);\n const r1 = (-b + root) / (2 * a);\n\n return [Math.min(r0, r1), Math.max(r0, r1)];\n }\n\n return [];\n }\n\n private solveLinearRoot() {\n return [-this.c0 / this.c1];\n }\n\n private almostZero(value: number) {\n return Math.abs(0 - value) <= Number.EPSILON;\n }\n}\n","import {transformVectorAsPoint, type BBox, type Vector2} from '@twick/core';\nimport {moveTo} from '../utils';\nimport type {CurvePoint} from './CurvePoint';\nimport type {Polynomial2D} from './Polynomial2D';\nimport {Segment} from './Segment';\nimport {UniformPolynomialCurveSampler} from './UniformPolynomialCurveSampler';\n\nexport abstract class PolynomialSegment extends Segment {\n protected readonly pointSampler: UniformPolynomialCurveSampler;\n\n public get arcLength(): number {\n return this.length;\n }\n\n public abstract override get points(): Vector2[];\n\n protected constructor(\n protected readonly curve: Polynomial2D,\n protected readonly length: number,\n ) {\n super();\n this.pointSampler = new UniformPolynomialCurveSampler(this);\n }\n\n public getBBox(): BBox {\n return this.curve.getBounds();\n }\n\n /**\n * Evaluate the polynomial at the given t value.\n *\n * @param t - The t value at which to evaluate the curve.\n */\n public eval(t: number): CurvePoint {\n const tangent = this.tangent(t);\n\n return {\n position: this.curve.eval(t),\n tangent,\n normal: tangent.perpendicular,\n };\n }\n\n /**\n * Split the curve into two separate polynomials at the given t value. The two\n * resulting curves form the same overall shape as the original curve.\n *\n * @param t - The t value at which to split the curve.\n */\n public abstract split(t: number): [PolynomialSegment, PolynomialSegment];\n\n public getPoint(distance: number): CurvePoint {\n const closestPoint = this.pointSampler.pointAtDistance(\n this.arcLength * distance,\n );\n return {\n position: closestPoint.position,\n tangent: closestPoint.tangent,\n normal: closestPoint.tangent.perpendicular,\n };\n }\n\n public transformPoints(matrix: DOMMatrix): Vector2[] {\n return this.points.map(point => transformVectorAsPoint(point, matrix));\n }\n\n /**\n * Return the tangent of the point that sits at the provided t value on the\n * curve.\n *\n * @param t - The t value at which to evaluate the curve.\n */\n public tangent(t: number): Vector2 {\n return this.curve.evalDerivative(t).normalized;\n }\n\n public draw(\n context: CanvasRenderingContext2D | Path2D,\n start = 0,\n end = 1,\n move = true,\n ): [CurvePoint, CurvePoint] {\n let curve: PolynomialSegment | null = null;\n let startT = start;\n let endT = end;\n let points = this.points;\n\n if (start !== 0 || end !== 1) {\n const startDistance = this.length * start;\n const endDistance = this.length * end;\n\n startT = this.pointSampler.distanceToT(startDistance);\n endT = this.pointSampler.distanceToT(endDistance);\n const relativeEndT = (endT - startT) / (1 - startT);\n\n const [, startSegment] = this.split(startT);\n [curve] = startSegment.split(relativeEndT);\n points = curve.points;\n }\n\n if (move) {\n moveTo(context, points[0]);\n }\n (curve ?? this).doDraw(context);\n\n const startTangent = this.tangent(startT);\n const endTangent = this.tangent(endT);\n\n return [\n {\n position: points[0],\n tangent: startTangent,\n normal: startTangent.perpendicular,\n },\n {\n position: points.at(-1)!,\n tangent: endTangent,\n normal: endTangent.perpendicular,\n },\n ];\n }\n\n protected abstract doDraw(context: CanvasRenderingContext2D | Path2D): void;\n}\n","import type {Vector2} from '@twick/core';\nimport {clamp, remap} from '@twick/core';\nimport type {CurvePoint} from './CurvePoint';\nimport type {PolynomialSegment} from './PolynomialSegment';\n\n/**\n * Class to uniformly sample points on a given polynomial curve.\n *\n * @remarks\n * In order to uniformly sample points from non-linear curves, this sampler\n * re-parameterizes the curve by arclength.\n */\nexport class UniformPolynomialCurveSampler {\n private sampledDistances: number[] = [];\n\n /**\n * @param curve - The curve to sample\n * @param samples - How many points to sample from the provided curve. The\n * more points get sampled, the higher the resolution–and\n * therefore precision–of the sampler.\n */\n public constructor(\n private readonly curve: PolynomialSegment,\n samples = 20,\n ) {\n this.resample(samples);\n }\n\n /**\n * Discard all previously sampled points and resample the provided number of\n * points from the curve.\n *\n * @param samples - The number of points to sample.\n */\n public resample(samples: number): void {\n this.sampledDistances = [0];\n\n let length = 0;\n let previous: Vector2 = this.curve.eval(0).position;\n for (let i = 1; i < samples; i++) {\n const t = i / (samples - 1);\n const curvePoint = this.curve.eval(t);\n const segmentLength = previous.sub(curvePoint.position).magnitude;\n\n length += segmentLength;\n\n this.sampledDistances.push(length);\n previous = curvePoint.position;\n }\n\n // Account for any accumulated floating point errors and explicitly set the\n // distance of the last point to the arclength of the curve.\n this.sampledDistances[this.sampledDistances.length - 1] =\n this.curve.arcLength;\n }\n\n /**\n * Return the point at the provided distance along the sampled curve's\n * arclength.\n *\n * @param distance - The distance along the curve's arclength for which to\n * retrieve the point.\n */\n public pointAtDistance(distance: number): CurvePoint {\n return this.curve.eval(this.distanceToT(distance));\n }\n\n /**\n * Return the t value for the point at the provided distance along the sampled\n * curve's arc length.\n *\n * @param distance - The distance along the arclength\n */\n public distanceToT(distance: number): number {\n const samples = this.sampledDistances.length;\n distance = clamp(0, this.curve.arcLength, distance);\n\n for (let i = 0; i < samples; i++) {\n const lower = this.sampledDistances[i];\n const upper = this.sampledDistances[i + 1];\n if (distance >= lower && distance <= upper) {\n return remap(\n lower,\n upper,\n i / (samples - 1),\n (i + 1) / (samples - 1),\n distance,\n );\n }\n }\n\n return 1;\n }\n}\n","import type {Vector2} from '@twick/core';\nimport {lineTo, moveTo} from '../utils';\nimport type {CurvePoint} from './CurvePoint';\nimport {Segment} from './Segment';\n\nexport class LineSegment extends Segment {\n private readonly length: number;\n private readonly vector: Vector2;\n private readonly normal: Vector2;\n public override readonly points: Vector2[];\n\n public constructor(\n public readonly from: Vector2,\n public readonly to: Vector2,\n ) {\n super();\n this.vector = to.sub(from);\n this.length = this.vector.magnitude;\n this.normal = this.vector.perpendicular.normalized.safe;\n this.points = [from, to];\n }\n\n public get arcLength(): number {\n return this.length;\n }\n\n public draw(\n context: CanvasRenderingContext2D | Path2D,\n start = 0,\n end = 1,\n move = false,\n ): [CurvePoint, CurvePoint] {\n const from = this.from.add(this.vector.scale(start));\n const to = this.from.add(this.vector.scale(end));\n if (move) {\n moveTo(context, from);\n }\n lineTo(context, to);\n\n return [\n {\n position: from,\n tangent: this.normal.flipped,\n normal: this.normal,\n },\n {\n position: to,\n tangent: this.normal,\n normal: this.normal,\n },\n ];\n }\n\n public getPoint(distance: number): CurvePoint {\n const point = this.from.add(this.vector.scale(distance));\n return {\n position: point,\n tangent: this.normal.flipped,\n normal: this.normal,\n };\n }\n}\n","import {Spacing} from '@twick/core';\nimport {compound} from './compound';\nimport {wrapper} from './signal';\n\nexport function spacingSignal(prefix?: string): PropertyDecorator {\n return (target, key) => {\n compound({\n top: prefix ? `${prefix}Top` : 'top',\n right: prefix ? `${prefix}Right` : 'right',\n bottom: prefix ? `${prefix}Bottom` : 'bottom',\n left: prefix ? `${prefix}Left` : 'left',\n })(target, key);\n wrapper(Spacing)(target, key);\n };\n}\n","import type {\n BBox,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n} from '@twick/core';\nimport {Vector2, clamp} from '@twick/core';\nimport type {CurveDrawingInfo} from '../curves/CurveDrawingInfo';\nimport type {CurvePoint} from '../curves/CurvePoint';\nimport type {CurveProfile} from '../curves/CurveProfile';\nimport {getPointAtDistance} from '../curves/getPointAtDistance';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport type {DesiredLength} from '../partials';\nimport {lineTo, moveTo, resolveCanvasStyle} from '../utils';\nimport type {ShapeProps} from './Shape';\nimport {Shape} from './Shape';\n\nexport interface CurveProps extends ShapeProps {\n /**\n * {@inheritDoc Curve.closed}\n */\n closed?: SignalValue<boolean>;\n /**\n * {@inheritDoc Curve.start}\n */\n start?: SignalValue<number>;\n /**\n * {@inheritDoc Curve.startOffset}\n */\n startOffset?: SignalValue<number>;\n /**\n * {@inheritDoc Curve.startArrow}\n */\n startArrow?: SignalValue<boolean>;\n /**\n * {@inheritDoc Curve.end}\n */\n end?: SignalValue<number>;\n /**\n * {@inheritDoc Curve.endOffset}\n */\n endOffset?: SignalValue<number>;\n /**\n * {@inheritDoc Curve.endArrow}\n */\n endArrow?: SignalValue<boolean>;\n /**\n * {@inheritDoc Curve.arrowSize}\n */\n arrowSize?: SignalValue<number>;\n}\n\n@nodeName('Curve')\nexport abstract class Curve extends Shape {\n /**\n * Whether the curve should be closed.\n *\n * @remarks\n * Closed curves have their start and end points connected.\n */\n @initial(false)\n @signal()\n public declare readonly closed: SimpleSignal<boolean, this>;\n\n /**\n * A percentage from the start before which the curve should be clipped.\n *\n * @remarks\n * The portion of the curve that comes before the given percentage will be\n * made invisible.\n *\n * This property is usefully for animating the curve appearing on the screen.\n * The value of `0` means the very start of the curve (accounting for the\n * {@link startOffset}) while `1` means the very end (accounting for the\n * {@link endOffset}).\n */\n @initial(0)\n @signal()\n public declare readonly start: SimpleSignal<number, this>;\n\n /**\n * The offset in pixels from the start of the curve.\n *\n * @remarks\n * This property lets you specify where along the defined curve the actual\n * visible portion starts. For example, setting it to `20` will make the first\n * 20 pixels of the curve invisible.\n *\n * This property is useful for trimming the curve using a fixed distance.\n * If you want to animate the curve appearing on the screen, use {@link start}\n * instead.\n */\n @initial(0)\n @signal()\n public declare readonly startOffset: SimpleSignal<number, this>;\n\n /**\n * Whether to display an arrow at the start of the visible curve.\n *\n * @remarks\n * Use {@link arrowSize} to control the size of the arrow.\n */\n @initial(false)\n @signal()\n public declare readonly startArrow: SimpleSignal<boolean, this>;\n\n /**\n * A percentage from the start after which the curve should be clipped.\n *\n * @remarks\n * The portion of the curve that comes after the given percentage will be\n * made invisible.\n *\n * This property is usefully for animating the curve appearing on the screen.\n * The value of `0` means the very start of the curve (accounting for the\n * {@link startOffset}) while `1` means the very end (accounting for the\n * {@link endOffset}).\n */\n @initial(1)\n @signal()\n public declare readonly end: SimpleSignal<number, this>;\n\n /**\n * The offset in pixels from the end of the curve.\n *\n * @remarks\n * This property lets you specify where along the defined curve the actual\n * visible portion ends. For example, setting it to `20` will make the last\n * 20 pixels of the curve invisible.\n *\n * This property is useful for trimming the curve using a fixed distance.\n * If you want to animate the curve appearing on the screen, use {@link end}\n * instead.\n */\n @initial(0)\n @signal()\n public declare readonly endOffset: SimpleSignal<number, this>;\n\n /**\n * Whether to display an arrow at the end of the visible curve.\n *\n * @remarks\n * Use {@link arrowSize} to control the size of the arrow.\n */\n @initial(false)\n @signal()\n public declare readonly endArrow: SimpleSignal<boolean, this>;\n\n /**\n * Controls the size of the end and start arrows.\n *\n * @remarks\n * To make the arrows visible make sure to enable {@link startArrow} and/or\n * {@link endArrow}.\n */\n @initial(24)\n @signal()\n public declare readonly arrowSize: SimpleSignal<number, this>;\n\n protected canHaveSubpath = false;\n\n protected override desiredSize(): SerializedVector2<DesiredLength> {\n return this.childrenBBox().size;\n }\n\n public constructor(props: CurveProps) {\n super(props);\n }\n\n protected abstract childrenBBox(): BBox;\n\n public abstract profile(): CurveProfile;\n\n /**\n * Convert a percentage along the curve to a distance.\n *\n * @remarks\n * The returned distance is given in relation to the full curve, not\n * accounting for {@link startOffset} and {@link endOffset}.\n *\n * @param value - The percentage along the curve.\n */\n public percentageToDistance(value: number): number {\n return clamp(\n 0,\n this.baseArcLength(),\n this.startOffset() + this.offsetArcLength() * value,\n );\n }\n\n /**\n * Convert a distance along the curve to a percentage.\n *\n * @remarks\n * The distance should be given in relation to the full curve, not\n * accounting for {@link startOffset} and {@link endOffset}.\n *\n * @param value - The distance along the curve.\n */\n public distanceToPercentage(value: number): number {\n return (value - this.startOffset()) / this.offsetArcLength();\n }\n\n /**\n * The base arc length of this curve.\n *\n * @remarks\n * This is the entire length of this curve, not accounting for\n * {@link startOffset | the offsets}.\n */\n public baseArcLength() {\n return this.profile().arcLength;\n }\n\n /**\n * The offset arc length of this curve.\n *\n * @remarks\n * This is the length of the curve that accounts for\n * {@link startOffset | the offsets}.\n */\n public offsetArcLength() {\n const startOffset = this.startOffset();\n const endOffset = this.endOffset();\n const baseLength = this.baseArcLength();\n return clamp(0, baseLength, baseLength - startOffset - endOffset);\n }\n\n /**\n * The visible arc length of this curve.\n *\n * @remarks\n * This arc length accounts for both the offset and the {@link start} and\n * {@link end} properties.\n */\n @computed()\n public arcLength() {\n return this.offsetArcLength() * Math.abs(this.start() - this.end());\n }\n\n /**\n * The percentage of the curve that's currently visible.\n *\n * @remarks\n * The returned value is the ratio between the visible length (as defined by\n * {@link start} and {@link end}) and the offset length of the curve.\n */\n public completion(): number {\n return Math.abs(this.start() - this.end());\n }\n\n protected processSubpath(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _path: Path2D,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _startPoint: Vector2 | null,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _endPoint: Vector2 | null,\n ) {\n // do nothing\n }\n\n @computed()\n protected curveDrawingInfo(): CurveDrawingInfo {\n const path = new Path2D();\n let subpath = new Path2D();\n const profile = this.profile();\n\n let start = this.percentageToDistance(this.start());\n let end = this.percentageToDistance(this.end());\n if (start > end) {\n [start, end] = [end, start];\n }\n\n const distance = end - start;\n const arrowSize = Math.min(distance / 2, this.arrowSize());\n\n if (this.startArrow()) {\n start += arrowSize / 2;\n }\n\n if (this.endArrow()) {\n end -= arrowSize / 2;\n }\n\n let length = 0;\n let startPoint = null;\n let startTangent = null;\n let endPoint = null;\n let endTangent = null;\n for (const segment of profile.segments) {\n const previousLength = length;\n length += segment.arcLength;\n if (length < start) {\n continue;\n }\n\n const relativeStart = (start - previousLength) / segment.arcLength;\n const relativeEnd = (end - previousLength) / segment.arcLength;\n\n const clampedStart = clamp(0, 1, relativeStart);\n const clampedEnd = clamp(0, 1, relativeEnd);\n\n if (\n this.canHaveSubpath &&\n endPoint &&\n !segment.getPoint(0).position.equals(endPoint)\n ) {\n path.addPath(subpath);\n this.processSubpath(subpath, startPoint, endPoint);\n subpath = new Path2D();\n startPoint = null;\n }\n\n const [startCurvePoint, endCurvePoint] = segment.draw(\n subpath,\n clampedStart,\n clampedEnd,\n startPoint === null,\n );\n\n if (startPoint === null) {\n startPoint = startCurvePoint.position;\n startTangent = startCurvePoint.normal.flipped.perpendicular;\n }\n\n endPoint = endCurvePoint.position;\n endTangent = endCurvePoint.normal.flipped.perpendicular;\n if (length > end) {\n break;\n }\n }\n\n if (\n this.closed() &&\n this.start.isInitial() &&\n this.end.isInitial() &&\n this.startOffset.isInitial() &&\n this.endOffset.isInitial()\n ) {\n subpath.closePath();\n }\n this.processSubpath(subpath, startPoint, endPoint);\n path.addPath(subpath);\n\n return {\n startPoint: startPoint ?? Vector2.zero,\n startTangent: startTangent ?? Vector2.right,\n endPoint: endPoint ?? Vector2.zero,\n endTangent: endTangent ?? Vector2.right,\n arrowSize,\n path,\n startOffset: start,\n };\n }\n\n protected getPointAtDistance(value: number): CurvePoint {\n return getPointAtDistance(this.profile(), value + this.startOffset());\n }\n\n public getPointAtPercentage(value: number): CurvePoint {\n return getPointAtDistance(this.profile(), this.percentageToDistance(value));\n }\n\n protected override getComputedLayout(): BBox {\n return this.offsetComputedLayout(super.getComputedLayout());\n }\n\n protected offsetComputedLayout(box: BBox): BBox {\n box.position = box.position.sub(this.childrenBBox().center);\n return box;\n }\n\n protected override getPath(): Path2D {\n return this.curveDrawingInfo().path;\n }\n\n protected override getCacheBBox(): BBox {\n const box = this.childrenBBox();\n const arrowSize =\n this.startArrow() || this.endArrow() ? this.arrowSize() : 0;\n const lineWidth = this.lineWidth();\n\n const coefficient = this.lineWidthCoefficient();\n\n return box.expand(Math.max(0, arrowSize, lineWidth * coefficient));\n }\n\n protected lineWidthCoefficient(): number {\n return this.lineCap() === 'square' ? 0.5 * 1.4143 : 0.5;\n }\n\n /**\n * Check if the path requires a profile.\n *\n * @remarks\n * The profile is only required if certain features are used. Otherwise, the\n * profile generation can be skipped, and the curve can be drawn directly\n * using the 2D context.\n */\n protected requiresProfile(): boolean {\n return (\n !this.start.isInitial() ||\n !this.startOffset.isInitial() ||\n !this.startArrow.isInitial() ||\n !this.end.isInitial() ||\n !this.endOffset.isInitial() ||\n !this.endArrow.isInitial()\n );\n }\n\n protected override drawShape(context: CanvasRenderingContext2D) {\n super.drawShape(context);\n if (this.startArrow() || this.endArrow()) {\n this.drawArrows(context);\n }\n }\n\n private drawArrows(context: CanvasRenderingContext2D) {\n const {startPoint, startTangent, endPoint, endTangent, arrowSize} =\n this.curveDrawingInfo();\n if (arrowSize < 0.001) {\n return;\n }\n\n context.save();\n context.beginPath();\n if (this.endArrow()) {\n this.drawArrow(context, endPoint, endTangent.flipped, arrowSize);\n }\n if (this.startArrow()) {\n this.drawArrow(context, startPoint, startTangent, arrowSize);\n }\n context.fillStyle = resolveCanvasStyle(this.stroke(), context);\n context.closePath();\n context.fill();\n context.restore();\n }\n\n private drawArrow(\n context: CanvasRenderingContext2D | Path2D,\n center: Vector2,\n tangent: Vector2,\n arrowSize: number,\n ) {\n const normal = tangent.perpendicular;\n const origin = center.add(tangent.scale(-arrowSize / 2));\n\n moveTo(context, origin);\n lineTo(context, origin.add(tangent.add(normal).scale(arrowSize)));\n lineTo(context, origin.add(tangent.sub(normal).scale(arrowSize)));\n lineTo(context, origin);\n context.closePath();\n }\n}\n","import {Vector2, clamp} from '@twick/core';\nimport type {CurvePoint} from './CurvePoint';\nimport type {CurveProfile} from './CurveProfile';\n\nexport function getPointAtDistance(\n profile: CurveProfile,\n distance: number,\n): CurvePoint {\n const clamped = clamp(0, profile.arcLength, distance);\n let length = 0;\n for (const segment of profile.segments) {\n const previousLength = length;\n length += segment.arcLength;\n if (length >= clamped) {\n const relative = (clamped - previousLength) / segment.arcLength;\n return segment.getPoint(clamp(0, 1, relative));\n }\n }\n\n return {position: Vector2.zero, tangent: Vector2.up, normal: Vector2.up};\n}\n","import type {BBox, SignalValue, SimpleSignal} from '@twick/core';\nimport {\n createSignal,\n easeOutExpo,\n linear,\n map,\n threadable,\n} from '@twick/core';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport type {CanvasStyleSignal} from '../decorators/canvasStyleSignal';\nimport {canvasStyleSignal} from '../decorators/canvasStyleSignal';\nimport type {PossibleCanvasStyle} from '../partials';\nimport {resolveCanvasStyle} from '../utils';\nimport type {LayoutProps} from './Layout';\nimport {Layout} from './Layout';\n\nexport interface ShapeProps extends LayoutProps {\n fill?: SignalValue<PossibleCanvasStyle>;\n stroke?: SignalValue<PossibleCanvasStyle>;\n strokeFirst?: SignalValue<boolean>;\n lineWidth?: SignalValue<number>;\n lineJoin?: SignalValue<CanvasLineJoin>;\n lineCap?: SignalValue<CanvasLineCap>;\n lineDash?: SignalValue<number[]>;\n lineDashOffset?: SignalValue<number>;\n antialiased?: SignalValue<boolean>;\n}\n\n@nodeName('Shape')\nexport abstract class Shape extends Layout {\n @canvasStyleSignal()\n public declare readonly fill: CanvasStyleSignal<this>;\n @canvasStyleSignal()\n public declare readonly stroke: CanvasStyleSignal<this>;\n @initial(false)\n @signal()\n public declare readonly strokeFirst: SimpleSignal<boolean, this>;\n @initial(0)\n @signal()\n public declare readonly lineWidth: SimpleSignal<number, this>;\n @initial('miter')\n @signal()\n public declare readonly lineJoin: SimpleSignal<CanvasLineJoin, this>;\n @initial('butt')\n @signal()\n public declare readonly lineCap: SimpleSignal<CanvasLineCap, this>;\n @initial([])\n @signal()\n public declare readonly lineDash: SimpleSignal<number[], this>;\n @initial(0)\n @signal()\n public declare readonly lineDashOffset: SimpleSignal<number, this>;\n @initial(true)\n @signal()\n public declare readonly antialiased: SimpleSignal<boolean, this>;\n\n protected readonly rippleStrength = createSignal<number, this>(0);\n\n @computed()\n protected rippleSize() {\n return easeOutExpo(this.rippleStrength(), 0, 50);\n }\n\n public constructor(props: ShapeProps) {\n super(props);\n }\n\n protected applyText(context: CanvasRenderingContext2D) {\n context.direction = this.textDirection();\n this.element.dir = this.textDirection();\n }\n\n protected applyStyle(context: CanvasRenderingContext2D) {\n context.fillStyle = resolveCanvasStyle(this.fill(), context);\n context.strokeStyle = resolveCanvasStyle(this.stroke(), context);\n context.lineWidth = this.lineWidth();\n context.lineJoin = this.lineJoin();\n context.lineCap = this.lineCap();\n context.setLineDash(this.lineDash());\n context.lineDashOffset = this.lineDashOffset();\n if (!this.antialiased()) {\n // from https://stackoverflow.com/a/68372384\n context.filter =\n 'url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxmaWx0ZXIgaWQ9ImZpbHRlciIgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj48ZmVDb21wb25lbnRUcmFuc2Zlcj48ZmVGdW5jUiB0eXBlPSJpZGVudGl0eSIvPjxmZUZ1bmNHIHR5cGU9ImlkZW50aXR5Ii8+PGZlRnVuY0IgdHlwZT0iaWRlbnRpdHkiLz48ZmVGdW5jQSB0eXBlPSJkaXNjcmV0ZSIgdGFibGVWYWx1ZXM9IjAgMSIvPjwvZmVDb21wb25lbnRUcmFuc2Zlcj48L2ZpbHRlcj48L3N2Zz4=#filter)';\n }\n }\n\n protected override async draw(context: CanvasRenderingContext2D) {\n this.drawShape(context);\n if (this.clip()) {\n context.clip(this.getPath());\n }\n await this.drawChildren(context);\n }\n\n protected drawShape(context: CanvasRenderingContext2D) {\n const path = this.getPath();\n const hasStroke = this.lineWidth() > 0 && this.stroke() !== null;\n const hasFill = this.fill() !== null;\n context.save();\n this.applyStyle(context);\n this.drawRipple(context);\n if (this.strokeFirst()) {\n hasStroke && context.stroke(path);\n hasFill && context.fill(path);\n } else {\n hasFill && context.fill(path);\n hasStroke && context.stroke(path);\n }\n context.restore();\n }\n\n protected override getCacheBBox(): BBox {\n return super.getCacheBBox().expand(this.lineWidth() / 2);\n }\n\n @computed()\n protected getPath(): Path2D {\n return new Path2D();\n }\n\n protected getRipplePath(): Path2D {\n return new Path2D();\n }\n\n protected drawRipple(context: CanvasRenderingContext2D) {\n const rippleStrength = this.rippleStrength();\n if (rippleStrength > 0) {\n const ripplePath = this.getRipplePath();\n context.save();\n context.globalAlpha *= map(0.54, 0, rippleStrength);\n context.fill(ripplePath);\n context.restore();\n }\n }\n\n @threadable()\n public *ripple(duration = 1) {\n this.rippleStrength(0);\n yield* this.rippleStrength(1, duration, linear);\n this.rippleStrength(0);\n }\n}\n","import type {\n InterpolationFunction,\n PossibleSpacing,\n PossibleVector2,\n SerializedVector2,\n Signal,\n SignalValue,\n SimpleSignal,\n SimpleVector2Signal,\n SpacingSignal,\n ThreadGenerator,\n TimingFunction,\n Vector2Signal,\n} from '@twick/core';\nimport {\n BBox,\n DependencyContext,\n Origin,\n Vector2,\n boolLerp,\n modify,\n originToOffset,\n threadable,\n transformVector,\n transformVectorAsPoint,\n tween,\n} from '@twick/core';\nimport type {Vector2LengthSignal} from '../decorators';\nimport {\n addInitializer,\n cloneable,\n computed,\n defaultStyle,\n getPropertyMeta,\n initial,\n interpolation,\n nodeName,\n signal,\n vector2Signal,\n} from '../decorators';\nimport {spacingSignal} from '../decorators/spacingSignal';\nimport type {\n DesiredLength,\n FlexBasis,\n FlexContent,\n FlexDirection,\n FlexItems,\n FlexWrap,\n LayoutMode,\n Length,\n LengthLimit,\n TextWrap,\n} from '../partials';\nimport {drawLine, drawPivot, is} from '../utils';\nimport type {NodeProps} from './Node';\nimport {Node} from './Node';\n\nexport interface LayoutProps extends NodeProps {\n layout?: LayoutMode;\n tagName?: keyof HTMLElementTagNameMap;\n\n width?: SignalValue<Length>;\n height?: SignalValue<Length>;\n maxWidth?: SignalValue<LengthLimit>;\n maxHeight?: SignalValue<LengthLimit>;\n minWidth?: SignalValue<LengthLimit>;\n minHeight?: SignalValue<LengthLimit>;\n ratio?: SignalValue<number>;\n\n marginTop?: SignalValue<number>;\n marginBottom?: SignalValue<number>;\n marginLeft?: SignalValue<number>;\n marginRight?: SignalValue<number>;\n margin?: SignalValue<PossibleSpacing>;\n\n paddingTop?: SignalValue<number>;\n paddingBottom?: SignalValue<number>;\n paddingLeft?: SignalValue<number>;\n paddingRight?: SignalValue<number>;\n padding?: SignalValue<PossibleSpacing>;\n\n direction?: SignalValue<FlexDirection>;\n basis?: SignalValue<FlexBasis>;\n grow?: SignalValue<number>;\n shrink?: SignalValue<number>;\n wrap?: SignalValue<FlexWrap>;\n\n justifyContent?: SignalValue<FlexContent>;\n alignContent?: SignalValue<FlexContent>;\n alignItems?: SignalValue<FlexItems>;\n alignSelf?: SignalValue<FlexItems>;\n rowGap?: SignalValue<Length>;\n columnGap?: SignalValue<Length>;\n gap?: SignalValue<Length>;\n\n fontFamily?: SignalValue<string>;\n fontSize?: SignalValue<number>;\n fontStyle?: SignalValue<string>;\n fontWeight?: SignalValue<number>;\n lineHeight?: SignalValue<Length>;\n letterSpacing?: SignalValue<number>;\n textWrap?: SignalValue<TextWrap>;\n textDirection?: SignalValue<CanvasDirection>;\n textAlign?: SignalValue<CanvasTextAlign>;\n\n size?: SignalValue<PossibleVector2<Length>>;\n offsetX?: SignalValue<number>;\n offsetY?: SignalValue<number>;\n offset?: SignalValue<PossibleVector2>;\n /**\n * The position of the center of this node.\n *\n * @remarks\n * This shortcut property will set the node's position so that the center ends\n * up in the given place.\n * If present, overrides the {@link NodeProps.position} property.\n * When {@link offset} is not set, this will be the same as the\n * {@link NodeProps.position}.\n */\n middle?: SignalValue<PossibleVector2>;\n /**\n * The position of the top edge of this node.\n *\n * @remarks\n * This shortcut property will set the node's position so that the top edge\n * ends up in the given place.\n * If present, overrides the {@link NodeProps.position} property.\n */\n top?: SignalValue<PossibleVector2>;\n /**\n * The position of the bottom edge of this node.\n *\n * @remarks\n * This shortcut property will set the node's position so that the bottom edge\n * ends up in the given place.\n * If present, overrides the {@link NodeProps.position} property.\n */\n bottom?: SignalValue<PossibleVector2>;\n /**\n * The position of the left edge of this node.\n *\n * @remarks\n * This shortcut property will set the node's position so that the left edge\n * ends up in the given place.\n * If present, overrides the {@link NodeProps.position} property.\n */\n left?: SignalValue<PossibleVector2>;\n /**\n * The position of the right edge of this node.\n *\n * @remarks\n * This shortcut property will set the node's position so that the right edge\n * ends up in the given place.\n * If present, overrides the {@link NodeProps.position} property.\n */\n right?: SignalValue<PossibleVector2>;\n /**\n * The position of the top left corner of this node.\n *\n * @remarks\n * This shortcut property will set the node's position so that the top left\n * corner ends up in the given place.\n * If present, overrides the {@link NodeProps.position} property.\n */\n topLeft?: SignalValue<PossibleVector2>;\n /**\n * The position of the top right corner of this node.\n *\n * @remarks\n * This shortcut property will set the node's position so that the top right\n * corner ends up in the given place.\n * If present, overrides the {@link NodeProps.position} property.\n */\n topRight?: SignalValue<PossibleVector2>;\n /**\n * The position of the bottom left corner of this node.\n *\n * @remarks\n * This shortcut property will set the node's position so that the bottom left\n * corner ends up in the given place.\n * If present, overrides the {@link NodeProps.position} property.\n */\n bottomLeft?: SignalValue<PossibleVector2>;\n /**\n * The position of the bottom right corner of this node.\n *\n * @remarks\n * This shortcut property will set the node's position so that the bottom\n * right corner ends up in the given place.\n * If present, overrides the {@link NodeProps.position} property.\n */\n bottomRight?: SignalValue<PossibleVector2>;\n clip?: SignalValue<boolean>;\n}\n\n@nodeName('Layout')\nexport class Layout extends Node {\n @initial(null)\n @interpolation(boolLerp)\n @signal()\n public declare readonly layout: SimpleSignal<LayoutMode, this>;\n\n @initial(null)\n @signal()\n public declare readonly maxWidth: SimpleSignal<LengthLimit, this>;\n @initial(null)\n @signal()\n public declare readonly maxHeight: SimpleSignal<LengthLimit, this>;\n @initial(null)\n @signal()\n public declare readonly minWidth: SimpleSignal<LengthLimit, this>;\n @initial(null)\n @signal()\n public declare readonly minHeight: SimpleSignal<LengthLimit, this>;\n @initial(null)\n @signal()\n public declare readonly ratio: SimpleSignal<number | null, this>;\n\n @spacingSignal('margin')\n public declare readonly margin: SpacingSignal<this>;\n\n @spacingSignal('padding')\n public declare readonly padding: SpacingSignal<this>;\n\n @initial('row')\n @signal()\n public declare readonly direction: SimpleSignal<FlexDirection, this>;\n @initial(null)\n @signal()\n public declare readonly basis: SimpleSignal<FlexBasis, this>;\n @initial(0)\n @signal()\n public declare readonly grow: SimpleSignal<number, this>;\n @initial(1)\n @signal()\n public declare readonly shrink: SimpleSignal<number, this>;\n @initial('nowrap')\n @signal()\n public declare readonly wrap: SimpleSignal<FlexWrap, this>;\n\n @initial('start')\n @signal()\n public declare readonly justifyContent: SimpleSignal<FlexContent, this>;\n @initial('normal')\n @signal()\n public declare readonly alignContent: SimpleSignal<FlexContent, this>;\n @initial('stretch')\n @signal()\n public declare readonly alignItems: SimpleSignal<FlexItems, this>;\n @initial('auto')\n @signal()\n public declare readonly alignSelf: SimpleSignal<FlexItems, this>;\n @initial(0)\n @vector2Signal({x: 'columnGap', y: 'rowGap'})\n public declare readonly gap: Vector2LengthSignal<this>;\n public get columnGap(): Signal<Length, number, this> {\n return this.gap.x;\n }\n public get rowGap(): Signal<Length, number, this> {\n return this.gap.y;\n }\n\n @defaultStyle('font-family')\n @signal()\n public declare readonly fontFamily: SimpleSignal<string, this>;\n @defaultStyle('font-size', parseFloat)\n @signal()\n public declare readonly fontSize: SimpleSignal<number, this>;\n @defaultStyle('font-style')\n @signal()\n public declare readonly fontStyle: SimpleSignal<string, this>;\n @defaultStyle('font-weight', parseInt)\n @signal()\n public declare readonly fontWeight: SimpleSignal<number, this>;\n @defaultStyle('line-height', parseFloat)\n @signal()\n public declare readonly lineHeight: SimpleSignal<Length, this>;\n @defaultStyle('letter-spacing', i => (i === 'normal' ? 0 : parseFloat(i)))\n @signal()\n public declare readonly letterSpacing: SimpleSignal<number, this>;\n\n @defaultStyle('white-space', i => (i === 'pre' ? 'pre' : i === 'normal'))\n @signal()\n public declare readonly textWrap: SimpleSignal<TextWrap, this>;\n @initial('inherit')\n @signal()\n public declare readonly textDirection: SimpleSignal<CanvasDirection, this>;\n @defaultStyle('text-align')\n @signal()\n public declare readonly textAlign: SimpleSignal<CanvasTextAlign, this>;\n\n protected getX(): number {\n if (this.isLayoutRoot()) {\n return this.x.context.getter();\n }\n\n return this.computedPosition().x;\n }\n protected setX(value: SignalValue<number>) {\n this.x.context.setter(value);\n }\n\n protected getY(): number {\n if (this.isLayoutRoot()) {\n return this.y.context.getter();\n }\n\n return this.computedPosition().y;\n }\n protected setY(value: SignalValue<number>) {\n this.y.context.setter(value);\n }\n\n /**\n * Represents the size of this node.\n *\n * @remarks\n * A size is a two-dimensional vector, where `x` represents the `width`, and `y`\n * represents the `height`.\n *\n * The value of both x and y is of type {@link partials.Length} which is\n * either:\n * - `number` - the desired length in pixels\n * - `${number}%` - a string with the desired length in percents, for example\n * `'50%'`\n * - `null` - an automatic length\n *\n * When retrieving the size, all units are converted to pixels, using the\n * current state of the layout. For example, retrieving the width set to\n * `'50%'`, while the parent has a width of `200px` will result in the number\n * `100` being returned.\n *\n * When the node is not part of the layout, setting its size using percents\n * refers to the size of the entire scene.\n *\n * @example\n * Initializing the size:\n * ```tsx\n * // with a possible vector:\n * <Node size={['50%', 200]} />\n * // with individual components:\n * <Node width={'50%'} height={200} />\n * ```\n *\n * Accessing the size:\n * ```tsx\n * // retrieving the vector:\n * const size = node.size();\n * // retrieving an individual component:\n * const width = node.size.x();\n * ```\n *\n * Setting the size:\n * ```tsx\n * // with a possible vector:\n * node.size(['50%', 200]);\n * node.size(() => ['50%', 200]);\n * // with individual components:\n * node.size.x('50%');\n * node.size.x(() => '50%');\n * ```\n */\n @initial({x: null, y: null})\n @vector2Signal({x: 'width', y: 'height'})\n public declare readonly size: Vector2LengthSignal<this>;\n public get width(): Signal<Length, number, this> {\n return this.size.x;\n }\n public get height(): Signal<Length, number, this> {\n return this.size.y;\n }\n\n protected getWidth(): number {\n return this.computedSize().width;\n }\n protected setWidth(value: SignalValue<Length>) {\n this.width.context.setter(value);\n }\n\n @threadable()\n protected *tweenWidth(\n value: SignalValue<Length>,\n time: number,\n timingFunction: TimingFunction,\n interpolationFunction: InterpolationFunction<Length>,\n ): ThreadGenerator {\n const width = this.desiredSize().x;\n const lock = typeof width !== 'number' || typeof value !== 'number';\n let from: number;\n if (lock) {\n from = this.size.x();\n } else {\n from = width;\n }\n\n let to: number;\n if (lock) {\n this.size.x(value);\n to = this.size.x();\n } else {\n to = value;\n }\n\n this.size.x(from);\n lock && this.lockSize();\n yield* tween(time, value =>\n this.size.x(interpolationFunction(from, to, timingFunction(value))),\n );\n this.size.x(value);\n lock && this.releaseSize();\n }\n\n protected getHeight(): number {\n return this.computedSize().height;\n }\n protected setHeight(value: SignalValue<Length>) {\n this.height.context.setter(value);\n }\n\n @threadable()\n protected *tweenHeight(\n value: SignalValue<Length>,\n time: number,\n timingFunction: TimingFunction,\n interpolationFunction: InterpolationFunction<Length>,\n ): ThreadGenerator {\n const height = this.desiredSize().y;\n const lock = typeof height !== 'number' || typeof value !== 'number';\n\n let from: number;\n if (lock) {\n from = this.size.y();\n } else {\n from = height;\n }\n\n let to: number;\n if (lock) {\n this.size.y(value);\n to = this.size.y();\n } else {\n to = value;\n }\n\n this.size.y(from);\n lock && this.lockSize();\n yield* tween(time, value =>\n this.size.y(interpolationFunction(from, to, timingFunction(value))),\n );\n this.size.y(value);\n lock && this.releaseSize();\n }\n\n /**\n * Get the desired size of this node.\n *\n * @remarks\n * This method can be used to control the size using external factors.\n * By default, the returned size is the same as the one declared by the user.\n */\n @computed()\n protected desiredSize(): SerializedVector2<DesiredLength> {\n return {\n x: this.width.context.getter(),\n y: this.height.context.getter(),\n };\n }\n\n @threadable()\n protected *tweenSize(\n value: SignalValue<SerializedVector2<Length>>,\n time: number,\n timingFunction: TimingFunction,\n interpolationFunction: InterpolationFunction<Vector2>,\n ): ThreadGenerator {\n const size = this.desiredSize();\n let from: Vector2;\n if (typeof size.x !== 'number' || typeof size.y !== 'number') {\n from = this.size();\n } else {\n from = new Vector2(<Vector2>size);\n }\n\n let to: Vector2;\n if (\n typeof value === 'object' &&\n typeof value.x === 'number' &&\n typeof value.y === 'number'\n ) {\n to = new Vector2(<Vector2>value);\n } else {\n this.size(value);\n to = this.size();\n }\n\n this.size(from);\n this.lockSize();\n yield* tween(time, value =>\n this.size(interpolationFunction(from, to, timingFunction(value))),\n );\n this.releaseSize();\n this.size(value);\n }\n\n /**\n * Represents the offset of this node's origin.\n *\n * @remarks\n * By default, the origin of a node is located at its center. The origin\n * serves as the pivot point when rotating and scaling a node, but it doesn't\n * affect the placement of its children.\n *\n * The value is relative to the size of this node. A value of `1` means as far\n * to the right/bottom as possible. Here are a few examples of offsets:\n * - `[-1, -1]` - top left corner\n * - `[1, -1]` - top right corner\n * - `[0, 1]` - bottom edge\n * - `[-1, 1]` - bottom left corner\n */\n @vector2Signal('offset')\n public declare readonly offset: Vector2Signal<this>;\n\n /**\n * The position of the center of this node.\n *\n * @remarks\n * When set, this shortcut property will modify the node's position so that\n * the center ends up in the given place.\n *\n * If the {@link offset} has not been changed, this will be the same as the\n * {@link position}.\n *\n * When retrieved, it will return the position of the center in the parent\n * space.\n */\n @originSignal(Origin.Middle)\n public declare readonly middle: SimpleVector2Signal<this>;\n\n /**\n * The position of the top edge of this node.\n *\n * @remarks\n * When set, this shortcut property will modify the node's position so that\n * the top edge ends up in the given place.\n *\n * When retrieved, it will return the position of the top edge in the parent\n * space.\n */\n @originSignal(Origin.Top)\n public declare readonly top: SimpleVector2Signal<this>;\n /**\n * The position of the bottom edge of this node.\n *\n * @remarks\n * When set, this shortcut property will modify the node's position so that\n * the bottom edge ends up in the given place.\n *\n * When retrieved, it will return the position of the bottom edge in the\n * parent space.\n */\n @originSignal(Origin.Bottom)\n public declare readonly bottom: SimpleVector2Signal<this>;\n /**\n * The position of the left edge of this node.\n *\n * @remarks\n * When set, this shortcut property will modify the node's position so that\n * the left edge ends up in the given place.\n *\n * When retrieved, it will return the position of the left edge in the parent\n * space.\n */\n @originSignal(Origin.Left)\n public declare readonly left: SimpleVector2Signal<this>;\n /**\n * The position of the right edge of this node.\n *\n * @remarks\n * When set, this shortcut property will modify the node's position so that\n * the right edge ends up in the given place.\n *\n * When retrieved, it will return the position of the right edge in the parent\n * space.\n */\n @originSignal(Origin.Right)\n public declare readonly right: SimpleVector2Signal<this>;\n /**\n * The position of the top left corner of this node.\n *\n * @remarks\n * When set, this shortcut property will modify the node's position so that\n * the top left corner ends up in the given place.\n *\n * When retrieved, it will return the position of the top left corner in the\n * parent space.\n */\n @originSignal(Origin.TopLeft)\n public declare readonly topLeft: SimpleVector2Signal<this>;\n /**\n * The position of the top right corner of this node.\n *\n * @remarks\n * When set, this shortcut property will modify the node's position so that\n * the top right corner ends up in the given place.\n *\n * When retrieved, it will return the position of the top right corner in the\n * parent space.\n */\n @originSignal(Origin.TopRight)\n public declare readonly topRight: SimpleVector2Signal<this>;\n /**\n * The position of the bottom left corner of this node.\n *\n * @remarks\n * When set, this shortcut property will modify the node's position so that\n * the bottom left corner ends up in the given place.\n *\n * When retrieved, it will return the position of the bottom left corner in\n * the parent space.\n */\n @originSignal(Origin.BottomLeft)\n public declare readonly bottomLeft: SimpleVector2Signal<this>;\n /**\n * The position of the bottom right corner of this node.\n *\n * @remarks\n * When set, this shortcut property will modify the node's position so that\n * the bottom right corner ends up in the given place.\n *\n * When retrieved, it will return the position of the bottom right corner in\n * the parent space.\n */\n @originSignal(Origin.BottomRight)\n public declare readonly bottomRight: SimpleVector2Signal<this>;\n\n @initial(false)\n @signal()\n public declare readonly clip: SimpleSignal<boolean, this>;\n\n public declare element: HTMLElement;\n public declare styles: CSSStyleDeclaration;\n\n @initial(0)\n @signal()\n protected declare readonly sizeLockCounter: SimpleSignal<number, this>;\n\n public constructor(props: LayoutProps) {\n super(props);\n this.element.dataset.motionCanvasKey = this.key;\n }\n\n public lockSize() {\n this.sizeLockCounter(this.sizeLockCounter() + 1);\n }\n\n public releaseSize() {\n this.sizeLockCounter(this.sizeLockCounter() - 1);\n }\n\n @computed()\n protected parentTransform(): Layout | null {\n return this.findAncestor(is(Layout));\n }\n\n @computed()\n public anchorPosition() {\n const size = this.computedSize();\n const offset = this.offset();\n\n return size.scale(0.5).mul(offset);\n }\n\n /**\n * Get the resolved layout mode of this node.\n *\n * @remarks\n * When the mode is `null`, its value will be inherited from the parent.\n *\n * Use {@link layout} to get the raw mode set for this node (without\n * inheritance).\n */\n @computed()\n public layoutEnabled(): boolean {\n return this.layout() ?? this.parentTransform()?.layoutEnabled() ?? false;\n }\n\n @computed()\n public isLayoutRoot(): boolean {\n return !this.layoutEnabled() || !this.parentTransform()?.layoutEnabled();\n }\n\n public override localToParent(): DOMMatrix {\n const matrix = super.localToParent();\n const offset = this.offset();\n if (!offset.exactlyEquals(Vector2.zero)) {\n const translate = this.size().mul(offset).scale(-0.5);\n matrix.translateSelf(translate.x, translate.y);\n }\n\n return matrix;\n }\n\n /**\n * A simplified version of {@link localToParent} matrix used for transforming\n * direction vectors.\n *\n * @internal\n */\n @computed()\n protected scalingRotationMatrix(): DOMMatrix {\n const matrix = new DOMMatrix();\n\n matrix.rotateSelf(0, 0, this.rotation());\n matrix.scaleSelf(this.scale.x(), this.scale.y());\n\n const offset = this.offset();\n if (!offset.exactlyEquals(Vector2.zero)) {\n const translate = this.size().mul(offset).scale(-0.5);\n matrix.translateSelf(translate.x, translate.y);\n }\n\n return matrix;\n }\n\n protected getComputedLayout(): BBox {\n return new BBox(this.element.getBoundingClientRect());\n }\n\n @computed()\n public computedPosition(): Vector2 {\n this.requestLayoutUpdate();\n const box = this.getComputedLayout();\n\n const position = new Vector2(\n box.x + (box.width / 2) * this.offset.x(),\n box.y + (box.height / 2) * this.offset.y(),\n );\n\n const parent = this.parentTransform();\n if (parent) {\n const parentRect = parent.getComputedLayout();\n position.x -= parentRect.x + (parentRect.width - box.width) / 2;\n position.y -= parentRect.y + (parentRect.height - box.height) / 2;\n }\n\n return position;\n }\n\n @computed()\n protected computedSize(): Vector2 {\n this.requestLayoutUpdate();\n return this.getComputedLayout().size;\n }\n\n /**\n * Find the closest layout root and apply any new layout changes.\n */\n @computed()\n protected requestLayoutUpdate() {\n const parent = this.parentTransform();\n if (this.appendedToView()) {\n parent?.requestFontUpdate();\n this.updateLayout();\n } else {\n parent!.requestLayoutUpdate();\n }\n }\n\n @computed()\n protected appendedToView() {\n const root = this.isLayoutRoot();\n if (root) {\n this.view().element.append(this.element);\n }\n\n return root;\n }\n\n /**\n * Apply any new layout changes to this node and its children.\n */\n @computed()\n protected updateLayout() {\n this.applyFont();\n this.applyFlex();\n if (this.layoutEnabled()) {\n const children = this.layoutChildren();\n for (const child of children) {\n child.updateLayout();\n }\n }\n }\n\n @computed()\n protected layoutChildren(): Layout[] {\n const queue = [...this.children()];\n const result: Layout[] = [];\n const elements: HTMLElement[] = [];\n while (queue.length) {\n const child = queue.shift();\n if (child instanceof Layout) {\n if (child.layoutEnabled()) {\n result.push(child);\n elements.push(child.element);\n }\n } else if (child) {\n queue.unshift(...child.children());\n }\n }\n this.element.replaceChildren(...elements);\n\n return result;\n }\n\n /**\n * Apply any new font changes to this node and all of its ancestors.\n */\n @computed()\n protected requestFontUpdate() {\n this.appendedToView();\n this.parentTransform()?.requestFontUpdate();\n this.applyFont();\n }\n\n protected override getCacheBBox(): BBox {\n return BBox.fromSizeCentered(this.computedSize());\n }\n\n protected override async draw(context: CanvasRenderingContext2D) {\n await document.fonts?.ready;\n if (this.clip()) {\n const size = this.computedSize();\n if (size.width === 0 || size.height === 0) {\n return;\n }\n\n context.beginPath();\n context.rect(size.width / -2, size.height / -2, size.width, size.height);\n context.closePath();\n context.clip();\n }\n\n await this.drawChildren(context);\n }\n\n public override drawOverlay(\n context: CanvasRenderingContext2D,\n matrix: DOMMatrix,\n ) {\n const size = this.computedSize();\n const offsetVector = size.mul(this.offset()).scale(0.5);\n const offset = transformVectorAsPoint(offsetVector, matrix);\n const box = BBox.fromSizeCentered(size);\n const layout = box.transformCorners(matrix);\n const padding = box\n .addSpacing(this.padding().scale(-1))\n .transformCorners(matrix);\n const margin = box.addSpacing(this.margin()).transformCorners(matrix);\n\n context.beginPath();\n drawLine(context, margin);\n drawLine(context, layout);\n context.closePath();\n context.fillStyle = 'rgba(255,193,125,0.6)';\n context.fill('evenodd');\n\n context.beginPath();\n drawLine(context, layout);\n drawLine(context, padding);\n context.closePath();\n context.fillStyle = 'rgba(180,255,147,0.6)';\n context.fill('evenodd');\n\n context.beginPath();\n drawLine(context, layout);\n context.closePath();\n context.lineWidth = 1;\n context.strokeStyle = 'white';\n context.stroke();\n\n context.beginPath();\n drawPivot(context, offset);\n context.stroke();\n }\n\n public getOriginDelta(origin: Origin) {\n const size = this.computedSize().scale(0.5);\n const offset = this.offset().mul(size);\n if (origin === Origin.Middle) {\n return offset.flipped;\n }\n\n const newOffset = originToOffset(origin).mul(size);\n return newOffset.sub(offset);\n }\n\n /**\n * Update the offset of this node and adjust the position to keep it in the\n * same place.\n *\n * @param offset - The new offset.\n */\n public moveOffset(offset: Vector2) {\n const size = this.computedSize().scale(0.5);\n const oldOffset = this.offset().mul(size);\n const newOffset = offset.mul(size);\n this.offset(offset);\n this.position(this.position().add(newOffset).sub(oldOffset));\n }\n\n protected parsePixels(value: number | null): string {\n return value === null ? '' : `${value}px`;\n }\n\n protected parseLength(value: number | string | null): string {\n if (value === null) {\n return '';\n }\n if (typeof value === 'string') {\n return value;\n }\n return `${value}px`;\n }\n\n @computed()\n protected applyFlex() {\n this.element.style.position = this.isLayoutRoot() ? 'absolute' : 'relative';\n\n const size = this.desiredSize();\n this.element.style.width = this.parseLength(size.x);\n this.element.style.height = this.parseLength(size.y);\n this.element.style.maxWidth = this.parseLength(this.maxWidth());\n this.element.style.minWidth = this.parseLength(this.minWidth());\n this.element.style.maxHeight = this.parseLength(this.maxHeight());\n this.element.style.minHeight = this.parseLength(this.minHeight()!);\n this.element.style.aspectRatio =\n this.ratio() === null ? '' : this.ratio()!.toString();\n\n this.element.style.marginTop = this.parsePixels(this.margin.top());\n this.element.style.marginBottom = this.parsePixels(this.margin.bottom());\n this.element.style.marginLeft = this.parsePixels(this.margin.left());\n this.element.style.marginRight = this.parsePixels(this.margin.right());\n\n this.element.style.paddingTop = this.parsePixels(this.padding.top());\n this.element.style.paddingBottom = this.parsePixels(this.padding.bottom());\n this.element.style.paddingLeft = this.parsePixels(this.padding.left());\n this.element.style.paddingRight = this.parsePixels(this.padding.right());\n\n this.element.style.flexDirection = this.direction();\n this.element.style.flexBasis = this.parseLength(this.basis()!);\n this.element.style.flexWrap = this.wrap();\n\n this.element.style.justifyContent = this.justifyContent();\n this.element.style.alignContent = this.alignContent();\n this.element.style.alignItems = this.alignItems();\n this.element.style.alignSelf = this.alignSelf();\n this.element.style.columnGap = this.parseLength(this.gap.x());\n this.element.style.rowGap = this.parseLength(this.gap.y());\n\n if (this.sizeLockCounter() > 0) {\n this.element.style.flexGrow = '0';\n this.element.style.flexShrink = '0';\n } else {\n this.element.style.flexGrow = this.grow().toString();\n this.element.style.flexShrink = this.shrink().toString();\n }\n }\n\n @computed()\n protected applyFont() {\n const loadingFonts = document.fonts\n ? Array.from(document.fonts).filter(font => font.status === 'loading')\n : [];\n if (loadingFonts.length > 0) {\n DependencyContext.collectPromise(\n (async () => {\n await document.fonts?.ready;\n })(),\n );\n }\n\n this.element.style.fontFamily = this.fontFamily.isInitial()\n ? ''\n : this.fontFamily();\n this.element.style.fontSize = this.fontSize.isInitial()\n ? ''\n : `${this.fontSize()}px`;\n this.element.style.fontStyle = this.fontStyle.isInitial()\n ? ''\n : this.fontStyle();\n if (this.lineHeight.isInitial()) {\n this.element.style.lineHeight = '';\n } else {\n const lineHeight = this.lineHeight();\n this.element.style.lineHeight =\n typeof lineHeight === 'string'\n ? (parseFloat(lineHeight as string) / 100).toString()\n : `${lineHeight}px`;\n }\n this.element.style.fontWeight = this.fontWeight.isInitial()\n ? ''\n : this.fontWeight().toString();\n this.element.style.letterSpacing = this.letterSpacing.isInitial()\n ? ''\n : `${this.letterSpacing()}px`;\n\n this.element.style.textAlign = this.textAlign.isInitial()\n ? ''\n : this.textAlign();\n\n if (this.textWrap.isInitial()) {\n this.element.style.whiteSpace = '';\n return;\n }\n\n const wrap = this.textWrap();\n\n if (typeof wrap === 'boolean') {\n this.element.style.whiteSpace = wrap ? 'normal' : 'nowrap';\n return;\n }\n\n if (wrap === 'pre') {\n this.element.style.whiteSpace = wrap;\n return;\n }\n\n if (wrap === 'balance') {\n this.element.style.whiteSpace = 'normal';\n this.element.style.textWrap = wrap;\n return;\n }\n }\n\n public override dispose() {\n super.dispose();\n this.sizeLockCounter?.context.dispose();\n if (this.element) {\n this.element.remove();\n this.element.innerHTML = '';\n }\n this.element = null as unknown as HTMLElement;\n this.styles = null as unknown as CSSStyleDeclaration;\n }\n\n public override hit(position: Vector2): Node | null {\n const local = transformVectorAsPoint(\n position,\n this.localToParent().inverse(),\n );\n if (this.cacheBBox().includes(local)) {\n return super.hit(position) ?? this;\n }\n\n return null;\n }\n}\n\nfunction originSignal(origin: Origin): PropertyDecorator {\n return (target, key) => {\n signal()(target, key);\n cloneable(false)(target, key);\n const meta = getPropertyMeta<any>(target, key);\n meta!.parser = value => new Vector2(value);\n meta!.getter = function (this: Layout) {\n const originOffset = this.computedSize().getOriginOffset(origin);\n return transformVectorAsPoint(originOffset, this.localToParent());\n };\n meta!.setter = function (\n this: Layout,\n value: SignalValue<PossibleVector2>,\n ) {\n this.position(\n modify(value, unwrapped => {\n const originDelta = this.getOriginDelta(origin);\n return transformVector(\n originDelta,\n this.scalingRotationMatrix(),\n ).flipped.add(unwrapped);\n }),\n );\n return this;\n };\n };\n}\n\naddInitializer<Layout>(Layout.prototype, instance => {\n instance.element = document.createElement('div');\n instance.element.style.display = 'flex';\n instance.element.style.boxSizing = 'border-box';\n instance.styles = getComputedStyle(instance.element);\n});\n","import type {\n ColorSignal,\n PossibleColor,\n PossibleSpacing,\n PossibleVector2,\n Promisable,\n ReferenceReceiver,\n Signal,\n SignalValue,\n SimpleSignal,\n SimpleVector2Signal,\n SpacingSignal,\n ThreadGenerator,\n TimingFunction,\n Vector2Signal,\n} from '@twick/core';\nimport {\n BBox,\n DependencyContext,\n UNIFORM_DESTINATION_MATRIX,\n UNIFORM_SOURCE_MATRIX,\n UNIFORM_TIME,\n Vector2,\n all,\n clamp,\n createSignal,\n easeInOutCubic,\n isReactive,\n modify,\n threadable,\n transformAngle,\n transformScalar,\n transformVector,\n transformVectorAsPoint,\n unwrap,\n useLogger,\n} from '@twick/core';\nimport {\n NODE_NAME,\n cloneable,\n colorSignal,\n computed,\n getPropertiesOf,\n initial,\n initializeSignals,\n inspectable,\n nodeName,\n parser,\n signal,\n vector2Signal,\n wrapper,\n} from '../decorators';\nimport type {FiltersSignal} from '../decorators/filtersSignal';\nimport {filtersSignal} from '../decorators/filtersSignal';\nimport {spacingSignal} from '../decorators/spacingSignal';\nimport type {Filter} from '../partials';\nimport type {\n PossibleShaderConfig,\n ShaderConfig,\n} from '../partials/ShaderConfig';\nimport {parseShader} from '../partials/ShaderConfig';\nimport {useScene2D} from '../scenes/useScene2D';\nimport {drawLine} from '../utils';\nimport type {View2D} from './View2D';\nimport type {ComponentChild, ComponentChildren, NodeConstructor} from './types';\n\nexport type NodeState = NodeProps & Record<string, any>;\n\nexport interface NodeProps {\n ref?: ReferenceReceiver<any>;\n children?: SignalValue<ComponentChildren>;\n /**\n * @deprecated Use {@link children} instead.\n */\n spawner?: SignalValue<ComponentChildren>;\n key?: string;\n\n x?: SignalValue<number>;\n y?: SignalValue<number>;\n position?: SignalValue<PossibleVector2>;\n rotation?: SignalValue<number>;\n scaleX?: SignalValue<number>;\n scaleY?: SignalValue<number>;\n scale?: SignalValue<PossibleVector2>;\n skewX?: SignalValue<number>;\n skewY?: SignalValue<number>;\n skew?: SignalValue<PossibleVector2>;\n zIndex?: SignalValue<number>;\n\n opacity?: SignalValue<number>;\n filters?: SignalValue<Filter[]>;\n\n shadowColor?: SignalValue<PossibleColor>;\n shadowBlur?: SignalValue<number>;\n shadowOffsetX?: SignalValue<number>;\n shadowOffsetY?: SignalValue<number>;\n shadowOffset?: SignalValue<PossibleVector2>;\n\n cache?: SignalValue<boolean>;\n /**\n * {@inheritDoc Node.cachePadding}\n */\n cachePaddingTop?: SignalValue<number>;\n /**\n * {@inheritDoc Node.cachePadding}\n */\n cachePaddingBottom?: SignalValue<number>;\n /**\n * {@inheritDoc Node.cachePadding}\n */\n cachePaddingLeft?: SignalValue<number>;\n /**\n * {@inheritDoc Node.cachePadding}\n */\n cachePaddingRight?: SignalValue<number>;\n /**\n * {@inheritDoc Node.cachePadding}\n */\n cachePadding?: SignalValue<PossibleSpacing>;\n\n composite?: SignalValue<boolean>;\n compositeOperation?: SignalValue<GlobalCompositeOperation>;\n /**\n * @experimental\n */\n shaders?: PossibleShaderConfig;\n}\n\n@nodeName('Node')\nexport class Node implements Promisable<Node> {\n /**\n * @internal\n */\n public declare readonly [NODE_NAME]: string;\n public declare isClass: boolean;\n\n /**\n * Represents the position of this node in local space of its parent.\n *\n * @example\n * Initializing the position:\n * ```tsx\n * // with a possible vector:\n * <Node position={[1, 2]} />\n * // with individual components:\n * <Node x={1} y={2} />\n * ```\n *\n * Accessing the position:\n * ```tsx\n * // retrieving the vector:\n * const position = node.position();\n * // retrieving an individual component:\n * const x = node.position.x();\n * ```\n *\n * Setting the position:\n * ```tsx\n * // with a possible vector:\n * node.position([1, 2]);\n * node.position(() => [1, 2]);\n * // with individual components:\n * node.position.x(1);\n * node.position.x(() => 1);\n * ```\n */\n @vector2Signal()\n public declare readonly position: Vector2Signal<this>;\n\n public get x() {\n return this.position.x as SimpleSignal<number, this>;\n }\n public get y() {\n return this.position.y as SimpleSignal<number, this>;\n }\n\n /**\n * A helper signal for operating on the position in world space.\n *\n * @remarks\n * Retrieving the position using this signal returns the position in world\n * space. Similarly, setting the position using this signal transforms the\n * new value to local space.\n *\n * If the new value is a function, the position of this node will be\n * continuously updated to always match the position returned by the function.\n * This can be useful to \"pin\" the node in a specific place or to make it\n * follow another node's position.\n *\n * Unlike {@link position}, this signal is not compound - it doesn't contain\n * separate signals for the `x` and `y` components.\n */\n @wrapper(Vector2)\n @cloneable(false)\n @signal()\n public declare readonly absolutePosition: SimpleVector2Signal<this>;\n\n protected getAbsolutePosition(): Vector2 {\n const matrix = this.localToWorld();\n return new Vector2(matrix.m41, matrix.m42);\n }\n\n protected setAbsolutePosition(value: SignalValue<PossibleVector2>) {\n this.position(\n modify(value, unwrapped =>\n transformVectorAsPoint(new Vector2(unwrapped), this.worldToParent()),\n ),\n );\n }\n\n /**\n * Represents the rotation (in degrees) of this node relative to its parent.\n */\n @initial(0)\n @signal()\n public declare readonly rotation: SimpleSignal<number, this>;\n\n /**\n * A helper signal for operating on the rotation in world space.\n *\n * @remarks\n * Retrieving the rotation using this signal returns the rotation in world\n * space. Similarly, setting the rotation using this signal transforms the\n * new value to local space.\n *\n * If the new value is a function, the rotation of this node will be\n * continuously updated to always match the rotation returned by the function.\n */\n @cloneable(false)\n @signal()\n public declare readonly absoluteRotation: SimpleSignal<number, this>;\n\n protected getAbsoluteRotation() {\n const matrix = this.localToWorld();\n return Vector2.degrees(matrix.m11, matrix.m12);\n }\n\n protected setAbsoluteRotation(value: SignalValue<number>) {\n this.rotation(\n modify(value, unwrapped =>\n transformAngle(unwrapped, this.worldToParent()),\n ),\n );\n }\n\n /**\n * Represents the scale of this node in local space of its parent.\n *\n * @example\n * Initializing the scale:\n * ```tsx\n * // with a possible vector:\n * <Node scale={[1, 2]} />\n * // with individual components:\n * <Node scaleX={1} scaleY={2} />\n * ```\n *\n * Accessing the scale:\n * ```tsx\n * // retrieving the vector:\n * const scale = node.scale();\n * // retrieving an individual component:\n * const scaleX = node.scale.x();\n * ```\n *\n * Setting the scale:\n * ```tsx\n * // with a possible vector:\n * node.scale([1, 2]);\n * node.scale(() => [1, 2]);\n * // with individual components:\n * node.scale.x(1);\n * node.scale.x(() => 1);\n * ```\n */\n @initial(Vector2.one)\n @vector2Signal('scale')\n public declare readonly scale: Vector2Signal<this>;\n\n /**\n * Represents the skew of this node in local space of its parent.\n *\n * @example\n * Initializing the skew:\n * ```tsx\n * // with a possible vector:\n * <Node skew={[40, 20]} />\n * // with individual components:\n * <Node skewX={40} skewY={20} />\n * ```\n *\n * Accessing the skew:\n * ```tsx\n * // retrieving the vector:\n * const skew = node.skew();\n * // retrieving an individual component:\n * const skewX = node.skew.x();\n * ```\n *\n * Setting the skew:\n * ```tsx\n * // with a possible vector:\n * node.skew([40, 20]);\n * node.skew(() => [40, 20]);\n * // with individual components:\n * node.skew.x(40);\n * node.skew.x(() => 40);\n * ```\n */\n @initial(Vector2.zero)\n @vector2Signal('skew')\n public declare readonly skew: Vector2Signal<this>;\n\n /**\n * A helper signal for operating on the scale in world space.\n *\n * @remarks\n * Retrieving the scale using this signal returns the scale in world space.\n * Similarly, setting the scale using this signal transforms the new value to\n * local space.\n *\n * If the new value is a function, the scale of this node will be continuously\n * updated to always match the position returned by the function.\n *\n * Unlike {@link scale}, this signal is not compound - it doesn't contain\n * separate signals for the `x` and `y` components.\n */\n @wrapper(Vector2)\n @cloneable(false)\n @signal()\n public declare readonly absoluteScale: SimpleVector2Signal<this>;\n\n protected getAbsoluteScale(): Vector2 {\n const matrix = this.localToWorld();\n return new Vector2(\n Vector2.magnitude(matrix.m11, matrix.m12),\n Vector2.magnitude(matrix.m21, matrix.m22),\n );\n }\n\n protected setAbsoluteScale(value: SignalValue<PossibleVector2>) {\n this.scale(\n modify(value, unwrapped => this.getRelativeScale(new Vector2(unwrapped))),\n );\n }\n\n private getRelativeScale(scale: Vector2): Vector2 {\n const parentScale = this.parent()?.absoluteScale() ?? Vector2.one;\n return scale.div(parentScale);\n }\n\n @initial(0)\n @signal()\n public declare readonly zIndex: SimpleSignal<number, this>;\n\n @initial(false)\n @signal()\n public declare readonly cache: SimpleSignal<boolean, this>;\n\n /**\n * Controls the padding of the cached canvas used by this node.\n *\n * @remarks\n * By default, the size of the cache is determined based on the bounding box\n * of the node and its children. That includes effects such as stroke or\n * shadow. This property can be used to expand the cache area further.\n * Usually used to account for custom effects created by {@link shaders}.\n */\n @spacingSignal('cachePadding')\n public declare readonly cachePadding: SpacingSignal<this>;\n\n @initial(false)\n @signal()\n public declare readonly composite: SimpleSignal<boolean, this>;\n\n @initial('source-over')\n @signal()\n public declare readonly compositeOperation: SimpleSignal<\n GlobalCompositeOperation,\n this\n >;\n\n private readonly compositeOverride = createSignal(0);\n\n @threadable()\n protected *tweenCompositeOperation(\n value: SignalValue<GlobalCompositeOperation>,\n time: number,\n timingFunction: TimingFunction,\n ) {\n const nextValue = unwrap(value);\n if (nextValue === 'source-over') {\n yield* this.compositeOverride(1, time, timingFunction);\n this.compositeOverride(0);\n this.compositeOperation(nextValue);\n } else {\n this.compositeOperation(nextValue);\n this.compositeOverride(1);\n yield* this.compositeOverride(0, time, timingFunction);\n }\n }\n\n /**\n * Represents the opacity of this node in the range 0-1.\n *\n * @remarks\n * The value is clamped to the range 0-1.\n */\n @initial(1)\n @parser((value: number) => clamp(0, 1, value))\n @signal()\n public declare readonly opacity: SimpleSignal<number, this>;\n\n @computed()\n public absoluteOpacity(): number {\n return (this.parent()?.absoluteOpacity() ?? 1) * this.opacity();\n }\n\n @filtersSignal()\n public declare readonly filters: FiltersSignal<this>;\n\n @initial('#0000')\n @colorSignal()\n public declare readonly shadowColor: ColorSignal<this>;\n\n @initial(0)\n @signal()\n public declare readonly shadowBlur: SimpleSignal<number, this>;\n\n @vector2Signal('shadowOffset')\n public declare readonly shadowOffset: Vector2Signal<this>;\n\n /**\n * @experimental\n */\n @initial([])\n @parser(parseShader)\n @signal()\n public declare readonly shaders: Signal<\n PossibleShaderConfig,\n ShaderConfig[],\n this\n >;\n\n @computed()\n protected hasFilters(): boolean {\n return !!this.filters().find(filter => filter.isActive());\n }\n\n @computed()\n protected hasShadow() {\n return (\n !!this.shadowColor() &&\n (this.shadowBlur() > 0 ||\n this.shadowOffset.x() !== 0 ||\n this.shadowOffset.y() !== 0)\n );\n }\n\n @computed()\n protected filterString(): string {\n let filters = '';\n const matrix = this.compositeToWorld();\n for (const filter of this.filters()) {\n if (filter.isActive()) {\n filters += ' ' + filter.serialize(matrix);\n }\n }\n\n return filters;\n }\n\n /**\n * @deprecated Use {@link children} instead.\n */\n @inspectable(false)\n @cloneable(false)\n @signal()\n protected declare readonly spawner: SimpleSignal<ComponentChildren, this>;\n protected getSpawner(): ComponentChildren {\n return this.children();\n }\n protected setSpawner(value: SignalValue<ComponentChildren>) {\n this.children(value);\n }\n\n @inspectable(false)\n @cloneable(false)\n @signal()\n public declare readonly children: Signal<ComponentChildren, Node[], this>;\n protected setChildren(value: SignalValue<ComponentChildren>) {\n if (this.children.context.raw() === value) {\n return;\n }\n\n this.children.context.setter(value);\n if (!isReactive(value)) {\n this.spawnChildren(false, value);\n } else if (!this.hasSpawnedChildren) {\n for (const oldChild of this.realChildren) {\n oldChild.parent(null);\n }\n }\n }\n protected getChildren(): Node[] {\n this.children.context.getter();\n return this.spawnedChildren();\n }\n\n @computed()\n protected spawnedChildren(): Node[] {\n const children = this.children.context.getter();\n if (isReactive(this.children.context.raw())) {\n this.spawnChildren(true, children);\n }\n return this.realChildren;\n }\n\n @computed()\n protected sortedChildren(): Node[] {\n return [...this.children()].sort((a, b) =>\n Math.sign(a.zIndex() - b.zIndex()),\n );\n }\n\n protected view2D: View2D;\n private stateStack: NodeState[] = [];\n protected realChildren: Node[] = [];\n protected hasSpawnedChildren = false;\n private unregister: () => void;\n public readonly parent = createSignal<Node | null>(null);\n public readonly properties = getPropertiesOf(this);\n public readonly key: string;\n public readonly creationStack?: string;\n\n public constructor({children, spawner, key, ...rest}: NodeProps) {\n const scene = useScene2D();\n [this.key, this.unregister] = scene.registerNode(this, key);\n this.view2D = scene.getView();\n this.creationStack = new Error().stack;\n initializeSignals(this, rest);\n if (spawner) {\n useLogger().warn({\n message: 'Node.spawner() has been deprecated.',\n remarks: 'Use <code>Node.children()</code> instead.',\n inspect: this.key,\n stack: new Error().stack,\n });\n }\n this.children(spawner ?? children);\n }\n\n /**\n * Get the local-to-world matrix for this node.\n *\n * @remarks\n * This matrix transforms vectors from local space of this node to world\n * space.\n *\n * @example\n * Calculate the absolute position of a point located 200 pixels to the right\n * of the node:\n * ```ts\n * const local = new Vector2(0, 200);\n * const world = transformVectorAsPoint(local, node.localToWorld());\n * ```\n */\n @computed()\n public localToWorld(): DOMMatrix {\n const parent = this.parent();\n return parent\n ? parent.localToWorld().multiply(this.localToParent())\n : this.localToParent();\n }\n\n /**\n * Get the world-to-local matrix for this node.\n *\n * @remarks\n * This matrix transforms vectors from world space to local space of this\n * node.\n *\n * @example\n * Calculate the position relative to this node for a point located in the\n * top-left corner of the screen:\n * ```ts\n * const world = new Vector2(0, 0);\n * const local = transformVectorAsPoint(world, node.worldToLocal());\n * ```\n */\n @computed()\n public worldToLocal() {\n return this.localToWorld().inverse();\n }\n\n /**\n * Get the world-to-parent matrix for this node.\n *\n * @remarks\n * This matrix transforms vectors from world space to local space of this\n * node's parent.\n */\n @computed()\n public worldToParent(): DOMMatrix {\n return this.parent()?.worldToLocal() ?? new DOMMatrix();\n }\n\n /**\n * Get the local-to-parent matrix for this node.\n *\n * @remarks\n * This matrix transforms vectors from local space of this node to local space\n * of this node's parent.\n */\n @computed()\n public localToParent(): DOMMatrix {\n const matrix = new DOMMatrix();\n matrix.translateSelf(this.x(), this.y());\n matrix.rotateSelf(0, 0, this.rotation());\n matrix.scaleSelf(this.scale.x(), this.scale.y());\n matrix.skewXSelf(this.skew.x());\n matrix.skewYSelf(this.skew.y());\n\n return matrix;\n }\n\n /**\n * A matrix mapping composite space to world space.\n *\n * @remarks\n * Certain effects such as blur and shadows ignore the current transformation.\n * This matrix can be used to transform their parameters so that the effect\n * appears relative to the closest composite root.\n */\n @computed()\n public compositeToWorld(): DOMMatrix {\n return this.compositeRoot()?.localToWorld() ?? new DOMMatrix();\n }\n\n @computed()\n protected compositeRoot(): Node | null {\n if (this.composite()) {\n return this;\n }\n\n return this.parent()?.compositeRoot() ?? null;\n }\n\n @computed()\n public compositeToLocal() {\n const root = this.compositeRoot();\n if (root) {\n const worldToLocal = this.worldToLocal();\n worldToLocal.m44 = 1;\n return root.localToWorld().multiply(worldToLocal);\n }\n return new DOMMatrix();\n }\n\n public view(): View2D {\n return this.view2D;\n }\n\n /**\n * Add the given node(s) as the children of this node.\n *\n * @remarks\n * The nodes will be appended at the end of the children list.\n *\n * @example\n * ```tsx\n * const node = <Layout />;\n * node.add(<Rect />);\n * node.add(<Circle />);\n * ```\n * Result:\n * ```mermaid\n * graph TD;\n * layout([Layout])\n * circle([Circle])\n * rect([Rect])\n * layout-->rect;\n * layout-->circle;\n * ```\n *\n * @param node - A node or an array of nodes to append.\n */\n public add(node: ComponentChildren): this {\n return this.insert(node, Infinity);\n }\n\n /**\n * Insert the given node(s) at the specified index in the children list.\n *\n * @example\n * ```tsx\n * const node = (\n * <Layout>\n * <Rect />\n * <Circle />\n * </Layout>\n * );\n *\n * node.insert(<Txt />, 1);\n * ```\n *\n * Result:\n * ```mermaid\n * graph TD;\n * layout([Layout])\n * circle([Circle])\n * text([Text])\n * rect([Rect])\n * layout-->rect;\n * layout-->text;\n * layout-->circle;\n * ```\n *\n * @param node - A node or an array of nodes to insert.\n * @param index - An index at which to insert the node(s).\n */\n public insert(node: ComponentChildren, index = 0): this {\n const array: ComponentChild[] = Array.isArray(node) ? node : [node];\n if (array.length === 0) {\n return this;\n }\n\n const children = this.children();\n const newChildren = children.slice(0, index);\n\n for (const node of array) {\n if (node instanceof Node) {\n newChildren.push(node);\n node.remove();\n node.parent(this);\n }\n }\n\n newChildren.push(...children.slice(index));\n this.setParsedChildren(newChildren);\n\n return this;\n }\n\n /**\n * Remove this node from the tree.\n */\n public remove(): this {\n const current = this.parent();\n if (current === null) {\n return this;\n }\n\n current.removeChild(this);\n this.parent(null);\n return this;\n }\n\n /**\n * Rearrange this node in relation to its siblings.\n *\n * @remarks\n * Children are rendered starting from the beginning of the children list.\n * We can change the rendering order by rearranging said list.\n *\n * A positive `by` arguments move the node up (it will be rendered on top of\n * the elements it has passed). Negative values move it down.\n *\n * @param by - Number of places by which the node should be moved.\n */\n public move(by = 1): this {\n const parent = this.parent();\n if (by === 0 || !parent) {\n return this;\n }\n\n const children = parent.children();\n const newChildren: Node[] = [];\n\n if (by > 0) {\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (child === this) {\n const target = i + by;\n for (; i < target && i + 1 < children.length; i++) {\n newChildren[i] = children[i + 1];\n }\n }\n newChildren[i] = child;\n }\n } else {\n for (let i = children.length - 1; i >= 0; i--) {\n const child = children[i];\n if (child === this) {\n const target = i + by;\n for (; i > target && i > 0; i--) {\n newChildren[i] = children[i - 1];\n }\n }\n newChildren[i] = child;\n }\n }\n\n parent.setParsedChildren(newChildren);\n\n return this;\n }\n\n /**\n * Move the node up in relation to its siblings.\n *\n * @remarks\n * The node will exchange places with the sibling right above it (if any) and\n * from then on will be rendered on top of it.\n */\n public moveUp(): this {\n return this.move(1);\n }\n\n /**\n * Move the node down in relation to its siblings.\n *\n * @remarks\n * The node will exchange places with the sibling right below it (if any) and\n * from then on will be rendered under it.\n */\n public moveDown(): this {\n return this.move(-1);\n }\n\n /**\n * Move the node to the top in relation to its siblings.\n *\n * @remarks\n * The node will be placed at the end of the children list and from then on\n * will be rendered on top of all of its siblings.\n */\n public moveToTop(): this {\n return this.move(Infinity);\n }\n\n /**\n * Move the node to the bottom in relation to its siblings.\n *\n * @remarks\n * The node will be placed at the beginning of the children list and from then\n * on will be rendered below all of its siblings.\n */\n public moveToBottom(): this {\n return this.move(-Infinity);\n }\n\n /**\n * Move the node to the provided position relative to its siblings.\n *\n * @remarks\n * If the node is getting moved to a lower position, it will be placed below\n * the sibling that's currently at the provided index (if any).\n * If the node is getting moved to a higher position, it will be placed above\n * the sibling that's currently at the provided index (if any).\n *\n * @param index - The index to move the node to.\n */\n public moveTo(index: number): this {\n const parent = this.parent();\n if (!parent) {\n return this;\n }\n\n const currentIndex = parent.children().indexOf(this);\n const by = index - currentIndex;\n\n return this.move(by);\n }\n\n /**\n * Move the node below the provided node in the parent's layout.\n *\n * @remarks\n * The node will be moved below the provided node and from then on will be\n * rendered below it. By default, if the node is already positioned lower than\n * the sibling node, it will not get moved.\n *\n * @param node - The sibling node below which to move.\n * @param directlyBelow - Whether the node should be positioned directly below\n * the sibling. When true, will move the node even if\n * it is already positioned below the sibling.\n */\n public moveBelow(node: Node, directlyBelow = false): this {\n const parent = this.parent();\n if (!parent) {\n return this;\n }\n\n if (node.parent() !== parent) {\n useLogger().error(\n \"Cannot position nodes relative to each other if they don't belong to the same parent.\",\n );\n return this;\n }\n\n const children = parent.children();\n const ownIndex = children.indexOf(this);\n const otherIndex = children.indexOf(node);\n\n if (!directlyBelow && ownIndex < otherIndex) {\n // Nothing to do if the node is already positioned below the target node.\n // We could move the node so it's directly below the sibling node, but\n // that might suddenly move it on top of other nodes. This is likely\n // not what the user wanted to happen when calling this method.\n return this;\n }\n\n const by = otherIndex - ownIndex - 1;\n\n return this.move(by);\n }\n\n /**\n * Move the node above the provided node in the parent's layout.\n *\n * @remarks\n * The node will be moved above the provided node and from then on will be\n * rendered on top of it. By default, if the node is already positioned\n * higher than the sibling node, it will not get moved.\n *\n * @param node - The sibling node below which to move.\n * @param directlyAbove - Whether the node should be positioned directly above the\n * sibling. When true, will move the node even if it is\n * already positioned above the sibling.\n */\n public moveAbove(node: Node, directlyAbove = false): this {\n const parent = this.parent();\n if (!parent) {\n return this;\n }\n\n if (node.parent() !== parent) {\n useLogger().error(\n \"Cannot position nodes relative to each other if they don't belong to the same parent.\",\n );\n return this;\n }\n\n const children = parent.children();\n const ownIndex = children.indexOf(this);\n const otherIndex = children.indexOf(node);\n\n if (!directlyAbove && ownIndex > otherIndex) {\n // Nothing to do if the node is already positioned above the target node.\n // We could move the node so it's directly above the sibling node, but\n // that might suddenly move it below other nodes. This is likely not what\n // the user wanted to happen when calling this method.\n return this;\n }\n\n const by = otherIndex - ownIndex + 1;\n\n return this.move(by);\n }\n\n /**\n * Change the parent of this node while keeping the absolute transform.\n *\n * @remarks\n * After performing this operation, the node will stay in the same place\n * visually, but its parent will be changed.\n *\n * @param newParent - The new parent of this node.\n */\n public reparent(newParent: Node) {\n const position = this.absolutePosition();\n const rotation = this.absoluteRotation();\n const scale = this.absoluteScale();\n newParent.add(this);\n this.absolutePosition(position);\n this.absoluteRotation(rotation);\n this.absoluteScale(scale);\n }\n\n /**\n * Remove all children of this node.\n */\n public removeChildren() {\n for (const oldChild of this.realChildren) {\n oldChild.parent(null);\n }\n this.setParsedChildren([]);\n }\n\n /**\n * Get the current children of this node.\n *\n * @remarks\n * Unlike {@link children}, this method does not have any side effects.\n * It does not register the `children` signal as a dependency, and it does not\n * spawn any children. It can be used to safely retrieve the current state of\n * the scene graph for debugging purposes.\n */\n public peekChildren(): readonly Node[] {\n return this.realChildren;\n }\n\n /**\n * Find all descendants of this node that match the given predicate.\n *\n * @param predicate - A function that returns true if the node matches.\n */\n public findAll<T extends Node>(predicate: (node: any) => node is T): T[];\n /**\n * Find all descendants of this node that match the given predicate.\n *\n * @param predicate - A function that returns true if the node matches.\n */\n public findAll<T extends Node = Node>(predicate: (node: any) => boolean): T[];\n public findAll<T extends Node>(predicate: (node: any) => node is T): T[] {\n const result: T[] = [];\n const queue = this.reversedChildren();\n while (queue.length > 0) {\n const node = queue.pop()!;\n if (predicate(node)) {\n result.push(node);\n }\n const children = node.children();\n for (let i = children.length - 1; i >= 0; i--) {\n queue.push(children[i]);\n }\n }\n\n return result;\n }\n\n /**\n * Find the first descendant of this node that matches the given predicate.\n *\n * @param predicate - A function that returns true if the node matches.\n */\n public findFirst<T extends Node>(\n predicate: (node: Node) => node is T,\n ): T | null;\n /**\n * Find the first descendant of this node that matches the given predicate.\n *\n * @param predicate - A function that returns true if the node matches.\n */\n public findFirst<T extends Node = Node>(\n predicate: (node: Node) => boolean,\n ): T | null;\n public findFirst<T extends Node>(\n predicate: (node: Node) => node is T,\n ): T | null {\n const queue = this.reversedChildren();\n while (queue.length > 0) {\n const node = queue.pop()!;\n if (predicate(node)) {\n return node;\n }\n const children = node.children();\n for (let i = children.length - 1; i >= 0; i--) {\n queue.push(children[i]);\n }\n }\n\n return null;\n }\n\n /**\n * Find the last descendant of this node that matches the given predicate.\n *\n * @param predicate - A function that returns true if the node matches.\n */\n public findLast<T extends Node>(\n predicate: (node: Node) => node is T,\n ): T | null;\n /**\n * Find the last descendant of this node that matches the given predicate.\n *\n * @param predicate - A function that returns true if the node matches.\n */\n public findLast<T extends Node = Node>(\n predicate: (node: Node) => boolean,\n ): T | null;\n public findLast<T extends Node>(\n predicate: (node: Node) => node is T,\n ): T | null {\n const search: Node[] = [];\n const queue = this.reversedChildren();\n\n while (queue.length > 0) {\n const node = queue.pop()!;\n search.push(node);\n const children = node.children();\n for (let i = children.length - 1; i >= 0; i--) {\n queue.push(children[i]);\n }\n }\n\n while (search.length > 0) {\n const node = search.pop()!;\n if (predicate(node)) {\n return node;\n }\n }\n\n return null;\n }\n\n /**\n * Find the closest ancestor of this node that matches the given predicate.\n *\n * @param predicate - A function that returns true if the node matches.\n */\n public findAncestor<T extends Node>(\n predicate: (node: Node) => node is T,\n ): T | null;\n /**\n * Find the closest ancestor of this node that matches the given predicate.\n *\n * @param predicate - A function that returns true if the node matches.\n */\n public findAncestor<T extends Node = Node>(\n predicate: (node: Node) => boolean,\n ): T | null;\n public findAncestor<T extends Node>(\n predicate: (node: Node) => node is T,\n ): T | null {\n let parent: Node | null = this.parent();\n while (parent) {\n if (predicate(parent)) {\n return parent;\n }\n parent = parent.parent();\n }\n\n return null;\n }\n\n /**\n * Get the nth children cast to the specified type.\n *\n * @param index - The index of the child to retrieve.\n */\n public childAs<T extends Node = Node>(index: number): T | null {\n return (this.children()[index] as T) ?? null;\n }\n\n /**\n * Get the children array cast to the specified type.\n */\n public childrenAs<T extends Node = Node>(): T[] {\n return this.children() as T[];\n }\n\n /**\n * Get the parent cast to the specified type.\n */\n public parentAs<T extends Node = Node>(): T | null {\n return (this.parent() as T) ?? null;\n }\n\n /**\n * Prepare this node to be disposed of.\n *\n * @remarks\n * This method is called automatically when a scene is refreshed. It will\n * be called even if the node is not currently attached to the tree.\n *\n * The goal of this method is to clean any external references to allow the\n * node to be garbage collected.\n */\n public dispose() {\n if (!this.unregister) {\n return;\n }\n\n this.stateStack = [];\n this.unregister();\n this.unregister = null!;\n for (const {signal} of this) {\n signal?.context.dispose();\n }\n for (const child of this.realChildren) {\n child.dispose();\n }\n }\n\n /**\n * Create a copy of this node.\n *\n * @param customProps - Properties to override.\n */\n public clone(customProps: NodeState = {}): this {\n const props = {...customProps};\n if (isReactive(this.children.context.raw())) {\n props.children ??= this.children.context.raw();\n } else if (this.children().length > 0) {\n props.children ??= this.children().map(child => child.clone());\n }\n\n for (const {key, meta, signal} of this) {\n if (!meta.cloneable || key in props) continue;\n if (meta.compound) {\n for (const [key, property] of meta.compoundEntries) {\n if (property in props) continue;\n const component = (<Record<string, SimpleSignal<any>>>(\n (<unknown>signal)\n ))[key];\n if (!component.context.isInitial()) {\n props[property] = component.context.raw();\n }\n }\n } else if (!signal.context.isInitial()) {\n props[key] = signal.context.raw();\n }\n }\n\n return this.instantiate(props);\n }\n\n /**\n * Create a copy of this node.\n *\n * @remarks\n * Unlike {@link clone}, a snapshot clone calculates any reactive properties\n * at the moment of cloning and passes the raw values to the copy.\n *\n * @param customProps - Properties to override.\n */\n public snapshotClone(customProps: NodeState = {}): this {\n const props = {\n ...this.getState(),\n ...customProps,\n };\n\n if (this.children().length > 0) {\n props.children ??= this.children().map(child => child.snapshotClone());\n }\n\n return this.instantiate(props);\n }\n\n /**\n * Create a reactive copy of this node.\n *\n * @remarks\n * A reactive copy has all its properties dynamically updated to match the\n * source node.\n *\n * @param customProps - Properties to override.\n */\n public reactiveClone(customProps: NodeState = {}): this {\n const props = {...customProps};\n if (this.children().length > 0) {\n props.children ??= this.children().map(child => child.reactiveClone());\n }\n\n for (const {key, meta, signal} of this) {\n if (!meta.cloneable || key in props) continue;\n props[key] = () => signal();\n }\n\n return this.instantiate(props);\n }\n\n /**\n * Create an instance of this node's class.\n *\n * @param props - Properties to pass to the constructor.\n */\n public instantiate(props: NodeProps = {}): this {\n return new (<NodeConstructor<NodeProps, this>>this.constructor)(props);\n }\n\n /**\n * Set the children without parsing them.\n *\n * @remarks\n * This method assumes that the caller took care of parsing the children and\n * updating the hierarchy.\n *\n * @param value - The children to set.\n */\n protected setParsedChildren(value: Node[]) {\n this.children.context.setter(value);\n this.realChildren = value;\n }\n\n protected spawnChildren(reactive: boolean, children: ComponentChildren) {\n const parsedChildren = this.parseChildren(children);\n\n const keep = new Set<string>();\n for (const newChild of parsedChildren) {\n const current = newChild.parent.context.raw() as Node | null;\n if (current && current !== this) {\n current.removeChild(newChild);\n }\n keep.add(newChild.key);\n newChild.parent(this);\n }\n\n for (const oldChild of this.realChildren) {\n if (!keep.has(oldChild.key)) {\n oldChild.parent(null);\n }\n }\n\n this.hasSpawnedChildren = reactive;\n this.realChildren = parsedChildren;\n }\n\n /**\n * Parse any `ComponentChildren` into an array of nodes.\n *\n * @param children - The children to parse.\n */\n protected parseChildren(children: ComponentChildren): Node[] {\n const result: Node[] = [];\n const array = Array.isArray(children) ? children : [children];\n for (const child of array) {\n if (child instanceof Node) {\n result.push(child);\n }\n }\n\n return result;\n }\n\n /**\n * Remove the given child.\n */\n protected removeChild(child: Node) {\n this.setParsedChildren(this.children().filter(node => node !== child));\n }\n\n /**\n * Whether this node should be cached or not.\n */\n protected requiresCache(): boolean {\n return (\n this.cache() ||\n this.opacity() < 1 ||\n this.compositeOperation() !== 'source-over' ||\n this.hasFilters() ||\n this.hasShadow() ||\n this.shaders().length > 0\n );\n }\n\n @computed()\n protected cacheCanvas(): CanvasRenderingContext2D {\n const canvas = document.createElement('canvas').getContext('2d');\n if (!canvas) {\n throw new Error('Could not create a cache canvas');\n }\n\n return canvas;\n }\n\n /**\n * Get a cache canvas with the contents of this node rendered onto it.\n */\n @computed()\n protected async cachedCanvas() {\n const context = this.cacheCanvas();\n const cache = this.worldSpaceCacheBBox();\n const matrix = this.localToWorld();\n\n context.canvas.width = cache.width;\n context.canvas.height = cache.height;\n\n context.setTransform(\n matrix.a,\n matrix.b,\n matrix.c,\n matrix.d,\n matrix.e - cache.x,\n matrix.f - cache.y,\n );\n await this.draw(context);\n\n return context;\n }\n\n /**\n * Get a bounding box for the contents rendered by this node.\n *\n * @remarks\n * The returned bounding box should be in local space.\n */\n protected getCacheBBox(): BBox {\n return new BBox();\n }\n\n /**\n * Get a bounding box for the contents rendered by this node as well\n * as its children.\n */\n @computed()\n public cacheBBox(): BBox {\n const cache = this.getCacheBBox();\n const children = this.children();\n const padding = this.cachePadding();\n if (children.length === 0) {\n return cache.addSpacing(padding);\n }\n\n const points: Vector2[] = cache.corners;\n for (const child of children) {\n const childCache = child.fullCacheBBox();\n const childMatrix = child.localToParent();\n points.push(\n ...childCache.corners.map(r => transformVectorAsPoint(r, childMatrix)),\n );\n }\n\n const bbox = BBox.fromPoints(...points);\n return bbox.addSpacing(padding);\n }\n\n /**\n * Get a bounding box for the contents rendered by this node (including\n * effects applied after caching).\n *\n * @remarks\n * The returned bounding box should be in local space.\n */\n @computed()\n protected fullCacheBBox(): BBox {\n const matrix = this.compositeToLocal();\n const shadowOffset = transformVector(this.shadowOffset(), matrix);\n const shadowBlur = transformScalar(this.shadowBlur(), matrix);\n\n const result = this.cacheBBox().expand(\n this.filters.blur() * 2 + shadowBlur,\n );\n\n if (shadowOffset.x < 0) {\n result.x += shadowOffset.x;\n result.width -= shadowOffset.x;\n } else {\n result.width += shadowOffset.x;\n }\n\n if (shadowOffset.y < 0) {\n result.y += shadowOffset.y;\n result.height -= shadowOffset.y;\n } else {\n result.height += shadowOffset.y;\n }\n\n return result;\n }\n\n /**\n * Get a bounding box in world space for the contents rendered by this node as\n * well as its children.\n *\n * @remarks\n * This is the same the bounding box returned by {@link cacheBBox} only\n * transformed to world space.\n */\n @computed()\n protected worldSpaceCacheBBox(): BBox {\n const viewBBox = BBox.fromSizeCentered(this.view().size());\n const canvasBBox = BBox.fromPoints(\n ...viewBBox.transformCorners(this.view().localToWorld()),\n );\n const cacheBBox = BBox.fromPoints(\n ...this.cacheBBox().transformCorners(this.localToWorld()),\n ).pixelPerfect.expand(2);\n\n return canvasBBox.intersection(cacheBBox);\n }\n\n @computed()\n protected parentWorldSpaceCacheBBox(): BBox {\n return (\n this.findAncestor(node => node.requiresCache())?.worldSpaceCacheBBox() ??\n new BBox(Vector2.zero, useScene2D().getSize())\n );\n }\n\n /**\n * Prepare the given context for drawing a cached node onto it.\n *\n * @remarks\n * This method is called before the contents of the cache canvas are drawn\n * on the screen. It can be used to apply effects to the entire node together\n * with its children, instead of applying them individually.\n * Effects such as transparency, shadows, and filters use this technique.\n *\n * Whether the node is cached is decided by the {@link requiresCache} method.\n *\n * @param context - The context using which the cache will be drawn.\n */\n protected setupDrawFromCache(context: CanvasRenderingContext2D) {\n context.globalCompositeOperation = this.compositeOperation();\n context.globalAlpha *= this.opacity();\n if (this.hasFilters()) {\n context.filter = this.filterString();\n }\n if (this.hasShadow()) {\n const matrix = this.compositeToWorld();\n const offset = transformVector(this.shadowOffset(), matrix);\n const blur = transformScalar(this.shadowBlur(), matrix);\n\n context.shadowColor = this.shadowColor().serialize();\n context.shadowBlur = blur;\n context.shadowOffsetX = offset.x;\n context.shadowOffsetY = offset.y;\n }\n\n const matrix = this.worldToLocal();\n context.transform(\n matrix.a,\n matrix.b,\n matrix.c,\n matrix.d,\n matrix.e,\n matrix.f,\n );\n }\n\n protected renderFromSource(\n context: CanvasRenderingContext2D,\n source: CanvasImageSource,\n x: number,\n y: number,\n ) {\n this.setupDrawFromCache(context);\n\n const compositeOverride = this.compositeOverride();\n context.drawImage(source, x, y);\n if (compositeOverride > 0) {\n context.save();\n context.globalAlpha *= compositeOverride;\n context.globalCompositeOperation = 'source-over';\n context.drawImage(source, x, y);\n context.restore();\n }\n }\n\n private shaderCanvas(destination: TexImageSource, source: TexImageSource) {\n const shaders = this.shaders();\n if (shaders.length === 0) {\n return null;\n }\n\n const scene = useScene2D();\n const size = scene.getRealSize();\n const parentCacheRect = this.parentWorldSpaceCacheBBox();\n const cameraToWorld = new DOMMatrix()\n .scaleSelf(\n size.width / parentCacheRect.width,\n size.height / -parentCacheRect.height,\n )\n .translateSelf(\n parentCacheRect.x / -size.width,\n parentCacheRect.y / size.height - 1,\n );\n\n const cacheRect = this.worldSpaceCacheBBox();\n const cameraToCache = new DOMMatrix()\n .scaleSelf(size.width / cacheRect.width, size.height / -cacheRect.height)\n .translateSelf(cacheRect.x / -size.width, cacheRect.y / size.height - 1)\n .invertSelf();\n\n const gl = scene.shaders.getGL();\n scene.shaders.copyTextures(destination, source);\n scene.shaders.clear();\n\n for (const shader of shaders) {\n const program = scene.shaders.getProgram(shader.fragment);\n if (!program) {\n continue;\n }\n\n if (shader.uniforms) {\n for (const [name, uniform] of Object.entries(shader.uniforms)) {\n const location = gl.getUniformLocation(program, name);\n if (location === null) {\n continue;\n }\n\n const value = unwrap(uniform);\n if (typeof value === 'number') {\n gl.uniform1f(location, value);\n } else if ('toUniform' in value) {\n value.toUniform(gl, location);\n } else if (value.length === 1) {\n gl.uniform1f(location, value[0]);\n } else if (value.length === 2) {\n gl.uniform2f(location, value[0], value[1]);\n } else if (value.length === 3) {\n gl.uniform3f(location, value[0], value[1], value[2]);\n } else if (value.length === 4) {\n gl.uniform4f(location, value[0], value[1], value[2], value[3]);\n }\n }\n }\n\n gl.uniform1f(\n gl.getUniformLocation(program, UNIFORM_TIME),\n this.view2D.globalTime(),\n );\n\n gl.uniform1i(\n gl.getUniformLocation(program, UNIFORM_TIME),\n scene.playback.frame,\n );\n\n gl.uniformMatrix4fv(\n gl.getUniformLocation(program, UNIFORM_SOURCE_MATRIX),\n false,\n cameraToCache.toFloat32Array(),\n );\n\n gl.uniformMatrix4fv(\n gl.getUniformLocation(program, UNIFORM_DESTINATION_MATRIX),\n false,\n cameraToWorld.toFloat32Array(),\n );\n\n shader.setup?.(gl, program);\n scene.shaders.render();\n shader.teardown?.(gl, program);\n }\n\n return gl.canvas;\n }\n\n /**\n * Render this node onto the given canvas.\n *\n * @param context - The context to draw with.\n */\n public async render(context: CanvasRenderingContext2D) {\n if (this.absoluteOpacity() <= 0) {\n return;\n }\n\n context.save();\n this.transformContext(context);\n\n if (this.requiresCache()) {\n const cacheRect = this.worldSpaceCacheBBox();\n if (cacheRect.width !== 0 && cacheRect.height !== 0) {\n const cache = (await this.cachedCanvas()).canvas;\n const source = this.shaderCanvas(context.canvas, cache);\n if (source) {\n this.renderFromSource(context, source, 0, 0);\n } else {\n this.renderFromSource(\n context,\n cache,\n cacheRect.position.x,\n cacheRect.position.y,\n );\n }\n }\n } else {\n await this.draw(context);\n }\n\n context.restore();\n }\n\n /**\n * Draw this node onto the canvas.\n *\n * @remarks\n * This method is used when drawing directly onto the screen as well as onto\n * the cache canvas.\n * It assumes that the context have already been transformed to local space.\n *\n * @param context - The context to draw with.\n */\n protected async draw(context: CanvasRenderingContext2D) {\n await this.drawChildren(context);\n }\n\n protected async drawChildren(context: CanvasRenderingContext2D) {\n for (const child of this.sortedChildren()) {\n await child.render(context);\n }\n }\n\n /**\n * Draw an overlay for this node.\n *\n * @remarks\n * The overlay for the currently inspected node is displayed on top of the\n * canvas.\n *\n * The provided context is in screen space. The local-to-screen matrix can be\n * used to transform all shapes that need to be displayed.\n * This approach allows to keep the line widths and gizmo sizes consistent,\n * no matter how zoomed-in the view is.\n *\n * @param context - The context to draw with.\n * @param matrix - A local-to-screen matrix.\n */\n public drawOverlay(context: CanvasRenderingContext2D, matrix: DOMMatrix) {\n const box = this.cacheBBox().transformCorners(matrix);\n const cache = this.getCacheBBox().transformCorners(matrix);\n context.strokeStyle = 'white';\n context.lineWidth = 1;\n context.beginPath();\n drawLine(context, box);\n context.closePath();\n context.stroke();\n\n context.strokeStyle = 'blue';\n context.beginPath();\n drawLine(context, cache);\n context.closePath();\n context.stroke();\n }\n\n protected transformContext(context: CanvasRenderingContext2D) {\n const matrix = this.localToParent();\n context.transform(\n matrix.a,\n matrix.b,\n matrix.c,\n matrix.d,\n matrix.e,\n matrix.f,\n );\n }\n\n /**\n * Try to find a node intersecting the given position.\n *\n * @param position - The searched position.\n */\n public hit(position: Vector2): Node | null {\n let hit: Node | null = null;\n const local = transformVectorAsPoint(\n position,\n this.localToParent().inverse(),\n );\n const children = this.children();\n for (let i = children.length - 1; i >= 0; i--) {\n hit = children[i].hit(local);\n if (hit) {\n break;\n }\n }\n\n return hit;\n }\n\n /**\n * Collect all asynchronous resources used by this node.\n */\n protected collectAsyncResources() {\n for (const child of this.children()) {\n child.collectAsyncResources();\n }\n }\n\n /**\n * Wait for any asynchronous resources that this node or its children have.\n *\n * @remarks\n * Certain resources like images are always loaded asynchronously.\n * Awaiting this method makes sure that all such resources are done loading\n * before continuing the animation.\n */\n public async toPromise(): Promise<this> {\n do {\n await DependencyContext.consumePromises();\n this.collectAsyncResources();\n } while (DependencyContext.hasPromises());\n return this;\n }\n\n /**\n * Return a snapshot of the node's current signal values.\n *\n * @remarks\n * This method will calculate the values of any reactive properties of the\n * node at the time the method is called.\n */\n public getState(): NodeState {\n const state: NodeState = {};\n for (const {key, meta, signal} of this) {\n if (!meta.cloneable || key in state) continue;\n state[key] = signal();\n }\n return state;\n }\n\n /**\n * Apply the given state to the node, setting all matching signal values to\n * the provided values.\n *\n * @param state - The state to apply to the node.\n */\n public applyState(state: NodeState): void;\n /**\n * Smoothly transition between the current state of the node and the given\n * state.\n *\n * @param state - The state to transition to.\n * @param duration - The duration of the transition.\n * @param timing - The timing function to use for the transition.\n */\n public applyState(\n state: NodeState,\n duration: number,\n timing?: TimingFunction,\n ): ThreadGenerator;\n public applyState(\n state: NodeState,\n duration?: number,\n timing: TimingFunction = easeInOutCubic,\n ): ThreadGenerator | void {\n if (duration === undefined) {\n for (const key in state) {\n const signal = this.signalByKey(key);\n if (signal) {\n signal(state[key]);\n }\n }\n }\n\n const tasks: ThreadGenerator[] = [];\n for (const key in state) {\n const signal = this.signalByKey(key);\n if (state[key] !== signal.context.raw()) {\n tasks.push(signal(state[key], duration!, timing));\n }\n }\n\n return all(...tasks);\n }\n\n /**\n * Push a snapshot of the node's current state onto the node's state stack.\n *\n * @remarks\n * This method can be used together with the {@link restore} method to save a\n * node's current state and later restore it. It is possible to store more\n * than one state by calling `save` method multiple times.\n */\n public save(): void {\n this.stateStack.push(this.getState());\n }\n\n /**\n * Restore the node to its last saved state.\n *\n * @remarks\n * This method can be used together with the {@link save} method to restore a\n * node to a previously saved state. Restoring a node to a previous state\n * removes that state from the state stack.\n *\n * @example\n * ```tsx\n * const node = <Circle width={100} height={100} fill={\"lightseagreen\"} />\n *\n * view.add(node);\n *\n * // Save the node's current state\n * node.save();\n *\n * // Modify some of the node's properties\n * yield* node.scale(2, 1);\n * yield* node.fill('hotpink', 1);\n *\n * // Restore the node to its saved state\n * node.restore();\n * ```\n */\n public restore(): void;\n /**\n * Tween the node to its last saved state.\n *\n * @remarks\n * This method can be used together with the {@link save} method to restore a\n * node to a previously saved state. Restoring a node to a previous state\n * removes that state from the state stack.\n *\n * @example\n * ```tsx\n * const node = <Circle width={100} height={100} fill={\"lightseagreen\"} />\n *\n * view.add(node);\n *\n * // Save the node's current state\n * node.save();\n *\n * // Modify some of the node's properties\n * yield* node.scale(2, 1);\n * yield* node.fill('hotpink', 1);\n *\n * // Tween the node to its saved state over 1 second\n * yield* node.restore(1);\n * ```\n *\n * @param duration - The duration of the transition.\n * @param timing - The timing function to use for the transition.\n */\n public restore(duration: number, timing?: TimingFunction): ThreadGenerator;\n public restore(\n duration?: number,\n timing: TimingFunction = easeInOutCubic,\n ): ThreadGenerator | void {\n const state = this.stateStack.pop();\n\n if (state !== undefined) {\n return this.applyState(state, duration!, timing);\n }\n }\n\n public *[Symbol.iterator]() {\n for (const key in this.properties) {\n const meta = this.properties[key];\n const signal = this.signalByKey(key);\n yield {meta, signal, key};\n }\n }\n\n private signalByKey(key: string): SimpleSignal<any> {\n return (<Record<string, SimpleSignal<any>>>(<unknown>this))[key];\n }\n\n private reversedChildren() {\n const children = this.children();\n const result: Node[] = [];\n for (let i = children.length - 1; i >= 0; i--) {\n result.push(children[i]);\n }\n return result;\n }\n}\n\nNode.prototype.isClass = true;\n","import type {SignalValue, WebGLConvertible} from '@twick/core';\nimport {experimentalLog, useLogger, useScene} from '@twick/core';\nimport type {Node} from '../components';\n\n/**\n * Describes a shader program used to apply effects to nodes.\n *\n * @experimental\n */\nexport interface ShaderConfig {\n /**\n * The source code of the fragment shader.\n *\n * @example\n * ```glsl\n * #version 300 es\n * precision highp float;\n *\n * #include \"@twick/core/shaders/common.glsl\"\n *\n * void main() {\n * out_color = texture(core_source_tx, source_uv);\n * }\n * ```\n */\n fragment: string;\n\n /**\n * Custom uniforms to be passed to the shader.\n *\n * @remarks\n * The keys of this object will be used as the uniform names.\n * The values can be either a number or an array of numbers.\n * The following table shows how the values will be mapped to GLSL types.\n *\n * | TypeScript | GLSL |\n * | ---------------------------------- | ------- |\n * | `number` | `float` |\n * | `[number, number]` | `vec2` |\n * | `[number, number, number]` | `vec3` |\n * | `[number, number, number, number]` | `vec4` |\n *\n * @example\n * ```ts\n * const shader = {\n * // ...\n * uniforms: {\n * my_value: () => 1,\n * my_vector: [1, 2, 3],\n * },\n * };\n * ```\n *\n * ```glsl\n * uniform float my_value;\n * uniform vec3 my_vector;\n * ```\n */\n uniforms?: Record<string, SignalValue<number | number[] | WebGLConvertible>>;\n\n /**\n * A custom hook run before the shader is used.\n *\n * @remarks\n * Gives you low-level access to the WebGL context and the shader program.\n *\n * @param gl - WebGL context.\n * @param program - The shader program.\n */\n setup?: (gl: WebGL2RenderingContext, program: WebGLProgram) => void;\n\n /**\n * A custom hook run after the shader is used.\n *\n * @remarks\n * Gives you low-level access to the WebGL context and the shader program.\n * Can be used to clean up resources created in the {@link setup} hook.\n *\n * @param gl - WebGL context.\n * @param program - The shader program.\n */\n teardown?: (gl: WebGL2RenderingContext, program: WebGLProgram) => void;\n}\n\nexport type PossibleShaderConfig =\n | (ShaderConfig | string)[]\n | ShaderConfig\n | string\n | null;\n\nexport function parseShader(\n this: Node,\n value: PossibleShaderConfig,\n): ShaderConfig[] {\n let result: ShaderConfig[];\n if (!value) {\n result = [];\n } else if (typeof value === 'string') {\n result = [{fragment: value}];\n } else if (Array.isArray(value)) {\n result = value.map(item =>\n typeof item === 'string' ? {fragment: item} : item,\n );\n } else {\n result = [value];\n }\n\n if (!useScene().experimentalFeatures && result.length > 0) {\n result = [];\n useLogger().log({\n ...experimentalLog(`Node uses experimental shaders.`),\n inspect: this.key,\n });\n }\n\n return result;\n}\n","import {useScene} from '@twick/core';\nimport type {Scene2D} from './Scene2D';\n\nexport function useScene2D(): Scene2D {\n return <Scene2D>useScene();\n}\n","import type {SerializedVector2, Vector2} from '@twick/core';\nimport {BBox, transformVectorAsPoint} from '@twick/core';\nimport type {CurveProfile} from '../curves';\nimport type {PolynomialSegment} from '../curves/PolynomialSegment';\nimport {computed} from '../decorators';\nimport type {DesiredLength} from '../partials';\nimport {arc, drawLine, drawPivot, moveTo} from '../utils';\nimport {Curve} from './Curve';\n\nexport interface BezierOverlayInfo {\n curve: Path2D;\n handleLines: Path2D;\n controlPoints: Vector2[];\n startPoint: Vector2;\n endPoint: Vector2;\n}\n\nexport abstract class Bezier extends Curve {\n public override profile(): CurveProfile {\n const segment = this.segment();\n return {\n segments: [segment],\n arcLength: segment.arcLength,\n minSin: 0,\n };\n }\n\n protected abstract segment(): PolynomialSegment;\n\n protected abstract overlayInfo(matrix: DOMMatrix): BezierOverlayInfo;\n\n @computed()\n protected childrenBBox(): BBox {\n return BBox.fromPoints(...this.segment().points);\n }\n\n protected override desiredSize(): SerializedVector2<DesiredLength> {\n return this.segment().getBBox().size;\n }\n\n protected override offsetComputedLayout(box: BBox): BBox {\n box.position = box.position.sub(this.segment().getBBox().center);\n return box;\n }\n\n public override drawOverlay(\n context: CanvasRenderingContext2D,\n matrix: DOMMatrix,\n ) {\n const size = this.computedSize();\n const box = this.childrenBBox().transformCorners(matrix);\n const offsetBeforeTransform = size.mul(this.offset()).scale(0.5);\n const offset = transformVectorAsPoint(offsetBeforeTransform, matrix);\n const overlayInfo = this.overlayInfo(matrix);\n\n context.lineWidth = 1;\n context.strokeStyle = 'white';\n context.fillStyle = 'white';\n\n // Draw the curve itself first so everything else gets drawn on top of it\n context.stroke(overlayInfo.curve);\n\n context.fillStyle = 'white';\n context.globalAlpha = 0.5;\n\n context.beginPath();\n context.stroke(overlayInfo.handleLines);\n\n context.globalAlpha = 1;\n context.lineWidth = 2;\n\n // Draw start and end points\n for (const point of [overlayInfo.startPoint, overlayInfo.endPoint]) {\n moveTo(context, point);\n context.beginPath();\n arc(context, point, 4);\n context.closePath();\n context.stroke();\n context.fill();\n }\n\n // Draw the control points\n context.fillStyle = 'black';\n for (const point of overlayInfo.controlPoints) {\n moveTo(context, point);\n context.beginPath();\n arc(context, point, 4);\n context.closePath();\n context.fill();\n context.stroke();\n }\n\n // Draw the offset marker\n context.lineWidth = 1;\n context.beginPath();\n drawPivot(context, offset);\n context.stroke();\n\n // Draw the bounding box\n context.beginPath();\n drawLine(context, box);\n context.closePath();\n context.stroke();\n }\n}\n","import type {SerializedVector2, SignalValue, SimpleSignal} from '@twick/core';\nimport {BBox, DEG2RAD} from '@twick/core';\nimport type {CurveProfile} from '../curves';\nimport {getCircleProfile} from '../curves';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport type {DesiredLength} from '../partials';\nimport type {CurveProps} from './Curve';\nimport {Curve} from './Curve';\n\nexport interface CircleProps extends CurveProps {\n /**\n * {@inheritDoc Circle.startAngle}\n */\n startAngle?: SignalValue<number>;\n /**\n * {@inheritDoc Circle.endAngle}\n */\n endAngle?: SignalValue<number>;\n /**\n * {@inheritDoc Circle.counterclockwise}\n */\n counterclockwise?: SignalValue<boolean>;\n /**\n * {@inheritDoc Circle.closed}\n */\n closed?: SignalValue<boolean>;\n}\n\n/**\n * A node for drawing circular shapes.\n *\n * @remarks\n * This node can be used to render shapes such as: circle, ellipse, arc, and\n * sector (pie chart).\n *\n * @preview\n * ```tsx editor\n * // snippet Simple circle\n * import {makeScene2D, Circle} from '@twick/2d';\n *\n * export default makeScene2D(function* (view) {\n * view.add(\n * <Circle\n * size={160}\n * fill={'lightseagreen'}\n * />\n * );\n * });\n *\n * // snippet Ellipse\n * import {makeScene2D, Circle} from '@twick/2d';\n *\n * export default makeScene2D(function* (view) {\n * view.add(\n * <Circle\n * width={160}\n * height={80}\n * fill={'lightseagreen'}\n * />\n * );\n * });\n *\n * // snippet Sector (pie chart):\n * import {makeScene2D, Circle} from '@twick/2d';\n * import {createRef} from '@twick/core';\n *\n * export default makeScene2D(function* (view) {\n * const ref = createRef<Circle>();\n * view.add(\n * <Circle\n * ref={ref}\n * size={160}\n * fill={'lightseagreen'}\n * startAngle={30}\n * endAngle={270}\n * closed={true}\n * />\n * );\n *\n * yield* ref().startAngle(270, 2).to(30, 2);\n * });\n *\n * // snippet Arc:\n * import {makeScene2D, Circle} from '@twick/2d';\n * import {createRef} from '@twick/core';\n *\n * export default makeScene2D(function* (view) {\n * const ref = createRef<Circle>();\n * view.add(\n * <Circle\n * ref={ref}\n * size={160}\n * stroke={'lightseagreen'}\n * lineWidth={8}\n * startAngle={-90}\n * endAngle={90}\n * />\n * );\n *\n * yield* ref().startAngle(-270, 2).to(-90, 2);\n * });\n *\n * // snippet Curve properties:\n * import {makeScene2D, Circle} from '@twick/2d';\n * import {all, createRef, easeInCubic, easeOutCubic} from '@twick/core';\n *\n * export default makeScene2D(function* (view) {\n * const ref = createRef<Circle>();\n * view.add(\n * <Circle\n * ref={ref}\n * size={160}\n * stroke={'lightseagreen'}\n * lineWidth={8}\n * endAngle={270}\n * endArrow\n * />,\n * );\n *\n * yield* all(ref().start(1, 1), ref().rotation(180, 1, easeInCubic));\n * ref().start(0).end(0);\n * yield* all(ref().end(1, 1), ref().rotation(360, 1, easeOutCubic));\n * });\n * ```\n */\n@nodeName('Circle')\nexport class Circle extends Curve {\n /**\n * The starting angle in degrees for the circle sector.\n *\n * @remarks\n * This property can be used together with {@link startAngle} to turn this\n * circle into a sector (when using fill) or an arc (when using stroke).\n *\n * @defaultValue 0\n */\n @initial(0)\n @signal()\n public declare readonly startAngle: SimpleSignal<number, this>;\n\n /**\n * The ending angle in degrees for the circle sector.\n *\n * @remarks\n * This property can be used together with {@link endAngle} to turn this\n * circle into a sector (when using fill) or an arc (when using stroke).\n *\n * @defaultValue 360\n */\n @initial(360)\n @signal()\n public declare readonly endAngle: SimpleSignal<number, this>;\n\n /**\n * Whether the circle sector should be drawn counterclockwise.\n *\n * @remarks\n * By default, the circle begins at {@link startAngle} and is drawn clockwise\n * until reaching {@link endAngle}. Setting this property to true will reverse\n * this direction.\n */\n @initial(false)\n @signal()\n public declare readonly counterclockwise: SimpleSignal<boolean, this>;\n\n /**\n * Whether the path of this circle should be closed.\n *\n * @remarks\n * When set to true, the path of this circle will start and end at the center.\n * This can be used to fine-tune how sectors are rendered.\n *\n * @example\n * A closed circle will look like a pie chart:\n * ```tsx\n * <Circle\n * size={300}\n * fill={'lightseagreen'}\n * endAngle={230}\n * closed={true}\n * />\n * ```\n * An open one will look like an arc:\n * ```tsx\n * <Circle\n * size={300}\n * stroke={'lightseagreen'}\n * lineWidth={8}\n * endAngle={230}\n * closed={false}\n * />\n * ```\n *\n * @defaultValue false\n */\n public declare readonly closed: SimpleSignal<boolean, this>;\n\n public constructor(props: CircleProps) {\n super(props);\n }\n\n @computed()\n public profile(): CurveProfile {\n return getCircleProfile(\n this.size().scale(0.5),\n this.startAngle() * DEG2RAD,\n this.endAngle() * DEG2RAD,\n this.closed(),\n this.counterclockwise(),\n );\n }\n\n protected override desiredSize(): SerializedVector2<DesiredLength> {\n return {\n x: this.width.context.getter(),\n y: this.height.context.getter(),\n };\n }\n\n protected override offsetComputedLayout(box: BBox): BBox {\n return box;\n }\n\n protected override childrenBBox(): BBox {\n return BBox.fromSizeCentered(this.computedSize());\n }\n\n protected override getPath(): Path2D {\n if (this.requiresProfile()) {\n return this.curveDrawingInfo().path;\n }\n\n return this.createPath();\n }\n\n protected override getRipplePath(): Path2D {\n return this.createPath(this.rippleSize());\n }\n\n protected override getCacheBBox(): BBox {\n return super.getCacheBBox().expand(this.rippleSize());\n }\n\n protected createPath(expand = 0) {\n const path = new Path2D();\n const start = this.startAngle() * DEG2RAD;\n let end = this.endAngle() * DEG2RAD;\n const size = this.size().scale(0.5).add(expand);\n const closed = this.closed();\n\n if (end > start + Math.PI * 2) {\n const loops = Math.floor((end - start) / (Math.PI * 2));\n end -= Math.PI * 2 * loops;\n }\n\n if (closed) {\n path.moveTo(0, 0);\n }\n path.ellipse(0, 0, size.x, size.y, 0, start, end, this.counterclockwise());\n if (closed) {\n path.closePath();\n }\n\n return path;\n }\n}\n","import {Vector2, clamp} from '@twick/core';\nimport {CubicBezierSegment} from './CubicBezierSegment';\nimport type {CurveProfile} from './CurveProfile';\nimport type {KnotInfo} from './KnotInfo';\nimport type {PolynomialSegment} from './PolynomialSegment';\nimport {QuadBezierSegment} from './QuadBezierSegment';\n\nfunction isCubicSegment(\n segment: PolynomialSegment,\n): segment is CubicBezierSegment {\n return segment instanceof CubicBezierSegment;\n}\n\n/**\n * Update a given knot's handles to be a blend between the user provided handles\n * and a set of auto calculated handles that smoothly connect the knot to its\n * two neighboring knots.\n *\n * @param knot - The knot for which to calculate the handles\n * @param previous - The previous knot in the spline, relative to the provided\n * knot.\n * @param next - The next knot in the spline, relative to the provided knot.\n * @param smoothness - The desired smoothness of the spline. Affects the scaling\n * of the auto calculated handles.\n */\nfunction calculateSmoothHandles(\n knot: KnotInfo,\n previous: KnotInfo,\n next: KnotInfo,\n smoothness: number,\n) {\n if (knot.auto.start === 0 && knot.auto.end === 0) {\n return;\n }\n\n // See for reference:\n // http://scaledinnovation.com/analytics/splines/aboutSplines.html\n const distanceToPrev = knot.position.sub(previous.position).magnitude;\n const distanceToNext = next.position.sub(knot.position).magnitude;\n const fa = (smoothness * distanceToPrev) / (distanceToPrev + distanceToNext);\n const fb = smoothness - fa;\n const startHandle = new Vector2(\n knot.position.x - fa * (next.position.x - previous.position.x),\n knot.position.y - fa * (next.position.y - previous.position.y),\n );\n const endHandle = new Vector2(\n knot.position.x + fb * (next.position.x - previous.position.x),\n knot.position.y + fb * (next.position.y - previous.position.y),\n );\n\n knot.startHandle = knot.startHandle.lerp(startHandle, knot.auto.start);\n knot.endHandle = knot.endHandle.lerp(endHandle, knot.auto.end);\n}\n\n/**\n * Calculate the `minSin` value of the curve profile so that miter joins get\n * taken into account properly.\n */\nfunction updateMinSin(profile: CurveProfile) {\n for (let i = 0; i < profile.segments.length; i++) {\n const segmentA = profile.segments[i] as PolynomialSegment;\n const segmentB = profile.segments[\n (i + 1) % profile.segments.length\n ] as PolynomialSegment;\n\n // Quadratic Bézier segments will always join smoothly with the previous\n // segment. This means that we can skip the segment since it's impossible\n // to have a miter join between the two segments.\n if (!isCubicSegment(segmentA) || !isCubicSegment(segmentB)) {\n continue;\n }\n\n const startVector = segmentA.p2.sub(segmentA.p3).normalized.safe;\n const endVector = segmentB.p1.sub(segmentB.p0).normalized.safe;\n const dot = startVector.dot(endVector);\n\n // A miter join can only occur if the handle is broken, so we can skip the\n // segment if the handles are mirrored.\n const isBroken = 1 - Math.abs(dot) > 0.0001;\n if (!isBroken) {\n continue;\n }\n\n const angleBetween = Math.acos(clamp(-1, 1, dot));\n const angleSin = Math.sin(angleBetween / 2);\n\n profile.minSin = Math.min(profile.minSin, Math.abs(angleSin));\n }\n}\n\nfunction addSegmentToProfile(\n profile: CurveProfile,\n p0: Vector2,\n p1: Vector2,\n p2: Vector2,\n p3?: Vector2,\n) {\n const segment =\n p3 !== undefined\n ? new CubicBezierSegment(p0, p1, p2, p3)\n : new QuadBezierSegment(p0, p1, p2);\n profile.segments.push(segment);\n profile.arcLength += segment.arcLength;\n}\n\n/**\n * Calculate the curve profile of a spline based on a set of knots.\n *\n * @param knots - The knots defining the spline\n * @param closed - Whether the spline should be closed or not\n * @param smoothness - The desired smoothness of the spline when using auto\n * calculated handles.\n */\nexport function getBezierSplineProfile(\n knots: KnotInfo[],\n closed: boolean,\n smoothness: number,\n): CurveProfile {\n const profile: CurveProfile = {\n segments: [],\n arcLength: 0,\n minSin: 1,\n };\n\n // First, we want to calculate the actual handle positions for each knot. We\n // do so using the knot's `auto` value to blend between the user-provided\n // handles and the auto calculated smooth handles.\n const numberOfKnots = knots.length;\n for (let i = 0; i < numberOfKnots; i++) {\n // Calculating the auto handles for a given knot requires both of the knot's\n // neighboring knots. To make sure that this works properly for the first\n // and last knots of the spline, we want to make sure to wrap around to the\n // beginning and end of the array, respectively.\n const prevIndex = (i - 1 + numberOfKnots) % numberOfKnots;\n const nextIndex = (i + 1) % numberOfKnots;\n calculateSmoothHandles(\n knots[i],\n knots[prevIndex],\n knots[nextIndex],\n smoothness,\n );\n }\n\n const firstKnot = knots[0];\n const secondKnot = knots[1];\n\n // Drawing the first and last segments of a spline has a few edge cases we\n // need to consider:\n // If the spline is not closed and the first knot should use the auto\n // calculated handles, we want to draw a quadratic Bézier curve instead of a\n // cubic one.\n if (!closed && firstKnot.auto.start === 1 && firstKnot.auto.end === 1) {\n addSegmentToProfile(\n profile,\n firstKnot.position,\n secondKnot.startHandle,\n secondKnot.position,\n );\n } else {\n // Otherwise, draw a cubic Bézier segment like we do for the other segments.\n addSegmentToProfile(\n profile,\n firstKnot.position,\n firstKnot.endHandle,\n secondKnot.startHandle,\n secondKnot.position,\n );\n }\n\n // Add all intermediate spline segments as cubic Bézier curve segments.\n for (let i = 1; i < numberOfKnots - 2; i++) {\n const start = knots[i];\n const end = knots[i + 1];\n addSegmentToProfile(\n profile,\n start.position,\n start.endHandle,\n end.startHandle,\n end.position,\n );\n }\n\n const lastKnot = knots.at(-1)!;\n const secondToLastKnot = knots.at(-2)!;\n\n if (knots.length > 2) {\n // Similar to the first segment, we also want to draw the last segment as a\n // quadratic Bézier curve if the curve is not closed and the knot should\n // use the auto calculated handles.\n if (!closed && lastKnot.auto.start === 1 && lastKnot.auto.end === 1) {\n addSegmentToProfile(\n profile,\n secondToLastKnot.position,\n secondToLastKnot.endHandle,\n lastKnot.position,\n );\n } else {\n addSegmentToProfile(\n profile,\n secondToLastKnot.position,\n secondToLastKnot.endHandle,\n lastKnot.startHandle,\n lastKnot.position,\n );\n }\n }\n\n // If the spline should be closed, add one final cubic Bézier segment\n // connecting the last and first knots.\n if (closed) {\n addSegmentToProfile(\n profile,\n lastKnot.position,\n lastKnot.endHandle,\n firstKnot.startHandle,\n firstKnot.position,\n );\n }\n\n updateMinSin(profile);\n\n return profile;\n}\n","import {Vector2, lazy} from '@twick/core';\nimport {quadraticCurveTo} from '../utils';\nimport {Polynomial2D} from './Polynomial2D';\nimport {PolynomialSegment} from './PolynomialSegment';\n\n/**\n * A spline segment representing a quadratic Bézier curve.\n */\nexport class QuadBezierSegment extends PolynomialSegment {\n @lazy(() => document.createElementNS('http://www.w3.org/2000/svg', 'path'))\n private static el: SVGPathElement;\n\n public get points(): Vector2[] {\n return [this.p0, this.p1, this.p2];\n }\n\n public constructor(\n public readonly p0: Vector2,\n public readonly p1: Vector2,\n public readonly p2: Vector2,\n ) {\n super(\n new Polynomial2D(\n p0,\n // 2*(-p0+p1)\n p0.flipped.add(p1).scale(2),\n // p0-2*p1+p2\n p0.sub(p1.scale(2)).add(p2),\n ),\n QuadBezierSegment.getLength(p0, p1, p2),\n );\n }\n\n public split(t: number): [PolynomialSegment, PolynomialSegment] {\n const a = new Vector2(\n this.p0.x + (this.p1.x - this.p0.x) * t,\n this.p0.y + (this.p1.y - this.p0.y) * t,\n );\n const b = new Vector2(\n this.p1.x + (this.p2.x - this.p1.x) * t,\n this.p1.y + (this.p2.y - this.p1.y) * t,\n );\n const p = new Vector2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);\n\n const left = new QuadBezierSegment(this.p0, a, p);\n const right = new QuadBezierSegment(p, b, this.p2);\n\n return [left, right];\n }\n\n protected static getLength(p0: Vector2, p1: Vector2, p2: Vector2): number {\n // Let the browser do the work for us instead of calculating the arclength\n // manually.\n QuadBezierSegment.el.setAttribute(\n 'd',\n `M ${p0.x} ${p0.y} Q ${p1.x} ${p1.y} ${p2.x} ${p2.y}`,\n );\n return QuadBezierSegment.el.getTotalLength();\n }\n\n protected override doDraw(context: CanvasRenderingContext2D | Path2D) {\n quadraticCurveTo(context, this.p1, this.p2);\n }\n}\n","import {Vector2} from '@twick/core';\nimport {ArcSegment} from './ArcSegment';\nimport type {CurveProfile} from './CurveProfile';\nimport {LineSegment} from './LineSegment';\nimport type {Segment} from './Segment';\n\nexport function getCircleProfile(\n size: Vector2,\n startAngle: number,\n endAngle: number,\n closed: boolean,\n counterclockwise = false,\n): CurveProfile {\n const profile: CurveProfile = {\n arcLength: 0,\n minSin: 1,\n segments: [],\n };\n\n if (endAngle < startAngle) {\n const loops = Math.floor((startAngle - endAngle) / (Math.PI * 2)) + 1;\n endAngle += Math.PI * 2 * loops;\n } else if (endAngle > startAngle + Math.PI * 2) {\n const loops = Math.floor((endAngle - startAngle) / (Math.PI * 2));\n endAngle -= Math.PI * 2 * loops;\n }\n\n const middleAngle = (startAngle + endAngle) / 2;\n const from = size.mul(Vector2.fromRadians(startAngle));\n const to = size.mul(Vector2.fromRadians(endAngle));\n const middle = size\n .mul(Vector2.fromRadians(middleAngle))\n .scale(counterclockwise ? -1 : 1);\n\n if (closed) {\n addSegment(profile, new LineSegment(Vector2.zero, from));\n }\n\n addArcSegment(\n profile,\n size,\n from,\n middle,\n startAngle,\n middleAngle,\n counterclockwise,\n );\n addArcSegment(\n profile,\n size,\n middle,\n to,\n middleAngle,\n endAngle,\n counterclockwise,\n );\n\n if (closed) {\n addSegment(profile, new LineSegment(to, Vector2.zero));\n }\n\n return profile;\n}\n\nfunction addSegment(profile: CurveProfile, segment: Segment) {\n profile.segments.push(segment);\n profile.arcLength += segment.arcLength;\n}\n\nfunction addArcSegment(\n profile: CurveProfile,\n size: Vector2,\n from: Vector2,\n to: Vector2,\n fromAngle: number,\n toAngle: number,\n counterclockwise: boolean,\n) {\n const small = Math.abs(fromAngle - toAngle) <= 180 ? 1 : 0;\n const flip = fromAngle > toAngle ? 0 : 1;\n const counter = counterclockwise ? 0 : 1;\n addSegment(\n profile,\n new ArcSegment(from, size, 0, 0, small ^ counter ^ flip, to),\n );\n}\n","import {\n BBox,\n DEG2RAD,\n Matrix2D,\n Vector2,\n lazy,\n transformVector,\n} from '@twick/core';\nimport {View2D} from '../components/View2D';\nimport type {CurvePoint} from './CurvePoint';\nimport {Segment} from './Segment';\n\nexport class ArcSegment extends Segment {\n @lazy(() => {\n const root = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n const el = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n root.appendChild(el);\n View2D.shadowRoot.appendChild(root);\n return el;\n })\n private static el: SVGPathElement;\n public readonly center: Vector2;\n // angle in radian\n public readonly startAngle: number;\n public readonly deltaAngle: number;\n public readonly xAxisRotation: number;\n private xAxisRotationMatrix: DOMMatrix;\n public override readonly points: Vector2[];\n private length: number;\n\n public constructor(\n public readonly startPoint: Vector2,\n public readonly radius: Vector2,\n public readonly xAxisRotationDegree: number,\n public readonly largeArcFlag: number,\n public readonly sweepFlag: number,\n public readonly endPoint: Vector2,\n ) {\n super();\n\n this.xAxisRotation = this.xAxisRotationDegree * DEG2RAD;\n this.radius = new Vector2(Math.abs(radius.x), Math.abs(radius.y));\n\n const rotationMatrix =\n Matrix2D.fromRotation(-xAxisRotationDegree).domMatrix;\n const pAccent = transformVector(\n startPoint.sub(endPoint).div(2),\n rotationMatrix,\n );\n\n const L =\n (pAccent.x * pAccent.x) / (radius.x * radius.x) +\n (pAccent.y * pAccent.y) / (radius.y * radius.y);\n\n if (L > 1) {\n const Lsqrt = Math.sqrt(L);\n radius.x = Lsqrt * radius.x;\n radius.y = Lsqrt * radius.y;\n }\n\n const cAccent = new Vector2(\n radius.ctg * pAccent.y,\n radius.perpendicular.ctg * pAccent.x,\n ).scale(\n Math.sqrt(\n 1 /\n ((pAccent.x * pAccent.x) / (radius.x * radius.x) +\n (pAccent.y * pAccent.y) / (radius.y * radius.y)) -\n 1,\n ) * (largeArcFlag === sweepFlag ? -1 : 1),\n );\n\n this.xAxisRotationMatrix =\n Matrix2D.fromRotation(xAxisRotationDegree).domMatrix;\n const rotatedCAccent = transformVector(cAccent, this.xAxisRotationMatrix);\n this.center = rotatedCAccent.add(startPoint.add(endPoint).div(2));\n\n const q = pAccent.sub(cAccent).div(radius);\n const s = pAccent.scale(-1).sub(cAccent).div(radius);\n this.startAngle = q.radians;\n this.deltaAngle = Vector2.angleBetween(q, s) % (Math.PI * 2);\n if (this.sweepFlag === 0 && this.deltaAngle > 0) {\n this.deltaAngle -= Math.PI * 2;\n }\n if (this.sweepFlag === 1 && this.deltaAngle < 0) {\n this.deltaAngle += Math.PI * 2;\n }\n\n ArcSegment.el.setAttribute(\n 'd',\n `M ${this.startPoint.x} ${this.startPoint.y} A ${this.radius.x} ${this.radius.y} ${this.xAxisRotationDegree} ${this.largeArcFlag} ${this.sweepFlag} ${this.endPoint.x} ${this.endPoint.y}`,\n );\n this.length = ArcSegment.el.getTotalLength();\n\n const bbox = new BBox(ArcSegment.el.getBBox());\n this.points = [bbox.topLeft, bbox.bottomRight];\n }\n\n public getAnglePosition(angle: number) {\n const rotatedVector = transformVector(\n this.radius.mul(Vector2.fromRadians(angle)),\n this.xAxisRotationMatrix,\n );\n return rotatedVector.add(this.center);\n }\n\n public getAngleDerivative(angle: number) {\n const derivative = new Vector2(\n -this.radius.x * Math.sin(angle),\n this.radius.y * Math.cos(angle),\n );\n return transformVector(derivative, this.xAxisRotationMatrix);\n }\n\n public draw(\n context: CanvasRenderingContext2D | Path2D,\n start: number,\n end: number,\n move: boolean,\n ): [CurvePoint, CurvePoint] {\n const startAngle = this.startAngle + this.deltaAngle * start;\n const endAngle = this.startAngle + this.deltaAngle * end;\n const startPos = this.getPoint(start);\n const endPos = this.getPoint(end);\n\n if (move) context.moveTo(startPos.position.x, startPos.position.y);\n\n context.ellipse(\n this.center.x,\n this.center.y,\n this.radius.x,\n this.radius.y,\n this.xAxisRotation,\n startAngle,\n endAngle,\n this.sweepFlag === 0,\n );\n\n return [startPos, endPos];\n }\n\n public getPoint(distance: number): CurvePoint {\n const angle = this.startAngle + distance * this.deltaAngle;\n const tangent = this.getAngleDerivative(angle).normalized;\n return {\n position:\n distance === 0\n ? this.startPoint\n : distance === 1\n ? this.endPoint\n : this.getAnglePosition(angle),\n tangent,\n normal: tangent.perpendicular,\n };\n }\n public get arcLength(): number {\n return this.length;\n }\n}\n","import type {SimpleSignal} from '@twick/core';\nimport {PlaybackState, lazy} from '@twick/core';\nimport {initial, signal} from '../decorators';\nimport {nodeName} from '../decorators/nodeName';\nimport {useScene2D} from '../scenes/useScene2D';\nimport type {Node} from './Node';\nimport type {RectProps} from './Rect';\nimport {Rect} from './Rect';\n\nexport interface View2DProps extends RectProps {\n assetHash: string;\n}\n\n@nodeName('View2D')\nexport class View2D extends Rect {\n // TODO: scope this to individual player\n @lazy(() => {\n const frameID = 'twick-2d-frame';\n let frame = document.querySelector<HTMLDivElement>(`#${frameID}`);\n if (!frame) {\n frame = document.createElement('div');\n frame.id = frameID;\n frame.style.position = 'absolute';\n frame.style.pointerEvents = 'none';\n frame.style.top = '0';\n frame.style.left = '0';\n frame.style.fontFeatureSettings = 'normal'; // TODO: find solution that fully isolates CSS\n frame.style.opacity = '0';\n frame.style.overflow = 'hidden';\n document.body.prepend(frame);\n }\n return frame.shadowRoot ?? frame.attachShadow({mode: 'open'});\n })\n public static shadowRoot: ShadowRoot;\n\n @initial(PlaybackState.Paused)\n @signal()\n public declare readonly playbackState: SimpleSignal<PlaybackState, this>;\n\n @initial(0)\n @signal()\n public declare readonly globalTime: SimpleSignal<number, this>;\n\n @initial(0)\n @signal()\n public declare readonly fps: SimpleSignal<number, this>;\n\n @signal()\n public declare readonly assetHash: SimpleSignal<string, this>;\n\n public constructor(props: View2DProps) {\n super({\n composite: true,\n fontFamily: 'Roboto',\n fontSize: 48,\n lineHeight: '120%',\n textWrap: false,\n fontStyle: 'normal',\n ...props,\n });\n this.view2D = this;\n\n View2D.shadowRoot.append(this.element);\n this.applyFlex();\n }\n\n public override dispose() {\n this.removeChildren();\n super.dispose();\n }\n\n public override async render(context: CanvasRenderingContext2D) {\n this.computedSize();\n this.computedPosition();\n await super.render(context);\n }\n\n /**\n * Find a node by its key.\n *\n * @param key - The key of the node.\n */\n public findKey<T extends Node = Node>(key: string): T | null {\n return (useScene2D().getNode(key) as T) ?? null;\n }\n\n protected override requestLayoutUpdate() {\n this.updateLayout();\n }\n\n protected override requestFontUpdate() {\n this.applyFont();\n }\n\n public override view(): View2D {\n return this;\n }\n}\n","import type {Vector2} from '@twick/core';\nimport {clamp} from '@twick/core';\nimport {CircleSegment} from './CircleSegment';\nimport type {CurveProfile} from './CurveProfile';\nimport {LineSegment} from './LineSegment';\n\nexport function getPolylineProfile(\n points: readonly Vector2[],\n radius: number,\n closed: boolean,\n): CurveProfile {\n const profile: CurveProfile = {\n arcLength: 0,\n segments: [],\n minSin: 1,\n };\n\n if (points.length === 0) {\n return profile;\n }\n\n if (closed) {\n const middle = points[0].add(points[points.length - 1]).scale(0.5);\n points = [middle, ...points, middle];\n }\n\n let last = points[0];\n for (let i = 2; i < points.length; i++) {\n const start = points[i - 2];\n const center = points[i - 1];\n const end = points[i];\n\n const centerToStart = start.sub(center);\n const centerToEnd = end.sub(center);\n const startVector = centerToStart.normalized.safe;\n const endVector = centerToEnd.normalized.safe;\n const angleBetween = Math.acos(clamp(-1, 1, startVector.dot(endVector)));\n const angleTan = Math.tan(angleBetween / 2);\n const angleSin = Math.sin(angleBetween / 2);\n\n const safeRadius = Math.min(\n radius,\n angleTan * centerToStart.magnitude * (i === 2 ? 1 : 0.5),\n angleTan * centerToEnd.magnitude * (i === points.length - 1 ? 1 : 0.5),\n );\n\n const circleOffsetDistance = angleSin === 0 ? 0 : safeRadius / angleSin;\n const pointOffsetDistance = angleTan === 0 ? 0 : safeRadius / angleTan;\n const circleDistance = startVector\n .add(endVector)\n .scale(1 / 2)\n .normalized.safe.scale(circleOffsetDistance)\n .add(center);\n\n const counter = startVector.perpendicular.dot(endVector) < 0;\n const line = new LineSegment(\n last,\n center.add(startVector.scale(pointOffsetDistance)),\n );\n const circle = new CircleSegment(\n circleDistance,\n safeRadius,\n startVector.perpendicular.scale(counter ? 1 : -1),\n endVector.perpendicular.scale(counter ? -1 : 1),\n counter,\n );\n\n if (line.arcLength > 0) {\n profile.segments.push(line);\n profile.arcLength += line.arcLength;\n }\n if (circle.arcLength > 0) {\n profile.segments.push(circle);\n profile.arcLength += circle.arcLength;\n }\n\n profile.minSin = Math.min(profile.minSin, Math.abs(angleSin));\n\n last = center.add(endVector.scale(pointOffsetDistance));\n }\n\n const line = new LineSegment(last, points[points.length - 1]);\n if (line.arcLength > 0) {\n profile.segments.push(line);\n profile.arcLength += line.arcLength;\n }\n\n return profile;\n}\n","import type {\n SerializedVector2,\n Signal,\n SignalValue,\n SimpleSignal,\n ThreadGenerator,\n TimingFunction,\n Vector2,\n} from '@twick/core';\nimport {\n BBox,\n createSignal,\n experimentalLog,\n map,\n unwrap,\n useLogger,\n useScene,\n} from '@twick/core';\nimport type {\n CodeFragmentDrawingInfo,\n CodeHighlighter,\n CodePoint,\n CodeRange,\n CodeSelection,\n CodeSignal,\n PossibleCodeScope,\n PossibleCodeSelection,\n} from '../code';\nimport {\n CodeCursor,\n codeSignal,\n CodeSignalContext,\n findAllCodeRanges,\n isPointInCodeSelection,\n lines,\n parseCodeSelection,\n resolveScope,\n} from '../code';\nimport {computed, initial, nodeName, parser, signal} from '../decorators';\nimport type {DesiredLength} from '../partials';\nimport type {ShapeProps} from './Shape';\nimport {Shape} from './Shape';\n\nexport interface DrawTokenHook {\n (\n ctx: CanvasRenderingContext2D,\n text: string,\n position: Vector2,\n color: string,\n selection: number,\n ): void;\n}\n\n/**\n * Describes custom drawing logic used by the Code node.\n */\nexport interface DrawHooks {\n /**\n * Custom drawing logic for individual code tokens.\n *\n * @example\n * ```ts\n * token(ctx, text, position, color, selection) {\n * const blur = map(3, 0, selection);\n * const alpha = map(0.5, 1, selection);\n * ctx.globalAlpha *= alpha;\n * ctx.filter = `blur(${blur}px)`;\n * ctx.fillStyle = color;\n * ctx.fillText(text, position.x, position.y);\n * }\n * ```\n */\n token: DrawTokenHook;\n}\n\nexport interface CodeProps extends ShapeProps {\n /**\n * {@inheritDoc Code.highlighter}\n */\n highlighter?: SignalValue<CodeHighlighter | null>;\n /**\n * {@inheritDoc Code.code}\n */\n code?: SignalValue<PossibleCodeScope>;\n /**\n * {@inheritDoc Code.selection}\n */\n selection?: SignalValue<PossibleCodeSelection>;\n /**\n * {@inheritDoc Code.drawHooks}\n */\n drawHooks?: SignalValue<DrawHooks>;\n}\n\n/**\n * A node for displaying and animating code.\n *\n * @experimental\n *\n * @preview\n * ```tsx editor\n * import {parser} from '@lezer/javascript';\n * import {Code, LezerHighlighter, makeScene2D} from '@twick/2d';\n * import {createRef} from '@twick/core';\n *\n * export default makeScene2D(function* (view) {\n * LezerHighlighter.registerParser(parser);\n * const code = createRef<Code>();\n *\n * view.add(\n * <Code\n * ref={code}\n * offset={-1}\n * position={view.size().scale(-0.5).add(60)}\n * fontFamily={'JetBrains Mono, monospace'}\n * fontSize={36}\n * code={`\\\n * function hello() {\n * console.log('Hello');\n * }`}\n * />,\n * );\n *\n * yield* code()\n * .code(\n * `\\\n * function hello() {\n * console.warn('Hello World');\n * }`,\n * 1,\n * )\n * .wait(0.5)\n * .back(1)\n * .wait(0.5);\n * });\n * ```\n */\n@nodeName('CodeBlock')\nexport class Code extends Shape {\n /**\n * Create a standalone code signal.\n *\n * @param initial - The initial code.\n * @param highlighter - Custom highlighter to use.\n */\n public static createSignal(\n initial: PossibleCodeScope,\n highlighter?: SignalValue<CodeHighlighter>,\n ): CodeSignal<void> {\n return new CodeSignalContext<void>(\n initial,\n undefined,\n highlighter,\n ).toSignal();\n }\n\n public static defaultHighlighter: CodeHighlighter | null = null;\n /**\n * The code highlighter to use for this code node.\n *\n * @remarks\n * Defaults to a shared {@link code.LezerHighlighter}.\n */\n @initial(() => Code.defaultHighlighter)\n @signal()\n public declare readonly highlighter: SimpleSignal<\n CodeHighlighter | null,\n this\n >;\n\n /**\n * The code to display.\n */\n @codeSignal()\n public declare readonly code: CodeSignal<this>;\n\n /**\n * Custom drawing logic for the code.\n *\n * @remarks\n * Check out {@link DrawHooks} for available render hooks.\n *\n * @example\n * Make the unselected code blurry and transparent:\n * ```tsx\n * <Code\n * drawHooks={{\n * token(ctx, text, position, color, selection) {\n * const blur = map(3, 0, selection);\n * const alpha = map(0.5, 1, selection);\n * ctx.globalAlpha *= alpha;\n * ctx.filter = `blur(${blur}px)`;\n * ctx.fillStyle = color;\n * ctx.fillText(text, position.x, position.y);\n * },\n * }}\n * // ...\n * />\n * ```\n */\n @initial<DrawHooks>({\n token(ctx, text, position, color, selection) {\n ctx.fillStyle = color;\n ctx.globalAlpha *= map(0.2, 1, selection);\n ctx.fillText(text, position.x, position.y);\n },\n })\n @signal()\n public declare readonly drawHooks: SimpleSignal<DrawHooks, this>;\n\n protected setDrawHooks(value: DrawHooks) {\n if (\n !useScene().experimentalFeatures &&\n value !== this.drawHooks.context.getInitial()\n ) {\n useLogger().log({\n ...experimentalLog(`Code uses experimental draw hooks.`),\n inspect: this.key,\n });\n } else {\n this.drawHooks.context.setter(value);\n }\n }\n\n /**\n * The currently selected code range.\n *\n * @remarks\n * Either a single {@link code.CodeRange} or an array of them\n * describing which parts of the code should be visually emphasized.\n *\n * You can use {@link code.word} and\n * {@link code.lines} to quickly create ranges.\n *\n * @example\n * The following will select the word \"console\" in the code.\n * Both lines and columns are 0-based. So it will select a 7-character-long\n * (`7`) word in the second line (`1`) starting at the third character (`2`).\n * ```tsx\n * <Code\n * selection={word(1, 2, 7)}\n * code={`\\\n * function hello() => {\n * console.log('Hello');\n * }`}\n * // ...\n * />\n * ```\n */\n @initial(lines(0, Infinity))\n @parser(parseCodeSelection)\n @signal()\n public declare readonly selection: Signal<\n PossibleCodeSelection,\n CodeSelection,\n this\n >;\n public oldSelection: CodeSelection | null = null;\n public selectionProgress = createSignal<number | null>(null);\n protected *tweenSelection(\n value: CodeRange[],\n duration: number,\n timingFunction: TimingFunction,\n ): ThreadGenerator {\n this.oldSelection = this.selection();\n this.selection(value);\n this.selectionProgress(0);\n yield* this.selectionProgress(1, duration, timingFunction);\n this.selectionProgress(null);\n this.oldSelection = null;\n }\n\n /**\n * Get the currently displayed code as a string.\n */\n @computed()\n public parsed(): string {\n return resolveScope(this.code(), scope => unwrap(scope.progress) > 0.5);\n }\n\n @computed()\n public highlighterCache() {\n const highlighter = this.highlighter();\n if (!highlighter || !highlighter.initialize()) return null;\n const code = this.code();\n const before = resolveScope(code, false);\n const after = resolveScope(code, true);\n\n return {\n before: highlighter.prepare(before),\n after: highlighter.prepare(after),\n };\n }\n\n private cursorCache: CodeCursor | undefined;\n private get cursor() {\n this.cursorCache ??= new CodeCursor(this);\n return this.cursorCache;\n }\n\n public constructor(props: CodeProps) {\n super({\n fontFamily: 'monospace',\n ...props,\n });\n }\n\n /**\n * Create a child code signal.\n *\n * @param initial - The initial code.\n */\n public createSignal(initial: PossibleCodeScope): CodeSignal<this> {\n return new CodeSignalContext<this>(\n initial,\n this,\n this.highlighter,\n ).toSignal();\n }\n\n /**\n * Find all code ranges that match the given pattern.\n *\n * @param pattern - Either a string or a regular expression to match.\n */\n public findAllRanges(pattern: string | RegExp): CodeRange[] {\n return findAllCodeRanges(this.parsed(), pattern);\n }\n\n /**\n * Find the first code range that matches the given pattern.\n *\n * @param pattern - Either a string or a regular expression to match.\n */\n public findFirstRange(pattern: string | RegExp): CodeRange {\n return (\n findAllCodeRanges(this.parsed(), pattern, 1)[0] ?? [\n [0, 0],\n [0, 0],\n ]\n );\n }\n\n /**\n * Find the last code range that matches the given pattern.\n *\n * @param pattern - Either a string or a regular expression to match.\n */\n public findLastRange(pattern: string | RegExp): CodeRange {\n return (\n findAllCodeRanges(this.parsed(), pattern).at(-1) ?? [\n [0, 0],\n [0, 0],\n ]\n );\n }\n\n /**\n * Return the bounding box of the given point (character) in the code.\n *\n * @remarks\n * The returned bound box is in local space of the `Code` node.\n *\n * @param point - The point to get the bounding box for.\n */\n public getPointBbox(point: CodePoint): BBox {\n const [line, column] = point;\n const drawingInfo = this.drawingInfo();\n let match: CodeFragmentDrawingInfo | undefined;\n for (const info of drawingInfo.fragments) {\n if (info.cursor.y < line) {\n match = info;\n continue;\n }\n\n if (info.cursor.y === line && info.cursor.x < column) {\n match = info;\n continue;\n }\n\n break;\n }\n\n if (!match) return new BBox();\n\n const size = this.computedSize();\n return new BBox(\n match.position\n .sub(size.scale(0.5))\n .addX(match.characterSize.x * (column - match.cursor.x)),\n match.characterSize,\n );\n }\n\n /**\n * Return bounding boxes of all characters in the selection.\n *\n * @remarks\n * The returned bound boxes are in local space of the `Code` node.\n * Each line of code has a separate bounding box.\n *\n * @param selection - The selection to get the bounding boxes for.\n */\n public getSelectionBbox(selection: PossibleCodeSelection): BBox[] {\n const size = this.computedSize();\n const range = parseCodeSelection(selection);\n const drawingInfo = this.drawingInfo();\n const bboxes: BBox[] = [];\n\n let current: BBox | null = null;\n let line = 0;\n let column = 0;\n for (const info of drawingInfo.fragments) {\n if (info.cursor.y !== line) {\n line = info.cursor.y;\n if (current) {\n bboxes.push(current);\n current = null;\n }\n }\n\n column = info.cursor.x;\n for (let i = 0; i < info.text.length; i++) {\n if (isPointInCodeSelection([line, column], range)) {\n const bbox = new BBox(\n info.position\n .sub(size.scale(0.5))\n .addX(info.characterSize.x * (column - info.cursor.x)),\n info.characterSize,\n );\n if (!current) {\n current = bbox;\n } else {\n current = current.union(bbox);\n }\n } else if (current) {\n bboxes.push(current);\n current = null;\n }\n\n column++;\n }\n }\n\n if (current) {\n bboxes.push(current);\n }\n\n return bboxes;\n }\n\n @computed()\n protected drawingInfo() {\n this.requestFontUpdate();\n const context = this.cacheCanvas();\n const code = this.code();\n\n context.save();\n this.applyStyle(context);\n this.applyText(context);\n this.cursor.setupDraw(context);\n this.cursor.drawScope(code);\n const info = this.cursor.getDrawingInfo();\n context.restore();\n\n return info;\n }\n\n protected override desiredSize(): SerializedVector2<DesiredLength> {\n this.requestFontUpdate();\n const context = this.cacheCanvas();\n const code = this.code();\n\n context.save();\n this.applyStyle(context);\n this.applyText(context);\n this.cursor.setupMeasure(context);\n this.cursor.measureSize(code);\n const size = this.cursor.getSize();\n context.restore();\n\n return size;\n }\n\n protected override async draw(\n context: CanvasRenderingContext2D,\n ): Promise<void> {\n this.requestFontUpdate();\n this.applyStyle(context);\n this.applyText(context);\n const size = this.computedSize();\n const drawingInfo = this.drawingInfo();\n\n context.save();\n context.translate(\n -size.width / 2,\n -size.height / 2 + drawingInfo.verticalOffset,\n );\n\n const drawHooks = this.drawHooks();\n for (const info of drawingInfo.fragments) {\n context.save();\n context.globalAlpha *= info.alpha;\n drawHooks.token(context, info.text, info.position, info.fill, info.time);\n context.restore();\n }\n\n context.restore();\n\n await this.drawChildren(context);\n }\n\n protected override applyText(context: CanvasRenderingContext2D) {\n super.applyText(context);\n context.font = this.styles.font;\n context.textBaseline = 'top';\n if ('letterSpacing' in context) {\n context.letterSpacing = this.styles.letterSpacing;\n }\n }\n\n protected override collectAsyncResources(): void {\n super.collectAsyncResources();\n this.highlighter()?.initialize();\n }\n}\n","import type {PossibleVector2, SignalValue, Vector2Signal} from '@twick/core';\nimport {CubicBezierSegment} from '../curves';\nimport type {PolynomialSegment} from '../curves/PolynomialSegment';\nimport {computed, vector2Signal} from '../decorators';\nimport {bezierCurveTo, lineTo, moveTo} from '../utils';\nimport type {BezierOverlayInfo} from './Bezier';\nimport {Bezier} from './Bezier';\nimport type {CurveProps} from './Curve';\n\nexport interface CubicBezierProps extends CurveProps {\n p0?: SignalValue<PossibleVector2>;\n p0X?: SignalValue<number>;\n p0Y?: SignalValue<number>;\n\n p1?: SignalValue<PossibleVector2>;\n p1X?: SignalValue<number>;\n p1Y?: SignalValue<number>;\n\n p2?: SignalValue<PossibleVector2>;\n p2X?: SignalValue<number>;\n p2Y?: SignalValue<number>;\n\n p3?: SignalValue<PossibleVector2>;\n p3X?: SignalValue<number>;\n p3Y?: SignalValue<number>;\n}\n\n/**\n * A node for drawing a cubic Bézier curve.\n *\n * @preview\n * ```tsx editor\n * import {makeScene2D, CubicBezier} from '@twick/2d';\n * import {createRef} from '@twick/core';\n *\n * export default makeScene2D(function* (view) {\n * const bezier = createRef<CubicBezier>();\n *\n * view.add(\n * <CubicBezier\n * ref={bezier}\n * lineWidth={4}\n * stroke={'lightseagreen'}\n * p0={[-200, -100]}\n * p1={[100, -100]}\n * p2={[-100, 100]}\n * p3={[200, 100]}\n * end={0}\n * />\n * );\n *\n * yield* bezier().end(1, 1);\n * yield* bezier().start(1, 1).to(0, 1);\n * });\n * ```\n */\nexport class CubicBezier extends Bezier {\n /**\n * The start point of the Bézier curve.\n */\n @vector2Signal('p0')\n public declare readonly p0: Vector2Signal<this>;\n\n /**\n * The first control point of the Bézier curve.\n */\n @vector2Signal('p1')\n public declare readonly p1: Vector2Signal<this>;\n\n /**\n * The second control point of the Bézier curve.\n */\n @vector2Signal('p2')\n public declare readonly p2: Vector2Signal<this>;\n\n /**\n * The end point of the Bézier curve.\n */\n @vector2Signal('p3')\n public declare readonly p3: Vector2Signal<this>;\n\n public constructor(props: CubicBezierProps) {\n super(props);\n }\n\n @computed()\n protected segment(): PolynomialSegment {\n return new CubicBezierSegment(this.p0(), this.p1(), this.p2(), this.p3());\n }\n\n protected overlayInfo(matrix: DOMMatrix): BezierOverlayInfo {\n const [p0, p1, p2, p3] = this.segment().transformPoints(matrix);\n\n const curvePath = new Path2D();\n moveTo(curvePath, p0);\n bezierCurveTo(curvePath, p1, p2, p3);\n\n const handleLinesPath = new Path2D();\n moveTo(handleLinesPath, p0);\n lineTo(handleLinesPath, p1);\n moveTo(handleLinesPath, p2);\n lineTo(handleLinesPath, p3);\n\n return {\n curve: curvePath,\n startPoint: p0,\n endPoint: p3,\n controlPoints: [p1, p2],\n handleLines: handleLinesPath,\n };\n }\n}\n","import type {\n PossibleVector2,\n SignalValue,\n SimpleSignal,\n Vector2Signal,\n} from '@twick/core';\nimport {map} from '@twick/core';\nimport {initial, nodeName, signal, vector2Signal} from '../decorators';\nimport type {ShapeProps} from './Shape';\nimport {Shape} from './Shape';\n\nexport interface GridProps extends ShapeProps {\n /**\n * {@inheritDoc Grid.spacing}\n */\n spacing?: SignalValue<PossibleVector2>;\n /**\n * {@inheritDoc Grid.start}\n */\n start?: SignalValue<number>;\n /**\n * {@inheritDoc Grid.end}\n */\n end?: SignalValue<number>;\n}\n\n/**\n * A node for drawing a two-dimensional grid.\n *\n * @preview\n * ```tsx editor\n * import {Grid, makeScene2D} from '@twick/2d';\n * import {all, createRef} from '@twick/core';\n *\n * export default makeScene2D(function* (view) {\n * const grid = createRef<Grid>();\n *\n * view.add(\n * <Grid\n * ref={grid}\n * width={'100%'}\n * height={'100%'}\n * stroke={'#666'}\n * start={0}\n * end={1}\n * />,\n * );\n *\n * yield* all(\n * grid().end(0.5, 1).to(1, 1).wait(1),\n * grid().start(0.5, 1).to(0, 1).wait(1),\n * );\n * });\n * ```\n */\n@nodeName('Grid')\nexport class Grid extends Shape {\n /**\n * The spacing between the grid lines.\n */\n @initial(80)\n @vector2Signal('spacing')\n public declare readonly spacing: Vector2Signal<this>;\n\n /**\n * The percentage that should be clipped from the beginning of each grid line.\n *\n * @remarks\n * The portion of each grid line that comes before the given percentage will\n * be made invisible.\n *\n * This property is useful for animating the grid appearing on-screen.\n */\n @initial(0)\n @signal()\n public declare readonly start: SimpleSignal<number, this>;\n\n /**\n * The percentage that should be clipped from the end of each grid line.\n *\n * @remarks\n * The portion of each grid line that comes after the given percentage will\n * be made invisible.\n *\n * This property is useful for animating the grid appearing on-screen.\n */\n @initial(1)\n @signal()\n public declare readonly end: SimpleSignal<number, this>;\n\n public constructor(props: GridProps) {\n super(props);\n }\n\n protected override drawShape(context: CanvasRenderingContext2D) {\n context.save();\n this.applyStyle(context);\n this.drawRipple(context);\n\n const spacing = this.spacing();\n const size = this.computedSize().scale(0.5);\n const steps = size.div(spacing).floored;\n\n for (let x = -steps.x; x <= steps.x; x++) {\n const [from, to] = this.mapPoints(-size.height, size.height);\n\n context.beginPath();\n context.moveTo(spacing.x * x, from);\n context.lineTo(spacing.x * x, to);\n context.stroke();\n }\n\n for (let y = -steps.y; y <= steps.y; y++) {\n const [from, to] = this.mapPoints(-size.width, size.width);\n\n context.beginPath();\n context.moveTo(from, spacing.y * y);\n context.lineTo(to, spacing.y * y);\n context.stroke();\n }\n\n context.restore();\n }\n\n private mapPoints(start: number, end: number): [number, number] {\n let from = map(start, end, this.start());\n let to = map(start, end, this.end());\n\n if (to < from) {\n [from, to] = [to, from];\n }\n\n return [from, to];\n }\n}\n","import type {\n ColorSignal,\n PossibleColor,\n SignalValue,\n SimpleSignal,\n} from '@twick/core';\nimport {useLogger} from '@twick/core';\nimport {colorSignal, computed, initial, signal} from '../decorators';\nimport type {ImgProps} from './Img';\nimport {Img} from './Img';\n\nexport interface IconProps extends ImgProps {\n /**\n * {@inheritDoc Icon.icon}\n */\n icon: SignalValue<string>;\n\n /**\n * {@inheritDoc Icon.color}\n */\n color?: SignalValue<PossibleColor>;\n}\n\n/**\n * An Icon Component that provides easy access to over 150k icons.\n * See https://icones.js.org/collection/all for all available Icons.\n */\nexport class Icon extends Img {\n /**\n * The identifier of the icon.\n *\n * @remarks\n * You can find identifiers on [Icônes](https://icones.js.org).\n * They can look like this:\n * * `mdi:language-typescript`\n * * `ph:anchor-simple-bold`\n * * `ph:activity-bold`\n */\n @signal()\n public declare icon: SimpleSignal<string, this>;\n\n /**\n * The color of the icon\n *\n * @remarks\n * Provide the color in one of the following formats:\n * * named color like `red`, `darkgray`, …\n * * hexadecimal string with # like `#bada55`, `#141414`\n * Value can be either RGB or RGBA: `#bada55`, `#bada55aa` (latter is partially transparent)\n * The shorthand version (e.g. `#abc` for `#aabbcc` is also possible.)\n *\n * @defaultValue 'white'\n */\n @initial('white')\n @colorSignal()\n public declare color: ColorSignal<this>;\n\n public constructor(props: IconProps) {\n super({\n ...props,\n src: null,\n });\n }\n\n /**\n * Create the URL that will be used as the Image source\n * @returns Address to Iconify API for the requested Icon.\n */\n @computed()\n protected svgUrl(): string {\n const iconPathSegment = this.icon().replace(':', '/');\n const encodedColorValue = encodeURIComponent(this.color().hex());\n // Iconify API is documented here: https://docs.iconify.design/api/svg.html#color\n return `https://api.iconify.design/${iconPathSegment}.svg?color=${encodedColorValue}`;\n }\n\n /**\n * overrides `Image.src` getter\n */\n protected getSrc(): string {\n return this.svgUrl();\n }\n\n /**\n * overrides `Image.src` setter to warn the user that the value\n * is not used\n */\n protected setSrc(src: string | null) {\n if (src === null) {\n return;\n }\n useLogger().warn(\n \"The Icon Component does not accept setting the `src`. If you need access to `src`, use '<Img/>` instead.\",\n );\n }\n}\n","import type {\n PossibleVector2,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n} from '@twick/core';\nimport {\n BBox,\n Color,\n DependencyContext,\n DetailedError,\n Vector2,\n useLogger,\n} from '@twick/core';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport type {DesiredLength} from '../partials';\nimport {drawImage} from '../utils';\nimport type {RectProps} from './Rect';\nimport {Rect} from './Rect';\n\nconst imageWithoutSource = `\nThe image won't be visible unless you specify a source:\n\n\\`\\`\\`tsx\nimport myImage from './example.png';\n// ...\n<Img src={myImage} />;\n\\`\\`\\`\n\nIf you did this intentionally, and don't want to see this warning, set the \\`src\\`\nproperty to \\`null\\`:\n\n\\`\\`\\`tsx\n<Img src={null} />\n\\`\\`\\`\n\n[Learn more](https://motioncanvas.io/docs/media#images) about working with\nimages.\n`;\n\nexport interface ImgProps extends RectProps {\n /**\n * {@inheritDoc Img.src}\n */\n src?: SignalValue<string | null>;\n /**\n * {@inheritDoc Img.alpha}\n */\n alpha?: SignalValue<number>;\n /**\n * {@inheritDoc Img.smoothing}\n */\n smoothing?: SignalValue<boolean>;\n}\n\n/**\n * A node for displaying images.\n *\n * @preview\n * ```tsx editor\n * import {Img} from '@twick/2d';\n * import {all, waitFor} from '@twick/core';\n * import {createRef} from '@twick/core';\n * import {makeScene2D} from '@twick/2d';\n *\n * export default makeScene2D(function* (view) {\n * const ref = createRef<Img>();\n * yield view.add(\n * <Img\n * ref={ref}\n * src=\"https://images.unsplash.com/photo-1679218407381-a6f1660d60e9\"\n * width={300}\n * radius={20}\n * />,\n * );\n *\n * // set the background using the color sampled from the image:\n * ref().fill(ref().getColorAtPoint(0));\n *\n * yield* all(\n * ref().size([100, 100], 1).to([300, null], 1),\n * ref().radius(50, 1).to(20, 1),\n * ref().alpha(0, 1).to(1, 1),\n * );\n * yield* waitFor(0.5);\n * });\n * ```\n */\n@nodeName('Img')\nexport class Img extends Rect {\n private static pool: Record<string, HTMLImageElement> = {};\n\n static {\n if (import.meta.hot) {\n import.meta.hot.on('twick:assets', ({urls}) => {\n for (const url of urls) {\n if (Img.pool[url]) {\n delete Img.pool[url];\n }\n }\n });\n }\n }\n\n /**\n * The source of this image.\n *\n * @example\n * Using a local image:\n * ```tsx\n * import image from './example.png';\n * // ...\n * view.add(<Img src={image} />)\n * ```\n * Loading an image from the internet:\n * ```tsx\n * view.add(<Img src=\"https://example.com/image.png\" />)\n * ```\n */\n @signal()\n public declare readonly src: SimpleSignal<string, this>;\n\n /**\n * The alpha value of this image.\n *\n * @remarks\n * Unlike opacity, the alpha value affects only the image itself, leaving the\n * fill, stroke, and children intact.\n */\n @initial(1)\n @signal()\n public declare readonly alpha: SimpleSignal<number, this>;\n\n /**\n * Whether the image should be smoothed.\n *\n * @remarks\n * When disabled, the image will be scaled using the nearest neighbor\n * interpolation with no smoothing. The resulting image will appear pixelated.\n *\n * @defaultValue true\n */\n @initial(true)\n @signal()\n public declare readonly smoothing: SimpleSignal<boolean, this>;\n\n public constructor(props: ImgProps) {\n super(props);\n if (!('src' in props)) {\n useLogger().warn({\n message: 'No source specified for the image',\n remarks: imageWithoutSource,\n inspect: this.key,\n });\n }\n }\n\n protected override desiredSize(): SerializedVector2<DesiredLength> {\n const custom = super.desiredSize();\n if (custom.x === null && custom.y === null) {\n const image = this.image();\n return {\n x: image.naturalWidth,\n y: image.naturalHeight,\n };\n }\n\n return custom;\n }\n\n @computed()\n protected image(): HTMLImageElement {\n const src = this.src();\n const url = new URL(src, window.location.origin);\n if (url.origin === window.location.origin) {\n const hash = this.view().assetHash();\n url.searchParams.set('asset-hash', hash);\n }\n\n let image = Img.pool[src];\n if (!image) {\n image = document.createElement('img');\n image.crossOrigin = 'anonymous';\n image.src = src;\n Img.pool[src] = image;\n }\n\n if (!image.complete) {\n DependencyContext.collectPromise(\n new Promise((resolve, reject) => {\n image.addEventListener('load', resolve);\n image.addEventListener('error', () =>\n // TODO: example for error handling inside DependencyContext (this shouldn't be UI specific)\n reject(\n new DetailedError({\n message: `Failed to load an image`,\n remarks: `\\\nThe <code>src</code> property was set to:\n<pre><code>${src}</code></pre>\nMake sure that source is correct and that the image exists.<br/>\n<a target='_blank' href='https://motioncanvas.io/docs/media#images'>Learn more</a>\nabout working with images.`,\n inspect: this.key,\n }),\n ),\n );\n }),\n );\n }\n\n return image;\n }\n\n @computed()\n protected imageCanvas(): CanvasRenderingContext2D {\n const canvas = document\n .createElement('canvas')\n .getContext('2d', {willReadFrequently: true});\n if (!canvas) {\n throw new Error('Could not create an image canvas');\n }\n\n return canvas;\n }\n\n @computed()\n protected filledImageCanvas() {\n const context = this.imageCanvas();\n const image = this.image();\n context.canvas.width = image.naturalWidth;\n context.canvas.height = image.naturalHeight;\n context.imageSmoothingEnabled = this.smoothing();\n context.drawImage(image, 0, 0);\n\n return context;\n }\n\n protected override async draw(context: CanvasRenderingContext2D) {\n this.drawShape(context);\n const alpha = this.alpha();\n if (alpha > 0) {\n const box = BBox.fromSizeCentered(this.computedSize());\n context.save();\n context.clip(this.getPath());\n if (alpha < 1) {\n context.globalAlpha *= alpha;\n }\n context.imageSmoothingEnabled = this.smoothing();\n drawImage(context, this.image(), box);\n context.restore();\n }\n\n if (this.clip()) {\n context.clip(this.getPath());\n }\n\n await this.drawChildren(context);\n }\n\n protected override applyFlex() {\n super.applyFlex();\n const image = this.image();\n this.element.style.aspectRatio = (\n this.ratio() ?? image.naturalWidth / image.naturalHeight\n ).toString();\n }\n\n /**\n * Get color of the image at the given position.\n *\n * @param position - The position in local space at which to sample the color.\n */\n public getColorAtPoint(position: PossibleVector2): Color {\n const size = this.computedSize();\n const naturalSize = this.naturalSize();\n\n const pixelPosition = new Vector2(position)\n .add(this.computedSize().scale(0.5))\n .mul(naturalSize.div(size).safe);\n\n return this.getPixelColor(pixelPosition);\n }\n\n /**\n * The natural size of this image.\n *\n * @remarks\n * The natural size is the size of the source image unaffected by the size\n * and scale properties.\n */\n @computed()\n public naturalSize() {\n const image = this.image();\n return new Vector2(image.naturalWidth, image.naturalHeight);\n }\n\n /**\n * Get color of the image at the given pixel.\n *\n * @param position - The pixel's position.\n */\n public getPixelColor(position: PossibleVector2): Color {\n const context = this.filledImageCanvas();\n const vector = new Vector2(position);\n const data = context.getImageData(vector.x, vector.y, 1, 1).data;\n\n return new Color({\n r: data[0],\n g: data[1],\n b: data[2],\n a: data[3] / 255,\n });\n }\n\n protected override collectAsyncResources() {\n super.collectAsyncResources();\n this.image();\n }\n}\n","import type {\n PossibleVector2,\n Signal,\n SignalValue,\n Vector2Signal,\n} from '@twick/core';\nimport {transformVectorAsPoint, Vector2} from '@twick/core';\nimport type {KnotInfo} from '../curves';\nimport {\n cloneable,\n compound,\n computed,\n initial,\n parser,\n signal,\n wrapper,\n} from '../decorators';\nimport type {NodeProps} from './Node';\nimport {Node} from './Node';\n\nexport interface KnotProps extends NodeProps {\n /**\n * {@inheritDoc Knot.startHandle}\n */\n startHandle?: SignalValue<PossibleVector2>;\n /**\n * {@inheritDoc Knot.endHandle}\n */\n endHandle?: SignalValue<PossibleVector2>;\n /**\n * {@inheritDoc Knot.auto}\n */\n auto?: SignalValue<PossibleKnotAuto>;\n startHandleAuto?: SignalValue<number>;\n endHandleAuto?: SignalValue<number>;\n}\n\nexport type KnotAuto = {startHandle: number; endHandle: number};\nexport type PossibleKnotAuto = KnotAuto | number | [number, number];\nexport type KnotAutoSignal<TOwner> = Signal<\n PossibleKnotAuto,\n KnotAuto,\n TOwner\n> & {\n endHandle: Signal<number, number, TOwner>;\n startHandle: Signal<number, number, TOwner>;\n};\n\n/**\n * A node representing a knot of a {@link Spline}.\n */\nexport class Knot extends Node {\n /**\n * The position of the knot's start handle. The position is provided relative\n * to the knot's position.\n *\n * @remarks\n * By default, the position of the start handle will be the mirrored position\n * of the {@link endHandle}.\n *\n * If neither an end handle nor a start handle is provided, the positions of\n * the handles gets calculated automatically to create smooth curve through\n * the knot. The smoothness of the resulting curve can be controlled via the\n * {@link Spline.smoothness} property.\n *\n * It is also possible to blend between a user-defined position and the\n * auto-calculated position by using the {@link auto} property.\n *\n * @defaultValue Mirrored position of the endHandle.\n */\n @wrapper(Vector2)\n @signal()\n public declare readonly startHandle: Vector2Signal<this>;\n\n /**\n * The position of the knot's end handle. The position is provided relative\n * to the knot's position.\n *\n * @remarks\n * By default, the position of the end handle will be the mirrored position\n * of the {@link startHandle}.\n *\n * If neither an end handle nor a start handle is provided, the positions of\n * the handles gets calculated automatically to create smooth curve through\n * the knot. The smoothness of the resulting curve can be controlled via the\n * {@link Spline.smoothness} property.\n *\n * It is also possible to blend between a user-defined position and the\n * auto-calculated position by using the {@link auto} property.\n *\n * @defaultValue Mirrored position of the startHandle.\n */\n @wrapper(Vector2)\n @signal()\n public declare readonly endHandle: Vector2Signal<this>;\n\n /**\n * How much to blend between the user-provided handles and the auto-calculated\n * handles.\n *\n * @remarks\n * This property has no effect if no explicit handles are provided for the\n * knot.\n *\n * @defaultValue 0\n */\n @cloneable(false)\n @initial(() => ({startHandle: 0, endHandle: 0}))\n @parser((value: PossibleKnotAuto) => {\n if (typeof value === 'object' && !Array.isArray(value)) {\n return value;\n }\n if (typeof value === 'number') {\n value = [value, value];\n }\n return {startHandle: value[0], endHandle: value[1]};\n })\n @compound({startHandle: 'startHandleAuto', endHandle: 'endHandleAuto'})\n public declare readonly auto: KnotAutoSignal<this>;\n public get startHandleAuto() {\n return this.auto.startHandle;\n }\n public get endHandleAuto() {\n return this.auto.endHandle;\n }\n\n public constructor(props: KnotProps) {\n super(\n props.startHandle === undefined && props.endHandle === undefined\n ? {auto: 1, ...props}\n : props,\n );\n }\n\n @computed()\n public points(): KnotInfo {\n const hasExplicitHandles =\n !this.startHandle.isInitial() || !this.endHandle.isInitial();\n const startHandle = hasExplicitHandles ? this.startHandle() : Vector2.zero;\n const endHandle = hasExplicitHandles ? this.endHandle() : Vector2.zero;\n\n return {\n position: this.position(),\n startHandle: transformVectorAsPoint(startHandle, this.localToParent()),\n endHandle: transformVectorAsPoint(endHandle, this.localToParent()),\n auto: {start: this.startHandleAuto(), end: this.endHandleAuto()},\n };\n }\n\n private getDefaultEndHandle() {\n return this.startHandle().flipped;\n }\n\n private getDefaultStartHandle() {\n return this.endHandle().flipped;\n }\n}\n","import type {SignalValue, SimpleSignal} from '@twick/core';\nimport {DependencyContext, useLogger} from '@twick/core';\nimport type {LiteAdaptor} from 'mathjax-full/js/adaptors/liteAdaptor';\nimport {liteAdaptor} from 'mathjax-full/js/adaptors/liteAdaptor';\nimport type {MathDocument} from 'mathjax-full/js/core/MathDocument';\nimport {RegisterHTMLHandler} from 'mathjax-full/js/handlers/html';\nimport {TeX} from 'mathjax-full/js/input/tex';\nimport {AllPackages} from 'mathjax-full/js/input/tex/AllPackages';\nimport {mathjax} from 'mathjax-full/js/mathjax';\nimport {SVG} from 'mathjax-full/js/output/svg';\nimport type {OptionList} from 'mathjax-full/js/util/Options';\nimport {initial, signal} from '../decorators';\nimport type {ImgProps} from './Img';\nimport {Img} from './Img';\n\nexport interface LatexProps extends ImgProps {\n tex?: SignalValue<string>;\n renderProps?: SignalValue<OptionList>;\n}\n\n/**\n * A node for rendering equations with LaTeX.\n *\n * @preview\n * ```tsx editor\n * import {Latex, makeScene2D} from '@twick/2d';\n *\n * export default makeScene2D(function* (view) {\n * view.add(\n * <Latex\n * // Note how this uses \\color to set the color.\n * tex=\"{\\color{white} ax^2+bx+c=0 \\implies x=\\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}}\"\n * width={600} // height and width can calculate based on each other\n * />,\n * );\n * });\n * ```\n */\nexport class Latex extends Img {\n private static svgContentsPool: Record<string, string> = {};\n private static mathJaxInitialized = false;\n private static adaptor: LiteAdaptor;\n private static jaxDocument: MathDocument<unknown, unknown, unknown>;\n\n private static initializeMathJax() {\n if (this.mathJaxInitialized) {\n return;\n }\n this.adaptor = liteAdaptor();\n RegisterHTMLHandler(this.adaptor);\n this.jaxDocument = mathjax.document('', {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n InputJax: new TeX({packages: AllPackages}),\n // eslint-disable-next-line @typescript-eslint/naming-convention\n OutputJax: new SVG({fontCache: 'local'}),\n });\n this.mathJaxInitialized = true;\n }\n\n private readonly imageElement = document.createElement('img');\n\n @initial({})\n @signal()\n public declare readonly options: SimpleSignal<OptionList, this>;\n\n @signal()\n public declare readonly tex: SimpleSignal<string, this>;\n\n public constructor(props: LatexProps) {\n super({...props, src: null});\n Latex.initializeMathJax();\n }\n\n protected override image(): HTMLImageElement {\n // Render props may change the look of the TeX, so we need to cache both\n // source and render props together.\n const src = `${this.tex()}::${JSON.stringify(this.options())}`;\n if (Latex.svgContentsPool[src]) {\n this.imageElement.src = Latex.svgContentsPool[src];\n if (!this.imageElement.complete) {\n DependencyContext.collectPromise(\n new Promise((resolve, reject) => {\n this.imageElement.addEventListener('load', resolve);\n this.imageElement.addEventListener('error', reject);\n }),\n );\n }\n return this.imageElement;\n }\n\n // Convert to TeX, look for any errors\n const tex = this.tex();\n const svg = Latex.adaptor.innerHTML(\n Latex.jaxDocument.convert(tex, this.options()) as any,\n );\n if (svg.includes('data-mjx-error')) {\n const errors = svg.match(/data-mjx-error=\"(.*?)\"/);\n if (errors && errors.length > 0) {\n useLogger().error(`Invalid MathJax: ${errors[1]}`);\n }\n }\n\n // Encode to raw base64 image format\n const text = `data:image/svg+xml;base64,${btoa(\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\\n${svg}`,\n )}`;\n Latex.svgContentsPool[src] = text;\n const image = document.createElement('img');\n image.src = text;\n image.src = text;\n if (!image.complete) {\n DependencyContext.collectPromise(\n new Promise((resolve, reject) => {\n image.addEventListener('load', resolve);\n image.addEventListener('error', reject);\n }),\n );\n }\n\n return image;\n }\n}\n","import type {\n PossibleVector2,\n SignalValue,\n SimpleSignal,\n ThreadGenerator,\n TimingFunction,\n} from '@twick/core';\nimport {\n BBox,\n createSignal,\n threadable,\n transformVectorAsPoint,\n tween,\n unwrap,\n useLogger,\n Vector2,\n} from '@twick/core';\nimport type {CurveProfile} from '../curves';\nimport {getPolylineProfile} from '../curves';\nimport {\n calculateLerpDistance,\n polygonLength,\n polygonPointsLerp,\n} from '../curves/createCurveProfileLerp';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport {arc, drawLine, drawPivot, lineTo, moveTo} from '../utils';\nimport type {CurveProps} from './Curve';\nimport {Curve} from './Curve';\nimport {Layout} from './Layout';\n\nconst lineWithoutPoints = `\nThe line won't be visible unless you specify at least two points:\n\n\\`\\`\\`tsx\n<Line\n stroke=\"#fff\"\n lineWidth={8}\n points={[\n [100, 0],\n [0, 0],\n [0, 100],\n ]}\n/>\n\\`\\`\\`\n\nAlternatively, you can define the points using the children:\n\n\\`\\`\\`tsx\n<Line stroke=\"#fff\" lineWidth={8}>\n <Node x={100} />\n <Node />\n <Node y={100} />\n</Line>\n\\`\\`\\`\n\nIf you did this intentionally, and want to disable this message, set the\n\\`points\\` property to \\`null\\`:\n\n\\`\\`\\`tsx\n<Line stroke=\"#fff\" lineWidth={8} points={null} />\n\\`\\`\\`\n`;\n\nexport interface LineProps extends CurveProps {\n /**\n * {@inheritDoc Line.radius}\n */\n radius?: SignalValue<number>;\n /**\n * {@inheritDoc Line.points}\n */\n points?: SignalValue<SignalValue<PossibleVector2>[]>;\n}\n\n/**\n * A node for drawing lines and polygons.\n *\n * @remarks\n * This node can be used to render any polygonal shape defined by a set of\n * points.\n *\n * @preview\n * ```tsx editor\n * // snippet Simple line\n * import {makeScene2D, Line} from '@twick/2d';\n *\n * export default makeScene2D(function* (view) {\n * view.add(\n * <Line\n * points={[\n * [150, 50],\n * [0, -50],\n * [-150, 50],\n * ]}\n * stroke={'lightseagreen'}\n * lineWidth={8}\n * radius={40}\n * startArrow\n * />,\n * );\n * });\n *\n * // snippet Polygon\n * import {makeScene2D, Line} from '@twick/2d';\n *\n * export default makeScene2D(function* (view) {\n * view.add(\n * <Line\n * points={[\n * [-200, 70],\n * [150, 70],\n * [100, -70],\n * [-100, -70],\n * ]}\n * fill={'lightseagreen'}\n * closed\n * />,\n * );\n * });\n *\n * // snippet Using signals\n * import {makeScene2D, Line} from '@twick/2d';\n * import {createSignal} from '@twick/core';\n *\n * export default makeScene2D(function* (view) {\n * const tip = createSignal(-150);\n * view.add(\n * <Line\n * points={[\n * [-150, 70],\n * [150, 70],\n * // this point is dynamically calculated based on the signal:\n * () => [tip(), -70],\n * ]}\n * stroke={'lightseagreen'}\n * lineWidth={8}\n * closed\n * />,\n * );\n *\n * yield* tip(150, 1).back(1);\n * });\n *\n * // snippet Tweening points\n * import {makeScene2D, Line} from '@twick/2d';\n * import {createRef} from '@twick/core';\n *\n * export default makeScene2D(function* (view) {\n * const line = createRef<Line>();\n * view.add(\n * <Line\n * ref={line}\n * points={[\n * [-150, 70],\n * [150, 70],\n * [0, -70],\n * ]}\n * stroke={'lightseagreen'}\n * lineWidth={8}\n * radius={20}\n * closed\n * />,\n * );\n *\n * yield* line()\n * .points(\n * [\n * [-150, 0],\n * [0, 100],\n * [150, 0],\n * [150, -70],\n * [-150, -70],\n * ],\n * 2,\n * )\n * .back(2);\n * });\n * ```\n */\n@nodeName('Line')\nexport class Line extends Curve {\n /**\n * Rotate the points to minimize the overall distance traveled when tweening.\n *\n * @param points - The points to rotate.\n * @param reference - The reference points to which the distance is measured.\n * @param closed - Whether the points form a closed polygon.\n */\n private static rotatePoints(\n points: Vector2[],\n reference: Vector2[],\n closed: boolean,\n ) {\n if (closed) {\n let minDistance = Infinity;\n let bestOffset = 0;\n for (let offset = 0; offset < points.length; offset += 1) {\n const distance = calculateLerpDistance(points, reference, offset);\n if (distance < minDistance) {\n minDistance = distance;\n bestOffset = offset;\n }\n }\n\n if (bestOffset) {\n const spliced = points.splice(0, bestOffset);\n points.splice(points.length, 0, ...spliced);\n }\n } else {\n const originalDistance = calculateLerpDistance(points, reference, 0);\n const reversedPoints = [...points].reverse();\n const reversedDistance = calculateLerpDistance(\n reversedPoints,\n reference,\n 0,\n );\n if (reversedDistance < originalDistance) {\n points.reverse();\n }\n }\n }\n\n /**\n * Distribute additional points along the polyline.\n *\n * @param points - The points of a polyline along which new points should be\n * distributed.\n * @param count - The number of points to add.\n */\n private static distributePoints(points: Vector2[], count: number) {\n if (points.length === 0) {\n for (let j = 0; j < count; j++) {\n points.push(Vector2.zero);\n }\n return;\n }\n\n if (points.length === 1) {\n const point = points[0];\n for (let j = 0; j < count; j++) {\n points.push(point);\n }\n return;\n }\n\n const desiredLength = points.length + count;\n const arcLength = polygonLength(points);\n let density = count / arcLength;\n\n let i = 0;\n while (points.length < desiredLength) {\n const pointsLeft = desiredLength - points.length;\n\n if (i + 1 >= points.length) {\n density = pointsLeft / arcLength;\n i = 0;\n continue;\n }\n\n const a = points[i];\n const b = points[i + 1];\n const length = a.sub(b).magnitude;\n const pointCount = Math.min(Math.round(length * density), pointsLeft) + 1;\n\n for (let j = 1; j < pointCount; j++) {\n points.splice(++i, 0, Vector2.lerp(a, b, j / pointCount));\n }\n\n i++;\n }\n }\n\n /**\n * The radius of the line's corners.\n */\n @initial(0)\n @signal()\n public declare readonly radius: SimpleSignal<number, this>;\n\n /**\n * The points of the line.\n *\n * @remarks\n * When set to `null`, the Line will use the positions of its children as\n * points.\n */\n @initial(null)\n @signal()\n public declare readonly points: SimpleSignal<\n SignalValue<PossibleVector2>[] | null,\n this\n >;\n\n @threadable()\n protected *tweenPoints(\n value: SignalValue<SignalValue<PossibleVector2>[] | null>,\n time: number,\n timingFunction: TimingFunction,\n ): ThreadGenerator {\n const fromPoints = [...this.parsedPoints()];\n const toPoints = this.parsePoints(unwrap(value));\n const closed = this.closed();\n\n const diff = fromPoints.length - toPoints.length;\n Line.distributePoints(diff < 0 ? fromPoints : toPoints, Math.abs(diff));\n Line.rotatePoints(toPoints, fromPoints, closed);\n\n this.tweenedPoints(fromPoints);\n yield* tween(\n time,\n value => {\n const progress = timingFunction(value);\n this.tweenedPoints(polygonPointsLerp(fromPoints, toPoints, progress));\n },\n () => {\n this.tweenedPoints(null);\n this.points(value);\n },\n );\n }\n\n private tweenedPoints = createSignal<Vector2[] | null>(null);\n\n public constructor(props: LineProps) {\n super(props);\n\n if (props.children === undefined && props.points === undefined) {\n useLogger().warn({\n message: 'No points specified for the line',\n remarks: lineWithoutPoints,\n inspect: this.key,\n });\n }\n }\n\n @computed()\n protected childrenBBox() {\n let points = this.tweenedPoints();\n if (!points) {\n const custom = this.points();\n points = custom\n ? custom.map(signal => new Vector2(unwrap(signal)))\n : this.children()\n .filter(child => !(child instanceof Layout) || child.isLayoutRoot())\n .map(child => child.position());\n }\n\n return BBox.fromPoints(...points);\n }\n\n @computed()\n public parsedPoints(): Vector2[] {\n return this.parsePoints(this.points());\n }\n\n @computed()\n public override profile(): CurveProfile {\n return getPolylineProfile(\n this.tweenedPoints() ?? this.parsedPoints(),\n this.radius(),\n this.closed(),\n );\n }\n\n protected override lineWidthCoefficient(): number {\n const radius = this.radius();\n const join = this.lineJoin();\n\n let coefficient = super.lineWidthCoefficient();\n\n if (radius === 0 && join === 'miter') {\n const {minSin} = this.profile();\n if (minSin > 0) {\n coefficient = Math.max(coefficient, 0.5 / minSin);\n }\n }\n\n return coefficient;\n }\n\n public override drawOverlay(\n context: CanvasRenderingContext2D,\n matrix: DOMMatrix,\n ) {\n const box = this.childrenBBox().transformCorners(matrix);\n const size = this.computedSize();\n const offsetVector = size.mul(this.offset()).scale(0.5);\n const offset = transformVectorAsPoint(offsetVector, matrix);\n\n context.fillStyle = 'white';\n context.strokeStyle = 'black';\n context.lineWidth = 1;\n\n const path = new Path2D();\n const pointsPreTransformation = this.tweenedPoints() ?? this.parsedPoints();\n const points = pointsPreTransformation.map(p =>\n transformVectorAsPoint(p, matrix),\n );\n if (points.length > 0) {\n moveTo(path, points[0]);\n for (const point of points) {\n lineTo(path, point);\n context.beginPath();\n arc(context, point, 4);\n context.closePath();\n context.fill();\n context.stroke();\n }\n }\n\n context.strokeStyle = 'white';\n context.stroke(path);\n\n context.beginPath();\n drawPivot(context, offset);\n context.stroke();\n\n context.beginPath();\n drawLine(context, box);\n context.closePath();\n context.stroke();\n }\n\n private parsePoints(points: SignalValue<PossibleVector2>[] | null) {\n return points\n ? points.map(signal => new Vector2(unwrap(signal)))\n : this.children().map(child => child.position());\n }\n}\n","import {Vector2} from '@twick/core';\nimport type {CurveProfile} from './CurveProfile';\nimport {LineSegment} from './LineSegment';\nimport {getPointAtDistance} from './getPointAtDistance';\nimport {getPolylineProfile} from './getPolylineProfile';\n\n// Based on kute.js svgMorph plugin\n\ninterface SubcurveProfile extends CurveProfile {\n closed: boolean;\n}\n\ninterface PolygonProfile {\n /**\n * If path closed, first point and last point must be equal\n */\n points: Vector2[];\n closed: boolean;\n}\n\n/**\n * Split segments of polygon until distance between adjacent point is less than or equal maxLength. This function mutate original points.\n * @param points - Polygon points\n * @param maxLength - max distance between two point\n */\n\nfunction bisect(points: Vector2[], maxLength: number) {\n for (let i = 0; i < points.length - 1; i++) {\n const a = points[i];\n let b = points[i + 1];\n while (a.sub(b).magnitude > maxLength) {\n b = Vector2.lerp(a, b, 0.5);\n points.splice(i + 1, 0, b);\n }\n }\n}\n\n/**\n * Convert curve which only contain LineSegment into polygon.\n * @param curve - curve to convert. curve must contain 1 subpath\n * @param maxLength - max distance between two point\n * @returns - null if curve contain segment other than LineSegment\n */\n\nfunction exactPolygonPoints(\n curve: SubcurveProfile,\n maxLength: number,\n): Vector2[] | null {\n const points: Vector2[] = [];\n\n let endPoint: Vector2 | null = null;\n for (const segment of curve.segments) {\n if (!(segment instanceof LineSegment)) return null;\n\n points.push(segment.from);\n\n endPoint = segment.to;\n }\n\n if (endPoint) points.push(endPoint);\n\n if (!Number.isNaN(maxLength) && maxLength > 0) {\n bisect(points, maxLength);\n }\n\n return points;\n}\n\n/**\n * Calculate area of polygon\n * @param points - polygon points\n * @returns - area of polygon\n */\n\nfunction polygonArea(points: Vector2[]) {\n return (\n points.reduce((area, a, i) => {\n const b = points[(i + 1) % points.length];\n return area + (a.y * b.x - a.x * b.y);\n }, 0) / 2\n );\n}\n\n/**\n * Convert curve into polygon by sampling curve profile\n * @param curve - curve to convert. curve must contain only 1 subpath\n * @param maxLength - max distance between point\n * @returns - always return polygon points\n */\n\nfunction approximatePolygonPoints(\n curve: SubcurveProfile,\n maxLength: number,\n): Vector2[] {\n const points: Vector2[] = [];\n\n let numPoints = 3;\n if (!Number.isNaN(maxLength) && maxLength > 0) {\n numPoints = Math.max(numPoints, Math.ceil(curve.arcLength / maxLength));\n }\n\n for (let i = 0; i < numPoints; i += 1) {\n const point = getPointAtDistance(\n curve,\n curve.arcLength * (i / (numPoints - 1)),\n );\n points.push(point.position);\n }\n\n if (polygonArea(points) > 0) points.reverse();\n\n return points;\n}\n\n/**\n * Split curve into subpaths\n * @param curve - curve to split\n * @returns - subpaths of curve\n */\n\nfunction splitCurve(curve: CurveProfile) {\n if (curve.segments.length === 0) return [];\n\n let current: SubcurveProfile = {\n arcLength: 0,\n minSin: 0,\n segments: [],\n closed: false,\n };\n\n let endPoint: Vector2 | null = null;\n\n const composite: SubcurveProfile[] = [current];\n\n for (const segment of curve.segments) {\n const start = segment.getPoint(0).position;\n\n if (endPoint && !start.equals(endPoint)) {\n current = {\n arcLength: 0,\n minSin: 0,\n segments: [],\n closed: false,\n };\n composite.push(current);\n }\n\n current.segments.push(segment);\n current.arcLength += segment.arcLength;\n endPoint = segment.getPoint(1).position;\n }\n\n for (const sub of composite) {\n sub.closed = sub.segments[0]\n .getPoint(0)\n .position.equals(\n sub.segments[sub.segments.length - 1].getPoint(1).position,\n );\n }\n\n return composite;\n}\n\n/**\n * Convert curve into polygon use best possible method\n * @param curve - curve to convert\n * @param maxLength - max distance between two point\n * @returns - polgon points\n */\n\nfunction subcurveToPolygon(\n curve: SubcurveProfile,\n maxLength: number,\n): PolygonProfile {\n const points =\n exactPolygonPoints(curve, maxLength) ||\n approximatePolygonPoints(curve, maxLength);\n return {\n points: [...points],\n closed: curve.closed,\n };\n}\n\n/**\n * Calculate polygon perimeter\n * @param points - polygon points\n * @returns - perimeter of polygon\n */\n\nexport function polygonLength(points: Vector2[]) {\n return points.reduce((length, point, i) => {\n if (i) return length + points[i - 1].sub(point).magnitude;\n return 0;\n }, 0);\n}\n\n/**s\n * Sample additional points for polygon to better match its pair. This will mutate original points.\n * @param points - polygon points\n * @param numPoints - number of points to be added\n */\n\nfunction addPoints(points: Vector2[], numPoints: number) {\n const desiredLength = points.length + numPoints;\n const step = polygonLength(points) / numPoints;\n\n let i = 0;\n let cursor = 0;\n let insertAt = step / 2;\n\n while (points.length < desiredLength) {\n const a = points[i];\n const b = points[(i + 1) % points.length];\n const length = a.sub(b).magnitude;\n\n if (insertAt <= cursor + length) {\n points.splice(\n i + 1,\n 0,\n length\n ? Vector2.lerp(a, b, (insertAt - cursor) / length)\n : new Vector2(a),\n );\n insertAt += step;\n } else {\n cursor += length;\n i += 1;\n }\n }\n}\n\n/**\n * Calculate total moving point distance when morphing between polygon points\n * @param points - first polygon points\n * @param reference - second polygon points\n * @param offset - offset for first polygon points\n * @returns\n */\n\nexport function calculateLerpDistance(\n points: Vector2[],\n reference: Vector2[],\n offset: number,\n) {\n const len = points.length;\n let sumOfSquares = 0;\n\n for (let i = 0; i < reference.length; i += 1) {\n const a = points[(offset + i) % len];\n const b = reference[i];\n sumOfSquares += a.sub(b).squaredMagnitude;\n }\n\n return sumOfSquares;\n}\n\n/**\n * Rotate polygon in order to minimize moving points.\n * @param polygon - polygon to be rotated\n * @param reference - polygon to be reference\n */\n\nfunction rotatePolygon(polygon: PolygonProfile, reference: PolygonProfile) {\n const {points, closed} = polygon;\n const len = points.length;\n\n if (!closed) {\n const originalDistance = calculateLerpDistance(points, reference.points, 0);\n const reversedPoints = [...points].reverse();\n const reversedDistance = calculateLerpDistance(\n reversedPoints,\n reference.points,\n 0,\n );\n if (reversedDistance < originalDistance) polygon.points = reversedPoints;\n } else {\n let minDistance = Infinity;\n let bestOffset = 0;\n const last = points.pop();\n\n // Closed polygon first point must equal last point\n // When we rotate polygon, first point is changed which mean last point also must changed\n // When we remove last point, calculateLerpDistance will assume last point is equal first point\n // Proof:\n // len = points.length = reference.length - 1\n // When i = 0:\n // (offset + i) % len = offset % len\n // When i = reference.length - 1 or i = len\n // (offset + i) % len = (offset + len) % len = offset % len\n\n for (let offset = 0; offset < len; offset += 1) {\n const distance = calculateLerpDistance(points, reference.points, offset);\n if (distance < minDistance) {\n minDistance = distance;\n bestOffset = offset;\n }\n }\n\n if (last) points.push(last);\n\n if (bestOffset) {\n points.pop();\n const spliced = points.splice(0, bestOffset);\n points.splice(points.length, 0, ...spliced);\n points.push(points[0]);\n }\n }\n}\n\n/**\n * Round polygon's points coordinate to a specified amount of decimal\n * @param points - polygon point to be rounded\n * @param round - amount of decimal\n * @returns - new polygon point\n */\n\nfunction roundPolygon(\n {points, ...rest}: PolygonProfile,\n round: number,\n): PolygonProfile {\n const pow = round >= 1 ? 10 ** round : 1;\n return {\n points: points.map(point => {\n const [x, y] = [point.x, point.y].map(n => Math.round(n * pow) / pow);\n return new Vector2(x, y);\n }),\n ...rest,\n };\n}\n\n/**\n * Create two polygon to tween between sub curve/path\n * @param from - source curve\n * @param to - targe curve\n * @param precision - desired distance between two point\n * @param round - amount of decimal when rounding\n * @returns two polygon ready to tween\n */\n\nfunction getSubcurveInterpolationPolygon(\n from: SubcurveProfile,\n to: SubcurveProfile,\n precision: number,\n round: number,\n) {\n const morphPrecision = precision;\n const fromRing = subcurveToPolygon(from, morphPrecision);\n const toRing = subcurveToPolygon(to, morphPrecision);\n\n const diff = fromRing.points.length - toRing.points.length;\n\n addPoints(fromRing.points, diff < 0 ? diff * -1 : 0);\n addPoints(toRing.points, diff > 0 ? diff : 0);\n\n if (!from.closed && to.closed) rotatePolygon(toRing, fromRing);\n else rotatePolygon(fromRing, toRing);\n\n return {\n from: roundPolygon(fromRing, round),\n to: roundPolygon(toRing, round),\n };\n}\n\n/**\n * Make two sub curve list have equal length\n * @param subcurves - List to add\n * @param reference - Reference list\n */\n\nfunction balanceSubcurves(\n subcurves: SubcurveProfile[],\n reference: SubcurveProfile[],\n) {\n for (let i = subcurves.length; i < reference.length; i++) {\n const point = reference[i].segments[0].getPoint(0).position;\n subcurves.push({\n arcLength: 0,\n closed: false,\n minSin: 0,\n segments: [new LineSegment(point, point)],\n });\n }\n}\n\n/**\n * Create two polygon to tween between curve\n * @param from - source curve\n * @param to - targe curve\n * @param precision - desired distance between two point\n * @param round - amount of decimal when rounding\n * @returns list that contain list of polygon before and after tween\n */\n\nfunction getInterpolationPolygon(\n from: CurveProfile,\n to: CurveProfile,\n precision: number,\n round: number,\n) {\n const fromSub = splitCurve(from);\n const toSub = splitCurve(to);\n\n if (fromSub.length < toSub.length) balanceSubcurves(fromSub, toSub);\n else balanceSubcurves(toSub, fromSub);\n\n return fromSub.map((sub, i) =>\n getSubcurveInterpolationPolygon(sub, toSub[i], precision, round),\n );\n}\n\n/**\n * Add curve into another curve\n * @param target - target curve\n * @param source - curve to add\n */\n\nfunction addCurveToCurve(target: CurveProfile, source: CurveProfile) {\n const {segments, arcLength, minSin} = source;\n target.segments.push(...segments);\n target.arcLength += arcLength;\n target.minSin = Math.min(target.minSin, minSin);\n}\n\n/**\n * Interpolate between two polygon points.\n * @param from - source polygon points\n * @param to - target polygon points\n * @param value - interpolation progress\n * @returns - new polygon points\n */\n\nexport function polygonPointsLerp(\n from: Vector2[],\n to: Vector2[],\n value: number,\n): Vector2[] {\n const points: Vector2[] = [];\n if (value === 0) return [...from];\n if (value === 1) return [...to];\n\n for (let i = 0; i < from.length; i++) {\n const a = from[i];\n const b = to[i];\n points.push(Vector2.lerp(a, b, value));\n }\n return points;\n}\n\n/**\n * Create interpolator to tween between two curve\n * @param a - source curve\n * @param b - target curve\n * @returns - curve interpolator\n */\n\nexport function createCurveProfileLerp(a: CurveProfile, b: CurveProfile) {\n const interpolations = getInterpolationPolygon(a, b, 5, 4);\n\n return (progress: number) => {\n const curve: CurveProfile = {\n segments: [],\n arcLength: 0,\n minSin: 1,\n };\n for (const {from, to} of interpolations) {\n const points = polygonPointsLerp(from.points, to.points, progress);\n addCurveToCurve(curve, getPolylineProfile(points, 0, false));\n }\n return curve;\n };\n}\n","import type {\n SignalValue,\n SimpleSignal,\n TimingFunction,\n Vector2,\n} from '@twick/core';\nimport {\n BBox,\n createSignal,\n isReactive,\n threadable,\n transformVectorAsPoint,\n tween,\n} from '@twick/core';\nimport type {CurveProfile} from '../curves';\nimport {createCurveProfileLerp} from '../curves/createCurveProfileLerp';\nimport {getPathProfile} from '../curves/getPathProfile';\nimport {computed, signal} from '../decorators';\nimport {drawLine, drawPivot} from '../utils';\nimport type {CurveProps} from './Curve';\nimport {Curve} from './Curve';\n\nexport interface PathProps extends CurveProps {\n data: SignalValue<string>;\n}\n\nexport class Path extends Curve {\n private currentProfile = createSignal<CurveProfile | null>(null);\n @signal()\n public declare readonly data: SimpleSignal<string, this>;\n\n public constructor(props: PathProps) {\n super(props);\n this.canHaveSubpath = true;\n }\n\n @computed()\n public override profile(): CurveProfile {\n return this.currentProfile() ?? getPathProfile(this.data());\n }\n\n protected override childrenBBox() {\n const points = this.profile().segments.flatMap(segment => segment.points);\n return BBox.fromPoints(...points);\n }\n\n protected override lineWidthCoefficient(): number {\n const join = this.lineJoin();\n\n let coefficient = super.lineWidthCoefficient();\n\n if (join === 'miter') {\n const {minSin} = this.profile();\n if (minSin > 0) {\n coefficient = Math.max(coefficient, 0.5 / minSin);\n }\n }\n\n return coefficient;\n }\n\n protected override processSubpath(\n path: Path2D,\n startPoint: Vector2 | null,\n endPoint: Vector2 | null,\n ): void {\n if (startPoint && endPoint && startPoint.equals(endPoint)) {\n path.closePath();\n }\n }\n\n @threadable()\n protected *tweenData(\n newPath: SignalValue<string>,\n time: number,\n timingFunction: TimingFunction,\n ) {\n const fromProfile = this.profile();\n const toProfile = getPathProfile(isReactive(newPath) ? newPath() : newPath);\n\n const interpolator = createCurveProfileLerp(fromProfile, toProfile);\n\n this.currentProfile(fromProfile);\n yield* tween(\n time,\n value => {\n const progress = timingFunction(value);\n this.currentProfile(interpolator(progress));\n },\n () => {\n this.currentProfile(null);\n this.data(newPath);\n },\n );\n }\n\n public override drawOverlay(\n context: CanvasRenderingContext2D,\n matrix: DOMMatrix,\n ): void {\n const box = this.childrenBBox().transformCorners(matrix);\n const size = this.computedSize();\n const offsetVector = size.mul(this.offset()).scale(0.5);\n const offset = transformVectorAsPoint(offsetVector, matrix);\n const segments = this.profile().segments;\n\n context.lineWidth = 1;\n context.strokeStyle = 'white';\n context.fillStyle = 'white';\n\n context.save();\n context.setTransform(matrix);\n let endPoint: Vector2 | null = null;\n let path = new Path2D();\n\n for (const segment of segments) {\n if (endPoint && !segment.getPoint(0).position.equals(endPoint)) {\n context.stroke(path);\n path = new Path2D();\n endPoint = null;\n }\n const [, end] = segment.draw(path, 0, 1, endPoint == null);\n endPoint = end.position;\n }\n context.stroke(path);\n context.restore();\n\n context.beginPath();\n drawPivot(context, offset);\n context.stroke();\n\n context.beginPath();\n drawLine(context, box);\n context.closePath();\n context.stroke();\n }\n}\n","import {Vector2, clamp} from '@twick/core';\nimport type {PathCommand} from 'parse-svg-path';\nimport parse from 'parse-svg-path';\nimport {ArcSegment} from './ArcSegment';\nimport {CubicBezierSegment} from './CubicBezierSegment';\nimport type {CurveProfile} from './CurveProfile';\nimport {LineSegment} from './LineSegment';\nimport {QuadBezierSegment} from './QuadBezierSegment';\nimport type {Segment} from './Segment';\n\nfunction addSegmentToProfile(profile: CurveProfile, segment: Segment) {\n profile.segments.push(segment);\n profile.arcLength += segment.arcLength;\n}\n\nfunction getArg(command: PathCommand, argumentIndex: number) {\n return command[argumentIndex + 1] as number;\n}\n\nfunction getVector2(command: PathCommand, argumentIndex: number) {\n return new Vector2(\n command[argumentIndex + 1] as number,\n command[argumentIndex + 2] as number,\n );\n}\n\nfunction getPoint(\n command: PathCommand,\n argumentIndex: number,\n isRelative: boolean,\n currentPoint: Vector2,\n) {\n const point = getVector2(command, argumentIndex);\n return isRelative ? currentPoint.add(point) : point;\n}\n\nfunction reflectControlPoint(control: Vector2, currentPoint: Vector2) {\n return currentPoint.add(currentPoint.sub(control));\n}\n\nfunction updateMinSin(profile: CurveProfile) {\n for (let i = 0; i < profile.segments.length; i++) {\n const segmentA = profile.segments[i];\n const segmentB = profile.segments[(i + 1) % profile.segments.length];\n\n // In cubic bezier this equal p2.sub(p3)\n const startVector = segmentA.getPoint(1).tangent.scale(-1);\n // In cubic bezier this equal p1.sub(p0)\n const endVector = segmentB.getPoint(0).tangent;\n const dot = startVector.dot(endVector);\n\n const angleBetween = Math.acos(clamp(-1, 1, dot));\n const angleSin = Math.sin(angleBetween / 2);\n\n profile.minSin = Math.min(profile.minSin, Math.abs(angleSin));\n }\n}\n\nexport function getPathProfile(data: string): CurveProfile {\n const profile: CurveProfile = {\n segments: [],\n arcLength: 0,\n minSin: 1,\n };\n\n const segments = parse(data);\n let currentPoint = new Vector2(0, 0);\n let firstPoint: Vector2 | null = null;\n\n for (const segment of segments) {\n const command = segment[0].toLowerCase();\n const isRelative = segment[0] === command;\n\n if (command === 'm') {\n currentPoint = getPoint(segment, 0, isRelative, currentPoint);\n firstPoint = currentPoint;\n } else if (command === 'l') {\n const nextPoint = getPoint(segment, 0, isRelative, currentPoint);\n addSegmentToProfile(profile, new LineSegment(currentPoint, nextPoint));\n currentPoint = nextPoint;\n } else if (command === 'h') {\n const x = getArg(segment, 0);\n const nextPoint = isRelative\n ? currentPoint.addX(x)\n : new Vector2(x, currentPoint.y);\n addSegmentToProfile(profile, new LineSegment(currentPoint, nextPoint));\n currentPoint = nextPoint;\n } else if (command === 'v') {\n const y = getArg(segment, 0);\n const nextPoint = isRelative\n ? currentPoint.addY(y)\n : new Vector2(currentPoint.x, y);\n addSegmentToProfile(profile, new LineSegment(currentPoint, nextPoint));\n currentPoint = nextPoint;\n } else if (command === 'q') {\n const controlPoint = getPoint(segment, 0, isRelative, currentPoint);\n const nextPoint = getPoint(segment, 2, isRelative, currentPoint);\n addSegmentToProfile(\n profile,\n new QuadBezierSegment(currentPoint, controlPoint, nextPoint),\n );\n currentPoint = nextPoint;\n } else if (command === 't') {\n const lastSegment = profile.segments.at(-1);\n const controlPoint =\n lastSegment instanceof QuadBezierSegment\n ? reflectControlPoint(lastSegment.p1, currentPoint)\n : currentPoint;\n\n const nextPoint = getPoint(segment, 0, isRelative, currentPoint);\n addSegmentToProfile(\n profile,\n new QuadBezierSegment(currentPoint, controlPoint, nextPoint),\n );\n currentPoint = nextPoint;\n } else if (command === 'c') {\n const startControlPoint = getPoint(segment, 0, isRelative, currentPoint);\n const endControlPoint = getPoint(segment, 2, isRelative, currentPoint);\n const nextPoint = getPoint(segment, 4, isRelative, currentPoint);\n addSegmentToProfile(\n profile,\n new CubicBezierSegment(\n currentPoint,\n startControlPoint,\n endControlPoint,\n nextPoint,\n ),\n );\n currentPoint = nextPoint;\n } else if (command === 's') {\n const lastSegment = profile.segments.at(-1);\n const startControlPoint =\n lastSegment instanceof CubicBezierSegment\n ? reflectControlPoint(lastSegment.p2, currentPoint)\n : currentPoint;\n\n const endControlPoint = getPoint(segment, 0, isRelative, currentPoint);\n const nextPoint = getPoint(segment, 2, isRelative, currentPoint);\n addSegmentToProfile(\n profile,\n new CubicBezierSegment(\n currentPoint,\n startControlPoint,\n endControlPoint,\n nextPoint,\n ),\n );\n currentPoint = nextPoint;\n } else if (command === 'a') {\n const radius = getVector2(segment, 0);\n const angle = getArg(segment, 2);\n const largeArcFlag = getArg(segment, 3);\n const sweepFlag = getArg(segment, 4);\n const nextPoint = getPoint(segment, 5, isRelative, currentPoint);\n addSegmentToProfile(\n profile,\n new ArcSegment(\n currentPoint,\n radius,\n angle,\n largeArcFlag,\n sweepFlag,\n nextPoint,\n ),\n );\n currentPoint = nextPoint;\n } else if (command === 'z') {\n if (!firstPoint) continue;\n if (currentPoint.equals(firstPoint)) continue;\n\n addSegmentToProfile(profile, new LineSegment(currentPoint, firstPoint));\n currentPoint = firstPoint;\n }\n }\n updateMinSin(profile);\n\n return profile;\n}\n","import type {SerializedVector2, SignalValue, SimpleSignal} from '@twick/core';\nimport {BBox, Vector2} from '@twick/core';\nimport type {CurveProfile} from '../curves';\nimport {getPolylineProfile} from '../curves';\nimport {computed, initial, signal} from '../decorators';\nimport type {DesiredLength} from '../partials';\nimport {drawPolygon} from '../utils';\nimport type {CurveProps} from './Curve';\nimport {Curve} from './Curve';\n\nexport interface PolygonProps extends CurveProps {\n /**\n * {@inheritDoc Polygon.sides}\n */\n sides?: SignalValue<number>;\n /**\n * {@inheritDoc Polygon.radius}\n */\n radius?: SignalValue<number>;\n}\n\n/**\n * A node for drawing regular polygons.\n *\n * @remarks\n * This node can be used to render shapes such as: triangle, pentagon,\n * hexagon and more.\n *\n * Note that the polygon is inscribed in a circle defined by the height\n * and width. If height and width are unequal, the polygon is inscribed\n * in the resulting ellipse.\n *\n * Since the polygon is inscribed in the circle, the actual displayed\n * height and width may differ somewhat from the bounding rectangle. This\n * will be particularly noticeable if the number of sides is low, e.g. for a\n * triangle.\n *\n * @preview\n * ```tsx editor\n * // snippet Polygon\n * import {makeScene2D, Polygon} from '@twick/2d';\n * import {createRef} from '@twick/core';\n *\n * export default makeScene2D(function* (view) {\n * const ref = createRef<Polygon>();\n * view.add(\n * <Polygon\n * ref={ref}\n * sides={6}\n * size={160}\n * fill={'lightseagreen'}\n * />\n * );\n *\n * yield* ref().sides(3, 2).to(6, 2);\n * });\n *\n * // snippet Pentagon outline\n * import {makeScene2D, Polygon} from '@twick/2d';\n *\n * export default makeScene2D(function* (view) {\n * view.add(\n * <Polygon\n * sides={5}\n * size={160}\n * radius={30}\n * stroke={'lightblue'}\n * lineWidth={8}\n * />\n * );\n * });\n * ```\n */\nexport class Polygon extends Curve {\n /**\n * The number of sides of the polygon.\n *\n * @remarks\n * For example, a value of 6 creates a hexagon.\n *\n * @example\n * ```tsx\n * <Polygon\n * size={320}\n * sides={7}\n * stroke={'#fff'}\n * lineWidth={8}\n * fill={'lightseagreen'}\n * />\n * ```\n */\n @initial(6)\n @signal()\n public declare readonly sides: SimpleSignal<number, this>;\n\n /**\n * The radius of the polygon's corners.\n *\n * @example\n * ```tsx\n * <Polygon\n * radius={30}\n * size={320}\n * sides={3}\n * stroke={'#fff'}\n * lineWidth={8}\n * />\n * ```\n */\n @initial(0)\n @signal()\n public declare readonly radius: SimpleSignal<number, this>;\n\n public constructor(props: PolygonProps) {\n super(props);\n }\n\n @computed()\n public override profile(): CurveProfile {\n const sides = this.sides();\n const radius = this.radius();\n\n const points = [];\n const size = this.computedSize().scale(0.5);\n for (let i = 0; i < sides; i++) {\n const theta = (i * 2 * Math.PI) / sides;\n const direction = Vector2.fromRadians(theta).perpendicular;\n points.push(direction.mul(size));\n }\n\n return getPolylineProfile(points, radius, true);\n }\n\n protected override desiredSize(): SerializedVector2<DesiredLength> {\n return {\n x: this.width.context.getter(),\n y: this.height.context.getter(),\n };\n }\n\n protected override offsetComputedLayout(box: BBox): BBox {\n return box;\n }\n\n protected override childrenBBox(): BBox {\n return BBox.fromSizeCentered(this.computedSize());\n }\n\n protected override requiresProfile(): boolean {\n return super.requiresProfile() || this.radius() > 0;\n }\n\n protected override getPath(): Path2D {\n if (this.requiresProfile()) {\n return this.curveDrawingInfo().path;\n }\n\n return this.createPath();\n }\n protected override getRipplePath(): Path2D {\n return this.createPath(this.rippleSize());\n }\n\n protected createPath(expand = 0) {\n const path = new Path2D();\n const sides = this.sides();\n const box = BBox.fromSizeCentered(this.size()).expand(expand);\n drawPolygon(path, box, sides);\n return path;\n }\n}\n","import type {PossibleVector2, SignalValue, Vector2Signal} from '@twick/core';\nimport {QuadBezierSegment} from '../curves';\nimport type {PolynomialSegment} from '../curves/PolynomialSegment';\nimport {computed, vector2Signal} from '../decorators';\nimport {lineTo, moveTo, quadraticCurveTo} from '../utils';\nimport type {BezierOverlayInfo} from './Bezier';\nimport {Bezier} from './Bezier';\nimport type {CurveProps} from './Curve';\n\nexport interface QuadBezierProps extends CurveProps {\n p0?: SignalValue<PossibleVector2>;\n p0X?: SignalValue<number>;\n p0Y?: SignalValue<number>;\n\n p1?: SignalValue<PossibleVector2>;\n p1X?: SignalValue<number>;\n p1Y?: SignalValue<number>;\n\n p2?: SignalValue<PossibleVector2>;\n p2X?: SignalValue<number>;\n p2Y?: SignalValue<number>;\n}\n\n/**\n * A node for drawing a quadratic Bézier curve.\n *\n * @preview\n * ```tsx editor\n * import {makeScene2D, QuadBezier} from '@twick/2d';\n * import {createRef} from '@twick/core';\n *\n * export default makeScene2D(function* (view) {\n * const bezier = createRef<QuadBezier>();\n *\n * view.add(\n * <QuadBezier\n * ref={bezier}\n * lineWidth={4}\n * stroke={'lightseagreen'}\n * p0={[-200, 0]}\n * p1={[0, -200]}\n * p2={[200, 0]}\n * end={0}\n * />\n * );\n *\n * yield* bezier().end(1, 1);\n * yield* bezier().start(1, 1).to(0, 1);\n * });\n * ```\n */\nexport class QuadBezier extends Bezier {\n /**\n * The start point of the Bézier curve.\n */\n @vector2Signal('p0')\n public declare readonly p0: Vector2Signal<this>;\n\n /**\n * The control point of the Bézier curve.\n */\n @vector2Signal('p1')\n public declare readonly p1: Vector2Signal<this>;\n\n /**\n * The end point of the Bézier curve.\n */\n @vector2Signal('p2')\n public declare readonly p2: Vector2Signal<this>;\n\n public constructor(props: QuadBezierProps) {\n super(props);\n }\n\n @computed()\n protected segment(): PolynomialSegment {\n return new QuadBezierSegment(this.p0(), this.p1(), this.p2());\n }\n\n protected overlayInfo(matrix: DOMMatrix): BezierOverlayInfo {\n const [p0, p1, p2] = this.segment().transformPoints(matrix);\n\n const curvePath = new Path2D();\n moveTo(curvePath, p0);\n quadraticCurveTo(curvePath, p1, p2);\n\n const handleLinesPath = new Path2D();\n moveTo(handleLinesPath, p0);\n lineTo(handleLinesPath, p1);\n lineTo(handleLinesPath, p2);\n\n return {\n curve: curvePath,\n startPoint: p0,\n endPoint: p2,\n controlPoints: [p1],\n handleLines: handleLinesPath,\n };\n }\n}\n","import type {PossibleVector2, SignalValue, Vector2Signal} from '@twick/core';\nimport {BBox, transformVectorAsPoint} from '@twick/core';\nimport type {CurveProfile} from '../curves';\nimport {LineSegment} from '../curves';\nimport {nodeName, vector2Signal} from '../decorators';\nimport {arc, drawLine, drawPivot} from '../utils';\nimport type {CurveProps} from './Curve';\nimport {Curve} from './Curve';\n\nexport interface RayProps extends CurveProps {\n /**\n * {@inheritDoc Ray.from}\n */\n from?: SignalValue<PossibleVector2>;\n fromX?: SignalValue<number>;\n fromY?: SignalValue<number>;\n\n /**\n * {@inheritDoc Ray.to}\n */\n to?: SignalValue<PossibleVector2>;\n toX?: SignalValue<number>;\n toY?: SignalValue<number>;\n}\n\n/**\n * A node for drawing an individual line segment.\n *\n * @preview\n * ```tsx editor\n * import {makeScene2D} from '@twick/2d';\n * import {Ray} from '@twick/2d';\n * import {createRef} from '@twick/core';\n *\n * export default makeScene2D(function* (view) {\n * const ray = createRef<Ray>();\n *\n * view.add(\n * <Ray\n * ref={ray}\n * lineWidth={8}\n * endArrow\n * stroke={'lightseagreen'}\n * fromX={-200}\n * toX={200}\n * />,\n * );\n *\n * yield* ray().start(1, 1);\n * yield* ray().start(0).end(0).start(1, 1);\n * });\n * ```\n */\n@nodeName('Ray')\nexport class Ray extends Curve {\n /**\n * The starting point of the ray.\n */\n @vector2Signal('from')\n public declare readonly from: Vector2Signal<this>;\n\n /**\n * The ending point of the ray.\n */\n @vector2Signal('to')\n public declare readonly to: Vector2Signal<this>;\n\n public constructor(props: RayProps) {\n super(props);\n }\n\n protected override childrenBBox() {\n return BBox.fromPoints(this.from(), this.to());\n }\n\n public override profile(): CurveProfile {\n const segment = new LineSegment(this.from(), this.to());\n\n return {\n arcLength: segment.arcLength,\n minSin: 1,\n segments: [segment],\n };\n }\n\n public override drawOverlay(\n context: CanvasRenderingContext2D,\n matrix: DOMMatrix,\n ) {\n const box = this.childrenBBox().transformCorners(matrix);\n const size = this.computedSize();\n const offsetVector = size.mul(this.offset()).scale(0.5);\n const offset = transformVectorAsPoint(offsetVector, matrix);\n const from = transformVectorAsPoint(this.from(), matrix);\n const to = transformVectorAsPoint(this.to(), matrix);\n\n context.fillStyle = 'white';\n context.strokeStyle = 'black';\n context.lineWidth = 1;\n\n context.beginPath();\n arc(context, from, 4);\n context.fill();\n context.stroke();\n\n context.beginPath();\n arc(context, to, 4);\n context.fill();\n context.stroke();\n\n context.strokeStyle = 'white';\n context.beginPath();\n drawLine(context, [from, to]);\n context.stroke();\n\n context.beginPath();\n drawPivot(context, offset);\n context.stroke();\n\n context.beginPath();\n drawLine(context, box);\n context.closePath();\n context.stroke();\n }\n}\n","import type {SignalValue, SimpleSignal} from '@twick/core';\nimport {BBox, useThread} from '@twick/core';\nimport type {\n Artboard,\n File,\n LinearAnimationInstance,\n Renderer,\n RiveCanvas,\n} from '@rive-app/canvas-advanced';\nimport RiveInitializer from '@rive-app/canvas-advanced';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport type {RectProps} from './Rect';\nimport {Rect} from './Rect';\n\nexport interface RiveProps extends RectProps {\n src?: SignalValue<string>;\n artboardId?: SignalValue<string | number>;\n animationId?: SignalValue<string | number>;\n}\n\ninterface RiveInstance {\n rive: RiveCanvas;\n renderer: Renderer;\n artboard: Artboard;\n animation: LinearAnimationInstance;\n canvas: HTMLCanvasElement;\n}\n\n@nodeName('Rive')\nexport class Rive extends Rect {\n @signal()\n public declare readonly src: SimpleSignal<string, this>;\n\n @initial(0)\n @signal()\n public declare readonly artboardId: SimpleSignal<number | string, this>;\n\n @initial(0)\n @signal()\n public declare readonly animationId: SimpleSignal<number | string, this>;\n\n @initial(0)\n @signal()\n protected declare readonly time: SimpleSignal<number, this>;\n\n protected currentTime: number = 0;\n protected lastTime: number = 0;\n\n public constructor(props: RiveProps) {\n super(props);\n\n const time = useThread().time;\n const start = time();\n this.time(() => time() - start);\n }\n\n @computed()\n private async rive(): Promise<RiveInstance> {\n const src = this.src();\n const rive = await RiveInitializer({\n locateFile: () => {\n return '/@rive-wasm';\n },\n });\n const canvas = document.createElement('canvas');\n canvas.width = this.width();\n canvas.height = this.height();\n\n const renderer = rive.makeRenderer(canvas);\n const bytes = await (await fetch(new Request(src))).arrayBuffer();\n const file = (await rive.load(new Uint8Array(bytes))) as File;\n\n const artboardId = this.artboardId();\n const artboard = this.getArtboard(artboardId, file);\n\n const animationId = this.animationId();\n const animation = this.getAnimation(animationId, artboard, rive);\n\n return {rive, renderer, artboard, animation, canvas};\n }\n\n protected override async draw(context: CanvasRenderingContext2D) {\n this.drawShape(context);\n\n this.currentTime = this.time();\n const timeToAdvance = this.currentTime - this.lastTime;\n this.lastTime = this.currentTime;\n\n const {rive, renderer, canvas, artboard, animation} = await this.rive();\n const box = BBox.fromSizeCentered(this.computedSize());\n\n const renderPromise = new Promise<void>(resolve => {\n function renderLoop() {\n renderer.clear();\n animation.advance(timeToAdvance);\n animation.apply(1);\n\n artboard.advance(timeToAdvance);\n\n renderer.save();\n renderer.align(\n rive.Fit.fill,\n rive.Alignment.center,\n {\n minX: 0,\n minY: 0,\n maxX: canvas.width,\n maxY: canvas.height,\n },\n artboard.bounds,\n );\n\n artboard.draw(renderer);\n renderer.restore();\n resolve();\n }\n\n rive.requestAnimationFrame(renderLoop);\n });\n\n await renderPromise;\n\n context.drawImage(canvas, box.x, box.y, box.width, box.height);\n if (this.clip()) {\n context.clip(this.getPath());\n }\n\n await this.drawChildren(context);\n }\n\n private getArtboard(artboardId: string | number, file: File): Artboard {\n if (typeof artboardId === 'string') {\n return file.artboardByName(artboardId);\n }\n if (typeof artboardId === 'number') {\n return file.artboardByIndex(artboardId);\n }\n return file.defaultArtboard();\n }\n\n private getAnimation(\n animationId: string | number,\n artboard: Artboard,\n rive: RiveCanvas,\n ): LinearAnimationInstance {\n let animation;\n if (typeof animationId === 'number') {\n animation = artboard.animationByIndex(animationId);\n } else if (typeof animationId === 'string') {\n animation = artboard.animationByName(animationId);\n } else {\n animation = artboard.animationByIndex(0);\n }\n return new rive.LinearAnimationInstance(animation, artboard);\n }\n}\n","import type {\n PossibleVector2,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n} from '@twick/core';\nimport {\n BBox,\n Vector2,\n transformVectorAsPoint,\n unwrap,\n useLogger,\n} from '@twick/core';\nimport type {CurveProfile, KnotInfo} from '../curves';\nimport {CubicBezierSegment, getBezierSplineProfile} from '../curves';\nimport type {PolynomialSegment} from '../curves/PolynomialSegment';\nimport {computed, initial, signal} from '../decorators';\nimport type {DesiredLength} from '../partials';\nimport {\n arc,\n bezierCurveTo,\n drawLine,\n drawPivot,\n lineTo,\n moveTo,\n quadraticCurveTo,\n} from '../utils';\nimport type {CurveProps} from './Curve';\nimport {Curve} from './Curve';\nimport {Knot} from './Knot';\nimport type {Node} from './Node';\n\nconst splineWithInsufficientKnots = `\nThe spline won't be visible unless you specify at least two knots:\n\n\\`\\`\\`tsx\n<Spline\n stroke=\"#fff\"\n lineWidth={8}\n points={[\n [100, 0],\n [0, 0],\n [0, 100],\n ]}\n/>\n\\`\\`\\`\n\nFor more control over the knot handles, you can alternatively provide the knots\nas children to the spline using the \\`Knot\\` component:\n\n\\`\\`\\`tsx\n<Spline stroke=\"#fff\" lineWidth={8}>\n <Knot x={100} endHandle={[-50, 0]} />\n <Knot />\n <Knot y={100} startHandle={[-100, 50]} />\n</Spline>\n\\`\\`\\`\n`;\n\nexport interface SplineProps extends CurveProps {\n /**\n * {@inheritDoc Spline.smoothness}\n */\n smoothness?: SignalValue<number>;\n\n /**\n * {@inheritDoc Spline.points}\n */\n points?: SignalValue<SignalValue<PossibleVector2[]>>;\n}\n\n/**\n * A node for drawing a smooth line through a number of points.\n *\n * @remarks\n * This node uses Bézier curves for drawing each segment of the spline.\n *\n * @example\n * Defining knots using the `points` property. This will automatically\n * calculate the handle positions for each knot do draw a smooth curve. You\n * can control the smoothness of the resulting curve via the\n * {@link Spline.smoothness} property:\n *\n * ```tsx\n * <Spline\n * lineWidth={4}\n * stroke={'white'}\n * smoothness={0.4}\n * points={[\n * [-400, 0],\n * [-200, -300],\n * [0, 0],\n * [200, -300],\n * [400, 0],\n * ]}\n * />\n * ```\n *\n * Defining knots with {@link Knot} nodes:\n *\n * ```tsx\n * <Spline lineWidth={4} stroke={'white'}>\n * <Knot position={[-400, 0]} />\n * <Knot position={[-200, -300]} />\n * <Knot\n * position={[0, 0]}\n * startHandle={[-100, 200]}\n * endHandle={[100, 200]}\n * />\n * <Knot position={[200, -300]} />\n * <Knot position={[400, 0]} />\n * </Spline>\n * ```\n */\nexport class Spline extends Curve {\n /**\n * The smoothness of the spline when using auto-calculated handles.\n *\n * @remarks\n * This property is only applied to knots that don't use explicit handles.\n *\n * @defaultValue 0.4\n */\n @initial(0.4)\n @signal()\n public declare readonly smoothness: SimpleSignal<number>;\n\n /**\n * The knots of the spline as an array of knots with auto-calculated handles.\n *\n * @remarks\n * You can control the smoothness of the resulting curve\n * via the {@link smoothness} property.\n */\n @initial(null)\n @signal()\n public declare readonly points: SimpleSignal<\n SignalValue<PossibleVector2>[] | null,\n this\n >;\n\n public constructor(props: SplineProps) {\n super(props);\n\n if (\n (props.children === undefined ||\n !Array.isArray(props.children) ||\n props.children.length < 2) &&\n (props.points === undefined || props.points.length < 2) &&\n props.spawner === undefined\n ) {\n useLogger().warn({\n message:\n 'Insufficient number of knots specified for spline. A spline needs at least two knots.',\n remarks: splineWithInsufficientKnots,\n inspect: this.key,\n });\n }\n }\n\n @computed()\n public override profile(): CurveProfile {\n return getBezierSplineProfile(\n this.knots(),\n this.closed(),\n this.smoothness(),\n );\n }\n\n @computed()\n public knots(): KnotInfo[] {\n const points = this.points();\n\n if (points) {\n return points.map(signal => {\n const point = new Vector2(unwrap(signal));\n\n return {\n position: point,\n startHandle: point,\n endHandle: point,\n auto: {start: 1, end: 1},\n };\n });\n }\n\n return this.children()\n .filter(this.isKnot)\n .map(knot => knot.points());\n }\n\n @computed()\n protected childrenBBox() {\n const points = (this.profile().segments as PolynomialSegment[]).flatMap(\n segment => segment.points,\n );\n return BBox.fromPoints(...points);\n }\n\n protected override lineWidthCoefficient(): number {\n const join = this.lineJoin();\n\n let coefficient = super.lineWidthCoefficient();\n\n if (join !== 'miter') {\n return coefficient;\n }\n\n const {minSin} = this.profile();\n if (minSin > 0) {\n coefficient = Math.max(coefficient, 0.5 / minSin);\n }\n\n return coefficient;\n }\n\n protected override desiredSize(): SerializedVector2<DesiredLength> {\n return this.getTightBBox().size;\n }\n\n protected override offsetComputedLayout(box: BBox): BBox {\n box.position = box.position.sub(this.getTightBBox().center);\n return box;\n }\n\n @computed()\n private getTightBBox(): BBox {\n const bounds = (this.profile().segments as PolynomialSegment[]).map(\n segment => segment.getBBox(),\n );\n return BBox.fromBBoxes(...bounds);\n }\n\n public override drawOverlay(\n context: CanvasRenderingContext2D,\n matrix: DOMMatrix,\n ) {\n const size = this.computedSize();\n const box = this.childrenBBox().transformCorners(matrix);\n const offsetVector = size.mul(this.offset()).scale(0.5);\n const offset = transformVectorAsPoint(offsetVector, matrix);\n const segments = this.profile().segments as PolynomialSegment[];\n\n context.lineWidth = 1;\n context.strokeStyle = 'white';\n context.fillStyle = 'white';\n\n const splinePath = new Path2D();\n\n // Draw the actual spline first so that all control points get drawn on top of it.\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const [from, startHandle, endHandle, to] =\n segment.transformPoints(matrix);\n\n moveTo(splinePath, from);\n if (segment instanceof CubicBezierSegment) {\n bezierCurveTo(splinePath, startHandle, endHandle, to as Vector2);\n } else {\n quadraticCurveTo(splinePath, startHandle, endHandle);\n }\n }\n context.stroke(splinePath);\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n context.fillStyle = 'white';\n\n const [from, startHandle, endHandle, to] =\n segment.transformPoints(matrix);\n\n const handlePath = new Path2D();\n\n context.globalAlpha = 0.5;\n // Line from p0 to p1\n moveTo(handlePath, from);\n lineTo(handlePath, startHandle);\n\n if (segment instanceof CubicBezierSegment) {\n // Line from p2 to p3\n moveTo(handlePath, endHandle);\n lineTo(handlePath, to as Vector2);\n context.beginPath();\n context.stroke(handlePath);\n } else {\n // Line from p1 to p2\n lineTo(handlePath, endHandle);\n context.beginPath();\n context.stroke(handlePath);\n }\n\n context.globalAlpha = 1;\n context.lineWidth = 2;\n\n // Draw first point of segment\n moveTo(context, from);\n context.beginPath();\n arc(context, from, 4);\n context.closePath();\n context.stroke();\n context.fill();\n\n // Draw final point of segment only if we're on the last segment.\n // Otherwise, it will get drawn as the start point of the next segment.\n if (i === segments.length - 1) {\n if (to !== undefined) {\n moveTo(context, to);\n context.beginPath();\n arc(context, to, 4);\n context.closePath();\n context.stroke();\n context.fill();\n }\n }\n\n // Draw the control points\n context.fillStyle = 'black';\n for (const point of [startHandle, endHandle]) {\n if (point.magnitude > 0) {\n moveTo(context, point);\n context.beginPath();\n arc(context, point, 4);\n context.closePath();\n context.fill();\n context.stroke();\n }\n }\n }\n\n context.lineWidth = 1;\n context.beginPath();\n drawPivot(context, offset);\n context.stroke();\n\n context.beginPath();\n drawLine(context, box);\n context.closePath();\n context.stroke();\n }\n\n private isKnot(node: Node): node is Knot {\n return node instanceof Knot;\n }\n}\n","import type {\n PossibleSpacing,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n ThreadGenerator,\n TimingFunction,\n} from '@twick/core';\nimport {\n BBox,\n Matrix2D,\n Vector2,\n all,\n clampRemap,\n delay,\n easeInOutSine,\n isReactive,\n lazy,\n threadable,\n tween,\n useLogger,\n} from '@twick/core';\nimport {computed, signal} from '../decorators';\nimport type {DesiredLength, PossibleCanvasStyle} from '../partials';\nimport {applyTransformDiff, getTransformDiff} from '../utils/diff';\nimport type {CircleProps} from './Circle';\nimport {Circle} from './Circle';\nimport type {ImgProps} from './Img';\nimport {Img} from './Img';\nimport {Layout} from './Layout';\nimport type {LineProps} from './Line';\nimport {Line} from './Line';\nimport type {NodeProps} from './Node';\nimport {Node} from './Node';\nimport type {PathProps} from './Path';\nimport {Path} from './Path';\nimport type {RectProps} from './Rect';\nimport {Rect} from './Rect';\nimport type {ShapeProps} from './Shape';\nimport {Shape} from './Shape';\nimport {View2D} from './View2D';\n\n/**\n * Represent SVG shape.\n * This only used single time because `node` may have reference to parent SVG renderer.\n */\nexport interface SVGShape {\n id: string;\n shape: Node;\n}\n\n/**\n * Data of SVGShape.\n * This can used many times because it do not reference parent SVG.\n * This must build into SVGShape\n */\nexport interface SVGShapeData {\n id: string;\n type: new (props: NodeProps) => Node;\n props: ShapeProps;\n children?: SVGShapeData[];\n}\n\n/**\n * Represent SVG document that contains SVG shapes.\n * This only used single time because `nodes` have reference to parent SVG renderer.\n */\nexport interface SVGDocument {\n size: Vector2;\n nodes: SVGShape[];\n}\n\n/**\n * Data of SVGDocument.\n * This can used many times because it do not reference parent SVG.\n * This must build into SVGDocument\n */\nexport interface SVGDocumentData {\n size: Vector2;\n nodes: SVGShapeData[];\n}\n\nexport interface SVGProps extends ShapeProps {\n svg: SignalValue<string>;\n}\n\n/**\nA Node for drawing and animating SVG images.\n\n@remarks\nIf you're not interested in animating SVG, you can use {@link Img} instead.\n */\nexport class SVG extends Shape {\n @lazy(() => {\n const element = document.createElement('div');\n View2D.shadowRoot.appendChild(element);\n return element;\n })\n protected static containerElement: HTMLDivElement;\n private static svgNodesPool: Record<string, SVGDocumentData> = {};\n\n /**\n * SVG string to be rendered\n */\n @signal()\n public declare readonly svg: SimpleSignal<string, this>;\n\n /**\n * Child to wrap all SVG node\n */\n public wrapper: Node;\n\n private lastTweenTargetSrc: string | null = null;\n private lastTweenTargetDocument: SVGDocument | null = null;\n\n public constructor(props: SVGProps) {\n super(props);\n this.wrapper = new Node({});\n this.wrapper.children(this.documentNodes);\n this.wrapper.scale(this.wrapperScale);\n this.add(this.wrapper);\n }\n\n /**\n * Get all SVG nodes with the given id.\n * @param id - An id to query.\n */\n public getChildrenById(id: string) {\n return this.document()\n .nodes.filter(node => node.id === id)\n .map(({shape}) => shape);\n }\n\n protected override desiredSize(): SerializedVector2<DesiredLength> {\n const docSize = this.document().size;\n const scale = this.calculateWrapperScale(\n docSize,\n super.desiredSize() as SerializedVector2<number | null>,\n );\n return docSize.mul(scale);\n }\n\n protected getCurrentSize() {\n return {\n x: this.width.isInitial() ? null : this.width(),\n y: this.height.isInitial() ? null : this.height(),\n };\n }\n\n protected calculateWrapperScale(\n documentSize: Vector2,\n parentSize: SerializedVector2<number | null>,\n ) {\n const result = new Vector2(1, 1);\n if (parentSize.x && parentSize.y) {\n result.x = parentSize.x / documentSize.width;\n result.y = parentSize.y / documentSize.height;\n } else if (parentSize.x && !parentSize.y) {\n result.x = parentSize.x / documentSize.width;\n result.y = result.x;\n } else if (!parentSize.x && parentSize.y) {\n result.y = parentSize.y / documentSize.height;\n result.x = result.y;\n }\n return result;\n }\n\n /**\n * Convert `SVGDocumentData` to `SVGDocument`.\n * @param data - `SVGDocumentData` to convert.\n */\n protected buildDocument(data: SVGDocumentData): SVGDocument {\n return {\n size: data.size,\n nodes: data.nodes.map(ch => this.buildShape(ch)),\n };\n }\n\n /**\n * Convert `SVGShapeData` to `SVGShape`.\n * @param data - `SVGShapeData` to convert.\n */\n protected buildShape({id, type, props, children}: SVGShapeData): SVGShape {\n return {\n id,\n shape: new type({\n children: children?.map(ch => this.buildShape(ch).shape),\n ...this.processElementStyle(props),\n }),\n };\n }\n\n /**\n * Convert an SVG string to `SVGDocument`.\n * @param svg - An SVG string to be parsed.\n */\n protected parseSVG(svg: string): SVGDocument {\n return this.buildDocument(SVG.parseSVGData(svg));\n }\n\n /**\n * Create a tweening list to tween between two SVG nodes.\n * @param from - The initial node,\n * @param to - The final node.\n * @param duration - The duration of the tween.\n * @param timing - The timing function.\n */\n protected *generateTransformer(\n from: Node,\n to: Node,\n duration: number,\n timing: TimingFunction,\n ): Generator<ThreadGenerator> {\n yield from.position(to.position(), duration, timing);\n yield from.scale(to.scale(), duration, timing);\n yield from.rotation(to.rotation(), duration, timing);\n if (\n from instanceof Path &&\n to instanceof Path &&\n from.data() !== to.data()\n ) {\n yield from.data(to.data(), duration, timing);\n }\n if (from instanceof Layout && to instanceof Layout) {\n yield from.size(to.size(), duration, timing);\n }\n if (from instanceof Shape && to instanceof Shape) {\n yield from.fill(to.fill(), duration, timing);\n yield from.stroke(to.stroke(), duration, timing);\n yield from.lineWidth(to.lineWidth(), duration, timing);\n }\n\n const fromChildren = from.children();\n const toChildren = to.children();\n for (let i = 0; i < fromChildren.length; i++) {\n yield* this.generateTransformer(\n fromChildren[i],\n toChildren[i],\n duration,\n timing,\n );\n }\n }\n\n @threadable()\n protected *tweenSvg(\n value: SignalValue<string>,\n time: number,\n timingFunction: TimingFunction,\n ) {\n const newValue = isReactive(value) ? value() : value;\n const newSVG = this.parseSVG(newValue);\n const currentSVG = this.document();\n const diff = getTransformDiff(currentSVG.nodes, newSVG.nodes);\n\n this.lastTweenTargetSrc = newValue;\n this.lastTweenTargetDocument = newSVG;\n\n applyTransformDiff(currentSVG.nodes, diff, ({shape, ...rest}) => ({\n ...rest,\n shape: shape.clone(),\n }));\n this.wrapper.children(currentSVG.nodes.map(shape => shape.shape));\n for (const item of currentSVG.nodes) {\n item.shape.parent(this.wrapper);\n }\n\n const beginning = 0.2;\n const ending = 0.8;\n const overlap = 0.15;\n\n const transformator: ThreadGenerator[] = [];\n const transformatorTime = (ending - beginning) * time;\n const transformatorDelay = beginning * time;\n\n for (const item of diff.transformed) {\n transformator.push(\n ...this.generateTransformer(\n item.from.current.shape,\n item.to.current.shape,\n transformatorTime,\n timingFunction,\n ),\n );\n }\n\n const autoWidth = this.width.isInitial();\n const autoHeight = this.height.isInitial();\n this.wrapper.scale(\n this.calculateWrapperScale(currentSVG.size, this.getCurrentSize()),\n );\n\n const baseTween = tween(\n time,\n value => {\n const progress = timingFunction(value);\n const remapped = clampRemap(beginning, ending, 0, 1, progress);\n\n const scale = this.wrapper.scale();\n if (autoWidth) {\n this.width(\n easeInOutSine(remapped, currentSVG.size.x, newSVG.size.x) * scale.x,\n );\n }\n\n if (autoHeight) {\n this.height(\n easeInOutSine(remapped, currentSVG.size.y, newSVG.size.y) * scale.y,\n );\n }\n\n const deletedOpacity = clampRemap(\n 0,\n beginning + overlap,\n 1,\n 0,\n progress,\n );\n for (const {current} of diff.deleted) {\n current.shape.opacity(deletedOpacity);\n }\n\n const insertedOpacity = clampRemap(ending - overlap, 1, 0, 1, progress);\n for (const {current} of diff.inserted) {\n current.shape.opacity(insertedOpacity);\n }\n },\n () => {\n this.wrapper.children(this.documentNodes);\n if (autoWidth) this.width.reset();\n if (autoHeight) this.height.reset();\n\n for (const {current} of diff.deleted) current.shape.dispose();\n for (const {from} of diff.transformed) {\n from.current.shape.dispose();\n }\n this.wrapper.scale(this.wrapperScale);\n },\n );\n yield* all(\n this.wrapper.scale(\n this.calculateWrapperScale(newSVG.size, this.getCurrentSize()),\n time,\n timingFunction,\n ),\n baseTween,\n delay(transformatorDelay, all(...transformator)),\n );\n }\n\n @computed()\n private wrapperScale(): Vector2 {\n return this.calculateWrapperScale(\n this.document().size,\n this.getCurrentSize(),\n );\n }\n\n /**\n * Get the current `SVGDocument`.\n */\n @computed()\n private document(): SVGDocument {\n try {\n const src = this.svg();\n if (this.lastTweenTargetDocument && src === this.lastTweenTargetSrc) {\n return this.lastTweenTargetDocument;\n }\n return this.parseSVG(src);\n } finally {\n this.lastTweenTargetSrc = null;\n this.lastTweenTargetDocument = null;\n }\n }\n\n /**\n * Get current document nodes.\n */\n @computed()\n private documentNodes() {\n return this.document().nodes.map(node => node.shape);\n }\n\n /**\n * Convert SVG colors in Shape properties to Motion Canvas colors.\n * @param param - Shape properties.\n * @returns Converted Shape properties.\n */\n private processElementStyle({fill, stroke, ...rest}: ShapeProps): ShapeProps {\n return {\n fill: fill === 'currentColor' ? this.fill : SVG.processSVGColor(fill),\n stroke:\n stroke === 'currentColor' ? this.stroke : SVG.processSVGColor(stroke),\n ...rest,\n };\n }\n\n /**\n * Parse an SVG string as `SVGDocumentData`.\n * @param svg - And SVG string to be parsed.\n * @returns `SVGDocumentData` that can be used to build SVGDocument.\n */\n protected static parseSVGData(svg: string) {\n const cached = SVG.svgNodesPool[svg];\n if (cached && (cached.size.x > 0 || cached.size.y > 0)) return cached;\n\n SVG.containerElement.innerHTML = svg;\n\n const svgRoot = SVG.containerElement.querySelector('svg');\n\n if (!svgRoot) {\n useLogger().error({\n message: 'Invalid SVG',\n object: svg,\n });\n return {\n size: new Vector2(0, 0),\n nodes: [],\n } as SVGDocumentData;\n }\n\n let viewBox = new BBox();\n let size = new Vector2();\n\n const hasViewBox = svgRoot.hasAttribute('viewBox');\n const hasSize =\n svgRoot.hasAttribute('width') || svgRoot.hasAttribute('height');\n\n if (hasViewBox) {\n const {x, y, width, height} = svgRoot.viewBox.baseVal;\n viewBox = new BBox(x, y, width, height);\n\n if (!hasSize) size = viewBox.size;\n }\n\n if (hasSize) {\n size = new Vector2(\n svgRoot.width.baseVal.value,\n svgRoot.height.baseVal.value,\n );\n\n if (!hasViewBox) viewBox = new BBox(0, 0, size.width, size.height);\n }\n\n if (!hasViewBox && !hasSize) {\n viewBox = new BBox(svgRoot.getBBox());\n size = viewBox.size;\n }\n\n const scale = size.div(viewBox.size);\n const center = viewBox.center;\n\n const rootTransform = new DOMMatrix()\n .scaleSelf(scale.x, scale.y)\n .translateSelf(-center.x, -center.y);\n\n const nodes = Array.from(\n SVG.extractGroupNodes(svgRoot, svgRoot, rootTransform, {}),\n );\n const builder: SVGDocumentData = {\n size,\n nodes,\n };\n SVG.svgNodesPool[svg] = builder;\n return builder;\n }\n\n /**\n * Get position, rotation and scale from Matrix transformation as Shape properties\n * @param transform - Matrix transformation\n * @returns MotionCanvas Shape properties\n */\n protected static getMatrixTransformation(transform: DOMMatrix): ShapeProps {\n const matrix2 = new Matrix2D(transform);\n\n const position = matrix2.translation;\n const rotation = matrix2.rotation;\n // matrix.scaling can give incorrect result when matrix contain skew operation\n const scale = {\n x: matrix2.x.magnitude,\n y: matrix2.y.magnitude,\n };\n if (matrix2.determinant < 0) {\n if (matrix2.values[0] < matrix2.values[3]) scale.x = -scale.x;\n else scale.y = -scale.y;\n }\n return {\n position,\n rotation,\n scale,\n };\n }\n\n /**\n * Convert an SVG color into a Motion Canvas color.\n * @param color - SVG color.\n * @returns Motion Canvas color.\n */\n private static processSVGColor(\n color: SignalValue<PossibleCanvasStyle> | undefined,\n ): SignalValue<PossibleCanvasStyle> | undefined {\n if (color === 'transparent' || color === 'none') {\n return null;\n }\n\n return color;\n }\n\n /**\n * Get the final transformation matrix for the given SVG element.\n * @param element - SVG element.\n * @param parentTransform - The transformation matrix of the parent.\n */\n private static getElementTransformation(\n element: SVGGraphicsElement,\n parentTransform: DOMMatrix,\n ) {\n const transform = element.transform.baseVal.consolidate();\n const transformMatrix = (\n transform ? parentTransform.multiply(transform.matrix) : parentTransform\n ).translate(\n SVG.parseNumberAttribute(element, 'x'),\n SVG.parseNumberAttribute(element, 'y'),\n );\n return transformMatrix;\n }\n\n private static parseLineCap(name: string | null): CanvasLineCap | null {\n if (!name) return null;\n if (name === 'butt' || name === 'round' || name === 'square') return name;\n\n useLogger().warn(`SVG: invalid line cap \"${name}\"`);\n return null;\n }\n\n private static parseLineJoin(name: string | null): CanvasLineJoin | null {\n if (!name) return null;\n if (name === 'bevel' || name === 'miter' || name === 'round') return name;\n\n if (name === 'arcs' || name === 'miter-clip') {\n useLogger().warn(`SVG: line join is not supported \"${name}\"`);\n } else {\n useLogger().warn(`SVG: invalid line join \"${name}\"`);\n }\n return null;\n }\n\n private static parseLineDash(value: string | null): number[] | null {\n if (!value) return null;\n\n const list = value.split(/,|\\s+/);\n if (list.findIndex(str => str.endsWith('%')) > 0) {\n useLogger().warn(`SVG: percentage line dash are ignored`);\n return null;\n }\n return list.map(str => parseFloat(str));\n }\n\n private static parseDashOffset(value: string | null): number | null {\n if (!value) return null;\n const trimmed = value.trim();\n if (trimmed.endsWith('%')) {\n useLogger().warn(`SVG: percentage line dash offset are ignored`);\n }\n return parseFloat(trimmed);\n }\n\n private static parseOpacity(value: string | null): number | null {\n if (!value) return null;\n if (value.endsWith('%')) return parseFloat(value) / 100;\n return parseFloat(value);\n }\n\n /**\n * Convert the SVG element's style to a Motion Canvas Shape properties.\n * @param element - An SVG element whose style should be converted.\n * @param inheritedStyle - The parent style that should be inherited.\n */\n private static getElementStyle(\n element: SVGGraphicsElement,\n inheritedStyle: ShapeProps,\n ): ShapeProps {\n return {\n fill: element.getAttribute('fill') ?? inheritedStyle.fill,\n stroke: element.getAttribute('stroke') ?? inheritedStyle.stroke,\n lineWidth: element.hasAttribute('stroke-width')\n ? parseFloat(element.getAttribute('stroke-width')!)\n : inheritedStyle.lineWidth,\n lineCap:\n this.parseLineCap(element.getAttribute('stroke-linecap')) ??\n inheritedStyle.lineCap,\n lineJoin:\n this.parseLineJoin(element.getAttribute('stroke-linejoin')) ??\n inheritedStyle.lineJoin,\n lineDash:\n this.parseLineDash(element.getAttribute('stroke-dasharray')) ??\n inheritedStyle.lineDash,\n lineDashOffset:\n this.parseDashOffset(element.getAttribute('stroke-dashoffset')) ??\n inheritedStyle.lineDashOffset,\n opacity:\n this.parseOpacity(element.getAttribute('opacity')) ??\n inheritedStyle.opacity,\n layout: false,\n };\n }\n\n /**\n * Extract `SVGShapeData` list from the SVG element's children.\n * This will not extract the current element's shape.\n * @param element - An element whose children will be extracted.\n * @param svgRoot - The SVG root (\"svg\" tag) of the element.\n * @param parentTransform - The transformation matrix applied to the parent.\n * @param inheritedStyle - The style of the current SVG `element` that the children should inherit.\n */\n private static *extractGroupNodes(\n element: SVGElement,\n svgRoot: Element,\n parentTransform: DOMMatrix,\n inheritedStyle: ShapeProps,\n ): Generator<SVGShapeData> {\n for (const child of element.children) {\n if (!(child instanceof SVGGraphicsElement)) continue;\n\n yield* this.extractElementNodes(\n child,\n svgRoot,\n parentTransform,\n inheritedStyle,\n );\n }\n }\n\n /**\n * Parse a number from an SVG element attribute.\n * @param element - SVG element whose attribute will be parsed.\n * @param name - The name of the attribute to parse.\n * @returns a parsed number or `0` if the attribute is not defined.\n */\n private static parseNumberAttribute(\n element: SVGElement,\n name: string,\n ): number {\n return parseFloat(element.getAttribute(name) ?? '0');\n }\n\n /**\n * Extract `SVGShapeData` list from the SVG element.\n * This will also recursively extract shapes from its children.\n * @param child - An SVG element to extract.\n * @param svgRoot - The SVG root (\"svg\" tag) of the element.\n * @param parentTransform - The transformation matrix applied to the parent.\n * @param inheritedStyle - The style of the parent SVG element that the element should inherit.\n */\n private static *extractElementNodes(\n child: SVGGraphicsElement,\n svgRoot: Element,\n parentTransform: DOMMatrix,\n inheritedStyle: ShapeProps,\n ): Generator<SVGShapeData> {\n const transformMatrix = SVG.getElementTransformation(\n child,\n parentTransform,\n );\n const style = SVG.getElementStyle(child, inheritedStyle);\n const id = child.id ?? '';\n if (child.tagName === 'g') {\n yield* SVG.extractGroupNodes(child, svgRoot, transformMatrix, style);\n } else if (child.tagName === 'use') {\n const hrefElement = svgRoot.querySelector(\n (child as SVGUseElement).href.baseVal,\n );\n if (!(hrefElement instanceof SVGGraphicsElement)) {\n useLogger().warn(`invalid SVG use tag. element \"${child.outerHTML}\"`);\n return;\n }\n\n yield* SVG.extractElementNodes(\n hrefElement,\n svgRoot,\n transformMatrix,\n inheritedStyle,\n );\n } else if (child.tagName === 'path') {\n const data = child.getAttribute('d');\n if (!data) {\n useLogger().warn('blank path data at ' + child.id);\n return;\n }\n const transformation = transformMatrix;\n yield {\n id: id || 'path',\n type: Path as unknown as new (props: NodeProps) => Node,\n props: {\n data,\n tweenAlignPath: true,\n ...SVG.getMatrixTransformation(transformation),\n ...style,\n } as PathProps,\n };\n } else if (child.tagName === 'rect') {\n const width = SVG.parseNumberAttribute(child, 'width');\n const height = SVG.parseNumberAttribute(child, 'height');\n const rx = SVG.parseNumberAttribute(child, 'rx');\n const ry = SVG.parseNumberAttribute(child, 'ry');\n\n const bbox = new BBox(0, 0, width, height);\n const center = bbox.center;\n const transformation = transformMatrix.translate(center.x, center.y);\n\n yield {\n id: id || 'rect',\n type: Rect,\n props: {\n width,\n height,\n radius: [rx, ry],\n ...SVG.getMatrixTransformation(transformation),\n ...style,\n } as RectProps,\n };\n } else if (['circle', 'ellipse'].includes(child.tagName)) {\n const cx = SVG.parseNumberAttribute(child, 'cx');\n const cy = SVG.parseNumberAttribute(child, 'cy');\n const size: PossibleSpacing =\n child.tagName === 'circle'\n ? SVG.parseNumberAttribute(child, 'r') * 2\n : [\n SVG.parseNumberAttribute(child, 'rx') * 2,\n SVG.parseNumberAttribute(child, 'ry') * 2,\n ];\n\n const transformation = transformMatrix.translate(cx, cy);\n\n yield {\n id: id || child.tagName,\n type: Circle,\n props: {\n size,\n ...style,\n ...SVG.getMatrixTransformation(transformation),\n } as CircleProps,\n };\n } else if (['line', 'polyline', 'polygon'].includes(child.tagName)) {\n const numbers =\n child.tagName === 'line'\n ? ['x1', 'y1', 'x2', 'y2'].map(attr =>\n SVG.parseNumberAttribute(child, attr),\n )\n : child\n .getAttribute('points')!\n .match(/-?[\\d.e+-]+/g)!\n .map(value => parseFloat(value));\n const points = numbers.reduce<number[][]>((accum, current) => {\n let last = accum.at(-1);\n if (!last || last.length === 2) {\n last = [];\n accum.push(last);\n }\n last.push(current);\n return accum;\n }, []);\n\n if (child.tagName === 'polygon') points.push(points[0]);\n\n yield {\n id: id || child.tagName,\n type: Line as unknown as new (props: NodeProps) => Node,\n props: {\n points,\n ...style,\n ...SVG.getMatrixTransformation(transformMatrix),\n } as LineProps,\n };\n } else if (child.tagName === 'image') {\n const x = SVG.parseNumberAttribute(child, 'x');\n const y = SVG.parseNumberAttribute(child, 'y');\n const width = SVG.parseNumberAttribute(child, 'width');\n const height = SVG.parseNumberAttribute(child, 'height');\n const href = child.getAttribute('href') ?? '';\n\n const bbox = new BBox(x, y, width, height);\n const center = bbox.center;\n const transformation = transformMatrix.translate(center.x, center.y);\n\n yield {\n id: id || child.tagName,\n type: Img,\n props: {\n src: href,\n ...style,\n ...SVG.getMatrixTransformation(transformation),\n } as ImgProps,\n };\n }\n }\n}\n","interface TransformDiff<T> {\n inserted: TransformDiffItem<T>[];\n deleted: TransformDiffItem<T>[];\n transformed: TransformDiffItemTransformed<T>[];\n}\n\ninterface TransformDiffItem<T> {\n before?: T;\n beforeIdIndex: number;\n current: T;\n currentIndex: number;\n}\n\ninterface TransformDiffItemTransformed<T> {\n insert: boolean;\n remove: boolean;\n from: TransformDiffItem<T>;\n to: TransformDiffItem<T>;\n}\n\ninterface ApplyTransformInserted<T> {\n item: TransformDiffItem<T>;\n order: number;\n}\n\ninterface ApplyTransformResult<T> {\n inserted: ApplyTransformInserted<T>[];\n}\n\ninterface Idable {\n id: string;\n}\n\nfunction getIdMap<T extends Idable>(list: T[]) {\n const map = new Map<string, TransformDiffItem<T>[]>();\n let before: T | undefined = undefined;\n for (const [index, current] of list.entries()) {\n const currentArray = map.get(current.id) ?? [];\n if (!map.has(current.id)) {\n map.set(current.id, currentArray);\n }\n\n currentArray.push({\n before,\n current,\n beforeIdIndex: before ? map.get(before.id)!.length - 1 : -1,\n currentIndex: index,\n });\n before = current;\n }\n return map;\n}\n\nexport function getTransformDiff<T extends Idable>(\n from: T[],\n to: T[],\n): TransformDiff<T> {\n const diff: TransformDiff<T> = {\n inserted: [],\n deleted: [],\n transformed: [],\n };\n\n const fromMap = getIdMap(from);\n const toMap = getIdMap(to);\n\n for (const [key, fromItem] of fromMap.entries()) {\n const toItem = toMap.get(key);\n if (toItem) {\n toMap.delete(key);\n for (let i = 0; i < Math.max(fromItem.length, toItem.length); i++) {\n const insert = i >= fromItem.length;\n const remove = i >= toItem.length;\n\n const fromNode = !insert ? fromItem[i] : fromItem[fromItem.length - 1];\n const toNode = !remove ? toItem[i] : toItem[toItem.length - 1];\n\n diff.transformed.push({\n insert,\n remove,\n from: fromNode,\n to: toNode,\n });\n }\n } else {\n for (const node of fromItem) {\n diff.deleted.push(node);\n }\n }\n }\n\n for (const toItem of toMap.values()) {\n for (const node of toItem) {\n diff.inserted.push(node);\n }\n }\n\n return diff;\n}\n\nexport function applyTransformDiff<T extends Idable>(\n current: T[],\n diff: TransformDiff<T>,\n cloner: (original: T) => T,\n): ApplyTransformResult<T> {\n function insert(item: TransformDiffItem<T>) {\n let idIndex = -1;\n const index = item.before\n ? current.findIndex(({id}) => {\n if (id === item.before?.id) {\n idIndex++;\n if (idIndex === item.beforeIdIndex) return true;\n }\n return false;\n })\n : 0;\n current.splice(index + 1, 0, item.current);\n }\n\n const result: ApplyTransformResult<T> = {\n inserted: diff.inserted.map(item => ({\n item,\n order: item.currentIndex,\n })),\n };\n\n for (const item of diff.transformed) {\n if (!item.insert) continue;\n\n const from = item.from;\n item.from = {\n ...item.to,\n current: cloner(from.current),\n };\n result.inserted.push({\n item: item.from,\n order: item.to.currentIndex,\n });\n }\n\n result.inserted.sort((a, b) => a.order - b.order);\n\n for (const item of result.inserted) {\n insert(item.item);\n }\n\n return result;\n}\n","import type {\n InterpolationFunction,\n SignalValue,\n SimpleSignal,\n ThreadGenerator,\n TimingFunction,\n} from '@twick/core';\nimport {DEFAULT, all, capitalize, threadable} from '@twick/core';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport {is} from '../utils';\nimport type {Node} from './Node';\nimport type {ShapeProps} from './Shape';\nimport {Shape} from './Shape';\nimport {TXT_TYPE, TxtLeaf} from './TxtLeaf';\nimport type {ComponentChildren} from './types';\n\ntype TxtChildren = string | Node | (string | Node)[];\ntype AnyTxt = Txt | TxtLeaf;\n\nexport interface TxtProps extends ShapeProps {\n children?: TxtChildren;\n text?: SignalValue<string>;\n}\n\n@nodeName('Txt')\nexport class Txt extends Shape {\n public readonly [TXT_TYPE] = true;\n\n /**\n * Create a bold text node.\n *\n * @remarks\n * This is a shortcut for\n * ```tsx\n * <Txt fontWeight={700} />\n * ```\n *\n * @param props - Additional text properties.\n */\n public static b(props: TxtProps) {\n return new Txt({...props, fontWeight: 700});\n }\n\n /**\n * Create an italic text node.\n *\n * @remarks\n * This is a shortcut for\n * ```tsx\n * <Txt fontStyle={'italic'} />\n * ```\n *\n * @param props - Additional text properties.\n */\n public static i(props: TxtProps) {\n return new Txt({...props, fontStyle: 'italic'});\n }\n\n @initial('')\n @signal()\n public declare readonly text: SimpleSignal<string, this>;\n\n protected getText(): string {\n return this.innerText();\n }\n\n protected setText(value: SignalValue<string>) {\n const children = this.children();\n let leaf: TxtLeaf | null = null;\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (leaf === null && child instanceof TxtLeaf) {\n leaf = child;\n } else {\n child.parent(null);\n }\n }\n\n if (leaf === null) {\n leaf = new TxtLeaf({text: value});\n leaf.parent(this);\n } else {\n leaf.text(value);\n }\n\n this.setParsedChildren([leaf]);\n }\n\n protected override setChildren(value: SignalValue<ComponentChildren>) {\n if (this.children.context.raw() === value) {\n return;\n }\n\n if (typeof value === 'string') {\n this.text(value);\n } else {\n super.setChildren(value);\n }\n }\n\n @threadable()\n protected *tweenText(\n value: SignalValue<string>,\n time: number,\n timingFunction: TimingFunction,\n interpolationFunction: InterpolationFunction<string>,\n ): ThreadGenerator {\n yield document.fonts?.ready;\n const children = this.children();\n if (children.length !== 1 || !(children[0] instanceof TxtLeaf)) {\n this.text.save();\n }\n\n const leaf = this.childAs<TxtLeaf>(0)!;\n const oldText = leaf.text.context.raw();\n const oldSize = this.size.context.raw();\n leaf.text(value);\n const newSize = this.size();\n leaf.text(oldText ?? DEFAULT);\n\n if (this.height() === 0) {\n this.height(newSize.height);\n }\n\n yield* all(\n this.size(newSize, time, timingFunction),\n leaf.text(value, time, timingFunction, interpolationFunction),\n );\n\n this.children.context.setter(value);\n this.size(oldSize);\n }\n\n protected getLayout(): boolean {\n return true;\n }\n\n public constructor({children, text, ...props}: TxtProps) {\n super(props);\n this.children(text ?? children);\n }\n\n @computed()\n protected innerText(): string {\n const children = this.childrenAs<Txt | TxtLeaf>();\n let text = '';\n for (const child of children) {\n text += child.text();\n }\n\n return text;\n }\n\n @computed()\n protected parentTxt() {\n const parent = this.parent();\n return parent instanceof Txt ? parent : null;\n }\n\n protected override parseChildren(children: ComponentChildren): AnyTxt[] {\n const result: AnyTxt[] = [];\n const array = Array.isArray(children) ? children : [children];\n for (const child of array) {\n if (child instanceof Txt || child instanceof TxtLeaf) {\n result.push(child);\n } else if (typeof child === 'string') {\n result.push(new TxtLeaf({text: child}));\n }\n }\n\n return result;\n }\n\n protected override applyFlex() {\n super.applyFlex();\n this.element.style.display = this.findAncestor(is(Txt))\n ? 'inline'\n : 'block';\n }\n\n protected override async draw(context: CanvasRenderingContext2D) {\n await document.fonts?.ready;\n await this.drawChildren(context);\n }\n}\n\n[\n 'fill',\n 'stroke',\n 'lineWidth',\n 'strokeFirst',\n 'lineCap',\n 'lineJoin',\n 'lineDash',\n 'lineDashOffset',\n].forEach(prop => {\n (Txt.prototype as any)[`getDefault${capitalize(prop)}`] = function (\n this: Txt,\n initial: unknown,\n ) {\n return (this.parentTxt() as any)?.[prop]() ?? initial;\n };\n});\n","import type {SignalValue, SimpleSignal} from '@twick/core';\nimport {BBox, capitalize, lazy, textLerp} from '@twick/core';\nimport {\n computed,\n initial,\n interpolation,\n nodeName,\n signal,\n} from '../decorators';\nimport type {ShapeProps} from './Shape';\nimport {Shape} from './Shape';\n\nexport interface TxtLeafProps extends ShapeProps {\n children?: string;\n text?: SignalValue<string>;\n}\n\nexport const TXT_TYPE = Symbol('Txt');\n\n@nodeName('TxtLeaf')\nexport class TxtLeaf extends Shape {\n @lazy(() => {\n try {\n return new (Intl as any).Segmenter(undefined, {\n granularity: 'grapheme',\n });\n } catch (e) {\n return null;\n }\n })\n protected static readonly segmenter: any;\n\n @initial('')\n @interpolation(textLerp)\n @signal()\n public declare readonly text: SimpleSignal<string, this>;\n\n public constructor({children, ...rest}: TxtLeafProps) {\n super(rest);\n if (children) {\n this.text(children);\n }\n }\n\n @computed()\n protected parentTxt() {\n const parent = this.parent();\n if (!parent) {\n return null;\n }\n\n if (!(TXT_TYPE in parent)) {\n return null;\n }\n\n return parent;\n }\n\n protected override async draw(context: CanvasRenderingContext2D) {\n this.requestFontUpdate();\n this.applyStyle(context);\n await document.fonts?.ready;\n this.applyText(context);\n context.font = this.styles.font;\n context.textBaseline = 'bottom';\n if ('letterSpacing' in context) {\n context.letterSpacing = `${this.letterSpacing()}px`;\n }\n const fontOffset = context.measureText('').fontBoundingBoxAscent;\n\n const parentRect = this.element.getBoundingClientRect();\n const {width, height} = this.size();\n const range = document.createRange();\n let line = '';\n const lineRect = new BBox();\n for (const childNode of this.element.childNodes) {\n if (!childNode.textContent) {\n continue;\n }\n\n range.selectNodeContents(childNode);\n const rangeRect = range.getBoundingClientRect();\n\n const x = width / -2 + rangeRect.left - parentRect.left;\n const y = height / -2 + rangeRect.top - parentRect.top + fontOffset;\n\n if (lineRect.y === y) {\n lineRect.width += rangeRect.width;\n line += childNode.textContent;\n } else {\n await this.drawText(context, line, lineRect);\n lineRect.x = x;\n lineRect.y = y;\n lineRect.width = rangeRect.width;\n lineRect.height = rangeRect.height;\n line = childNode.textContent;\n }\n }\n\n await this.drawText(context, line, lineRect);\n }\n\n protected async drawText(\n context: CanvasRenderingContext2D,\n text: string,\n box: BBox,\n ) {\n const y = box.y;\n text = text.replace(/\\s+/g, ' ');\n if (this.lineWidth() <= 0) {\n context.fillText(text, box.x, y);\n } else if (this.strokeFirst()) {\n context.strokeText(text, box.x, y);\n context.fillText(text, box.x, y);\n } else {\n context.fillText(text, box.x, y);\n context.strokeText(text, box.x, y);\n }\n }\n\n protected override getCacheBBox(): BBox {\n const size = this.computedSize();\n const range = document.createRange();\n range.selectNodeContents(this.element);\n const bbox = range.getBoundingClientRect();\n\n const lineWidth = this.lineWidth();\n // We take the default value of the miterLimit as 10.\n const miterLimitCoefficient = this.lineJoin() === 'miter' ? 0.5 * 10 : 0.5;\n\n return new BBox(-size.width / 2, -size.height / 2, bbox.width, bbox.height)\n .expand([0, this.fontSize() * 0.5])\n .expand(lineWidth * miterLimitCoefficient);\n }\n\n protected override applyFlex() {\n super.applyFlex();\n this.element.style.display = 'inline';\n }\n\n protected override updateLayout() {\n this.applyFont();\n this.applyFlex();\n\n // Make sure the text is aligned correctly even if the text is smaller than\n // the container.\n if (this.justifyContent.isInitial()) {\n this.element.style.justifyContent =\n this.styles.getPropertyValue('text-align');\n }\n\n const wrap =\n this.styles.whiteSpace !== 'nowrap' && this.styles.whiteSpace !== 'pre';\n\n if (wrap) {\n this.element.innerText = '';\n\n if (TxtLeaf.segmenter) {\n for (const word of TxtLeaf.segmenter.segment(this.text())) {\n this.element.appendChild(document.createTextNode(word.segment));\n }\n } else {\n for (const word of this.text().split('')) {\n this.element.appendChild(document.createTextNode(word));\n }\n }\n } else if (this.styles.whiteSpace === 'pre') {\n this.element.innerText = '';\n for (const line of this.text().split('\\n')) {\n this.element.appendChild(document.createTextNode(line + '\\n'));\n }\n } else {\n this.element.innerText = this.text();\n }\n }\n}\n\n/**\n * Overwrite all getters for signal values to return the parent value if it\n * exists.\n *\n * The getters on the TxtLeaf class are used by the `@signal` decorators and\n * are not used by the class or its consumers directly.\n *\n * Check out 2d/src/lib/utils/makeSignalExtensions.ts if this is confusing.\n */\n[\n 'fill',\n 'stroke',\n 'lineWidth',\n 'strokeFirst',\n 'lineCap',\n 'lineJoin',\n 'lineDash',\n 'lineDashOffset',\n].forEach(prop => {\n (TxtLeaf.prototype as any)[`get${capitalize(prop)}`] = function (\n this: TxtLeaf,\n ) {\n return (\n (this.parentTxt() as any)?.[prop]() ??\n (this as any)[prop].context.getInitial()\n );\n };\n});\n","import type {SerializedVector2, SignalValue, SimpleSignal} from '@twick/core';\nimport {BBox, DependencyContext, PlaybackState} from '@twick/core';\nimport Hls from 'hls.js';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport type {DesiredLength} from '../partials';\nimport {drawImage} from '../utils';\nimport {ImageCommunication} from '../utils/video/ffmpeg-client';\nimport {dropExtractor, getFrame} from '../utils/video/mp4-parser-manager';\nimport type {MediaProps} from './Media';\nimport {Media} from './Media';\n\nexport interface VideoProps extends MediaProps {\n /**\n * {@inheritDoc Video.alpha}\n */\n alpha?: SignalValue<number>;\n /**\n * {@inheritDoc Video.smoothing}\n */\n smoothing?: SignalValue<boolean>;\n /**\n * {@inheritDoc Video.decoder}\n */\n decoder?: SignalValue<'web' | 'ffmpeg' | 'slow' | null>;\n}\n\n@nodeName('Video')\nexport class Video extends Media {\n /**\n * The alpha value of this video.\n *\n * @remarks\n * Unlike opacity, the alpha value affects only the video itself, leaving the\n * fill, stroke, and children intact.\n */\n @initial(1)\n @signal()\n public declare readonly alpha: SimpleSignal<number, this>;\n\n /**\n * Whether the video should be smoothed.\n *\n * @remarks\n * When disabled, the video will be scaled using the nearest neighbor\n * interpolation with no smoothing. The resulting video will appear pixelated.\n *\n * @defaultValue true\n */\n @initial(true)\n @signal()\n public declare readonly smoothing: SimpleSignal<boolean, this>;\n\n /**\n * Which decoder to use during rendering. The `web` decoder is the fastest\n * but only supports MP4 files. The `ffmpeg` decoder is slower and more resource\n * intensive but supports more formats. The `slow` decoder is the slowest but\n * supports all formats.\n *\n * @defaultValue null\n */\n @initial(null)\n @signal()\n public declare readonly decoder: SimpleSignal<\n 'web' | 'ffmpeg' | 'slow' | null,\n this\n >;\n\n public detectedFileType: 'mp4' | 'webm' | 'hls' | 'mov' | 'unknown' =\n 'unknown';\n private fileTypeWasDetected: boolean = false;\n\n private static readonly pool: Record<string, HTMLVideoElement> = {};\n\n private static readonly imageCommunication = !import.meta.hot\n ? null\n : new ImageCommunication();\n\n public constructor(props: VideoProps) {\n super(props);\n }\n\n protected override desiredSize(): SerializedVector2<DesiredLength> {\n const custom = super.desiredSize();\n if (custom.x === null && custom.y === null) {\n const image = this.video();\n return {\n x: image.videoWidth,\n y: image.videoHeight,\n };\n }\n\n return custom;\n }\n\n protected mediaElement(): HTMLVideoElement {\n return this.video();\n }\n\n protected seekedMedia(): HTMLVideoElement {\n return this.seekedVideo();\n }\n\n protected fastSeekedMedia(): HTMLVideoElement {\n return this.fastSeekedVideo();\n }\n\n @computed()\n private video(): HTMLVideoElement {\n const src = this.src();\n \n // Use a temporary key for undefined src to avoid conflicts\n const key = `${this.key}/${src || 'pending'}`;\n \n let video = Video.pool[key];\n if (!video) {\n video = document.createElement('video');\n video.crossOrigin = 'anonymous';\n\n // Only set src if it's valid, otherwise leave it empty\n if (src && src !== 'undefined') {\n try {\n const parsedSrc = new URL(src, window.location.origin);\n \n if (parsedSrc.pathname.endsWith('.m3u8')) {\n const hls = new Hls();\n hls.loadSource(src);\n hls.attachMedia(video);\n } else {\n video.src = src;\n }\n } catch (error) {\n // Fallback to direct assignment\n video.src = src;\n }\n }\n\n Video.pool[key] = video;\n } else if (src && src !== 'undefined' && video.src !== src) {\n // Update existing video element if src has changed and is now valid\n try {\n const parsedSrc = new URL(src, window.location.origin);\n \n if (parsedSrc.pathname.endsWith('.m3u8')) {\n const hls = new Hls();\n hls.loadSource(src);\n hls.attachMedia(video);\n } else {\n video.src = src;\n }\n } catch (error) {\n // Fallback to direct assignment\n video.src = src;\n }\n \n // Move video to correct pool key\n delete Video.pool[key];\n const newKey = `${this.key}/${src}`;\n Video.pool[newKey] = video;\n }\n\n // If src is still undefined, wait for it to become available\n if (!src || src === 'undefined') {\n DependencyContext.collectPromise(\n new Promise<void>(resolve => {\n // Check periodically for valid src\n const checkSrc = () => {\n const currentSrc = this.src();\n if (currentSrc && currentSrc !== 'undefined') {\n resolve();\n } else {\n setTimeout(checkSrc, 10);\n }\n };\n checkSrc();\n }),\n );\n }\n\n const weNeedToWait = this.waitForCanPlayNecessary(video);\n \n if (!weNeedToWait) {\n return video;\n }\n\n DependencyContext.collectPromise(\n new Promise<void>(resolve => {\n this.waitForCanPlay(video, resolve);\n }),\n );\n\n return video;\n }\n\n @computed()\n protected seekedVideo(): HTMLVideoElement {\n const video = this.video();\n const time = this.clampTime(this.time());\n\n video.playbackRate = this.playbackRate();\n\n if (!video.paused) {\n video.pause();\n }\n\n if (this.lastTime === time) {\n return video;\n }\n\n this.setCurrentTime(time);\n\n return video;\n }\n\n @computed()\n protected fastSeekedVideo(): HTMLVideoElement {\n const video = this.video();\n const time = this.clampTime(this.time());\n\n video.playbackRate = this.playbackRate();\n\n if (this.lastTime === time) {\n return video;\n }\n\n const playing =\n this.playing() && time < video.duration && video.playbackRate > 0;\n \n if (playing) {\n if (video.paused) {\n DependencyContext.collectPromise(video.play());\n }\n } else {\n if (!video.paused) {\n video.pause();\n }\n }\n\n // reseek when video is out of sync by more than one second\n if (Math.abs(video.currentTime - time) > 1) {\n this.setCurrentTime(time);\n } else if (!playing) {\n video.currentTime = time;\n }\n\n return video;\n }\n\n protected lastFrame: ImageBitmap | null = null;\n\n protected async webcodecSeekedVideo(): Promise<CanvasImageSource> {\n const video = this.video();\n const time = this.clampTime(this.time());\n\n video.playbackRate = this.playbackRate();\n\n if (this.lastFrame && this.lastTime === time) {\n return this.lastFrame;\n }\n\n const fps = this.view().fps() / this.playbackRate();\n return getFrame(this.key, video.src, time, fps);\n }\n\n protected async ffmpegSeekedVideo(): Promise<ImageBitmap> {\n const video = this.video();\n const time = this.clampTime(this.time());\n const duration = this.getDuration();\n\n video.playbackRate = this.playbackRate();\n\n if (this.lastFrame && this.lastTime === time) {\n return this.lastFrame;\n }\n\n const fps = this.view().fps() / this.playbackRate();\n\n if (!Video.imageCommunication) {\n throw new Error('ServerSeekedVideo can only be used with HMR.');\n }\n\n const frame = await Video.imageCommunication.getFrame(\n this.key,\n video.src,\n time,\n duration,\n fps,\n );\n this.lastFrame = frame;\n this.lastTime = time;\n\n return frame;\n }\n\n protected async seekFunction() {\n const playbackState = this.view().playbackState();\n\n // During playback\n if (\n playbackState === PlaybackState.Playing ||\n playbackState === PlaybackState.Presenting\n ) {\n return this.fastSeekedVideo();\n }\n\n if (playbackState === PlaybackState.Paused) {\n return this.seekedVideo();\n }\n\n // During rendering, if set explicitly\n if (this.decoder() === 'slow') {\n return this.seekedVideo();\n }\n\n if (this.decoder() === 'ffmpeg') {\n return this.ffmpegSeekedVideo();\n }\n\n if (this.decoder() === 'web') {\n return this.webcodecSeekedVideo();\n }\n\n if (!this.fileTypeWasDetected) {\n this.detectFileType();\n }\n\n // If not set explicitly, use detected file type to determine decoder\n if (this.detectedFileType === 'webm') {\n return this.ffmpegSeekedVideo();\n }\n\n if (this.detectedFileType === 'hls') {\n return this.seekedVideo();\n }\n\n return this.webcodecSeekedVideo();\n }\n\n protected override async draw(context: CanvasRenderingContext2D) {\n // Auto-start playback if Twick is playing but media isn't\n this.autoPlayBasedOnTwick();\n \n this.drawShape(context);\n const alpha = this.alpha();\n if (alpha > 0) {\n const video = await this.seekFunction();\n\n const box = BBox.fromSizeCentered(this.computedSize());\n context.save();\n context.clip(this.getPath());\n if (alpha < 1) {\n context.globalAlpha *= alpha;\n }\n context.imageSmoothingEnabled = this.smoothing();\n drawImage(context, video, box);\n context.restore();\n }\n\n if (this.clip()) {\n context.clip(this.getPath());\n }\n\n await this.drawChildren(context);\n }\n\n protected override applyFlex() {\n super.applyFlex();\n try {\n const video = this.video();\n // Only set aspect ratio if video element is available and has valid dimensions\n if (video && video.videoWidth > 0 && video.videoHeight > 0) {\n this.element.style.aspectRatio = (\n this.ratio() ?? video.videoWidth / video.videoHeight\n ).toString();\n }\n } catch (error) {\n // If video element is not ready yet, skip setting aspect ratio\n // It will be set later when the video becomes available\n }\n }\n\n public override remove() {\n super.remove();\n dropExtractor(this.key, this.src());\n return this;\n }\n\n private handleUnknownFileType(src: string) {\n console.warn(\n `WARNING: Could not detect file type of video (${src}), will default to using mp4 decoder. If your video file is not an mp4 file, this will lead to an error - to fix this, reencode your video as an mp4 file (better performance) or specify a different decoder: https://docs.re.video/common-issues/slow-rendering#use-mp4-decoder`,\n );\n this.detectedFileType = 'unknown';\n this.fileTypeWasDetected = true;\n }\n\n private detectFileType() {\n return DependencyContext.collectPromise(\n (async () => {\n const src = this.src();\n const extension = src.split('?')[0].split('.').pop()?.toLowerCase();\n\n if (\n extension === 'mp4' ||\n extension === 'webm' ||\n extension === 'mov'\n ) {\n this.detectedFileType = extension;\n this.fileTypeWasDetected = true;\n return;\n }\n\n if (extension === 'm3u8') {\n this.detectedFileType = 'hls';\n this.fileTypeWasDetected = true;\n return;\n }\n\n if (!src.startsWith('http://') && !src.startsWith('https://')) {\n this.handleUnknownFileType(src);\n return;\n }\n\n const response = await fetch(src, {method: 'HEAD'});\n const contentType = response.headers.get('Content-Type');\n\n if (!contentType) {\n this.handleUnknownFileType(src);\n return;\n }\n\n if (contentType.includes('video/mp4')) {\n this.detectedFileType = 'mp4';\n this.fileTypeWasDetected = true;\n return;\n }\n\n if (contentType.includes('video/webm')) {\n this.detectedFileType = 'webm';\n this.fileTypeWasDetected = true;\n return;\n }\n\n if (contentType.includes('video/quicktime')) {\n this.detectedFileType = 'mov';\n this.fileTypeWasDetected = true;\n return;\n }\n\n if (\n contentType.includes('application/vnd.apple.mpegurl') ||\n contentType.includes('application/x-mpegURL')\n ) {\n this.detectedFileType = 'hls';\n this.fileTypeWasDetected = true;\n return;\n }\n\n this.handleUnknownFileType(src);\n })(),\n );\n }\n}\n","export class ImageCommunication {\n public constructor() {\n if (!import.meta.hot) {\n throw new Error('FfmpegVideoFrame can only be used with HMR.');\n }\n }\n\n public async getFrame(\n id: string,\n src: string,\n time: number,\n duration: number,\n fps: number,\n ) {\n const response = await fetch('/twick-ffmpeg-decoder/video-frame', {\n method: 'POST',\n headers: {\n // eslint-disable-next-line\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n id,\n filePath: src,\n startTime: time,\n duration,\n fps,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const width = parseInt(response.headers.get('X-Frame-Width') || '1080', 10);\n const height = parseInt(\n response.headers.get('X-Frame-Height') || '1920',\n 10,\n );\n\n const arrayBuffer = await response.arrayBuffer();\n\n const imageData = new ImageData(\n new Uint8ClampedArray(arrayBuffer),\n width,\n height,\n );\n\n return createImageBitmap(imageData);\n }\n}\n","import {createFile} from 'mp4box';\nimport {FrameSampler} from './sampler';\nimport {Segment} from './segment';\nimport {MP4FileSink} from './sink';\nimport type {Edit} from './utils';\nimport {description, mp4BoxEditToEdit} from './utils';\n\n/**\n * Loads the file at the given URI until it finds the moov box.\n * Once found, it calls `setConfig` with the video configuration.\n * @param uri - The URI of the video file.\n * @param setConfig - Callback to set the video configuration.\n * @returns\n */\nasync function getFileInfo(uri: string) {\n return new Promise<{\n file: any;\n edits: Edit[];\n config: VideoDecoderConfig;\n }>((res, rej) => {\n const file = createFile();\n let found = false;\n const controller = new AbortController();\n\n file.onReady = (info: any) => {\n found = true;\n controller.abort();\n\n const track = info.videoTracks[0];\n\n const config = {\n // Browser doesn't support parsing full vp8 codec (eg: `vp08.00.41.08`),\n // they only support `vp8`.\n codec: track.codec.startsWith('vp08') ? 'vp8' : track.codec,\n codedHeight: track.video.height,\n codedWidth: track.video.width,\n description: description(file, track),\n };\n\n const defaultEdit: Omit<Edit, 'fps'> = {\n mediaTime: 0,\n segmentDuration: track.duration,\n mediaRateInteger: 1,\n mediaRateFraction: 0,\n };\n\n const editsFromVideo: Omit<Edit, 'fps'>[] = track.edits?.map(\n (edit: any) => mp4BoxEditToEdit(edit),\n );\n\n // If there are no entries, use the default edit\n const editsWithoutFps = editsFromVideo?.length\n ? editsFromVideo\n : [defaultEdit];\n\n // Calculate FPS for each segment\n const edits = editsWithoutFps.map(edit => {\n const trackDurationInSec = track.duration / track.timescale;\n const segmentDurationInSec =\n edit.segmentDuration / track.movie_timescale;\n const segmentFrames =\n track.nb_samples * (segmentDurationInSec / trackDurationInSec);\n const mediaRate =\n edit.mediaRateInteger + edit.mediaRateFraction / 0xffff;\n const fps = (segmentFrames / segmentDurationInSec) * mediaRate;\n return {...edit, fps};\n });\n\n file.setExtractionOptions(track.id);\n file.start();\n\n res({file, edits, config});\n };\n\n return fetch(uri, {signal: controller.signal}).then(async response => {\n if (!response.body) {\n throw new Error('Response body is null');\n }\n\n const reader = response.body.getReader();\n const sink = new MP4FileSink(file, () => {});\n\n while (!found) {\n await reader.read().then(({done, value}) => {\n if (done) {\n file.flush();\n controller.abort();\n rej('Could not find moov');\n return;\n }\n\n sink.write(value);\n });\n }\n });\n });\n}\n\nexport class Mp4Parser {\n private uri: string;\n private file: any;\n private edits: Edit[] = [];\n private decoderConfig?: VideoDecoderConfig;\n\n private startTime: number;\n private targetFps: number;\n\n private nextSegment = 0;\n private sampler?: FrameSampler;\n\n public constructor(uri: string, targetFps: number, startTime: number) {\n this.uri = uri;\n this.targetFps = targetFps;\n this.startTime = startTime;\n }\n\n public async start() {\n const {file, edits, config} = await getFileInfo(this.uri);\n this.file = file;\n this.edits = edits;\n this.decoderConfig = config;\n }\n\n public async getNextFrame() {\n // Start the first segment\n if (!this.sampler) {\n // Skip segments until the start time\n let startTimeWithinSegment = this.startTime;\n while (this.nextSegment < this.edits.length) {\n const segmentDurationInSeconds = this.getSecondDurationOfSegment(\n this.edits[this.nextSegment],\n );\n if (startTimeWithinSegment < segmentDurationInSeconds) {\n break;\n }\n\n startTimeWithinSegment -= segmentDurationInSeconds;\n this.nextSegment++;\n }\n\n // The timestamp is outside of the video\n if (this.nextSegment >= this.edits.length) {\n throw new Error(\n `Timestamp ${this.startTime} is outside of the video, max timestamp is ${this.getDuration()}`,\n );\n }\n\n const segment = new Segment(\n this.uri,\n this.file,\n this.edits,\n this.nextSegment,\n startTimeWithinSegment,\n );\n await segment.start(this.decoderConfig!);\n\n this.sampler = new FrameSampler(\n segment,\n this.edits[this.nextSegment].fps,\n this.targetFps,\n 0,\n );\n this.nextSegment++;\n }\n\n // Try to get the next frame\n let frame = await this.sampler.getNextFrame();\n\n // If there are no more frames in the current segment, start the next segment\n while (!frame && this.nextSegment < this.edits.length) {\n this.sampler.getSegment().close();\n this.sampler.getLastFrame()?.close();\n const segment = new Segment(\n this.uri,\n this.file,\n this.edits,\n this.nextSegment,\n 0,\n );\n await segment.start(this.decoderConfig!);\n\n this.sampler = new FrameSampler(\n segment,\n this.edits[this.nextSegment].fps,\n this.targetFps,\n this.sampler.getSum(), // Carry over the sum from the previous segment\n );\n this.nextSegment++;\n\n frame = await this.sampler.getNextFrame();\n }\n\n // If there are no more frames, return the last frame\n if (!frame) {\n frame = this.sampler.getLastFrame();\n\n // We can close the segment\n await this.sampler.getSegment().close();\n\n // If we still don't have a frame, throw an error\n if (!frame) {\n throw new Error('There are no frames in the video.');\n }\n }\n\n return frame;\n }\n\n private getSecondDurationOfSegment(edit: Edit) {\n const mediaRate = edit.mediaRateInteger + edit.mediaRateFraction / 0xffff;\n const duration =\n edit.segmentDuration / this.file.getInfo().videoTracks[0].movie_timescale;\n return duration / mediaRate;\n }\n\n public getDuration() {\n return this.edits.reduce(\n (acc, edit) => acc + this.getSecondDurationOfSegment(edit),\n 0,\n );\n }\n\n private getTimeSubtractingFrames(frames: number) {\n const durationOfPastSegmentsInSeconds = this.edits\n .slice(0, this.nextSegment - 1)\n .reduce((acc, edit) => acc + this.getSecondDurationOfSegment(edit), 0);\n\n if (!this.sampler) {\n throw new Error('No current segment');\n }\n\n const currentSegmentStartTime = this.sampler.getSegment().getStartTime();\n const samplerTime = this.sampler.getTime(frames);\n\n return (\n durationOfPastSegmentsInSeconds + currentSegmentStartTime + samplerTime\n );\n }\n\n public getTime() {\n return this.getTimeSubtractingFrames(0);\n }\n\n public getLastTime() {\n return this.getTimeSubtractingFrames(1);\n }\n\n public getLastFrame() {\n return this.sampler?.getLastFrame();\n }\n\n public close() {\n this.sampler?.getSegment().close();\n this.sampler?.getLastFrame()?.close();\n this.file.flush();\n }\n}\n","import type {Segment} from './segment';\n\nexport class FrameSampler {\n private framesRequested = 0;\n private lastFrame?: VideoFrame;\n\n public constructor(\n private segment: Segment,\n private sourceFps: number,\n private targetFps: number,\n private sum: number = 0,\n ) {}\n\n public async getNextFrame() {\n const samplingRate = this.sourceFps / this.targetFps;\n this.sum += samplingRate;\n this.framesRequested += 1;\n\n // Return last frame if we haven't progressed enough to get a new frame.\n if (this.sum < 1 && this.lastFrame) {\n return this.lastFrame;\n }\n\n // Burn frames if we have too many.\n while (this.sum >= 2) {\n // Burn frame\n const frame = await this.segment.getNextFrame();\n\n // If there are no more frames, return\n if (!frame) {\n return;\n }\n\n frame.close();\n this.sum -= 1;\n }\n\n // Get a new frame.\n if (this.sum >= 1 || !this.lastFrame) {\n this.sum -= 1;\n const frame = await this.segment.getNextFrame();\n\n // If there are no more frames, return\n if (!frame) {\n return;\n }\n\n this.lastFrame?.close();\n this.lastFrame = frame;\n return frame;\n }\n\n // One of the three if statements above is always true.\n throw new Error('Unreachable code');\n }\n\n public getLastFrame() {\n return this.lastFrame;\n }\n\n public getSum() {\n return this.sum;\n }\n\n public getSegment() {\n return this.segment;\n }\n\n public getTime(framesToSubtract: number) {\n return (this.framesRequested - framesToSubtract) / this.targetFps;\n }\n}\n","// Wraps an MP4Box File as a WritableStream underlying sink.\nexport class MP4FileSink {\n private setStatus;\n private file;\n private offset;\n\n public constructor(file: any, setStatus: any, offset: number = 0) {\n this.file = file;\n this.setStatus = setStatus;\n this.offset = offset;\n }\n\n public write(chunk: any) {\n const buffer = new ArrayBuffer(chunk.byteLength);\n new Uint8Array(buffer).set(chunk);\n\n // Inform MP4Box where in the file this chunk is from.\n (buffer as any).fileStart = this.offset;\n this.offset += buffer.byteLength;\n\n this.setStatus('fetch', (this.offset / 1024 ** 2).toFixed(1) + ' MiB');\n this.file.appendBuffer(buffer);\n }\n\n public close() {\n this.setStatus('fetch', 'Done');\n this.file.flush();\n }\n}\n","import {MP4FileSink} from './sink';\nimport type {Edit} from './utils';\n\nconst MAX_DECODE_QUEUE_SIZE = 30;\n\nexport class Segment {\n private done: boolean = false;\n private currentFramePastSegmentEndTime: boolean = false;\n private abortController = new AbortController();\n private uri: string;\n\n private file: any;\n private edit: Edit;\n\n private responseFinished: boolean = false;\n private decoder: VideoDecoder;\n\n private framesProcessed = 0;\n private startTime: number;\n private framesDue = 0;\n private frameBuffer: VideoFrame[] = [];\n private encodedChunkQueue: EncodedVideoChunk[] = [];\n\n private readMore: () => Promise<void> = async () => {};\n\n public constructor(\n uri: string,\n file: any,\n edits: Edit[],\n currentSegment: number,\n startTime: number = 0,\n ) {\n this.uri = uri;\n\n this.file = file;\n this.file.onSamples = this.onSamples.bind(this);\n this.edit = edits[currentSegment];\n\n this.startTime = startTime;\n\n // Check how many frames we skipped because of the startTime and add them to the frames processed.\n const framesSkipped = Math.floor(this.startTime * this.edit.fps);\n this.framesProcessed += framesSkipped;\n\n this.decoder = new VideoDecoder({\n output: this.onFrame.bind(this),\n error(e) {\n console.error(e);\n },\n });\n }\n\n public async start(decoderConfig: VideoDecoderConfig) {\n // If this is an empty edit, we just need to fill the buffer with empty frames.\n if (this.edit.mediaTime === -1) {\n this.done = true;\n this.responseFinished = true;\n this.decoder.close();\n\n const segmentDurationInSeconds =\n this.edit.segmentDuration /\n this.file.getInfo().videoTracks[0].movie_timescale;\n const framesToFill = Math.ceil(segmentDurationInSeconds * this.edit.fps);\n\n const height = this.file.getInfo().videoTracks[0].track_height;\n const width = this.file.getInfo().videoTracks[0].track_width;\n\n const bufferSize = height * width * 4;\n const buffer = new ArrayBuffer(bufferSize);\n const uint8Array = new Uint8Array(buffer);\n\n // Make the frame black\n uint8Array.fill(0);\n\n this.frameBuffer = Array.from({length: framesToFill}, () => {\n return new VideoFrame(uint8Array, {\n timestamp: 0,\n duration: 1 / this.edit.fps,\n codedHeight: height,\n codedWidth: width,\n format: 'BGRA',\n });\n });\n\n return;\n }\n\n this.decoder.configure(decoderConfig);\n const videoTrack = this.file.getInfo().videoTracks[0];\n const trak = this.file.getTrackById(videoTrack.id);\n\n const mediaTimeInTimescale = this.edit.mediaTime;\n const startTimeInTimescale = this.startTime * videoTrack.timescale;\n const seekTimeInTimescale = mediaTimeInTimescale + startTimeInTimescale;\n\n const seekTimeInSec = seekTimeInTimescale / videoTrack.timescale;\n const seekInfo = this.file.seekTrack(seekTimeInSec, true, trak);\n this.readMore = await this.startStreamingAtOffset(\n this.file,\n this.uri,\n seekInfo.offset,\n );\n }\n\n /**\n * Starts streaming the video at the given URI from the given offset.\n * @param file - MP4Box file. Needs to be created and configured before calling this function.\n * @param uri - URI of the video file.\n * @param offset - Offset to start streaming from.\n * @returns - A function to read more data from the response.\n */\n private async startStreamingAtOffset(file: any, uri: string, offset: number) {\n return fetch(uri, {\n headers: {\n /* eslint-disable-next-line @typescript-eslint/naming-convention */\n Range: `bytes=${offset}-`,\n },\n signal: this.abortController.signal,\n }).then(async response => {\n if (!response.body) {\n throw new Error('Response body is null');\n }\n\n const reader = response.body.getReader();\n const sink = new MP4FileSink(file, () => {}, offset);\n\n return async () => {\n return reader.read().then(({done, value}) => {\n // Request is done.\n if (done) {\n this.responseFinished = true;\n this.abortController.abort();\n sink.close();\n return;\n }\n\n sink.write(value);\n });\n };\n });\n }\n\n /**\n * Called when samples are available on the MP4 file.\n * Sends chunks to the decoder.\n */\n private onSamples(_unused1: any, _unused2: any, samples: any) {\n for (const sample of samples) {\n const chunk = new EncodedVideoChunk({\n type: sample.is_sync ? 'key' : 'delta',\n timestamp: (1e6 * sample.cts) / sample.timescale,\n duration: (1e6 * sample.duration) / sample.timescale,\n data: sample.data,\n });\n this.framesDue++;\n this.encodedChunkQueue.push(chunk);\n\n const videoTrack = this.file.getInfo().videoTracks[0];\n const trak = this.file.getTrackById(videoTrack.id);\n this.file.releaseSample(trak, sample.number);\n }\n }\n\n private async decodeChunks() {\n while (\n this.encodedChunkQueue.length > 0 &&\n this.decoder.decodeQueueSize < MAX_DECODE_QUEUE_SIZE\n ) {\n const chunk = this.encodedChunkQueue.shift();\n if (chunk) {\n this.decoder.decode(chunk);\n }\n }\n // When edit is empty, we cannot call decoder.flush() because decoder was already closed\n if (this.done) {\n this.currentFramePastSegmentEndTime = true;\n return;\n }\n if (this.responseFinished && this.encodedChunkQueue.length === 0) {\n await this.flushDecoderWithRetry();\n this.currentFramePastSegmentEndTime = true;\n return;\n }\n }\n\n private async flushDecoderWithRetry(maxRetries = 3, timeoutMs = 2000) {\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n // Sometimes decoder.flush does not resolve even though the queue size is zero\n if (this.decoder.decodeQueueSize === 0) {\n return;\n }\n try {\n await Promise.race([\n this.decoder.flush(),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Flush timeout')), timeoutMs),\n ),\n ]);\n } catch (error: any) {\n if (attempt === maxRetries) {\n throw error;\n }\n }\n }\n }\n\n /**\n * Called when the decoder has a frame ready.\n * Pushes the frame to the buffer so it can be consumed.\n */\n private async onFrame(frame: VideoFrame) {\n this.framesDue--;\n\n // If the frame comes before the seek time, close it.\n const mediaTimeInSec =\n this.edit.mediaTime / this.file.getInfo().videoTracks[0].timescale;\n const seekTimeInSec = this.startTime + mediaTimeInSec;\n const frameTimeInSec = frame.timestamp / 1e6;\n if (frameTimeInSec < seekTimeInSec) {\n frame.close();\n return;\n }\n\n // Check if we are past the segment duration.\n const segmentDurationInSec =\n this.edit.segmentDuration /\n this.file.getInfo().videoTracks[0].movie_timescale;\n const segmentEndTime = mediaTimeInSec + segmentDurationInSec;\n if (frameTimeInSec > segmentEndTime) {\n frame.close();\n this.done = true;\n await this.decoder.flush();\n return;\n }\n\n this.frameBuffer.push(frame);\n }\n\n private async populateBuffer() {\n // Fetch more frames if we don't have any.\n while (\n this.frameBuffer.length === 0 &&\n !this.currentFramePastSegmentEndTime\n ) {\n if (!this.responseFinished) {\n await this.readMore();\n }\n await this.decodeChunks();\n await new Promise(res => setTimeout(res, 0));\n }\n\n // Wait for decoder if there are frames due.\n if (this.frameBuffer.length === 0 && this.framesDue > 0) {\n let maxIterations = 200;\n while (this.frameBuffer.length === 0) {\n await new Promise(res => setTimeout(res, 10));\n maxIterations--;\n\n if (this.done) {\n return;\n }\n\n if (maxIterations === 0) {\n return; // TODO: investigate further, shouldn't this be an error?\n }\n }\n }\n }\n\n public async getNextFrame() {\n await this.populateBuffer();\n const frame = this.frameBuffer.shift();\n if (frame) {\n this.framesProcessed++;\n }\n return frame;\n }\n\n /**\n * Called when we are done with the extractor.\n */\n public async close() {\n this.abortController.abort();\n this.frameBuffer.forEach(frame => frame.close());\n try {\n if (this.decoder.state === 'configured') {\n await this.decoder.flush();\n this.decoder.close();\n }\n } catch (e) {\n // Ignore\n }\n }\n\n public getFramesProcessed() {\n return this.framesProcessed;\n }\n\n public getStartTime() {\n return this.startTime;\n }\n}\n","import {DataStream} from 'mp4box';\n\nexport function description(file: any, track: any) {\n const trak = file.getTrackById(track.id);\n for (const entry of trak.mdia.minf.stbl.stsd.entries) {\n const box = entry.avcC || entry.hvcC || entry.vpcC || entry.av1C;\n if (box) {\n const stream = new DataStream(undefined, 0, DataStream.BIG_ENDIAN);\n box.write(stream);\n return new Uint8Array(stream.buffer, 8); // Remove the box header.\n }\n }\n throw new Error('avcC, hvcC, vpcC, or av1C box not found');\n}\n\nexport interface Edit {\n mediaTime: number;\n segmentDuration: number;\n mediaRateInteger: number;\n mediaRateFraction: number;\n fps: number;\n}\n\nexport function mp4BoxEditToEdit(edit: any): Omit<Edit, 'fps'> {\n return {\n mediaTime: edit.media_time,\n segmentDuration: edit.segment_duration,\n mediaRateInteger: edit.media_rate_integer,\n mediaRateFraction: edit.media_rate_fraction,\n };\n}\n","import {Mp4Parser} from './parser';\n\n// List of VideoFrameExtractors\nconst videoFrameExtractors = new Map<string, Mp4Parser>();\n\nexport async function dropExtractor(id: string, filePath: string) {\n const extractorId = filePath + '-' + id;\n const extractor = videoFrameExtractors.get(extractorId);\n if (extractor) {\n extractor.close();\n videoFrameExtractors.delete(extractorId);\n }\n}\n\nexport async function getFrame(\n id: string,\n filePath: string,\n time: number,\n fps: number,\n) {\n // Check if we already have a VideoFrameExtractor for this video\n const extractorId = filePath + '-' + id;\n let extractor = videoFrameExtractors.get(extractorId);\n\n const frameDuration = 1 / fps;\n\n /**\n * Sometimes, HTMLVideoElement.duration is not accurate, which can lead to the\n * requested time being greater than the duration.\n * To prevent this, we clamp the time to the duration reported by the extractor.\n */\n const duration = extractor?.getDuration();\n if (duration && time > duration) {\n time = duration;\n }\n\n const isOldFrame =\n extractor && Math.abs(time - extractor.getLastTime()) < frameDuration / 2;\n\n // If time has not changed, return the last frame\n if (extractor && isOldFrame) {\n const lastFrame = extractor.getLastFrame();\n if (!lastFrame) {\n throw new Error('No last frame');\n }\n\n return lastFrame;\n }\n\n // If the video has skipped back we need to create a new extractor\n if (extractor && time + frameDuration < extractor.getTime()) {\n extractor.close();\n videoFrameExtractors.delete(extractorId);\n extractor = undefined;\n }\n\n // If the video has skipped forward we need to create a new extractor\n if (extractor && time > extractor.getTime() + frameDuration * 1.5) {\n extractor.close();\n videoFrameExtractors.delete(extractorId);\n extractor = undefined;\n }\n\n if (!extractor) {\n extractor = new Mp4Parser(filePath, fps, time);\n await extractor.start();\n videoFrameExtractors.set(extractorId, extractor);\n }\n\n // Go to the frame that is closest to the requested time\n return extractor.getNextFrame();\n}\n","import type {\n ComponentChildren,\n FunctionComponent,\n JSXProps,\n Node,\n NodeConstructor,\n} from './components';\n\nexport namespace JSX {\n export type Element = Node;\n export type ElementClass = Node;\n export interface ElementChildrenAttribute {\n children: any;\n }\n}\n\nfunction isClassComponent(\n // eslint-disable-next-line @typescript-eslint/ban-types\n fn: Function,\n): fn is new (...args: unknown[]) => unknown {\n return !!fn.prototype?.isClass;\n}\n\nexport const Fragment: FunctionComponent = ({children}) => children;\n\nexport function jsx(\n type: NodeConstructor | FunctionComponent | typeof Fragment,\n config: JSXProps,\n key?: any,\n): ComponentChildren {\n const {ref, children, ...rest} = config;\n const flatChildren = Array.isArray(children) ? children.flat() : children;\n\n if (type === Fragment) {\n return flatChildren;\n }\n\n if (isClassComponent(type)) {\n const node = new type({...rest, children: flatChildren, key});\n ref?.(node);\n return node;\n } else {\n return type({...rest, ref, children: flatChildren, key});\n }\n}\nexport {jsx as jsxs};\n","import type {\n AssetInfo,\n FullSceneDescription,\n Inspectable,\n InspectedAttributes,\n InspectedElement,\n Scene,\n ThreadGeneratorFactory,\n} from '@twick/core';\nimport {\n GeneratorScene,\n SceneRenderEvent,\n Vector2,\n transformVectorAsPoint,\n useLogger,\n} from '@twick/core';\nimport type {Node} from '../components';\nimport {Audio, Media, Video, View2D} from '../components';\n\nexport class Scene2D extends GeneratorScene<View2D> implements Inspectable {\n private view: View2D | null = null;\n private registeredNodes = new Map<string, Node>();\n private readonly nodeCounters = new Map<string, number>();\n private assetHash = Date.now().toString();\n\n public constructor(\n description: FullSceneDescription<ThreadGeneratorFactory<View2D>>,\n ) {\n super(description);\n this.recreateView();\n if (import.meta.hot) {\n import.meta.hot.on('twick:assets', () => {\n this.assetHash = Date.now().toString();\n this.getView().assetHash(this.assetHash);\n });\n }\n }\n\n public getView(): View2D {\n return this.view!;\n }\n\n public override next(): Promise<void> {\n this.getView()\n ?.playbackState(this.playback.state)\n .globalTime(this.playback.time);\n return super.next();\n }\n\n public async draw(context: CanvasRenderingContext2D) {\n context.save();\n this.renderLifecycle.dispatch([SceneRenderEvent.BeforeRender, context]);\n context.save();\n this.renderLifecycle.dispatch([SceneRenderEvent.BeginRender, context]);\n this.getView()\n .playbackState(this.playback.state)\n .globalTime(this.playback.time)\n .fps(this.playback.fps);\n await this.getView().render(context);\n this.renderLifecycle.dispatch([SceneRenderEvent.FinishRender, context]);\n context.restore();\n this.renderLifecycle.dispatch([SceneRenderEvent.AfterRender, context]);\n context.restore();\n }\n\n public override reset(previousScene?: Scene): Promise<void> {\n for (const key of this.registeredNodes.keys()) {\n try {\n this.registeredNodes.get(key)!.dispose();\n } catch (e: any) {\n this.logger.error(e);\n }\n }\n this.registeredNodes.clear();\n this.registeredNodes = new Map<string, Node>();\n this.nodeCounters.clear();\n this.recreateView();\n\n return super.reset(previousScene);\n }\n\n public inspectPosition(x: number, y: number): InspectedElement | null {\n const node = this.getNodeByPosition(x, y);\n return node?.key;\n }\n\n public getNodeByPosition(x: number, y: number): Node | null {\n return this.execute(() => this.getView().hit(new Vector2(x, y)) ?? null);\n }\n\n public validateInspection(\n element: InspectedElement | null,\n ): InspectedElement | null {\n return this.getNode(element)?.key ?? null;\n }\n\n public inspectAttributes(\n element: InspectedElement,\n ): InspectedAttributes | null {\n const node = this.getNode(element);\n if (!node) return null;\n\n const attributes: Record<string, any> = {\n stack: node.creationStack,\n key: node.key,\n };\n for (const {key, meta, signal} of node) {\n if (!meta.inspectable) continue;\n attributes[key] = signal();\n }\n\n return attributes;\n }\n\n public drawOverlay(\n element: InspectedElement,\n matrix: DOMMatrix,\n context: CanvasRenderingContext2D,\n ): void {\n const node = this.getNode(element);\n if (node) {\n this.execute(() => {\n node.drawOverlay(context, matrix.multiply(node.localToWorld()));\n });\n }\n }\n\n public transformMousePosition(x: number, y: number): Vector2 | null {\n return transformVectorAsPoint(\n new Vector2(x, y),\n this.getView().localToParent().inverse(),\n );\n }\n\n public registerNode(node: Node, key?: string): [string, () => void] {\n const className = node.constructor?.name ?? 'unknown';\n const counter = (this.nodeCounters.get(className) ?? 0) + 1;\n this.nodeCounters.set(className, counter);\n\n if (key && this.registeredNodes.has(key)) {\n useLogger().error({\n message: `Duplicated node key: \"${key}\".`,\n inspect: key,\n stack: new Error().stack,\n });\n key = undefined;\n }\n\n key ??= `${this.name}/${className}[${counter}]`;\n this.registeredNodes.set(key, node);\n const currentNodeMap = this.registeredNodes;\n return [key, () => currentNodeMap.delete(key!)];\n }\n\n public getNode(key: any): Node | null {\n if (typeof key !== 'string') return null;\n return this.registeredNodes.get(key) ?? null;\n }\n\n public *getDetachedNodes() {\n for (const node of this.registeredNodes.values()) {\n if (!node.parent() && node !== this.view) yield node;\n }\n }\n\n public override getMediaAssets(): Array<AssetInfo> {\n const playingVideos = Array.from(this.registeredNodes.values())\n .filter((node): node is Video => node instanceof Video)\n .filter(video => (video as Video).isPlaying());\n\n const playingAudios = Array.from(this.registeredNodes.values())\n .filter((node): node is Audio => node instanceof Audio)\n .filter(audio => (audio as Audio).isPlaying());\n\n const returnObjects: AssetInfo[] = [];\n\n returnObjects.push(\n ...playingVideos.map(vid => ({\n key: vid.key,\n type: 'video' as const,\n src: vid.src(),\n decoder: vid.decoder(),\n playbackRate:\n typeof vid.playbackRate === 'function'\n ? vid.playbackRate()\n : vid.playbackRate,\n volume: vid.getVolume(),\n currentTime: vid.getCurrentTime(),\n duration: vid.getDuration(),\n })),\n );\n\n returnObjects.push(\n ...playingAudios.map(audio => ({\n key: audio.key,\n type: 'audio' as const,\n src: audio.src(),\n playbackRate:\n typeof audio.playbackRate === 'function'\n ? audio.playbackRate()\n : audio.playbackRate,\n volume: audio.getVolume(),\n currentTime: audio.getCurrentTime(),\n duration: audio.getDuration(),\n })),\n );\n\n return returnObjects;\n }\n\n public override stopAllMedia() {\n const playingMedia = Array.from(this.registeredNodes.values())\n .filter((node): node is Media => node instanceof Media)\n .filter(video => (video as Media).isPlaying());\n\n for (const media of playingMedia) {\n media.dispose();\n }\n }\n\n public override adjustVolume(volumeScale: number) {\n const mediaNodes = Array.from(this.registeredNodes.values()).filter(\n (node): node is Media => node instanceof Media,\n );\n\n for (const media of mediaNodes) {\n media.setVolume(media.getVolume() * volumeScale);\n }\n }\n\n protected recreateView() {\n this.execute(() => {\n const size = this.getSize();\n this.view = new View2D({\n position: size.scale(this.resolutionScale / 2),\n scale: this.resolutionScale,\n assetHash: this.assetHash,\n size,\n });\n });\n }\n}\n","import type {DescriptionOf, ThreadGeneratorFactory} from '@twick/core';\nimport type {View2D} from '../components';\nimport {Scene2D} from './Scene2D';\n\nexport function makeScene2D(\n name: string,\n runner: ThreadGeneratorFactory<View2D>,\n): DescriptionOf<Scene2D> {\n return {\n klass: Scene2D,\n name,\n config: runner,\n stack: new Error().stack,\n plugins: ['@twick/2d/editor'],\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,aAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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,IAAI,MAAM,EAAE;AAAA,IACnB,SAAS,CAAC,kBAAkB;AAAA,EAC9B;AACF;","names":["SVG","import_core","lines","lines","lines","import_core","import_core","import_core","import_core","import_core","import_core","import_core","import_core","key","signal","initial","import_core","import_core","initial","parser","key","signal","radius","import_core","import_core","parse","import_core","initial","filter","lines","initial","t","import_highlight","parser","import_core","import_core","import_core","import_core","import_core","import_core","import_core","import_core","t","all","t","import_core","import_core","t","t","t","import_core","import_core","import_core","import_core","import_core","import_core","import_core","import_core","node","signal","key","matrix","blur","value","import_core","import_core","import_core","import_core","t","import_core","import_core","import_core","addSegment","import_core","line","import_core","initial","import_core","import_core","import_core","import_core","import_core","import_core","import_core","value","signal","import_core","import_core","addSegmentToProfile","updateMinSin","parse","import_core","import_core","import_core","RiveInitializer","import_core","signal","import_core","map","insert","remove","value","SVG","import_core","import_core","word","initial","import_core","import_meta","import_mp4box","Segment","Segment","import_meta","Hls","import_meta","import_core","import_meta","description","signal"]}
|