@motionscript/charts 0.0.0-stage → 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +201 -0
  3. package/dist/bar-chart/bar-chart.d.ts +286 -0
  4. package/dist/bar-chart/bar-chart.d.ts.map +1 -0
  5. package/dist/bar-chart/bar-chart.js +610 -0
  6. package/dist/bar-chart/bar-chart.js.map +1 -0
  7. package/dist/bar-chart/category-axis.d.ts +77 -0
  8. package/dist/bar-chart/category-axis.d.ts.map +1 -0
  9. package/dist/bar-chart/category-axis.js +141 -0
  10. package/dist/bar-chart/category-axis.js.map +1 -0
  11. package/dist/bar-chart/chart-bars.d.ts +149 -0
  12. package/dist/bar-chart/chart-bars.d.ts.map +1 -0
  13. package/dist/bar-chart/chart-bars.js +236 -0
  14. package/dist/bar-chart/chart-bars.js.map +1 -0
  15. package/dist/bar-chart/index.d.ts +16 -0
  16. package/dist/bar-chart/index.d.ts.map +1 -0
  17. package/dist/bar-chart/index.js +12 -0
  18. package/dist/bar-chart/index.js.map +1 -0
  19. package/dist/bar-chart/shared.d.ts +146 -0
  20. package/dist/bar-chart/shared.d.ts.map +1 -0
  21. package/dist/bar-chart/shared.js +182 -0
  22. package/dist/bar-chart/shared.js.map +1 -0
  23. package/dist/browser/chunks/chunk-ZMBOBHYL.js +2 -0
  24. package/dist/browser/chunks/chunk-ZMBOBHYL.js.map +7 -0
  25. package/dist/browser/index.js +2 -0
  26. package/dist/browser/index.js.map +7 -0
  27. package/dist/browser/kit.js +2 -0
  28. package/dist/browser/kit.js.map +7 -0
  29. package/dist/browser/manifest.json +12 -0
  30. package/dist/engine.d.ts +27 -0
  31. package/dist/engine.d.ts.map +1 -0
  32. package/dist/engine.js +27 -0
  33. package/dist/engine.js.map +1 -0
  34. package/dist/index.d.ts +6 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +6 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/kit/chart-border.d.ts +28 -0
  39. package/dist/kit/chart-border.d.ts.map +1 -0
  40. package/dist/kit/chart-border.js +45 -0
  41. package/dist/kit/chart-border.js.map +1 -0
  42. package/dist/kit/chart-canvas.d.ts +56 -0
  43. package/dist/kit/chart-canvas.d.ts.map +1 -0
  44. package/dist/kit/chart-canvas.js +125 -0
  45. package/dist/kit/chart-canvas.js.map +1 -0
  46. package/dist/kit/chart-legend.d.ts +126 -0
  47. package/dist/kit/chart-legend.d.ts.map +1 -0
  48. package/dist/kit/chart-legend.js +212 -0
  49. package/dist/kit/chart-legend.js.map +1 -0
  50. package/dist/kit/shared.d.ts +251 -0
  51. package/dist/kit/shared.d.ts.map +1 -0
  52. package/dist/kit/shared.js +401 -0
  53. package/dist/kit/shared.js.map +1 -0
  54. package/dist/kit/vertical-axis.d.ts +99 -0
  55. package/dist/kit/vertical-axis.d.ts.map +1 -0
  56. package/dist/kit/vertical-axis.js +176 -0
  57. package/dist/kit/vertical-axis.js.map +1 -0
  58. package/dist/line-chart/chart-line.d.ts +91 -0
  59. package/dist/line-chart/chart-line.d.ts.map +1 -0
  60. package/dist/line-chart/chart-line.js +156 -0
  61. package/dist/line-chart/chart-line.js.map +1 -0
  62. package/dist/line-chart/chart-region.d.ts +47 -0
  63. package/dist/line-chart/chart-region.d.ts.map +1 -0
  64. package/dist/line-chart/chart-region.js +101 -0
  65. package/dist/line-chart/chart-region.js.map +1 -0
  66. package/dist/line-chart/horizontal-axis.d.ts +85 -0
  67. package/dist/line-chart/horizontal-axis.d.ts.map +1 -0
  68. package/dist/line-chart/horizontal-axis.js +158 -0
  69. package/dist/line-chart/horizontal-axis.js.map +1 -0
  70. package/dist/line-chart/index.d.ts +22 -0
  71. package/dist/line-chart/index.d.ts.map +1 -0
  72. package/dist/line-chart/index.js +19 -0
  73. package/dist/line-chart/index.js.map +1 -0
  74. package/dist/line-chart/line-chart.d.ts +347 -0
  75. package/dist/line-chart/line-chart.d.ts.map +1 -0
  76. package/dist/line-chart/line-chart.js +701 -0
  77. package/dist/line-chart/line-chart.js.map +1 -0
  78. package/dist/line-chart/shared.d.ts +171 -0
  79. package/dist/line-chart/shared.d.ts.map +1 -0
  80. package/dist/line-chart/shared.js +270 -0
  81. package/dist/line-chart/shared.js.map +1 -0
  82. package/dist/line-chart/x-scale.d.ts +84 -0
  83. package/dist/line-chart/x-scale.d.ts.map +1 -0
  84. package/dist/line-chart/x-scale.js +302 -0
  85. package/dist/line-chart/x-scale.js.map +1 -0
  86. package/dist/nodes.d.ts +20 -0
  87. package/dist/nodes.d.ts.map +1 -0
  88. package/dist/nodes.js +20 -0
  89. package/dist/nodes.js.map +1 -0
  90. package/dist/pie-chart/index.d.ts +18 -0
  91. package/dist/pie-chart/index.d.ts.map +1 -0
  92. package/dist/pie-chart/index.js +14 -0
  93. package/dist/pie-chart/index.js.map +1 -0
  94. package/dist/pie-chart/pie-chart.d.ts +170 -0
  95. package/dist/pie-chart/pie-chart.d.ts.map +1 -0
  96. package/dist/pie-chart/pie-chart.js +291 -0
  97. package/dist/pie-chart/pie-chart.js.map +1 -0
  98. package/dist/pie-chart/pie-legend.d.ts +60 -0
  99. package/dist/pie-chart/pie-legend.d.ts.map +1 -0
  100. package/dist/pie-chart/pie-legend.js +131 -0
  101. package/dist/pie-chart/pie-legend.js.map +1 -0
  102. package/dist/pie-chart/pie-ring.d.ts +266 -0
  103. package/dist/pie-chart/pie-ring.d.ts.map +1 -0
  104. package/dist/pie-chart/pie-ring.js +708 -0
  105. package/dist/pie-chart/pie-ring.js.map +1 -0
  106. package/dist/pie-chart/shared.d.ts +210 -0
  107. package/dist/pie-chart/shared.d.ts.map +1 -0
  108. package/dist/pie-chart/shared.js +240 -0
  109. package/dist/pie-chart/shared.js.map +1 -0
  110. package/package.json +69 -3
  111. package/registry.json +23 -0
  112. package/src/bar-chart/bar-chart.ts +804 -0
  113. package/src/bar-chart/category-axis.ts +177 -0
  114. package/src/bar-chart/chart-bars.ts +310 -0
  115. package/src/bar-chart/index.ts +31 -0
  116. package/src/bar-chart/shared.ts +354 -0
  117. package/src/engine.ts +26 -0
  118. package/src/index.ts +5 -0
  119. package/src/kit/chart-border.ts +61 -0
  120. package/src/kit/chart-canvas.ts +157 -0
  121. package/src/kit/chart-legend.ts +250 -0
  122. package/src/kit/shared.ts +675 -0
  123. package/src/kit/vertical-axis.ts +224 -0
  124. package/src/line-chart/chart-line.ts +208 -0
  125. package/src/line-chart/chart-region.ts +135 -0
  126. package/src/line-chart/horizontal-axis.ts +202 -0
  127. package/src/line-chart/index.ts +39 -0
  128. package/src/line-chart/line-chart.ts +894 -0
  129. package/src/line-chart/shared.ts +459 -0
  130. package/src/line-chart/x-scale.ts +367 -0
  131. package/src/nodes.ts +20 -0
  132. package/src/pie-chart/index.ts +37 -0
  133. package/src/pie-chart/pie-chart.ts +374 -0
  134. package/src/pie-chart/pie-legend.ts +159 -0
  135. package/src/pie-chart/pie-ring.ts +903 -0
  136. package/src/pie-chart/shared.ts +490 -0
  137. package/README.md +0 -4
