basalt-ui 2.15.0 → 2.17.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 (152) hide show
  1. package/CHANGELOG.md +157 -105
  2. package/MIGRATING.md +160 -12
  3. package/agent/agents/basalt-design-reviewer.md +3 -3
  4. package/agent/rules/basalt-mantine.md +1 -1
  5. package/agent/skills/basalt-design/SKILL.md +2 -2
  6. package/configs/card-inset.test.ts +57 -0
  7. package/configs/oxlint-basalt.json +1 -1
  8. package/configs/oxlint-plugin.js +42 -18
  9. package/configs/oxlint-plugin.test.ts +37 -6
  10. package/dist/agent/chat/thread-message.js +1 -1
  11. package/dist/agent/chat/thread-outcome-card.js +1 -1
  12. package/dist/charts/ChartCard.js +1 -1
  13. package/dist/charts/Donut.d.ts.map +1 -1
  14. package/dist/charts/Donut.js +2 -2
  15. package/dist/charts/DualPanel.js +2 -2
  16. package/dist/charts/Heatmap.d.ts.map +1 -1
  17. package/dist/charts/Heatmap.js +2 -2
  18. package/dist/charts/MirroredBars.js +2 -2
  19. package/dist/charts/Sparkline.d.ts +4 -2
  20. package/dist/charts/Sparkline.d.ts.map +1 -1
  21. package/dist/charts/Sparkline.js +3 -3
  22. package/dist/charts/chart-card.module.css +2 -2
  23. package/dist/charts/compile.d.ts +8 -3
  24. package/dist/charts/compile.d.ts.map +1 -1
  25. package/dist/charts/compile.js +19 -9
  26. package/dist/charts/cursor.d.ts +14 -1
  27. package/dist/charts/cursor.d.ts.map +1 -1
  28. package/dist/charts/cursor.js +29 -3
  29. package/dist/charts/date-tick-format.d.ts +17 -0
  30. package/dist/charts/date-tick-format.d.ts.map +1 -0
  31. package/dist/charts/date-tick-format.js +81 -0
  32. package/dist/charts/panel.d.ts +2 -1
  33. package/dist/charts/panel.d.ts.map +1 -1
  34. package/dist/charts/panel.js +3 -2
  35. package/dist/charts/types.d.ts +5 -1
  36. package/dist/charts/types.d.ts.map +1 -1
  37. package/dist/cli/shot/board.js +1 -1
  38. package/dist/cli/shot/capture.d.ts +16 -0
  39. package/dist/cli/shot/capture.d.ts.map +1 -1
  40. package/dist/cli/shot/capture.js +24 -3
  41. package/dist/cli/shot/measure.d.ts +21 -2
  42. package/dist/cli/shot/measure.d.ts.map +1 -1
  43. package/dist/cli/shot/measure.js +20 -5
  44. package/dist/cli/shot/playwright.d.ts +4 -0
  45. package/dist/cli/shot/playwright.d.ts.map +1 -1
  46. package/dist/cli/shot/types.d.ts +3 -2
  47. package/dist/cli/shot/types.d.ts.map +1 -1
  48. package/dist/dashboard/delta-badge.d.ts +2 -2
  49. package/dist/dashboard/delta-badge.d.ts.map +1 -1
  50. package/dist/dashboard/delta-badge.js +12 -14
  51. package/dist/dashboard/query-state.d.ts +35 -0
  52. package/dist/dashboard/query-state.d.ts.map +1 -1
  53. package/dist/dashboard/query-state.js +12 -1
  54. package/dist/dashboard/settings-section.d.ts.map +1 -1
  55. package/dist/dashboard/settings-section.js +5 -2
  56. package/dist/dashboard/stat-card-parts.d.ts +40 -0
  57. package/dist/dashboard/stat-card-parts.d.ts.map +1 -0
  58. package/dist/dashboard/stat-card-parts.js +55 -0
  59. package/dist/dashboard/stat-card.d.ts +46 -34
  60. package/dist/dashboard/stat-card.d.ts.map +1 -1
  61. package/dist/dashboard/stat-card.js +157 -88
  62. package/dist/dashboard/stat-card.module.css +222 -9
  63. package/dist/dashboard/stat-card.module.css.d.ts +20 -0
  64. package/dist/dashboard/widget-header.d.ts.map +1 -1
  65. package/dist/dashboard/widget-header.js +73 -9
  66. package/dist/dashboard/widget-header.module.css +28 -20
  67. package/dist/guard/guard-hook.d.ts.map +1 -1
  68. package/dist/guard/index.d.ts +4 -2
  69. package/dist/guard/index.d.ts.map +1 -1
  70. package/dist/guard/index.js +18 -4
  71. package/dist/guard/vx-names.d.ts.map +1 -1
  72. package/dist/guard/vx-names.js +1 -0
  73. package/dist/shell/app-mobile-nav.module.css +2 -2
  74. package/dist/shell/app-sidebar-account.js +1 -1
  75. package/dist/shell/app-sidebar.js +2 -2
  76. package/dist/shell/app-sidebar.module.css +8 -8
  77. package/dist/shell/index.js +5 -1
  78. package/dist/shell/page-bar.js +1 -1
  79. package/dist/table/data-table.d.ts.map +1 -1
  80. package/dist/table/data-table.js +3 -0
  81. package/dist/theme/chrome-vars.d.ts +82 -0
  82. package/dist/theme/chrome-vars.d.ts.map +1 -0
  83. package/dist/theme/chrome-vars.js +36 -0
  84. package/dist/theme/controls.module.css +20 -1
  85. package/dist/theme/controls.module.css.d.ts +1 -0
  86. package/dist/theme/index.d.ts.map +1 -1
  87. package/dist/theme/index.js +61 -54
  88. package/dist/tokens/core.d.ts +10 -4
  89. package/dist/tokens/core.d.ts.map +1 -1
  90. package/dist/tokens/core.js +16 -10
  91. package/dist/tokens/ctl-vars.d.ts +15 -0
  92. package/dist/tokens/ctl-vars.d.ts.map +1 -0
  93. package/dist/tokens/ctl-vars.js +22 -0
  94. package/dist/tokens/derive.d.ts.map +1 -1
  95. package/dist/tokens/derive.js +2 -2
  96. package/dist/tokens/palette.d.ts +37 -29
  97. package/dist/tokens/palette.d.ts.map +1 -1
  98. package/dist/tokens/palette.js +32 -21
  99. package/dist/tokens/space-scale.d.ts +14 -0
  100. package/dist/tokens/space-scale.d.ts.map +1 -0
  101. package/dist/tokens/space-scale.js +10 -0
  102. package/llms.txt +6 -3
  103. package/package.json +1 -1
  104. package/src/agent/chat/thread-message.tsx +1 -1
  105. package/src/agent/chat/thread-outcome-card.tsx +2 -2
  106. package/src/charts/ChartCard.tsx +1 -1
  107. package/src/charts/Donut.tsx +2 -2
  108. package/src/charts/DualPanel.tsx +2 -2
  109. package/src/charts/Heatmap.tsx +2 -2
  110. package/src/charts/MirroredBars.tsx +2 -2
  111. package/src/charts/Sparkline.tsx +7 -5
  112. package/src/charts/chart-card.module.css +2 -2
  113. package/src/charts/compile.ts +31 -11
  114. package/src/charts/cursor.ts +48 -3
  115. package/src/charts/date-tick-format.ts +132 -0
  116. package/src/charts/panel.tsx +5 -3
  117. package/src/charts/types.ts +5 -1
  118. package/src/cli/shot/board.ts +1 -1
  119. package/src/cli/shot/capture.ts +35 -3
  120. package/src/cli/shot/measure.ts +33 -6
  121. package/src/cli/shot/playwright.ts +1 -1
  122. package/src/cli/shot/types.ts +3 -2
  123. package/src/dashboard/delta-badge.tsx +24 -18
  124. package/src/dashboard/query-state.tsx +38 -0
  125. package/src/dashboard/settings-section.tsx +5 -2
  126. package/src/dashboard/stat-card-parts.tsx +108 -0
  127. package/src/dashboard/stat-card.module.css +222 -9
  128. package/src/dashboard/stat-card.module.css.d.ts +20 -0
  129. package/src/dashboard/stat-card.tsx +291 -183
  130. package/src/dashboard/widget-header.module.css +28 -20
  131. package/src/dashboard/widget-header.tsx +103 -7
  132. package/src/guard/guard-hook.ts +3 -1
  133. package/src/guard/index.ts +27 -13
  134. package/src/guard/vx-names.ts +1 -0
  135. package/src/shell/app-mobile-nav.module.css +2 -2
  136. package/src/shell/app-sidebar-account.tsx +1 -1
  137. package/src/shell/app-sidebar.module.css +8 -8
  138. package/src/shell/app-sidebar.tsx +2 -2
  139. package/src/shell/index.tsx +10 -4
  140. package/src/shell/page-bar.tsx +1 -1
  141. package/src/table/data-table.tsx +10 -4
  142. package/src/theme/__snapshots__/plain-theme.test.ts.snap +185 -85
  143. package/src/theme/chrome-vars.ts +111 -0
  144. package/src/theme/controls.module.css +20 -1
  145. package/src/theme/controls.module.css.d.ts +1 -0
  146. package/src/theme/ctl-theme.tsx +1 -1
  147. package/src/theme/index.ts +82 -124
  148. package/src/tokens/core.ts +16 -8
  149. package/src/tokens/ctl-vars.ts +32 -0
  150. package/src/tokens/derive.ts +7 -2
  151. package/src/tokens/palette.ts +40 -29
  152. package/src/tokens/space-scale.ts +13 -0
