basalt-ui 2.26.0 → 2.27.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 (53) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/MIGRATING.md +91 -12
  3. package/dist/charts/Bars.d.ts.map +1 -1
  4. package/dist/charts/Bars.js +37 -1
  5. package/dist/charts/ChartCard.d.ts +8 -2
  6. package/dist/charts/ChartCard.d.ts.map +1 -1
  7. package/dist/charts/ChartCard.js +2 -0
  8. package/dist/charts/Sparkline.d.ts.map +1 -1
  9. package/dist/charts/Sparkline.js +76 -15
  10. package/dist/charts/chart-box.module.css +78 -1
  11. package/dist/charts/chart-box.module.css.d.ts +1 -0
  12. package/dist/charts/chart-legend.module.css +0 -14
  13. package/dist/charts/compile.d.ts +20 -0
  14. package/dist/charts/compile.d.ts.map +1 -1
  15. package/dist/charts/compile.js +85 -12
  16. package/dist/charts/legend.d.ts.map +1 -1
  17. package/dist/charts/legend.js +37 -87
  18. package/dist/charts/sparkline.module.css +4 -0
  19. package/dist/charts/state.d.ts +7 -0
  20. package/dist/charts/state.d.ts.map +1 -1
  21. package/dist/charts/state.js +14 -3
  22. package/dist/cli/shot/capture.d.ts +32 -3
  23. package/dist/cli/shot/capture.d.ts.map +1 -1
  24. package/dist/cli/shot/capture.js +17 -7
  25. package/dist/dashboard/meter-model.d.ts +17 -3
  26. package/dist/dashboard/meter-model.d.ts.map +1 -1
  27. package/dist/dashboard/meter-model.js +69 -19
  28. package/dist/dashboard/meter-parts.d.ts.map +1 -1
  29. package/dist/dashboard/meter-parts.js +28 -12
  30. package/dist/dashboard/meter.module.css +17 -1
  31. package/dist/dashboard/stat-strip.d.ts.map +1 -1
  32. package/dist/dashboard/stat-strip.js +90 -22
  33. package/dist/dashboard/stat-strip.module.css +13 -3
  34. package/dist/dashboard/stat-strip.module.css.d.ts +1 -0
  35. package/llms.txt +3 -2
  36. package/package.json +1 -1
  37. package/src/charts/Bars.tsx +50 -2
  38. package/src/charts/ChartCard.tsx +9 -1
  39. package/src/charts/Sparkline.tsx +113 -20
  40. package/src/charts/chart-box.module.css +78 -1
  41. package/src/charts/chart-box.module.css.d.ts +1 -0
  42. package/src/charts/chart-legend.module.css +0 -14
  43. package/src/charts/compile.ts +140 -18
  44. package/src/charts/legend.tsx +10 -74
  45. package/src/charts/sparkline.module.css +4 -0
  46. package/src/charts/state.tsx +30 -5
  47. package/src/cli/shot/capture.ts +25 -9
  48. package/src/dashboard/meter-model.ts +122 -31
  49. package/src/dashboard/meter-parts.tsx +53 -19
  50. package/src/dashboard/meter.module.css +17 -1
  51. package/src/dashboard/stat-strip.module.css +13 -3
  52. package/src/dashboard/stat-strip.module.css.d.ts +1 -0
  53. package/src/dashboard/stat-strip.tsx +114 -26
@@ -15,7 +15,10 @@ import { ruleX, ruleY } from '@tanstack/charts/rule'
15
15
  import { scaleLinear } from '@tanstack/charts/scales/linear'
16
16
  import { scaleUtc } from 'd3-scale'
17
17
  import { portal } from '@tanstack/charts/tooltip/portal'
