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
@@ -9,7 +9,7 @@ import { rowX } from './types'
9
9
  import type { ChartMarks, ChartSeries, ChartX, PlotContext, PlotRow } from './types'
10
10
 
11
11
  const MAX_END_LABELS = 3
12
- /** Below this vertical gap two end labels would collide; then none is drawn. */
12
+ /** Two end labels closer than this (px, vertically) are pushed apart to it. */
13
13
  const END_LABEL_MIN_GAP = 13
14
14
  const END_LABEL_DX = 6
15
15
  /**
@@ -42,10 +42,15 @@ export function endLabelAnchor(opts: {
42
42
  return room >= label.length * fontSize * END_LABEL_GLYPH_EM + END_LABEL_DX ? 'start' : 'end'
43
43
  }
44
44
 
45
+ /** `Lines`' one naming switch: who names the series. */
46
+ export type LinesNaming = 'auto' | 'legend' | 'endLabels'
47
+
45
48
  export type EndLabel<T, X extends ChartX> = {
46
49
  series: ChartSeries<T>
47
50
  row: PlotRow<T, X>
48
51
  anchor: EndLabelAnchor
52
+ /** A vertical shift in px (negative is up) that keeps this label clear of its neighbours. */
53
+ nudge: number
49
54
  }
50
55
 