@@ -14,7 +14,7 @@ import { useCallback, useMemo } from 'react'
14
14
  import type { ReactElement } from 'react'
15
15
  import { VX, alpha } from '../tokens'
16
16
  import { resolveContainerClass } from '../tokens/size-classes'
17
- import { defaultFormatX, defaultNumberFormat, engineRow, seriesRow, visibleSeries } from './compile'
17
+ import { defaultNumberFormat, engineRow, seriesRow, visibleSeries } from './compile'
18
18
  import { barMark, emphasis, lineMark, markersOf, thinFill } from './marks'
19
19
  import { PanelRung, chartHeightOf, paneX, paneY, rowsOf } from './panel'
20
20
  import type { PaneBuilder, PanelInput, PanelPlan } from './panel'
@@ -182,7 +182,7 @@ export function DualPanel<T, X extends Date | number = Date | number>(
182
182
  // A row's x as a fraction of the plot (the domain is padded half a step each side).
183
183
  const fillAt = (v: Date | number): number =>
184
184
  ((v instanceof Date ? v.getTime() : v) - (lo - pad)) / (hi - lo + 2 * pad)
185
- const format = (v: ChartValue): string => (formatX ? formatX(v as X) : defaultFormatX(v))
185
+ const format = formatX ? (v: ChartValue): string => formatX(v as X) : undefined
186
186
 
187
187
  const visible = visibleSeries(lines, hidden)
188
188
  const barOn = !hidden.has(BAR_KEY)
@@ -10,7 +10,6 @@
10
10
  import { colorGradientLegend } from '@tanstack/charts/legend'
11
11
  import { cell } from '@tanstack/charts/rect'
12
12
  import { scaleBand } from '@tanstack/charts/scales/band'
13
- import { tooltip as tooltipHost } from '@tanstack/charts/tooltip'
14
13
  import { portal } from '@tanstack/charts/tooltip/portal'
15
14
  import type { ChartBuildContext, ChartPoint, StoredChartSpec } from '@tanstack/charts/types/core'
16
15
  import { scaleQuantize } from 'd3-scale'
@@ -24,6 +23,7 @@ import type { CartesianDefinition } from './compile'
24
23
  import { resolveNamedState } from './band-fold'
25
24
  import type { NamedChartState } from './band-fold'
26
25
  import { ABSENT_OPACITY, RAMP_LEVELS, RAMP_OPACITIES } from './heatmap-fill'
26
+ import { engineTooltip } from './cursor'
27
27
  import { ChartEngine, idPrefixOf } from './host'
28
28
  import { ChartLegend } from './legend'
29
29
  import { useCoarsePointer } from '../common/use-media-query'
@@ -239,7 +239,7 @@ export function Heatmap<T, K extends string = string>(props: HeatmapProps<T, K>)
239
239
  cell(group, { id, x: 'col', y: 'row', inset: CELL_INSET, key: 'id', ...paint })
240
240
  const tooltipOptions = showTooltip
241
241
  ? {
242
- use: tooltipHost,
242
+ use: engineTooltip,
243
243
  portal,
244
244
  content: (points: readonly ChartPoint[]) => {
245
245
  const point = points[0]
@@ -21,7 +21,7 @@ import { useCallback, useMemo } from 'react'
21
21
  import type { ReactElement } from 'react'
22
22
  import { VX, alpha } from '../tokens'
23
23
  import { resolveContainerClass } from '../tokens/size-classes'
24
- import { defaultFormatX, defaultNumberFormat, seriesRow, visibleSeries } from './compile'
24
+ import { defaultNumberFormat, seriesRow, visibleSeries } from './compile'
25
25
  import { barMark, emphasis } from './marks'
26
26
  import { PanelRung, chartHeightOf, paneX, paneY, rowsOf } from './panel'
27
27
  import type { PaneBuilder, PanelInput, PanelPlan } from './panel'
@@ -191,7 +191,7 @@ export function MirroredBars<T, X extends ChartX = ChartX, K extends string = st
191
191
  : VX.neutral
192
192
  const upOn = visible.includes(upSeries)
193
193
  const downOn = visible.includes(downSeries)
194
- const format = (v: ChartValue): string => (formatX ? formatX(v as X) : defaultFormatX(v))
194
+ const format = formatX ? (v: ChartValue): string => formatX(v as X) : undefined
195
195
  const upMax = paneMax(up, upSeries, drawn, upOn)
196
196
  const downMax = paneMax(down, downSeries, drawn, downOn)
197
197
  const bandWidth = 2 * model.halfStep * BAND_FILL
@@ -34,9 +34,11 @@ export type SparklineProps = BasaltProps & {
34
34
  mark?: 'line' | 'bar' | undefined
35
35
  /** A `VX.*` ref or a series token. Default `VX.faint`. */
36
36
  color?: string | undefined
37
- /** Paints the last point in `emphasisColor` — the one reading a trend beside a KPI is for. */
37
+ /** Paints the last point in `emphasisColor` — the one reading a trend beside a KPI is for.
38
+ * Default `true`; pass `false` for a bare line. */
38
39
  emphasizeLast?: boolean | undefined
39
- /** Default `VX.accent`. */
40
+ /** Default `VX.line`, the line's own neutral, so a single metric stays neutral. Pass a status or
41
+ * trend colour to make the end dot carry a verdict. */
40
42
  emphasisColor?: string | undefined
41
43
  /** Pending / error / empty, the same contract as every other kind. The placeholder fills the
42
44
  * sparkline's own `width` × `height`, so a loading tile does not shift when the trend lands. */
@@ -45,7 +47,7 @@ export type SparklineProps = BasaltProps & {
45
47
 
46
48
  type Point = { i: number; v: number | null }
47
49
 
48
- const LINE_WIDTH = 1.6
50
+ const LINE_WIDTH = 1.5
49
51
  const DOT_R = 2.5
50
52
  const BAR_GAP = 0.15
51
53
  // Pixel policy of the self-pooling (`poolSparkline`): the densest a series may draw.
@@ -249,8 +251,8 @@ export function Sparkline(props: SparklineProps): ReactElement {
249
251
  width,
250
252
  mark = 'line',
251
253
  color = VX.faint,
252
- emphasizeLast = false,
253
- emphasisColor = VX.accent,
254
+ emphasizeLast = true,
255
+ emphasisColor = VX.line,
254
256
  state,
255
257
  className,
256
258
  style,
@@ -7,12 +7,12 @@
7
7
  */
8
8
 
9
9
  .header {
10
- padding: 4px var(--vx-space-card-inset-x, 0.8125rem) 4px;
10
+ padding: 4px var(--vx-space-card-inset-x, 1rem) 4px;
11
11
  }
12
12
 
13
13
  @container (min-width: 480px) {
14
14
  .header {
15
- padding-top: var(--vx-space-card-inset-y, 0.6875rem);
15
+ padding-top: var(--vx-space-card-inset-y, 0.75rem);
16
16
  }
17
17
  }
18
18
 
@@ -5,6 +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
9
  import { crosshair } from '@tanstack/charts/crosshair'
9
10
  import { decorative } from '@tanstack/charts/mark/decorative'
10
11
  import { rect } from '@tanstack/charts/rect'
@@ -122,18 +123,11 @@ export function defaultNumberFormat(v: number): string {
122
123
  return compact(v, { digits: Math.abs(v) >= 1000 ? 1 : 2 })
123
124
  }
124
125
 
125
- const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
126
126
  const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
127
- const pad2 = (n: number): string => String(n).padStart(2, '0')
128
-
129
- /** `DD.MM`, read in UTC like the time scale that placed it (a local read shifts a day west of UTC). */
130
- export function utcAxisDate(d: Date): string {
131
- return `${pad2(d.getUTCDate())}.${pad2(d.getUTCMonth() + 1)}`
132
- }
133
127
 
134
128
  /** `Mon Sep 1 2026`, in UTC; a non-midnight instant adds `HH:MM`. */
135
129
  export function utcHeaderDate(d: Date): string {
136
- const date = `${DAYS[d.getUTCDay()]} ${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()} ${d.getUTCFullYear()}`
130
+ const date = `${DAYS[d.getUTCDay()]} ${monthName(d)} ${d.getUTCDate()} ${d.getUTCFullYear()}`
137
131
  const ms = d.getTime() % DAY_MS
138
132
  return ms === 0 ? date : `${date} ${pad2(d.getUTCHours())}:${pad2(d.getUTCMinutes())}`
139
133
  }
@@ -319,18 +313,38 @@ export function strideTicks<V>(values: readonly V[], cls: ContainerClass): V[] {
319
313
  return strideEvery(values, LADDER[cls].xTicks)
320
314
  }
321
315
 
316
+ /**
317
+ * The one decision between a consumer's x format and the default: the consumer's wins; else dates
318
+ * read span-aware from the given tick values; else the plain default (numbers, strings, and a lone
319
+ * Date with no ticks to read a span from).
320
+ */
321
+ export function xTickFormat(
322
+ consumer: ((v: ChartValue) => string) | undefined,
323
+ tickValues: readonly ChartValue[],
324
+ ): (v: ChartValue) => string {
325
+ if (consumer) return consumer
326
+ if (tickValues.length === 0 || !tickValues.every((v): v is Date => v instanceof Date))
327
+ return defaultFormatX
328
+ const dateFormat = dateTickFormat(tickValues)
329
+ return (v) => (v instanceof Date ? dateFormat(v) : defaultFormatX(v))
330
+ }
331
+
322
332
  export function xGuide<X extends ChartX>(opts: {
323
333
  model: XScaleModel<X>
324
334
  xTicks: number | readonly X[] | undefined
325
- format: (v: ChartValue) => string
335
+ /** A consumer's formatter; absent, Date ticks get the span-aware {@link xTickFormat}. */
336
+ format?: ((v: ChartValue) => string) | undefined
326
337
  cls: ContainerClass
327
338
  /** The whole chart's height: decides whether the left margin is locked to zero. */
328
339
  height: number
329
340
  }): Omit<ChartPositionScaleOptions<ChartValue>, 'scale'> {
330
- const { model, xTicks, format, cls, height } = opts
341
+ const { model, xTicks, cls, height } = opts
331
342
  const ladder = LADDER[cls]
332
343
  const inside = labelsInside(cls, height)
333
344
  const ticks = xTickPolicy(model, xTicks ?? ladder.xTicks)
345
+ // A Date axis always resolves to `values` (the time scale has an extent; a band axis lists its
346
+ // buckets), so `{ count }` is only ever a number axis and never needs the date formatter.
347
+ const format = xTickFormat(opts.format, 'values' in ticks ? ticks.values : [])
334
348
  // A continuous scale's domain start and span; a band scale pads its first slot, so none applies.
335
349
  const [leftEdgeX, spanX] =
336
350
  !model.band && model.extent
@@ -703,7 +717,13 @@ function buildScales<T, X extends ChartX>(opts: {
703
717
  return {
704
718
  x: {
705
719
  scale: model.scale,
706
- ...xGuide({ model, xTicks: input.xTicks, format: formatX, cls, height }),
720
+ ...xGuide({
721
+ model,
722
+ xTicks: input.xTicks,
723
+ format: input.formatX ? formatX : undefined,
724
+ cls,
725
+ height,
726
+ }),
707
727
  },
708
728
  y: {
709
729
  scale: yScaleFor(input.y, left.domain),
@@ -294,10 +294,55 @@ export function followerOptions(
294
294
  return onFollow ? {} : ({ follower: { group, chartId } } satisfies TooltipFollowerOptions)
295
295
  }
296
296
 
297
+ /** The engine host's hover readout element. */
298
+ export const TOOLTIP_READOUT = '.ts-chart-tooltip'
299
+
300
+ /**
301
+ * The engine host stamps `role="status"` on its readout on every paint; a hover readout is a
302
+ * tooltip. `aria-live="polite"` stays, so a keyboard user still hears the reading. The host hands
303
+ * out no element: the readout is in the chart's container, except in the portal's fallback, which
304
+ * parks it on `<body>` — only then is the owner document searched (and every chart's readout
305
+ * stamped, which is right for each). Idempotent; a pinned custom body's `role="dialog"` is left
306
+ * alone.
307
+ */
308
+ function stampTooltipRole(container: Element): void {
309
+ const own = container.querySelectorAll(TOOLTIP_READOUT)
310
+ const readouts = own.length > 0 ? own : container.ownerDocument.querySelectorAll(TOOLTIP_READOUT)
311
+ for (const el of readouts)
312
+ if (el.getAttribute('role') === 'status') el.setAttribute('role', 'tooltip')
313
+ }
314
+
315
+ /**
316
+ * Decorates a tooltip host so every `paint` is followed by {@link stampTooltipRole}. The one
317
+ * stamping seam: `quietWhileFollowing` is built on it, and so is any chart that wires the engine host
318
+ * directly (Donut, Heatmap).
319
+ */
320
+ export function withTooltipRole(extension: ChartTooltipExtension): ChartTooltipExtension {
321
+ return {
322
+ ...extension,
323
+ create: (context) => {
324
+ const host = extension.create(context)
325
+ return {
326
+ ...host,
327
+ paint: (paint) => {
328
+ host.paint(paint)
329
+ stampTooltipRole(context.container)
330
+ },
331
+ }
332
+ },
333
+ }
334
+ }
335
+
336
+ /**
337
+ * The engine's tooltip host with its readout stamped, built once: a chart passes this as
338
+ * `tooltip.use`, so the extension keeps one identity across memo rebuilds.
339
+ */
340
+ export const engineTooltip = withTooltipRole(tooltip)
341
+
297
342
  /**
298
343
  * The engine's DOM tooltip host, silent while this chart FOLLOWS another's cursor. A follower
299
344
  * resolves the leader's focus group (so the engine draws the same dots at the shared x); the host
300
- * would then paint a tooltip and fill its `role="status"` live region. Whenever `isForeign` holds,
345
+ * would then paint a tooltip and fill its live region. Whenever `isForeign` holds,
301
346
  * this wrapper calls the host's `hide()` instead of `paint()`: a follower that has never led never
302
347
  * creates the element, and one that has led keeps it in the DOM, hidden. Otherwise (leader, no
303
348
  * `follower` option, or after the leader clears) it defers to the host.
@@ -309,9 +354,9 @@ export function followerOptions(
309
354
  * re-check this wrapper, the live region included, on every `@tanstack/charts` upgrade.
310
355
  */
311
356
  export const quietWhileFollowing: ChartTooltipExtension = {
312
- ...tooltip,
357
+ ...engineTooltip,
313
358
  create: (context) => {
314
- const host = tooltip.create(context)
359
+ const host = engineTooltip.create(context)
315
360
  let configured = false
316
361
  let follower: TooltipFollowerOptions['follower']
317
362
  return {
@@ -0,0 +1,132 @@
1
+ /**
2
+ * The default Date x tick labels: chosen from the TICK step (not the data step), read in UTC like
3
+ * the scale that placed them. A label may recur on one axis only behind a MARKER label (a day or a
4
+ * year) — `12:00, 18:00, 18.10, 06:00, 12:00` is fine, `17.10, 17.10, 18.10` is not. Each span has
5
+ * a ladder of levels, plainest first; the first level that holds the invariant wins. The last rung
6
+ * of every ladder names the whole date (or instant) of its tick, so the invariant always holds.
7
+ */
8
+
9
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
10
+ export const pad2 = (n: number): string => String(n).padStart(2, '0')
11
+
12
+ export const monthName = (d: Date): string => MONTHS[d.getUTCMonth()]!
13
+
14
+ const DAY_MS = 86_400_000
15
+ const HOUR_MS = 3_600_000
16
+ /**
17
+ * Month ticks are 28–31 days apart; 27 days leaves slack for a consumer's uneven ticks while
18
+ * keeping a 2-week step on the day ladder.
19
+ */
20
+ const MONTH_STEP_MS = 27 * DAY_MS
21
+
22
+ /** `DD.MM`, read in UTC like the time scale (a local read shifts a day west of UTC). */
23
+ export function utcAxisDate(d: Date): string {
24
+ return `${pad2(d.getUTCDate())}.${pad2(d.getUTCMonth() + 1)}`
25
+ }
26
+
27
+ const utcClock = (d: Date): string => `${pad2(d.getUTCHours())}:${pad2(d.getUTCMinutes())}`
28
+ const utcClockSeconds = (d: Date): string => `${utcClock(d)}:${pad2(d.getUTCSeconds())}`
29
+ const utcClockMillis = (d: Date): string =>
30
+ `${utcClockSeconds(d)}.${String(d.getUTCMilliseconds()).padStart(3, '0')}`
31
+ /** Two digits: a widened day label stays 8 characters and still reads as the `DD.MM` family. */
32
+ const utcAxisDateYear = (d: Date): string =>
33
+ `${utcAxisDate(d)}.${String(d.getUTCFullYear()).slice(2)}`
34
+
35
+ const isMidnight = (t: number): boolean => t % DAY_MS === 0
36
+ const isJanuary = (d: Date): boolean => d.getUTCMonth() === 0
37
+ const dayOf = (t: number): number => Math.floor(t / DAY_MS)
38
+ const startsNewDay = (t: number, prev: number | undefined): boolean =>
39
+ prev === undefined || dayOf(t) !== dayOf(prev)
40
+
41
+ type Label = { text: string; marker: boolean }
42
+ /** One label per tick time (ascending), as a whole: a label may depend on its predecessor. */
43
+ type Level = (times: readonly number[]) => Label[]
44
+
45
+ const marker = (text: string): Label => ({ text, marker: true })
46
+ const plain = (text: string): Label => ({ text, marker: false })
47
+ const each =
48
+ (label: (t: number, d: Date, prev: number | undefined) => Label): Level =>
49
+ (times) =>
50
+ times.map((t, i) => label(t, new Date(t), times[i - 1]))
51
+
52
+ /** Under a day: `HH:MM`, a midnight tick carries the day. */
53
+ const subDayLevels: Level[] = [
54
+ each((t, d) => (isMidnight(t) ? marker(utcAxisDate(d)) : plain(utcClock(d)))),
55
+ // No midnight in reach: the first tick of each day carries its date instead.
56
+ each((t, d, prev) =>
57
+ isMidnight(t)
58
+ ? marker(utcAxisDate(d))
59
+ : startsNewDay(t, prev)
60
+ ? marker(`${utcAxisDate(d)} ${utcClock(d)}`)
61
+ : plain(utcClock(d)),
62
+ ),
63
+ each((_, d) => marker(`${utcAxisDate(d)} ${utcClock(d)}`)),
64
+ // Sub-minute steps: the seconds, then (sub-second steps) the milliseconds. Every label names its
65
+ // whole instant to the millisecond, and `dateTickFormat` dedupes ticks to the millisecond, so
66
+ // the last rung cannot repeat.
67
+ each((_, d) => marker(`${utcAxisDate(d)} ${utcClockSeconds(d)}`)),
68
+ each((_, d) => marker(`${utcAxisDate(d)} ${utcClockMillis(d)}`)),
69
+ ]
70
+
71
+ /**
72
+ * A day or more: `DD.MM`. Ticks are at least a day apart here, so they fall on different UTC days
73
+ * and the last rung, which names the full date, cannot repeat.
74
+ */
75
+ const dayLevels: Level[] = [
76
+ each((_, d) => marker(utcAxisDate(d))),
77
+ each((_, d) => marker(utcAxisDateYear(d))),
78
+ ]
79
+
80
+ /** A month or more: the month, a January tick carries the year. */
81
+ const monthLevels: Level[] = [
82
+ each((_, d) => (isJanuary(d) ? marker(String(d.getUTCFullYear())) : plain(monthName(d)))),
83
+ each((_, d) => marker(`${monthName(d)} ${d.getUTCFullYear()}`)),
84
+ // Ticks a month apart in name only (Jan 1 and Jan 31): fall to the day ladder (ticks here are
85
+ // >= 27 days apart, so its full-date last rung is unique).
86
+ ...dayLevels,
87
+ ]
88
+
89
+ /** A marker label is unique on the axis; any other label repeats only after a marker. */
90
+ function holdsInvariant(labels: readonly Label[]): boolean {
91
+ const markers = new Set<string>()
92
+ const since = new Set<string>()
93
+ for (const { text, marker: isMarker } of labels) {
94
+ if (isMarker ? markers.has(text) : since.has(text)) return false
95
+ if (isMarker) {
96
+ markers.add(text)
97
+ since.clear()
98
+ } else since.add(text)
99
+ }
100
+ return true
101
+ }
102
+
103
+ /** The first level whose labels hold the invariant, else the last (see each ladder's last rung). */
104
+ function pickLabels(levels: readonly Level[], times: readonly number[]): Label[] {
105
+ let labels: Label[] = []
106
+ for (const level of levels) {
107
+ labels = level(times)
108
+ if (holdsInvariant(labels)) return labels
109
+ }
110
+ return labels
111
+ }
112
+
113
+ /**
114
+ * The tick step: the smallest gap between ticks. One tick has no gap, so it takes the span its own
115
+ * instant implies: a midnight is a day, anything else is read as a clock time.
116
+ */
117
+ function stepOf(times: readonly number[]): number {
118
+ if (times.length === 1) return isMidnight(times[0]!) ? DAY_MS : HOUR_MS
119
+ return times.reduce((min, t, i) => (i === 0 ? min : Math.min(min, t - times[i - 1]!)), Infinity)
120
+ }
121
+
122
+ /**
123
+ * A formatter for one tick set. A Date that is not among the ticks (a hover, a consumer reading
124
+ * the axis format) reads as plain `DD.MM`: its position in the set is undefined.
125
+ */
126
+ export function dateTickFormat(ticks: readonly Date[]): (d: Date) => string {
127
+ const times = [...new Set(ticks.map((t) => t.getTime()))].toSorted((a, b) => a - b)
128
+ const step = stepOf(times)
129
+ const levels = step < DAY_MS ? subDayLevels : step < MONTH_STEP_MS ? dayLevels : monthLevels
130
+ const text = new Map(pickLabels(levels, times).map((l, i) => [times[i]!, l.text]))
131
+ return (d) => text.get(d.getTime()) ?? utcAxisDate(d)
132
+ }
@@ -20,7 +20,7 @@ import { useCallback } from 'react'
20
20
  import type { ReactElement } from 'react'
21
21
  import { ChartShell } from './CartesianChart'
22
22
  import type { ChartShellProps, ShellContext } from './CartesianChart'
23
- import { defaultFormatX, engineRow, utcHeaderDate, visibleSeries, xGuide, yGuide } from './compile'
23
+ import { engineRow, utcHeaderDate, visibleSeries, xGuide, xTickFormat, yGuide } from './compile'
24
24
  import type { CartesianDefinition } from './compile'
25
25
  import { cursorBinding, followerOptions, quietWhileFollowing } from './cursor'
26
26
  import { plotAccess } from './plot-context'
@@ -110,7 +110,8 @@ type ChartScale = NonNullable<StoredChartSpec['scales'][string]>['scale']
110
110
  export const paneX = <X extends ChartX>(opts: {
111
111
  scale: ChartScale
112
112
  model: XScaleModel<X>
113
- format: (v: ChartValue) => string
113
+ /** A consumer's x format; absent, the span-aware default ({@link xTickFormat}). */
114
+ format?: ((v: ChartValue) => string) | undefined
114
115
  cls: ContainerClass
115
116
  /** The whole chart's height ({@link chartHeightOf}). */
116
117
  height: number
@@ -204,10 +205,11 @@ function panelDefinition<T, X extends ChartX>(
204
205
  const owned = new Set(series.map((s) => s.key))
205
206
  const visible = visibleSeries(series, hidden)
206
207
  const hiddenSeries = series.filter((s) => !visible.includes(s))
208
+ const headerFormat = xTickFormat(formatX ? (v: ChartValue) => formatX(v as X) : undefined, [])
207
209
  const header = (v: ChartValue, d: T): string => {
208
210
  if (tooltip?.formatHeader) return tooltip.formatHeader(v as X, d)
209
211
  if (v instanceof Date && !formatX) return utcHeaderDate(v)
210
- return formatX ? formatX(v as X) : defaultFormatX(v)
212
+ return headerFormat(v)
211
213
  }
212
214
  const definition: CartesianDefinition = {
213
215
  chart: () => composed,
@@ -303,7 +303,11 @@ export type CartesianChartProps<T, X extends ChartX = ChartX> = BasaltProps & {
303
303
  * extent (and warns in dev). A no-op on a string or band x (`Bars`, `MirroredBars`, `BandStrip`).
304
304
  */
305
305
  xDomain?: readonly [X, X] | undefined
306
- /** Tick label for an x value. Default: `DD.MM` for dates, compact numbers, strings verbatim. */
306
+ /**
307
+ * Tick label for an x value. Default: compact numbers, strings verbatim, and dates by tick step
308
+ * (`HH:MM` with the day on midnight, `DD.MM`, a month with the year on January; a label recurs
309
+ * only behind a day or year label).
310
+ */
307
311
  formatX?: ((x: X) => string) | undefined
308
312
  zones?: readonly ZoneSpec[] | undefined
309
313
  xZones?: readonly XZoneSpec<X>[] | undefined
@@ -59,7 +59,7 @@ const metricsTable = (rows: AnchorMetrics[]): string => {
59
59
  .filter((a) => a.nested.length > 0)
60
60
  .map(
61
61
  (a) =>
62
- `<li>${a.scheme}/${a.viewport}<ul>${a.nested.map((n) => `<li>${esc(n.path)} r${n.radius} p ${sides(n.padding)}</li>`).join('')}</ul></li>`,
62
+ `<li>${a.scheme}/${a.viewport}<ul>${a.nested.map((n) => `<li>${esc(n.path)} r${n.radius === 'full' ? ' full' : n.radius} p ${sides(n.padding)}</li>`).join('')}</ul></li>`,
63
63
  )
64
64
  return (
65
65
  `<table><tr><th></th><th>box</th><th>padding</th><th>gap r/c</th><th>radius</th><th>border</th>` +
@@ -225,6 +225,38 @@ export const tooltipSelector = (describedBy: string): string =>
225
225
  ? `[role="tooltip"][id=${JSON.stringify(describedBy)}]`
226
226
  : '[role="tooltip"]:not([data-shot-seen])'
227
227
 
228
+ /** `tooltipSelector`, narrowed to a rendered readout: a hidden 0×0 one of another chart never wins `.first()`. */
229
+ export const visibleTooltip = (describedBy: string): string =>
230
+ `${tooltipSelector(describedBy)}:visible`
231
+
232
+ /**
233
+ * Where a trigger is hovered: its centre, or the `data-shot-at="x,y"` fractions of its box when the
234
+ * centre paints no readout (a donut's hole).
235
+ */
236
+ export function hoverAtOf(el: Element | null): string {
237
+ return el?.getAttribute('data-shot-at') ?? ''
238
+ }
239
+
240
+ const HOVER_AT = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\s*$/
241
+
242
+ /**
243
+ * Exactly two non-negative numbers, each in [0, 1): 1 is the box's far edge, outside it. Anything else (a missing half, a third
244
+ * field, a value outside the box, a sign) is null, so the trigger is hovered at its centre.
245
+ */
246
+ export function parseHoverAt(raw: string): { x: number; y: number } | null {
247
+ const m = HOVER_AT.exec(raw)
248
+ if (!m) return null
249
+ const [x, y] = [Number(m[1]), Number(m[2])]
250
+ return x < 1 && y < 1 ? { x, y } : null
251
+ }
252
+
253
+ export async function hoverTrigger(target: PwLocator): Promise<void> {
254
+ const at = parseHoverAt(String(await target.evaluate(hoverAtOf)))
255
+ const box = at ? await target.boundingBox() : null
256
+ const position = at && box ? { x: at.x * box.width, y: at.y * box.height } : undefined
257
+ await target.hover({ timeout: HOVER_TIMEOUT_MS, ...(position && { position }) })
258
+ }
259
+
228
260
  /**
229
261
  * The box of the tooltip an action opened, or null when none shows up. Call `markVisibleTooltips`
230
262
  * before the action; `describedBy` is the trigger's own tooltip id, when it has one.
@@ -234,7 +266,7 @@ async function openTooltipBox(
234
266
  describedBy: string,
235
267
  timeout = TIP_PROBE_MS,
236
268
  ): Promise<Box | null> {
237
- const tip = c.page.locator(tooltipSelector(describedBy)).first()
269
+ const tip = c.page.locator(visibleTooltip(describedBy)).first()
238
270
  try {
239
271
  await tip.waitFor({ state: 'visible', timeout })
240
272
  } catch {
@@ -262,7 +294,7 @@ async function captureHover(c: Ctx, name: string): Promise<void> {
262
294
  const inner = c.page.locator(`${sel(name)} [data-shot-hover]`).first()
263
295
  const target = (await inner.count()) > 0 ? inner : anchor
264
296
  await c.page.evaluate(markVisibleTooltips, undefined)
265
- await target.hover({ timeout: HOVER_TIMEOUT_MS })
297
+ await hoverTrigger(target)
266
298
  const describedBy = idOf(await target.evaluate(describedByOf))
267
299
  const [box, tip] = [await anchor.boundingBox(), await openTooltipBox(c, describedBy)]
268
300
  if (!box || !tip) return void (await snap(anchor, path))
@@ -337,7 +369,7 @@ async function captureTooltip(c: Ctx, name: string): Promise<void> {
337
369
  const anchor = anchorOf(c, name)
338
370
  await reveal(anchor)
339
371
  await c.page.evaluate(markVisibleTooltips, undefined)
340
- await trigger.hover({ timeout: HOVER_TIMEOUT_MS })
372
+ await hoverTrigger(trigger)
341
373
  const describedBy = idOf(await trigger.evaluate(describedByOf))
342
374
  const t = await openTooltipBox(c, describedBy, TOOLTIP_TIMEOUT_MS)
343
375
  if (!t) throw new Error('no visible [role="tooltip"] after hover')
@@ -33,7 +33,29 @@ export type TextReading = {
33
33
  /** No opaque ancestor background was found: `bg` is white by assumption. */
34
34
  assumedWhite: boolean
35
35
  }
36
- export type Reading = Omit<Measurement, 'contrast'> & { texts: TextReading[] }
36
+ /** A computed `border-top-left-radius` as the page read it, with the box it rounds. */
37
+ export type RawRadius = { value: string; width: number; height: number }
38
+ export type Reading = Omit<Measurement, 'contrast' | 'radius' | 'nested'> & {
39
+ radius: RawRadius
40
+ nested: { path: string; radius: RawRadius; padding: Measurement['padding'] }[]
41
+ texts: TextReading[]
42
+ }
43
+
44
+ /**
45
+ * A radius in px, or `'full'` when it rounds the box completely: a percentage of 50 or more
46
+ * (`50%` is a circle/pill however the box is shaped), or a px radius of at least half the shorter
47
+ * side (`9999px`). A zero-size box has nothing to round: 0. A smaller percentage stays a number,
48
+ * resolved against the shorter side — the radius a reader sees on a wide, short box.
49
+ */
50
+ export function radiusReading({ value, width, height }: RawRadius): number | 'full' {
51
+ const first = value.trim()
52
+ const n = Number.parseFloat(first)
53
+ if (width <= 0 || height <= 0 || !Number.isFinite(n) || n <= 0) return 0
54
+ if (first.endsWith('%'))
55
+ return n >= 50 ? 'full' : Math.round((n / 100) * Math.min(width, height) * 100) / 100
56
+ if (n >= Math.min(width, height) / 2) return 'full'
57
+ return Math.round(n * 100) / 100
58
+ }
37
59
 
38
60
  const hex = (c: readonly number[]): string =>
39
61
  '#' +
@@ -46,7 +68,7 @@ const hex = (c: readonly number[]): string =>
46
68
  * Contrast per text reading: `min` over all, `failures` below the WCAG AA threshold. The threshold
47
69
  * is tested on the UNROUNDED ratio; only the stored value is rounded.
48
70
  */
49
- export function finishMeasurement({ texts, ...rest }: Reading): Measurement {
71
+ export function finishMeasurement({ texts, radius, nested, ...rest }: Reading): Measurement {
50
72
  const failures: ContrastFailure[] = []
51
73
  let min: number | null = null
52
74
  for (const t of texts) {
@@ -58,7 +80,12 @@ export function finishMeasurement({ texts, ...rest }: Reading): Measurement {
58
80
  }
59
81
  }
60
82
  const backdrop = texts.some((t) => t.assumedWhite) ? ({ backdrop: 'assumed-white' } as const) : {}
61
- return { ...rest, contrast: { min, failures, ...backdrop } }
83
+ return {
84
+ ...rest,
85
+ radius: radiusReading(radius),
86
+ nested: nested.map((n) => ({ ...n, radius: radiusReading(n.radius) })),
87
+ contrast: { min, failures, ...backdrop },
88
+ }
62
89
  }
63
90
 
64
91
  /* oxlint-disable unicorn/consistent-function-scoping -- the helpers below are serialised into the page with it: no outer scope */
@@ -143,7 +170,7 @@ export function measureAnchor(root: Element): Reading {
143
170
  const fontSizes = new Set<number>()
144
171
  const texts: Reading['texts'] = []
145
172
  const painted: [number, number][] = []
146
- const nested: Measurement['nested'] = []
173
+ const nested: Reading['nested'] = []
147
174
  const pathOf = (el: Element): string => {
148
175
  const parts: string[] = []
149
176
  for (let n: Element | null = el; n && n !== root; n = n.parentElement) {
@@ -164,7 +191,7 @@ export function measureAnchor(root: Element): Reading {
164
191
  if (el !== root && (hasBg || hasBorder) && nested.length < 60) {
165
192
  nested.push({
166
193
  path: pathOf(el),
167
- radius: px(s.borderTopLeftRadius),
194
+ radius: { value: s.borderTopLeftRadius, width: px(r.width), height: px(r.height) },
168
195
  padding: sides(s, 'padding'),
169
196
  })
170
197
  }
@@ -215,7 +242,7 @@ export function measureAnchor(root: Element): Reading {
215
242
  box: { width: px(rect.width), height: px(rect.height) },
216
243
  padding: sides(cs, 'padding'),
217
244
  gap,
218
- radius: px(cs.borderTopLeftRadius),
245
+ radius: { value: cs.borderTopLeftRadius, width: px(rect.width), height: px(rect.height) },
219
246
  borderWidth: widest,
220
247
  fontSizes: [...fontSizes].toSorted((a, b) => a - b),
221
248
  nested,
@@ -26,7 +26,7 @@ export type ShotOptions = {
26
26
  export type PwLocator = {
27
27
  first(): PwLocator
28
28
  count(): Promise<number>
29
- hover(options?: { timeout?: number }): Promise<void>
29
+ hover(options?: { timeout?: number; position?: { x: number; y: number } }): Promise<void>
30
30
  isVisible(): Promise<boolean>
31
31
  boundingBox(): Promise<Box | null>
32
32
  scrollIntoViewIfNeeded(): Promise<void>
@@ -32,10 +32,11 @@ export type Measurement = {
32
32
  box: { width: number; height: number }
33
33
  padding: Sides
34
34
  gap: { row: number; column: number }
35
- radius: number
35
+ /** px, or `'full'` for a radius that rounds the box completely (`50%`, `9999px`). */
36
+ radius: number | 'full'
36
37
  borderWidth: number
37
38
  fontSizes: number[]
38
- nested: { path: string; radius: number; padding: Sides }[]
39
+ nested: { path: string; radius: number | 'full'; padding: Sides }[]
39
40
  emptyRatio: number
40
41
  /** `min` is null when the anchor holds no text. */
41
42
  contrast: {