basalt-ui 2.21.0 → 2.22.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 (226) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/MIGRATING.md +277 -12
  3. package/agent/agents/basalt-design-reviewer.md +1 -1
  4. package/agent/rules/basalt-tokens.md +1 -1
  5. package/agent/skills/basalt-design/SKILL.md +1 -1
  6. package/agent/skills/basalt-design/references/anti-defaults.md +1 -1
  7. package/agent/skills/basalt-design/references/catalogue.md +1 -0
  8. package/dist/charts/BandStrip.d.ts.map +1 -1
  9. package/dist/charts/BandStrip.js +27 -3
  10. package/dist/charts/Bars.d.ts.map +1 -1
  11. package/dist/charts/Bars.js +5 -0
  12. package/dist/charts/CartesianChart.d.ts +8 -0
  13. package/dist/charts/CartesianChart.d.ts.map +1 -1
  14. package/dist/charts/CartesianChart.js +8 -5
  15. package/dist/charts/ChartCard.d.ts +12 -3
  16. package/dist/charts/ChartCard.d.ts.map +1 -1
  17. package/dist/charts/ChartCard.js +29 -8
  18. package/dist/charts/DualPanel.d.ts.map +1 -1
  19. package/dist/charts/DualPanel.js +5 -8
  20. package/dist/charts/Heatmap.d.ts +12 -1
  21. package/dist/charts/Heatmap.d.ts.map +1 -1
  22. package/dist/charts/Heatmap.js +34 -5
  23. package/dist/charts/Lines.d.ts +3 -0
  24. package/dist/charts/Lines.d.ts.map +1 -1
  25. package/dist/charts/Lines.js +29 -6
  26. package/dist/charts/MirroredBars.d.ts.map +1 -1
  27. package/dist/charts/MirroredBars.js +4 -6
  28. package/dist/charts/Sparkline.d.ts +7 -1
  29. package/dist/charts/Sparkline.d.ts.map +1 -1
  30. package/dist/charts/Sparkline.js +39 -14
  31. package/dist/charts/StackedArea.d.ts +4 -1
  32. package/dist/charts/StackedArea.d.ts.map +1 -1
  33. package/dist/charts/StackedArea.js +9 -3
  34. package/dist/charts/band-fold.d.ts +20 -1
  35. package/dist/charts/band-fold.d.ts.map +1 -1
  36. package/dist/charts/band-fold.js +9 -0
  37. package/dist/charts/chart-box.module.css +19 -0
  38. package/dist/charts/chart-card.module.css +25 -0
  39. package/dist/charts/chart-legend.module.css +7 -0
  40. package/dist/charts/compile.d.ts +17 -6
  41. package/dist/charts/compile.d.ts.map +1 -1
  42. package/dist/charts/compile.js +145 -74
  43. package/dist/charts/labels.d.ts +15 -4
  44. package/dist/charts/labels.d.ts.map +1 -1
  45. package/dist/charts/labels.js +34 -10
  46. package/dist/charts/legend.d.ts +2 -0
  47. package/dist/charts/legend.d.ts.map +1 -1
  48. package/dist/charts/legend.js +7 -21
  49. package/dist/charts/marks.js +1 -1
  50. package/dist/charts/panel.d.ts +0 -6
  51. package/dist/charts/panel.d.ts.map +1 -1
  52. package/dist/charts/panel.js +1 -10
  53. package/dist/charts/ref-label.d.ts +26 -0
  54. package/dist/charts/ref-label.d.ts.map +1 -0
  55. package/dist/charts/ref-label.js +63 -0
  56. package/dist/charts/scales.d.ts +4 -1
  57. package/dist/charts/scales.d.ts.map +1 -1
  58. package/dist/charts/scales.js +14 -3
  59. package/dist/charts/sparkline.module.css +10 -11
  60. package/dist/charts/sparkline.module.css.d.ts +1 -2
  61. package/dist/charts/state.d.ts +2 -0
  62. package/dist/charts/state.d.ts.map +1 -1
  63. package/dist/charts/state.js +2 -1
  64. package/dist/charts/types.d.ts +14 -5
  65. package/dist/charts/types.d.ts.map +1 -1
  66. package/dist/cli/doctor-upgrade.d.ts +1 -0
  67. package/dist/cli/doctor-upgrade.d.ts.map +1 -1
  68. package/dist/cli/doctor-upgrade.js +1 -0
  69. package/dist/cli/init.d.ts +2 -0
  70. package/dist/cli/init.d.ts.map +1 -1
  71. package/dist/cli/init.js +68 -4
  72. package/dist/cli/shot/capture.d.ts +21 -2
  73. package/dist/cli/shot/capture.d.ts.map +1 -1
  74. package/dist/cli/shot/capture.js +194 -32
  75. package/dist/cli/shot/detect.d.ts.map +1 -1
  76. package/dist/cli/shot/detect.js +14 -1
  77. package/dist/cli/shot/playwright.d.ts +5 -2
  78. package/dist/cli/shot/playwright.d.ts.map +1 -1
  79. package/dist/cli/shot/types.d.ts +2 -0
  80. package/dist/cli/shot/types.d.ts.map +1 -1
  81. package/dist/cli/shot/types.js +2 -0
  82. package/dist/controls/controls.module.css +11 -1
  83. package/dist/controls/filter-pill.d.ts.map +1 -1
  84. package/dist/controls/filter-pill.js +1 -0
  85. package/dist/controls/sync-button.d.ts.map +1 -1
  86. package/dist/controls/sync-button.js +22 -3
  87. package/dist/controls/sync-button.module.css +34 -2
  88. package/dist/controls/sync-button.module.css.d.ts +1 -0
  89. package/dist/dashboard/bar-list.d.ts.map +1 -1
  90. package/dist/dashboard/bar-list.js +7 -8
  91. package/dist/dashboard/bar-list.module.css +53 -0
  92. package/dist/dashboard/bar-list.module.css.d.ts +1 -0
  93. package/dist/dashboard/index.d.ts +1 -0
  94. package/dist/dashboard/index.d.ts.map +1 -1
  95. package/dist/dashboard/index.js +2 -0
  96. package/dist/dashboard/meter-model.d.ts +77 -3
  97. package/dist/dashboard/meter-model.d.ts.map +1 -1
  98. package/dist/dashboard/meter-model.js +88 -15
  99. package/dist/dashboard/meter-parts.d.ts +8 -0
  100. package/dist/dashboard/meter-parts.d.ts.map +1 -1
  101. package/dist/dashboard/meter-parts.js +238 -71
  102. package/dist/dashboard/meter.d.ts +43 -60
  103. package/dist/dashboard/meter.d.ts.map +1 -1
  104. package/dist/dashboard/meter.js +20 -3
  105. package/dist/dashboard/meter.module.css +61 -0
  106. package/dist/dashboard/meter.module.css.d.ts +5 -0
  107. package/dist/dashboard/page-summary.d.ts +20 -0
  108. package/dist/dashboard/page-summary.d.ts.map +1 -0
  109. package/dist/dashboard/page-summary.js +28 -0
  110. package/dist/dashboard/page-summary.module.css +89 -0
  111. package/dist/dashboard/page-summary.module.css.d.ts +15 -0
  112. package/dist/dashboard/section.d.ts +25 -2
  113. package/dist/dashboard/section.d.ts.map +1 -1
  114. package/dist/dashboard/section.js +10 -5
  115. package/dist/dashboard/section.module.css +23 -0
  116. package/dist/dashboard/section.module.css.d.ts +1 -0
  117. package/dist/dashboard/stat-card-parts.d.ts.map +1 -1
  118. package/dist/dashboard/stat-card-parts.js +1 -1
  119. package/dist/dashboard/stat-card.d.ts +4 -2
  120. package/dist/dashboard/stat-card.d.ts.map +1 -1
  121. package/dist/dashboard/stat-card.js +7 -5
  122. package/dist/dashboard/stat-card.module.css +17 -0
  123. package/dist/dashboard/stat-strip.d.ts +7 -1
  124. package/dist/dashboard/stat-strip.d.ts.map +1 -1
  125. package/dist/dashboard/stat-strip.js +74 -46
  126. package/dist/dashboard/stat-strip.module.css +67 -20
  127. package/dist/dashboard/stat-strip.module.css.d.ts +4 -0
  128. package/dist/dashboard/visual-slot.d.ts +7 -1
  129. package/dist/dashboard/visual-slot.d.ts.map +1 -1
  130. package/dist/dashboard/visual-slot.js +3 -1
  131. package/dist/guard/vx-names.d.ts.map +1 -1
  132. package/dist/guard/vx-names.js +2 -0
  133. package/dist/index.d.ts +1 -1
  134. package/dist/index.d.ts.map +1 -1
  135. package/dist/index.js +3 -1
  136. package/dist/styles.css +34 -2
  137. package/dist/theme/chrome-vars.d.ts +20 -5
  138. package/dist/theme/chrome-vars.d.ts.map +1 -1
  139. package/dist/theme/chrome-vars.js +46 -3
  140. package/dist/theme/controls.module.css +23 -0
  141. package/dist/theme/controls.module.css.d.ts +1 -0
  142. package/dist/theme/index.d.ts.map +1 -1
  143. package/dist/theme/index.js +8 -20
  144. package/dist/tokens/core.d.ts +2 -1
  145. package/dist/tokens/core.d.ts.map +1 -1
  146. package/dist/tokens/core.js +6 -1
  147. package/dist/tokens/derive.d.ts +3 -1
  148. package/dist/tokens/derive.d.ts.map +1 -1
  149. package/dist/tokens/derive.js +16 -1
  150. package/dist/tokens/palette.d.ts +4 -0
  151. package/dist/tokens/palette.d.ts.map +1 -1
  152. package/dist/tokens/palette.js +4 -0
  153. package/dist/tokens/status-text.d.ts.map +1 -1
  154. package/dist/tokens/status-text.js +3 -1
  155. package/llms.txt +38 -20
  156. package/package.json +1 -1
  157. package/src/charts/BandStrip.tsx +33 -3
  158. package/src/charts/Bars.tsx +6 -0
  159. package/src/charts/CartesianChart.tsx +16 -3
  160. package/src/charts/ChartCard.tsx +34 -6
  161. package/src/charts/DualPanel.tsx +3 -6
  162. package/src/charts/Heatmap.tsx +54 -5
  163. package/src/charts/Lines.tsx +56 -10
  164. package/src/charts/MirroredBars.tsx +3 -5
  165. package/src/charts/Sparkline.tsx +50 -13
  166. package/src/charts/StackedArea.tsx +14 -4
  167. package/src/charts/band-fold.ts +31 -1
  168. package/src/charts/chart-box.module.css +19 -0
  169. package/src/charts/chart-card.module.css +25 -0
  170. package/src/charts/chart-legend.module.css +7 -0
  171. package/src/charts/compile.ts +210 -85
  172. package/src/charts/labels.ts +48 -14
  173. package/src/charts/legend.tsx +10 -20
  174. package/src/charts/marks.ts +1 -1
  175. package/src/charts/panel.tsx +1 -16
  176. package/src/charts/ref-label.ts +104 -0
  177. package/src/charts/scales.ts +22 -2
  178. package/src/charts/sparkline.module.css +10 -11
  179. package/src/charts/sparkline.module.css.d.ts +1 -2
  180. package/src/charts/state.tsx +3 -1
  181. package/src/charts/types.ts +14 -5
  182. package/src/cli/doctor-upgrade.ts +1 -1
  183. package/src/cli/init.ts +100 -3
  184. package/src/cli/shot/capture.ts +251 -32
  185. package/src/cli/shot/detect.ts +18 -1
  186. package/src/cli/shot/playwright.ts +2 -2
  187. package/src/cli/shot/types.ts +3 -0
  188. package/src/controls/controls.module.css +11 -1
  189. package/src/controls/filter-pill.tsx +2 -0
  190. package/src/controls/sync-button.module.css +34 -2
  191. package/src/controls/sync-button.module.css.d.ts +1 -0
  192. package/src/controls/sync-button.tsx +40 -4
  193. package/src/dashboard/bar-list.module.css +53 -0
  194. package/src/dashboard/bar-list.module.css.d.ts +1 -0
  195. package/src/dashboard/bar-list.tsx +78 -69
  196. package/src/dashboard/index.ts +1 -0
  197. package/src/dashboard/meter-model.ts +186 -20
  198. package/src/dashboard/meter-parts.tsx +285 -64
  199. package/src/dashboard/meter.module.css +61 -0
  200. package/src/dashboard/meter.module.css.d.ts +5 -0
  201. package/src/dashboard/meter.tsx +60 -10
  202. package/src/dashboard/page-summary.module.css +89 -0
  203. package/src/dashboard/page-summary.module.css.d.ts +15 -0
  204. package/src/dashboard/page-summary.tsx +95 -0
  205. package/src/dashboard/section.module.css +23 -0
  206. package/src/dashboard/section.module.css.d.ts +1 -0
  207. package/src/dashboard/section.tsx +59 -11
  208. package/src/dashboard/stat-card-parts.tsx +5 -1
  209. package/src/dashboard/stat-card.module.css +17 -0
  210. package/src/dashboard/stat-card.tsx +12 -6
  211. package/src/dashboard/stat-strip.module.css +67 -20
  212. package/src/dashboard/stat-strip.module.css.d.ts +4 -0
  213. package/src/dashboard/stat-strip.tsx +118 -72
  214. package/src/dashboard/visual-slot.ts +12 -3
  215. package/src/guard/vx-names.ts +2 -0
  216. package/src/index.ts +2 -0
  217. package/src/styles.css +34 -2
  218. package/src/theme/__snapshots__/plain-theme.test.ts.snap +186 -60
  219. package/src/theme/chrome-vars.ts +77 -8
  220. package/src/theme/controls.module.css +23 -0
  221. package/src/theme/controls.module.css.d.ts +1 -0
  222. package/src/theme/index.ts +12 -25
  223. package/src/tokens/core.ts +4 -1
  224. package/src/tokens/derive.ts +32 -3
  225. package/src/tokens/palette.ts +4 -0
  226. package/src/tokens/status-text.ts +2 -0