51
56
  type LastPoint<T, X extends ChartX> = {
@@ -56,17 +61,45 @@ type LastPoint<T, X extends ChartX> = {
56
61
  }
57
62
 
58
63
  /**
59
- * The end labels to draw: none off the wide class, with a right axis, with more than
60
- * {@link MAX_END_LABELS} lines, or when two would collide in pixels (against the plot's height).
61
- * A series whose last point the plot's own x scale cannot place, or places outside the plot
64
+ * Pushes labels apart: `ys` are the labels' heights in px from the plot's bottom, returned as the
65
+ * shift each needs (positive is up) so no two sit closer than {@link END_LABEL_MIN_GAP} and the
66
+ * topmost stays inside the plot. Order is kept.
67
+ */
68
+ export function spreadLabels(ys: readonly number[], plotHeight: number): number[] {
69
+ const order = ys.map((y, i) => i).toSorted((a, b) => (ys[a] as number) - (ys[b] as number))
70
+ const placed = new Map<number, number>()
71
+ let floor = -Infinity
72
+ for (const i of order) {
73
+ const at = Math.max(ys[i] as number, floor)
74
+ placed.set(i, at)
75
+ floor = at + END_LABEL_MIN_GAP
76
+ }
77
+ // Pushed past the top: slide the whole stack back down, then re-sweep from the top.
78
+ const top = plotHeight - END_LABEL_MIN_GAP / 2
79
+ let ceiling = Infinity
80
+ for (const i of order.toReversed()) {
81
+ const at = Math.min(placed.get(i) as number, ceiling, top)
82
+ placed.set(i, at)
83
+ ceiling = at - END_LABEL_MIN_GAP
84
+ }
85
+ return ys.map((y, i) => (placed.get(i) as number) - y)
86
+ }
87
+
88
+ /**
89
+ * The end labels to draw. `auto`: on the wide class only, with ≤ {@link MAX_END_LABELS} lines and
90
+ * no right axis; `endLabels`: at every width and any line count (still no right axis, whose
91
+ * series read another scale); `legend`: none. Labels that would collide are spread apart, never
92
+ * dropped. A series whose last point the plot's own x scale cannot place, or places outside the plot
62
93
  * (`plot.xFraction` outside [0, 1]: clipped by a narrower `xDomain`), has no label.
63
94
  */
64
95
  export function endLabelPlan<T, X extends ChartX>(
65
96
  plot: PlotContext<T, X>,
66
97
  lines: readonly ChartSeries<T>[],
98
+ naming: LinesNaming = 'auto',
67
99
  ): EndLabel<T, X>[] {
68
- if (plot.containerClass !== 'wide' || plot.y2 !== undefined) return []
69
- if (lines.length === 0 || lines.length > MAX_END_LABELS) return []
100
+ if (naming === 'legend' || plot.y2 !== undefined || lines.length === 0) return []
101
+ if (naming === 'auto' && (plot.containerClass !== 'wide' || lines.length > MAX_END_LABELS))
102
+ return []
70
103
  const last = lines.flatMap((series): LastPoint<T, X>[] => {
71
104
  const row = plot.rows(series.key).findLast((r) => r.y !== null)
72
105
  if (row === undefined || row.y === null) return []
@@ -74,14 +107,13 @@ export function endLabelPlan<T, X extends ChartX>(
74
107
  if (fraction === null || fraction < 0 || fraction > 1) return []
75
108
  return [{ series, row, y: row.y, fraction }]
76
109
  })
77
- // Collision check in pixels from the plot height: labels that would overlap are not drawn at all.
78
110
  // No `y2` here (returned above), so every label reads the left domain.
79
111
  const [lo, hi] = plot.yDomain
80
- const ys = last
81
- .map(({ y }) => ((y - lo) / (hi - lo || 1)) * plot.plotHeight)
82
- .toSorted((a, b) => a - b)
83
- if (ys.some((y, i) => i > 0 && y - (ys[i - 1] as number) < END_LABEL_MIN_GAP)) return []
84
- return last.map(({ series, row, fraction }) => ({
112
+ const shifts = spreadLabels(
113
+ last.map(({ y }) => ((y - lo) / (hi - lo || 1)) * plot.plotHeight),
114
+ plot.plotHeight,
115
+ )
116
+ return last.map(({ series, row, fraction }, i) => ({
85
117
  series,
86
118
  row,
87
119
  anchor: endLabelAnchor({
@@ -90,6 +122,7 @@ export function endLabelPlan<T, X extends ChartX>(
90
122
  label: series.label,
91
123
  fontSize: VX.text.micro,
92
124
  }),
125
+ nudge: 0 - (shifts[i] as number),
93
126
  }))
94
127
  }
95
128
 
@@ -101,7 +134,7 @@ export function endLabelOffset(anchor: EndLabelAnchor): { dx: number; dy: number
101
134
  }
102
135
 
103
136
  export function endLabelMarks<T, X extends ChartX>(plan: readonly EndLabel<T, X>[]): ChartMarks {
104
- return plan.map(({ series, row, anchor }) =>
137
+ return plan.map(({ series, row, anchor, nudge }) =>
105
138
  decorative(
106
139
  text([row], {
107
140
  id: `${series.key}-end-label`,
@@ -111,7 +144,8 @@ export function endLabelMarks<T, X extends ChartX>(plan: readonly EndLabel<T, X>
111
144
  fill: series.color,
112
145
  fontSize: VX.text.micro,
113
146
  anchor,
114
- ...endLabelOffset(anchor),
147
+ dx: endLabelOffset(anchor).dx,
148
+ dy: endLabelOffset(anchor).dy + nudge,
115
149
  }),
116
150
  ),
117
151
  )
@@ -49,7 +49,8 @@ const rowBaseStyle: CSSProperties = {
49
49
  flexWrap: 'wrap',
50
50
  alignItems: 'center',
51
51
  rowGap: 4,
52
- fontSize: VX.legendFontSize,
52
+ // The tick step: ticks, legend and tooltip are one size, so a chart card has at most three.
53
+ fontSize: VX.text.micro,
53
54
  color: VX.ink2,
54
55
  lineHeight: 1.35,
55
56
  }
@@ -153,29 +154,15 @@ function Swatch({ s, mode }: { s: SwatchStyle; mode: LegendMode }): ReactElement
153
154
  </>
154
155
  )
155
156
  if ((s.mark ?? 'line') === 'line') return <LineSwatch s={s} compact={mode === 'dots'} />
156
- if (mode === 'dots')
157
- return (
158
- <span
159
- aria-hidden
160
- className={classes.dot}
161
- style={{
162
- width: 8,
163
- height: 8,
164
- // theme-allow raw-surface — a legend dot is a circle, not a surface corner
165
- borderRadius: '50%',
166
- background: swatchFill(s),
167
- opacity: s.fillOpacity ?? 1,
168
- flex: 'none',
169
- }}
170
- />
171
- )
157
+ // One shape per mark kind at every width: a bar is a rounded square, compact (8) or wide (10).
158
+ const size = mode === 'dots' ? 8 : 10
172
159
  return (
173
160
  <span
174
161
  aria-hidden
175
- className={classes.chip}
162
+ className={mode === 'dots' ? classes.dot : classes.chip}
176
163
  style={{
177
- width: 10,
178
- height: 10,
164
+ width: size,
165
+ height: size,
179
166
  // theme-allow raw-surface — swatch geometry, not a surface corner
180
167
  borderRadius: 2,
181
168
  background: swatchFill(s),
@@ -196,6 +183,8 @@ export type ChartLegendProps<T> = {
196
183
  onHighlight: (key: string | null) => void
197
184
  /** Keeps the legend's box but shows and offers nothing: a chart with no marks names no series. */
198
185
  concealed?: boolean
186
+ /** `auto` mode only: gone from the wide class up, where end labels name the lines (CSS). */
187
+ hideAtWide?: boolean
199
188
  }
200
189
 
201
190
  export function ChartLegend<T>(props: ChartLegendProps<T>): ReactElement | null {
@@ -210,6 +199,7 @@ export function ChartLegend<T>(props: ChartLegendProps<T>): ReactElement | null
210
199
  // `aria-hidden` is belt-and-braces for a tree that ignores computed visibility.
211
200
  {...(props.concealed && { 'aria-hidden': true })}
212
201
  {...(auto && { className: classes.auto })}
202
+ {...(auto && props.hideAtWide && { 'data-hide-wide': '' })}
213
203
  style={rowLayout(props.mode, props.concealed === true)}
214
204
  >
215
205
  {groups.map((group, gi) => [
@@ -52,7 +52,7 @@ export function lineMark<T, X extends ChartX>(
52
52
  stroke: s.color,
53
53
  strokeWidth: s.strokeWidth ?? LINE_STROKE_WIDTH,
54
54
  strokeOpacity: (s.strokeOpacity ?? 1) * emphasis(plot.highlighted, s),
55
- curve: chartCurve(s.curve ?? 'monotone'),
55
+ curve: chartCurve(s.curve ?? 'linear'),
56
56
  ...(s.dash === 'dashed' && { strokeDasharray: DASH }),
57
57
  ...(yScale !== undefined && { yScale }),
58
58
  })
@@ -90,15 +90,12 @@ export const paneY = (opts: {
90
90
  format: (v: number) => string
91
91
  ticks: number
92
92
  cls: ContainerClass
93
- /** The whole chart's height ({@link chartHeightOf}). */
94
- height: number
95
93
  }): StoredChartSpec['scales'][string] => ({
96
94
  scale: opts.scale,
97
95
  ...yGuide({
98
96
  cfg: { ticks: opts.ticks },
99
97
  axis: { domain: opts.domain, format: opts.format },
100
98
  cls: opts.cls,
101
- height: opts.height,
102
99
  side: 'left',
103
100
  grid: true,
104
101
  }),
@@ -113,23 +110,11 @@ export const paneX = <X extends ChartX>(opts: {
113
110
  /** A consumer's x format; absent, the span-aware default ({@link xTickFormat}). */
114
111
  format?: ((v: ChartValue) => string) | undefined
115
112
  cls: ContainerClass
116
- /** The whole chart's height ({@link chartHeightOf}). */
117
- height: number
118
113
  }): StoredChartSpec['scales'][string] => ({
119
114
  scale: opts.scale,
120
- ...xGuide({
121
- model: opts.model,
122
- xTicks: undefined,
123
- format: opts.format,
124
- cls: opts.cls,
125
- height: opts.height,
126
- }),
115
+ ...xGuide({ model: opts.model, xTicks: undefined, format: opts.format, cls: opts.cls }),
127
116
  })
128
117
 
129
- /** The whole chart's height from one pane's: a pane gets `share` of the height less the gap. */
130
- export const chartHeightOf = (paneHeight: number, share: number, gap: number): number =>
131
- paneHeight > 0 && share > 0 ? paneHeight / share + gap : 0
132
-
133
118
  /** One row per datum for a series: a `null` or non-finite value is kept as a gap. */
134
119
  export function rowsOf<T, X extends ChartX>(
135
120
  data: readonly T[],
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Where a reference line's caption sits. Pure, so the rule is tested without an engine: a
3
+ * caption takes the first of four spots (end/start of the plot, above/below its line) that stays
4
+ * inside the plot and that no data line runs through; `RefLine.labelPosition` pins one.
5
+ */
6
+
7
+ export type RefLabelPosition = 'end-above' | 'end-below' | 'start-above' | 'start-below'
8
+
9
+ /** A data point as a share of the plot width and a y value on the line's own axis. */
10
+ export type RefLabelPoint = { fx: number; y: number }
11
+
12
+ /** A glyph's advance as a share of the font size (proportional Latin text, capitals included). */
13
+ const GLYPH_EM = 0.62
14
+ /** The inset from the plot edge (the text's `dx`) and the gap between caption and line, in px. */
15
+ const EDGE_INSET = 6
16
+ const LINE_GAP = 3
17
+
18
+ const ORDER_END: readonly RefLabelPosition[] = [
19
+ 'end-above',
20
+ 'end-below',
21
+ 'start-above',
22
+ 'start-below',
23
+ ]
24
+ const ORDER_START: readonly RefLabelPosition[] = [
25
+ 'start-above',
26
+ 'start-below',
27
+ 'end-above',
28
+ 'end-below',
29
+ ]
30
+
31
+ /** The y range of the polyline `points` (sorted by `fx`) between `fx0` and `fx1`, or `null`. */
32
+ function yRangeWithin(
33
+ points: readonly RefLabelPoint[],
34
+ fx0: number,
35
+ fx1: number,
36
+ ): [number, number] | null {
37
+ let lo = Infinity
38
+ let hi = -Infinity
39
+ const take = (y: number): void => {
40
+ if (y < lo) lo = y
41
+ if (y > hi) hi = y
42
+ }
43
+ const at = (a: RefLabelPoint, b: RefLabelPoint, fx: number): number =>
44
+ b.fx === a.fx ? a.y : a.y + ((b.y - a.y) * (fx - a.fx)) / (b.fx - a.fx)
45
+ for (let i = 0; i < points.length; i++) {
46
+ const p = points[i] as RefLabelPoint
47
+ if (p.fx >= fx0 && p.fx <= fx1) take(p.y)
48
+ const next = points[i + 1]
49
+ if (next === undefined || (p.fx < fx0 && next.fx < fx0) || (p.fx > fx1 && next.fx > fx1))
50
+ continue
51
+ // A segment entering or leaving the window contributes where it crosses its edge.
52
+ for (const edge of [fx0, fx1]) {
53
+ if ((p.fx < edge && next.fx > edge) || (p.fx > edge && next.fx < edge))
54
+ take(at(p.fx < next.fx ? p : next, p.fx < next.fx ? next : p, edge))
55
+ }
56
+ }
57
+ return lo <= hi ? [lo, hi] : null
58
+ }
59
+
60
+ export function refLabelPosition(opts: {
61
+ /** `RefLine.labelPosition`: wins over everything. */
62
+ pinned: RefLabelPosition | undefined
63
+ /** The default end when nothing constrains it: `true` for a right-axis line. */
64
+ startFirst: boolean
65
+ value: number
66
+ domain: readonly [number, number]
67
+ plotWidth: number
68
+ plotHeight: number
69
+ label: string
70
+ fontSize: number
71
+ /** One polyline per visible series on the line's axis. */
72
+ series: readonly (readonly RefLabelPoint[])[]
73
+ }): RefLabelPosition {
74
+ const { pinned, startFirst, value, plotWidth, plotHeight, label, fontSize, series } = opts
75
+ const order = startFirst ? ORDER_START : ORDER_END
76
+ if (pinned !== undefined) return pinned
77
+ const [lo, hi] = [Math.min(...opts.domain), Math.max(...opts.domain)]
78
+ if (hi === lo || plotWidth <= 0 || plotHeight <= 0) return order[0] as RefLabelPosition
79
+ const perPx = (hi - lo) / plotHeight
80
+ const widthFx = (label.length * fontSize * GLYPH_EM + EDGE_INSET) / plotWidth
81
+ const heightPx = fontSize + 2
82
+ const bandOf = (position: RefLabelPosition): [number, number] =>
83
+ position.endsWith('above')
84
+ ? [value + LINE_GAP * perPx, value + (LINE_GAP + heightPx) * perPx]
85
+ : [value - (LINE_GAP + heightPx) * perPx, value - LINE_GAP * perPx]
86
+ const inPlot = (position: RefLabelPosition): boolean => {
87
+ const [from, to] = bandOf(position)
88
+ return from >= lo && to <= hi
89
+ }
90
+ const clear = (position: RefLabelPosition): boolean => {
91
+ const [from, to] = bandOf(position)
92
+ const [fx0, fx1] = position.startsWith('end')
93
+ ? [1 - widthFx, 1 - EDGE_INSET / plotWidth]
94
+ : [EDGE_INSET / plotWidth, widthFx]
95
+ return series.every((points) => {
96
+ const range = yRangeWithin(points, fx0, fx1)
97
+ return range === null || range[1] < from || range[0] > to
98
+ })
99
+ }
100
+ // A caption that cannot avoid the data still stays inside the plot.
101
+ return (
102
+ order.find((p) => inPlot(p) && clear(p)) ?? order.find(inPlot) ?? (order[0] as RefLabelPosition)
103
+ )
104
+ }
@@ -7,7 +7,7 @@
7
7
  import { scaleBand } from '@tanstack/charts/scales/band'
8
8
  import { scaleLinear } from '@tanstack/charts/scales/linear'
9
9
  import { scalePoint } from '@tanstack/charts/scales/point'
10
- import { scaleLog, scaleUtc } from 'd3-scale'
10
+ import { scaleLinear as d3Linear, scaleLog, scaleUtc } from 'd3-scale'
11
11
  import type { ChartPositionScaleOptions } from '@tanstack/charts/types/core'
12
12
  import type { AxisConfig, ChartSeries, ChartX, XZoneSpec } from './types'
13
13
 
@@ -25,6 +25,23 @@ export function padAutoUpper(candidate: number, pad: number): number {
25
25
  return candidate > 0 ? candidate * pad : candidate / pad
26
26
  }
27
27
 
28
+ /**
29
+ * Raises `upper` until the axis' top tick (for `count` ticks over `[lower, upper]`) reaches `max`:
30
+ * a padded domain can end between ticks, so the line peaks above the last label. Each step adds
31
+ * one tick interval, so the loop ends within a few turns.
32
+ */
33
+ function coverTop(lower: number, upper: number, max: number, count: number): number {
34
+ let top = upper
35
+ for (let i = 0; i < 4; i++) {
36
+ const ticks = d3Linear().domain([lower, top]).ticks(count)
37
+ const last = ticks.at(-1)
38
+ const step = ticks.length > 1 ? (ticks[1] as number) - (ticks[0] as number) : 0
39
+ if (last === undefined || step <= 0 || last >= max) return top
40
+ top = last + step
41
+ }
42
+ return top
43
+ }
44
+
28
45
  /**
29
46
  * One y axis' domain. `extraBounds` are the finite zone and reference-line values pinned to this
30
47
  * axis — a target past the data must stay inside the plot. Infinite bounds clamp to the domain by
@@ -35,6 +52,9 @@ export function resolveYDomain<T>(
35
52
  data: readonly T[],
36
53
  series: readonly ChartSeries<T>[],
37
54
  extraBounds: readonly number[] = [],
55
+ /** The number of ticks the axis will draw (0: none, or its own tick values): when set, an AUTO
56
+ * domain ends on a tick at or above the data's maximum. */
57
+ tickCount = 0,
38
58
  ): readonly [number, number] {
39
59
  const domain = cfg?.domain ?? 'auto'
40
60
  if (Array.isArray(domain)) return domain as readonly [number, number]
@@ -67,7 +87,7 @@ export function resolveYDomain<T>(
67
87
  const lower = padAutoLower(Math.min(min, cfg?.autoMinCeil ?? 0), pad)
68
88
  // A flat series would be a scale with no extent: every point on one pixel.
69
89
  if (lower === upper) return [Math.min(lower, 0), upper === 0 ? 1 : upper * pad]
70
- return [lower, upper]
90
+ return [lower, tickCount > 0 && !cfg?.nice ? coverTop(lower, upper, max, tickCount) : upper]
71
91
  }
72
92
 
73
93
  /** A configured y scale instance for a resolved domain. */
@@ -4,7 +4,8 @@
4
4
  * a mark: the plot is the whole box, and a chip inside it would have to hide some series (a line's
5
5
  * last segment, a bar, the end dot) wherever it landed. Above is always free inside a card or strip
6
6
  * cell (the hero value or caption is what sits there), and the chip is opaque so it reads over it.
7
- * It takes the side away from the hovered point.
7
+ * It rides the hovered point: its left edge is the point's fraction, shifted back by that same
8
+ * fraction of its own width, so it is centred on a mid point and flush with the box at either end.
8
9
  */
9
10
 
10
11
  .root {
@@ -13,7 +14,9 @@
13
14
 
14
15
  .readout {
15
16
  position: absolute;
16
- bottom: 100%;
17
+ /* The layer is inset from the root by the line's plot margin; lifting by it puts the chip back
18
+ * on the root's top edge, the line a host slot reserves. */
19
+ bottom: calc(100% + var(--basalt-spark-lift, 0px));
17
20
  z-index: 1;
18
21
  max-width: 100%;
19
22
  box-sizing: border-box;
@@ -35,19 +38,15 @@
35
38
  border-radius: var(--vx-radius-ctrl);
36
39
  }
37
40
 
38
- .start {
39
- left: 0;
40
- }
41
-
42
- .end {
43
- right: 0;
44
- }
45
-
46
41
  .label {
47
- font-family: var(--basalt-font-mono);
48
42
  opacity: 0.7;
49
43
  }
50
44
 
45
+ .layer {
46
+ position: absolute;
47
+ pointer-events: none;
48
+ }
49
+
51
50
  .dot {
52
51
  position: absolute;
53
52
  width: 6px;
@@ -5,9 +5,8 @@
5
5
  declare const classes: {
6
6
  readonly root: string
7
7
  readonly readout: string
8
- readonly start: string
9
- readonly end: string
10
8
  readonly label: string
9
+ readonly layer: string
11
10
  readonly dot: string
12
11
  }
13
12
  export default classes
@@ -84,6 +84,8 @@ export function ChartPlaceholder(props: {
84
84
  /** For a box too small to hold a sentence (a sparkline): error and empty show a `—` and carry the
85
85
  * label as the accessible name and the hover title. */
86
86
  compact?: boolean
87
+ /** Error only: what failed to load, "Could not load {noun}". Default: no noun. */
88
+ noun?: string
87
89
  }): ReactElement | null {
88
90
  const kind = resolveChartState(props.state)
89
91
  if (kind === null) return null
@@ -110,7 +112,7 @@ export function ChartPlaceholder(props: {
110
112
  {kind === 'error' && (
111
113
  <span style={errorHeadStyle}>
112
114
  <span aria-hidden="true" data-basalt-status-dot="" style={dotStyle} />
113
- Could not load this chart
115
+ Could not load{props.noun === undefined ? '' : ` ${props.noun}`}
114
116
  </span>
115
117
  )}
116
118
  <span style={errorMessageStyle}>{label}</span>
@@ -6,6 +6,7 @@ import type { StoredChartSpec } from '@tanstack/charts/types/core'
6
6
  import type { BasaltProps } from '../common/props'
7
7
  import type { ContainerClass } from '../tokens/size-classes'
8
8
  import type { CurveName } from './curves'
9
+ import type { RefLabelPosition } from './ref-label'
9
10
 
10
11
  /** What `x` may return. The value type picks the x scale (§ 9.4): `Date` → time, `number` → linear,
11
12
  * `string` → point (lines) or band (bars). */
@@ -27,8 +28,10 @@ export type ChartSeries<T> = {
27
28
  mark?: 'line' | 'bar' | 'area' | undefined
28
29
  /** Default `'solid'`; `'dashed'` is `VX.dashArray` on the line, the legend and the tooltip. */
29
30
  dash?: 'solid' | 'dashed' | undefined
30
- /** Interpolation between points. Default `'monotone'`. A piecewise-constant quantity (a price
31
- * tier, a config value) is a step: a smoothed curve draws values that never existed. */
31
+ /** Interpolation between points. Default `'linear'`: discrete values (a daily total, a monthly
32
+ * rate) are joined by straight segments, never by a smoothed curve with crossings between points
33
+ * that never happened. `'monotone'` is an opt-in for a continuous measure; a piecewise-constant
34
+ * quantity (a price tier, a config value) is a step. */
32
35
  curve?: CurveName | undefined
33
36
  strokeWidth?: number | undefined
34
37
  /**
@@ -155,11 +158,17 @@ export type RefLine = {
155
158
  dashed?: boolean | undefined
156
159
  axis?: 'left' | 'right' | undefined
157
160
  /**
158
- * Names the line on the plot: a small muted caption at the plot's right end (left end for a
159
- * right-axis line, clear of its tick labels), above the line, below it near the plot's top. It
160
- * follows the legend toggle. The ink is `--vx-ink2`, never the line colour.
161
+ * Names the line on the plot: a small muted caption on one of four spots (the plot's end or
162
+ * start, above or below the line). It follows the legend toggle. The ink is `--vx-ink2`, never
163
+ * the line colour.
161
164
  */
162
165
  label?: string | undefined
166
+ /**
167
+ * Pins the caption's spot. Default: the first spot (the plot's right end above the line; the left
168
+ * end for a right-axis line) that stays inside the plot and that no data line runs through, so a
169
+ * line in the top or bottom quarter, or one a series ends on, moves its caption.
170
+ */
171
+ labelPosition?: RefLabelPosition | undefined
163
172
  /**
164
173
  * Names the line in the legend (its color, dashed as `dashed`; a toggle hides the line), so a
165
174
  * threshold needs no always-`null` series. `mark` is the swatch shape. Default `'line'`. The
@@ -370,7 +370,7 @@ export function seedTsconfigExtends(cwd: string): string | null {
370
370
  }
371
371
 
372
372
  const SEED_HINT = 'node_modules/basalt-ui/agent/templates/main.tpl'
373
- const ROUTER_PLUGIN_FIX =
373
+ export const ROUTER_PLUGIN_FIX =
374
374
  "Fix: `bun add -D @tanstack/router-plugin`, add `tanstackRouter({ target: 'react', autoCodeSplitting: true })` " +
375
375
  "from '@tanstack/router-plugin/vite' to `plugins` in vite.config.ts (before react()), then run vite once " +
376
376
  'to generate src/routeTree.gen.ts — or define the tree in code (`createRootRoute` + `createRoute`), drop the routeTree.gen import and pass the tree to createBasaltRouter.'
package/src/cli/init.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * the managed-file manifest engine back from `./index`, this package's shared CLI helpers, and the
4
4
  * oxlint-preset plugin reader from `./sync` (also called there).
5
5
  */
6
- import { existsSync } from 'node:fs'
6
+ import { existsSync, readFileSync } from 'node:fs'
7
7
  import { resolve } from 'node:path'
8
8
 
9
9
  import { deriveSpacing } from '../tokens/core'
@@ -34,7 +34,8 @@ import {
34
34
  writeFileEnsuringDir,
35
35
  writeUnit,
36
36
  } from './index'
37
- import { seedTsconfigExtends } from './doctor-upgrade'
37
+ import { ROUTER_PLUGIN_FIX, seedTsconfigExtends } from './doctor-upgrade'
38
+ import { routerSeedDest } from './router-wiring'
38
39
  import { readOxlintPresetPlugins } from './sync'
39
40
 
40
41
  /**
@@ -57,6 +58,70 @@ const KEPT_FILE_COST: Record<string, string> = {
57
58
  'DESIGN.md': 'the design brief Claude reads is yours, not the seeded one.',
58
59
  }
59
60
 
61
+ /** One line at a time (string literals keep their inner spaces): trimmed, `;`, trailing `,` and `"` quotes undone. */
62
+ const normalise = (code: string): string =>
63
+ code
64
+ .split('\n')
65
+ .map((line) =>
66
+ line
67
+ .trim()
68
+ .replace(/[;,]$/, '')
69
+ .replace(/"([^"']*)"/g, "'$1'"),
70
+ )
71
+ .filter(Boolean)
72
+ .join('\n')
73
+
74
+ const viteTemplate = (css: boolean, app: string): string => `import { StrictMode } from 'react'
75
+ import { createRoot } from 'react-dom/client'
76
+ ${css ? "import './index.css'" : ''}
77
+ import App from '${app}'
78
+
79
+ createRoot(document.getElementById('root')!).render(
80
+ <StrictMode>
81
+ <App />
82
+ </StrictMode>,
83
+ )`
84
+
85
+ const STOCK_MAINS = [true, false].flatMap((css) =>
86
+ ['.tsx', ''].map((ext) => normalise(viteTemplate(css, './App' + ext))),
87
+ )
88
+
89
+ /** Whether `text` is create-vite's react-ts `main.tsx`, untouched (formatting aside): never an edited file. */
90
+ export const isStockViteMain = (text: string): boolean => STOCK_MAINS.includes(normalise(text))
91
+
92
+ const ALSO_REQUIRED_PEERS = ['motion']
93
+
94
+ /** The required peers of `.` (plus the ones `styles.css` imports) the app does not declare yet, with their ranges. */
95
+ function missingPeers(cwd: string, pkgRoot: string): Record<string, string> {
96
+ const shipped = JSON.parse(readFileSync(resolve(pkgRoot, 'package.json'), 'utf8')) as {
97
+ peerDependencies?: Record<string, string>
98
+ peerDependenciesMeta?: Record<string, { optional?: boolean }>
99
+ }
100
+ const app = JSON.parse(readFileSync(resolve(cwd, 'package.json'), 'utf8')) as Record<
101
+ string,
102
+ Record<string, string> | undefined
103
+ >
104
+ const declared = new Set(
105
+ ['dependencies', 'devDependencies', 'peerDependencies'].flatMap((k) =>
106
+ Object.keys(app[k] ?? {}),
107
+ ),
108
+ )
109
+ return Object.fromEntries(
110
+ Object.entries(shipped.peerDependencies ?? {}).filter(
111
+ ([name]) =>
112
+ !declared.has(name) &&
113
+ (shipped.peerDependenciesMeta?.[name]?.optional !== true ||
114
+ ALSO_REQUIRED_PEERS.includes(name)),
115
+ ),
116
+ )
117
+ }
118
+
119
+ const hasRouterPlugin = (cwd: string): boolean =>
120
+ ['vite.config.ts', 'vite.config.mts', 'vite.config.js', 'vite.config.mjs'].some((f) => {
121
+ const abs = resolve(cwd, f)
122
+ return existsSync(abs) && readFileSync(abs, 'utf8').includes('@tanstack/router-plugin')
123
+ })
124
+
60
125
  /** What happened to a kept `.oxlintrc.json`, by the merge result (null: `--no-merge-lint`). */
61
126
  function oxlintrcCost(merge: MergeLintResult | null): string {
62
127
  if (merge === 'added' || merge === 'already') {
@@ -149,6 +214,12 @@ export function init(cwd: string = process.cwd(), scaffoldFlags: ScaffoldFlags =
149
214
  )
150
215
  const files = managedFiles(placement, ctx.pkgRoot).filter((f) => !skippedSeeds.has(f.dest))
151
216
 
217
+ const mainDest = routerSeedDest(placement.appRel, 'main')
218
+ const mainPath = resolve(cwd, mainDest)
219
+ const stockMain =
220
+ !skippedSeeds.has(mainDest) &&
221
+ existsSync(mainPath) &&
222
+ isStockViteMain(readFileSync(mainPath, 'utf8'))
152
223
  const writtenFiles: string[] = []
153
224
  const keptFiles: string[] = []
154
225
  const missingSources: string[] = []
@@ -163,7 +234,7 @@ export function init(cwd: string = process.cwd(), scaffoldFlags: ScaffoldFlags =
163
234
  // Whole files (managed + seed) are skip-if-exists on init; a marker-spliced region always
164
235
  // inserts/updates itself inside its host file.
165
236
  const destExists = existsSync(resolve(cwd, file.dest))
166
- if (!file.markers && destExists) {
237
+ if (!file.markers && destExists && !(stockMain && file.dest === mainDest)) {
167
238
  // Already present — keep the consumer's copy untouched. Record the SHIPPED hash (normalized,
168
239
  // same ledger form `writeUnit` uses) so a later sync treats a pre-existing-but-different file
169
240
  // as locally drifted (skip unless --force), never silently clobbering a file the consumer
@@ -186,6 +257,28 @@ export function init(cwd: string = process.cwd(), scaffoldFlags: ScaffoldFlags =
186
257
  const mergeLint: MergeLintResult | null =
187
258
  scaffoldFlags.noMergeLint === true ? null : mergeOxlintExtends(cwd, ctx.vars.OXLINT_PRESET_PATH)
188
259
 
260
+ // The entry was seeded above or kept; either way the app still needs the peers it imports and the router plugin.
261
+ const keptUnwired =
262
+ keptFiles.includes(mainDest) && !/from ['"]basalt-ui['"/]/.test(readFileSync(mainPath, 'utf8'))
263
+ const advice: string[] = []
264
+ if (stockMain || keptUnwired) {
265
+ const missing = missingPeers(cwd, ctx.pkgRoot)
266
+ const count = Object.keys(missing).length
267
+ if (count > 0 && stockMain) {
268
+ patchPackageJson(cwd, (pkg) => {
269
+ pkg['dependencies'] = { ...(pkg['dependencies'] as Record<string, string>), ...missing }
270
+ return true
271
+ })
272
+ advice.push(
273
+ `added ${count} missing peers to package.json; run \`bun install\` (init does not).`,
274
+ )
275
+ } else if (count > 0) {
276
+ const specs = Object.entries(missing).map(([name, range]) => `${name}@${range}`)
277
+ advice.push(`missing peers: \`bun add ${specs.join(' ')}\`.`)
278
+ }
279
+ if (!hasRouterPlugin(cwd)) advice.push(ROUTER_PLUGIN_FIX.replace(/^Fix: /, 'router plugin: '))
280
+ }
281
+
189
282
  manifest.basaltVersion = ctx.vars.BASALT_VERSION
190
283
  manifest.spacingScale = { ...deriveSpacing(0).scale }
191
284
  writeFileEnsuringDir(resolve(cwd, MANIFEST_PATH), `${JSON.stringify(manifest, null, 2)}\n`)
@@ -194,6 +287,10 @@ export function init(cwd: string = process.cwd(), scaffoldFlags: ScaffoldFlags =
194
287
  `basalt-ui init: ${writtenFiles.length} written, ${keptFiles.length} kept, manifest at ${MANIFEST_PATH}`,
195
288
  )
196
289
  reportPrune(pruned)
290
+ if (stockMain) {
291
+ console.log(`basalt-ui init: seeded ${mainDest} (it was the unmodified Vite template).`)
292
+ }
293
+ for (const line of advice) console.log(`basalt-ui init: ${line}`)
197
294
  if (missingSources.length > 0) {
198
295
  console.log(
199
296
  `basalt-ui init: ${missingSources.length} shipped asset(s) not present, skipped: ${missingSources.join(', ')}`,