@@ -0,0 +1,224 @@
1
+ import {
2
+ command,
3
+ Node2D,
4
+ Rect,
5
+ RotatedBox,
6
+ Text,
7
+ easeOut,
8
+ property,
9
+ insetsOps,
10
+ textOps,
11
+ type CommandArgs,
12
+ type NodeConfig,
13
+ type Node2DProps,
14
+ } from "@motionscript/core"
15
+
16
+ import {
17
+ DEFAULT_Y_AXIS,
18
+ enterBudget,
19
+ formatMarker,
20
+ type AxisConfig,
21
+ type Range,
22
+ } from "./shared"
23
+ import { at, compose, type Seekable } from "@motionscript/core/component"
24
+
25
+ export interface VerticalAxisProps extends Node2DProps {
26
+ /** `[min, max]` of the vertical scale the markers are positioned within. */
27
+ range: Range
28
+ /**
29
+ * Tick values (in data units) to draw up the axis, each placed by its fraction
30
+ * across {@link VerticalAxisProps.range}. Need not be evenly spaced or include
31
+ * the ends.
32
+ */
33
+ markers: number[]
34
+ /** Marker/caption text style, grid stroke, and gutters — see {@link AxisConfig}. */
35
+ axis: AxisConfig
36
+ /**
37
+ * Rotated caption drawn in the gutter to the left of the marker column. Empty
38
+ * string (the default) hides it — no caption node is built and no label gutter
39
+ * is reserved.
40
+ */
41
+ label: string
42
+ }
43
+
44
+ /** How far a marker starts to the right of its slot when it enters, in px. */
45
+ const SLIDE = 24
46
+
47
+ /** How a tick value is captioned — see {@link VerticalAxis.labelFor}. */
48
+ export type MarkerLabel = (value: number) => string
49
+
50
+ /**
51
+ * The numeric vertical axis shared by the cartesian charts: a **column of
52
+ * {@link Text} nodes**, one per marker value, running top-to-bottom (highest
53
+ * value at the top). Pure layout — no `Graphics` — so the markers are real text
54
+ * nodes the scene can measure, restyle, or animate individually.
55
+ *
56
+ * Each marker is positioned so its centre lands exactly on its value's fraction
57
+ * across `range` within the axis's filled height, so unevenly-spaced markers
58
+ * land where their values fall. Both the caption and the position are *bound*,
59
+ * not snapshotted: a chart that rescales its axes (see `LineChart.zoomTo`)
60
+ * tweens `range`/`markers` live. Only the marker **count** is fixed at
61
+ * construction.
62
+ *
63
+ * {@link enter} staggers them in **bottom-to-top**: each marker starts pushed a
64
+ * little to the right and transparent, then fades and slides left into place.
65
+ * The resting state is the landed one, so a chart that is never told to enter
66
+ * still reads as a finished chart.
67
+ */
68
+ export class VerticalAxis extends Node2D<VerticalAxisProps> {
69
+ @property({ default: () => [0, 1] as Range }) declare range: Range
70
+ @property({ default: () => [] as number[] }) declare markers: number[]
71
+ @property({ default: DEFAULT_Y_AXIS }) declare axis: AxisConfig
72
+ @property({ default: "" }) declare label: string
73
+
74
+ /**
75
+ * How a tick value is captioned. Defaults to the bare numeric reading; a
76
+ * chart with a number format on this axis replaces it (see `number-format`).
77
+ *
78
+ * A plain field rather than a `@property`, for the reason the horizontal
79
+ * axis's twin spells out: it is a policy, not a value, and there is nothing
80
+ * to tween between two formatters.
81
+ */
82
+ labelFor: MarkerLabel = formatMarker
83
+
84
+ /** One text node per marker, ordered top → bottom, for the staggered enter. */
85
+ private markerNodes: Text[] = []
86
+ /** The caption node, or null when `label` is empty. Entered after the markers. */
87
+ private labelNode: Text | null = null
88
+
89
+ /** The live tick values, top → bottom (highest first) — re-read every frame. */
90
+ private get sortedMarkers(): number[] {
91
+ return [...this.markers].sort((a, b) => b - a)
92
+ }
93
+
94
+ /**
95
+ * Tick `i`'s value, or `undefined` once the live `markers` list is shorter
96
+ * than the column of text nodes built for it — a slot with no value renders as
97
+ * empty text rather than repeating its neighbour.
98
+ */
99
+ private valueAt(index: number): number | undefined {
100
+ return this.sortedMarkers[index]
101
+ }
102
+
103
+ /** Tick `i`'s fraction across the live `range`, 0 at the bottom edge. */
104
+ private fracAt(index: number): number {
105
+ const v = this.valueAt(index)
106
+ if (v === undefined) return 0
107
+ const [min, max] = this.range
108
+ return max <= min ? 0 : (v - min) / (max - min)
109
+ }
110
+
111
+ constructor(props?: NodeConfig<VerticalAxis, VerticalAxisProps>) {
112
+ super(props)
113
+
114
+ // Composed from plain props (range/markers/label) — no context needed, so
115
+ // it's built here. super() applied the props, so the reads below resolve.
116
+ const tickPad = insetsOps.resolve(this.axis.tickPadding).right
117
+ const titlePad = insetsOps.resolve(this.axis.titlePadding).right
118
+
119
+ this.markerNodes = this.markers.map((_, i) => {
120
+ const marker: Text = new Text({
121
+ ...textOps.styleProps(this.axis.labelStyle),
122
+ text: () => {
123
+ const v = this.valueAt(i)
124
+ return v === undefined ? "" : this.labelFor(v)
125
+ },
126
+ y: () => {
127
+ // Node2D space is y-up, so the fraction runs from the bottom.
128
+ const height = this.layoutBounds.height
129
+ const centred = (this.fracAt(i) - 0.5) * height
130
+ // Held inside the axis's top edge — the backstop for a chart whose
131
+ // headroom is smaller than its marker text is tall, which a theme with
132
+ // much larger markers can arrange. Only the top, because what lies
133
+ // below the axis is the chart's own horizontal axis and legend.
134
+ const limit = height / 2 - marker.layoutBounds.height / 2
135
+ return Math.min(centred, limit)
136
+ },
137
+ })
138
+ return marker
139
+ })
140
+
141
+ const children: Node2D[] = []
142
+ if (this.label !== "") {
143
+ this.labelNode = new Text({
144
+ ...textOps.styleProps(this.axis.titleStyle),
145
+ text: this.label,
146
+ })
147
+ // Node2D space is y-up and rotation is clockwise, so -90° reads bottom-to-top.
148
+ children.push(
149
+ new RotatedBox({
150
+ angle: -90,
151
+ width: "hug",
152
+ height: "hug",
153
+ children: this.labelNode,
154
+ })
155
+ )
156
+ }
157
+ children.push(
158
+ new Rect({
159
+ height: "fill",
160
+ width: "hug",
161
+ padding: { right: tickPad },
162
+ children: this.markerNodes,
163
+ })
164
+ )
165
+
166
+ this.add(new Rect({ flow: "horizontal", gap: titlePad, children }))
167
+ }
168
+
169
+ /**
170
+ * Primes every marker (and the caption) at its pre-entrance state: shifted
171
+ * right and transparent. Idempotent, and separate from {@link enter} so the
172
+ * chart can arm its whole composition before the first frame is drawn.
173
+ */
174
+ arm(slide = SLIDE): void {
175
+ for (const marker of this.markerNodes) marker.set({ opacity: 0, x: slide })
176
+ this.labelNode?.set({ opacity: 0, x: slide })
177
+ }
178
+
179
+ /**
180
+ * Stagger the markers in bottom to top, then slide the caption in from the
181
+ * right after them.
182
+ *
183
+ * A {@link Seekable} rather than a generator — see the note on the horizontal
184
+ * axis's `enter`. The offsets were always static; expressing them as `wait`
185
+ * inside a generator is what made them reachable only by running it.
186
+ *
187
+ * `args.duration` is the **whole** entrance, not one marker's slide: the
188
+ * stagger and the caption are carved out of it rather than added on top. See
189
+ * {@link enterBudget} for why that distinction matters here.
190
+ *
191
+ * `args.data.stagger` is seconds between successive markers (derived when
192
+ * omitted); `args.data.slide` is the starting rightward offset in px.
193
+ */
194
+ @command()
195
+ enter(args: CommandArgs<{ stagger?: number; slide?: number }> & { duration: number }): Seekable {
196
+ const { stagger, slide = SLIDE } = args.data ?? {}
197
+ const easing = args.easing ?? easeOut()
198
+ const nodes = this.markerNodes
199
+ if (nodes.length === 0) return compose([])
200
+ const { step, per, caption } = enterBudget(
201
+ args.duration,
202
+ nodes.length,
203
+ this.labelNode !== null,
204
+ stagger
205
+ )
206
+
207
+ this.arm(slide)
208
+
209
+ // Bottom marker leads: markerNodes is top → bottom, so walk it in reverse.
210
+ const markers = nodes.map((node, i) => {
211
+ const order = nodes.length - 1 - i // bottom-most = 0
212
+ return at(order * step, node.to({ data: { opacity: 1, x: 0 }, duration: per, easing }))
213
+ })
214
+ const lastMarkerEnds = (nodes.length - 1) * step + per
215
+
216
+ // Once every marker has landed, the caption slides in from the right.
217
+ return compose([
218
+ ...markers,
219
+ ...(this.labelNode
220
+ ? [at(lastMarkerEnds, this.labelNode.to({ data: { opacity: 1, x: 0 }, duration: caption, easing }))]
221
+ : []),
222
+ ])
223
+ }
224
+ }
@@ -0,0 +1,208 @@
1
+ import {
2
+ type AssetScope,
3
+ Graphics2D,
4
+ Node2D,
5
+ command,
6
+ easeOut,
7
+ strokeOps,
8
+ property,
9
+ type Command,
10
+ type CommandArgs,
11
+ type EasingFunction,
12
+ type Node2DProps,
13
+ type RenderContext2D,
14
+ type Stroke,
15
+ type StrokeResolved,
16
+ type Vector2,
17
+ } from "@motionscript/core"
18
+
19
+ import { SPOTLIGHT_DIM } from "../kit/shared"
20
+ import {
21
+ EMPTY_REGION_BOX,
22
+ clipPolylineToBox,
23
+ hasRegion,
24
+ type RegionBox,
25
+ } from "./shared"
26
+ import { declarePaints } from "@motionscript/core/component"
27
+
28
+ export interface ChartLineProps extends Node2DProps {
29
+ /**
30
+ * The series polyline, already mapped into this node's local pixel space
31
+ * (origin at centre, y-up) by the parent {@link LineChart}. Ordered along x.
32
+ */
33
+ points: Vector2[]
34
+ /** Line colour + weight (+ optional dash/cap/join) — the per-series stroke. */
35
+ stroke: Stroke
36
+ /**
37
+ * Reveal of the line in `[0, 1]`: 0 hides it, 1 traces it fully from its left
38
+ * end to its right.
39
+ *
40
+ * Defaults to **1**, unlike the standalone chart this was ported from: in the
41
+ * studio a node's resting state is what the paused editor canvas paints, so a
42
+ * chart that only appeared once a command had run would edit blind. {@link
43
+ * enter} drives it from 0 regardless of where it rests, so the animation is
44
+ * unchanged.
45
+ */
46
+ progress: number
47
+ /**
48
+ * Whether this line is drawn at all. `false` hides it outright — the switch
49
+ * the chart flips alongside its legend's per-series toggle.
50
+ */
51
+ enabled: boolean
52
+ /**
53
+ * A slice of the plot to spotlight, in this node's own pixel space. When set
54
+ * to a real box, the stretches of the line *outside* it drop to
55
+ * {@link ChartLineProps.dimOpacity} while the stretches inside stay full.
56
+ */
57
+ spotlight: RegionBox
58
+ /** Opacity the out-of-region stretches fade to. */
59
+ dimOpacity: number
60
+ }
61
+
62
+ /**
63
+ * A single series line of a {@link LineChart}: one rounded polyline traced
64
+ * through pre-mapped pixel `points`, drawn as one {@link Graphics2D} command list.
65
+ * Sized and positioned by the parent, which shares the plot's coordinate frame.
66
+ *
67
+ * Two signals drive it: {@link ChartLineProps.progress} traces the line in
68
+ * (animated by {@link enter}) and `enabled` shows or hides it wholesale.
69
+ */
70
+ export class ChartLine extends Node2D<ChartLineProps> {
71
+ @property({ default: () => [] as Vector2[] }) declare points: Vector2[]
72
+ @property({ default: [], mapper: strokeOps.resolve, tween: strokeOps.lerp })
73
+ declare stroke: Stroke
74
+ @property({ default: 1 }) declare progress: number
75
+ @property({ default: true }) declare enabled: boolean
76
+ @property({ default: () => EMPTY_REGION_BOX }) declare spotlight: RegionBox
77
+ @property({ default: SPOTLIGHT_DIM }) declare dimOpacity: number
78
+
79
+ /**
80
+ * This node extends `Node2D` rather than `ShapeNode`, so nothing declares the
81
+ * paint props it carries — see {@link declarePaints}.
82
+ */
83
+ override declareAssets(assets: AssetScope): void {
84
+ super.declareAssets(assets)
85
+ declarePaints(this, assets)
86
+ }
87
+
88
+ protected renderSelf(ctx: RenderContext2D): void {
89
+ if (!this.enabled) return
90
+ const pts = this.points
91
+ if (pts.length < 2) return
92
+
93
+ const p = Math.max(0, Math.min(1, this.progress))
94
+ if (p <= 0) return
95
+
96
+ const drawn = this.tracePoints(pts, p)
97
+ if (drawn.length < 2) return
98
+ const stroke = this.stroke as StrokeResolved[]
99
+ const radius = (stroke[0]?.weight ?? 0) * 2 // round the joins
100
+
101
+ const box = this.spotlight
102
+ if (!hasRegion(box)) {
103
+ ctx.draw(new Graphics2D().line({ points: drawn, radius }).stroke(stroke))
104
+ return
105
+ }
106
+
107
+ // Spotlit: the whole line goes down to `dimOpacity`, then the stretches
108
+ // inside the region are re-drawn over it at full strength. Two passes rather
109
+ // than one dim + one bright *complementary* pair, so the bright run has
110
+ // continuous geometry through the region and its joins round the way an
111
+ // unspotlit line's do — and so the boundary lands exactly on the region edge.
112
+ ctx.draw(
113
+ new Graphics2D()
114
+ .line({ points: drawn, radius })
115
+ .stroke(stroke)
116
+ .opacity(Math.max(0, Math.min(1, this.dimOpacity)))
117
+ )
118
+
119
+ // One `draw` per run: shapes chained before a `stroke()` are combined into a
120
+ // single surface, and stroking a union of disjoint open paths doesn't paint
121
+ // — so a line that leaves the region and comes back would lose both halves.
122
+ for (const run of clipPolylineToBox(drawn, box)) {
123
+ ctx.draw(new Graphics2D().line({ points: run, radius }).stroke(stroke))
124
+ }
125
+ }
126
+
127
+ /**
128
+ * The prefix of `pts` revealed at fraction `p ∈ [0, 1]`, measuring the reveal
129
+ * by *cumulative arc length* so the line traces at a steady pace regardless of
130
+ * uneven point spacing. Returns the whole-point prefix plus one interpolated
131
+ * point partway along the active segment.
132
+ */
133
+ private tracePoints(pts: Vector2[], p: number): Vector2[] {
134
+ if (p >= 1 || pts.length < 2) return pts
135
+ if (p <= 0) return []
136
+
137
+ const segLen: number[] = []
138
+ let total = 0
139
+ for (let i = 1; i < pts.length; i++) {
140
+ const d = Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y)
141
+ segLen.push(d)
142
+ total += d
143
+ }
144
+ if (total === 0) return pts
145
+
146
+ let target = total * p
147
+ const out: Vector2[] = [pts[0]]
148
+ for (let i = 0; i < segLen.length; i++) {
149
+ if (target >= segLen[i]) {
150
+ out.push(pts[i + 1])
151
+ target -= segLen[i]
152
+ } else {
153
+ const t = segLen[i] === 0 ? 0 : target / segLen[i]
154
+ out.push({
155
+ x: pts[i].x + (pts[i + 1].x - pts[i].x) * t,
156
+ y: pts[i].y + (pts[i + 1].y - pts[i].y) * t,
157
+ })
158
+ break
159
+ }
160
+ }
161
+ return out
162
+ }
163
+
164
+ /**
165
+ * Trace the line in from its left end to its right over `duration` seconds.
166
+ * Drives `progress` `0 → 1`.
167
+ *
168
+ * A `Command` rather than a generator, so the trace can be *evaluated* at a
169
+ * time instead of run to one — which is what lets a scene containing this
170
+ * chart be scrubbed in constant time. It no longer needs to prime `progress`
171
+ * to 0 first: the value at `t` is a function of `t`, so a repeat call re-traces
172
+ * by definition rather than by having reset something.
173
+ */
174
+ @command()
175
+ enter(args: CommandArgs<Record<string, never>> & { duration: number }): Command<ChartLineProps> {
176
+ return this.enterFrom(0, args.duration, args.easing ?? easeOut())
177
+ }
178
+
179
+ /**
180
+ * The trace, with both ends stated: `progress` runs `from` → `to`.
181
+ *
182
+ * What {@link LineChart.showSeries} and `hideSeries` are both made of — they
183
+ * are the same motion in opposite directions, and expressing them as one thing
184
+ * with endpoints is what stops the pair drifting apart.
185
+ *
186
+ * `enabled` rides along in the same value rather than being set before or after
187
+ * the command. A line is drawable for every `t` the trace covers and undrawn
188
+ * outside it, which is what makes arriving at a time backwards show what
189
+ * arriving forwards does — a flag flipped by a side effect would not.
190
+ */
191
+ enterFrom(
192
+ from: number,
193
+ duration: number,
194
+ easing: EasingFunction = easeOut(),
195
+ to = 1
196
+ ): Command<ChartLineProps> {
197
+ return this.command<ChartLineProps>(
198
+ (t) => {
199
+ const progress = from + (to - from) * t
200
+ // Hidden only once it has fully retraced, so the last frame of a hide is
201
+ // the empty plot rather than a line that vanished a frame early.
202
+ return { progress, enabled: progress > 0 }
203
+ },
204
+ duration,
205
+ easing
206
+ )
207
+ }
208
+ }
@@ -0,0 +1,135 @@
1
+ import {
2
+ type AssetScope,
3
+ Graphics2D,
4
+ Node2D,
5
+ fillOps,
6
+ strokeOps,
7
+ property,
8
+ type Fill,
9
+ type FillResolved,
10
+ type Node2DProps,
11
+ type RenderContext2D,
12
+ type Stroke,
13
+ type StrokeResolved,
14
+ } from "@motionscript/core"
15
+
16
+ import {
17
+ DEFAULT_CHART_THEME,
18
+ EMPTY_REGION_BOX,
19
+ hasRegion,
20
+ type RegionBox,
21
+ } from "./shared"
22
+ import { declarePaints } from "@motionscript/core/component"
23
+
24
+ export interface ChartRegionProps extends Node2DProps {
25
+ /**
26
+ * The highlighted slice, already resolved into this node's local pixel space
27
+ * (origin at centre, y-up) by the parent {@link LineChart}. A degenerate box
28
+ * draws nothing.
29
+ */
30
+ box: RegionBox
31
+ /** Dashed rule marking each *bounded* edge of the box. */
32
+ stroke: Stroke
33
+ /** Wash filling the box, under the series lines. */
34
+ fill: Fill
35
+ /**
36
+ * Reveal of the annotation in `[0, 1]`: 0 hides it, 1 draws it fully. Driven
37
+ * by the chart's own `regionReveal`, so the rules and the series' dimming move
38
+ * as one.
39
+ */
40
+ reveal: number
41
+ }
42
+
43
+ /**
44
+ * The **region call-out** of a {@link LineChart}: a washed rectangle over the
45
+ * plot with a dashed rule down each edge the author actually bounded. Sized and
46
+ * positioned entirely from the pre-mapped {@link ChartRegionProps.box} rather
47
+ * than its own `layoutBounds` — the box already carries the plot geometry.
48
+ *
49
+ * It draws only the *marking*; fading the series outside the region is
50
+ * {@link ChartLine}'s job (it clips its own polyline against the same box), so
51
+ * the two can't disagree about where the boundary is.
52
+ *
53
+ * Only bounded edges get a rule: a region given just an `x` range spans the full
54
+ * plot height, so its top and bottom edges are the plot's own border, not a data
55
+ * bound — drawing dashes there would assert a limit the author didn't set.
56
+ */
57
+ export class ChartRegion extends Node2D<ChartRegionProps> {
58
+ @property({ default: () => EMPTY_REGION_BOX }) declare box: RegionBox
59
+ @property({
60
+ default: DEFAULT_CHART_THEME.region.stroke,
61
+ mapper: strokeOps.resolve,
62
+ tween: strokeOps.lerp,
63
+ })
64
+ declare stroke: Stroke
65
+ @property({
66
+ default: DEFAULT_CHART_THEME.region.fill,
67
+ mapper: fillOps.resolve,
68
+ tween: fillOps.lerp,
69
+ })
70
+ declare fill: Fill
71
+ @property({ default: 0 }) declare reveal: number
72
+
73
+ /**
74
+ * This node extends `Node2D` rather than `ShapeNode`, so nothing declares the
75
+ * paint props it carries — see {@link declarePaints}.
76
+ */
77
+ override declareAssets(assets: AssetScope): void {
78
+ super.declareAssets(assets)
79
+ declarePaints(this, assets)
80
+ }
81
+
82
+ protected renderSelf(ctx: RenderContext2D): void {
83
+ const box = this.box
84
+ if (!hasRegion(box)) return
85
+
86
+ const r = Math.max(0, Math.min(1, this.reveal))
87
+ if (r <= 0) return
88
+
89
+ const width = box.right - box.left
90
+ const height = box.top - box.bottom
91
+ const cx = (box.left + box.right) / 2
92
+ const cy = (box.bottom + box.top) / 2
93
+
94
+ // Wash first, so the rules sit over their own tint.
95
+ const layers = this.fill as FillResolved[]
96
+ if (layers.length > 0) {
97
+ ctx.draw(
98
+ new Graphics2D()
99
+ .rect({ x: cx, y: cy, width, height })
100
+ .fill(this.fill)
101
+ .opacity(r)
102
+ )
103
+ }
104
+
105
+ // One rule per bounded edge, growing from the region's centre outward as
106
+ // `reveal` climbs — the same "trace it in" beat as the series lines.
107
+ const stroke = this.stroke as StrokeResolved[]
108
+ if (stroke.length === 0) return
109
+
110
+ // One `draw` per rule rather than four line ops under a single paint:
111
+ // shapes chained before a `stroke()` are combined into one surface, and
112
+ // stroking a union of disjoint open paths doesn't paint.
113
+ const rule = (points: { x: number; y: number }[]) =>
114
+ ctx.draw(new Graphics2D().line({ points }).stroke(this.stroke).opacity(r))
115
+
116
+ if (box.xBounded) {
117
+ const half = (height / 2) * r
118
+ for (const x of [box.left, box.right]) {
119
+ rule([
120
+ { x, y: cy - half },
121
+ { x, y: cy + half },
122
+ ])
123
+ }
124
+ }
125
+ if (box.yBounded) {
126
+ const half = (width / 2) * r
127
+ for (const y of [box.bottom, box.top]) {
128
+ rule([
129
+ { x: cx - half, y },
130
+ { x: cx + half, y },
131
+ ])
132
+ }
133
+ }
134
+ }
135
+ }