@@ -92,3 +92,22 @@
92
92
  height: auto;
93
93
  min-height: inherit;
94
94
  }
95
+
96
+ /*
97
+ * The engine paints its tooltip rows as a grid of `.55rem | minmax(0, 1fr) | auto` with inline
98
+ * styles and `overflow-wrap: anywhere` on the card, so a narrow tooltip (a 390 viewport, a pointer
99
+ * near an edge) squeezes the name column to one character per line. The name keeps a floor and
100
+ * never wraps; a long name ends in an ellipsis, the value stays right-aligned. The tooltip is
101
+ * portalled out of the chart's tree, hence the global class names. `!important` because the
102
+ * engine's own values are inline.
103
+ */
104
+ :global(.ts-chart-tooltip__row) {
105
+ grid-template-columns: 0.55rem minmax(6rem, max-content) auto !important;
106
+ }
107
+
108
+ :global(.ts-chart-tooltip__row > span:nth-child(2)) {
109
+ max-width: 14rem;
110
+ overflow: hidden;
111
+ text-overflow: ellipsis;
112
+ white-space: nowrap;
113
+ }
@@ -70,3 +70,28 @@
70
70
  .factsBasis {
71
71
  margin: var(--vx-space-stack-xs) 0 0;
72
72
  }
73
+
74
+ /*
75
+ * A fact's tone is INK only (the value and its trailing text), never a fill. The status solids are
76
+ * the text-safe ones (`status-text.ts`). `stale` is the strip cell's dimmed value, verbatim
77
+ * (`stat-strip.module.css` `.cell[data-stale]`).
78
+ */
79
+ .fact[data-tone='good'] :is(.factValue, .factUnit, .factPeriod) {
80
+ color: var(--vx-status-good);
81
+ }
82
+
83
+ .fact[data-tone='warn'] :is(.factValue, .factUnit, .factPeriod) {
84
+ color: var(--vx-status-warn);
85
+ }
86
+
87
+ .fact[data-tone='bad'] :is(.factValue, .factUnit, .factPeriod) {
88
+ color: var(--vx-status-bad);
89
+ }
90
+
91
+ .fact[data-tone='muted'] :is(.factValue, .factUnit, .factPeriod) {
92
+ color: var(--vx-muted);
93
+ }
94
+
95
+ .factsRow[data-stale] {
96
+ opacity: 0.55;
97
+ }
@@ -36,3 +36,10 @@
36
36
  display: inline-flex;
