@canvas-commons/2d 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/editor/index.css +40 -0
- package/editor/index.js +525 -0
- package/editor/index.js.map +1 -0
- package/lib/index-OvpZ-GsA.d.ts +5673 -0
- package/lib/index-OvpZ-GsA.d.ts.map +1 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +10326 -0
- package/lib/index.js.map +1 -0
- package/lib/jsx-dev-runtime.d.ts +2 -0
- package/lib/jsx-dev-runtime.js +2 -0
- package/lib/jsx-runtime.d.ts +2 -0
- package/lib/jsx-runtime.js +28 -0
- package/lib/jsx-runtime.js.map +1 -0
- package/package.json +79 -0
- package/src/editor/NodeInspectorConfig.tsx +76 -0
- package/src/editor/PreviewOverlayConfig.tsx +65 -0
- package/src/editor/Provider.tsx +109 -0
- package/src/editor/SceneGraphTabConfig.tsx +87 -0
- package/src/editor/icons/CircleIcon.tsx +7 -0
- package/src/editor/icons/CodeIcon.tsx +8 -0
- package/src/editor/icons/CurveIcon.tsx +7 -0
- package/src/editor/icons/GridIcon.tsx +7 -0
- package/src/editor/icons/IconMap.ts +35 -0
- package/src/editor/icons/ImgIcon.tsx +8 -0
- package/src/editor/icons/LayoutIcon.tsx +9 -0
- package/src/editor/icons/LineIcon.tsx +7 -0
- package/src/editor/icons/NodeIcon.tsx +7 -0
- package/src/editor/icons/RayIcon.tsx +7 -0
- package/src/editor/icons/RectIcon.tsx +7 -0
- package/src/editor/icons/ShapeIcon.tsx +7 -0
- package/src/editor/icons/TxtIcon.tsx +8 -0
- package/src/editor/icons/VideoIcon.tsx +7 -0
- package/src/editor/icons/View2DIcon.tsx +10 -0
- package/src/editor/index.css +0 -0
- package/src/editor/index.ts +19 -0
- package/src/editor/shortcuts.ts +27 -0
- package/src/editor/tree/DetachedRoot.tsx +27 -0
- package/src/editor/tree/NodeElement.tsx +72 -0
- package/src/editor/tree/TreeElement.tsx +70 -0
- package/src/editor/tree/TreeRoot.tsx +10 -0
- package/src/editor/tree/ViewRoot.tsx +20 -0
- package/src/editor/tree/index.module.scss +45 -0
- package/src/editor/tree/index.ts +4 -0
- package/src/editor/tree/navigation.ts +145 -0
- package/src/editor/tsconfig.build.json +5 -0
- package/src/editor/tsconfig.json +12 -0
- package/src/editor/tsdoc.json +4 -0
- package/src/editor/utils/SignalSet.ts +37 -0
- package/src/editor/utils/index.ts +1 -0
- package/src/editor/vite-env.d.ts +1 -0
- package/src/lib/code/CodeCursor.ts +468 -0
- package/src/lib/code/CodeDiffer.ts +77 -0
- package/src/lib/code/CodeFragment.ts +96 -0
- package/src/lib/code/CodeHighlighter.ts +73 -0
- package/src/lib/code/CodeMetrics.ts +47 -0
- package/src/lib/code/CodeRange.test.ts +113 -0
- package/src/lib/code/CodeRange.ts +222 -0
- package/src/lib/code/CodeScope.ts +100 -0
- package/src/lib/code/CodeSelection.ts +28 -0
- package/src/lib/code/CodeSignal.ts +348 -0
- package/src/lib/code/CodeTokenizer.ts +54 -0
- package/src/lib/code/DefaultHighlightStyle.ts +98 -0
- package/src/lib/code/LezerHighlighter.ts +113 -0
- package/src/lib/code/diff.test.ts +311 -0
- package/src/lib/code/diff.ts +319 -0
- package/src/lib/code/extractRange.ts +125 -0
- package/src/lib/code/index.ts +13 -0
- package/src/lib/components/Bezier.ts +103 -0
- package/src/lib/components/Camera.ts +401 -0
- package/src/lib/components/Circle.ts +310 -0
- package/src/lib/components/Code.ts +532 -0
- package/src/lib/components/CubicBezier.ts +115 -0
- package/src/lib/components/Curve.ts +460 -0
- package/src/lib/components/Grid.ts +134 -0
- package/src/lib/components/Icon.ts +153 -0
- package/src/lib/components/Img.ts +328 -0
- package/src/lib/components/Knot.ts +156 -0
- package/src/lib/components/Latex.ts +537 -0
- package/src/lib/components/Layout.ts +1101 -0
- package/src/lib/components/Line.ts +394 -0
- package/src/lib/components/Node.ts +1941 -0
- package/src/lib/components/Path.ts +132 -0
- package/src/lib/components/Polygon.ts +266 -0
- package/src/lib/components/QuadBezier.ts +103 -0
- package/src/lib/components/Ray.ts +126 -0
- package/src/lib/components/Rect.ts +219 -0
- package/src/lib/components/SVG.ts +853 -0
- package/src/lib/components/Shape.ts +322 -0
- package/src/lib/components/Spline.ts +318 -0
- package/src/lib/components/Txt.test.tsx +81 -0
- package/src/lib/components/Txt.ts +204 -0
- package/src/lib/components/TxtLeaf.ts +210 -0
- package/src/lib/components/Video.ts +368 -0
- package/src/lib/components/View2D.ts +85 -0
- package/src/lib/components/__logs__/image-without-source.ts +18 -0
- package/src/lib/components/__logs__/line-without-points.ts +31 -0
- package/src/lib/components/__logs__/reactive-playback-rate.ts +22 -0
- package/src/lib/components/__logs__/spline-with-insufficient-knots.ts +25 -0
- package/src/lib/components/__tests__/Camera.test.tsx +73 -0
- package/src/lib/components/__tests__/children.test.tsx +142 -0
- package/src/lib/components/__tests__/clone.test.tsx +126 -0
- package/src/lib/components/__tests__/fontInheritance.test.tsx +102 -0
- package/src/lib/components/__tests__/generatorTest.ts +27 -0
- package/src/lib/components/__tests__/mockScene2D.ts +50 -0
- package/src/lib/components/__tests__/query.test.tsx +122 -0
- package/src/lib/components/__tests__/state.test.tsx +60 -0
- package/src/lib/components/index.ts +26 -0
- package/src/lib/components/types.ts +35 -0
- package/src/lib/curves/ArcSegment.ts +169 -0
- package/src/lib/curves/CircleSegment.ts +99 -0
- package/src/lib/curves/CubicBezierSegment.ts +80 -0
- package/src/lib/curves/CurveDrawingInfo.ts +11 -0
- package/src/lib/curves/CurvePoint.ts +15 -0
- package/src/lib/curves/CurveProfile.ts +28 -0
- package/src/lib/curves/KnotInfo.ts +10 -0
- package/src/lib/curves/LineSegment.ts +75 -0
- package/src/lib/curves/Polynomial.ts +355 -0
- package/src/lib/curves/Polynomial2D.ts +62 -0
- package/src/lib/curves/PolynomialSegment.ts +151 -0
- package/src/lib/curves/QuadBezierSegment.ts +66 -0
- package/src/lib/curves/Segment.ts +31 -0
- package/src/lib/curves/UniformPolynomialCurveSampler.ts +93 -0
- package/src/lib/curves/createCurveProfileLerp.ts +471 -0
- package/src/lib/curves/getBezierSplineProfile.ts +227 -0
- package/src/lib/curves/getCircleProfile.ts +86 -0
- package/src/lib/curves/getPathProfile.ts +177 -0
- package/src/lib/curves/getPointAtDistance.ts +21 -0
- package/src/lib/curves/getPolylineProfile.test.ts +21 -0
- package/src/lib/curves/getPolylineProfile.ts +88 -0
- package/src/lib/curves/getRectProfile.ts +138 -0
- package/src/lib/curves/index.ts +16 -0
- package/src/lib/decorators/canvasStyleSignal.ts +15 -0
- package/src/lib/decorators/colorSignal.ts +9 -0
- package/src/lib/decorators/compound.ts +85 -0
- package/src/lib/decorators/computed.ts +18 -0
- package/src/lib/decorators/defaultStyle.ts +15 -0
- package/src/lib/decorators/filtersSignal.ts +133 -0
- package/src/lib/decorators/index.ts +10 -0
- package/src/lib/decorators/initializers.ts +32 -0
- package/src/lib/decorators/nodeName.ts +13 -0
- package/src/lib/decorators/signal.test.ts +89 -0
- package/src/lib/decorators/signal.ts +348 -0
- package/src/lib/decorators/spacingSignal.ts +15 -0
- package/src/lib/decorators/transformSignals.test.ts +858 -0
- package/src/lib/decorators/transformSignals.ts +1633 -0
- package/src/lib/decorators/vector2Signal.ts +35 -0
- package/src/lib/globals.d.ts +2 -0
- package/src/lib/index.ts +9 -0
- package/src/lib/jsx-dev-runtime.ts +2 -0
- package/src/lib/jsx-runtime.ts +45 -0
- package/src/lib/morphers/PathMorpher.ts +8 -0
- package/src/lib/morphers/defaultMorpher.ts +43 -0
- package/src/lib/morphers/index.ts +4 -0
- package/src/lib/morphers/manimMorpher.ts +658 -0
- package/src/lib/parse-svg-path.d.ts +14 -0
- package/src/lib/partials/Filter.ts +185 -0
- package/src/lib/partials/Gradient.ts +103 -0
- package/src/lib/partials/Pattern.ts +35 -0
- package/src/lib/partials/RoughConfig.ts +180 -0
- package/src/lib/partials/ShaderConfig.ts +122 -0
- package/src/lib/partials/index.ts +5 -0
- package/src/lib/partials/types.ts +58 -0
- package/src/lib/scenes/Scene2D.ts +167 -0
- package/src/lib/scenes/index.ts +3 -0
- package/src/lib/scenes/makeScene2D.ts +19 -0
- package/src/lib/scenes/useScene2D.ts +6 -0
- package/src/lib/tsconfig.build.json +5 -0
- package/src/lib/tsconfig.json +11 -0
- package/src/lib/tsdoc.json +4 -0
- package/src/lib/utils/CanvasUtils.ts +304 -0
- package/src/lib/utils/PathDataBuilder.ts +320 -0
- package/src/lib/utils/diff.test.ts +453 -0
- package/src/lib/utils/diff.ts +148 -0
- package/src/lib/utils/index.ts +5 -0
- package/src/lib/utils/is.ts +11 -0
- package/src/lib/utils/makeSignalExtensions.ts +29 -0
- package/src/lib/utils/rough.ts +513 -0
- package/src/lib/utils/withDefaults.tsx +26 -0
- package/src/tsconfig.base.json +18 -0
- package/src/tsconfig.build.json +8 -0
- package/src/tsconfig.json +5 -0
- package/tsconfig.project.json +7 -0
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["addSegment","updateMinSin","addSegmentToProfile","imageWithoutSource","lineWithoutPoints","SVG","SVGNode","splineWithInsufficientKnots","reactivePlaybackRate","t"],"sources":["../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/CodeCursor.ts","../src/lib/code/diff.ts","../src/lib/code/CodeDiffer.ts","../src/lib/partials/Filter.ts","../src/lib/decorators/initializers.ts","../src/lib/decorators/computed.ts","../src/lib/utils/makeSignalExtensions.ts","../src/lib/decorators/signal.ts","../src/lib/decorators/compound.ts","../src/lib/decorators/vector2Signal.ts","../src/lib/partials/Gradient.ts","../src/lib/partials/Pattern.ts","../src/lib/partials/RoughConfig.ts","../src/lib/utils/CanvasUtils.ts","../src/lib/utils/is.ts","../src/lib/utils/PathDataBuilder.ts","../src/lib/utils/rough.ts","../src/lib/utils/withDefaults.tsx","../src/lib/decorators/canvasStyleSignal.ts","../src/lib/decorators/colorSignal.ts","../src/lib/decorators/defaultStyle.ts","../src/lib/decorators/filtersSignal.ts","../src/lib/decorators/nodeName.ts","../src/lib/curves/CurveProfile.ts","../src/lib/curves/getPointAtDistance.ts","../src/lib/decorators/spacingSignal.ts","../src/lib/decorators/transformSignals.ts","../src/lib/partials/ShaderConfig.ts","../src/lib/scenes/useScene2D.ts","../src/lib/components/Node.ts","../src/lib/components/Layout.ts","../src/lib/components/Shape.ts","../src/lib/components/Curve.ts","../src/lib/components/Bezier.ts","../src/lib/curves/Segment.ts","../src/lib/curves/CircleSegment.ts","../src/lib/curves/Polynomial.ts","../src/lib/curves/Polynomial2D.ts","../src/lib/curves/UniformPolynomialCurveSampler.ts","../src/lib/curves/PolynomialSegment.ts","../src/lib/curves/CubicBezierSegment.ts","../src/lib/curves/LineSegment.ts","../src/lib/curves/getRectProfile.ts","../src/lib/components/Rect.ts","../src/lib/components/Camera.ts","../src/lib/curves/QuadBezierSegment.ts","../src/lib/curves/getBezierSplineProfile.ts","../src/lib/components/View2D.ts","../src/lib/curves/ArcSegment.ts","../src/lib/curves/getCircleProfile.ts","../src/lib/curves/getPolylineProfile.ts","../src/lib/components/Circle.ts","../src/lib/components/Code.ts","../src/lib/components/CubicBezier.ts","../src/lib/components/Grid.ts","../src/lib/curves/createCurveProfileLerp.ts","../src/lib/curves/getPathProfile.ts","../src/lib/morphers/defaultMorpher.ts","../src/lib/morphers/manimMorpher.ts","../src/lib/utils/diff.ts","../src/lib/components/__logs__/image-without-source.ts","../src/lib/components/Img.ts","../src/lib/components/__logs__/line-without-points.ts","../src/lib/components/Line.ts","../src/lib/components/Path.ts","../src/lib/components/SVG.ts","../src/lib/components/Icon.ts","../src/lib/components/Knot.ts","../src/lib/components/Latex.ts","../src/lib/components/Polygon.ts","../src/lib/components/QuadBezier.ts","../src/lib/components/Ray.ts","../src/lib/components/__logs__/spline-with-insufficient-knots.ts","../src/lib/components/Spline.ts","../src/lib/components/TxtLeaf.ts","../src/lib/components/Txt.ts","../src/lib/components/__logs__/reactive-playback-rate.ts","../src/lib/components/Video.ts","../src/lib/code/CodeTokenizer.ts","../src/lib/code/extractRange.ts","../src/lib/code/CodeSignal.ts","../src/lib/code/DefaultHighlightStyle.ts","../src/lib/code/LezerHighlighter.ts","../src/lib/scenes/Scene2D.ts","../src/lib/scenes/makeScene2D.ts"],"sourcesContent":["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 {CodeMetrics, 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 {SignalValue, unwrap} from '@canvas-commons/core';\nimport {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","import escapeRegExpString from 'escape-string-regexp';\n\nexport 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 * When a string is passed, it looks for **exact matches**.\n * When a RegExp object is passed, it will match against it.\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(escapeRegExpString(pattern), 'g');\n } else {\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 {\n CodePoint,\n CodeRange,\n isCodeRange,\n isPointInCodeRange,\n} 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","import {\n clampRemap,\n Color,\n map,\n SerializedVector2,\n unwrap,\n Vector2,\n} from '@canvas-commons/core';\nimport {Code} from '../components';\nimport {CodeFragment, parseCodeFragment} from './CodeFragment';\nimport {CodeHighlighter} from './CodeHighlighter';\nimport {CodeMetrics} from './CodeMetrics';\nimport {CodePoint, CodeRange} from './CodeRange';\nimport {CodeScope, 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 tweenCursor = 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.tweenCursor = 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 isBigger =\n fragment.after.newRows > fragment.before.newRows ? 1 : -1;\n const isBefore = progress < 0.5 ? 1 : -1;\n const scale = isBigger * isBefore * 4;\n offsetY = map(\n Math.abs(fragment.after.newRows - fragment.before.newRows) / scale,\n 0,\n mirrored,\n );\n }\n\n this.drawToken(\n fragment,\n scope,\n this.cursor.addY(offsetY),\n this.tweenCursor,\n alpha,\n );\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 this.tweenCursor.y +=\n progress > 0.5 ? fragment.after.newRows : fragment.before.newRows;\n this.tweenCursor.x = progress > 0.5 ? afterEnd : beforeEnd;\n }\n }\n\n private drawToken(\n fragment: CodeFragment,\n scope: CodeScope,\n offset: SerializedVector2,\n tweenCursor: 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 (\n skipAhead < highlight.skipAhead &&\n code.content.charAt(i + skipAhead) !== '\\n'\n );\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 ? tweenCursor.x + stringLength : stringLength,\n tweenCursor.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","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 {CodeScope, CodeTag, resolveScope} from './CodeScope';\nimport {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 {\n createSignal,\n map,\n SignalValue,\n SimpleSignal,\n transformScalar,\n} from '@canvas-commons/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","const INITIALIZERS = Symbol.for('@canvas-commons/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 {createComputed} from '@canvas-commons/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","import {SignalExtensions, capitalize} from '@canvas-commons/core';\nimport {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 {\n capitalize,\n deepLerp,\n InterpolationFunction,\n SignalContext,\n SignalValue,\n TimingFunction,\n useLogger,\n} from '@canvas-commons/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('@canvas-commons/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 anchor: 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 anchor: Signal<Vector2, this>;\n *\n * // same as:\n * \\@parser(value => new Vector2(value))\n * \\@interpolation(Vector2.lerp)\n * \\@property()\n * public declare anchor: 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 {\n CompoundSignalContext,\n SignalContext,\n deepLerp,\n map,\n modify,\n useLogger,\n} from '@canvas-commons/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<\n TSetterValue,\n TValue extends TSetterValue,\n TKeys extends keyof TValue = keyof TValue,\n TOwner = void,\n>(\n entries: Record<string, string>,\n klass: typeof CompoundSignalContext<\n TSetterValue,\n TValue,\n TKeys,\n TOwner\n > = CompoundSignalContext,\n): 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 klass(\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 as TKeys, 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 {\n PossibleVector2,\n Signal,\n Vector2,\n Vector2SignalContext,\n} from '@canvas-commons/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 Vector2SignalContext,\n )(target, key);\n wrapper(Vector2)(target, key);\n };\n}\n","import {\n Color,\n PossibleColor,\n PossibleVector2,\n SignalValue,\n SimpleSignal,\n Vector2Signal,\n unwrap,\n} from '@canvas-commons/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 declare public readonly type: SimpleSignal<GradientType, this>;\n\n @vector2Signal('from')\n declare public readonly from: Vector2Signal<this>;\n\n @vector2Signal('to')\n declare public readonly to: Vector2Signal<this>;\n\n @initial(0)\n @signal()\n declare public readonly angle: SimpleSignal<number, this>;\n @initial(0)\n @signal()\n declare public readonly fromRadius: SimpleSignal<number, this>;\n @initial(0)\n @signal()\n declare public readonly toRadius: SimpleSignal<number, this>;\n @initial([])\n @signal()\n declare public 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 {SimpleSignal} from '@canvas-commons/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\n// TODO Support custom transformation matrices\nexport interface PatternProps {\n image: CanvasImageSource;\n repetition?: CanvasRepetition;\n}\n\nexport class Pattern {\n @signal()\n declare public readonly image: SimpleSignal<CanvasImageSource, this>;\n @initial(null)\n @signal()\n declare public 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 * Rough.js integration types for Canvas Commons\n *\n * @remarks\n * These types define the configuration options for rendering shapes with\n * a hand-drawn, sketchy appearance using Rough.js.\n */\n\n/**\n * Fill style options for rough shapes.\n *\n * @remarks\n * - `hachure`: Parallel lines filling the shape (default)\n * - `solid`: Solid fill with slight irregularity\n * - `zigzag`: Zigzag pattern filling\n * - `cross-hatch`: Crossed parallel lines\n * - `dots`: Dotted pattern filling\n * - `dashed`: Dashed lines filling\n * - `zigzag-line`: Zigzag lines filling\n */\nexport type RoughFillStyle =\n | 'hachure'\n | 'solid'\n | 'zigzag'\n | 'cross-hatch'\n | 'dots'\n | 'dashed'\n | 'zigzag-line';\n\n/**\n * Configuration options for rough rendering.\n *\n * @remarks\n * These options control the appearance of the hand-drawn style.\n * All numeric values can be animated using signals.\n */\nexport interface RoughConfig {\n /**\n * Numerical value indicating how rough the drawing is.\n *\n * @remarks\n * A value of 0 will produce a smooth shape, while higher values\n * introduce more irregularity. Typical range is 0-10.\n *\n * @defaultValue 1\n */\n roughness: number;\n\n /**\n * Controls the curve deviation from a straight line.\n *\n * @remarks\n * A value of 0 will cause lines to be perfectly straight.\n * Higher values introduce more curvature.\n *\n * @defaultValue 1\n */\n bowing: number;\n\n /**\n * Seed for the random number generator.\n *\n * @remarks\n * Using the same seed produces consistent results, which is useful\n * for reproducible animations.\n */\n seed?: number;\n\n /**\n * Fill style for the shape.\n *\n * @defaultValue 'hachure'\n */\n fillStyle: RoughFillStyle;\n\n /**\n * Thickness of the lines used for filling.\n *\n * @remarks\n * Only applicable for hachure, cross-hatch, and similar fill styles.\n *\n * @defaultValue Half of strokeWidth, or 1\n */\n fillWeight?: number;\n\n /**\n * Angle of the hachure lines in degrees.\n *\n * @remarks\n * Only applicable for hachure and cross-hatch fill styles.\n *\n * @defaultValue -41\n */\n hachureAngle: number;\n\n /**\n * Gap between hachure lines in pixels.\n *\n * @remarks\n * Only applicable for hachure, cross-hatch, and similar fill styles.\n *\n * @defaultValue 4 times strokeWidth\n */\n hachureGap: number;\n\n /**\n * Curve tightness for hachure lines.\n *\n * @remarks\n * Lower values create more curved hachure lines.\n *\n * @defaultValue 0.95\n */\n curveStepCount?: number;\n\n /**\n * Simplification tolerance for paths.\n *\n * @remarks\n * Higher values simplify the path more aggressively.\n *\n * @defaultValue 0\n */\n simplification?: number;\n\n /**\n * Whether to disable multi-stroke rendering.\n *\n * @remarks\n * By default, Rough.js renders strokes with multiple lines for a\n * more sketchy appearance. Set to true to use a single stroke.\n *\n * @defaultValue false\n */\n disableMultiStroke?: boolean;\n\n /**\n * Whether to disable multi-stroke fill.\n *\n * @remarks\n * By default, Rough.js renders fills with multiple passes.\n * Set to true to use a single fill pass.\n *\n * @defaultValue false\n */\n disableMultiStrokeFill?: boolean;\n}\n\n/**\n * Partial rough configuration with defaults applied.\n */\nexport type PartialRoughConfig = Partial<RoughConfig>;\n\n/**\n * Get default rough configuration.\n *\n * @returns Default configuration values\n */\nexport function getDefaultRoughConfig(): RoughConfig {\n return {\n roughness: 1,\n bowing: 1,\n fillStyle: 'hachure',\n hachureAngle: -41,\n hachureGap: 4,\n };\n}\n\n/**\n * Merge partial rough configuration with defaults.\n *\n * @param config - Partial configuration to merge\n * @returns Complete configuration with defaults applied\n */\nexport function mergeRoughConfig(config: PartialRoughConfig): RoughConfig {\n return {\n ...getDefaultRoughConfig(),\n ...config,\n };\n}\n","import {BBox, Color, Spacing, Vector2} from '@canvas-commons/core';\nimport {CanvasStyle, Gradient, Pattern, PossibleCanvasStyle} 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","/**\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 {Vector2} from '@canvas-commons/core';\n\n/**\n * A builder for constructing SVG path data strings.\n *\n * @remarks\n * This class provides a fluent API for building SVG path data, which can be\n * used to create Path2D objects or passed to other renderers like Rough.js.\n *\n * @example\n * ```ts\n * const builder = new PathDataBuilder();\n * builder.moveTo(0, 0).lineTo(100, 100).closePath();\n * const pathData = builder.toString(); // \"M 0 0 L 100 100 Z\"\n * const path = new Path2D(pathData);\n * ```\n */\nexport class PathDataBuilder {\n private commands: string[] = [];\n\n /**\n * Move to a point without drawing.\n *\n * @param x - The x coordinate\n * @param y - The y coordinate\n */\n public moveTo(x: number, y: number): this {\n this.commands.push(`M ${x} ${y}`);\n return this;\n }\n\n /**\n * Draw a line to a point.\n *\n * @param x - The x coordinate\n * @param y - The y coordinate\n */\n public lineTo(x: number, y: number): this {\n this.commands.push(`L ${x} ${y}`);\n return this;\n }\n\n /**\n * Draw a cubic Bezier curve.\n *\n * @param cp1x - First control point x\n * @param cp1y - First control point y\n * @param cp2x - Second control point x\n * @param cp2y - Second control point y\n * @param x - End point x\n * @param y - End point y\n */\n public bezierCurveTo(\n cp1x: number,\n cp1y: number,\n cp2x: number,\n cp2y: number,\n x: number,\n y: number,\n ): this {\n this.commands.push(`C ${cp1x} ${cp1y} ${cp2x} ${cp2y} ${x} ${y}`);\n return this;\n }\n\n /**\n * Draw a quadratic Bezier curve.\n *\n * @param cpx - Control point x\n * @param cpy - Control point y\n * @param x - End point x\n * @param y - End point y\n */\n public quadraticCurveTo(\n cpx: number,\n cpy: number,\n x: number,\n y: number,\n ): this {\n this.commands.push(`Q ${cpx} ${cpy} ${x} ${y}`);\n return this;\n }\n\n /**\n * Draw an elliptical arc.\n *\n * @remarks\n * Converts canvas ellipse parameters to SVG arc commands. For full ellipses,\n * this generates two arc commands to work around SVG's limitation of 180-degree\n * maximum arc sweeps.\n *\n * @param x - Center x coordinate\n * @param y - Center y coordinate\n * @param radiusX - Horizontal radius\n * @param radiusY - Vertical radius\n * @param rotation - Rotation angle in radians\n * @param startAngle - Start angle in radians\n * @param endAngle - End angle in radians\n * @param counterclockwise - Whether to draw counterclockwise\n */\n public ellipse(\n x: number,\n y: number,\n radiusX: number,\n radiusY: number,\n rotation: number,\n startAngle: number,\n endAngle: number,\n counterclockwise = false,\n ): this {\n const start = startAngle;\n const end = endAngle;\n\n let angleDiff = end - start;\n if (counterclockwise && angleDiff > 0) {\n angleDiff -= 2 * Math.PI;\n } else if (!counterclockwise && angleDiff < 0) {\n angleDiff += 2 * Math.PI;\n }\n\n const startPoint = Vector2.fromRadians(start).mul(\n new Vector2(radiusX, radiusY),\n );\n const rotatedStart = startPoint.rotate(rotation);\n const startX = x + rotatedStart.x;\n const startY = y + rotatedStart.y;\n\n const endPoint = Vector2.fromRadians(end).mul(\n new Vector2(radiusX, radiusY),\n );\n const rotatedEnd = endPoint.rotate(rotation);\n const endX = x + rotatedEnd.x;\n const endY = y + rotatedEnd.y;\n\n if (this.commands.length === 0) {\n this.moveTo(startX, startY);\n } else {\n this.lineTo(startX, startY);\n }\n\n // Determine if this is a large arc (> 180 degrees)\n const largeArc = Math.abs(angleDiff) > Math.PI ? 1 : 0;\n const sweep = counterclockwise ? 0 : 1;\n\n // Convert rotation from radians to degrees\n const rotationDeg = (rotation * 180) / Math.PI;\n\n if (Math.abs(Math.abs(angleDiff) - 2 * Math.PI) < 0.001) {\n const midAngle = start + angleDiff / 2;\n const midPoint = Vector2.fromRadians(midAngle).mul(\n new Vector2(radiusX, radiusY),\n );\n const rotatedMid = midPoint.rotate(rotation);\n const midX = x + rotatedMid.x;\n const midY = y + rotatedMid.y;\n\n this.commands.push(\n `A ${radiusX} ${radiusY} ${rotationDeg} 0 ${sweep} ${midX} ${midY}`,\n );\n this.commands.push(\n `A ${radiusX} ${radiusY} ${rotationDeg} 0 ${sweep} ${endX} ${endY}`,\n );\n } else {\n // Partial arc\n this.commands.push(\n `A ${radiusX} ${radiusY} ${rotationDeg} ${largeArc} ${sweep} ${endX} ${endY}`,\n );\n }\n\n return this;\n }\n\n /**\n * Draw a circular arc using the arc command.\n *\n * @remarks\n * This is a convenience method that calls {@link ellipse} with equal radii.\n *\n * @param x - Center x coordinate\n * @param y - Center y coordinate\n * @param radius - Arc radius\n * @param startAngle - Start angle in radians\n * @param endAngle - End angle in radians\n * @param counterclockwise - Whether to draw counterclockwise\n */\n public arc(\n x: number,\n y: number,\n radius: number,\n startAngle: number,\n endAngle: number,\n counterclockwise = false,\n ): this {\n return this.ellipse(\n x,\n y,\n radius,\n radius,\n 0,\n startAngle,\n endAngle,\n counterclockwise,\n );\n }\n\n /**\n * Draw an arc to a point with a given radius.\n *\n * @remarks\n * This matches the Canvas API's arcTo method. It draws a straight line from\n * the current point to the start of an arc, then draws an arc with the given\n * radius that is tangent to the line from the current point to (x1, y1) and\n * the line from (x1, y1) to (x2, y2).\n *\n * @param x1 - First control point x\n * @param y1 - First control point y\n * @param x2 - Second control point x\n * @param y2 - Second control point y\n * @param radius - Arc radius\n */\n public arcTo(\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n radius: number,\n ): this {\n if (this.commands.length === 0) {\n this.moveTo(x1, y1);\n return this;\n }\n\n const lastCommand = this.commands[this.commands.length - 1];\n const coords = lastCommand.split(' ').slice(1).map(Number);\n const p0 = new Vector2(\n coords[coords.length - 2],\n coords[coords.length - 1],\n );\n const p1 = new Vector2(x1, y1);\n const p2 = new Vector2(x2, y2);\n\n const v1 = p0.sub(p1);\n const v2 = p2.sub(p1);\n\n const v1Length = v1.magnitude;\n const v2Length = v2.magnitude;\n\n if (v1Length === 0 || v2Length === 0) {\n this.lineTo(x1, y1);\n return this;\n }\n\n const v1n = v1.normalized;\n const v2n = v2.normalized;\n\n const angle = Math.acos(v1n.dot(v2n));\n\n if (Math.abs(angle) < 0.0001 || Math.abs(angle - Math.PI) < 0.0001) {\n this.lineTo(x1, y1);\n return this;\n }\n\n const tangentLength = radius / Math.tan(angle / 2);\n\n const t1 = p1.add(v1n.scale(tangentLength));\n const t2 = p1.add(v2n.scale(tangentLength));\n\n this.lineTo(t1.x, t1.y);\n\n const bisector = v1n.add(v2n).normalized;\n const centerDistance = radius / Math.sin(angle / 2);\n const center = p1.add(bisector.scale(centerDistance));\n\n const startAngle = Math.atan2(t1.y - center.y, t1.x - center.x);\n const endAngle = Math.atan2(t2.y - center.y, t2.x - center.x);\n\n let angleDiff = endAngle - startAngle;\n const cross = v1n.x * v2n.y - v1n.y * v2n.x;\n const counterclockwise = cross > 0;\n\n if (counterclockwise && angleDiff > 0) {\n angleDiff -= 2 * Math.PI;\n } else if (!counterclockwise && angleDiff < 0) {\n angleDiff += 2 * Math.PI;\n }\n\n const largeArc = Math.abs(angleDiff) > Math.PI ? 1 : 0;\n const sweep = counterclockwise ? 0 : 1;\n\n this.commands.push(\n `A ${radius} ${radius} 0 ${largeArc} ${sweep} ${t2.x} ${t2.y}`,\n );\n\n return this;\n }\n\n /**\n * Close the current path.\n */\n public closePath(): this {\n this.commands.push('Z');\n return this;\n }\n\n /**\n * Get the SVG path data string.\n *\n * @returns The complete SVG path data\n */\n public toString(): string {\n return this.commands.join(' ');\n }\n\n /**\n * Reset the builder to empty state.\n */\n public clear(): this {\n this.commands = [];\n return this;\n }\n}\n","import {BBox, Spacing, Vector2} from '@canvas-commons/core';\nimport rough from 'roughjs';\nimport type {RoughCanvas} from 'roughjs/bin/canvas';\nimport type {Drawable, Options} from 'roughjs/bin/core';\nimport {RoughConfig, RoughFillStyle} from '../partials';\nimport {PossibleCanvasStyle} from '../partials/types';\nimport {\n adjustRectRadius,\n canvasStyleParser,\n resolveCanvasStyle,\n} from './CanvasUtils';\n\n// Export Drawable type for use in other modules\nexport type {Drawable};\n\n/**\n * Cache for RoughCanvas instances per canvas element.\n *\n * @remarks\n * We cache RoughCanvas instances to avoid recreating them for each draw call.\n */\nconst RoughCanvasCache = new WeakMap<HTMLCanvasElement, RoughCanvas>();\n\n/**\n * Get or create a RoughCanvas instance for the given canvas context.\n *\n * @param context - The 2D rendering context\n * @returns A RoughCanvas instance for drawing rough shapes\n */\nfunction getRoughCanvas(context: CanvasRenderingContext2D): RoughCanvas {\n const canvas = context.canvas;\n let rc = RoughCanvasCache.get(canvas);\n\n if (!rc) {\n rc = rough.canvas(canvas);\n RoughCanvasCache.set(canvas, rc);\n }\n\n return rc;\n}\n\n/**\n * Convert Canvas Commons fill style to a color string for Rough.js.\n *\n * @param style - The fill style (color, gradient, or pattern)\n * @param context - The rendering context\n * @returns A color string or undefined\n */\nfunction styleToColor(\n style: PossibleCanvasStyle | null,\n context: CanvasRenderingContext2D,\n): string | undefined {\n if (style === null) {\n return undefined;\n }\n\n // Parse the style to CanvasStyle\n const parsedStyle = canvasStyleParser(style);\n\n if (parsedStyle === null) {\n return undefined;\n }\n\n // Resolve to canvas-compatible format\n const resolvedStyle = resolveCanvasStyle(parsedStyle, context);\n\n // Rough.js only accepts string colors, not gradients or patterns\n // For gradients and patterns, return undefined (rough.js will use default)\n if (typeof resolvedStyle === 'string') {\n return resolvedStyle;\n }\n\n return undefined;\n}\n\n/**\n * Convert Canvas Commons rough config to Rough.js options.\n *\n * @param config - Canvas Commons rough configuration\n * @param fill - Fill style from shape\n * @param stroke - Stroke style from shape\n * @param strokeWidth - Line width from shape\n * @param context - The rendering context\n * @returns Rough.js options object\n */\nfunction configToRoughOptions(\n config: Partial<RoughConfig>,\n fill: PossibleCanvasStyle | null,\n stroke: PossibleCanvasStyle | null,\n strokeWidth: number,\n context: CanvasRenderingContext2D,\n): Options {\n const options: Options = {\n roughness: config.roughness ?? 1,\n bowing: config.bowing ?? 1,\n seed: config.seed,\n stroke: styleToColor(stroke, context),\n strokeWidth: strokeWidth,\n fill: styleToColor(fill, context),\n fillStyle: config.fillStyle ?? 'hachure',\n fillWeight: config.fillWeight,\n hachureAngle: config.hachureAngle ?? -41,\n hachureGap: config.hachureGap ?? strokeWidth * 4,\n curveStepCount: config.curveStepCount,\n simplification: config.simplification,\n disableMultiStroke: config.disableMultiStroke,\n disableMultiStrokeFill: config.disableMultiStrokeFill,\n };\n\n return options;\n}\n\n/**\n * Convert a rounded rectangle to SVG path data.\n *\n * @param box - The bounding box of the rectangle\n * @param radius - Corner radius values\n * @param smoothCorners - Whether to use smooth corners (bezier curves)\n * @param cornerSharpness - Sharpness of smooth corners\n * @returns SVG path data string\n */\nexport function roundedRectToSVGPath(\n box: BBox,\n radius: Spacing,\n smoothCorners: boolean,\n cornerSharpness: number,\n): string {\n const topLeft = adjustRectRadius(radius.top, radius.right, radius.left, box);\n const topRight = adjustRectRadius(\n radius.right,\n radius.top,\n radius.bottom,\n box,\n );\n const bottomRight = adjustRectRadius(\n radius.bottom,\n radius.left,\n radius.right,\n box,\n );\n const bottomLeft = adjustRectRadius(\n radius.left,\n radius.bottom,\n radius.top,\n box,\n );\n\n if (smoothCorners) {\n const sharpness = (r: number): number => {\n const val = r * cornerSharpness;\n return r - val;\n };\n\n // Build SVG path with bezier curves for smooth corners\n return [\n `M ${box.left + topLeft} ${box.top}`,\n `L ${box.right - topRight} ${box.top}`,\n `C ${box.right - sharpness(topRight)} ${box.top} ${box.right} ${box.top + sharpness(topRight)} ${box.right} ${box.top + topRight}`,\n `L ${box.right} ${box.bottom - bottomRight}`,\n `C ${box.right} ${box.bottom - sharpness(bottomRight)} ${box.right - sharpness(bottomRight)} ${box.bottom} ${box.right - bottomRight} ${box.bottom}`,\n `L ${box.left + bottomLeft} ${box.bottom}`,\n `C ${box.left + sharpness(bottomLeft)} ${box.bottom} ${box.left} ${box.bottom - sharpness(bottomLeft)} ${box.left} ${box.bottom - bottomLeft}`,\n `L ${box.left} ${box.top + topLeft}`,\n `C ${box.left} ${box.top + sharpness(topLeft)} ${box.left + sharpness(topLeft)} ${box.top} ${box.left + topLeft} ${box.top}`,\n 'Z',\n ].join(' ');\n }\n\n // For regular rounded corners, we need to use arcs\n // SVG arc command: A rx ry x-axis-rotation large-arc-flag sweep-flag x y\n // Canvas arcTo draws a 90-degree arc, so we use: A r r 0 0 1 x y\n const pathParts: string[] = [];\n\n // Start at top-left corner (after the radius)\n pathParts.push(`M ${box.left + topLeft} ${box.top}`);\n\n // Top edge to top-right corner\n pathParts.push(`L ${box.right - topRight} ${box.top}`);\n if (topRight > 0) {\n pathParts.push(\n `A ${topRight} ${topRight} 0 0 1 ${box.right} ${box.top + topRight}`,\n );\n }\n\n // Right edge to bottom-right corner\n pathParts.push(`L ${box.right} ${box.bottom - bottomRight}`);\n if (bottomRight > 0) {\n pathParts.push(\n `A ${bottomRight} ${bottomRight} 0 0 1 ${box.right - bottomRight} ${box.bottom}`,\n );\n }\n\n // Bottom edge to bottom-left corner\n pathParts.push(`L ${box.left + bottomLeft} ${box.bottom}`);\n if (bottomLeft > 0) {\n pathParts.push(\n `A ${bottomLeft} ${bottomLeft} 0 0 1 ${box.left} ${box.bottom - bottomLeft}`,\n );\n }\n\n // Left edge to top-left corner\n pathParts.push(`L ${box.left} ${box.top + topLeft}`);\n if (topLeft > 0) {\n pathParts.push(\n `A ${topLeft} ${topLeft} 0 0 1 ${box.left + topLeft} ${box.top}`,\n );\n }\n\n // Close the path\n pathParts.push('Z');\n\n return pathParts.join(' ');\n}\n\n/**\n * Generate a rough rectangle drawable.\n *\n * @param context - The 2D rendering context\n * @param box - The bounding box of the rectangle\n * @param config - Rough configuration\n * @param fill - Fill style\n * @param stroke - Stroke style\n * @param strokeWidth - Line width\n * @returns A Drawable object that can be cached and drawn\n */\nexport function generateRoughRect(\n context: CanvasRenderingContext2D,\n box: BBox,\n config: Partial<RoughConfig>,\n fill: PossibleCanvasStyle | null,\n stroke: PossibleCanvasStyle | null,\n strokeWidth: number,\n): Drawable {\n const rc = getRoughCanvas(context);\n const options = configToRoughOptions(\n config,\n fill,\n stroke,\n strokeWidth,\n context,\n );\n\n // Rough.js draws from top-left, canvas-commons uses center origin\n const x = box.x;\n const y = box.y;\n const width = box.width;\n const height = box.height;\n\n return rc.generator.rectangle(x, y, width, height, options);\n}\n\n/**\n * Draw a rough rectangle.\n *\n * @param context - The 2D rendering context\n * @param box - The bounding box of the rectangle\n * @param config - Rough configuration\n * @param fill - Fill style\n * @param stroke - Stroke style\n * @param strokeWidth - Line width\n */\nexport function drawRoughRect(\n context: CanvasRenderingContext2D,\n box: BBox,\n config: Partial<RoughConfig>,\n fill: PossibleCanvasStyle | null,\n stroke: PossibleCanvasStyle | null,\n strokeWidth: number,\n): void {\n const drawable = generateRoughRect(\n context,\n box,\n config,\n fill,\n stroke,\n strokeWidth,\n );\n const rc = getRoughCanvas(context);\n rc.draw(drawable);\n}\n\n/**\n * Draw a cached rough drawable.\n *\n * @param context - The 2D rendering context\n * @param drawable - The cached drawable to render\n */\nexport function drawRoughDrawable(\n context: CanvasRenderingContext2D,\n drawable: Drawable,\n): void {\n const rc = getRoughCanvas(context);\n rc.draw(drawable);\n}\n\n/**\n * Generate a rough rounded rectangle drawable.\n *\n * @param context - The 2D rendering context\n * @param box - The bounding box of the rectangle\n * @param radius - Corner radius values\n * @param smoothCorners - Whether to use smooth corners\n * @param cornerSharpness - Sharpness of smooth corners\n * @param config - Rough configuration\n * @param fill - Fill style\n * @param stroke - Stroke style\n * @param strokeWidth - Line width\n * @returns A Drawable object that can be cached and drawn\n */\nexport function generateRoughRoundedRect(\n context: CanvasRenderingContext2D,\n box: BBox,\n radius: Spacing,\n smoothCorners: boolean,\n cornerSharpness: number,\n config: Partial<RoughConfig>,\n fill: PossibleCanvasStyle | null,\n stroke: PossibleCanvasStyle | null,\n strokeWidth: number,\n): Drawable {\n // Convert the rounded rectangle to SVG path data\n const pathData = roundedRectToSVGPath(\n box,\n radius,\n smoothCorners,\n cornerSharpness,\n );\n\n // Generate using rough path\n return generateRoughPath(\n context,\n pathData,\n config,\n fill,\n stroke,\n strokeWidth,\n );\n}\n\n/**\n * Draw a rough rounded rectangle.\n *\n * @param context - The 2D rendering context\n * @param box - The bounding box of the rectangle\n * @param radius - Corner radius values\n * @param smoothCorners - Whether to use smooth corners\n * @param cornerSharpness - Sharpness of smooth corners\n * @param config - Rough configuration\n * @param fill - Fill style\n * @param stroke - Stroke style\n * @param strokeWidth - Line width\n */\nexport function drawRoughRoundedRect(\n context: CanvasRenderingContext2D,\n box: BBox,\n radius: Spacing,\n smoothCorners: boolean,\n cornerSharpness: number,\n config: Partial<RoughConfig>,\n fill: PossibleCanvasStyle | null,\n stroke: PossibleCanvasStyle | null,\n strokeWidth: number,\n): void {\n const drawable = generateRoughRoundedRect(\n context,\n box,\n radius,\n smoothCorners,\n cornerSharpness,\n config,\n fill,\n stroke,\n strokeWidth,\n );\n drawRoughDrawable(context, drawable);\n}\n\n/**\n * Draw a rough circle/ellipse.\n *\n * @param context - The 2D rendering context\n * @param center - Center point of the circle\n * @param size - Size (width and height) of the ellipse\n * @param config - Rough configuration\n * @param fill - Fill style\n * @param stroke - Stroke style\n * @param strokeWidth - Line width\n */\nexport function drawRoughCircle(\n context: CanvasRenderingContext2D,\n center: Vector2,\n size: Vector2,\n config: Partial<RoughConfig>,\n fill: PossibleCanvasStyle | null,\n stroke: PossibleCanvasStyle | null,\n strokeWidth: number,\n): void {\n const rc = getRoughCanvas(context);\n const options = configToRoughOptions(\n config,\n fill,\n stroke,\n strokeWidth,\n context,\n );\n\n const drawable = rc.generator.ellipse(\n center.x,\n center.y,\n size.x * 2,\n size.y * 2,\n options,\n );\n rc.draw(drawable);\n}\n\n/**\n * Generate a rough path drawable from SVG path data.\n *\n * @param context - The 2D rendering context\n * @param pathData - SVG path string\n * @param config - Rough configuration\n * @param fill - Fill style\n * @param stroke - Stroke style\n * @param strokeWidth - Line width\n * @returns A Drawable object that can be cached and drawn\n */\nexport function generateRoughPath(\n context: CanvasRenderingContext2D,\n pathData: string,\n config: Partial<RoughConfig>,\n fill: PossibleCanvasStyle | null,\n stroke: PossibleCanvasStyle | null,\n strokeWidth: number,\n): Drawable {\n const rc = getRoughCanvas(context);\n const options = configToRoughOptions(\n config,\n fill,\n stroke,\n strokeWidth,\n context,\n );\n\n return rc.generator.path(pathData, options);\n}\n\n/**\n * Draw a rough path from SVG path data.\n *\n * @param context - The 2D rendering context\n * @param pathData - SVG path string\n * @param config - Rough configuration\n * @param fill - Fill style\n * @param stroke - Stroke style\n * @param strokeWidth - Line width\n */\nexport function drawRoughPath(\n context: CanvasRenderingContext2D,\n pathData: string,\n config: Partial<RoughConfig>,\n fill: PossibleCanvasStyle | null,\n stroke: PossibleCanvasStyle | null,\n strokeWidth: number,\n): void {\n const drawable = generateRoughPath(\n context,\n pathData,\n config,\n fill,\n stroke,\n strokeWidth,\n );\n drawRoughDrawable(context, drawable);\n}\n\n/**\n * Helper to create rough config from individual signals.\n *\n * @param roughness - Roughness value\n * @param bowing - Bowing value\n * @param fillStyle - Fill style\n * @param fillWeight - Fill weight\n * @param hachureAngle - Hachure angle\n * @param hachureGap - Hachure gap\n * @param seed - Random seed (always defined, generated from useRandom if not specified)\n * @param disableMultiStroke - Disable multiple strokes for stroke\n * @param disableMultiStrokeFill - Disable multiple strokes for fill\n * @returns Partial rough configuration\n */\nexport function createRoughConfig(\n roughness: number,\n bowing: number,\n fillStyle: RoughFillStyle,\n fillWeight: number | undefined,\n hachureAngle: number,\n hachureGap: number,\n seed: number,\n disableMultiStroke: boolean,\n disableMultiStrokeFill: boolean,\n): Partial<RoughConfig> {\n return {\n roughness,\n bowing,\n fillStyle,\n fillWeight,\n hachureAngle,\n hachureGap,\n seed,\n disableMultiStroke,\n disableMultiStrokeFill,\n };\n}\n","import {FunctionComponent, NodeConstructor, PropsOf} from '../components';\n\n/**\n * Create a higher order component with default props.\n *\n * @example\n * ```tsx\n * const MyTxt = withDefaults(Txt, {\n * fill: '#f3303f',\n * });\n *\n * // ...\n *\n * view.add(<MyTxt>Hello, World!</MyTxt>);\n * ```\n *\n * @param component - The base class or function component to wrap.\n * @param defaults - The default props to apply.\n */\nexport function withDefaults<T extends FunctionComponent | NodeConstructor>(\n component: T,\n defaults: PropsOf<T>,\n) {\n const Node = component;\n return (props: PropsOf<T>) => <Node {...defaults} {...props} />;\n}\n","import {Color, Signal} from '@canvas-commons/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 {Color} from '@canvas-commons/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 '@canvas-commons/core';\nimport {Layout} from '../components';\n\nexport function defaultStyle<T>(initial?: T): PropertyDecorator {\n return (target: any, key) => {\n target[`getDefault${capitalize(<string>key)}`] = function (this: Layout) {\n const parent = this.parentTransform();\n if (parent && this.layout() !== false) {\n return (parent as any)[key]();\n }\n\n return initial;\n };\n };\n}\n","import {\n Signal,\n SignalContext,\n SignalValue,\n SimpleSignal,\n ThreadGenerator,\n TimingFunction,\n all,\n deepLerp,\n easeInOutCubic,\n unwrap,\n} from '@canvas-commons/core';\nimport {FILTERS, Filter, FilterName} 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('@canvas-commons/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","import {Segment} from './Segment';\n\nexport interface CurveProfile {\n arcLength: number;\n segments: Segment[];\n minSin: number;\n}\n\n/**\n * Convert a curve profile to SVG path data.\n *\n * @param profile - The curve profile to convert\n * @returns SVG path data string\n */\nexport function profileToSVGPathData(profile: CurveProfile): string {\n if (profile.segments.length === 0) {\n return '';\n }\n\n const commands: string[] = [];\n for (let i = 0; i < profile.segments.length; i++) {\n const segment = profile.segments[i];\n const move = i === 0;\n commands.push(segment.toSVGCommands(0, 1, move));\n }\n\n return commands.join(' ');\n}\n","import {Vector2, clamp} from '@canvas-commons/core';\nimport {CurvePoint} from './CurvePoint';\nimport {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 {Spacing} from '@canvas-commons/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 {\n DEFAULT,\n InterpolationFunction,\n PossibleVector2,\n Signal,\n SignalContext,\n SignalExtensions,\n SignalGenerator,\n SignalValue,\n SimpleVector2Signal,\n ThreadGenerator,\n TimingFunction,\n Vector2,\n Vector2Signal,\n Vector2SignalContext,\n deepLerp,\n unwrap,\n} from '@canvas-commons/core';\nimport {Node} from '../components/Node';\nimport {makeSignalExtensions} from '../utils/makeSignalExtensions';\nimport {compound} from './compound';\nimport {addInitializer} from './initializers';\nimport {getPropertyMetaOrCreate, wrapper} from './signal';\n\n/**\n * Utility class for handling coordinate space transformations.\n *\n * Provides shared logic for converting between different coordinate spaces:\n * - **Local**: The node's own coordinate system relative to its parent\n * - **Absolute**: The global coordinate system of the scene\n * - **View**: The coordinate system of the view/camera\n * - **Relative**: Coordinate system relative to another specific node\n *\n * @example\n * ```typescript\n * // Convert an absolute position to local coordinates\n * const localPos = TransformConverter.absoluteToLocalPosition(node, [100, 200]);\n *\n * // Convert a view space scale to local coordinates\n * const localScale = TransformConverter.viewToLocalScale(node, [2, 2]);\n * ```\n */\nclass TransformConverter {\n private static wrapVectorSignalTransform(\n value: SignalValue<PossibleVector2>,\n transform: (val: Vector2) => Vector2,\n ): SignalValue<PossibleVector2> {\n if (typeof value === 'function') {\n return () => transform(new Vector2(value()));\n }\n return transform(new Vector2(value));\n }\n\n private static wrapScalarSignalTransform(\n value: SignalValue<number>,\n transform: (val: number) => number,\n ): SignalValue<number> {\n if (typeof value === 'function') {\n return () => transform(value());\n }\n return transform(value);\n }\n\n public static absoluteToLocalPosition(\n owner: Node,\n absoluteValue: SignalValue<PossibleVector2>,\n ): SignalValue<PossibleVector2> {\n return this.wrapVectorSignalTransform(absoluteValue, val =>\n val.transformAsPoint(owner.worldToParent()),\n );\n }\n\n public static absoluteToLocalScale(\n owner: Node,\n absoluteValue: SignalValue<PossibleVector2>,\n ): SignalValue<PossibleVector2> {\n return this.wrapVectorSignalTransform(absoluteValue, val => {\n const parentAbsScale = owner.parent()?.absoluteScale() ?? Vector2.one;\n return val.div(parentAbsScale);\n });\n }\n\n public static absoluteToLocalRotation(\n owner: Node,\n absoluteValue: SignalValue<number>,\n ): SignalValue<number> {\n return this.wrapScalarSignalTransform(absoluteValue, val => {\n const parentAbsRotation = owner.parent()?.absoluteRotation() ?? 0;\n return val - parentAbsRotation;\n });\n }\n\n public static relativeToAbsolutePosition(\n targetNode: Node,\n relativeValue: SignalValue<PossibleVector2>,\n ): SignalValue<PossibleVector2> {\n return this.wrapVectorSignalTransform(relativeValue, val =>\n val.add(targetNode.absolutePosition()),\n );\n }\n\n public static relativeToAbsoluteScale(\n targetNode: Node,\n relativeValue: SignalValue<PossibleVector2>,\n ): SignalValue<PossibleVector2> {\n return this.wrapVectorSignalTransform(relativeValue, val =>\n val.mul(targetNode.absoluteScale()),\n );\n }\n\n public static relativeToAbsoluteRotation(\n targetNode: Node,\n relativeValue: SignalValue<number>,\n ): SignalValue<number> {\n return this.wrapScalarSignalTransform(\n relativeValue,\n val => val + targetNode.absoluteRotation(),\n );\n }\n\n public static viewToLocalPosition(\n owner: Node,\n viewValue: SignalValue<PossibleVector2>,\n ): SignalValue<PossibleVector2> {\n return this.wrapVectorSignalTransform(viewValue, val => {\n const worldPos = val.transformAsPoint(owner.view().localToWorld());\n return worldPos.transformAsPoint(owner.worldToParent());\n });\n }\n\n public static viewToLocalScale(\n owner: Node,\n viewValue: SignalValue<PossibleVector2>,\n ): SignalValue<PossibleVector2> {\n return this.wrapVectorSignalTransform(viewValue, val => {\n const viewMatrix = owner.view().localToWorld();\n const [xMagnitude, yMagnitude] = this.getViewScaleMagnitudes(viewMatrix);\n return new Vector2(val.x / xMagnitude, val.y / yMagnitude);\n });\n }\n\n public static viewToLocalRotation(\n owner: Node,\n viewValue: SignalValue<number>,\n ): SignalValue<number> {\n return this.wrapScalarSignalTransform(\n viewValue,\n val => val - this.getViewRotation(owner),\n );\n }\n\n public static getViewRotation(owner: Node): number {\n const viewMatrix = owner.view().localToWorld();\n return Vector2.degrees(viewMatrix.m11, viewMatrix.m12);\n }\n\n public static calculateViewSpaceScale(\n owner: Node,\n localScale: Vector2,\n ): Vector2 {\n const viewMatrix = owner.view().localToWorld();\n return new Vector2(\n Vector2.magnitude(\n viewMatrix.m11 * localScale.x,\n viewMatrix.m12 * localScale.x,\n ),\n Vector2.magnitude(\n viewMatrix.m21 * localScale.y,\n viewMatrix.m22 * localScale.y,\n ),\n );\n }\n\n private static getViewScaleMagnitudes(\n viewMatrix: DOMMatrix,\n ): [number, number] {\n return [\n Vector2.magnitude(viewMatrix.m11, viewMatrix.m12),\n Vector2.magnitude(viewMatrix.m21, viewMatrix.m22),\n ];\n }\n\n public static absoluteToLocalLayoutPosition(\n owner: Node,\n absoluteValue: SignalValue<PossibleVector2>,\n ): SignalValue<PossibleVector2> {\n return this.wrapVectorSignalTransform(absoluteValue, val =>\n val.transformAsPoint(owner.worldToLocal()),\n );\n }\n}\n\ninterface ComponentTransformMethod<TOwner> {\n (): number;\n (value: SignalValue<number>): TOwner;\n (\n value: SignalValue<number>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): ThreadGenerator;\n}\n\nconst GETTER_ARGS = 0;\nconst SETTER_ARGS = 1;\n\n/**\n * Enhanced transform method interface that provides both vector and component access.\n *\n * This interface allows you to work with 2D transforms in multiple ways:\n * - Get/set the entire vector: `position()` or `position([x, y])`\n * - Animate the vector: `position([x, y], duration)`\n * - Access individual components: `position.x()` or `position.y()`\n * - Animate components: `position.x(value, duration)`\n *\n * @typeParam TOwner - The type of the object that owns this transform method\n */\ninterface EnhancedTransformMethod<TOwner> {\n /** Get the current transform value */\n (): Vector2;\n /** Set the transform value immediately */\n (value: SignalValue<PossibleVector2>): TOwner;\n /** Animate the transform to a new value */\n (\n value: SignalValue<PossibleVector2>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): SignalGenerator<PossibleVector2, Vector2>;\n /** Access to the X component of the transform */\n x: ComponentTransformMethod<TOwner>;\n /** Access to the Y component of the transform */\n y: ComponentTransformMethod<TOwner>;\n}\n\n// Node-based transform method interface (takes a node parameter)\ninterface NodeTransformMethod<TOwner extends Node> {\n (node: Node): CurriedRelativeTransformSignal<TOwner>;\n}\n\n// Transform-specific signal helpers with enhanced component-wise support\ninterface PositionSignalHelpers<TOwner extends Node> {\n abs: EnhancedTransformMethod<TOwner>;\n relativeTo: NodeTransformMethod<TOwner>;\n view: EnhancedTransformMethod<TOwner>;\n local: EnhancedTransformMethod<TOwner>;\n}\n\ninterface ScaleSignalHelpers<TOwner extends Node> {\n abs: EnhancedTransformMethod<TOwner>;\n relativeTo: NodeScaleTransformMethod<TOwner>;\n view: EnhancedTransformMethod<TOwner>;\n local: EnhancedTransformMethod<TOwner>;\n}\n\n// Node-based scale transform method interface (similar to position but returns scale signal)\ninterface NodeScaleTransformMethod<TOwner extends Node> {\n (node: Node): CurriedRelativeScaleSignal<TOwner>;\n}\n\n// Rotation-specific transform method interface (scalar)\ninterface EnhancedRotationMethod<TOwner extends Node> {\n (): number;\n (value: SignalValue<number>): TOwner;\n (\n value: SignalValue<number>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): SignalGenerator<number, number>;\n}\n\n// Node-based rotation transform method interface\ninterface NodeRotationMethod<TOwner extends Node> {\n (node: Node): CurriedRelativeRotationSignal<TOwner>;\n}\n\ninterface RotationSignalHelpers<TOwner extends Node> {\n abs: EnhancedRotationMethod<TOwner>;\n relativeTo: NodeRotationMethod<TOwner>;\n view: EnhancedRotationMethod<TOwner>;\n local: EnhancedRotationMethod<TOwner>;\n}\n\n/**\n * Enhanced position signal that provides coordinate space transformation methods.\n *\n * @example\n * ```typescript\n * // Get/set position in different coordinate spaces\n * node.position([100, 200]); // Set local position\n * node.position.abs([300, 400]); // Set absolute position\n * node.position.relativeTo(other, [50, 0]); // Set position relative to another node\n * node.position.view([0, 0]); // Set position in view space\n *\n * // Component access\n * node.position.x(150); // Set only X coordinate\n * node.position.abs.y(250); // Set only absolute Y coordinate\n * ```\n */\nexport type PositionSignal<TOwner extends Node = Node> = Vector2Signal<TOwner> &\n PositionSignalHelpers<TOwner>;\n\n/**\n * Enhanced scale signal that provides coordinate space transformation methods.\n *\n * @example\n * ```typescript\n * // Scale operations in different coordinate spaces\n * node.scale([2, 1.5]); // Set local scale\n * node.scale.abs([4, 3]); // Set absolute scale\n * node.scale.relativeTo(parent, [0.5, 0.5]); // Scale relative to parent\n * ```\n */\nexport type ScaleSignal<TOwner extends Node = Node> = Vector2Signal<TOwner> &\n ScaleSignalHelpers<TOwner>;\n\n/**\n * Enhanced rotation signal that provides coordinate space transformation methods.\n *\n * @example\n * ```typescript\n * // Rotation operations in different coordinate spaces\n * node.rotation(45); // Set local rotation (degrees)\n * node.rotation.abs(90); // Set absolute rotation\n * node.rotation.relativeTo(other, 180); // Set rotation relative to another node\n * ```\n */\nexport type RotationSignal<TOwner extends Node = Node> = Signal<\n number,\n number,\n TOwner\n> &\n RotationSignalHelpers<TOwner>;\n\n/**\n * Layout position signal for computed position properties like `top`, `left`, etc.\n *\n * These signals compute their values dynamically based on the node's size and origin,\n * and delegate setting operations to the main position signal.\n */\nexport type LayoutPositionSignal<TOwner extends Node = Node> =\n SimpleVector2Signal<TOwner> & PositionSignalHelpers<TOwner>;\n\n// Shared helper functions for creating enhanced transform methods\n\n/**\n * UNIFIED TRANSFORM SIGNAL ARCHITECTURE\n *\n * Every signal in the system is a coordinate space transformation:\n * - Forward transform: base space → target space\n * - Inverse transform: target space → base space\n * - Component access and tweening built on top\n */\n\n// Type for component configuration\ninterface ComponentConfig<TTarget> {\n getComponent: (target: TTarget, component: 'x' | 'y') => number;\n setComponent: (\n target: TTarget,\n component: 'x' | 'y',\n value: number,\n ) => TTarget;\n}\n\n// Standard Vector2 component configuration\nconst VECTOR2_COMPONENT_CONFIG: ComponentConfig<Vector2> = {\n getComponent: (vec: Vector2, component: 'x' | 'y') => vec[component],\n setComponent: (vec: Vector2, component: 'x' | 'y', value: number) =>\n new Vector2(component === 'x' ? [value, vec.y] : [vec.x, value]),\n};\n\n/**\n * Creates a unified transform signal that handles coordinate space transformations.\n * This is the foundation for all signals (abs, view, local, relativeTo, origin signals).\n */\nfunction createTransformSignal<TBase, TTarget, TOwner extends Node>(\n baseGetter: () => TBase,\n baseSetter: (value: SignalValue<TBase>) => TOwner,\n baseTweener: (\n value: SignalValue<TBase>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<TTarget>,\n ) => any,\n forwardTransform: (base: TBase) => TTarget,\n inverseTransform: (target: TTarget) => SignalValue<TBase>,\n componentConfig?: ComponentConfig<TTarget>,\n) {\n // Main signal function with proper overloads\n function signal(): TTarget;\n function signal(value: SignalValue<TTarget>): TOwner;\n function signal(\n value: SignalValue<TTarget>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<TTarget>,\n ): any;\n function signal(\n value?: SignalValue<TTarget>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<TTarget>,\n ): TTarget | TOwner | any {\n if (arguments.length === 0) {\n // Getter: apply forward transform\n return forwardTransform(baseGetter());\n }\n\n if (arguments.length === 1) {\n // Setter: apply inverse transform and store\n const baseValue = inverseTransform(unwrap(value!));\n return baseSetter(baseValue);\n }\n\n // Tweener: apply inverse transform and animate\n const baseValue = inverseTransform(unwrap(value!));\n return baseTweener(\n baseValue,\n duration!,\n timingFunction,\n interpolationFunction,\n );\n }\n\n // Add component accessors for Vector2-like targets\n if (componentConfig) {\n const {getComponent, setComponent} = componentConfig;\n\n (signal as any).x = function (\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<TTarget>,\n ): number | TOwner | any {\n if (arguments.length === 0) {\n return getComponent(signal(), 'x');\n }\n\n const currentTarget = signal();\n const newTarget = setComponent(currentTarget, 'x', unwrap(value!));\n\n if (arguments.length === 1) {\n return signal(newTarget);\n }\n\n // Component tweening\n return signal(\n newTarget,\n duration!,\n timingFunction,\n interpolationFunction as InterpolationFunction<TTarget>,\n );\n };\n\n (signal as any).y = function (\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<TTarget>,\n ): number | TOwner | any {\n if (arguments.length === 0) {\n return getComponent(signal(), 'y');\n }\n\n const currentTarget = signal();\n const newTarget = setComponent(currentTarget, 'y', unwrap(value!));\n\n if (arguments.length === 1) {\n return signal(newTarget);\n }\n\n // Component tweening\n return signal(\n newTarget,\n duration!,\n timingFunction,\n interpolationFunction as InterpolationFunction<TTarget>,\n );\n };\n }\n\n return signal;\n}\n\n/**\n * Create a curried relative transform signal.\n */\nfunction createCurriedRelativeSignal<TOwner extends Node = Node>(\n baseContext: PositionSignalContext<TOwner>,\n targetNode: Node,\n): CurriedRelativeTransformSignal<TOwner> {\n // Create the main function\n const curriedSignal = function (\n ...args: any[]\n ): Vector2 | TOwner | SignalGenerator<PossibleVector2, Vector2> {\n if (args.length === 0) {\n // Getter: compute relative position using internal method\n return baseContext['relativeToImpl'](targetNode);\n }\n\n // Setter/Tweener: delegate to internal method\n const [value, duration, timingFunction, interpolationFunction] = args;\n return baseContext['relativeToImpl'](\n targetNode,\n value,\n duration,\n timingFunction,\n interpolationFunction,\n );\n };\n\n // Add component accessors\n Object.defineProperty(curriedSignal, 'x', {\n get() {\n return function (...args: any[]): number | TOwner | ThreadGenerator {\n if (args.length === 0) {\n return (curriedSignal() as Vector2).x;\n }\n // Component setter/tweener - build new vector and set/animate it\n const current = curriedSignal() as Vector2;\n if (args.length === 1) {\n return curriedSignal(\n new Vector2([unwrap(args[0]), current.y]),\n ) as TOwner;\n }\n // Component tweener\n const [value, duration, timingFunction, interpolationFunction] = args;\n return curriedSignal(\n new Vector2([unwrap(value), current.y]),\n duration,\n timingFunction,\n interpolationFunction as any,\n ) as ThreadGenerator;\n };\n },\n });\n\n Object.defineProperty(curriedSignal, 'y', {\n get() {\n return function (...args: any[]): number | TOwner | ThreadGenerator {\n if (args.length === 0) {\n return (curriedSignal() as Vector2).y;\n }\n // Component setter/tweener - build new vector and set/animate it\n const current = curriedSignal() as Vector2;\n if (args.length === 1) {\n return curriedSignal(\n new Vector2([current.x, unwrap(args[0])]),\n ) as TOwner;\n }\n // Component tweener\n const [value, duration, timingFunction, interpolationFunction] = args;\n return curriedSignal(\n new Vector2([current.x, unwrap(value)]),\n duration,\n timingFunction,\n interpolationFunction as any,\n ) as ThreadGenerator;\n };\n },\n });\n\n return curriedSignal as CurriedRelativeTransformSignal<TOwner>;\n}\n\n// Properly typed curried signal interface for position\ninterface CurriedRelativeTransformSignal<TOwner extends Node> {\n (): Vector2;\n (value: SignalValue<PossibleVector2>): TOwner;\n (\n value: SignalValue<PossibleVector2>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): SignalGenerator<PossibleVector2, Vector2>;\n\n x: ComponentTransformMethod<TOwner>;\n y: ComponentTransformMethod<TOwner>;\n}\n\n/**\n * Create a curried relative transform signal for rotation.\n */\nfunction createCurriedRelativeRotationSignal<TOwner extends Node = Node>(\n baseContext: RotationSignalContext<TOwner>,\n targetNode: Node,\n): CurriedRelativeRotationSignal<TOwner> {\n // Create the main function\n const curriedSignal = function (\n ...args: any[]\n ): number | TOwner | SignalGenerator<number, number> {\n if (args.length === 0) {\n // Getter: compute relative rotation using internal method\n return baseContext['relativeToImpl'](targetNode);\n }\n\n // Setter/Tweener: delegate to internal method\n const [value, duration, timingFunction, interpolationFunction] = args;\n return baseContext['relativeToImpl'](\n targetNode,\n value,\n duration,\n timingFunction,\n interpolationFunction,\n );\n };\n\n return curriedSignal as CurriedRelativeRotationSignal<TOwner>;\n}\n\n/**\n * Create a curried relative transform signal for scale.\n */\nfunction createCurriedRelativeScaleSignal<TOwner extends Node = Node>(\n baseContext: ScaleSignalContext<TOwner>,\n targetNode: Node,\n): CurriedRelativeScaleSignal<TOwner> {\n // Create the main function\n const curriedSignal = function (\n ...args: any[]\n ): Vector2 | TOwner | SignalGenerator<PossibleVector2, Vector2> {\n if (args.length === 0) {\n // Getter: compute relative scale\n const absScale = (baseContext as any).owner.absoluteScale();\n const targetAbsScale = targetNode.absoluteScale();\n return absScale.div(targetAbsScale);\n }\n\n // Setter/Tweener: convert relative scale to local scale and set it\n const [value, duration, timingFunction, interpolationFunction] = args;\n const absoluteValue = TransformConverter.relativeToAbsoluteScale(\n targetNode,\n value,\n );\n const localValue = TransformConverter.absoluteToLocalScale(\n (baseContext as any).owner,\n absoluteValue,\n );\n return (baseContext as any).invoke(\n localValue,\n duration,\n timingFunction,\n interpolationFunction,\n ) as TOwner | SignalGenerator<PossibleVector2, Vector2>;\n };\n\n // Add component accessors\n Object.defineProperty(curriedSignal, 'x', {\n get() {\n return function (...args: any[]): number | TOwner | ThreadGenerator {\n if (args.length === 0) {\n return (curriedSignal() as Vector2).x;\n }\n // Component setter/tweener - build new vector and set/animate it\n const current = curriedSignal() as Vector2;\n if (args.length === 1) {\n return curriedSignal(\n new Vector2([unwrap(args[0]), current.y]),\n ) as TOwner;\n }\n // Component tweener\n const [value, duration, timingFunction, interpolationFunction] = args;\n return curriedSignal(\n new Vector2([unwrap(value), current.y]),\n duration,\n timingFunction,\n interpolationFunction as any,\n ) as ThreadGenerator;\n };\n },\n });\n\n Object.defineProperty(curriedSignal, 'y', {\n get() {\n return function (...args: any[]): number | TOwner | ThreadGenerator {\n if (args.length === 0) {\n return (curriedSignal() as Vector2).y;\n }\n // Component setter/tweener - build new vector and set/animate it\n const current = curriedSignal() as Vector2;\n if (args.length === 1) {\n return curriedSignal(\n new Vector2([current.x, unwrap(args[0])]),\n ) as TOwner;\n }\n // Component tweener\n const [value, duration, timingFunction, interpolationFunction] = args;\n return curriedSignal(\n new Vector2([current.x, unwrap(value)]),\n duration,\n timingFunction,\n interpolationFunction as any,\n ) as ThreadGenerator;\n };\n },\n });\n\n return curriedSignal as CurriedRelativeScaleSignal<TOwner>;\n}\n\n// Properly typed curried signal interface for rotation\ninterface CurriedRelativeRotationSignal<TOwner extends Node> {\n (): number;\n (value: SignalValue<number>): TOwner;\n (\n value: SignalValue<number>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): SignalGenerator<number, number>;\n}\n\n// Properly typed curried signal interface for scale\ninterface CurriedRelativeScaleSignal<TOwner extends Node> {\n (): Vector2;\n (value: SignalValue<PossibleVector2>): TOwner;\n (\n value: SignalValue<PossibleVector2>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): SignalGenerator<PossibleVector2, Vector2>;\n\n x: ComponentTransformMethod<TOwner>;\n y: ComponentTransformMethod<TOwner>;\n}\n\n// Position-aware Vector2 signal context\nexport class PositionSignalContext<\n TOwner extends Node = Node,\n> extends Vector2SignalContext<TOwner> {\n public constructor(\n entries: ('x' | 'y' | [keyof Vector2, Signal<number, number, TOwner>])[],\n parser: (value: PossibleVector2) => Vector2,\n initial: SignalValue<PossibleVector2>,\n interpolation: InterpolationFunction<Vector2>,\n owner: TOwner,\n extensions: Partial<SignalExtensions<PossibleVector2, Vector2>> = {},\n ) {\n super(entries, parser, initial, interpolation, owner, extensions);\n\n // Create enhanced transform methods using unified approach\n Object.defineProperty(this.invokable, 'abs', {\n value: createTransformSignal<PossibleVector2, Vector2, TOwner>(\n () => this.get(),\n value => this.invoke(value) as TOwner,\n (value, duration, timingFunction, interpolationFunction) =>\n this.invoke(value, duration, timingFunction, interpolationFunction),\n local =>\n new Vector2(local).transformAsPoint(this.owner.parentToWorld()),\n absolute =>\n TransformConverter.absoluteToLocalPosition(\n this.owner,\n unwrap(absolute!) as PossibleVector2,\n ),\n VECTOR2_COMPONENT_CONFIG,\n ),\n enumerable: false,\n });\n\n Object.defineProperty(this.invokable, 'view', {\n value: createTransformSignal<PossibleVector2, Vector2, TOwner>(\n () => this.get(),\n value => this.invoke(value) as TOwner,\n (value, duration, timingFunction, interpolationFunction) =>\n this.invoke(value, duration, timingFunction, interpolationFunction),\n local => {\n // Transform local position to world, then world to view space\n const worldPos = new Vector2(local).transformAsPoint(\n this.owner.parentToWorld(),\n );\n return worldPos.transformAsPoint(this.owner.view().worldToLocal());\n },\n view =>\n TransformConverter.viewToLocalPosition(\n this.owner,\n unwrap(view!) as PossibleVector2,\n ),\n VECTOR2_COMPONENT_CONFIG,\n ),\n enumerable: false,\n });\n\n Object.defineProperty(this.invokable, 'local', {\n value: createTransformSignal<PossibleVector2, Vector2, TOwner>(\n () => this.get(),\n value => this.invoke(value) as TOwner,\n (value, duration, timingFunction, interpolationFunction) =>\n this.invoke(value, duration, timingFunction, interpolationFunction),\n local => new Vector2(local),\n local => local,\n VECTOR2_COMPONENT_CONFIG,\n ),\n enumerable: false,\n });\n\n Object.defineProperty(this.invokable, 'relativeTo', {\n value: this.relativeTo.bind(this),\n enumerable: false,\n });\n }\n\n public override toSignal(): PositionSignal<TOwner> {\n return this.invokable as PositionSignal<TOwner>;\n }\n\n // Internal method for the actual relativeTo implementation\n private relativeToImpl(\n node: Node,\n value?: SignalValue<PossibleVector2>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): Vector2 | TOwner | SignalGenerator<PossibleVector2, Vector2> {\n if (arguments.length === 1) {\n const absPosition = this.owner.absolutePosition();\n const targetAbsPosition = node.absolutePosition();\n return absPosition.sub(targetAbsPosition);\n }\n\n // Convert relative value to local value and set it\n const absoluteValue = TransformConverter.relativeToAbsolutePosition(\n node,\n value!,\n );\n const localValue = TransformConverter.absoluteToLocalPosition(\n this.owner,\n absoluteValue,\n );\n return this.invoke(\n localValue,\n duration,\n timingFunction,\n interpolationFunction,\n ) as TOwner | SignalGenerator<PossibleVector2, Vector2>;\n }\n\n public relativeTo(node: Node): CurriedRelativeTransformSignal<TOwner> {\n return createCurriedRelativeSignal(this, node);\n }\n}\n\n// Scale-aware Vector2 signal context\nexport class ScaleSignalContext<\n TOwner extends Node = Node,\n> extends Vector2SignalContext<TOwner> {\n public constructor(\n entries: ('x' | 'y' | [keyof Vector2, Signal<number, number, TOwner>])[],\n parser: (value: PossibleVector2) => Vector2,\n initial: SignalValue<PossibleVector2>,\n interpolation: InterpolationFunction<Vector2>,\n owner: TOwner,\n extensions: Partial<SignalExtensions<PossibleVector2, Vector2>> = {},\n ) {\n super(entries, parser, initial, interpolation, owner, extensions);\n\n // Create enhanced transform methods using unified approach\n Object.defineProperty(this.invokable, 'abs', {\n value: createTransformSignal<PossibleVector2, Vector2, TOwner>(\n () => this.get(),\n value => this.invoke(value) as TOwner,\n (value, duration, timingFunction, interpolationFunction) =>\n this.invoke(value, duration, timingFunction, interpolationFunction),\n () => {\n const matrix = this.owner.localToWorld();\n return new Vector2(\n Vector2.magnitude(matrix.m11, matrix.m12),\n Vector2.magnitude(matrix.m21, matrix.m22),\n );\n },\n absolute =>\n TransformConverter.absoluteToLocalScale(\n this.owner,\n unwrap(absolute!) as PossibleVector2,\n ),\n VECTOR2_COMPONENT_CONFIG,\n ),\n enumerable: false,\n });\n\n Object.defineProperty(this.invokable, 'view', {\n value: createTransformSignal<PossibleVector2, Vector2, TOwner>(\n () => this.get(),\n value => this.invoke(value) as TOwner,\n (value, duration, timingFunction, interpolationFunction) =>\n this.invoke(value, duration, timingFunction, interpolationFunction),\n local =>\n TransformConverter.calculateViewSpaceScale(\n this.owner,\n new Vector2(local),\n ),\n view =>\n TransformConverter.viewToLocalScale(\n this.owner,\n unwrap(view!) as PossibleVector2,\n ),\n VECTOR2_COMPONENT_CONFIG,\n ),\n enumerable: false,\n });\n\n Object.defineProperty(this.invokable, 'local', {\n value: createTransformSignal<PossibleVector2, Vector2, TOwner>(\n () => this.get(),\n value => this.invoke(value) as TOwner,\n (value, duration, timingFunction, interpolationFunction) =>\n this.invoke(value, duration, timingFunction, interpolationFunction),\n local => new Vector2(local),\n local => local,\n VECTOR2_COMPONENT_CONFIG,\n ),\n enumerable: false,\n });\n\n Object.defineProperty(this.invokable, 'relativeTo', {\n value: this.relativeTo.bind(this),\n enumerable: false,\n });\n }\n\n public override toSignal(): ScaleSignal<TOwner> {\n return this.invokable as ScaleSignal<TOwner>;\n }\n\n public relativeTo(node: Node): CurriedRelativeScaleSignal<TOwner> {\n return createCurriedRelativeScaleSignal(this, node);\n }\n}\n\n// Rotation-aware signal context\nexport class RotationSignalContext<\n TOwner extends Node = Node,\n> extends SignalContext<number, number, TOwner> {\n public constructor(\n initial: SignalValue<number> | undefined,\n interpolation: InterpolationFunction<number>,\n owner: TOwner,\n parser: (value: number) => number = value => value,\n extensions: Partial<SignalExtensions<number, number>> = {},\n ) {\n super(initial, interpolation, owner, parser, extensions);\n\n Object.defineProperty(this.invokable, 'abs', {\n value: this.abs.bind(this),\n enumerable: false,\n });\n\n Object.defineProperty(this.invokable, 'relativeTo', {\n value: this.relativeTo.bind(this),\n enumerable: false,\n });\n\n Object.defineProperty(this.invokable, 'view', {\n value: this.view.bind(this),\n enumerable: false,\n });\n\n Object.defineProperty(this.invokable, 'local', {\n value: this.local.bind(this),\n enumerable: false,\n });\n }\n\n public override toSignal(): RotationSignal<TOwner> {\n return this.invokable as RotationSignal<TOwner>;\n }\n\n public abs(): number;\n public abs(value: SignalValue<number>): TOwner;\n public abs(\n value: SignalValue<number>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): SignalGenerator<number, number>;\n public abs(\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): number | TOwner | SignalGenerator<number, number> {\n if (arguments.length === 0) {\n // Get absolute rotation by extracting it from localToWorld matrix\n const matrix = this.owner.localToWorld();\n return Vector2.degrees(matrix.m11, matrix.m12);\n }\n\n // Convert absolute rotation to local rotation and set it\n const localValue = TransformConverter.absoluteToLocalRotation(\n this.owner,\n value!,\n );\n return this.invoke(\n localValue,\n duration,\n timingFunction,\n interpolationFunction,\n ) as TOwner | SignalGenerator<number, number>;\n }\n\n // Internal method for the actual relativeTo implementation\n private relativeToImpl(\n node: Node,\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): number | TOwner | SignalGenerator<number, number> {\n if (arguments.length === 1) {\n const absRotation = this.owner.absoluteRotation();\n const targetAbsRotation = node.absoluteRotation();\n return absRotation - targetAbsRotation;\n }\n\n // Convert relative rotation to local rotation and set it\n const absoluteValue = TransformConverter.relativeToAbsoluteRotation(\n node,\n value!,\n );\n const localValue = TransformConverter.absoluteToLocalRotation(\n this.owner,\n absoluteValue,\n );\n return this.invoke(\n localValue,\n duration,\n timingFunction,\n interpolationFunction,\n ) as TOwner | SignalGenerator<number, number>;\n }\n\n public relativeTo(node: Node): CurriedRelativeRotationSignal<TOwner> {\n return createCurriedRelativeRotationSignal(this, node);\n }\n\n public view(): number;\n public view(value: SignalValue<number>): TOwner;\n public view(\n value: SignalValue<number>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): SignalGenerator<number, number>;\n public view(\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): number | TOwner | SignalGenerator<number, number> {\n if (arguments.length === 0) {\n // For rotation in view space, we need to get the rotation relative to view\n const currentRotation = this.get();\n const viewRotation = TransformConverter.getViewRotation(this.owner);\n return currentRotation + viewRotation;\n }\n\n // Convert view space rotation to local rotation and set it\n const localValue = TransformConverter.viewToLocalRotation(\n this.owner,\n value!,\n );\n return this.invoke(\n localValue,\n duration,\n timingFunction,\n interpolationFunction,\n ) as TOwner | SignalGenerator<number, number>;\n }\n\n public local(): number;\n public local(value: SignalValue<number>): TOwner;\n public local(\n value: SignalValue<number>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): SignalGenerator<number, number>;\n public local(\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): number | TOwner | SignalGenerator<number, number> {\n if (arguments.length === 0) {\n return this.get();\n }\n\n // Local value is just the raw value\n return this.invoke(\n value!,\n duration,\n timingFunction,\n interpolationFunction,\n ) as TOwner | SignalGenerator<number, number>;\n }\n}\n\n// Custom setter function type for layout positions\ntype LayoutPositionSetter<TOwner> = (\n value: SignalValue<PossibleVector2> | typeof DEFAULT,\n) => TOwner;\n\n// Layout position signal context (for computed position signals like top, left, etc.)\nexport class LayoutPositionSignalContext<\n TOwner extends Node = Node,\n> extends SignalContext<PossibleVector2, Vector2, TOwner> {\n private readonly hasCustomDelegate: boolean;\n\n public constructor(\n initial: SignalValue<PossibleVector2> | undefined,\n interpolation: InterpolationFunction<Vector2>,\n owner: TOwner,\n parser: (value: PossibleVector2) => Vector2 = value => new Vector2(value),\n extensions: Partial<SignalExtensions<PossibleVector2, Vector2>> = {},\n ) {\n super(initial, interpolation, owner, parser, extensions);\n\n // Track if we have custom delegation behavior\n this.hasCustomDelegate = Boolean(extensions.getter || extensions.setter);\n\n // Create enhanced transform methods with component access using shared helpers\n const absMethod = this.abs.bind(this);\n\n // Add component methods to abs\n (absMethod as any).x = function (\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): number | TOwner | ThreadGenerator {\n if (arguments.length === 0) {\n return absMethod().x;\n }\n // Get the current absolute position once and preserve the y component\n const currentAbsPos = absMethod();\n const newAbsPos = new Vector2([unwrap(value!), currentAbsPos.y]);\n if (arguments.length === 1) {\n return absMethod(newAbsPos);\n }\n return absMethod(\n newAbsPos,\n duration!,\n timingFunction,\n interpolationFunction as any,\n ) as ThreadGenerator;\n };\n\n (absMethod as any).y = function (\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): number | TOwner | ThreadGenerator {\n if (arguments.length === 0) {\n return absMethod().y;\n }\n // Get the current absolute position once and preserve the x component\n const currentAbsPos = absMethod();\n const newAbsPos = new Vector2([currentAbsPos.x, unwrap(value!)]);\n if (arguments.length === 1) {\n return absMethod(newAbsPos);\n }\n return absMethod(\n newAbsPos,\n duration!,\n timingFunction,\n interpolationFunction as any,\n ) as ThreadGenerator;\n };\n\n Object.defineProperty(this.invokable, 'abs', {\n value: absMethod,\n enumerable: false,\n });\n\n Object.defineProperty(this.invokable, 'relativeTo', {\n value: this.relativeTo.bind(this),\n enumerable: false,\n });\n\n const viewMethod = this.view.bind(this);\n\n // Add component methods to view\n (viewMethod as any).x = function (\n this: LayoutPositionSignalContext<TOwner>,\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): number | TOwner | ThreadGenerator {\n if (arguments.length === 0) {\n return viewMethod().x;\n }\n\n // For view space component setting, we need to be more precise about preserving the other component\n // Get the current LOCAL position and current VIEW position\n const currentLocal = this.get();\n const currentView = currentLocal\n .transformAsPoint(this.owner.localToWorld())\n .transformAsPoint(this.owner.view().worldToLocal());\n\n // Create target view position with only the x component changed\n const targetView = new Vector2([unwrap(value!), currentView.y]);\n\n // Transform to local and set\n const targetLocal = new Vector2(\n unwrap(TransformConverter.viewToLocalPosition(this.owner, targetView)),\n );\n\n if (arguments.length === 1) {\n return this.invoke(targetLocal) as TOwner;\n }\n return this.invoke(\n targetLocal,\n duration!,\n timingFunction,\n interpolationFunction as any,\n ) as ThreadGenerator;\n }.bind(this);\n\n (viewMethod as any).y = function (\n this: LayoutPositionSignalContext<TOwner>,\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): number | TOwner | ThreadGenerator {\n if (arguments.length === 0) {\n return viewMethod().y;\n }\n\n // Get the current LOCAL position and current VIEW position\n const currentLocal = this.get();\n const currentView = currentLocal\n .transformAsPoint(this.owner.localToWorld())\n .transformAsPoint(this.owner.view().worldToLocal());\n\n // Create target view position with only the y component changed\n const targetView = new Vector2([currentView.x, unwrap(value!)]);\n\n // Transform to local and set\n const targetLocal = new Vector2(\n unwrap(TransformConverter.viewToLocalPosition(this.owner, targetView)),\n );\n\n if (arguments.length === 1) {\n return this.invoke(targetLocal) as TOwner;\n }\n return this.invoke(\n targetLocal,\n duration!,\n timingFunction,\n interpolationFunction as any,\n ) as ThreadGenerator;\n }.bind(this);\n\n Object.defineProperty(this.invokable, 'view', {\n value: viewMethod,\n enumerable: false,\n });\n\n const localMethod = this.local.bind(this);\n\n // Add component methods to local\n (localMethod as any).x = function (\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): number | TOwner | ThreadGenerator {\n if (arguments.length === 0) {\n return localMethod().x;\n }\n // Get the current local position once and preserve the y component\n const currentLocalPos = localMethod();\n const newLocalPos = new Vector2([unwrap(value!), currentLocalPos.y]);\n if (arguments.length === 1) {\n return localMethod(newLocalPos);\n }\n return localMethod(\n newLocalPos,\n duration!,\n timingFunction,\n interpolationFunction as any,\n ) as ThreadGenerator;\n };\n\n (localMethod as any).y = function (\n value?: SignalValue<number>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<number>,\n ): number | TOwner | ThreadGenerator {\n if (arguments.length === 0) {\n return localMethod().y;\n }\n // Get the current local position once and preserve the x component\n const currentLocalPos = localMethod();\n const newLocalPos = new Vector2([currentLocalPos.x, unwrap(value!)]);\n if (arguments.length === 1) {\n return localMethod(newLocalPos);\n }\n return localMethod(\n newLocalPos,\n duration!,\n timingFunction,\n interpolationFunction as any,\n ) as ThreadGenerator;\n };\n\n Object.defineProperty(this.invokable, 'local', {\n value: localMethod,\n enumerable: false,\n });\n }\n\n /**\n * Override get to use custom getter if available.\n * This enables computed layout positions (e.g., top, left) to calculate their values dynamically.\n */\n public override get(): Vector2 {\n if (this.extensions.getter) {\n return this.extensions.getter();\n }\n return super.get();\n }\n\n /**\n * Set a custom setter function for layout position delegation.\n * This allows layout signals to delegate setting behavior to position updates.\n */\n public setCustomSetter(setterFunc: LayoutPositionSetter<TOwner>): void {\n this.extensions.setter = setterFunc;\n }\n\n /**\n * Override invoke to handle layout-specific delegation patterns.\n * Uses custom setter for simple value assignments when available.\n */\n public override invoke(\n value?: SignalValue<PossibleVector2> | typeof DEFAULT,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): Vector2 | TOwner | SignalGenerator<PossibleVector2, Vector2> {\n // Getter: no arguments\n if (arguments.length === GETTER_ARGS) {\n return this.get();\n }\n\n // Setter: single argument with custom delegate\n if (\n arguments.length === SETTER_ARGS &&\n this.hasCustomDelegate &&\n this.extensions.setter\n ) {\n const result = this.extensions.setter(value!);\n return result !== undefined ? result : this.owner;\n }\n\n // Animation or fallback to default behavior\n return super.invoke(value, duration, timingFunction, interpolationFunction);\n }\n\n public override toSignal(): LayoutPositionSignal<TOwner> {\n return this.invokable as LayoutPositionSignal<TOwner>;\n }\n\n public abs(): Vector2;\n public abs(value: SignalValue<PossibleVector2>): TOwner;\n public abs(\n value: SignalValue<PossibleVector2>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): SignalGenerator<PossibleVector2, Vector2>;\n public abs(\n value?: SignalValue<PossibleVector2>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): Vector2 | TOwner | SignalGenerator<PossibleVector2, Vector2> {\n if (arguments.length === 0) {\n // For layout position signals, get the current computed value\n const currentValue = this.get();\n return currentValue.transformAsPoint(this.owner.localToWorld());\n }\n\n // Convert absolute value to local value for this layout position and set it\n const localValue = TransformConverter.absoluteToLocalLayoutPosition(\n this.owner,\n value!,\n );\n return this.invoke(\n localValue,\n duration,\n timingFunction,\n interpolationFunction,\n ) as TOwner | SignalGenerator<PossibleVector2, Vector2>;\n }\n\n public relativeTo(node: Node): Vector2;\n public relativeTo(node: Node, value: SignalValue<PossibleVector2>): TOwner;\n public relativeTo(\n node: Node,\n value: SignalValue<PossibleVector2>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): SignalGenerator<PossibleVector2, Vector2>;\n public relativeTo(\n node: Node,\n value?: SignalValue<PossibleVector2>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): Vector2 | TOwner | SignalGenerator<PossibleVector2, Vector2> {\n if (arguments.length === 1) {\n // For layout positions, calculate relative position using absolute coordinates\n const currentValue = this.get();\n const absPosition = currentValue.transformAsPoint(\n this.owner.localToWorld(),\n );\n const targetAbsPosition = node.absolutePosition();\n return absPosition.sub(targetAbsPosition);\n }\n\n // Convert relative value to local value and set it\n const absoluteValue = TransformConverter.relativeToAbsolutePosition(\n node,\n value!,\n );\n const localValue = TransformConverter.absoluteToLocalLayoutPosition(\n this.owner,\n absoluteValue,\n );\n return this.invoke(\n localValue,\n duration,\n timingFunction,\n interpolationFunction,\n ) as TOwner | SignalGenerator<PossibleVector2, Vector2>;\n }\n\n public view(): Vector2;\n public view(value: SignalValue<PossibleVector2>): TOwner;\n public view(\n value: SignalValue<PossibleVector2>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): SignalGenerator<PossibleVector2, Vector2>;\n public view(\n value?: SignalValue<PossibleVector2>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): Vector2 | TOwner | SignalGenerator<PossibleVector2, Vector2> {\n if (arguments.length === 0) {\n const currentValue = this.get();\n return currentValue.transformAsPoint(this.owner.view().localToWorld());\n }\n\n // Convert view space value to local value and set it\n const localValue = TransformConverter.viewToLocalPosition(\n this.owner,\n value!,\n );\n return this.invoke(\n localValue,\n duration,\n timingFunction,\n interpolationFunction,\n ) as TOwner | SignalGenerator<PossibleVector2, Vector2>;\n }\n\n public local(): Vector2;\n public local(value: SignalValue<PossibleVector2>): TOwner;\n public local(\n value: SignalValue<PossibleVector2>,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): SignalGenerator<PossibleVector2, Vector2>;\n public local(\n value?: SignalValue<PossibleVector2>,\n duration?: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): Vector2 | TOwner | SignalGenerator<PossibleVector2, Vector2> {\n if (arguments.length === 0) {\n return this.get();\n }\n\n // Local value is just the raw value\n return this.invoke(\n value!,\n duration,\n timingFunction,\n interpolationFunction,\n ) as TOwner | SignalGenerator<PossibleVector2, Vector2>;\n }\n}\n\n/**\n * Creates an enhanced position signal with coordinate space transformation methods.\n *\n * This decorator creates a position signal that supports operations in multiple coordinate spaces:\n * - **Local**: Relative to the node's parent\n * - **Absolute**: In the global scene coordinates\n * - **View**: In the camera/view coordinate system\n * - **Relative**: Relative to another specific node\n *\n * @param prefix - Optional prefix for the underlying X/Y property names.\n * Can be a string (e.g., 'scale' creates 'scaleX'/'scaleY') or\n * an object mapping \\{x: 'propX', y: 'propY'\\}\n *\n * @example\n * ```typescript\n * class MyNode extends Node {\n * \\@positionSignal()\n * declare readonly position: PositionSignal<this>;\n *\n * \\@positionSignal('anchor')\n * declare readonly anchor: PositionSignal<this>; // Uses anchorX/anchorY\n * }\n * ```\n */\nexport function positionSignal(\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 PositionSignalContext,\n )(target, key);\n wrapper(Vector2)(target, key);\n };\n}\n\n/**\n * Creates an enhanced scale signal with coordinate space transformation methods.\n *\n * Scale signals support operations in multiple coordinate spaces:\n * - **Local**: Scale relative to the node's parent\n * - **Absolute**: Scale in global scene coordinates\n * - **View**: Scale in camera/view coordinate system\n * - **Relative**: Scale relative to another node's scale\n *\n * @param prefix - Optional prefix for the underlying X/Y property names\n *\n * @example\n * ```typescript\n * class MyNode extends Node {\n * \\@scaleSignal('scale')\n * declare readonly scale: ScaleSignal<this>;\n * }\n *\n * // Usage:\n * node.scale([2, 1.5]); // Local scale\n * node.scale.abs([4, 3]); // Absolute scale\n * node.scale.relativeTo(parent, [0.5, 0.5]); // Scale relative to parent\n * ```\n */\nexport function scaleSignal(\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 ScaleSignalContext,\n )(target, key);\n wrapper(Vector2)(target, key);\n };\n}\n\n/**\n * Creates an enhanced rotation signal with coordinate space transformation methods.\n *\n * Rotation signals work with degrees and support operations in multiple coordinate spaces:\n * - **Local**: Rotation relative to the node's parent\n * - **Absolute**: Rotation in global scene coordinates\n * - **View**: Rotation in camera/view coordinate system\n * - **Relative**: Rotation relative to another node's rotation\n *\n * @example\n * ```typescript\n * class MyNode extends Node {\n * \\@rotationSignal()\n * declare readonly rotation: RotationSignal<this>;\n * }\n *\n * // Usage:\n * node.rotation(45); // Local rotation (45 degrees)\n * node.rotation.abs(90); // Absolute rotation (90 degrees)\n * node.rotation.relativeTo(other, 180); // 180 degrees relative to other node\n * ```\n */\nexport function rotationSignal(): PropertyDecorator {\n return (target, key) => {\n const meta = getPropertyMetaOrCreate<number>(target, key);\n addInitializer(target, (instance: Node) => {\n const initial = meta.default;\n const parser = meta.parser?.bind(instance) ?? ((value: number) => value);\n const signalContext = new RotationSignalContext(\n initial,\n meta.interpolationFunction ?? deepLerp,\n instance,\n parser,\n makeSignalExtensions(meta, instance, key as string),\n );\n\n // Use Object.defineProperty to avoid casting\n Object.defineProperty(instance, key, {\n value: signalContext.toSignal(),\n writable: false,\n enumerable: true,\n configurable: false,\n });\n });\n };\n}\n","import {\n experimentalLog,\n SignalValue,\n useLogger,\n useScene,\n WebGLConvertible,\n} from '@canvas-commons/core';\nimport {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 \"@canvas-commons/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 '@canvas-commons/core';\nimport type {Scene2D} from './Scene2D';\n\nexport function useScene2D(): Scene2D {\n return <Scene2D>useScene();\n}\n","import {\n BBox,\n ColorSignal,\n DependencyContext,\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 UNIFORM_DESTINATION_MATRIX,\n UNIFORM_SOURCE_MATRIX,\n UNIFORM_TIME,\n Vector2,\n Vector2Signal,\n all,\n clamp,\n createSignal,\n easeInOutCubic,\n isReactive,\n threadable,\n transformScalar,\n unwrap,\n useLogger,\n} from '@canvas-commons/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 {FiltersSignal, filtersSignal} from '../decorators/filtersSignal';\nimport {spacingSignal} from '../decorators/spacingSignal';\nimport {\n PositionSignal,\n RotationSignal,\n ScaleSignal,\n positionSignal,\n rotationSignal,\n scaleSignal,\n} from '../decorators/transformSignals';\nimport {Filter} from '../partials';\nimport {\n PossibleShaderConfig,\n ShaderConfig,\n parseShader,\n} from '../partials/ShaderConfig';\nimport {useScene2D} from '../scenes/useScene2D';\nimport {drawLine} from '../utils';\nimport type {ComponentChild, ComponentChildren, NodeConstructor} from './types';\nimport type {View2D} from './View2D';\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 declare public readonly [NODE_NAME]: string;\n declare public 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 @positionSignal()\n declare public readonly position: PositionSignal<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 * @deprecated Use `position.abs` instead.\n */\n @wrapper(Vector2)\n @cloneable(false)\n @signal()\n declare public readonly absolutePosition: SimpleVector2Signal<this>;\n\n protected getAbsolutePosition(): Vector2 {\n return this.position.abs();\n }\n\n protected setAbsolutePosition(value: SignalValue<PossibleVector2>) {\n this.position.abs(value);\n }\n\n /**\n * Represents the rotation (in degrees) of this node relative to its parent.\n */\n @initial(0)\n @rotationSignal()\n declare public readonly rotation: RotationSignal<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 * @deprecated Use `rotation.abs` instead.\n */\n @cloneable(false)\n @signal()\n declare public readonly absoluteRotation: SimpleSignal<number, this>;\n\n protected getAbsoluteRotation() {\n return this.rotation.abs();\n }\n\n protected setAbsoluteRotation(value: SignalValue<number>) {\n this.rotation.abs(value);\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 @scaleSignal('scale')\n declare public readonly scale: ScaleSignal<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 declare public 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 * @deprecated Use `scale.abs` instead.\n */\n @wrapper(Vector2)\n @cloneable(false)\n @signal()\n declare public readonly absoluteScale: SimpleVector2Signal<this>;\n\n protected getAbsoluteScale(): Vector2 {\n return this.scale.abs();\n }\n\n protected setAbsoluteScale(value: SignalValue<PossibleVector2>) {\n this.scale.abs(value);\n }\n\n @initial(0)\n @signal()\n declare public readonly zIndex: SimpleSignal<number, this>;\n\n @initial(false)\n @signal()\n declare public 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 declare public readonly cachePadding: SpacingSignal<this>;\n\n @initial(false)\n @signal()\n declare public readonly composite: SimpleSignal<boolean, this>;\n\n @initial('source-over')\n @signal()\n declare public 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 declare public 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 declare public readonly filters: FiltersSignal<this>;\n\n @initial('#0000')\n @colorSignal()\n declare public readonly shadowColor: ColorSignal<this>;\n\n @initial(0)\n @signal()\n declare public readonly shadowBlur: SimpleSignal<number, this>;\n\n @vector2Signal('shadowOffset')\n declare public readonly shadowOffset: Vector2Signal<this>;\n\n /**\n * @experimental\n */\n @initial([])\n @parser(parseShader)\n @signal()\n declare public 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 declare protected 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 declare public 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 = local.transformAsPoint(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 = world.transformAsPoint(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 parent-to-world matrix for this node.\n *\n * @remarks\n * This matrix transforms vectors from local space of this node's parent to\n * world space.\n */\n @computed()\n public parentToWorld(): DOMMatrix {\n return this.parent()?.localToWorld() ?? 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): this {\n const position = this.position.abs();\n const rotation = this.rotation.abs();\n const scale = this.scale.abs();\n newParent.add(this);\n this.position.abs(position);\n this.rotation.abs(rotation);\n this.scale.abs(scale);\n\n return this;\n }\n\n /**\n * Remove all children of this node.\n */\n public removeChildren(): this {\n for (const oldChild of this.realChildren) {\n oldChild.parent(null);\n }\n this.setParsedChildren([]);\n\n return this;\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 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 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 => r.transformAsPoint(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 = this.shadowOffset().transform(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()).expand(\n this.view().cachePadding(),\n );\n const canvasBBox = BBox.fromPoints(\n ...viewBBox.transformCorners(this.view().localToWorld()),\n );\n const cacheBBox = BBox.fromPoints(\n ...this.cacheBBox().transformCorners(this.localToWorld()),\n );\n\n return canvasBBox.intersection(cacheBBox).pixelPerfect.expand(2);\n }\n\n @computed()\n protected parentWorldSpaceCacheBBox(): BBox {\n return (\n this.findAncestor(node => node.requiresCache())?.worldSpaceCacheBBox() ??\n new BBox(Vector2.zero, useScene2D().getRealSize())\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 = this.shadowOffset().transform(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 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 = 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 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 draw(context: CanvasRenderingContext2D) {\n this.drawChildren(context);\n }\n\n protected drawChildren(context: CanvasRenderingContext2D) {\n for (const child of this.sortedChildren()) {\n 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 = position.transformAsPoint(this.localToParent().inverse());\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 {\n BBox,\n DEFAULT,\n Direction,\n InterpolationFunction,\n Origin,\n PossibleSpacing,\n PossibleVector2,\n SerializedVector2,\n Signal,\n SignalValue,\n SimpleSignal,\n SpacingSignal,\n ThreadGenerator,\n TimingFunction,\n Vector2,\n Vector2Signal,\n boolLerp,\n deepLerp,\n modify,\n originToOffset,\n threadable,\n tween,\n} from '@canvas-commons/core';\nimport {\n Vector2LengthSignal,\n addInitializer,\n cloneable,\n computed,\n defaultStyle,\n initial,\n interpolation,\n nodeName,\n signal,\n vector2Signal,\n wrapper,\n} from '../decorators';\nimport {spacingSignal} from '../decorators/spacingSignal';\nimport {\n LayoutPositionSignal,\n LayoutPositionSignalContext,\n} from '../decorators/transformSignals';\nimport {\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 {Node, NodeProps} 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<PossibleVector2<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 anchorX?: SignalValue<number>;\n anchorY?: SignalValue<number>;\n anchor?: 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 anchor} 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 declare public readonly layout: SimpleSignal<LayoutMode, this>;\n\n @initial(null)\n @signal()\n declare public readonly maxWidth: SimpleSignal<LengthLimit, this>;\n @initial(null)\n @signal()\n declare public readonly maxHeight: SimpleSignal<LengthLimit, this>;\n @initial(null)\n @signal()\n declare public readonly minWidth: SimpleSignal<LengthLimit, this>;\n @initial(null)\n @signal()\n declare public readonly minHeight: SimpleSignal<LengthLimit, this>;\n @initial(null)\n @signal()\n declare public readonly ratio: SimpleSignal<number | null, this>;\n\n @spacingSignal('margin')\n declare public readonly margin: SpacingSignal<this>;\n\n @spacingSignal('padding')\n declare public readonly padding: SpacingSignal<this>;\n\n @initial('row')\n @signal()\n declare public readonly direction: SimpleSignal<FlexDirection, this>;\n @initial(null)\n @signal()\n declare public readonly basis: SimpleSignal<FlexBasis, this>;\n @initial(0)\n @signal()\n declare public readonly grow: SimpleSignal<number, this>;\n @initial(1)\n @signal()\n declare public readonly shrink: SimpleSignal<number, this>;\n @initial('nowrap')\n @signal()\n declare public readonly wrap: SimpleSignal<FlexWrap, this>;\n\n @initial('start')\n @signal()\n declare public readonly justifyContent: SimpleSignal<FlexContent, this>;\n @initial('normal')\n @signal()\n declare public readonly alignContent: SimpleSignal<FlexContent, this>;\n @initial('stretch')\n @signal()\n declare public readonly alignItems: SimpleSignal<FlexItems, this>;\n @initial('auto')\n @signal()\n declare public readonly alignSelf: SimpleSignal<FlexItems, this>;\n @initial(0)\n @vector2Signal({x: 'columnGap', y: 'rowGap'})\n declare public 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('Roboto')\n @signal()\n declare public readonly fontFamily: SimpleSignal<string, this>;\n @defaultStyle(48)\n @signal()\n declare public readonly fontSize: SimpleSignal<number, this>;\n @defaultStyle('normal')\n @signal()\n declare public readonly fontStyle: SimpleSignal<string, this>;\n @defaultStyle(500)\n @signal()\n declare public readonly fontWeight: SimpleSignal<number, this>;\n @defaultStyle('120%')\n @signal()\n declare public readonly lineHeight: SimpleSignal<Length, this>;\n @defaultStyle(0)\n @signal()\n declare public readonly letterSpacing: SimpleSignal<number, this>;\n\n @defaultStyle(false)\n @signal()\n declare public readonly textWrap: SimpleSignal<TextWrap, this>;\n @initial('ltr')\n @signal()\n declare public readonly textDirection: SimpleSignal<CanvasDirection, this>;\n @defaultStyle('start')\n @signal()\n declare public 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 declare public 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 anchors:\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('anchor')\n declare public readonly anchor: 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 anchor} 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 declare public readonly middle: LayoutPositionSignal<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 declare public readonly top: LayoutPositionSignal<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 declare public readonly bottom: LayoutPositionSignal<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 declare public readonly left: LayoutPositionSignal<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 declare public readonly right: LayoutPositionSignal<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 declare public readonly topLeft: LayoutPositionSignal<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 declare public readonly topRight: LayoutPositionSignal<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 declare public readonly bottomLeft: LayoutPositionSignal<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 declare public readonly bottomRight: LayoutPositionSignal<this>;\n\n /**\n * Get the cardinal point corresponding to the given origin.\n *\n * @param origin - The origin or direction of the point.\n */\n public cardinalPoint(origin: Origin | Direction): LayoutPositionSignal<this> {\n switch (origin) {\n case Origin.TopLeft:\n return this.topLeft;\n case Origin.TopRight:\n return this.topRight;\n case Origin.BottomLeft:\n return this.bottomLeft;\n case Origin.BottomRight:\n return this.bottomRight;\n case Origin.Top:\n case Direction.Top:\n return this.top;\n case Origin.Bottom:\n case Direction.Bottom:\n return this.bottom;\n case Origin.Left:\n case Direction.Left:\n return this.left;\n case Origin.Right:\n case Direction.Right:\n return this.right;\n default:\n return this.middle;\n }\n }\n\n @initial(false)\n @signal()\n declare public readonly clip: SimpleSignal<boolean, this>;\n\n declare public element: HTMLElement;\n declare public styles: CSSStyleDeclaration;\n\n @initial(0)\n @signal()\n declare protected readonly sizeLockCounter: SimpleSignal<number, this>;\n\n public constructor(props: LayoutProps) {\n super(props);\n this.element.dataset.canvasCommonsKey = 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.anchor();\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.anchor();\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.anchor();\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.anchor.x(),\n box.y + (box.height / 2) * this.anchor.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 draw(context: CanvasRenderingContext2D) {\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 this.drawChildren(context);\n }\n\n public override drawOverlay(\n context: CanvasRenderingContext2D,\n matrix: DOMMatrix,\n ) {\n const size = this.computedSize();\n const offset = size.mul(this.anchor()).scale(0.5).transformAsPoint(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.anchor().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.anchor().mul(size);\n const newOffset = offset.mul(size);\n this.anchor(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 this.element.style.fontFamily = this.fontFamily();\n this.element.style.fontSize = `${this.fontSize()}px`;\n this.element.style.fontStyle = this.fontStyle();\n\n const lineHeight = this.lineHeight();\n this.element.style.lineHeight =\n typeof lineHeight === 'number'\n ? `${lineHeight}px`\n : (parseFloat(lineHeight as string) / 100).toString();\n\n this.element.style.fontWeight = this.fontWeight().toString();\n this.element.style.letterSpacing = `${this.letterSpacing()}px`;\n this.element.style.textAlign = this.textAlign();\n\n const wrap = this.textWrap();\n if (typeof wrap === 'boolean') {\n this.element.style.whiteSpace = wrap ? 'normal' : 'nowrap';\n } else {\n this.element.style.whiteSpace = wrap;\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 = position.transformAsPoint(this.localToParent().inverse());\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<PossibleVector2>()(target, key);\n cloneable(false)(target, key);\n wrapper(Vector2)(target, key);\n\n addInitializer(target, (instance: Layout) => {\n const parser = (value: PossibleVector2) => new Vector2(value);\n\n const signalContext = new LayoutPositionSignalContext(\n undefined,\n deepLerp,\n instance,\n parser,\n {\n getter: function (this: Layout) {\n return this.computedSize()\n .getOriginOffset(origin)\n .transformAsPoint(this.localToParent());\n }.bind(instance),\n },\n );\n\n signalContext.setCustomSetter(\n function (\n this: Layout,\n value: SignalValue<PossibleVector2> | typeof DEFAULT,\n ) {\n if (value === DEFAULT) {\n return this;\n }\n this.position(\n modify(value, unwrapped =>\n this.getOriginDelta(origin)\n .transform(this.scalingRotationMatrix())\n .flipped.add(unwrapped),\n ),\n );\n return this;\n }.bind(instance),\n );\n\n Object.defineProperty(instance, key, {\n value: signalContext.toSignal(),\n writable: false,\n enumerable: true,\n configurable: false,\n });\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 {\n BBox,\n SignalValue,\n SimpleSignal,\n createSignal,\n easeOutExpo,\n linear,\n map,\n threadable,\n useRandom,\n} from '@canvas-commons/core';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport {\n CanvasStyleSignal,\n canvasStyleSignal,\n} from '../decorators/canvasStyleSignal';\nimport {PossibleCanvasStyle, RoughFillStyle} from '../partials';\nimport {createRoughConfig, drawRoughPath, resolveCanvasStyle} from '../utils';\nimport {Layout, LayoutProps} 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 * Enable rough.js rendering.\n */\n rough?: SignalValue<boolean>;\n /**\n * {@inheritDoc RoughConfig.roughness}\n */\n roughness?: SignalValue<number>;\n /**\n * {@inheritDoc RoughConfig.bowing}\n */\n bowing?: SignalValue<number>;\n /**\n * {@inheritDoc RoughConfig.fillStyle}\n */\n roughFillStyle?: SignalValue<RoughFillStyle>;\n /**\n * {@inheritDoc RoughConfig.fillWeight}\n */\n roughFillWeight?: SignalValue<number>;\n /**\n * {@inheritDoc RoughConfig.hachureAngle}\n */\n roughHachureAngle?: SignalValue<number>;\n /**\n * {@inheritDoc RoughConfig.hachureGap}\n */\n roughHachureGap?: SignalValue<number>;\n /**\n * {@inheritDoc RoughConfig.seed}\n */\n roughSeed?: SignalValue<number>;\n /**\n * {@inheritDoc RoughConfig.disableMultiStroke}\n */\n roughDisableMultiStroke?: SignalValue<boolean>;\n /**\n * {@inheritDoc RoughConfig.disableMultiStrokeFill}\n */\n roughDisableMultiStrokeFill?: SignalValue<boolean>;\n}\n\n@nodeName('Shape')\nexport abstract class Shape extends Layout {\n @canvasStyleSignal()\n declare public readonly fill: CanvasStyleSignal<this>;\n @canvasStyleSignal()\n declare public readonly stroke: CanvasStyleSignal<this>;\n @initial(false)\n @signal()\n declare public readonly strokeFirst: SimpleSignal<boolean, this>;\n @initial(0)\n @signal()\n declare public readonly lineWidth: SimpleSignal<number, this>;\n @initial('miter')\n @signal()\n declare public readonly lineJoin: SimpleSignal<CanvasLineJoin, this>;\n @initial('butt')\n @signal()\n declare public readonly lineCap: SimpleSignal<CanvasLineCap, this>;\n @initial([])\n @signal()\n declare public readonly lineDash: SimpleSignal<number[], this>;\n @initial(0)\n @signal()\n declare public readonly lineDashOffset: SimpleSignal<number, this>;\n @initial(true)\n @signal()\n declare public readonly antialiased: SimpleSignal<boolean, this>;\n\n // Rough.js signals\n /**\n * Enable rough.js rendering.\n */\n @initial(false)\n @signal()\n declare public readonly rough: SimpleSignal<boolean, this>;\n /**\n * {@inheritDoc RoughConfig.roughness}\n */\n @initial(1)\n @signal()\n declare public readonly roughness: SimpleSignal<number, this>;\n /**\n * {@inheritDoc RoughConfig.bowing}\n */\n @initial(1)\n @signal()\n declare public readonly bowing: SimpleSignal<number, this>;\n /**\n * {@inheritDoc RoughConfig.fillStyle}\n */\n @initial('hachure')\n @signal()\n declare public readonly roughFillStyle: SimpleSignal<RoughFillStyle, this>;\n /**\n * {@inheritDoc RoughConfig.fillWeight}\n */\n @signal()\n declare public readonly roughFillWeight: SimpleSignal<\n number | undefined,\n this\n >;\n /**\n * {@inheritDoc RoughConfig.hachureAngle}\n */\n @initial(-41)\n @signal()\n declare public readonly roughHachureAngle: SimpleSignal<number, this>;\n /**\n * {@inheritDoc RoughConfig.hachureGap}\n */\n @initial(4)\n @signal()\n declare public readonly roughHachureGap: SimpleSignal<number, this>;\n /**\n * {@inheritDoc RoughConfig.seed}\n */\n @signal()\n declare public readonly roughSeed: SimpleSignal<number | undefined, this>;\n /**\n * {@inheritDoc RoughConfig.disableMultiStroke}\n */\n @initial(false)\n @signal()\n declare public readonly roughDisableMultiStroke: SimpleSignal<boolean, this>;\n /**\n * {@inheritDoc RoughConfig.disableMultiStrokeFill}\n */\n @initial(false)\n @signal()\n declare public readonly roughDisableMultiStrokeFill: SimpleSignal<\n boolean,\n this\n >;\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 if (props.roughSeed === undefined) {\n this.roughSeed(useRandom().nextInt(0, Number.MAX_SAFE_INTEGER));\n }\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 draw(context: CanvasRenderingContext2D) {\n this.drawShape(context);\n if (this.clip()) {\n context.clip(this.getPath());\n }\n this.drawChildren(context);\n }\n\n protected drawShape(context: CanvasRenderingContext2D) {\n if (this.rough()) {\n this.drawShapeRough(context);\n } else {\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\n protected drawShapeRough(context: CanvasRenderingContext2D) {\n const pathData = this.getPathData();\n if (!pathData) {\n return;\n }\n\n context.save();\n\n if (!this.antialiased()) {\n context.filter =\n 'url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxmaWx0ZXIgaWQ9ImZpbHRlciIgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj48ZmVDb21wb25lbnRUcmFuc2Zlcj48ZmVGdW5jUiB0eXBlPSJpZGVudGl0eSIvPjxmZUZ1bmNHIHR5cGU9ImlkZW50aXR5Ii8+PGZlRnVuY0IgdHlwZT0iaWRlbnRpdHkiLz48ZmVGdW5jQSB0eXBlPSJkaXNjcmV0ZSIgdGFibGVWYWx1ZXM9IjAgMSIvPjwvZmVDb21wb25lbnRUcmFuc2Zlcj48L2ZpbHRlcj48L3N2Zz4=#filter)';\n }\n\n const seed = this.roughSeed();\n if (seed === undefined) {\n context.restore();\n return;\n }\n\n const roughConfig = createRoughConfig(\n this.roughness(),\n this.bowing(),\n this.roughFillStyle(),\n this.roughFillWeight(),\n this.roughHachureAngle(),\n this.roughHachureGap(),\n seed,\n this.roughDisableMultiStroke(),\n this.roughDisableMultiStrokeFill(),\n );\n\n drawRoughPath(\n context,\n pathData,\n roughConfig,\n this.fill(),\n this.stroke(),\n this.lineWidth(),\n );\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 /**\n * Get the SVG path data string for this shape.\n *\n * @remarks\n * This method returns an SVG path data string that represents the shape's\n * geometry. The default implementation returns an empty string. Subclasses\n * should override this method to provide their actual path data.\n *\n * The path data can be used to create Path2D objects, passed to Rough.js,\n * or used for SVG export.\n *\n * @returns An SVG path data string (e.g., \"M 0 0 L 100 100 Z\")\n */\n @computed()\n protected getPathData(): string {\n return '';\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 {\n BBox,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n Vector2,\n clamp,\n} from '@canvas-commons/core';\nimport {CurveDrawingInfo} from '../curves/CurveDrawingInfo';\nimport {CurvePoint} from '../curves/CurvePoint';\nimport {CurveProfile, profileToSVGPathData} from '../curves/CurveProfile';\nimport {getPointAtDistance} from '../curves/getPointAtDistance';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport {DesiredLength} from '../partials';\nimport {lineTo, moveTo, resolveCanvasStyle} from '../utils';\nimport {Shape, ShapeProps} 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 declare public 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 declare public 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 declare public 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 declare public 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 declare public 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 declare public 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 declare public 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 declare public 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 @computed()\n protected override getPathData(): string {\n return profileToSVGPathData(this.profile());\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 {BBox, SerializedVector2, Vector2} from '@canvas-commons/core';\nimport {CurveProfile} from '../curves';\nimport {PolynomialSegment} from '../curves/PolynomialSegment';\nimport {computed} from '../decorators';\nimport {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 offset = size.mul(this.anchor()).scale(0.5).transformAsPoint(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 {Vector2} from '@canvas-commons/core';\nimport {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 /**\n * Convert this segment to SVG path commands.\n *\n * @param start - Start distance along the segment (0 to arcLength)\n * @param end - End distance along the segment (0 to arcLength)\n * @param move - Whether to include a moveTo command at the start\n * @returns SVG path data string for this segment\n */\n public abstract toSVGCommands(\n start: number,\n end: number,\n move: boolean,\n ): string;\n}\n","import {Vector2, clamp} from '@canvas-commons/core';\nimport {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 public toSVGCommands(from = 0, to = 1, move = false): string {\n const startPos = this.getPoint(from).position;\n const endPos = this.getPoint(to).position;\n\n const commands: string[] = [];\n if (move) {\n commands.push(`M ${startPos.x} ${startPos.y}`);\n }\n\n if (Math.abs(this.angle) > 0.0001) {\n const angleCovered = (to - from) * Math.abs(this.angle);\n const largeArc = angleCovered > Math.PI ? 1 : 0;\n const sweep = this.counter ? 0 : 1;\n\n commands.push(\n `A ${this.radius} ${this.radius} 0 ${largeArc} ${sweep} ${endPos.x} ${endPos.y}`,\n );\n }\n\n return commands.join(' ');\n }\n}\n","import {clamp} from '@canvas-commons/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 {BBox, Vector2} from '@canvas-commons/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 {Vector2, clamp, remap} from '@canvas-commons/core';\nimport {CurvePoint} from './CurvePoint';\nimport {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 {BBox, Vector2} from '@canvas-commons/core';\nimport {moveTo} from '../utils';\nimport {CurvePoint} from './CurvePoint';\nimport {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 => point.transformAsPoint(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 public toSVGCommands(start = 0, end = 1, move = true): string {\n let curve: PolynomialSegment | null = null;\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 const startT = this.pointSampler.distanceToT(startDistance);\n const 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 const commands: string[] = [];\n if (move) {\n commands.push(`M ${points[0].x} ${points[0].y}`);\n }\n commands.push((curve ?? this).doSVGCommands());\n\n return commands.join(' ');\n }\n\n protected abstract doDraw(context: CanvasRenderingContext2D | Path2D): void;\n protected abstract doSVGCommands(): string;\n}\n","import {Vector2, lazy} from '@canvas-commons/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 override doSVGCommands(): string {\n return `C ${this.p1.x} ${this.p1.y} ${this.p2.x} ${this.p2.y} ${this.p3.x} ${this.p3.y}`;\n }\n\n protected static getLength(\n p0: Vector2,\n p1: Vector2,\n p2: Vector2,\n p3: Vector2,\n ): number {\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 {Vector2} from '@canvas-commons/core';\nimport {lineTo, moveTo} from '../utils';\nimport {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 public toSVGCommands(start = 0, end = 1, move = false): string {\n const from = this.from.add(this.vector.scale(start));\n const to = this.from.add(this.vector.scale(end));\n const commands: string[] = [];\n\n if (move) {\n commands.push(`M ${from.x} ${from.y}`);\n }\n commands.push(`L ${to.x} ${to.y}`);\n\n return commands.join(' ');\n }\n}\n","import {BBox, Spacing, Vector2} from '@canvas-commons/core';\nimport {adjustRectRadius} from '../utils';\nimport {CircleSegment} from './CircleSegment';\nimport {CubicBezierSegment} from './CubicBezierSegment';\nimport {CurveProfile} from './CurveProfile';\nimport {LineSegment} from './LineSegment';\nimport {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 {\n BBox,\n PossibleSpacing,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n SpacingSignal,\n} from '@canvas-commons/core';\nimport {getRectProfile} from '../curves/getRectProfile';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport {spacingSignal} from '../decorators/spacingSignal';\nimport {DesiredLength} from '../partials';\nimport {PathDataBuilder, drawRoundRect, roundedRectToSVGPath} from '../utils';\nimport {Curve, CurveProps} 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 declare public 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 declare public 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 declare public 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 @computed()\n protected override getPathData(): string {\n const box = BBox.fromSizeCentered(this.size());\n const radius = this.radius();\n const hasRoundedCorners =\n radius.top > 0 ||\n radius.right > 0 ||\n radius.bottom > 0 ||\n radius.left > 0;\n\n if (hasRoundedCorners || this.smoothCorners()) {\n return roundedRectToSVGPath(\n box,\n radius,\n this.smoothCorners(),\n this.cornerSharpness(),\n );\n }\n\n const builder = new PathDataBuilder();\n builder.moveTo(box.left, box.top);\n builder.lineTo(box.right, box.top);\n builder.lineTo(box.right, box.bottom);\n builder.lineTo(box.left, box.bottom);\n builder.closePath();\n return builder.toString();\n }\n\n protected override getPath(): Path2D {\n if (this.requiresProfile()) {\n return this.curveDrawingInfo().path;\n }\n\n const pathData = this.getPathData();\n if (pathData) {\n return new Path2D(pathData);\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 {\n all,\n DEFAULT,\n easeInOutCubic,\n InterpolationFunction,\n modify,\n PossibleVector2,\n Reference,\n SignalValue,\n SimpleSignal,\n threadable,\n ThreadGenerator,\n TimingFunction,\n tween,\n unwrap,\n Vector2,\n} from '@canvas-commons/core';\nimport {cloneable, computed, signal} from '../decorators';\nimport {Curve} from './Curve';\nimport {Node, NodeProps} from './Node';\nimport {Rect, RectProps} from './Rect';\n\nexport interface CameraProps extends NodeProps {\n /**\n * {@inheritDoc Camera.scene}\n */\n scene?: Node;\n\n /**\n * {@inheritDoc Camera.zoom}\n */\n zoom?: SignalValue<number>;\n}\n\n/**\n * A node representing an orthographic camera.\n *\n * @preview\n * ```tsx editor\n * import {Camera, Circle, makeScene2D, Rect} from '@canvas-commons/2d';\n * import {all, createRef} from '@canvas-commons/core';\n *\n * export default makeScene2D(function* (view) {\n * const camera = createRef<Camera>();\n * const rect = createRef<Rect>();\n * const circle = createRef<Circle>();\n *\n * view.add(\n * <>\n * <Camera ref={camera}>\n * <Rect\n * ref={rect}\n * fill={'lightseagreen'}\n * size={100}\n * position={[100, -50]}\n * />\n * <Circle\n * ref={circle}\n * fill={'hotpink'}\n * size={120}\n * position={[-100, 50]}\n * />\n * </Camera>\n * </>,\n * );\n *\n * yield* all(\n * camera().centerOn(rect(), 3),\n * camera().rotation(180, 3),\n * camera().zoom(1.8, 3),\n * );\n * yield* camera().centerOn(circle(), 2);\n * yield* camera().reset(1);\n * });\n * ```\n */\nexport class Camera extends Node {\n /**\n * The scene node that the camera is rendering.\n */\n @signal()\n declare public readonly scene: SimpleSignal<Node, this>;\n\n public constructor({children, ...props}: CameraProps) {\n super(props);\n\n if (!this.scene()) {\n this.scene(new Node({}));\n }\n\n if (children) {\n this.scene().add(children);\n }\n\n const scene = this.scene();\n if (scene.parent() !== this) {\n scene.parent(this);\n }\n }\n\n protected setScene(value: SignalValue<Node>) {\n const previous = this.scene.context.raw();\n this.scene.context.setter(value);\n const current = this.scene.context.raw();\n if (previous instanceof Node && previous !== current) {\n previous.parent(null);\n }\n if (current instanceof Node && current.parent() !== this) {\n current.parent(this);\n }\n }\n\n /**\n * The zoom level of the camera.\n *\n * @defaultValue 1\n */\n @cloneable(false)\n @signal()\n declare public readonly zoom: SimpleSignal<number, this>;\n\n protected getZoom(): number {\n return 1 / this.scale.x();\n }\n\n protected setZoom(value: SignalValue<number>) {\n this.scale(modify(value, unwrapped => 1 / unwrapped));\n }\n\n protected getDefaultZoom() {\n return this.scale.x.context.getInitial();\n }\n\n protected *tweenZoom(\n value: SignalValue<number>,\n duration: number,\n timingFunction: TimingFunction,\n interpolationFunction: InterpolationFunction<number>,\n ): ThreadGenerator {\n const from = this.scale.x();\n yield* tween(duration, v => {\n this.zoom(\n 1 / interpolationFunction(from, 1 / unwrap(value), timingFunction(v)),\n );\n });\n }\n\n /**\n * Resets the camera's position, rotation and zoom level to their original\n * values.\n *\n * @param duration - The duration of the tween.\n * @param timingFunction - The timing function to use for the tween.\n */\n @threadable()\n public *reset(\n duration: number,\n timingFunction: TimingFunction = easeInOutCubic,\n ): ThreadGenerator {\n yield* all(\n this.position(DEFAULT, duration, timingFunction),\n this.zoom(DEFAULT, duration, timingFunction),\n this.rotation(DEFAULT, duration, timingFunction),\n );\n }\n\n /**\n * Centers the camera on the specified position without changing the zoom\n * level.\n *\n * @param position - The position to center the camera on.\n * @param duration - The duration of the tween.\n * @param timingFunction - The timing function to use for the tween.\n * @param interpolationFunction - The interpolation function to use for the\n * tween.\n */\n public centerOn(\n position: PossibleVector2,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): ThreadGenerator;\n /**\n * Centers the camera on the specified node without changing the zoom level.\n *\n * @param node - The node to center the camera on.\n * @param duration - The duration of the tween.\n * @param timingFunction - The timing function to use for the tween.\n * @param interpolationFunction - The interpolation function to use for the\n * tween.\n */\n public centerOn(\n node: Node,\n duration: number,\n timingFunction?: TimingFunction,\n interpolationFunction?: InterpolationFunction<Vector2>,\n ): ThreadGenerator;\n @threadable()\n public *centerOn(\n positionOrNode: Node | PossibleVector2,\n duration: number,\n timing: TimingFunction = easeInOutCubic,\n interpolationFunction: InterpolationFunction<Vector2> = Vector2.lerp,\n ): ThreadGenerator {\n const position =\n positionOrNode instanceof Node\n ? positionOrNode.position\n .abs()\n .transformAsPoint(this.scene().worldToLocal())\n : positionOrNode;\n yield* this.position(position, duration, timing, interpolationFunction);\n }\n\n /**\n * Makes the camera follow a path specified by the provided curve.\n *\n * @remarks\n * This will not change the orientation of the camera. To make the camera\n * orient itself along the curve, use {@link followCurveWithRotation} or\n * {@link followCurveWithRotationReverse}.\n *\n * If you want to follow the curve in reverse, use {@link followCurveReverse}.\n *\n * @param curve - The curve to follow.\n * @param duration - The duration of the tween.\n * @param timing - The timing function to use for the tween.\n */\n @threadable()\n public *followCurve(\n curve: Curve,\n duration: number,\n timing: TimingFunction = easeInOutCubic,\n ): ThreadGenerator {\n yield* tween(duration, value => {\n const t = timing(value);\n const point = curve\n .getPointAtPercentage(t)\n .position.transformAsPoint(curve.localToWorld());\n\n this.position(point);\n });\n }\n\n /**\n * Makes the camera follow a path specified by the provided curve in reverse.\n *\n * @remarks\n * This will not change the orientation of the camera. To make the camera\n * orient itself along the curve, use {@link followCurveWithRotation} or\n * {@link followCurveWithRotationReverse}.\n *\n * If you want to follow the curve forward, use {@link followCurve}.\n *\n * @param curve - The curve to follow.\n * @param duration - The duration of the tween.\n * @param timing - The timing function to use for the tween.\n */\n @threadable()\n public *followCurveReverse(\n curve: Curve,\n duration: number,\n timing: TimingFunction = easeInOutCubic,\n ) {\n yield* tween(duration, value => {\n const t = 1 - timing(value);\n const point = curve\n .getPointAtPercentage(t)\n .position.transformAsPoint(curve.localToWorld());\n\n this.position(point);\n });\n }\n\n /**\n * Makes the camera follow a path specified by the provided curve while\n * pointing the camera the direction of the tangent.\n *\n * @remarks\n * To make the camera follow the curve without changing its orientation, use\n * {@link followCurve} or {@link followCurveReverse}.\n *\n * If you want to follow the curve in reverse, use\n * {@link followCurveWithRotationReverse}.\n *\n * @param curve - The curve to follow.\n * @param duration - The duration of the tween.\n * @param timing - The timing function to use for the tween.\n */\n @threadable()\n public *followCurveWithRotation(\n curve: Curve,\n duration: number,\n timing: TimingFunction = easeInOutCubic,\n ) {\n yield* tween(duration, value => {\n const t = timing(value);\n const {position, normal} = curve.getPointAtPercentage(t);\n const point = position.transformAsPoint(curve.localToWorld());\n const angle = normal.flipped.perpendicular.degrees;\n\n this.position(point);\n this.rotation(angle);\n });\n }\n\n /**\n * Makes the camera follow a path specified by the provided curve in reverse\n * while pointing the camera the direction of the tangent.\n *\n * @remarks\n * To make the camera follow the curve without changing its orientation, use\n * {@link followCurve} or {@link followCurveReverse}.\n *\n * If you want to follow the curve forward, use\n * {@link followCurveWithRotation}.\n *\n * @param curve - The curve to follow.\n * @param duration - The duration of the tween.\n * @param timing - The timing function to use for the tween.\n */\n @threadable()\n public *followCurveWithRotationReverse(\n curve: Curve,\n duration: number,\n timing: TimingFunction = easeInOutCubic,\n ) {\n yield* tween(duration, value => {\n const t = 1 - timing(value);\n const {position, normal} = curve.getPointAtPercentage(t);\n const point = position.transformAsPoint(curve.localToWorld());\n const angle = normal.flipped.perpendicular.degrees;\n\n this.position(point);\n this.rotation(angle);\n });\n }\n\n protected override transformContext(context: CanvasRenderingContext2D) {\n const matrix = this.localToParent().inverse();\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 * Extend the `localToWorld` chain so descendants of the camera's scene\n * end up in canvas-pixel coordinates that match where they actually\n * render.\n */\n @computed()\n public override localToWorld(): DOMMatrix {\n const parent = this.parent();\n const matrix = this.localToParent().inverse();\n return parent ? parent.localToWorld().multiply(matrix) : matrix;\n }\n\n /**\n * Override parentToWorld to fix gizmo drawing; may have side effects on the\n * absolute position of the camera, but direct reads from position\n * should be fine.\n *\n * If you need the absolute position of the camera, use\n * `view.localToWorld().transformPoint(camera.position())` instead.\n */\n @computed()\n public override parentToWorld(): DOMMatrix {\n return this.localToParent();\n }\n\n public override hit(position: Vector2): Node | null {\n const local = position.transformAsPoint(this.localToParent());\n return this.scene().hit(local);\n }\n\n protected override drawChildren(context: CanvasRenderingContext2D) {\n this.scene().render(context);\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public static Stage({\n children,\n cameraRef,\n scene,\n ...props\n }: RectProps & {cameraRef?: Reference<Camera>; scene?: Node}) {\n const camera = new Camera({scene: scene, children});\n\n cameraRef?.(camera);\n\n return new Rect({\n clip: true,\n ...props,\n children: [camera],\n });\n }\n}\n","import {Vector2, lazy} from '@canvas-commons/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 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 protected override doSVGCommands(): string {\n return `Q ${this.p1.x} ${this.p1.y} ${this.p2.x} ${this.p2.y}`;\n }\n}\n","import {Vector2, clamp} from '@canvas-commons/core';\nimport {CubicBezierSegment} from './CubicBezierSegment';\nimport {CurveProfile} from './CurveProfile';\nimport {KnotInfo} from './KnotInfo';\nimport {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 if (knots.length < 2) {\n return profile;\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 {PlaybackState, SimpleSignal, lazy} from '@canvas-commons/core';\nimport {initial, signal} from '../decorators';\nimport {nodeName} from '../decorators/nodeName';\nimport {useScene2D} from '../scenes/useScene2D';\nimport type {Node} from './Node';\nimport {Rect, RectProps} from './Rect';\n\nexport interface View2DProps extends RectProps {\n assetHash: string;\n}\n\n@nodeName('View2D')\nexport class View2D extends Rect {\n @lazy(() => {\n const frameID = 'canvas-commons-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.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 declare public readonly playbackState: SimpleSignal<PlaybackState, this>;\n\n @initial(0)\n @signal()\n declare public readonly globalTime: SimpleSignal<number, this>;\n\n @signal()\n declare public readonly assetHash: SimpleSignal<string, this>;\n\n public constructor(props: View2DProps) {\n super({\n composite: true,\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 render(context: CanvasRenderingContext2D) {\n this.computedSize();\n this.computedPosition();\n 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 {BBox, DEG2RAD, Matrix2D, Vector2, lazy} from '@canvas-commons/core';\nimport {View2D} from '../components/View2D';\nimport {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 pAccent = startPoint\n .sub(endPoint)\n .div(2)\n .transform(Matrix2D.fromRotation(-xAxisRotationDegree).domMatrix);\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 this.center = cAccent\n .transform(this.xAxisRotationMatrix)\n .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 return this.radius\n .mul(Vector2.fromRadians(angle))\n .transform(this.xAxisRotationMatrix)\n .add(this.center);\n }\n\n public getAngleDerivative(angle: number) {\n return new Vector2(\n -this.radius.x * Math.sin(angle),\n this.radius.y * Math.cos(angle),\n ).transform(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\n public get arcLength(): number {\n return this.length;\n }\n\n public toSVGCommands(start = 0, end = 1, move = false): string {\n const startPos = this.getPoint(start).position;\n const endPos = this.getPoint(end).position;\n\n const commands: string[] = [];\n if (move) {\n commands.push(`M ${startPos.x} ${startPos.y}`);\n }\n\n const angleCovered = (end - start) * Math.abs(this.deltaAngle);\n const largeArc = angleCovered > Math.PI ? 1 : 0;\n\n commands.push(\n `A ${this.radius.x} ${this.radius.y} ${this.xAxisRotationDegree} ${largeArc} ${this.sweepFlag} ${endPos.x} ${endPos.y}`,\n );\n\n return commands.join(' ');\n }\n}\n","import {Vector2} from '@canvas-commons/core';\nimport {ArcSegment} from './ArcSegment';\nimport {CurveProfile} from './CurveProfile';\nimport {LineSegment} from './LineSegment';\nimport {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 {Vector2, clamp} from '@canvas-commons/core';\nimport {CircleSegment} from './CircleSegment';\nimport {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 {\n BBox,\n DEG2RAD,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n} from '@canvas-commons/core';\nimport {CurveProfile, getCircleProfile} from '../curves';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport {DesiredLength} from '../partials';\nimport {PathDataBuilder} from '../utils';\nimport {Curve, CurveProps} 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 '@canvas-commons/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 '@canvas-commons/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 '@canvas-commons/2d';\n * import {createRef} from '@canvas-commons/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 '@canvas-commons/2d';\n * import {createRef} from '@canvas-commons/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 '@canvas-commons/2d';\n * import {all, createRef, easeInCubic, easeOutCubic} from '@canvas-commons/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 declare public 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 declare public 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 declare public 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 declare public 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 @computed()\n protected override getPathData(): string {\n const builder = new PathDataBuilder();\n const start = this.startAngle() * DEG2RAD;\n let end = this.endAngle() * DEG2RAD;\n const size = this.size().scale(0.5);\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 builder.moveTo(0, 0);\n }\n\n builder.ellipse(\n 0,\n 0,\n size.x,\n size.y,\n 0,\n start,\n end,\n this.counterclockwise(),\n );\n\n if (closed) {\n builder.closePath();\n }\n\n return builder.toString();\n }\n\n protected override getPath(): Path2D {\n if (this.requiresProfile()) {\n return this.curveDrawingInfo().path;\n }\n\n const pathData = this.getPathData();\n if (pathData) {\n return new Path2D(pathData);\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 {\n BBox,\n createSignal,\n experimentalLog,\n map,\n SerializedVector2,\n Signal,\n SignalValue,\n SimpleSignal,\n ThreadGenerator,\n TimingFunction,\n unwrap,\n useLogger,\n useScene,\n Vector2,\n} from '@canvas-commons/core';\nimport {\n CodeCursor,\n CodeFragmentDrawingInfo,\n CodeHighlighter,\n CodePoint,\n CodeRange,\n CodeSelection,\n CodeSignal,\n codeSignal,\n CodeSignalContext,\n findAllCodeRanges,\n isPointInCodeSelection,\n lines,\n parseCodeSelection,\n PossibleCodeScope,\n PossibleCodeSelection,\n resolveScope,\n} from '../code';\nimport {computed, initial, nodeName, parser, signal} from '../decorators';\nimport {DesiredLength} from '../partials';\nimport {Shape, ShapeProps} from './Shape';\n\n/**\n * @experimental\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 *\n * @experimental\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 * @preview\n * ```tsx editor\n * import {Code, makeScene2D} from '@canvas-commons/2d';\n * import {createRef} from '@canvas-commons/core';\n *\n * export default makeScene2D(function* (view) {\n * const code = createRef<Code>();\n *\n * view.add(\n * <Code\n * ref={code}\n * anchor={-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('Code')\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: SignalValue<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 /**\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 declare public readonly highlighter: SimpleSignal<\n CodeHighlighter | null,\n this\n >;\n\n /**\n * The code to display.\n */\n @codeSignal()\n declare public 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 * @experimental\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 declare public 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 declare public 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 highlighter: Code.defaultHighlighter,\n ...props,\n });\n }\n\n /**\n * Create a child code signal.\n *\n * @param initial - The initial code.\n */\n public createSignal(\n initial: SignalValue<PossibleCodeScope>,\n ): 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 search for.\n * When a string is passed, it looks for **exact matches**.\n * When a RegExp object is passed, it will match against it.\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 search for.\n * When a string is passed, it looks for **exact matches**.\n * When a RegExp object is passed, it will match against it.\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 search for.\n * When a string is passed, it looks for **exact matches**.\n * When a RegExp object is passed, it will match against it.\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 bounding 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 draw(context: CanvasRenderingContext2D): 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 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 {\n PossibleVector2,\n SignalValue,\n Vector2Signal,\n} from '@canvas-commons/core';\nimport {CubicBezierSegment} from '../curves';\nimport {PolynomialSegment} from '../curves/PolynomialSegment';\nimport {computed, vector2Signal} from '../decorators';\nimport {bezierCurveTo, lineTo, moveTo} from '../utils';\nimport {Bezier, BezierOverlayInfo} from './Bezier';\nimport {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 '@canvas-commons/2d';\n * import {createRef} from '@canvas-commons/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 declare public readonly p0: Vector2Signal<this>;\n\n /**\n * The first control point of the Bézier curve.\n */\n @vector2Signal('p1')\n declare public readonly p1: Vector2Signal<this>;\n\n /**\n * The second control point of the Bézier curve.\n */\n @vector2Signal('p2')\n declare public readonly p2: Vector2Signal<this>;\n\n /**\n * The end point of the Bézier curve.\n */\n @vector2Signal('p3')\n declare public 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 {\n PossibleVector2,\n SignalValue,\n SimpleSignal,\n Vector2Signal,\n map,\n} from '@canvas-commons/core';\nimport {initial, nodeName, signal, vector2Signal} from '../decorators';\nimport {Shape, ShapeProps} 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 '@canvas-commons/2d';\n * import {all, createRef} from '@canvas-commons/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 declare public 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 declare public 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 declare public 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 {Vector2} from '@canvas-commons/core';\nimport {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 {Vector2, clamp} from '@canvas-commons/core';\nimport parse, {PathCommand} from 'parse-svg-path';\nimport {ArcSegment} from './ArcSegment';\nimport {CubicBezierSegment} from './CubicBezierSegment';\nimport {CurveProfile} from './CurveProfile';\nimport {LineSegment} from './LineSegment';\nimport {QuadBezierSegment} from './QuadBezierSegment';\nimport {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 {CurveProfile} from '../curves/CurveProfile';\nimport {createCurveProfileLerp} from '../curves/createCurveProfileLerp';\nimport {getPathProfile} from '../curves/getPathProfile';\nimport {PathMorpher} from './PathMorpher';\n\nfunction curveProfileToPath(profile: CurveProfile): string {\n const parts: string[] = [];\n let lastEnd: {x: number; y: number} | null = null;\n\n for (const segment of profile.segments) {\n const start = segment.getPoint(0).position;\n const end = segment.getPoint(1).position;\n\n if (!lastEnd || start.x !== lastEnd.x || start.y !== lastEnd.y) {\n parts.push(`M${start.x},${start.y}`);\n }\n parts.push(`L${end.x},${end.y}`);\n lastEnd = end;\n }\n\n return parts.join('');\n}\n\n/**\n * Create a path morpher that uses the Kute.js-inspired polygon interpolation\n * algorithm. Paths are sampled into polygons, point counts are equalized, and\n * corresponding points are linearly interpolated.\n */\nexport function defaultMorpher(): PathMorpher {\n return {\n createInterpolator(fromPath: string, toPath: string) {\n const fromProfile = getPathProfile(fromPath);\n const toProfile = getPathProfile(toPath);\n const interpolator = createCurveProfileLerp(fromProfile, toProfile);\n\n return (progress: number): string => {\n if (progress <= 0) return fromPath;\n if (progress >= 1) return toPath;\n return curveProfileToPath(interpolator(progress));\n };\n },\n };\n}\n","import {PathMorpher} from './PathMorpher';\n\nexport interface ManimMorpherOptions {\n alignPoints?: boolean;\n}\n\ninterface CubicSegment {\n p0: [number, number];\n p1: [number, number];\n p2: [number, number];\n p3: [number, number];\n}\n\ntype Subpath = CubicSegment[];\n\nfunction lineToCubic(\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n): CubicSegment {\n return {\n p0: [x0, y0],\n p1: [x0 + (x1 - x0) / 3, y0 + (y1 - y0) / 3],\n p2: [x0 + (2 * (x1 - x0)) / 3, y0 + (2 * (y1 - y0)) / 3],\n p3: [x1, y1],\n };\n}\n\nfunction quadToCubic(\n x0: number,\n y0: number,\n cpx: number,\n cpy: number,\n x1: number,\n y1: number,\n): CubicSegment {\n return {\n p0: [x0, y0],\n p1: [x0 + (2 * (cpx - x0)) / 3, y0 + (2 * (cpy - y0)) / 3],\n p2: [x1 + (2 * (cpx - x1)) / 3, y1 + (2 * (cpy - y1)) / 3],\n p3: [x1, y1],\n };\n}\n\nfunction arcToCubic(\n x0: number,\n y0: number,\n rx: number,\n ry: number,\n xRotation: number,\n largeArc: number,\n sweep: number,\n x1: number,\n y1: number,\n): CubicSegment[] {\n if (rx === 0 || ry === 0) return [lineToCubic(x0, y0, x1, y1)];\n\n const sinPhi = Math.sin((xRotation * Math.PI) / 180);\n const cosPhi = Math.cos((xRotation * Math.PI) / 180);\n\n const xp = (cosPhi * (x0 - x1)) / 2 + (sinPhi * (y0 - y1)) / 2;\n const yp = (-sinPhi * (x0 - x1)) / 2 + (cosPhi * (y0 - y1)) / 2;\n\n let rxSq = rx * rx;\n let rySq = ry * ry;\n const xpSq = xp * xp;\n const ypSq = yp * yp;\n\n const lambda = xpSq / rxSq + ypSq / rySq;\n if (lambda > 1) {\n const scale = Math.sqrt(lambda);\n rx *= scale;\n ry *= scale;\n rxSq = rx * rx;\n rySq = ry * ry;\n }\n\n const denom = rxSq * ypSq + rySq * xpSq;\n if (denom === 0) return [lineToCubic(x0, y0, x1, y1)];\n\n let sq = Math.max(0, (rxSq * rySq - denom) / denom);\n sq = Math.sqrt(sq) * (largeArc === sweep ? -1 : 1);\n\n const cxp = (sq * rx * yp) / ry;\n const cyp = (-sq * ry * xp) / rx;\n\n const cx = cosPhi * cxp - sinPhi * cyp + (x0 + x1) / 2;\n const cy = sinPhi * cxp + cosPhi * cyp + (y0 + y1) / 2;\n\n function angle(ux: number, uy: number, vx: number, vy: number): number {\n const dot = ux * vx + uy * vy;\n const len = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy));\n let acos = Math.acos(Math.max(-1, Math.min(1, dot / len)));\n if (ux * vy - uy * vx < 0) acos = -acos;\n return acos;\n }\n\n const theta1 = angle(1, 0, (xp - cxp) / rx, (yp - cyp) / ry);\n let dtheta = angle(\n (xp - cxp) / rx,\n (yp - cyp) / ry,\n (-xp - cxp) / rx,\n (-yp - cyp) / ry,\n );\n\n if (!sweep && dtheta > 0) dtheta -= 2 * Math.PI;\n if (sweep && dtheta < 0) dtheta += 2 * Math.PI;\n\n const segments = Math.max(1, Math.ceil(Math.abs(dtheta) / (Math.PI / 2)));\n const segAngle = dtheta / segments;\n const alpha = (4 / 3) * Math.tan(segAngle / 4);\n\n const result: CubicSegment[] = [];\n for (let i = 0; i < segments; i++) {\n const a1 = theta1 + i * segAngle;\n const a2 = theta1 + (i + 1) * segAngle;\n\n const cos1 = Math.cos(a1);\n const sin1 = Math.sin(a1);\n const cos2 = Math.cos(a2);\n const sin2 = Math.sin(a2);\n\n const ep1x = rx * cos1;\n const ep1y = ry * sin1;\n const ep2x = rx * cos2;\n const ep2y = ry * sin2;\n\n const cp1x = ep1x - alpha * rx * sin1;\n const cp1y = ep1y + alpha * ry * cos1;\n const cp2x = ep2x + alpha * rx * sin2;\n const cp2y = ep2y - alpha * ry * cos2;\n\n result.push({\n p0: [\n cosPhi * ep1x - sinPhi * ep1y + cx,\n sinPhi * ep1x + cosPhi * ep1y + cy,\n ],\n p1: [\n cosPhi * cp1x - sinPhi * cp1y + cx,\n sinPhi * cp1x + cosPhi * cp1y + cy,\n ],\n p2: [\n cosPhi * cp2x - sinPhi * cp2y + cx,\n sinPhi * cp2x + cosPhi * cp2y + cy,\n ],\n p3: [\n cosPhi * ep2x - sinPhi * ep2y + cx,\n sinPhi * ep2x + cosPhi * ep2y + cy,\n ],\n });\n }\n return result;\n}\n\nfunction parseToCubicSubpaths(d: string): Subpath[] {\n const commands = d.match(/[MmLlHhVvCcSsQqTtAaZz][^MmLlHhVvCcSsQqTtAaZz]*/g);\n if (!commands) return [];\n\n const subpaths: Subpath[] = [];\n let currentSubpath: CubicSegment[] = [];\n let currentX = 0;\n let currentY = 0;\n let subpathStartX = 0;\n let subpathStartY = 0;\n let lastControlX = 0;\n let lastControlY = 0;\n\n function pushSegment(seg: CubicSegment) {\n currentSubpath.push(seg);\n currentX = seg.p3[0];\n currentY = seg.p3[1];\n }\n\n function flushSubpath() {\n if (currentSubpath.length > 0) {\n subpaths.push(currentSubpath);\n currentSubpath = [];\n }\n }\n\n for (const cmd of commands) {\n const type = cmd[0];\n const argStr = cmd.slice(1).trim();\n const args = (argStr.match(/-?[0-9]*\\.?[0-9]+(?:e[-+]?\\d+)?/gi) ?? []).map(\n Number,\n );\n\n switch (type) {\n case 'M':\n flushSubpath();\n currentX = args[0];\n currentY = args[1];\n subpathStartX = currentX;\n subpathStartY = currentY;\n for (let i = 2; i < args.length; i += 2) {\n pushSegment(lineToCubic(currentX, currentY, args[i], args[i + 1]));\n }\n break;\n case 'm':\n flushSubpath();\n currentX += args[0];\n currentY += args[1];\n subpathStartX = currentX;\n subpathStartY = currentY;\n for (let i = 2; i < args.length; i += 2) {\n pushSegment(\n lineToCubic(\n currentX,\n currentY,\n currentX + args[i],\n currentY + args[i + 1],\n ),\n );\n }\n break;\n case 'L':\n for (let i = 0; i < args.length; i += 2) {\n pushSegment(lineToCubic(currentX, currentY, args[i], args[i + 1]));\n }\n break;\n case 'l':\n for (let i = 0; i < args.length; i += 2) {\n pushSegment(\n lineToCubic(\n currentX,\n currentY,\n currentX + args[i],\n currentY + args[i + 1],\n ),\n );\n }\n break;\n case 'H':\n for (let i = 0; i < args.length; i++) {\n pushSegment(lineToCubic(currentX, currentY, args[i], currentY));\n }\n break;\n case 'h':\n for (let i = 0; i < args.length; i++) {\n pushSegment(\n lineToCubic(currentX, currentY, currentX + args[i], currentY),\n );\n }\n break;\n case 'V':\n for (let i = 0; i < args.length; i++) {\n pushSegment(lineToCubic(currentX, currentY, currentX, args[i]));\n }\n break;\n case 'v':\n for (let i = 0; i < args.length; i++) {\n pushSegment(\n lineToCubic(currentX, currentY, currentX, currentY + args[i]),\n );\n }\n break;\n case 'C':\n for (let i = 0; i < args.length; i += 6) {\n pushSegment({\n p0: [currentX, currentY],\n p1: [args[i], args[i + 1]],\n p2: [args[i + 2], args[i + 3]],\n p3: [args[i + 4], args[i + 5]],\n });\n lastControlX = args[i + 2];\n lastControlY = args[i + 3];\n }\n break;\n case 'c':\n for (let i = 0; i < args.length; i += 6) {\n const cp1x = currentX + args[i];\n const cp1y = currentY + args[i + 1];\n const cp2x = currentX + args[i + 2];\n const cp2y = currentY + args[i + 3];\n const endX = currentX + args[i + 4];\n const endY = currentY + args[i + 5];\n pushSegment({\n p0: [currentX, currentY],\n p1: [cp1x, cp1y],\n p2: [cp2x, cp2y],\n p3: [endX, endY],\n });\n lastControlX = cp2x;\n lastControlY = cp2y;\n }\n break;\n case 'S':\n for (let i = 0; i < args.length; i += 4) {\n const refX = 2 * currentX - lastControlX;\n const refY = 2 * currentY - lastControlY;\n pushSegment({\n p0: [currentX, currentY],\n p1: [refX, refY],\n p2: [args[i], args[i + 1]],\n p3: [args[i + 2], args[i + 3]],\n });\n lastControlX = args[i];\n lastControlY = args[i + 1];\n }\n break;\n case 's':\n for (let i = 0; i < args.length; i += 4) {\n const refX = 2 * currentX - lastControlX;\n const refY = 2 * currentY - lastControlY;\n const cp2x = currentX + args[i];\n const cp2y = currentY + args[i + 1];\n const endX = currentX + args[i + 2];\n const endY = currentY + args[i + 3];\n pushSegment({\n p0: [currentX, currentY],\n p1: [refX, refY],\n p2: [cp2x, cp2y],\n p3: [endX, endY],\n });\n lastControlX = cp2x;\n lastControlY = cp2y;\n }\n break;\n case 'Q':\n for (let i = 0; i < args.length; i += 4) {\n pushSegment(\n quadToCubic(\n currentX,\n currentY,\n args[i],\n args[i + 1],\n args[i + 2],\n args[i + 3],\n ),\n );\n lastControlX = args[i];\n lastControlY = args[i + 1];\n }\n break;\n case 'q':\n for (let i = 0; i < args.length; i += 4) {\n const cpx = currentX + args[i];\n const cpy = currentY + args[i + 1];\n const endX = currentX + args[i + 2];\n const endY = currentY + args[i + 3];\n pushSegment(quadToCubic(currentX, currentY, cpx, cpy, endX, endY));\n lastControlX = cpx;\n lastControlY = cpy;\n }\n break;\n case 'T':\n for (let i = 0; i < args.length; i += 2) {\n const cpx = 2 * currentX - lastControlX;\n const cpy = 2 * currentY - lastControlY;\n pushSegment(\n quadToCubic(currentX, currentY, cpx, cpy, args[i], args[i + 1]),\n );\n lastControlX = cpx;\n lastControlY = cpy;\n }\n break;\n case 't':\n for (let i = 0; i < args.length; i += 2) {\n const cpx = 2 * currentX - lastControlX;\n const cpy = 2 * currentY - lastControlY;\n const endX = currentX + args[i];\n const endY = currentY + args[i + 1];\n pushSegment(quadToCubic(currentX, currentY, cpx, cpy, endX, endY));\n lastControlX = cpx;\n lastControlY = cpy;\n }\n break;\n case 'A':\n for (let i = 0; i < args.length; i += 7) {\n const arcSegs = arcToCubic(\n currentX,\n currentY,\n args[i],\n args[i + 1],\n args[i + 2],\n args[i + 3],\n args[i + 4],\n args[i + 5],\n args[i + 6],\n );\n for (const seg of arcSegs) pushSegment(seg);\n }\n break;\n case 'a':\n for (let i = 0; i < args.length; i += 7) {\n const arcSegs = arcToCubic(\n currentX,\n currentY,\n args[i],\n args[i + 1],\n args[i + 2],\n args[i + 3],\n args[i + 4],\n currentX + args[i + 5],\n currentY + args[i + 6],\n );\n for (const seg of arcSegs) pushSegment(seg);\n }\n break;\n case 'Z':\n case 'z':\n if (currentX !== subpathStartX || currentY !== subpathStartY) {\n pushSegment(\n lineToCubic(currentX, currentY, subpathStartX, subpathStartY),\n );\n }\n flushSubpath();\n currentX = subpathStartX;\n currentY = subpathStartY;\n break;\n }\n }\n\n flushSubpath();\n return subpaths;\n}\n\nfunction degenerateSubpath(x: number, y: number): Subpath {\n return [\n {\n p0: [x, y],\n p1: [x, y],\n p2: [x, y],\n p3: [x, y],\n },\n ];\n}\n\nfunction subpathCenter(subpath: Subpath): [number, number] {\n let sx = 0;\n let sy = 0;\n let count = 0;\n for (const seg of subpath) {\n sx += seg.p0[0] + seg.p3[0];\n sy += seg.p0[1] + seg.p3[1];\n count += 2;\n }\n return count > 0 ? [sx / count, sy / count] : [0, 0];\n}\n\nfunction alignSubpathCounts(\n a: Subpath[],\n b: Subpath[],\n): [Subpath[], Subpath[]] {\n const maxLen = Math.max(a.length, b.length);\n const resultA: Subpath[] = [];\n const resultB: Subpath[] = [];\n\n for (let i = 0; i < maxLen; i++) {\n if (i < a.length && i < b.length) {\n resultA.push(a[i]);\n resultB.push(b[i]);\n } else if (i < a.length) {\n resultA.push(a[i]);\n const center = subpathCenter(a[i]);\n resultB.push(degenerateSubpath(center[0], center[1]));\n } else {\n const center = subpathCenter(b[i]);\n resultA.push(degenerateSubpath(center[0], center[1]));\n resultB.push(b[i]);\n }\n }\n\n return [resultA, resultB];\n}\n\nfunction splitCubicAt(\n seg: CubicSegment,\n t: number,\n): [CubicSegment, CubicSegment] {\n const [x0, y0] = seg.p0;\n const [x1, y1] = seg.p1;\n const [x2, y2] = seg.p2;\n const [x3, y3] = seg.p3;\n\n const ax = x0 + (x1 - x0) * t;\n const ay = y0 + (y1 - y0) * t;\n const bx = x1 + (x2 - x1) * t;\n const by = y1 + (y2 - y1) * t;\n const cx = x2 + (x3 - x2) * t;\n const cy = y2 + (y3 - y2) * t;\n\n const dx = ax + (bx - ax) * t;\n const dy = ay + (by - ay) * t;\n const ex = bx + (cx - bx) * t;\n const ey = by + (cy - by) * t;\n\n const fx = dx + (ex - dx) * t;\n const fy = dy + (ey - dy) * t;\n\n return [\n {p0: [x0, y0], p1: [ax, ay], p2: [dx, dy], p3: [fx, fy]},\n {p0: [fx, fy], p1: [ex, ey], p2: [cx, cy], p3: [x3, y3]},\n ];\n}\n\nfunction subdivideSegment(seg: CubicSegment, n: number): CubicSegment[] {\n if (n <= 1) return [seg];\n\n const result: CubicSegment[] = [];\n let remaining = seg;\n for (let i = 0; i < n - 1; i++) {\n const t = 1 / (n - i);\n const [left, right] = splitCubicAt(remaining, t);\n result.push(left);\n remaining = right;\n }\n result.push(remaining);\n return result;\n}\n\nfunction subdivideSubpath(subpath: Subpath, targetCount: number): Subpath {\n if (subpath.length >= targetCount) return subpath;\n\n const ratio = targetCount / subpath.length;\n const result: CubicSegment[] = [];\n let allocated = 0;\n\n for (let i = 0; i < subpath.length; i++) {\n const idealEnd = Math.round(ratio * (i + 1));\n const subdivisions = idealEnd - allocated;\n result.push(...subdivideSegment(subpath[i], subdivisions));\n allocated = idealEnd;\n }\n\n return result;\n}\n\nfunction alignSegmentCounts(a: Subpath, b: Subpath): [Subpath, Subpath] {\n if (a.length === b.length) return [a, b];\n\n const target = Math.max(a.length, b.length);\n return [subdivideSubpath(a, target), subdivideSubpath(b, target)];\n}\n\nfunction dist2(a: [number, number], b: [number, number]): number {\n const dx = a[0] - b[0];\n const dy = a[1] - b[1];\n return dx * dx + dy * dy;\n}\n\nfunction totalControlPointDistance(a: Subpath, b: Subpath): number {\n let total = 0;\n const len = Math.min(a.length, b.length);\n for (let i = 0; i < len; i++) {\n total += dist2(a[i].p0, b[i].p0);\n total += dist2(a[i].p1, b[i].p1);\n total += dist2(a[i].p2, b[i].p2);\n total += dist2(a[i].p3, b[i].p3);\n }\n return total;\n}\n\nfunction rotateCurvesToMinimizeDistance(from: Subpath, to: Subpath): Subpath {\n if (from.length <= 1) return from;\n\n const first = from[0];\n const last = from[from.length - 1];\n const isClosed =\n Math.abs(first.p0[0] - last.p3[0]) < 0.5 &&\n Math.abs(first.p0[1] - last.p3[1]) < 0.5;\n\n if (!isClosed) return from;\n\n let bestRotation = 0;\n let bestDistance = totalControlPointDistance(from, to);\n\n for (let r = 1; r < from.length; r++) {\n const rotated = [...from.slice(r), ...from.slice(0, r)];\n const d = totalControlPointDistance(rotated, to);\n if (d < bestDistance) {\n bestDistance = d;\n bestRotation = r;\n }\n }\n\n if (bestRotation === 0) return from;\n return [...from.slice(bestRotation), ...from.slice(0, bestRotation)];\n}\n\nfunction subpathsToPathString(subpaths: Subpath[]): string {\n const parts: string[] = [];\n for (const subpath of subpaths) {\n if (subpath.length === 0) continue;\n parts.push(`M${subpath[0].p0[0]},${subpath[0].p0[1]}`);\n for (const seg of subpath) {\n parts.push(\n `C${seg.p1[0]},${seg.p1[1]} ${seg.p2[0]},${seg.p2[1]} ${seg.p3[0]},${seg.p3[1]}`,\n );\n }\n }\n return parts.join('');\n}\n\nfunction lerpPoint(\n a: [number, number],\n b: [number, number],\n t: number,\n): [number, number] {\n return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];\n}\n\n/**\n * Create a path morpher that uses the Manim-inspired algorithm for\n * cubic-bezier-based path interpolation with intelligent subpath alignment,\n * segment equalization, and closed-path rotation optimization.\n */\nexport function manimMorpher(options: ManimMorpherOptions = {}): PathMorpher {\n const {alignPoints: doAlign = true} = options;\n\n return {\n createInterpolator(fromPath: string, toPath: string) {\n let fromSubpaths = parseToCubicSubpaths(fromPath);\n let toSubpaths = parseToCubicSubpaths(toPath);\n\n if (fromSubpaths.length === 0 || toSubpaths.length === 0) {\n return (progress: number) => (progress < 0.5 ? fromPath : toPath);\n }\n\n [fromSubpaths, toSubpaths] = alignSubpathCounts(fromSubpaths, toSubpaths);\n\n const alignedFrom: Subpath[] = [];\n const alignedTo: Subpath[] = [];\n\n for (let i = 0; i < fromSubpaths.length; i++) {\n const [af, at] = alignSegmentCounts(fromSubpaths[i], toSubpaths[i]);\n const rotated = doAlign ? rotateCurvesToMinimizeDistance(af, at) : af;\n alignedFrom.push(rotated);\n alignedTo.push(at);\n }\n\n return (progress: number): string => {\n if (progress <= 0) return fromPath;\n if (progress >= 1) return toPath;\n\n const result: Subpath[] = [];\n for (let i = 0; i < alignedFrom.length; i++) {\n const fromSp = alignedFrom[i];\n const toSp = alignedTo[i];\n const interpolated: CubicSegment[] = [];\n\n for (let j = 0; j < fromSp.length; j++) {\n interpolated.push({\n p0: lerpPoint(fromSp[j].p0, toSp[j].p0, progress),\n p1: lerpPoint(fromSp[j].p1, toSp[j].p1, progress),\n p2: lerpPoint(fromSp[j].p2, toSp[j].p2, progress),\n p3: lerpPoint(fromSp[j].p3, toSp[j].p3, progress),\n });\n }\n result.push(interpolated);\n }\n\n return subpathsToPathString(result);\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","export default `The 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://canvascommons.io/docs/media#images) about working with\nimages.\n`;\n","import {\n BBox,\n Color,\n DependencyContext,\n DetailedError,\n PossibleVector2,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n TimingFunction,\n Vector2,\n easeInOutCubic,\n isReactive,\n threadable,\n tween,\n useLogger,\n viaProxy,\n} from '@canvas-commons/core';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport {DesiredLength} from '../partials';\nimport {drawImage} from '../utils';\nimport {Rect, RectProps} from './Rect';\nimport imageWithoutSource from './__logs__/image-without-source';\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 '@canvas-commons/2d';\n * import {all, waitFor} from '@canvas-commons/core';\n * import {createRef} from '@canvas-commons/core';\n * import {makeScene2D} from '@canvas-commons/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('canvas-commons: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 declare public 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 declare public 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 declare public 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 rawSrc = this.src();\n let src = '';\n let key = '';\n if (rawSrc) {\n key = viaProxy(rawSrc);\n const url = new URL(key, 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 src = url.toString();\n }\n\n let image = Img.pool[key];\n if (!image) {\n image = document.createElement('img');\n image.crossOrigin = 'anonymous';\n image.src = src;\n Img.pool[key] = 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 reject(\n new DetailedError({\n message: `Failed to load an image`,\n remarks: `\\\nThe <code>src</code> property was set to:\n<pre><code>${rawSrc}</code></pre>\n...which resolved to the following url:\n<pre><code>${src}</code></pre>\nMake sure that source is correct and that the image exists.<br/>\n<a target='_blank' href='https://canvascommons.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 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 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 @threadable()\n protected *tweenSrc(\n value: SignalValue<string>,\n time: number,\n timingFunction: TimingFunction = easeInOutCubic,\n ) {\n const newSrc = isReactive(value) ? value() : value;\n const currentOpacity = this.opacity();\n const halfTime = time / 2;\n yield* tween(halfTime, v => {\n this.opacity(currentOpacity * (1 - timingFunction(v)));\n });\n this.src.context.setter(newSrc);\n yield* tween(halfTime, v => {\n this.opacity(currentOpacity * timingFunction(v));\n });\n }\n\n protected override collectAsyncResources() {\n super.collectAsyncResources();\n this.image();\n }\n}\n","export default `The 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","import {\n BBox,\n createSignal,\n PossibleVector2,\n SignalValue,\n SimpleSignal,\n threadable,\n ThreadGenerator,\n TimingFunction,\n tween,\n unwrap,\n useLogger,\n Vector2,\n} from '@canvas-commons/core';\nimport {CurveProfile, 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 lineWithoutPoints from './__logs__/line-without-points';\nimport {Curve, CurveProps} from './Curve';\nimport {Layout} from './Layout';\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 '@canvas-commons/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 '@canvas-commons/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 '@canvas-commons/2d';\n * import {createSignal} from '@canvas-commons/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 '@canvas-commons/2d';\n * import {createRef} from '@canvas-commons/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 = arcLength === 0 ? 0 : 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 = arcLength === 0 ? 0 : 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 let pointCount = Math.min(Math.round(length * density), pointsLeft) + 1;\n\n if (arcLength === 0) {\n pointCount = 2;\n }\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 declare public 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 declare public 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 offset = size.mul(this.anchor()).scale(0.5).transformAsPoint(matrix);\n\n context.fillStyle = 'white';\n context.strokeStyle = 'black';\n context.lineWidth = 1;\n\n const path = new Path2D();\n const points = (this.tweenedPoints() ?? this.parsedPoints()).map(point =>\n point.transformAsPoint(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 {\n BBox,\n createSignal,\n isReactive,\n SignalValue,\n SimpleSignal,\n threadable,\n TimingFunction,\n tween,\n Vector2,\n} from '@canvas-commons/core';\nimport {CurveProfile} from '../curves';\nimport {createCurveProfileLerp} from '../curves/createCurveProfileLerp';\nimport {getPathProfile} from '../curves/getPathProfile';\nimport {computed, signal} from '../decorators';\nimport {drawLine, drawPivot} from '../utils';\nimport {Curve, CurveProps} 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 declare public 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 offset = size.mul(this.anchor()).scale(0.5).transformAsPoint(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 {\n BBox,\n Matrix2D,\n PossibleSpacing,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n ThreadGenerator,\n TimingFunction,\n Vector2,\n all,\n clampRemap,\n delay,\n easeInOutSine,\n isReactive,\n lazy,\n threadable,\n tween,\n useLogger,\n} from '@canvas-commons/core';\nimport {computed, signal} from '../decorators';\nimport {PathMorpher, defaultMorpher} from '../morphers';\nimport {DesiredLength, PossibleCanvasStyle} from '../partials';\nimport {applyTransformDiff, getTransformDiff} from '../utils/diff';\nimport {Circle, CircleProps} from './Circle';\nimport {Img, ImgProps} from './Img';\nimport {Layout} from './Layout';\nimport {Line, LineProps} from './Line';\nimport {Node, NodeProps} from './Node';\nimport {Path, PathProps} from './Path';\nimport {Rect, RectProps} from './Rect';\nimport {Shape, ShapeProps} 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 morpher?: PathMorpher;\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 declare public readonly svg: SimpleSignal<string, this>;\n\n /**\n * Child to wrap all SVG node\n */\n public wrapper: Node;\n\n protected readonly morpher: PathMorpher;\n\n private lastTweenTargetSrc: string | null = null;\n private lastTweenTargetDocument: SVGDocument | null = null;\n\n public constructor(props: SVGProps) {\n const {morpher, ...rest} = props;\n super(rest);\n this.morpher = morpher ?? defaultMorpher();\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 const fromData = from.data();\n const toData = to.data();\n const interpolator = this.morpher.createInterpolator(fromData, toData);\n\n yield tween(\n duration,\n value => {\n const progress = timing(value);\n from.data.context.setter(interpolator(progress));\n },\n () => {\n from.data(toData);\n },\n );\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 let newSVG: SVGDocument;\n try {\n newSVG = this.parseSVG(newValue);\n } catch (e) {\n useLogger().warn(`Failed to parse SVG during tween: ${e}`);\n newSVG = {size: new Vector2(0, 0), nodes: []};\n }\n const currentSVG = this.document();\n\n if (currentSVG.nodes.length === 0 || newSVG.nodes.length === 0) {\n this.svg.context.setter(newValue);\n return;\n }\n\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 } catch (e) {\n useLogger().warn(`Failed to parse SVG document: ${e}`);\n return {\n size: new Vector2(0, 0),\n nodes: [],\n };\n } finally {\n this.lastTweenTargetSrc = null;\n this.lastTweenTargetDocument = null;\n }\n }\n\n /**\n * Get current document nodes.\n */\n @computed()\n protected documentNodes() {\n return this.document().nodes.map(node => node.shape);\n }\n\n /**\n * Convert SVG colors in Shape properties to Canvas Commons colors.\n * @param param - Shape properties.\n * @returns Converted Shape properties.\n */\n private processElementStyle({\n fill,\n stroke,\n lineWidth,\n strokeFirst,\n ...rest\n }: ShapeProps): ShapeProps {\n return {\n fill: fill === 'currentColor' ? this.fill : SVG.processSVGColor(fill),\n stroke:\n stroke === undefined || stroke === 'currentColor'\n ? this.stroke\n : SVG.processSVGColor(stroke),\n lineWidth: lineWidth || this.lineWidth,\n strokeFirst: strokeFirst ?? this.strokeFirst,\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\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 CanvasCommons 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 Canvas Commons color.\n * @param color - SVG color.\n * @returns Canvas Commons 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 Canvas Commons 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 === 'svg' && child instanceof SVGSVGElement) {\n let nestedTransform = transformMatrix;\n\n if (child.hasAttribute('viewBox')) {\n const vb = child.viewBox.baseVal;\n const width = SVG.parseNumberAttribute(child, 'width') || vb.width;\n const height = SVG.parseNumberAttribute(child, 'height') || vb.height;\n\n const scaleX = vb.width > 0 ? width / vb.width : 1;\n const scaleY = vb.height > 0 ? height / vb.height : 1;\n\n nestedTransform = nestedTransform\n .scale(scaleX, scaleY)\n .translate(-vb.x, -vb.y);\n }\n\n yield* SVG.extractGroupNodes(child, svgRoot, nestedTransform, 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","import {\n ColorSignal,\n DependencyContext,\n PossibleColor,\n SignalValue,\n SimpleSignal,\n TimingFunction,\n isReactive,\n threadable,\n useLogger,\n} from '@canvas-commons/core';\nimport {colorSignal, computed, initial, signal} from '../decorators';\nimport {SVG, SVGProps} from './SVG';\n\nexport interface IconProps extends Omit<SVGProps, 'svg'> {\n /**\n * {@inheritDoc Icon.icon}\n */\n icon: SignalValue<string>;\n\n /**\n * {@inheritDoc Icon.color}\n */\n color?: SignalValue<PossibleColor>;\n}\n\nconst PLACEHOLDER_SVG =\n '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><rect width=\"24\" height=\"24\" fill=\"none\"/></svg>';\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 SVG {\n private static iconSvgCache: Map<string, string> = new Map();\n private static pendingFetches: Map<string, Promise<string>> = new Map();\n\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 declare public readonly 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 declare public readonly color: ColorSignal<this>;\n\n public constructor(props: IconProps) {\n super({\n ...props,\n svg: () => this.iconSvg(),\n });\n }\n\n protected override collectAsyncResources(): void {\n super.collectAsyncResources();\n this.iconSvg();\n }\n\n @computed()\n protected iconSvg(): string {\n const iconId = this.icon();\n const color = this.color().hex();\n const cacheKey = `${iconId}::${color}`;\n\n const cached = Icon.iconSvgCache.get(cacheKey);\n if (cached !== undefined) {\n return cached;\n }\n\n if (iconId === null || iconId === undefined) {\n return PLACEHOLDER_SVG;\n }\n\n const fetchPromise = this.fetchIconSvg(iconId, color);\n DependencyContext.collectPromise(fetchPromise);\n\n return PLACEHOLDER_SVG;\n }\n\n private async fetchIconSvg(iconId: string, color: string): Promise<string> {\n const cacheKey = `${iconId}::${color}`;\n\n const cached = Icon.iconSvgCache.get(cacheKey);\n if (cached !== undefined) {\n return cached;\n }\n\n const pending = Icon.pendingFetches.get(cacheKey);\n if (pending !== undefined) {\n return pending;\n }\n\n const iconPath = iconId.replace(':', '/');\n const encodedColor = encodeURIComponent(color);\n const url = `https://api.iconify.design/${iconPath}.svg?color=${encodedColor}`;\n\n const fetchPromise = fetch(url)\n .then(response => {\n if (!response.ok) {\n throw new Error(`Failed to fetch icon: ${iconId}`);\n }\n return response.text();\n })\n .then(svg => {\n Icon.iconSvgCache.set(cacheKey, svg);\n Icon.pendingFetches.delete(cacheKey);\n return svg;\n })\n .catch(error => {\n Icon.pendingFetches.delete(cacheKey);\n useLogger().error(`Error fetching icon ${iconId}: ${error}`);\n return PLACEHOLDER_SVG;\n });\n\n Icon.pendingFetches.set(cacheKey, fetchPromise);\n return fetchPromise;\n }\n\n @threadable()\n protected *tweenIcon(\n value: SignalValue<string>,\n time: number,\n timingFunction: TimingFunction,\n ) {\n const newIconId = isReactive(value) ? value() : value;\n const color = this.color().hex();\n\n const newSvg: string = yield this.fetchIconSvg(newIconId, color);\n\n yield* this.svg(newSvg, time, timingFunction);\n this.icon.context.setter(newIconId);\n }\n}\n","import {\n PossibleVector2,\n Signal,\n SignalValue,\n Vector2,\n Vector2Signal,\n} from '@canvas-commons/core';\nimport {KnotInfo} from '../curves';\nimport {\n cloneable,\n compound,\n computed,\n initial,\n parser,\n signal,\n wrapper,\n} from '../decorators';\nimport {Node, NodeProps} 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 declare public 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 declare public 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 declare public 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: startHandle.transformAsPoint(this.localToParent()),\n endHandle: endHandle.transformAsPoint(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 {\n SerializedVector2,\n Signal,\n SignalValue,\n SimpleSignal,\n ThreadGenerator,\n TimingFunction,\n Vector2,\n all,\n delay,\n easeInOutCubic,\n lazy,\n threadable,\n tween,\n useLogger,\n} from '@canvas-commons/core';\nimport {liteAdaptor} from 'mathjax-full/js/adaptors/liteAdaptor.js';\nimport {RegisterHTMLHandler} from 'mathjax-full/js/handlers/html.js';\nimport {TeX} from 'mathjax-full/js/input/tex.js';\nimport {AllPackages} from 'mathjax-full/js/input/tex/AllPackages.js';\nimport {mathjax} from 'mathjax-full/js/mathjax.js';\nimport {SVG} from 'mathjax-full/js/output/svg.js';\nimport {OptionList} from 'mathjax-full/js/util/Options.js';\nimport {computed, initial, parser, signal} from '../decorators';\nimport {Curve} from './Curve';\nimport {Node} from './Node';\nimport {Path} from './Path';\nimport {Rect} from './Rect';\nimport {\n SVGDocument,\n SVGDocumentData,\n SVG as SVGNode,\n SVGProps,\n SVGShapeData,\n} from './SVG';\n\nconst Adaptor = liteAdaptor();\nRegisterHTMLHandler(Adaptor);\n\nconst 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\nexport interface LatexProps extends Omit<SVGProps, 'svg'> {\n tex?: SignalValue<string[] | string>;\n renderProps?: SignalValue<OptionList>;\n}\n\n/**\n * A node for animating equations with LaTeX.\n *\n * @preview\n * ```tsx editor\n * import {Latex, makeScene2D} from '@canvas-commons/2d';\n * import {createRef, waitFor} from '@canvas-commons/core';\n *\n * export default makeScene2D(function* (view) {\n * const tex = createRef<Latex>();\n * view.add(<Latex ref={tex} tex=\"{{y=}}{{a}}{{x^2}}\" fill=\"white\" />);\n *\n * yield* waitFor(0.2);\n * yield* tex().tex('{{y=}}{{a}}{{x^2}} + {{bx}}', 1);\n * yield* waitFor(0.2);\n * yield* tex().tex(\n * '{{y=}}{{\\\\left(}}{{a}}{{x^2}} + {{bx}}{{\\\\over 1}}{{\\\\right)}}',\n * 1,\n * );\n * yield* waitFor(0.2);\n * yield* tex().tex('{{y=}}{{a}}{{x^2}}', 1);\n * });\n * ```\n */\nexport class Latex extends SVGNode {\n @lazy(() => {\n return parseFloat(\n window.getComputedStyle(SVGNode.containerElement).fontSize,\n );\n })\n private static containerFontSize: number;\n private static svgContentsPool: Record<string, string> = {};\n private static texNodesPool: Record<string, SVGDocumentData> = {};\n private svgSubTexMap: Record<string, string[]> = {};\n\n @initial({})\n @signal()\n declare public readonly options: SimpleSignal<OptionList, this>;\n\n @initial('')\n @parser(function (this: Latex, value: string[] | string): string[] {\n const array = typeof value === 'string' ? [value] : value;\n return array\n .reduce<string[]>((prev, current) => {\n prev.push(...current.split(/{{(.*?)}}/));\n return prev;\n }, [])\n .filter(sub => sub.trim().length > 0);\n })\n @signal()\n declare public readonly tex: Signal<string[] | string, string[], this>;\n\n public constructor(props: LatexProps) {\n super({\n fontSize: 48,\n ...props,\n svg: '',\n });\n this.svg(this.latexSVG);\n }\n\n protected override calculateWrapperScale(\n documentSize: Vector2,\n parentSize: SerializedVector2<number | null>,\n ): Vector2 {\n if (parentSize.x || parentSize.y) {\n return super.calculateWrapperScale(documentSize, parentSize);\n }\n return new Vector2(this.fontSize() / Latex.containerFontSize);\n }\n\n @computed()\n protected latexSVG() {\n return this.texToSvg(this.tex());\n }\n\n private getNodeCharacterId({id}: SVGShapeData) {\n if (!id.includes('-')) return id;\n return id.substring(id.lastIndexOf('-') + 1);\n }\n\n protected override parseSVG(svg: string): SVGDocument {\n if (!this.svgSubTexMap[svg]) {\n return super.parseSVG(svg);\n }\n const subTexs = this.svgSubTexMap[svg].map(sub => sub.trim());\n const key = `[${subTexs.join(',')}]::${JSON.stringify(this.options())}`;\n const cached = Latex.texNodesPool[key];\n if (cached && (cached.size.x > 0 || cached.size.y > 0)) {\n return this.buildDocument(Latex.texNodesPool[key]);\n }\n const oldSVG = SVGNode.parseSVGData(svg);\n const oldNodes = [...oldSVG.nodes];\n\n const newNodes: SVGShapeData[] = [];\n const pendingFragments: {sub: string; nodeCount: number}[] = [];\n for (const sub of subTexs) {\n const subSvg = this.subTexToSVG(sub);\n const subNodes = SVGNode.parseSVGData(subSvg).nodes;\n\n if (subNodes.length === 0) {\n continue;\n }\n\n const firstId = this.getNodeCharacterId(subNodes[0]);\n const spliceIndex = oldNodes.findIndex(\n node => this.getNodeCharacterId(node) === firstId,\n );\n if (spliceIndex === -1) {\n pendingFragments.push({sub, nodeCount: subNodes.length});\n continue;\n }\n const children = oldNodes.splice(spliceIndex, subNodes.length);\n\n if (children.length === 1) {\n newNodes.push({\n ...children[0],\n id: sub,\n });\n continue;\n }\n\n newNodes.push({\n id: sub,\n type: Node,\n props: {},\n children,\n });\n }\n for (const pending of pendingFragments) {\n const children = oldNodes.splice(0, pending.nodeCount);\n if (children.length === 0) continue;\n if (children.length === 1) {\n newNodes.push({...children[0], id: pending.sub});\n } else {\n newNodes.push({\n id: pending.sub,\n type: Node,\n props: {},\n children,\n });\n }\n }\n if (oldNodes.length > 0) {\n newNodes.push({\n id: '__structural__',\n type: Node,\n props: {},\n children: [...oldNodes],\n });\n }\n\n const newSVG: SVGDocumentData = {\n size: oldSVG.size,\n nodes: newNodes,\n };\n Latex.texNodesPool[key] = newSVG;\n return this.buildDocument(newSVG);\n }\n\n protected texToSvg(subTexs: string[]) {\n const singleTex = subTexs.join('');\n const svg = this.singleTexToSVG(singleTex);\n if (subTexs.length > 1) {\n this.svgSubTexMap[svg] = subTexs;\n }\n return svg;\n }\n\n private subTexToSVG(subTex: string) {\n let tex = subTex.trim();\n if (\n ['\\\\overline', '\\\\sqrt', '\\\\sqrt{'].includes(tex) ||\n tex.endsWith('_') ||\n tex.endsWith('^') ||\n tex.endsWith('dot')\n ) {\n tex += '{\\\\quad}';\n }\n\n if (tex === '\\\\substack') tex = '\\\\quad';\n\n const numLeft = tex.match(/\\\\left[()[\\]|.\\\\]/g)?.length ?? 0;\n const numRight = tex.match(/\\\\right[()[\\]|.\\\\]/g)?.length ?? 0;\n if (numLeft !== numRight) {\n tex = tex.replace(/\\\\left/g, '\\\\big').replace(/\\\\right/g, '\\\\big');\n }\n\n const bracesLeft = tex.match(/((?<!\\\\)|(?<=\\\\\\\\)){/g)?.length ?? 0;\n const bracesRight = tex.match(/((?<!\\\\)|(?<=\\\\\\\\))}/g)?.length ?? 0;\n\n if (bracesLeft < bracesRight) {\n tex = '{'.repeat(bracesRight - bracesLeft) + tex;\n } else if (bracesRight < bracesLeft) {\n tex += '}'.repeat(bracesLeft - bracesRight);\n }\n\n const hasArrayBegin = tex.includes('\\\\begin{array}');\n const hasArrayEnd = tex.includes('\\\\end{array}');\n if (hasArrayBegin !== hasArrayEnd) tex = '';\n\n return this.singleTexToSVG(tex);\n }\n\n private singleTexToSVG(tex: string): string {\n const src = `${tex}::${JSON.stringify(this.options())}`;\n if (Latex.svgContentsPool[src]) {\n return Latex.svgContentsPool[src];\n }\n\n const svg = Adaptor.innerHTML(JaxDocument.convert(tex, this.options()));\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 Latex.svgContentsPool[src] = svg;\n return svg;\n }\n\n private getShapes(): Curve[] {\n return this.wrapper\n .children()\n .flatMap(child =>\n child.children().length > 0 ? child.children() : [child],\n )\n .filter((c): c is Curve => c instanceof Path || c instanceof Rect);\n }\n\n private getFragmentShapes(): Curve[][] {\n return this.wrapper.children().map(child => {\n const children = child.children().length > 0 ? child.children() : [child];\n return children.filter(\n (c): c is Curve => c instanceof Path || c instanceof Rect,\n );\n });\n }\n\n private getTargetFragmentShapes(doc: SVGDocument): Curve[][] {\n return doc.nodes.map(node => {\n const shape = node.shape;\n if (shape.children().length > 0) {\n return shape\n .children()\n .filter((c): c is Curve => c instanceof Path || c instanceof Rect);\n }\n return shape instanceof Path || shape instanceof Rect ? [shape] : [];\n });\n }\n\n private createFragmentMorphAnimations(\n sourceShapes: Curve[],\n targetShapes: Curve[],\n time: number,\n timingFunction: TimingFunction,\n ): ThreadGenerator[] {\n const animations: ThreadGenerator[] = [];\n const maxLen = Math.max(sourceShapes.length, targetShapes.length);\n\n for (let i = 0; i < maxLen; i++) {\n const from = sourceShapes[i];\n const to = targetShapes[i];\n\n if (from && to) {\n if (from instanceof Path && to instanceof Path) {\n const fromData = from.data();\n const toData = to.data();\n if (fromData && toData && fromData !== toData) {\n const interpolator = this.morpher.createInterpolator(\n fromData,\n toData,\n );\n animations.push(\n tween(time, t => {\n const progress = timingFunction(t);\n from.data.context.setter(interpolator(progress));\n }),\n );\n }\n animations.push(\n from.position(to.position(), time, timingFunction),\n from.scale(to.scale(), time, timingFunction),\n );\n } else if (from instanceof Rect && to instanceof Rect) {\n animations.push(\n from.position(to.position(), time, timingFunction),\n from.scale(to.scale(), time, timingFunction),\n from.size(to.size(), time, timingFunction),\n );\n } else {\n animations.push(from.opacity(0, time * 0.3, timingFunction));\n const clone = to.clone();\n clone.opacity(0);\n this.wrapper.add(clone);\n animations.push(\n delay(time * 0.7, clone.opacity(1, time * 0.3, timingFunction)),\n );\n }\n } else if (from && !to) {\n animations.push(from.opacity(0, time * 0.3, timingFunction));\n } else if (!from && to) {\n const clone = to.clone();\n clone.opacity(0);\n this.wrapper.add(clone);\n animations.push(clone.opacity(1, time, timingFunction));\n }\n }\n\n return animations;\n }\n\n @threadable()\n protected *tweenTex(\n value: string[],\n time: number,\n timingFunction: TimingFunction,\n ) {\n const parsedValue = this.tex.context.parse(value);\n const newSVG = this.texToSvg(parsedValue);\n const currentShapes = this.getShapes();\n\n const targetDoc = this.parseSVG(newSVG);\n const targetShapes = targetDoc.nodes.flatMap(node => {\n const shape = node.shape;\n if (shape.children().length > 0) {\n return shape\n .children()\n .filter((c): c is Curve => c instanceof Path || c instanceof Rect);\n }\n return shape instanceof Path || shape instanceof Rect ? [shape] : [];\n });\n\n const currentPaths = currentShapes.filter(\n (s): s is Path => s instanceof Path,\n );\n const currentRects = currentShapes.filter(\n (s): s is Rect => s instanceof Rect,\n );\n const targetPaths = targetShapes.filter(\n (s): s is Path => s instanceof Path,\n );\n const targetRects = targetShapes.filter(\n (s): s is Rect => s instanceof Rect,\n );\n\n yield* all(\n ...this.createFragmentMorphAnimations(\n currentPaths,\n targetPaths,\n time,\n timingFunction,\n ),\n ...this.createFragmentMorphAnimations(\n currentRects,\n targetRects,\n time,\n timingFunction,\n ),\n );\n\n this.svg.context.setter(newSVG);\n this.tex.context.setter(parsedValue);\n this.wrapper.children(this.documentNodes);\n }\n\n /**\n * Animate from the current tex to a new value using a fragment-to-fragment\n * mapping.\n *\n * @param value - The new tex value.\n * @param mapping - A mapping from source fragment indices to target fragment\n * indices. For example, `[[0], [1, 2]]` maps source fragment 0 to target\n * fragment 0, and source fragment 1 to both target fragments 1 and 2.\n * @param time - The duration of the animation.\n * @param timingFunction - The timing function.\n */\n @threadable()\n public *map(\n value: string[] | string,\n mapping: number[][],\n time: number,\n timingFunction?: TimingFunction,\n ) {\n const logger = useLogger();\n const parsedValue = this.tex.context.parse(value);\n const newSVG = this.texToSvg(parsedValue);\n const targetDoc = this.parseSVG(newSVG);\n\n const timing: TimingFunction = timingFunction ?? easeInOutCubic;\n\n const sourceFragments = this.getFragmentShapes();\n const targetFragments = this.getTargetFragmentShapes(targetDoc);\n\n const mappedTargetIndices = new Set<number>();\n const animations: ThreadGenerator[] = [];\n\n for (let srcIdx = 0; srcIdx < mapping.length; srcIdx++) {\n const targetIndices = mapping[srcIdx];\n const srcShapes = sourceFragments[srcIdx];\n\n if (!srcShapes || srcShapes.length === 0) {\n continue;\n }\n\n if (!targetIndices || targetIndices.length === 0) {\n for (const shape of srcShapes) {\n animations.push(shape.opacity(0, time * 0.3, timing));\n }\n continue;\n }\n\n for (let t = 0; t < targetIndices.length; t++) {\n const tgtIdx = targetIndices[t];\n\n if (tgtIdx < 0 || tgtIdx >= targetFragments.length) {\n logger.warn(\n `texMap: target index ${tgtIdx} is out of bounds (0-${targetFragments.length - 1})`,\n );\n continue;\n }\n\n mappedTargetIndices.add(tgtIdx);\n const tgtShapes = targetFragments[tgtIdx];\n\n if (t === 0) {\n animations.push(\n ...this.createFragmentMorphAnimations(\n srcShapes,\n tgtShapes,\n time,\n timing,\n ),\n );\n } else {\n const clonedSrc = srcShapes.map(shape => {\n const clone = shape.clone();\n this.wrapper.add(clone);\n return clone;\n });\n animations.push(\n ...this.createFragmentMorphAnimations(\n clonedSrc,\n tgtShapes,\n time,\n timing,\n ),\n );\n }\n }\n }\n\n for (\n let srcIdx = mapping.length;\n srcIdx < sourceFragments.length;\n srcIdx++\n ) {\n const srcShapes = sourceFragments[srcIdx];\n if (srcShapes) {\n for (const shape of srcShapes) {\n animations.push(shape.opacity(0, time * 0.3, timing));\n }\n }\n }\n\n for (let tgtIdx = 0; tgtIdx < targetFragments.length; tgtIdx++) {\n if (mappedTargetIndices.has(tgtIdx)) {\n continue;\n }\n\n const tgtShapes = targetFragments[tgtIdx];\n for (const shape of tgtShapes) {\n const clone = shape.clone();\n clone.opacity(0);\n this.wrapper.add(clone);\n animations.push(clone.opacity(1, time, timing));\n }\n }\n\n yield* all(...animations);\n\n this.svg.context.setter(newSVG);\n this.tex.context.setter(parsedValue);\n this.wrapper.children(this.documentNodes);\n }\n}\n","import {\n BBox,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n Vector2,\n} from '@canvas-commons/core';\nimport {CurveProfile, getPolylineProfile} from '../curves';\nimport {computed, initial, signal} from '../decorators';\nimport {DesiredLength} from '../partials';\nimport {PathDataBuilder, drawPolygon} from '../utils';\nimport {Curve, CurveProps} 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 '@canvas-commons/2d';\n * import {createRef} from '@canvas-commons/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 '@canvas-commons/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 * // snippet Accessing vertex data\n * import {Circle, Polygon, makeScene2D} from '@canvas-commons/2d';\n * import {createRef, range} from '@canvas-commons/core';\n *\n * export default makeScene2D(function* (view) {\n * const polygon = createRef<Polygon>();\n * view.add(\n * <Polygon ref={polygon} sides={3} lineWidth={4} stroke={'white'} size={160}>\n * {range(6).map(index => (\n * <Circle\n * fill={'white'}\n * size={20}\n * position={() => polygon().vertex(index)}\n * opacity={() => polygon().vertexCompletion(index)}\n * />\n * ))}\n * </Polygon>,\n * );\n *\n * yield* polygon().sides(6, 2).wait(0.5).back(2);\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 declare public 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 declare public readonly radius: SimpleSignal<number, this>;\n\n public constructor(props: PolygonProps) {\n super(props);\n }\n\n /**\n * Get the position of the nth vertex in the local space of this polygon.\n *\n * @param index - The index of the vertex.\n */\n public vertex(index: number): Vector2 {\n const size = this.computedSize().scale(0.5);\n const theta = (index * 2 * Math.PI) / this.sides();\n const direction = Vector2.fromRadians(theta).perpendicular;\n return direction.mul(size);\n }\n\n /**\n * Get the completion of the nth vertex.\n *\n * @remarks\n * The completion is a value between `0` and `1` that describes how the given\n * vertex partakes in the polygon.\n *\n * For integer values of {@link sides}, the completion is simply `1` for\n * each index making up the polygon and `0` for any other index. If `sides`\n * includes a fraction, the last index of the polygon will have a completion\n * equal to said fraction.\n *\n * Check out the {@link Polygon | Accessing vertex data} example for a\n * demonstration.\n *\n * @param index - The index of the vertex.\n */\n public vertexCompletion(index: number): number {\n const sides = this.sides();\n if (index < 0 || index > sides) {\n return 0;\n }\n\n if (index < sides - 1) {\n return 1;\n }\n\n return sides - index;\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 @computed()\n protected override getPathData(): string {\n const builder = new PathDataBuilder();\n const sides = this.sides();\n const size = this.computedSize().scale(0.5);\n\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 point = direction.mul(size);\n\n if (i === 0) {\n builder.moveTo(point.x, point.y);\n } else {\n builder.lineTo(point.x, point.y);\n }\n }\n\n builder.closePath();\n return builder.toString();\n }\n\n protected override getPath(): Path2D {\n if (this.requiresProfile()) {\n return this.curveDrawingInfo().path;\n }\n\n const pathData = this.getPathData();\n if (pathData) {\n return new Path2D(pathData);\n }\n\n return this.createPath();\n }\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 {\n PossibleVector2,\n SignalValue,\n Vector2Signal,\n} from '@canvas-commons/core';\nimport {QuadBezierSegment} from '../curves';\nimport {PolynomialSegment} from '../curves/PolynomialSegment';\nimport {computed, vector2Signal} from '../decorators';\nimport {lineTo, moveTo, quadraticCurveTo} from '../utils';\nimport {Bezier, BezierOverlayInfo} from './Bezier';\nimport {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 '@canvas-commons/2d';\n * import {createRef} from '@canvas-commons/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 declare public readonly p0: Vector2Signal<this>;\n\n /**\n * The control point of the Bézier curve.\n */\n @vector2Signal('p1')\n declare public readonly p1: Vector2Signal<this>;\n\n /**\n * The end point of the Bézier curve.\n */\n @vector2Signal('p2')\n declare public 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 {\n BBox,\n PossibleVector2,\n SignalValue,\n Vector2Signal,\n} from '@canvas-commons/core';\nimport {CurveProfile, LineSegment} from '../curves';\nimport {nodeName, vector2Signal} from '../decorators';\nimport {arc, drawLine, drawPivot} from '../utils';\nimport {Curve, CurveProps} 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 '@canvas-commons/2d';\n * import {Ray} from '@canvas-commons/2d';\n * import {createRef} from '@canvas-commons/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 declare public readonly from: Vector2Signal<this>;\n\n /**\n * The ending point of the ray.\n */\n @vector2Signal('to')\n declare public 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 offset = size.mul(this.anchor()).scale(0.5).transformAsPoint(matrix);\n const from = this.from().transformAsPoint(matrix);\n const to = this.to().transformAsPoint(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","export default `The 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","import {\n BBox,\n PossibleVector2,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n Vector2,\n unwrap,\n useLogger,\n} from '@canvas-commons/core';\nimport {\n CubicBezierSegment,\n CurveProfile,\n KnotInfo,\n getBezierSplineProfile,\n} from '../curves';\nimport {PolynomialSegment} from '../curves/PolynomialSegment';\nimport {computed, initial, signal} from '../decorators';\nimport {DesiredLength} from '../partials';\nimport {\n arc,\n bezierCurveTo,\n drawLine,\n drawPivot,\n lineTo,\n moveTo,\n quadraticCurveTo,\n} from '../utils';\nimport splineWithInsufficientKnots from './__logs__/spline-with-insufficient-knots';\nimport {Curve, CurveProps} from './Curve';\nimport {Knot} from './Knot';\nimport {Node} from './Node';\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 declare public 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 declare public 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 ||\n (typeof props.points !== 'function' && 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 offset = size.mul(this.anchor()).scale(0.5).transformAsPoint(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 {\n BBox,\n SignalValue,\n SimpleSignal,\n capitalize,\n lazy,\n textLerp,\n} from '@canvas-commons/core';\nimport {\n computed,\n initial,\n interpolation,\n nodeName,\n signal,\n} from '../decorators';\nimport {Shape, ShapeProps} from './Shape';\nimport {Txt} from './Txt';\nimport {View2D} from './View2D';\n\nexport interface TxtLeafProps extends ShapeProps {\n children?: string;\n text?: SignalValue<string>;\n}\n\n@nodeName('TxtLeaf')\nexport class TxtLeaf extends Shape {\n @lazy(() => {\n const formatter = document.createElement('span');\n View2D.shadowRoot.append(formatter);\n return formatter;\n })\n protected static formatter: HTMLDivElement;\n\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 declare public 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 return parent instanceof Txt ? parent : null;\n }\n\n protected override draw(context: CanvasRenderingContext2D) {\n this.requestFontUpdate();\n this.applyStyle(context);\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 let lineRect: BBox | null = null;\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) {\n lineRect = new BBox(x, y, rangeRect.width, rangeRect.height);\n line = childNode.textContent;\n continue;\n }\n\n if (lineRect.y === y) {\n lineRect.width += rangeRect.width;\n line += childNode.textContent;\n } else {\n 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 if (lineRect) {\n this.drawText(context, line, lineRect);\n }\n }\n\n protected drawText(\n context: CanvasRenderingContext2D,\n text: string,\n box: BBox,\n ) {\n const y = box.y;\n if (this.styles.whiteSpace !== 'pre') {\n text = text.replace(/\\s+/g, ' ');\n }\n\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 '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 {\n DEFAULT,\n InterpolationFunction,\n SignalValue,\n SimpleSignal,\n ThreadGenerator,\n TimingFunction,\n all,\n capitalize,\n threadable,\n} from '@canvas-commons/core';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport {is} from '../utils';\nimport {Node} from './Node';\nimport {Shape, ShapeProps} from './Shape';\nimport {TxtLeaf} from './TxtLeaf';\nimport {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 /**\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 declare public 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 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 const oldHeight = this.height();\n if (oldHeight === 0) {\n this.height(newSize.height);\n } else if (newSize.height === 0) {\n newSize.height = oldHeight;\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 draw(context: CanvasRenderingContext2D) {\n 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","export default `The \\`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","import {\n BBox,\n DependencyContext,\n PlaybackState,\n SerializedVector2,\n SignalValue,\n SimpleSignal,\n clamp,\n isReactive,\n useLogger,\n useThread,\n} from '@canvas-commons/core';\nimport {computed, initial, nodeName, signal} from '../decorators';\nimport {DesiredLength} from '../partials';\nimport {drawImage} from '../utils';\nimport {Rect, RectProps} from './Rect';\nimport reactivePlaybackRate from './__logs__/reactive-playback-rate';\n\nexport interface VideoProps extends RectProps {\n /**\n * {@inheritDoc Video.src}\n */\n src?: SignalValue<string>;\n /**\n * {@inheritDoc Video.alpha}\n */\n alpha?: SignalValue<number>;\n /**\n * {@inheritDoc Video.smoothing}\n */\n smoothing?: SignalValue<boolean>;\n /**\n * {@inheritDoc Video.loop}\n */\n loop?: SignalValue<boolean>;\n /**\n * {@inheritDoc Video.playbackRate}\n */\n playbackRate?: number;\n /**\n * The starting time for this video in seconds.\n */\n time?: SignalValue<number>;\n play?: boolean;\n}\n\n@nodeName('Video')\nexport class Video extends Rect {\n private static readonly pool: Record<string, HTMLVideoElement> = {};\n\n /**\n * The source of this video.\n *\n * @example\n * Using a local video:\n * ```tsx\n * import video from './example.mp4';\n * // ...\n * view.add(<Video src={video} />)\n * ```\n * Loading an image from the internet:\n * ```tsx\n * view.add(<Video src=\"https://example.com/video.mp4\" />)\n * ```\n */\n @signal()\n declare public readonly src: SimpleSignal<string, this>;\n\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 declare public 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 declare public readonly smoothing: SimpleSignal<boolean, this>;\n\n /**\n * Whether this video should loop upon reaching the end.\n */\n @initial(false)\n @signal()\n declare public readonly loop: SimpleSignal<boolean, this>;\n\n /**\n * The rate at which the video plays, as multiples of the normal speed.\n *\n * @defaultValue 1\n */\n @initial(1)\n @signal()\n declare public readonly playbackRate: SimpleSignal<number, this>;\n\n @initial(0)\n @signal()\n declare protected readonly time: SimpleSignal<number, this>;\n\n @initial(false)\n @signal()\n declare protected readonly playing: SimpleSignal<boolean, this>;\n\n private lastTime = -1;\n\n public constructor({play, ...props}: VideoProps) {\n super(props);\n if (play) {\n this.play();\n }\n }\n\n /**\n * {@inheritDoc Curve.completion}\n */\n public curveCompletion(): number {\n return super.completion();\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 return this.video().duration;\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 /**\n * The completion of this video in the range from 0 to 1.\n *\n * @remarks\n * To get the percentage of the stroke that's currently visible, use\n * {@link Video.curveCompletion} instead.\n */\n @computed()\n public override completion(): number {\n return this.clampTime(this.time()) / this.video().duration;\n }\n\n @computed()\n protected video(): HTMLVideoElement {\n const src = this.src();\n const key = `${this.key}/${src}`;\n let video = Video.pool[key];\n if (!video) {\n video = document.createElement('video');\n video.src = src;\n Video.pool[key] = video;\n }\n\n if (video.readyState < 2) {\n DependencyContext.collectPromise(\n new Promise<void>(resolve => {\n const listener = () => {\n resolve();\n video.removeEventListener('canplay', listener);\n };\n video.addEventListener('canplay', listener);\n }),\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 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 if (Math.abs(video.currentTime - time) > 0.2) {\n this.setCurrentTime(time);\n } else if (!playing) {\n video.currentTime = time;\n }\n\n return video;\n }\n\n protected override draw(context: CanvasRenderingContext2D) {\n this.drawShape(context);\n const alpha = this.alpha();\n if (alpha > 0) {\n const playbackState = this.view().playbackState();\n const video =\n playbackState === PlaybackState.Playing ||\n playbackState === PlaybackState.Presenting\n ? this.fastSeekedVideo()\n : this.seekedVideo();\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 this.drawChildren(context);\n }\n\n protected override applyFlex() {\n super.applyFlex();\n const video = this.video();\n this.element.style.aspectRatio = (\n this.ratio() ?? video.videoWidth / video.videoHeight\n ).toString();\n }\n\n protected setCurrentTime(value: number) {\n const video = this.video();\n if (video.readyState < 2) return;\n\n video.currentTime = value;\n this.lastTime = value;\n if (video.seeking) {\n DependencyContext.collectPromise(\n new Promise<void>(resolve => {\n const listener = () => {\n resolve();\n video.removeEventListener('seeked', listener);\n };\n video.addEventListener('seeked', listener);\n }),\n );\n }\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 public play() {\n const time = useThread().time;\n const start = time();\n const offset = this.time();\n const playbackRate = this.playbackRate();\n this.playing(true);\n this.time(() => this.clampTime(offset + (time() - start) * playbackRate));\n }\n\n public pause() {\n this.playing(false);\n this.time.save();\n this.video().pause();\n }\n\n public seek(time: number) {\n const playing = this.playing();\n this.time(this.clampTime(time));\n if (playing) {\n this.play();\n } else {\n this.pause();\n }\n }\n\n public clampTime(time: number): number {\n const duration = this.video().duration;\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.seekedVideo();\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 {CodeRange} from './CodeRange';\nimport {CodeTag, 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 {\n createSignal,\n deepLerp,\n DependencyContext,\n Signal,\n SignalContext,\n SignalValue,\n ThreadGenerator,\n TimingFunction,\n unwrap,\n} from '@canvas-commons/core';\nimport {Code} from '../components';\nimport {addInitializer, getPropertyMetaOrCreate} from '../decorators';\nimport {defaultDiffer} from './CodeDiffer';\nimport {insert, replace} from './CodeFragment';\nimport {CodeHighlighter} from './CodeHighlighter';\nimport {CodePoint, CodeRange} from './CodeRange';\nimport {\n CODE,\n CodeScope,\n CodeTag,\n parseCodeScope,\n PossibleCodeScope,\n resolveCodeTag,\n} from './CodeScope';\nimport {defaultTokenize} from './CodeTokenizer';\nimport {extractRange} from './extractRange';\n\ninterface CodeModifier<TOwner> {\n (code: CodeTag): TOwner;\n (code: CodeTag, duration: number): ThreadGenerator;\n (duration?: number): TagGenerator;\n}\n\ninterface CodeInsert<TOwner> {\n (point: CodePoint, code: CodeTag): TOwner;\n (point: CodePoint, code: CodeTag, duration: number): ThreadGenerator;\n (point: CodePoint, duration?: number): TagGenerator;\n}\n\ninterface CodeRemove<TOwner> {\n (range: CodeRange): TOwner;\n (range: CodeRange, duration: number): ThreadGenerator;\n}\n\ninterface CodeReplace<TOwner> {\n (range: CodeRange, code: CodeTag): TOwner;\n (range: CodeRange, code: CodeTag, duration: number): ThreadGenerator;\n (range: CodeRange, duration?: number): TagGenerator;\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: SignalValue<PossibleCodeScope>,\n owner: TOwner,\n private readonly highlighter?: SignalValue<CodeHighlighter | null>,\n ) {\n super(initial, deepLerp, owner);\n if (owner instanceof Code) {\n this.highlighter ??= owner.highlighter;\n }\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: CodeTag): TOwner;\n public append(code: CodeTag, duration: number): ThreadGenerator;\n public append(duration?: number): TagGenerator;\n public append(\n first: CodeTag | number = 0.6,\n duration?: number,\n ): TOwner | ThreadGenerator | TagGenerator {\n if (typeof first !== 'undefined' && typeof first !== 'number') {\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(CODE(strings, ...tags), savedDuration);\n }\n\n public prepend(code: CodeTag): TOwner;\n public prepend(code: CodeTag, duration: number): ThreadGenerator;\n public prepend(duration?: number): TagGenerator;\n public prepend(\n first: CodeTag | number = 0.6,\n duration?: number,\n ): TOwner | ThreadGenerator | TagGenerator {\n if (typeof first !== 'undefined' && typeof first !== 'number') {\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(CODE(strings, ...tags), savedDuration);\n }\n\n public insert(point: CodePoint, code: CodeTag): TOwner;\n public insert(\n point: CodePoint,\n code: CodeTag,\n duration: number,\n ): ThreadGenerator;\n public insert(point: CodePoint, duration?: number): TagGenerator;\n public insert(\n point: CodePoint,\n first: CodeTag | number = 0.6,\n duration?: number,\n ): TOwner | ThreadGenerator | TagGenerator {\n return this.replace([point, point], first as CodeTag, duration as number);\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: CodeTag): TOwner;\n public replace(\n range: CodeRange,\n code: CodeTag,\n duration: number,\n ): ThreadGenerator;\n public replace(range: CodeRange, duration?: number): TagGenerator;\n public replace(\n range: CodeRange,\n first: CodeTag | number = 0.6,\n duration?: number,\n ): TOwner | ThreadGenerator | TagGenerator {\n if (typeof first !== 'undefined' && typeof first !== 'number') {\n if (duration === undefined) {\n const current = this.get();\n const [fragments, index] = extractRange(range, current.fragments);\n fragments[index] = first;\n return this.set({\n progress: current.progress,\n fragments,\n });\n } else {\n return this.replaceTween(range, first, duration);\n }\n }\n\n const savedDuration = first;\n return (strings, ...tags) =>\n this.replaceTween(range, CODE(strings, ...tags), savedDuration);\n }\n\n private *replaceTween(range: CodeRange, code: CodeTag, duration: number) {\n let current = this.get();\n const [fragments, index] = extractRange(range, current.fragments);\n const progress = createSignal(0);\n const resolved = resolveCodeTag(code, true);\n const scope = {\n progress,\n fragments: [replace(fragments[index] as string, resolved)],\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: CodeTag, duration: number) {\n let current = this.get();\n const progress = createSignal(0);\n const resolved = resolveCodeTag(value, true);\n const scope = {\n progress,\n fragments: [insert(resolved)],\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: CodeTag, duration: number) {\n let current = this.get();\n const progress = createSignal(0);\n const resolved = resolveCodeTag(value, true);\n const scope = {\n progress,\n fragments: [insert(resolved)],\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 {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 {HighlightStyle} from '@codemirror/language';\nimport {Parser, SyntaxNode, Tree} from '@lezer/common';\nimport {highlightTree} from '@lezer/highlight';\nimport {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 {\n FullSceneDescription,\n GeneratorScene,\n Inspectable,\n InspectedAttributes,\n InspectedElement,\n Scene,\n SceneRenderEvent,\n ThreadGeneratorFactory,\n Vector2,\n useLogger,\n} from '@canvas-commons/core';\nimport {Node, 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('canvas-commons: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 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 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 return this.execute(\n () => this.getView().hit(new Vector2(x, y))?.key ?? null,\n );\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 new Vector2(x, y).transformAsPoint(\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 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 {\n createSceneMetadata,\n DescriptionOf,\n ThreadGeneratorFactory,\n} from '@canvas-commons/core';\nimport type {View2D} from '../components';\nimport {Scene2D} from './Scene2D';\n\nexport function makeScene2D(\n runner: ThreadGeneratorFactory<View2D>,\n): DescriptionOf<Scene2D> {\n return {\n klass: Scene2D,\n config: runner,\n stack: new Error().stack,\n meta: createSceneMetadata(),\n plugins: ['@canvas-commons/2d/editor'],\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AASA,SAAgB,cACd,SACA,WACA,OACa;CACb,MAAM,QAAQ,MAAM,MAAM,IAAI;CAC9B,MAAM,WAAW,MAAM,MAAM,SAAS;CACtC,MAAM,aAAa,KAAK,MACtB,QAAQ,YAAY,MAAM,EAAE,EAAE,QAAQ,SACxC;CACA,IAAI,YAAY;CAChB,IAAI,WAAW;CAEf,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,OAAO,MAAM;EACnB,MAAM,QAAQ,KAAK,MAAM,QAAQ,YAAY,IAAI,EAAE,QAAQ,SAAS;EACpE,IAAI,QAAQ,UACV,WAAW;CAEf;CAEA,IAAI,MAAM,SAAS,GACjB,YAAY,KAAK,MAAM,QAAQ,YAAY,QAAQ,EAAE,QAAQ,SAAS;CAGxE,OAAO;EACL,SAAS;EACT,SAAS,MAAM,SAAS;EACxB,WAAW,SAAS;EACpB;EACA;EACA;CACF;AACF;AAEA,SAAgB,cAAc,OAAkC;CAC9D,OAAO,OAAO,YAAY,KAAA;AAC5B;;;AC7BA,SAAgB,kBAA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OAAO,UAAU,KAAK,GAAG;AAC3B;;;;;;;;;;;;AAaA,SAAgB,kBACd,SACA,KACA,QACA,MACA,QACA,aACU;CACV,MAAM,KAAK,eAAe,OAAO;CACjC,MAAM,UAAU,qBACd,QACA,MACA,QACA,aACA,OACF;CAGA,MAAM,IAAI,IAAI;CACd,MAAM,IAAI,IAAI;CACd,MAAM,QAAQ,IAAI;CAClB,MAAM,SAAS,IAAI;CAEnB,OAAO,GAAG,UAAU,UAAU,GAAG,GAAG,OAAO,QAAQ,OAAO;AAC5D;;;;;;;;;;;AAYA,SAAgB,cACd,SACA,KACA,QACA,MACA,QACA,aACM;CACN,MAAM,WAAW,kBACf,SACA,KACA,QACA,MACA,QACA,WACF;CAEA,eAD0B,OACzB,EAAE,KAAK,QAAQ;AAClB;;;;;;;AAQA,SAAgB,kBACd,SACA,UACM;CAEN,eAD0B,OACzB,EAAE,KAAK,QAAQ;AAClB;;;;;;;;;;;;;;;AAgBA,SAAgB,yBACd,SACA,KACA,QACA,eACA,iBACA,QACA,MACA,QACA,aACU;CAUV,OAAO,kBACL,SATe,qBACf,KACA,QACA,eACA,eAMO,GACP,QACA,MACA,QACA,WACF;AACF;;;;;;;;;;;;;;AAeA,SAAgB,qBACd,SACA,KACA,QACA,eACA,iBACA,QACA,MACA,QACA,aACM;CAYN,kBAAkB,SAXD,yBACf,SACA,KACA,QACA,eACA,iBACA,QACA,MACA,QACA,WAEgC,CAAC;AACrC;;;;;;;;;;;;AAaA,SAAgB,gBACd,SACA,QACA,MACA,QACA,MACA,QACA,aACM;CACN,MAAM,KAAK,eAAe,OAAO;CACjC,MAAM,UAAU,qBACd,QACA,MACA,QACA,aACA,OACF;CAEA,MAAM,WAAW,GAAG,UAAU,QAC5B,OAAO,GACP,OAAO,GACP,KAAK,IAAI,GACT,KAAK,IAAI,GACT,OACF;CACA,GAAG,KAAK,QAAQ;AAClB;;;;;;;;;;;;AAaA,SAAgB,kBACd,SACA,UACA,QACA,MACA,QACA,aACU;CACV,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