basalt-ui 2.10.0 → 2.11.1

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 (78) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/MIGRATING.md +36 -13
  3. package/agent/rules/basalt-charts.md +2 -2
  4. package/agent/skills/basalt-charts/SKILL.md +16 -17
  5. package/dist/charts/BandStrip.d.ts +3 -2
  6. package/dist/charts/BandStrip.d.ts.map +1 -1
  7. package/dist/charts/CartesianChart.d.ts +3 -0
  8. package/dist/charts/CartesianChart.d.ts.map +1 -1
  9. package/dist/charts/CartesianChart.js +9 -3
  10. package/dist/charts/DualPanel.d.ts.map +1 -1
  11. package/dist/charts/DualPanel.js +21 -15
  12. package/dist/charts/Heatmap.d.ts +33 -3
  13. package/dist/charts/Heatmap.d.ts.map +1 -1
  14. package/dist/charts/Heatmap.js +111 -68
  15. package/dist/charts/Lines.d.ts.map +1 -1
  16. package/dist/charts/Lines.js +7 -45
  17. package/dist/charts/MirroredBars.js +2 -2
  18. package/dist/charts/Sparkline.d.ts +12 -0
  19. package/dist/charts/Sparkline.d.ts.map +1 -1
  20. package/dist/charts/Sparkline.js +68 -5
  21. package/dist/charts/band-fold.d.ts +7 -0
  22. package/dist/charts/band-fold.d.ts.map +1 -1
  23. package/dist/charts/compile.d.ts +4 -1
  24. package/dist/charts/compile.d.ts.map +1 -1
  25. package/dist/charts/compile.js +43 -19
  26. package/dist/charts/heatmap-fill.d.ts +15 -0
  27. package/dist/charts/heatmap-fill.d.ts.map +1 -0
  28. package/dist/charts/heatmap-fill.js +13 -0
  29. package/dist/charts/host.d.ts +5 -1
  30. package/dist/charts/host.d.ts.map +1 -1
  31. package/dist/charts/host.js +37 -1
  32. package/dist/charts/index.d.ts +1 -1
  33. package/dist/charts/index.d.ts.map +1 -1
  34. package/dist/charts/labels.d.ts +34 -0
  35. package/dist/charts/labels.d.ts.map +1 -0
  36. package/dist/charts/labels.js +63 -0
  37. package/dist/charts/marks.d.ts +8 -1
  38. package/dist/charts/marks.d.ts.map +1 -1
  39. package/dist/charts/marks.js +50 -13
  40. package/dist/charts/panel.d.ts +7 -1
  41. package/dist/charts/panel.d.ts.map +1 -1
  42. package/dist/charts/panel.js +9 -4
  43. package/dist/charts/plot-context.d.ts +42 -0
  44. package/dist/charts/plot-context.d.ts.map +1 -0
  45. package/dist/charts/plot-context.js +64 -0
  46. package/dist/charts/scales.d.ts +6 -1
  47. package/dist/charts/scales.d.ts.map +1 -1
  48. package/dist/charts/scales.js +28 -8
  49. package/dist/charts/ticks.d.ts +12 -0
  50. package/dist/charts/ticks.d.ts.map +1 -0
  51. package/dist/charts/ticks.js +42 -0
  52. package/dist/charts/types.d.ts +39 -5
  53. package/dist/charts/types.d.ts.map +1 -1
  54. package/dist/tokens/core.d.ts +6 -0
  55. package/dist/tokens/core.d.ts.map +1 -1
  56. package/dist/tokens/core.js +5 -3
  57. package/llms.txt +12 -4
  58. package/package.json +1 -1
  59. package/src/charts/BandStrip.tsx +2 -5
  60. package/src/charts/CartesianChart.tsx +13 -2
  61. package/src/charts/DualPanel.tsx +22 -16
  62. package/src/charts/Heatmap.tsx +181 -76
  63. package/src/charts/Lines.tsx +11 -57
  64. package/src/charts/MirroredBars.tsx +2 -2
  65. package/src/charts/Sparkline.tsx +106 -5
  66. package/src/charts/band-fold.ts +11 -0
  67. package/src/charts/compile.ts +60 -20
  68. package/src/charts/heatmap-fill.ts +19 -0
  69. package/src/charts/host.tsx +59 -0
  70. package/src/charts/index.ts +1 -1
  71. package/src/charts/labels.ts +118 -0
  72. package/src/charts/marks.ts +72 -14
  73. package/src/charts/panel.tsx +18 -5
  74. package/src/charts/plot-context.ts +109 -0
  75. package/src/charts/scales.ts +41 -11
  76. package/src/charts/ticks.ts +61 -0
  77. package/src/charts/types.ts +39 -5
  78. package/src/tokens/core.ts +10 -3