37
37
  }
38
38
  }
39
+
40
+ /* Lines' `naming="auto"`: from the wide class the end labels name the lines, so the legend goes. */
41
+ @container (min-width: 800px) {
42
+ .auto[data-hide-wide] {
43
+ display: none;
44
+ }
45
+ }
@@ -5,7 +5,7 @@
5
5
  * binding, the tooltip content, and the container-class guide ladder.
6
6
  * TanStack owns margins (measured), layout, focus and keyboard, the tooltip surface and SSR.
7
7
  */
8
- import { dateTickFormat, monthName, pad2, utcAxisDate } from './date-tick-format'
8
+ import { dateTickFormat, utcAxisDate } from './date-tick-format'
9
9
  import { crosshair } from '@tanstack/charts/crosshair'
10
10
  import { decorative } from '@tanstack/charts/mark/decorative'
11
11
  import { rect } from '@tanstack/charts/rect'
@@ -16,6 +16,7 @@ import { scaleUtc } from 'd3-scale'
16
16
  import { portal } from '@tanstack/charts/tooltip/portal'
17
17
  import type {
18
18
  ChartBuildContext,
19
+ ChartTooltipAnchorContext,
19
20
  ChartGradient,
20
21
  ChartPoint,
21
22
  ChartPositionScaleOptions,
@@ -24,14 +25,16 @@ import type {
24
25
  ResponsiveChartDefinition,
25
26
  StoredChartSpec,
26
27
  } from '@tanstack/charts/types/core'
27
- import { SHORT_CHART_HEIGHT } from './box'
28
28
  import { compact } from '../format/number'
29
+ import { NON_FINITE, dateFormat } from '../format/shared'
29
30
  import { VX } from '../tokens'
30
31
  import type { ContainerClass } from '../tokens/size-classes'
31
32
  import { cursorBinding, followerOptions, quietWhileFollowing } from './cursor'
32
33
  import { cursorDots } from './marks'
33
34
  import { bucketTicks, strideEvery } from './ticks'
34
35
  import { MAIN_PANE, plotAccess, plotContext } from './plot-context'
36
+ import { refLabelPosition } from './ref-label'
37
+ import type { RefLabelPoint } from './ref-label'
35
38
  import type { PlotSizes } from './plot-context'
36
39
  import { resolveContainerClass } from '../tokens/size-classes'
37
40
  import { resolveYDomain, xScaleFor, xZoneFractions, yScaleFor } from './scales'
@@ -91,6 +94,10 @@ export type CartesianInput<T, X extends ChartX> = Pick<
91
94
  stack?: 'stacked' | 'normalized'
92
95
  /** The plot area the engine last laid out; `null` before the first layout (the frame stands in). */
93
96
  plot?: PlotSizes | null
97
+ /** The tooltip opens below the chart (a strip of cells), above only when there is no room. */
98
+ tooltipBelow?: boolean
99
+ /** The vertical rule under the cursor. Default `true`; a bar kind has none (its hover is the bar). */
100
+ crosshair?: boolean
94
101
  }