18
- import type { ChartTooltipPortalExtension } from '@tanstack/charts/tooltip/portal'
18
+ import type {
19
+ ChartTooltipPortalExtension,
20
+ ChartTooltipPortalPositionContext,
21
+ } from '@tanstack/charts/tooltip/portal'
19
22
  import type {
20
23
  ChartBuildContext,
21
24
  ChartTooltipAnchorContext,
@@ -1024,6 +1027,22 @@ const stripAnchor = (
1024
1027
  }
1025
1028
  const STRIP_TOOLTIP_PLACEMENT = ['bottom', 'top'] as const
1026
1029
  const STRIP_TOOLTIP_OFFSET = 8
1030
+ /**
1031
+ * A slotted `Bars` (`tooltipBelow` and `bare`): a micro-visual whose tooltip is the one-line chip
1032
+ * (`chart-box.module.css`, `data-basalt-slot`) in the line the cell reserves above the plot. It
1033
+ * anchors to the plot's top edge, clear of the focus ring, and opens upward, never below the plot and never over the
1034
+ * bars; the card clamp's vertical flip does not apply to it.
1035
+ */
1036
+ const slotAnchor = (
1037
+ points: readonly ChartPoint[],
1038
+ { plot }: ChartTooltipAnchorContext,
1039
+ ): { x: number; y: number } => {
1040
+ const xs = points.map((p) => p.x)
1041
+ return { x: (Math.min(...xs) + Math.max(...xs)) / 2, y: plot.y }
1042
+ }
1043
+ const SLOT_TOOLTIP_PLACEMENT = ['top'] as const
1044
+ /** The host's focus ring sits outside the plot: `.basalt-chart:focus-visible` is a 2px outline at a 0.125rem offset. */
1045
+ const SLOT_RING_CLEARANCE = 2 + 2
1027
1046
 
1028
1047
  /** A tooltip's chrome (title row, padding) and each series row, px: the guess the bar anchor reserves. */
1029
1048
  const TIP_CHROME = 30
@@ -1062,38 +1081,135 @@ const barAnchor =
1062
1081
  const TIP_CARD = '[data-basalt-chart-card], [data-strip-cell], .mantine-Card-root'
1063
1082
  /** Air between a card-clamped tooltip and the card's edge, px. */
1064
1083
  const TIP_CARD_AIR = 4
1084
+ /** A card narrower than this keeps the engine's width and horizontal placement (a ~120px strip
1085
+ * cell would squeeze a tooltip to its 6rem label floor); the vertical rule applies to every card. */
1086
+ const TIP_CARD_ROOMY = 192
1065
1087
 
1066
1088
  /**
1067
- * The engine places a portalled tooltip against the viewport, so at the first or last point of a
1068
- * chart it opens past the card's edge, over the neighbouring card. Its placements (a hover, and its
1069
- * own resize / scroll repositions, which never pass through `position`) all write the element's
1070
- * inline `left`, so each write is followed by a slide back inside the card (the viewport placement
1071
- * stands when the card is narrower than the tooltip).
1089
+ * The engine places a portalled tooltip against the viewport, so it opens past the card's edge, over
1090
+ * the neighbouring card or the section heading above. Its placements (a hover, and its own resize /
1091
+ * scroll repositions, which never pass through `position`) all write the element's inline `left` and
1092
+ * `top`, so each write is followed by a settle inside the card (`settleInCard`).
1072
1093
  */
1073
- const cardPortal: ChartTooltipPortalExtension = {
1094
+ /** What a card clamp does: `card` a chart tooltip (both axes, the card's width), `slot` a slotted
1095
+ * `Bars` chip (flush above its plot), `strip` a `BandStrip`'s (sideways only, as before Wave 39). */
1096
+ type TipMode = 'card' | 'slot' | 'strip'
1097
+
1098
+ const cardPortal = (mode: TipMode): ChartTooltipPortalExtension => ({
1074
1099
  id: portal.id,
1075
1100
  create(context, options) {
1076
1101
  const inner = portal.create(context, options)
1077
1102
  const { element, container } = context
1078
- const watch = new MutationObserver(() => clampToCard(element, container))
1103
+ if (mode === 'slot') element.dataset['basaltSlot'] = ''
1104
+ let last: ChartTooltipPortalPositionContext | undefined
1105
+ const watch = new MutationObserver(() => {
1106
+ if (last) settleInCard(element, container, last, mode)
1107
+ })
1079
1108
  watch.observe(element, { attributes: true, attributeFilter: ['style'] })
1080
1109
  return {
1081
1110
  ...inner,
1111
+ position(next) {
1112
+ last = next
1113
+ return inner.position(next)
1114
+ },
1082
1115
  destroy() {
1083
1116
  watch.disconnect()
1084
1117
  inner.destroy()
1085
1118
  },
1086
1119
  }
1087
1120
  },
1088
- }
1121
+ })
1089
1122
 
1090
- function clampToCard(tip: HTMLElement, within: Element): void {
1123
+ /**
1124
+ * Keeps a tooltip inside its card on both axes. A card with room lets the tooltip grow up to its
1125
+ * width before a label wraps, and re-centres it on the anchor at that width. A tooltip that would
1126
+ * cross the card's top or bottom flips to the other side of its anchor when that side fits; neither
1127
+ * fitting, it slides in; taller than the card, it aligns to the card's top (the only overflow).
1128
+ * A `slot` tooltip (a slotted `Bars`, one line) keeps its place above the plot, centred on the
1129
+ * anchor, capped at the card's width and held inside the card sideways and at its top. A hidden or unmeasured tooltip is left alone, and an unchanged position
1130
+ * is not written back (a write re-runs this).
1131
+ */
1132
+ export function settleInCard(
1133
+ tip: HTMLElement,
1134
+ within: Element,
1135
+ ctx: ChartTooltipPortalPositionContext,
1136
+ mode: TipMode = 'card',
1137
+ ): void {
1138
+ const slot = mode === 'slot'
1139
+ if (tip.hidden || tip.offsetHeight === 0) return
1091
1140
  const card = within.closest(TIP_CARD)?.getBoundingClientRect()
1092
- const left = Number.parseFloat(tip.style.left)
1093
- const width = tip.offsetWidth
1094
- if (!card || Number.isNaN(left) || width + 2 * TIP_CARD_AIR > card.width) return
1095
- const next = Math.min(Math.max(left, card.left + TIP_CARD_AIR), card.right - width - TIP_CARD_AIR)
1096
- if (Math.abs(next - left) > 0.5) tip.style.left = `${next}px`
1141
+ const surface = ctx.surface.element.getBoundingClientRect()
1142
+ const { width: sceneW, height: sceneH } = ctx.scene
1143
+ let left = Number.parseFloat(tip.style.left)
1144
+ let top = Number.parseFloat(tip.style.top)
1145
+ if (!card || Number.isNaN(left) || Number.isNaN(top) || !surface.width || !sceneW || !sceneH)
1146
+ return
1147
+ const w0 = tip.offsetWidth
1148
+ const toClient = (p: { x: number; y: number }): { x: number; y: number } => ({
1149
+ x: surface.left + (p.x / sceneW) * surface.width,
1150
+ y: surface.top + (p.y / sceneH) * surface.height,
1151
+ })
1152
+ if (mode === 'strip') {
1153
+ // A `BandStrip`: sideways only, as before; the engine's width and vertical placement stand.
1154
+ if (w0 + 2 * TIP_CARD_AIR <= card.width)
1155
+ left = Math.min(Math.max(left, card.left + TIP_CARD_AIR), card.right - w0 - TIP_CARD_AIR)
1156
+ if (Math.abs(left - Number.parseFloat(tip.style.left)) > 0.5) tip.style.left = `${left}px`
1157
+ return
1158
+ }
1159
+ const roomy = card.width >= TIP_CARD_ROOMY
1160
+ // A wider tooltip is centred again on its anchor at that width, and held inside the card.
1161
+ const grown = roomy || slot
1162
+ if (!grown) {
1163
+ // A card that shrank under a wider tooltip: the engine's own width and cap again.
1164
+ if (tip.dataset['basaltMax'] !== undefined) {
1165
+ tip.style.maxWidth = tip.dataset['basaltMax']
1166
+ tip.style.removeProperty('width')
1167
+ delete tip.dataset['basaltMax']
1168
+ }
1169
+ } else {
1170
+ tip.dataset['basaltMax'] ??= tip.style.maxWidth
1171
+ // Grows to its content, capped at the card's width; the engine's shrink-to-fit would narrow it
1172
+ // to the room right of its `left`.
1173
+ const cap = `${card.width - 2 * TIP_CARD_AIR}px`
1174
+ if (tip.style.maxWidth !== cap) tip.style.maxWidth = cap
1175
+ if (tip.style.width !== 'max-content') tip.style.width = 'max-content'
1176
+ }
1177
+ const [w, h] = [tip.offsetWidth, tip.offsetHeight]
1178
+ const anchor = toClient(ctx.anchor)
1179
+ const gap = Math.max(0, Number.isFinite(ctx.offset) ? (ctx.offset ?? 10) : 10)
1180
+ const maxTop = card.bottom - TIP_CARD_AIR - h
1181
+ // The card's header (title and facts) is off-limits while the plot area below it can hold the tooltip.
1182
+ const headerBottom = slot
1183
+ ? undefined
1184
+ : within
1185
+ .closest(TIP_CARD)
1186
+ ?.querySelector('[data-basalt-facts]')
1187
+ ?.parentElement?.getBoundingClientRect().bottom
1188
+ const belowHeader = headerBottom === undefined ? undefined : headerBottom + TIP_CARD_AIR
1189
+ const minTop =
1190
+ belowHeader !== undefined && belowHeader <= maxTop ? belowHeader : card.top + TIP_CARD_AIR
1191
+ const side = tip.dataset['placement']
1192
+ if (slot) {
1193
+ // Above the plot, in the reserved line, clear of the focus ring: no flip, never pushed down over the bars.
1194
+ top = Math.max(anchor.y - gap - SLOT_RING_CLEARANCE - h, card.top)
1195
+ left = anchor.x - w / 2
1196
+ } else if (side === 'top' || side === 'bottom') {
1197
+ const above = anchor.y - gap - h
1198
+ const below = anchor.y + gap
1199
+ const order = side === 'top' ? [above, below] : [below, above]
1200
+ const fits = order.findIndex((t) => t >= minTop && t <= maxTop)
1201
+ top = order[Math.max(fits, 0)] ?? top
1202
+ if (fits > 0) tip.dataset['placement'] = side === 'top' ? 'bottom' : 'top'
1203
+ if (roomy) left = anchor.x - w / 2
1204
+ }
1205
+ if (!slot) top = maxTop < minTop ? minTop : Math.min(Math.max(top, minTop), maxTop)
1206
+ if (grown || w + 2 * TIP_CARD_AIR <= card.width)
1207
+ left = Math.min(
1208
+ Math.max(left, card.left + TIP_CARD_AIR),
1209
+ Math.max(card.right - w - TIP_CARD_AIR, card.left + TIP_CARD_AIR),
1210
+ )
1211
+ if (Math.abs(left - Number.parseFloat(tip.style.left)) > 0.5) tip.style.left = `${left}px`
1212
+ if (Math.abs(top - Number.parseFloat(tip.style.top)) > 0.5) tip.style.top = `${top}px`
1097
1213
  }
1098
1214
 
1099
1215
  function tooltipSpec<T, X extends ChartX>(opts: {
@@ -1108,19 +1224,25 @@ function tooltipSpec<T, X extends ChartX>(opts: {
1108
1224
  }): NonNullable<CartesianDefinition['tooltip']> {
1109
1225
  const { input, axes, visible, keys, visibleKeys, formatX, dayOnly } = opts
1110
1226
  const hidden = input.series.filter((s) => !visibleKeys.has(s.key))
1227
+ const slot = input.tooltipBelow === true && input.bare === true
1111
1228
  const rowSeries = (input.reverseRows ? visible.toReversed() : visible).filter(
1112
1229
  (s) => s.tooltip !== false,
1113
1230
  )
1114
1231
  return {
1115
1232
  use: quietWhileFollowing,
1116
1233
  ...followerOptions(input.tooltip, input.cursorGroup, input.chartId),
1117
- portal: cardPortal,
1234
+ portal: cardPortal(slot ? 'slot' : input.tooltipBelow === true ? 'strip' : 'card'),
1118
1235
  anchor: input.tooltipBelow
1119
- ? stripAnchor
1236
+ ? slot
1237
+ ? slotAnchor
1238
+ : stripAnchor
1120
1239
  : visible.some((s) => s.mark === 'bar')
1121
1240
  ? barAnchor(rowSeries.length)
1122
1241
  : 'group-center',
1123
- ...(input.tooltipBelow && { placement: STRIP_TOOLTIP_PLACEMENT, offset: STRIP_TOOLTIP_OFFSET }),
1242
+ ...(input.tooltipBelow &&
1243
+ (slot
1244
+ ? { placement: SLOT_TOOLTIP_PLACEMENT, offset: 0 }
1245
+ : { placement: STRIP_TOOLTIP_PLACEMENT, offset: STRIP_TOOLTIP_OFFSET })),
1124
1246
  content: (points: readonly ChartPoint[]) => {
1125
1247
  const primary = points[0]
1126
1248
  if (!primary) return { rows: [] }
@@ -38,7 +38,7 @@ export function legendEntries<T>(
38
38
  groups: boolean,
39
39
  ): ChartSeries<T>[][] {
40
40
  const entries = series.filter((s) => s.legend !== false)
41
- // Series lead, zones and reference lines follow: the compact fold takes the references from the end.
41
+ // Series lead, zones and reference lines follow: the compact row wraps between entries and names them all.
42
42
  if (!groups) return entries.length ? [entries.toSorted(byReferenceLast)] : []
43
43
  return ROLE_ORDER.map((role) => entries.filter((s) => (s.role ?? 'series') === role)).filter(
44
44
  (g) => g.length > 0,
@@ -200,99 +200,36 @@ export type ChartLegendProps<T> = {
200
200
  hideAtWide?: boolean
201
201
  }
202
202
 
203
- const VISUALLY_HIDDEN = {
204
- position: 'absolute',
205
- width: '1px',
206
- height: '1px',
207
- overflow: 'hidden',
208
- clipPath: 'inset(50%)',
209
- whiteSpace: 'nowrap',
210
- } as const
211
-
212
- /**
213
- * The number of lines the visible entries (and the chip) sit on. Bucketed by vertical centre, so the
214
- * chip's own height (shorter than an entry's) does not read as another line.
215
- */
216
- function lineCount(row: HTMLElement, more: HTMLElement): number {
217
- const shown = [...row.querySelectorAll<HTMLElement>('[data-legend-key]')].filter(
218
- (it) => !it.hasAttribute('data-legend-folded'),
219
- )
220
- if (!more.hidden) shown.push(more)
221
- const centres = shown
222
- .map((it) => {
223
- const r = it.getBoundingClientRect()
224
- return r.top + r.height / 2
225
- })
226
- .toSorted((x, y) => x - y)
227
- // A new line starts where the centre jumps by more than half an entry's height.
228
- return centres.filter((c, i) => i === 0 || c - (centres[i - 1] ?? c) > 6).length
229
- }
230
-
231
203
  /**
232
- * The compact legend names every series at every width. When the row wraps below 480px, the
233
- * zone / reference entries fold into a `+N` chip (named for assistive tech by the folded labels), the
234
- * last first, only while the row has more lines than the series alone would; a series never folds.
235
- * The entries are in display order: series, then zones / references.
236
- * Measured on the node, never in React state, so a hover or a resize does not re-render.
204
+ * The compact legend names every entry at every width: nothing folds, the row wraps between entries
205
+ * (series, then overlays, then references). A label that ellipsizes carries its full name in
206
+ * `title`; one that fits carries none. Measured on the node, never in React state.
237
207
  */
238
- function foldLegend(row: HTMLElement): void {
239
- const items = [...row.querySelectorAll<HTMLElement>('[data-legend-key]')]
240
- const more = row.querySelector<HTMLElement>('[data-legend-more]')
241
- for (const it of items) it.removeAttribute('data-legend-folded')
242
- more?.setAttribute('hidden', '')
243
- // A label that ellipsizes carries its full name in `title`; one that fits carries none.
208
+ function titleClipped(row: HTMLElement): void {
244
209
  for (const label of row.querySelectorAll<HTMLElement>('[data-legend-label]')) {
245
210
  if (label.scrollWidth > label.clientWidth + 0.5) label.title = label.textContent ?? ''
246
211
  else label.removeAttribute('title')
247
212
  }
248
- // `--bc-fold` is the stylesheet's compact flag (chart-legend.module.css); wide keeps every entry.
249
- if (more === null || getComputedStyle(row).getPropertyValue('--bc-fold').trim() !== '1') return
250
- const references = items.filter((it) => it.dataset['legendRole'] === 'reference')
251
- // The series-only line count is the floor: folding a reference that frees no line only hides a name.
252
- for (const r of references) r.setAttribute('data-legend-folded', '')
253
- const floor = lineCount(row, more)
254
- for (const r of references) r.removeAttribute('data-legend-folded')
255
- const folded: HTMLElement[] = []
256
- while (folded.length < references.length && lineCount(row, more) > floor) {
257
- const last = references[references.length - 1 - folded.length]
258
- if (last === undefined) break
259
- last.setAttribute('data-legend-folded', '')
260
- folded.push(last)
261
- more.removeAttribute('hidden')
262
- const names = folded.map((f) => f.textContent).join(', ')
263
- more.textContent = `+${folded.length}`
264
- more.title = names
265
- // The folded labels, visually hidden: assistive tech reads `+2: Caution, Danger`.
266
- const hiddenNames = document.createElement('span')
267
- hiddenNames.textContent = `: ${names}`
268
- Object.assign(hiddenNames.style, VISUALLY_HIDDEN)
269
- more.append(hiddenNames)
270
- }
271
- // Folding freed no line (the chip's own width cost it): show every name instead.
272
- if (folded.length > 0 && lineCount(row, more) > floor) {
273
- for (const f of folded) f.removeAttribute('data-legend-folded')
274
- more.setAttribute('hidden', '')
275
- }
276
213
  }
277
214
 
278
215
  export function ChartLegend<T>(props: ChartLegendProps<T>): ReactElement | null {
279
216
  const rowRef = useRef<HTMLFieldSetElement>(null)
280
217
  const auto = props.mode === 'auto'
281
- // Re-fold when the entries change; a resize re-folds through the observer.
218
+ // Re-title when the entries change; a resize re-titles through the observer.
282
219
  const signature = props.series.map((s) => s.key).join('|')
283
- // `signature` is intentionally an extra dep: the fold must re-run when the entries change.
220
+ // `signature` is intentionally an extra dep: the titles must re-run when the entries change.
284
221
  useLayoutEffect(() => {
285
- if (auto && rowRef.current !== null) foldLegend(rowRef.current)
222
+ if (auto && rowRef.current !== null) titleClipped(rowRef.current)
286
223
  }, [auto, signature])
287
224
  // Same: `signature` re-subscribes the observer to the re-rendered row.
288
225
  useEffect(() => {
289
226
  const row = rowRef.current
290
227
  if (!auto || row === null || typeof ResizeObserver === 'undefined') return
291
- const observer = new ResizeObserver(() => foldLegend(row))
228
+ const observer = new ResizeObserver(() => titleClipped(row))
292
229
  observer.observe(row)
293
230
  // A web font landing changes the entry widths without resizing the row.
294
231
  let live = true
295
- void document.fonts?.ready?.then(() => live && foldLegend(row))
232
+ void document.fonts?.ready?.then(() => live && titleClipped(row))
296
233
  return () => {
297
234
  live = false
298
235
  observer.disconnect()
@@ -359,7 +296,6 @@ export function ChartLegend<T>(props: ChartLegendProps<T>): ReactElement | null
359
296
  )
360
297
  }),
361
298
  ])}
362
- {auto && <span data-legend-more="" hidden style={noteStyle} />}
363
299
  </fieldset>
364
300
  )
365
301
  }
@@ -88,6 +88,10 @@
88
88
  top: 0;
89
89
  }
90
90
 
91
+ .readout[data-short] .label {
92
+ display: none;
93
+ }
94
+
91
95
  .readout[data-stacked] .label {
92
96
  display: block;
93
97
  }
@@ -41,12 +41,35 @@ const pendingStyle: CSSProperties = {
41
41
  /** Bar ghost heights (% of the plot) of a pending plot: a mild rise, not data. */
42
42
  const GHOST_BARS = [38, 52, 44, 66, 58, 74, 62, 48] as const
43
43
 
44
+ /**
45
+ * The shape a pending plot draws: `'bars'` (default), `'line'` for a line or area chart, or a bar
46
+ * count when the loaded chart's data length is known (a 6-month chart loads 6 bars).
47
+ */
48
+ export type PlotGhostShape = 'bars' | 'line' | number
49
+
50
+ /** A mild rise across the width, in a 100 x 40 box stretched to the plot. */
51
+ const GHOST_LINE = '0,30 12,26 25,28 38,18 50,22 62,12 75,16 88,8 100,12'
52
+
44
53
  /** The loaded shape of a plot, drawn in neutral tone (`chart-box.module.css` `.ghost`). */
45
- function PlotGhost(): ReactElement {
54
+ function PlotGhost({ shape = 'bars' }: { shape?: PlotGhostShape }): ReactElement {
55
+ if (shape === 'line')
56
+ return (
57
+ <div aria-hidden="true" data-basalt-plot-ghost="line" className={boxClasses.ghost}>
58
+ <svg viewBox="0 0 100 40" preserveAspectRatio="none" className={boxClasses.ghostLine}>
59
+ <polyline points={GHOST_LINE} vectorEffect="non-scaling-stroke" />
60
+ </svg>
61
+ </div>
62
+ )
63
+ const count =
64
+ typeof shape === 'number' ? Math.max(1, Math.min(Math.floor(shape), 60)) : GHOST_BARS.length
46
65
  return (
47
- <div aria-hidden="true" data-basalt-plot-ghost="" className={boxClasses.ghost}>
48
- {GHOST_BARS.map((h, i) => (
49
- <span key={i} className={boxClasses.ghostBar} style={{ height: `${h}%` }} />
66
+ <div aria-hidden="true" data-basalt-plot-ghost="bars" className={boxClasses.ghost}>
67
+ {Array.from({ length: count }, (_, i) => (
68
+ <span
69
+ key={i}
70
+ className={boxClasses.ghostBar}
71
+ style={{ height: `${GHOST_BARS[i % GHOST_BARS.length]}%` }}
72
+ />
50
73
  ))}
51
74
  </div>
52
75
  )
@@ -105,6 +128,8 @@ export function ChartPlaceholder(props: {
105
128
  compact?: boolean
106
129
  /** Error only: what failed to load, "Could not load {noun}". Default: no noun. */
107
130
  noun?: string
131
+ /** Pending only: the ghost's shape. Default `'bars'`. */
132
+ ghost?: PlotGhostShape
108
133
  }): ReactElement | null {
109
134
  const kind = resolveChartState(props.state)
110
135
  if (kind === null) return null
@@ -127,7 +152,7 @@ export function ChartPlaceholder(props: {
127
152
  if (kind === 'pending')
128
153
  return fit(
129
154
  <output aria-label="Loading chart" aria-busy="true" className={stateClass} style={style}>
130
- {!props.compact && <PlotGhost />}
155
+ {!props.compact && <PlotGhost {...(props.ghost !== undefined && { shape: props.ghost })} />}
131
156
  </output>,
132
157
  )
133
158
  const label =
@@ -140,20 +140,22 @@ export function withParam(route: string, state: ShotState): string {
140
140
  return `${path}${path.includes('?') ? '&' : '?'}shot-state=${state}${fragment}`
141
141
  }
142
142
 
143
- /** The rect union of `boxes`, grown by `margin` and clamped to the viewport (`tall`: its current height). */
143
+ /** The rect union of `boxes`, grown by `margin` and clamped to the viewport (`tall`: its current height); null when nothing of it is inside. */
144
144
  export function unionClip(
145
145
  boxes: readonly Box[],
146
146
  margin: number,
147
147
  viewport: Viewport,
148
148
  tall?: number,
149
- ): Box {
149
+ ): Box | null {
150
150
  const { width, height: base } = VIEWPORT_SPECS[viewport]
151
151
  const height = tall ?? base
152
152
  const left = Math.max(0, Math.min(...boxes.map((b) => b.x)) - margin)
153
153
  const top = Math.max(0, Math.min(...boxes.map((b) => b.y)) - margin)
154
154
  const right = Math.min(width, Math.max(...boxes.map((b) => b.x + b.width)) + margin)
155
155
  const bottom = Math.min(height, Math.max(...boxes.map((b) => b.y + b.height)) + margin)
156
- return { x: left, y: top, width: Math.max(1, right - left), height: Math.max(1, bottom - top) }
156
+ return right <= left || bottom <= top
157
+ ? null
158
+ : { x: left, y: top, width: right - left, height: bottom - top }
157
159
  }
158
160
 
159
161
  /** One screenshot with the options every shot shares. */
@@ -170,6 +172,19 @@ const snap = (
170
172
  ...extra,
171
173
  })
172
174
 
175
+ /** A clip of `targets` re-measured against the live page height (`c.height` goes stale after a reflow); an empty clip is retried once after a frame, then fails. */
176
+ export async function snapClip(c: Ctx, path: string, targets: readonly PwLocator[]): Promise<void> {
177
+ for (let retry = true; ; retry = false) {
178
+ const live = await c.page.evaluate<number>('window.innerHeight')
179
+ const boxes = (await Promise.all(targets.map((t) => t.boundingBox()))).filter((b) => b !== null)
180
+ const clip =
181
+ boxes.length === targets.length && unionClip(boxes, FOCUS_MARGIN_PX, c.viewport, live)
182
+ if (clip) return void (await snap(c.page, path, { clip }))
183
+ if (!retry) throw new Error('Clipped area is either empty or outside the resulting image')
184
+ await c.page.evaluate(FRAMES)
185
+ }
186
+ }
187
+
173
188
  function record(c: Ctx, { name, state, status, file, note, stateful }: Outcome): void {
174
189
  const { route, scheme, viewport } = c
175
190
  c.shots.push({
@@ -545,6 +560,9 @@ export async function hoverTrigger(target: PwLocator): Promise<void> {
545
560
  await target.hover({ timeout: HOVER_TIMEOUT_MS, ...(position && { position }) })
546
561
  }
547
562
 
563
+ const tipOf = (c: Ctx, describedBy: string): PwLocator =>
564
+ c.page.locator(visibleTooltip(describedBy)).first()
565
+
548
566
  /**
549
567
  * The box of the tooltip an action opened, or null when none shows up. Call `markVisibleTooltips`
550
568
  * before the action; `describedBy` is the trigger's own tooltip id, when it has one.
@@ -554,7 +572,7 @@ async function openTooltipBox(
554
572
  describedBy: string,
555
573
  timeout = TIP_PROBE_MS,
556
574
  ): Promise<Box | null> {
557
- const tip = c.page.locator(visibleTooltip(describedBy)).first()
575
+ const tip = tipOf(c, describedBy)
558
576
  try {
559
577
  await tip.waitFor({ state: 'visible', timeout })
560
578
  } catch {
@@ -586,7 +604,7 @@ async function captureHover(c: Ctx, name: string): Promise<void> {
586
604
  const describedBy = idOf(await target.evaluate(describedByOf))
587
605
  const [box, tip] = [await settledBox(anchor), await openTooltipBox(c, describedBy)]
588
606
  if (!box || !tip) return void (await snap(anchor, path))
589
- await snap(c.page, path, { clip: unionClip([box, tip], FOCUS_MARGIN_PX, c.viewport, c.height) })
607
+ await snapClip(c, path, [anchor, tipOf(c, describedBy)])
590
608
  })
591
609
  await c.page.mouse.move(0, 0)
592
610
  }
@@ -645,9 +663,7 @@ async function captureFocus(c: Ctx, name: string): Promise<void> {
645
663
  ),
646
664
  )
647
665
  const tip = await openTooltipBox(c, focused)
648
- await snap(c.page, path, {
649
- clip: unionClip(tip ? [box, tip] : [box], FOCUS_MARGIN_PX, c.viewport, c.height),
650
- })
666
+ await snapClip(c, path, tip ? [anchor, tipOf(c, focused)] : [anchor])
651
667
  })
652
668
  await c.page.evaluate('document.activeElement?.blur()')
653
669
  }
@@ -666,7 +682,7 @@ async function captureTooltip(c: Ctx, name: string): Promise<void> {
666
682
  if (!t) throw new Error('no visible [role="tooltip"] after hover')
667
683
  const a = await settledBox(anchor)
668
684
  if (!a) throw new Error('tooltip or anchor has no box')
669
- await snap(c.page, path, { clip: unionClip([a, t], FOCUS_MARGIN_PX, c.viewport, c.height) })
685
+ await snapClip(c, path, [anchor, tipOf(c, describedBy)])
670
686
  })
671
687
  await c.page.mouse.move(0, 0)
672
688
  }