@@ -1,4 +1,15 @@
1
1
  import { oneOf } from '../common/errors'
2
+ import type { ChartSeries } from './types'
3
+
4
+ /**
5
+ * The fields a named state carries wherever one is declared (`BandStrip`'s `states`, `Heatmap`'s):
6
+ * the key, its legend label and color, its fill opacity, and the legend / tooltip / note switches.
7
+ * One base so a field means the same thing on every kind.
8
+ */
9
+ export type NamedChartState = Pick<
10
+ ChartSeries<never>,
11
+ 'key' | 'label' | 'color' | 'tooltip' | 'legend' | 'note' | 'fillOpacity'
12
+ >
2
13
 
3
14
  /** A run of adjacent slots drawn as one band; `items` are the source data it stands for. */
4
15
  export type Group<T> = { start: number; items: T[] }
@@ -29,6 +29,9 @@ import { VX } from '../tokens'
29
29
  import type { ContainerClass } from '../tokens/size-classes'
30
30
  import { cursorBinding, sourceOnlyFocus } from './cursor'
31
31
  import { cursorDots } from './marks'
32
+ import { bucketTicks, strideEvery } from './ticks'
33
+ import { MAIN_PANE, plotAccess, plotContext } from './plot-context'
34
+ import type { PlotSizes } from './plot-context'
32
35
  import { resolveContainerClass } from '../tokens/size-classes'
33
36
  import { resolveYDomain, xScaleFor, xZoneFractions, yScaleFor } from './scales'
34
37
  import type { XScaleModel } from './scales'
@@ -62,6 +65,7 @@ export type CartesianInput<T, X extends ChartX> = Pick<
62
65
  | 'y'
63
66
  | 'y2'
64
67
  | 'xTicks'
68
+ | 'xDomain'
65
69
  | 'formatX'
66
70
  | 'zones'
67
71
  | 'xZones'
@@ -84,6 +88,8 @@ export type CartesianInput<T, X extends ChartX> = Pick<
84
88
  reverseRows?: boolean
85
89
  /** Bar kinds: how the left-axis `mark: 'bar'` series combine for the auto domain. */
86
90
  stack?: 'stacked' | 'normalized'
91
+ /** The plot area the engine last laid out; `null` before the first layout (the frame stands in). */
92
+ plot?: PlotSizes | null
87
93
  }
88
94
 
89
95
  /** Font size and tick counts per container class (§ 9.6). */