95
102
 
96
103
  /** The one tick-label size, at every container width: the caption size, so a card never mixes sizes. */
@@ -104,36 +111,55 @@ const LADDER = {
104
111
  wide: { xTicks: 6, yTicks: 5 },
105
112
  } as const satisfies Record<ContainerClass, { xTicks: number; yTicks: number }>
106
113
 
107
- /** Space between the plot's left edge and a compact y label drawn inside it. */
108
- const INSIDE_LABEL_DX = 4
109
-
110
114
  /**
111
115
  * A tick within this share of the x domain from its start counts as on the left edge: half a
112
116
  * `DD.MM` label is ~15 px, 4–5% of a compact plot. Round ticks rarely land on the domain start
113
117
  * exactly, so an equality test would miss the common case.
114
118
  */
115
119
  const LEFT_EDGE_SHARE = 0.05
116
- const INSIDE_LABEL_DY = -6
117
-
118
- /**
119
- * Y labels go inside the plot only for the compact class under `SHORT_CHART_HEIGHT` (the box's own
120
- * short signal); otherwise they sit in a left gutter. `height` is the whole chart's, `0` before it
121
- * is measured, which keeps the gutter rather than flipping a first paint inside.
122
- */
123
- const labelsInside = (cls: ContainerClass, height: number): boolean =>
124
- cls === 'compact' && height > 0 && height < SHORT_CHART_HEIGHT
125
120
 
126
121
  export function defaultNumberFormat(v: number): string {
127
122
  return compact(v, { digits: Math.abs(v) >= 1000 ? 1 : 2 })
128
123
  }
129
124
 
130
- const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
125
+ /**
126
+ * The UTC midnight of the day a day-keyed instant stands for. A key at LOCAL midnight is that local
127
+ * calendar date (east of UTC it is `22:00` UTC of the day before); any other key is its UTC date, so
128
+ * a key at 12:00 UTC or later never rolls to the next day.
129
+ */
130
+ function bucketDay(d: Date): Date {
131
+ const local = d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0
132
+ return new Date(
133
+ local
134
+ ? Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())
135
+ : Math.floor(d.getTime() / DAY_MS) * DAY_MS,
136
+ )
137
+ }
131
138
 
132
- /** `Mon Sep 1 2026`, in UTC; a non-midnight instant adds `HH:MM`. */
133
- export function utcHeaderDate(d: Date): string {
134
- const date = `${DAYS[d.getUTCDay()]} ${monthName(d)} ${d.getUTCDate()} ${d.getUTCFullYear()}`
135
- const ms = d.getTime() % DAY_MS
136
- return ms === 0 ? date : `${date} ${pad2(d.getUTCHours())}:${pad2(d.getUTCMinutes())}`
139
+ /**
140
+ * The tooltip's date: weekday, day, month and year in the page's locale (`defineFormat` /
141
+ * `BasaltProvider`), read in UTC like the time scale; a non-midnight instant adds `HH:MM`. With
142
+ * `dayOnly` (a day-granular series) the instant is its bucket's DAY, never a clock time: see
143
+ * {@link bucketDay}.
144
+ */
145
+ export function utcHeaderDate(d: Date, dayOnly = false): string {
146
+ if (!Number.isFinite(d.getTime())) return NON_FINITE
147
+ const at = dayOnly ? bucketDay(d) : d
148
+ const date = dateFormat(undefined, {
149
+ weekday: 'short',
150
+ day: 'numeric',
151
+ month: 'short',
152
+ year: 'numeric',
153
+ timeZone: 'UTC',
154
+ }).format(at)
155
+ if (dayOnly || d.getTime() % DAY_MS === 0) return date
156
+ const clock = dateFormat(undefined, {
157
+ hour: '2-digit',
158
+ minute: '2-digit',
159
+ hourCycle: 'h23',
160
+ timeZone: 'UTC',
161
+ }).format(d)
162
+ return `${date} ${clock}`
137
163
  }
138
164
 
139
165
  const DAY_MS = 86_400_000
@@ -253,10 +279,8 @@ export function yGuide<T>(opts: {
253
279
  cls: ContainerClass
254
280
  side: 'left' | 'right'
255
281
  grid: boolean
256
- /** The whole chart's height: decides inside or gutter labels. */
257
- height: number
258
282
  }): Omit<ChartPositionScaleOptions<number>, 'scale'> {
259
- const { cfg, axis, cls, side, grid, height } = opts
283
+ const { cfg, axis, cls, side, grid } = opts
260
284
  const ladder = LADDER[cls]
261
285
  const ticks =
262
286
  typeof cfg?.ticks === 'object'
@@ -264,23 +288,14 @@ export function yGuide<T>(opts: {
264
288
  : { count: typeof cfg?.ticks === 'number' ? cfg.ticks : ladder.yTicks }
265
289
  const gridLine = grid ? { grid: GRID_LINE } : {}
266
290
  if (cls === 'micro') return { ...gridLine, axis: false }
267
- // Labels sit INSIDE the plot, above their grid line, so the plot keeps the full width.
268
- const inside = labelsInside(cls, height)
291
+ // Labels sit in a gutter OUTSIDE the plot, against its edge: a line never runs through one.
269
292
  return {
270
293
  ...gridLine,
271
294
  ...(side === 'right' && { side: 'right' as const }),
272
295
  axis: {
273
296
  line: false,
274
- ticks: { ...ticks, format: axis.format, line: false, ...(inside && { size: 0, padding: 0 }) },
275
- tickLabels: {
276
- fontSize: TICK_FONT,
277
- opacity: 1,
278
- ...(inside && {
279
- anchor: side === 'left' ? ('start' as const) : ('end' as const),
280
- dx: side === 'left' ? INSIDE_LABEL_DX : -INSIDE_LABEL_DX,
281
- dy: INSIDE_LABEL_DY,
282
- }),
283
- },
297
+ ticks: { ...ticks, format: axis.format, line: false },
298
+ tickLabels: { fontSize: TICK_FONT, opacity: 1 },
284
299
  },
285
300
  }
286
301
  }
@@ -339,12 +354,9 @@ export function xGuide<X extends ChartX>(opts: {
339
354
  /** A consumer's formatter; absent, Date ticks get the span-aware {@link xTickFormat}. */
340
355
  format?: ((v: ChartValue) => string) | undefined
341
356
  cls: ContainerClass
342
- /** The whole chart's height: decides whether the left margin is locked to zero. */
343
- height: number
344
357
  }): Omit<ChartPositionScaleOptions<ChartValue>, 'scale'> {
345
- const { model, xTicks, cls, height } = opts
358
+ const { model, xTicks, cls } = opts
346
359
  const ladder = LADDER[cls]
347
- const inside = labelsInside(cls, height)
348
360
  const ticks = xTickPolicy(model, xTicks ?? ladder.xTicks)
349
361
  // A Date axis always resolves to `values` (the time scale has an extent; a band axis lists its
350
362
  // buckets), so `{ count }` is only ever a number axis and never needs the date formatter.
@@ -363,13 +375,10 @@ export function xGuide<X extends ChartX>(opts: {
363
375
  opacity: 1,
364
376
  thin: true,
365
377
  // A label centred on a tick near the plot's left edge hangs left of it, under the gutter's
366
- // lowest y label (outside labels) or off the plot (inside labels, left margin locked to
367
- // zero): start-anchor it. `+value` is a Date's timestamp, or the number itself.
368
- anchor: ({ index, value }: { index: number; value: ChartValue }) => {
369
- const pinnedFirst = inside && index === 0
378
+ // lowest y label: start-anchor it. `+value` is a Date's timestamp, or the number itself.
379
+ anchor: ({ value }: { value: ChartValue }) => {
370
380
  const share = (+value - leftEdgeX) / spanX
371
- const onLeftEdge = share >= 0 && share <= LEFT_EDGE_SHARE
372
- return pinnedFirst || onLeftEdge ? ('start' as const) : undefined
381
+ return share >= 0 && share <= LEFT_EDGE_SHARE ? ('start' as const) : undefined
373
382
  },
374
383
  },
375
384
  },
@@ -536,6 +545,7 @@ function leftDomain<T, X extends ChartX>(
536
545
  input: CartesianInput<T, X>,
537
546
  series: readonly ChartSeries<T>[],
538
547
  bounds: readonly number[],
548
+ tickCount: number,
539
549
  ): readonly [number, number] {
540
550
  const auto = input.y?.domain === undefined || input.y.domain === 'auto'
541
551
  if (auto && input.stack === 'normalized') return normalizedDomain(input.data, series)
@@ -544,6 +554,7 @@ function leftDomain<T, X extends ChartX>(
544
554
  input.data,
545
555
  auto && input.stack ? stackedSeries(series) : series,
546
556
  bounds,
557
+ tickCount,
547
558
  )
548
559
  }
549
560
 
@@ -551,8 +562,12 @@ function leftDomain<T, X extends ChartX>(
551
562
  function resolveAxes<T, X extends ChartX>(
552
563
  input: CartesianInput<T, X>,
553
564
  visible: readonly ChartSeries<T>[],
565
+ cls: ContainerClass,
554
566
  ): Axes<T> {
555
567
  const hasY2 = input.y2 !== undefined
568
+ // Ticks the axis draws at this class: a domain that ends on one never leaves the data above the top label.
569
+ const tickCount = (cfg: AxisConfig<T> | undefined): number =>
570
+ typeof cfg?.ticks === 'object' ? 0 : (cfg?.ticks ?? LADDER[cls].yTicks)
556
571
  const bounds = overlayBounds(input)
557
572
  const onRight = (s: ChartSeries<T>): boolean => hasY2 && s.axis === 'right'
558
573
  const left: YAxis = {
@@ -560,12 +575,19 @@ function resolveAxes<T, X extends ChartX>(
560
575
  input,
561
576
  visible.filter((s) => !onRight(s)),
562
577
  bounds.left,
578
+ tickCount(input.y),
563
579
  ),
564
580
  format: input.y?.format ?? defaultNumberFormat,
565
581
  }
566
582
  const right: YAxis | null = hasY2
567
583
  ? {
568
- domain: resolveYDomain(input.y2, input.data, visible.filter(onRight), bounds.right),
584
+ domain: resolveYDomain(
585
+ input.y2,
586
+ input.data,
587
+ visible.filter(onRight),
588
+ bounds.right,
589
+ tickCount(input.y2),
590
+ ),
569
591
  format: input.y2?.format ?? defaultNumberFormat,
570
592
  }
571
593
  : null
@@ -686,17 +708,40 @@ function underlayMarks<T, X extends ChartX>(
686
708
  return [...zones, ...xZones]
687
709
  }
688
710
 
689
- /** A ref label within this share of the plot height of the top flips below its line. */
690
- const REF_LABEL_TOP_SHARE = 0.12
691
711
  const REF_LABEL_DX = 6
692
712
  const REF_LABEL_DY_ABOVE = -5
693
713
  const REF_LABEL_DY_BELOW = 11
694
714
 
695
- /** The caption naming a reference line, at the plot end clear of its own axis' tick labels. */
696
- const refLabelMark = <T>(r: RefLine, i: number, axes: Axes<T>): ChartMarks[number] => {
697
- const [lo, hi] = axes.axisOf(r.axis).domain
698
- const nearTop = hi !== lo && (r.value - lo) / (hi - lo) > 1 - REF_LABEL_TOP_SHARE
699
- const atStart = r.axis === 'right' && axes.scaleId(r.axis) === 'y2'
715
+ /** What a reference line's caption needs to choose its spot: the plot in px and the data on its axis. */
716
+ type RefLabelContext<T, X extends ChartX> = {
717
+ plotWidth: number
718
+ plotHeight: number
719
+ /** One polyline per visible series on the line's axis. */
720
+ lines: (side: 'left' | 'right' | undefined) => readonly (readonly RefLabelPoint[])[]
721
+ axes: Axes<T>
722
+ model: XScaleModel<X>
723
+ }
724
+
725
+ /** The caption naming a reference line, at the spot {@link refLabelPosition} picks. */
726
+ const refLabelMark = <T, X extends ChartX>(
727
+ r: RefLine,
728
+ i: number,
729
+ ctx: RefLabelContext<T, X>,
730
+ ): ChartMarks[number] => {
731
+ const { axes } = ctx
732
+ const startFirst = r.axis === 'right' && axes.scaleId(r.axis) === 'y2'
733
+ const position = refLabelPosition({
734
+ pinned: r.labelPosition,
735
+ startFirst,
736
+ value: r.value,
737
+ domain: axes.axisOf(r.axis).domain,
738
+ plotWidth: ctx.plotWidth,
739
+ plotHeight: ctx.plotHeight,
740
+ label: r.label ?? '',
741
+ fontSize: VX.text.micro,
742
+ series: ctx.lines(r.axis),
743
+ })
744
+ const atStart = position.startsWith('start')
700
745
  return decorative(
701
746
  text([{ f: atStart ? 0 : 1 }], {
702
747
  id: `ref-${i}-label`,
@@ -709,15 +754,16 @@ const refLabelMark = <T>(r: RefLine, i: number, axes: Axes<T>): ChartMarks[numbe
709
754
  fontSize: VX.text.micro,
710
755
  anchor: atStart ? 'start' : 'end',
711
756
  dx: atStart ? REF_LABEL_DX : -REF_LABEL_DX,
712
- dy: nearTop ? REF_LABEL_DY_BELOW : REF_LABEL_DY_ABOVE,
757
+ dy: position.endsWith('above') ? REF_LABEL_DY_ABOVE : REF_LABEL_DY_BELOW,
713
758
  }),
714
759
  )
715
760
  }
716
761
 
717
- /** Reference lines, over the marks. */
762
+ /** Reference lines, over the marks. `label` reads the plot size, so only a chart with an unpinned caption pays for it. */
718
763
  const refLineMarks = <T, X extends ChartX>(
719
764
  input: CartesianInput<T, X>,
720
765
  axes: Axes<T>,
766
+ label: () => RefLabelContext<T, X>,
721
767
  ): ChartMarks =>
722
768
  (input.refLines ?? []).flatMap((r, i) =>
723
769
  // A line that names itself in the legend can be toggled off there.
@@ -732,7 +778,7 @@ const refLineMarks = <T, X extends ChartX>(
732
778
  yScale: axes.scaleId(r.axis),
733
779
  ...(r.dashed && { strokeDasharray: DASH }),
734
780
  }),
735
- ...(r.label ? [refLabelMark(r, i, axes)] : []),
781
+ ...(r.label ? [refLabelMark(r, i, label())] : []),
736
782
  ],
737
783
  )
738
784
 
@@ -742,10 +788,9 @@ function buildScales<T, X extends ChartX>(opts: {
742
788
  axes: Axes<T>
743
789
  formatX: (v: ChartValue) => string
744
790
  cls: ContainerClass
745
- height: number
746
791
  zoneScale: boolean
747
792
  }): StoredChartSpec['scales'] {
748
- const { input, model, axes, formatX, cls, height, zoneScale } = opts
793
+ const { input, model, axes, formatX, cls, zoneScale } = opts
749
794
  const { left, right } = axes
750
795
  return {
751
796
  x: {
@@ -755,7 +800,6 @@ function buildScales<T, X extends ChartX>(opts: {
755
800
  xTicks: input.xTicks,
756
801
  format: input.formatX ? formatX : undefined,
757
802
  cls,
758
- height,
759
803
  }),
760
804
  },
761
805
  y: {
@@ -764,7 +808,6 @@ function buildScales<T, X extends ChartX>(opts: {
764
808
  cfg: input.y,
765
809
  axis: left,
766
810
  cls,
767
- height,
768
811
  side: 'left',
769
812
  grid: input.y?.grid ?? true,
770
813
  }),
@@ -777,7 +820,6 @@ function buildScales<T, X extends ChartX>(opts: {
777
820
  cfg: input.y2,
778
821
  axis: right,
779
822
  cls,
780
- height,
781
823
  side: 'right',
782
824
  grid: input.y2?.grid ?? false,
783
825
  }),
@@ -793,14 +835,42 @@ function buildScales<T, X extends ChartX>(opts: {
793
835
  function tooltipHeader<T, X extends ChartX>(
794
836
  input: CartesianInput<T, X>,
795
837
  formatX: (v: ChartValue) => string,
838
+ dayOnly: boolean,
796
839
  v: ChartValue,
797
840
  d: T,
798
841
  ): string {
799
842
  if (input.tooltip && input.tooltip.formatHeader) return input.tooltip.formatHeader(v as X, d)
800
- if (v instanceof Date && !input.formatX) return utcHeaderDate(v)
843
+ if (v instanceof Date && !input.formatX) return utcHeaderDate(v, dayOnly)
801
844
  return formatX(v)
802
845
  }
803
846
 
847
+ /**
848
+ * A day-granular x: every step between its distinct instants is a whole day or more (23 h: a DST
849
+ * day), or its one instant is a UTC midnight. The tooltip header of such a series is its date, never
850
+ * a clock time (a bucket keyed by local midnight is `22:00` UTC in a UTC+2 zone).
851
+ */
852
+ export function dayGranular(values: readonly ChartX[]): boolean {
853
+ const times = values.flatMap((v) => (v instanceof Date ? [v.getTime()] : []))
854
+ if (times.length === 0 || times.length !== values.length) return false
855
+ const sorted = times.toSorted((a, b) => a - b)
856
+ if (sorted.length === 1) return (sorted[0] as number) % DAY_MS === 0
857
+ // 23 h, not 24: a local-midnight key is only 23 h after the previous one across a spring-forward DST.
858
+ return sorted.every((t, i) => i === 0 || t - (sorted[i - 1] as number) >= DAY_MS - HOUR_MS)
859
+ }
860
+
861
+ const HOUR_MS = 3_600_000
862
+
863
+ /** The word without its case or a plural `s`: `Sessions` and `session` are one unit. */
864
+ const stem = (w: string): string => w.toLowerCase().replace(/s$/, '')
865
+
866
+ /** A row's label repeats the unit its value already carries (`Sessions` / `27 sessions`). */
867
+ function unitIsName(label: string, value: string): string | null {
868
+ const words = value.trim().split(/\s+/)
869
+ const unit = words.at(-1)
870
+ if (words.length < 2 || unit === undefined || stem(unit) !== stem(label.trim())) return null
871
+ return words.slice(0, -1).join(' ')
872
+ }
873
+
804
874
  /** `plot.rows`: one row per datum for a visible series, `[]` for a hidden one, a throw for a typo. */
805
875
  function rowsOf<T, X extends ChartX>(
806
876
  input: CartesianInput<T, X>,
@@ -843,6 +913,22 @@ function cursorDotMarks<T, X extends ChartX>(
843
913
  })
844
914
  }
845
915
 
916
+ /**
917
+ * `tooltipBelow` (a `BandStrip`, a short bar of cells under a hero value and beside its neighbours):
918
+ * the tooltip opens below the strip, above only when there is no room, so it never covers the
919
+ * cell's own value, with a gap clear of the cell edge.
920
+ */
921
+ /** The hovered cell's centre x, on the strip's bottom edge: `bottom` opens just under the strip. */
922
+ const stripAnchor = (
923
+ points: readonly ChartPoint[],
924
+ { plot }: ChartTooltipAnchorContext,
925
+ ): { x: number; y: number } => {
926
+ const xs = points.map((p) => p.x)
927
+ return { x: (Math.min(...xs) + Math.max(...xs)) / 2, y: plot.y + plot.height }
928
+ }
929
+ const STRIP_TOOLTIP_PLACEMENT = ['bottom', 'top'] as const
930
+ const STRIP_TOOLTIP_OFFSET = 8
931
+
846
932
  function tooltipSpec<T, X extends ChartX>(opts: {
847
933
  input: CartesianInput<T, X>
848
934
  axes: Axes<T>
@@ -850,8 +936,10 @@ function tooltipSpec<T, X extends ChartX>(opts: {
850
936
  keys: ReadonlySet<string>
851
937
  visibleKeys: ReadonlySet<string>
852
938
  formatX: (v: ChartValue) => string
939
+ /** The x is day-granular: the header is a date, not a clock time. */
940
+ dayOnly: boolean
853
941
  }): NonNullable<CartesianDefinition['tooltip']> {
854
- const { input, axes, visible, keys, visibleKeys, formatX } = opts
942
+ const { input, axes, visible, keys, visibleKeys, formatX, dayOnly } = opts
855
943
  const hidden = input.series.filter((s) => !visibleKeys.has(s.key))
856
944
  const rowSeries = (input.reverseRows ? visible.toReversed() : visible).filter(
857
945
  (s) => s.tooltip !== false,
@@ -860,7 +948,8 @@ function tooltipSpec<T, X extends ChartX>(opts: {
860
948
  use: quietWhileFollowing,
861
949
  ...followerOptions(input.tooltip, input.cursorGroup, input.chartId),
862
950
  portal,
863
- anchor: 'group-center',
951
+ anchor: input.tooltipBelow ? stripAnchor : 'group-center',
952
+ ...(input.tooltipBelow && { placement: STRIP_TOOLTIP_PLACEMENT, offset: STRIP_TOOLTIP_OFFSET }),
864
953
  content: (points: readonly ChartPoint[]) => {
865
954
  const primary = points[0]
866
955
  if (!primary) return { rows: [] }
@@ -875,20 +964,17 @@ function tooltipSpec<T, X extends ChartX>(opts: {
875
964
  for (const s of rowSeries) {
876
965
  const v = s.getValue(d)
877
966
  if (v === null || !Number.isFinite(v)) continue
878
- rows.push(
879
- seriesRow(
880
- s,
881
- s.formatValue
882
- ? s.formatValue(v, d)
883
- : axes.axisOf(axes.onRight(s) ? 'right' : 'left').format(v),
884
- input.highlighted === s.key,
885
- ),
886
- )
967
+ const text = s.formatValue
968
+ ? s.formatValue(v, d)
969
+ : axes.axisOf(axes.onRight(s) ? 'right' : 'left').format(v)
970
+ // A lone series whose value already ends in its own name (`27 sessions`) prints the name once.
971
+ const bare = input.series.length === 1 ? unitIsName(s.label, text) : null
972
+ rows.push(seriesRow(s, bare ?? text, input.highlighted === s.key))
887
973
  }
888
974
  const extra: readonly ChartTooltipRow[] =
889
975
  (input.tooltip || undefined)?.rows?.(d, { visible, hidden }) ?? []
890
976
  return {
891
- title: tooltipHeader(input, formatX, x, d),
977
+ title: tooltipHeader(input, formatX, dayOnly, x, d),
892
978
  rows: [...rows, ...extra.map(engineRow)],
893
979
  }
894
980
  },
@@ -913,20 +999,42 @@ export function compileCartesian<T, X extends ChartX>(
913
999
  const visibleKeys = new Set(visible.map((s) => s.key))
914
1000
  const keys = new Set(input.series.map((s) => s.key))
915
1001
  const model = xScaleFor(input.data.map(input.x), input.band === true, input.xDomain)
916
- const axes = resolveAxes(input, visible)
917
- const under = underlayMarks(input, model, axes)
918
- const over = refLineMarks(input, axes)
919
- const dots = cursorDotMarks(input, visible, axes)
1002
+ // The y domain depends on the tick count, so on the class; everything else about the axes
1003
+ // (formats, sides) does not, and `shared` stands for it.
1004
+ const byClass = new Map<ContainerClass, Axes<T>>()
1005
+ const axesAt = (cls: ContainerClass): Axes<T> => {
1006
+ const found = byClass.get(cls)
1007
+ if (found) return found
1008
+ const made = resolveAxes(input, visible, cls)
1009
+ byClass.set(cls, made)
1010
+ return made
1011
+ }
1012
+ const shared = axesAt('regular')
1013
+ const dots = cursorDotMarks(input, visible, shared)
920
1014
  const rows = rowsOf(input, visibleKeys)
921
1015
  const formatX = (v: ChartValue): string =>
922
1016
  input.formatX ? input.formatX(v as X) : defaultFormatX(v)
923
1017
  const gradients = input.series.flatMap((s, i) =>
924
- s.area ? [seriesAreaGradient(s, i, input, axes)] : [],
1018
+ s.area ? [seriesAreaGradient(s, i, input, shared)] : [],
925
1019
  )
1020
+ const dayOnly = dayGranular(model.values)
1021
+ const names = (input.refLines ?? []).some((r) => r.label !== undefined && r.label !== '')
1022
+ // What an unpinned reference caption avoids: each visible series as (x share, y) points.
1023
+ const linesOn = (side: 'left' | 'right' | undefined): RefLabelPoint[][] =>
1024
+ visible
1025
+ .filter((s) => shared.onRight(s) === (side === 'right' && shared.right !== null))
1026
+ .map((s) =>
1027
+ rows(s.key).flatMap((r) => {
1028
+ const fx = model.fraction(r.x)
1029
+ return fx === null || r.y === null ? [] : [{ fx, y: r.y }]
1030
+ }),
1031
+ )
926
1032
 
927
1033
  const definition: CartesianDefinition = {
928
1034
  chart: ({ width, height }: ChartBuildContext): StoredChartSpec => {
929
1035
  const cls = resolveContainerClass(width)
1036
+ const axes = axesAt(cls)
1037
+ const access = plotAccess(definition, input.plot, MAIN_PANE)
930
1038
  const kindMarks = input.marks(
931
1039
  plotContext(
932
1040
  {
@@ -942,24 +1050,41 @@ export function compileCartesian<T, X extends ChartX>(
942
1050
  yDomain: axes.left.domain,
943
1051
  y2Domain: axes.right?.domain,
944
1052
  },
945
- plotAccess(definition, input.plot, MAIN_PANE),
1053
+ access,
946
1054
  ),
947
1055
  )
1056
+ const under = underlayMarks(input, model, axes)
1057
+ const over = refLineMarks(input, axes, () => {
1058
+ // Reading the plot size recompiles once on the measured area; the frame stands in before it.
1059
+ access.read()
1060
+ const size = access.size()
1061
+ return {
1062
+ plotWidth: size?.width ?? width,
1063
+ plotHeight: size?.height ?? height,
1064
+ lines: linesOn,
1065
+ axes,
1066
+ model,
1067
+ }
1068
+ })
948
1069
  return {
949
- marks: [...under, ...kindMarks, ...dots, ...over, crosshair({ x: CROSSHAIR, y: false })],
1070
+ marks: [
1071
+ ...under,
1072
+ ...kindMarks,
1073
+ ...dots,
1074
+ ...over,
1075
+ ...(input.crosshair === false ? [] : [crosshair({ x: CROSSHAIR, y: false })]),
1076
+ ],
950
1077
  scales: buildScales({
951
1078
  input,
952
1079
  model,
953
1080
  axes,
954
1081
  formatX,
955
1082
  cls,
956
- height,
957
- zoneScale: under.length > 0 || (input.refLines ?? []).some((r) => r.label),
1083
+ zoneScale: under.length > 0 || names,
958
1084
  }),
959
1085
  theme: CHART_THEME,
960
1086
  ...(gradients.length > 0 && { gradients }),
961
1087
  clip: true,
962
- ...(labelsInside(cls, height) && { margin: { left: 0, ...(axes.right && { right: 0 }) } }),
963
1088
  }
964
1089
  },
965
1090
  // Followers resolve the leader's group, so they draw its dots; `quietWhileFollowing` mutes the
@@ -977,7 +1102,7 @@ export function compileCartesian<T, X extends ChartX>(
977
1102
  tooltip:
978
1103
  input.tooltip === false
979
1104
  ? false
980
- : tooltipSpec({ input, axes, visible, keys, visibleKeys, formatX }),
1105
+ : tooltipSpec({ input, axes: shared, visible, keys, visibleKeys, formatX, dayOnly }),
981
1106
  }
982
1107
  return definition
983
1108
  }