@@ -96,6 +102,13 @@ const LADDER = {
96
102
 
97
103
  /** Space between the plot's left edge and a compact y label drawn inside it. */
98
104
  const INSIDE_LABEL_DX = 4
105
+
106
+ /**
107
+ * A tick within this share of the x domain from its start counts as on the left edge: half a
108
+ * `DD.MM` label is ~15 px, 4–5% of a compact plot. Round ticks rarely land on the domain start
109
+ * exactly, so an equality test would miss the common case.
110
+ */
111
+ const LEFT_EDGE_SHARE = 0.05
99
112
  const INSIDE_LABEL_DY = -6
100
113
 
101
114
  /**
@@ -275,11 +288,21 @@ export function yGuide<T>(opts: {
275
288
  }
276
289
  }
277
290
 
291
+ /** The buckets of a band Date axis, or `null` for any other axis. */
292
+ function bucketDates<X extends ChartX>(model: XScaleModel<X>): readonly Date[] | null {
293
+ if (!model.band || model.kind !== 'date') return null
294
+ const dates = model.values.filter((v): v is X & Date => v instanceof Date)
295
+ return dates.length === model.values.length ? dates : null
296
+ }
297
+
278
298
  function xTickPolicy<X extends ChartX>(
279
299
  model: XScaleModel<X>,
280
300
  xTicks: number | readonly X[],
281
301
  ): { values: readonly ChartValue[] } | { count: number } {
282
302
  if (typeof xTicks === 'object') return { values: xTicks }
303
+ const buckets = typeof xTicks === 'number' && Number.isFinite(xTicks) ? bucketDates(model) : null
304
+ if (buckets !== null && typeof xTicks === 'number')
305
+ return { values: bucketTicks(buckets, xTicks) }
283
306
  if (model.band || model.kind === 'string') return { values: model.values }
284
307
  if (model.kind === 'date' && model.extent)
285
308
  return {
@@ -294,8 +317,7 @@ function xTickPolicy<X extends ChartX>(
294
317
  * the ones that collide, so a short-label grid (18 hour columns) would otherwise draw all of them.
295
318
  */
296
319
  export function strideTicks<V>(values: readonly V[], cls: ContainerClass): V[] {
297
- const stride = Math.max(1, Math.ceil(values.length / LADDER[cls].xTicks))
298
- return values.filter((_, i) => i % stride === 0)
320
+ return strideEvery(values, LADDER[cls].xTicks)
299
321
  }
300
322
 
301
323
  export function xGuide<X extends ChartX>(opts: {
@@ -310,6 +332,11 @@ export function xGuide<X extends ChartX>(opts: {
310
332
  const ladder = LADDER[cls]
311
333
  const inside = labelsInside(cls, height)
312
334
  const ticks = xTickPolicy(model, xTicks ?? ladder.xTicks)
335
+ // A continuous scale's domain start and span; a band scale pads its first slot, so none applies.
336
+ const [leftEdgeX, spanX] =
337
+ !model.band && model.extent
338
+ ? [model.extent[0], model.extent[1] - model.extent[0]]
339
+ : [Number.NaN, Number.NaN]
313
340
  return {
314
341
  axis: {
315
342
  line: AXIS_LINE,
@@ -318,10 +345,15 @@ export function xGuide<X extends ChartX>(opts: {
318
345
  fontSize: ladder.font,
319
346
  opacity: 1,
320
347
  thin: true,
321
- // A locked-zero left margin (inside labels) must not clip the first label.
322
- ...(inside && {
323
- anchor: ({ index }: { index: number }) => (index === 0 ? ('start' as const) : undefined),
324
- }),
348
+ // A label centred on a tick near the plot's left edge hangs left of it, under the gutter's
349
+ // lowest y label (outside labels) or off the plot (inside labels, left margin locked to
350
+ // zero): start-anchor it. `+value` is a Date's timestamp, or the number itself.
351
+ anchor: ({ index, value }: { index: number; value: ChartValue }) => {
352
+ const pinnedFirst = inside && index === 0
353
+ const share = (+value - leftEdgeX) / spanX
354
+ const onLeftEdge = share >= 0 && share <= LEFT_EDGE_SHARE
355
+ return pinnedFirst || onLeftEdge ? ('start' as const) : undefined
356
+ },
325
357
  },
326
358
  },
327
359
  }
@@ -755,7 +787,7 @@ function cursorDotMarks<T, X extends ChartX>(
755
787
  ? []
756
788
  : [{ x: input.x(d), y, series: s.key, datum: d }]
757
789
  })
758
- return [cursorDots(s, rows, axes.onRight(s) ? 'y2' : undefined)]
790
+ return cursorDots(s, rows, axes.onRight(s) ? 'y2' : undefined)
759
791
  })
760
792
  }
761
793
 
@@ -827,7 +859,7 @@ export function compileCartesian<T, X extends ChartX>(
827
859
  const visible = visibleSeries(input.series, input.hidden ?? new Set<string>())
828
860
  const visibleKeys = new Set(visible.map((s) => s.key))
829
861
  const keys = new Set(input.series.map((s) => s.key))
830
- const model = xScaleFor(input.data.map(input.x), input.band === true)
862
+ const model = xScaleFor(input.data.map(input.x), input.band === true, input.xDomain)
831
863
  const axes = resolveAxes(input, visible)
832
864
  const under = underlayMarks(input, model, axes)
833
865
  const over = refLineMarks(input, axes)
@@ -839,20 +871,27 @@ export function compileCartesian<T, X extends ChartX>(
839
871
  s.area ? [seriesAreaGradient(s, i, input, axes)] : [],
840
872
  )
841
873
 
842
- return {
874
+ const definition: CartesianDefinition = {
843
875
  chart: ({ width, height }: ChartBuildContext): StoredChartSpec => {
844
876
  const cls = resolveContainerClass(width)
845
- const kindMarks = input.marks({
846
- rows,
847
- visible,
848
- highlighted: input.highlighted ?? null,
849
- containerClass: cls,
850
- width,
851
- height,
852
- y2: axes.right ? 'y2' : undefined,
853
- yDomain: axes.left.domain,
854
- y2Domain: axes.right?.domain,
855
- })
877
+ const kindMarks = input.marks(
878
+ plotContext(
879
+ {
880
+ rows,
881
+ visible,
882
+ highlighted: input.highlighted ?? null,
883
+ containerClass: cls,
884
+ width,
885
+ height,
886
+ data: input.data,
887
+ xFraction: model.fraction,
888
+ y2: axes.right ? 'y2' : undefined,
889
+ yDomain: axes.left.domain,
890
+ y2Domain: axes.right?.domain,
891
+ },
892
+ plotAccess(definition, input.plot, MAIN_PANE),
893
+ ),
894
+ )
856
895
  return {
857
896
  marks: [...under, ...kindMarks, ...dots, ...over, crosshair({ x: CROSSHAIR, y: false })],
858
897
  scales: buildScales({
@@ -888,4 +927,5 @@ export function compileCartesian<T, X extends ChartX>(
888
927
  ? false
889
928
  : tooltipSpec({ input, axes, visible, keys, visibleKeys, formatX }),
890
929
  }
930
+ return definition
891
931
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The `Heatmap` fills as numbers: the ramp's floor and the flat absent fill are tuned TOGETHER,
3
+ * because a near-baseline measured hour must never read as an unmeasured one. `heatmap-fill.test.ts`
4
+ * holds the pair to a ΔE*ab floor against every ramp step in both schemes — retune here, not at a
5
+ * call site.
6
+ */
7
+
8
+ /** Intensity steps: quantized, so the gradient legend and the cells are the same ramp. */
9
+ export const RAMP_LEVELS = 8
10
+ /** Opacity of the lowest ramp step. */
11
+ export const RAMP_FLOOR = 0.28
12
+ /** Opacity of the flat neutral fill of an absent cell. */
13
+ export const ABSENT_OPACITY = 0.08
14
+
15
+ /** The ramp's opacities, lowest to full ink. */
16
+ export const RAMP_OPACITIES: readonly number[] = Array.from(
17
+ { length: RAMP_LEVELS },
18
+ (_, i) => RAMP_FLOOR + ((1 - RAMP_FLOOR) * i) / (RAMP_LEVELS - 1),
19
+ )
@@ -7,8 +7,13 @@
7
7
  * box is final in the server HTML and hydration only redraws the svg inside it (W10).
8
8
  */
9
9
  import { Chart } from '@tanstack/charts/react'
10
+ import type { ChartProps } from '@tanstack/charts/react'
11
+ import type { ChartValue } from '@tanstack/charts/types/core'
12
+ import { useEffect, useMemo } from 'react'
10
13
  import type { CSSProperties, ReactElement } from 'react'
11
14
  import type { CartesianDefinition } from './compile'
15
+ import { MAIN_PANE, measuredPlots, readsPlot, recordPlots, watchPlotReads } from './plot-context'
16
+ import type { PlotSize, PlotSizes } from './plot-context'
12
17
  import { ChartBox } from './box'
13
18
  import type { ChartBoxHeight } from './box'
14
19
  import { INITIAL_WIDTH } from './sizing'
@@ -22,8 +27,14 @@ export type ChartEngineProps = {
22
27
  idPrefix: string
23
28
  /** `touch-action: pan-y`: a vertical swipe across the chart still scrolls the page. */
24
29
  coarse: boolean
30
+ /** The laid-out plot area of every pane after each layout, in px; fires only for a definition
31
+ * whose `marks` read it (and once more for a read that comes after the measurement). */
32
+ onPlot?: (sizes: PlotSizes) => void
25
33
  }
26
34
 
35
+ /** The engine props of a basalt definition (`CartesianDefinition`'s datum and value types). */
36
+ type EngineProps = ChartProps<unknown, ChartValue, number>
37
+
27
38
  /** `currentColor` is the axis ink. The font is pinned to mono (the 1.x tick look) and inherited by
28
39
  * the svg — TanStack measures guides with the host's computed font. */
29
40
  const HOST_STYLE: CSSProperties = {
@@ -40,7 +51,30 @@ export function ChartEngine({
40
51
  height,
41
52
  idPrefix,
42
53
  coarse,
54
+ onPlot,
43
55
  }: ChartEngineProps): ReactElement {
56
+ useEffect(() => {
57
+ if (!onPlot) return
58
+ watchPlotReads(definition, () => {
59
+ // A microtask: the read happens inside the engine's build, which may sit in a React render.
60
+ queueMicrotask(() => {
61
+ const sizes = measuredPlots(definition)
62
+ if (sizes) onPlot(sizes)
63
+ })
64
+ })
65
+ return () => watchPlotReads(definition, undefined)
66
+ }, [definition, onPlot])
67
+ // Stable, so the engine does not re-register its render hook on every chart render.
68
+ const onRender = useMemo<EngineProps['onRender']>(
69
+ () =>
70
+ onPlot &&
71
+ ((context) => {
72
+ const sizes = measurePlots(context)
73
+ recordPlots(definition, sizes)
74
+ if (readsPlot(definition)) onPlot(sizes)
75
+ }),
76
+ [onPlot, definition],
77
+ )
44
78
  return (
45
79
  <ChartBox height={height}>
46
80
  <Chart
@@ -49,6 +83,7 @@ export function ChartEngine({
49
83
  initialWidth={INITIAL_WIDTH}
50
84
  idPrefix={idPrefix}
51
85
  className="basalt-chart"
86
+ {...(onRender && { onRender })}
52
87
  style={coarse ? COARSE_STYLE : HOST_STYLE}
53
88
  />
54
89
  </ChartBox>
@@ -58,3 +93,27 @@ export function ChartEngine({
58
93
  /** Scopes the engine's SVG resource ids per chart instance (`useId` output carries colons). */
59
94
  export const idPrefixOf = (id: string, prefix = 'chart'): string =>
60
95
  `basalt-${prefix}-${id.replaceAll(/[^\w-]/g, '')}`
96
+
97
+ type RenderContext = Parameters<NonNullable<EngineProps['onRender']>>[0]
98
+
99
+ const sizeOf = (width: number, height: number): PlotSize => ({ width, height })
100
+
101
+ /**
102
+ * The laid-out plot area of each pane. A single chart is the scene's own `chart` bounds. A composed
103
+ * chart's panes are laid out inside the engine's view composition and not exposed on the scene, so
104
+ * each pane's plot is the rect of its marks clip (`<owner>:<pane>:marks:clip-defs`), which the
105
+ * rung's `clip: true` makes the plot exactly.
106
+ */
107
+ function measurePlots({ scene, svg }: RenderContext): PlotSizes {
108
+ const views = svg.querySelectorAll('g.ts-chart__view')
109
+ if (views.length === 0) return { [MAIN_PANE]: sizeOf(scene.chart.width, scene.chart.height) }
110
+ const sizes: Record<string, PlotSize> = {}
111
+ for (const view of views) {
112
+ const base = view.getAttribute('data-ts-key')?.replace(/view$/, '')
113
+ const clip = base && view.querySelector(`[data-ts-key="${base}marks:clip-defs"] rect`)
114
+ const pane = base?.split(':').at(-2)
115
+ if (!pane || !clip) continue
116
+ sizes[pane] = sizeOf(Number(clip.getAttribute('width')), Number(clip.getAttribute('height')))
117
+ }
118
+ return sizes
119
+ }
@@ -19,7 +19,7 @@ export {
19
19
  } from './BandStrip'
20
20
  export { foldBands } from './band-fold'
21
21
  export { Donut, type DonutProps, type DonutDatum } from './Donut'
22
- export { Heatmap, type HeatmapProps } from './Heatmap'
22
+ export { Heatmap, type HeatmapProps, type HeatmapState } from './Heatmap'
23
23
  export { DualPanel, type DualPanelProps, type DualPanelLine, type DualPanelBar } from './DualPanel'
24
24
  export {
25
25
  MirroredBars,
@@ -0,0 +1,118 @@
1
+ /**
2
+ * `Lines`' end labels: which series carry one, and on which side of its last point it sits. Pure,
3
+ * so the rules are tested without an engine; `endLabelMarks` is the only part that draws.
4
+ */
5
+ import { decorative } from '@tanstack/charts/mark/decorative'
6
+ import { text } from '@tanstack/charts/text'
7
+ import { VX } from '../tokens'
8
+ import { rowX } from './types'
9
+ import type { ChartMarks, ChartSeries, ChartX, PlotContext, PlotRow } from './types'
10
+
11
+ const MAX_END_LABELS = 3
12
+ /** Below this vertical gap two end labels would collide; then none is drawn. */
13
+ const END_LABEL_MIN_GAP = 13
14
+ const END_LABEL_DX = 6
15
+ /**
16
+ * A glyph's advance as a share of the font size, for the room check. 0.85 covers proportional
17
+ * Latin text, capitals included, in the shipped faces; a run of the widest capitals (`W`, `M` are
18
+ * ~1 em) or a much wider face can still exceed it, so the estimate errs towards flipping: a label
19
+ * that did not need to flip sits above its point, one that needed to and did not is cut.
20
+ */
21
+ const END_LABEL_GLYPH_EM = 0.85
22
+ /** A label flipped inside the plot sits this far above its point. */
23
+ const END_LABEL_FLIP_DY = -9
24
+
25
+ export type EndLabelAnchor = 'start' | 'end'
26
+
27
+ /**
28
+ * The side of its point an end label takes: `start` (right of the point) unless the point leaves
29
+ * less room than the label needs. `fraction` is the point's x as a share of the plot width,
30
+ * `plotWidth` the plot in px. Before the engine has measured the plot, `plotWidth` is the frame's,
31
+ * which is wider than the plot by the axis gutters: the first frame can keep `start` for a label
32
+ * the measured frame then flips.
33
+ */
34
+ export function endLabelAnchor(opts: {
35
+ fraction: number
36
+ plotWidth: number
37
+ label: string
38
+ fontSize: number
39
+ }): EndLabelAnchor {
40
+ const { fraction, plotWidth, label, fontSize } = opts
41
+ const room = (1 - fraction) * plotWidth
42
+ return room >= label.length * fontSize * END_LABEL_GLYPH_EM + END_LABEL_DX ? 'start' : 'end'
43
+ }
44
+
45
+ export type EndLabel<T, X extends ChartX> = {
46
+ series: ChartSeries<T>
47
+ row: PlotRow<T, X>
48
+ anchor: EndLabelAnchor
49
+ }
50
+
51
+ type LastPoint<T, X extends ChartX> = {
52
+ series: ChartSeries<T>
53
+ row: PlotRow<T, X>
54
+ y: number
55
+ fraction: number
56
+ }
57
+
58
+ /**
59
+ * The end labels to draw: none off the wide class, with a right axis, with more than
60
+ * {@link MAX_END_LABELS} lines, or when two would collide in pixels (against the plot's height).
61
+ * A series whose last point the plot's own x scale cannot place, or places outside the plot
62
+ * (`plot.xFraction` outside [0, 1]: clipped by a narrower `xDomain`), has no label.
63
+ */
64
+ export function endLabelPlan<T, X extends ChartX>(
65
+ plot: PlotContext<T, X>,
66
+ lines: readonly ChartSeries<T>[],
67
+ ): EndLabel<T, X>[] {
68
+ if (plot.containerClass !== 'wide' || plot.y2 !== undefined) return []
69
+ if (lines.length === 0 || lines.length > MAX_END_LABELS) return []
70
+ const last = lines.flatMap((series): LastPoint<T, X>[] => {
71
+ const row = plot.rows(series.key).findLast((r) => r.y !== null)
72
+ if (row === undefined || row.y === null) return []
73
+ const fraction = plot.xFraction(row.x)
74
+ if (fraction === null || fraction < 0 || fraction > 1) return []
75
+ return [{ series, row, y: row.y, fraction }]
76
+ })
77
+ // Collision check in pixels from the plot height: labels that would overlap are not drawn at all.
78
+ // No `y2` here (returned above), so every label reads the left domain.
79
+ const [lo, hi] = plot.yDomain
80
+ const ys = last
81
+ .map(({ y }) => ((y - lo) / (hi - lo || 1)) * plot.plotHeight)
82
+ .toSorted((a, b) => a - b)
83
+ if (ys.some((y, i) => i > 0 && y - (ys[i - 1] as number) < END_LABEL_MIN_GAP)) return []
84
+ return last.map(({ series, row, fraction }) => ({
85
+ series,
86
+ row,
87
+ anchor: endLabelAnchor({
88
+ fraction,
89
+ plotWidth: plot.plotWidth,
90
+ label: series.label,
91
+ fontSize: VX.text.micro,
92
+ }),
93
+ }))
94
+ }
95
+
96
+ /** The offset of a label from its point: right of it, level; or left of it and above. */
97
+ export function endLabelOffset(anchor: EndLabelAnchor): { dx: number; dy: number } {
98
+ return anchor === 'end'
99
+ ? { dx: -END_LABEL_DX, dy: END_LABEL_FLIP_DY }
100
+ : { dx: END_LABEL_DX, dy: 0 }
101
+ }
102
+
103
+ export function endLabelMarks<T, X extends ChartX>(plan: readonly EndLabel<T, X>[]): ChartMarks {
104
+ return plan.map(({ series, row, anchor }) =>
105
+ decorative(
106
+ text([row], {
107
+ id: `${series.key}-end-label`,
108
+ x: rowX,
109
+ y: 'y',
110
+ text: () => series.label,
111
+ fill: series.color,
112
+ fontSize: VX.text.micro,
113
+ anchor,
114
+ ...endLabelOffset(anchor),
115
+ }),
116
+ ),
117
+ )
118
+ }
@@ -58,6 +58,47 @@ export function lineMark<T, X extends ChartX>(
58
58
  })
59
59
  }
60
60
 
61
+ const isFinitePoint = <T, X extends ChartX>(r: PlotRow<T, X> | undefined): boolean =>
62
+ r !== undefined && r.y !== null && Number.isFinite(r.y)
63
+
64
+ /** A lone dot's radius as a multiple of the series' stroke width, so it reads as the line's end cap. */
65
+ const LONE_DOT_STROKE_FACTOR = 1.25
66
+
67
+ /**
68
+ * The dot for a point a line cannot draw: a finite value with no finite neighbour in `drawn` (the
69
+ * rows the line is drawn through: a one-point window, or a value between nulls). A path of one
70
+ * point has no length, so without this the series is invisible. One mark per series. A point the
71
+ * series' own `getMarker` already marks is left to it.
72
+ */
73
+ export function loneDots<T, X extends ChartX>(
74
+ s: ChartSeries<T>,
75
+ drawn: readonly PlotRow<T, X>[],
76
+ yScale: 'y2' | undefined,
77
+ highlighted: string | null,
78
+ ): ChartMarks {
79
+ const lone = drawn.filter(
80
+ (r, i) =>
81
+ isFinitePoint(r) &&
82
+ !isFinitePoint(drawn[i - 1]) &&
83
+ !isFinitePoint(drawn[i + 1]) &&
84
+ !s.getMarker?.(r.datum),
85
+ )
86
+ if (lone.length === 0) return []
87
+ return [
88
+ decorative(
89
+ dot(lone, {
90
+ id: `${s.key}-lone`,
91
+ x: rowX,
92
+ y: 'y',
93
+ r: Math.max(VX.dotR - 1, (s.strokeWidth ?? LINE_STROKE_WIDTH) * LONE_DOT_STROKE_FACTOR),
94
+ fill: s.color,
95
+ fillOpacity: (s.strokeOpacity ?? 1) * emphasis(highlighted, s),
96
+ ...(yScale !== undefined && { yScale }),
97
+ }),
98
+ ),
99
+ ]
100
+ }
101
+
61
102
  type MarkerGroup<T, X extends ChartX> = {
62
103
  color: string
63
104
  opacity: number
@@ -114,22 +155,39 @@ export function cursorDots<T, X extends ChartX>(
114
155
  s: ChartSeries<T>,
115
156
  rows: readonly PlotRow<T, X>[],
116
157
  yScale: 'y2' | undefined,
117
- ): ChartMarks[number] {
118
- return dot(rows, {
119
- id: `${s.key}-cursor`,
120
- x: rowX,
121
- y: 'y',
122
- r: VX.dotR,
123
- fill: s.color,
124
- fillOpacity: 0,
125
- stroke: VX.surface.panel,
126
- strokeWidth: 1.5,
127
- strokeOpacity: 0,
128
- states: [{ when: { focus: 'x' }, style: { fillOpacity: 1, strokeOpacity: 1 } }],
129
- ...(yScale !== undefined && { yScale }),
130
- })
158
+ ): ChartMarks {
159
+ // `dot.fill` is constant, so a series with `getMarker` gets one mark per distinct datum colour.
160
+ const byColor = new Map<string, PlotRow<T, X>[]>([[s.color, []]])
161
+ for (const row of rows) {
162
+ const color = s.getMarker?.(row.datum)?.color ?? s.color
163
+ const group = byColor.get(color)
164
+ if (group) group.push(row)
165
+ else byColor.set(color, [row])
166
+ }
167
+ return [...byColor].flatMap(([color, group]) =>
168
+ // The series colour keeps `<key>-cursor` even when no datum uses it; others are keyed by colour.
169
+ group.length === 0 && color !== s.color
170
+ ? []
171
+ : [
172
+ dot(group, {
173
+ id: color === s.color ? `${s.key}-cursor` : `${s.key}-cursor-${colorSlug(color)}`,
174
+ x: rowX,
175
+ y: 'y',
176
+ r: VX.dotR,
177
+ fill: color,
178
+ fillOpacity: 0,
179
+ stroke: VX.surface.panel,
180
+ strokeWidth: 1.5,
181
+ strokeOpacity: 0,
182
+ states: [{ when: { focus: 'x' }, style: { fillOpacity: 1, strokeOpacity: 1 } }],
183
+ ...(yScale !== undefined && { yScale }),
184
+ }),
185
+ ],
186
+ )
131
187
  }
132
188
 
189
+ const colorSlug = (color: string): string => color.replaceAll(/[^\w-]+/g, '_')
190
+
133
191
  /**
134
192
  * A single-series `barY`. The engine stacks every `barY` that has no explicit extent, and a row with
135
193
  * no `z`/`color` channel is its own series: an N-by-N matrix (a 5k-row `DualPanel` took 10 s). So
@@ -24,6 +24,8 @@ import type { ChartShellProps, ShellContext } from './CartesianChart'
24
24
  import { defaultFormatX, engineRow, utcHeaderDate, visibleSeries, xGuide, yGuide } from './compile'
25
25
  import type { CartesianDefinition } from './compile'
26
26
  import { cursorBinding, sourceOnlyFocus } from './cursor'
27
+ import { plotAccess } from './plot-context'
28
+ import type { PlotAccess } from './plot-context'
27
29
  import type { XScaleModel } from './scales'
28
30
  import { CHART_THEME, CROSSHAIR } from './theme'
29
31
  import type { ContainerClass } from '../tokens/size-classes'
@@ -36,8 +38,12 @@ import type {
36
38
  PlotRow,
37
39
  } from './types'
38
40
 
41
+ /** What a pane builder is given: the engine's frame for the pane and its plot-size access, to build
42
+ * a `PlotContext` with `plotContext()` (`plot-context.ts`). */
43
+ export type PaneContext = ChartBuildContext & { plot: PlotAccess }
44
+
39
45
  /** One pane, built per container class: its marks and its scales (x, y, and any helper scale). */
40
- export type PaneBuilder = (ctx: ChartBuildContext) => {
46
+ export type PaneBuilder = (ctx: PaneContext) => {
41
47
  marks: ChartMarks
42
48
  scales: StoredChartSpec['scales']
43
49
  }
@@ -135,10 +141,13 @@ export function rowsOf<T, X extends ChartX>(
135
141
  }
136
142
 
137
143
  /** A pane as a composable view. The crosshair is per pane: together they span both. */
138
- function paneView(build: PaneBuilder): ComposableResponsiveChartDefinition {
144
+ function paneView(
145
+ build: PaneBuilder,
146
+ access: () => PlotAccess,
147
+ ): ComposableResponsiveChartDefinition {
139
148
  return {
140
149
  chart: (ctx) => {
141
- const { marks, scales } = build(ctx)
150
+ const { marks, scales } = build({ ...ctx, plot: access() })
142
151
  return {
143
152
  marks: [...marks, crosshair({ x: CROSSHAIR, y: false })],
144
153
  scales,
@@ -176,7 +185,10 @@ function panelDefinition<T, X extends ChartX>(
176
185
  ? Math.min(Math.max(plan.topFraction, MIN_PANE_SHARE), 1 - MIN_PANE_SHARE)
177
186
  : 0.5
178
187
  const composed = composeViews({
179
- views: { top: paneView(plan.top), bottom: paneView(plan.bottom) },
188
+ views: {
189
+ top: paneView(plan.top, () => plotAccess(definition, ctx.plot, 'top')),
190
+ bottom: paneView(plan.bottom, () => plotAccess(definition, ctx.plot, 'bottom')),
191
+ },
180
192
  layout: grid({
181
193
  rows: [
182
194
  { id: 'top', grow: top },
@@ -196,7 +208,7 @@ function panelDefinition<T, X extends ChartX>(
196
208
  if (v instanceof Date && !formatX) return utcHeaderDate(v)
197
209
  return formatX ? formatX(v as X) : defaultFormatX(v)
198
210
  }
199
- return {
211
+ const definition: CartesianDefinition = {
200
212
  chart: () => composed,
201
213
  focus: tooltip?.onFollow ? 'group-x' : sourceOnlyFocus(cursorGroup, chartId),
202
214
  maxFocusDistance: Number.POSITIVE_INFINITY,
@@ -224,6 +236,7 @@ function panelDefinition<T, X extends ChartX>(
224
236
  },
225
237
  },
226
238
  }
239
+ return definition
227
240
  }
228
241
 
229
242
  export function PanelRung<T, X extends ChartX>(props: PanelRungProps<T, X>): ReactElement {