@squadbase/vantage 0.6.2-dev1.42c4e48 → 0.6.2-dev1.9365dcd

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 (148) hide show
  1. package/dist/{build-MFWRPYKW.js → build-X5NVCQKT.js} +4 -4
  2. package/dist/{build-MFWRPYKW.js.map → build-X5NVCQKT.js.map} +1 -1
  3. package/dist/{chunk-IBGOCWJB.js → chunk-2ICNHUG6.js} +186 -82
  4. package/dist/chunk-2ICNHUG6.js.map +1 -0
  5. package/dist/{chunk-5ZOP4SQR.js → chunk-2N72FKLB.js} +12 -7
  6. package/dist/chunk-2N72FKLB.js.map +1 -0
  7. package/dist/chunk-HKSVYMYJ.js +7919 -0
  8. package/dist/chunk-HKSVYMYJ.js.map +1 -0
  9. package/dist/{chunk-PXRX5PEC.js → chunk-PDOBHMUQ.js} +3 -3
  10. package/dist/chunk-PDOBHMUQ.js.map +1 -0
  11. package/dist/{chunk-A2UUGASH.js → chunk-U736PVHY.js} +2 -2
  12. package/dist/chunk-U736PVHY.js.map +1 -0
  13. package/dist/{chunk-QEWCYW3I.js → chunk-WAMZWZJB.js} +13 -3
  14. package/dist/chunk-WAMZWZJB.js.map +1 -0
  15. package/dist/{chunk-OB6UBJXF.js → chunk-XPQSTZUU.js} +125 -35
  16. package/dist/chunk-XPQSTZUU.js.map +1 -0
  17. package/dist/cli.js +3 -3
  18. package/dist/components/index.d.ts +1832 -100
  19. package/dist/components/index.js +4 -4
  20. package/dist/{dev-DCTOHQ6W.js → dev-4XEDTELV.js} +4 -4
  21. package/dist/{dev-DCTOHQ6W.js.map → dev-4XEDTELV.js.map} +1 -1
  22. package/dist/doc/index.js +2 -2
  23. package/dist/doc/index.js.map +1 -1
  24. package/dist/markdown/index.js +1 -1
  25. package/dist/markdown/index.js.map +1 -1
  26. package/dist/slide/index.js +2 -2
  27. package/dist/slide/index.js.map +1 -1
  28. package/dist/table/index.js +6 -6
  29. package/dist/table/index.js.map +1 -1
  30. package/dist/ui/index.d.ts +4 -1
  31. package/dist/ui/index.js +21 -111
  32. package/dist/ui/index.js.map +1 -1
  33. package/dist/{upgrade-DBBE6GIR.js → upgrade-JHXZBGQS.js} +3 -3
  34. package/dist/{upgrade-DBBE6GIR.js.map → upgrade-JHXZBGQS.js.map} +1 -1
  35. package/dist/vite/index.js +2 -2
  36. package/docs/en/components.md +29 -15
  37. package/docs/en/parts/data-table.md +22 -0
  38. package/docs/en/parts/delta.md +50 -0
  39. package/docs/en/parts/format.md +43 -0
  40. package/docs/en/parts/kpi-card.md +57 -0
  41. package/docs/en/parts/metric-value.md +3 -2
  42. package/docs/en/parts/sparkline.md +1 -1
  43. package/docs/en/parts/trend-indicator.md +17 -1
  44. package/docs/en/ui-and-theming.md +1 -1
  45. package/docs/index.json +92 -32
  46. package/docs/ja/components.md +27 -15
  47. package/docs/ja/parts/data-table.md +22 -0
  48. package/docs/ja/parts/delta.md +50 -0
  49. package/docs/ja/parts/format.md +44 -0
  50. package/docs/ja/parts/kpi-card.md +55 -0
  51. package/docs/ja/parts/metric-value.md +3 -2
  52. package/docs/ja/parts/sparkline.md +1 -1
  53. package/docs/ja/parts/trend-indicator.md +17 -1
  54. package/docs/ja/ui-and-theming.md +2 -2
  55. package/package.json +26 -24
  56. package/registry/ui/accordion.tsx +4 -2
  57. package/registry/ui/alert-dialog.tsx +3 -3
  58. package/registry/ui/alert.tsx +3 -1
  59. package/registry/ui/app-shell.tsx +7 -1
  60. package/registry/ui/area-chart.tsx +2817 -157
  61. package/registry/ui/attention-list.tsx +303 -0
  62. package/registry/ui/avatar.tsx +1 -1
  63. package/registry/ui/badge.tsx +3 -1
  64. package/registry/ui/bar-chart.tsx +2816 -157
  65. package/registry/ui/bar-list.tsx +3507 -93
  66. package/registry/ui/box-plot-chart.tsx +3880 -0
  67. package/registry/ui/breadcrumb.tsx +3 -1
  68. package/registry/ui/button.tsx +3 -1
  69. package/registry/ui/calendar.tsx +3 -1
  70. package/registry/ui/card.tsx +4 -2
  71. package/registry/ui/category-bar.tsx +998 -16
  72. package/registry/ui/chart-frame.tsx +1366 -0
  73. package/registry/ui/checkbox.tsx +3 -1
  74. package/registry/ui/collapsible.tsx +3 -1
  75. package/registry/ui/combobox.tsx +2 -2
  76. package/registry/ui/command.tsx +3 -1
  77. package/registry/ui/dashboard-card.tsx +71 -28
  78. package/registry/ui/data-table.tsx +678 -56
  79. package/registry/ui/date-range-picker.tsx +245 -64
  80. package/registry/ui/delta.tsx +188 -0
  81. package/registry/ui/dialog.tsx +5 -3
  82. package/registry/ui/donut-chart.tsx +2893 -173
  83. package/registry/ui/drawer.tsx +1 -1
  84. package/registry/ui/dropdown-menu.tsx +5 -3
  85. package/registry/ui/echart.tsx +483 -46
  86. package/registry/ui/field.tsx +1 -1
  87. package/registry/ui/filter-bar.tsx +33 -6
  88. package/registry/ui/funnel-steps.tsx +3344 -49
  89. package/registry/ui/heatmap.tsx +1760 -0
  90. package/registry/ui/histogram-chart.tsx +3960 -0
  91. package/registry/ui/hover-card.tsx +2 -2
  92. package/registry/ui/input-group.tsx +3 -1
  93. package/registry/ui/input.tsx +3 -1
  94. package/registry/ui/kbd.tsx +3 -1
  95. package/registry/ui/kpi-card.tsx +699 -0
  96. package/registry/ui/label.tsx +3 -1
  97. package/registry/ui/legend.tsx +3536 -0
  98. package/registry/ui/line-chart.tsx +2817 -151
  99. package/registry/ui/metric-value.tsx +9 -1
  100. package/registry/ui/multi-select.tsx +11 -5
  101. package/registry/ui/page-shell.tsx +106 -51
  102. package/registry/ui/pagination.tsx +3 -1
  103. package/registry/ui/paired-chart.tsx +3801 -0
  104. package/registry/ui/placeholder.tsx +8 -2
  105. package/registry/ui/popover.tsx +4 -2
  106. package/registry/ui/progress-circle.tsx +607 -12
  107. package/registry/ui/progress.tsx +3 -1
  108. package/registry/ui/radio-group.tsx +1 -1
  109. package/registry/ui/sample-data.tsx +86 -0
  110. package/registry/ui/scatter-chart.tsx +4186 -0
  111. package/registry/ui/scroll-area.tsx +3 -2
  112. package/registry/ui/searchable-select.tsx +8 -3
  113. package/registry/ui/section-header.tsx +5 -3
  114. package/registry/ui/segmented-control.tsx +7 -2
  115. package/registry/ui/select.tsx +4 -2
  116. package/registry/ui/separator.tsx +3 -1
  117. package/registry/ui/sheet.tsx +4 -2
  118. package/registry/ui/sidebar.tsx +4 -2
  119. package/registry/ui/skeleton.tsx +4 -2
  120. package/registry/ui/slider.tsx +3 -1
  121. package/registry/ui/sparkline.tsx +84 -9
  122. package/registry/ui/spinner.tsx +3 -1
  123. package/registry/ui/states.tsx +34 -5
  124. package/registry/ui/status-badge.tsx +81 -39
  125. package/registry/ui/switch.tsx +3 -1
  126. package/registry/ui/table.tsx +4 -2
  127. package/registry/ui/tabs.tsx +5 -3
  128. package/registry/ui/textarea.tsx +3 -1
  129. package/registry/ui/toast.tsx +2 -2
  130. package/registry/ui/toggle-group.tsx +3 -1
  131. package/registry/ui/toggle.tsx +3 -1
  132. package/registry/ui/tooltip.tsx +4 -2
  133. package/registry/ui/tracker.tsx +624 -17
  134. package/registry/ui/trend-indicator.tsx +13 -1
  135. package/registry/ui/updated-at.tsx +122 -0
  136. package/registry/ui/waterfall-chart.tsx +4222 -0
  137. package/skills/vantage-design/SKILL.md +10 -2
  138. package/templates/AGENTS.md +13 -1
  139. package/templates/agents/page.md +10 -0
  140. package/theme.css +241 -147
  141. package/dist/chunk-5ZOP4SQR.js.map +0 -1
  142. package/dist/chunk-A2UUGASH.js.map +0 -1
  143. package/dist/chunk-AG6RZ2RR.js +0 -3208
  144. package/dist/chunk-AG6RZ2RR.js.map +0 -1
  145. package/dist/chunk-IBGOCWJB.js.map +0 -1
  146. package/dist/chunk-OB6UBJXF.js.map +0 -1
  147. package/dist/chunk-PXRX5PEC.js.map +0 -1
  148. package/dist/chunk-QEWCYW3I.js.map +0 -1
@@ -1,21 +1,52 @@
1
1
  // Copied by `vantage add ui donut-chart`. This file is yours to edit.
2
- // Generated from @squadbase/vantage src/components/donut-chart.tsx by `npm run registry` (in Vantage, edit src/, not registry/).
2
+ // Generated from @squadbase/squadkit registry/charts/donut-chart.tsx by `pnpm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
3
5
  /**
4
- * DonutChart — a typed donut / pie chart over `EChart`: pass rows plus the
5
- * name column (`category`) and the value column (`value`). The donut prints a
6
- * label in its hole — the formatted total unless `label` says otherwise —
7
- * as plain HTML over the canvas, so it takes the page's type and colours.
6
+ * DonutChart — a typed donut / pie chart over `EChart`: pass rows, the label
7
+ * key (`index`) and the value key (`categories: [valueKey]`). Slices are sorted
8
+ * largest first and coloured with the `--chart-1..5` tokens in fixed order;
9
+ * more than 5 fold into one「その他」slice. The hole is empty by default (the
10
+ * total usually repeats a KPI); `donutOptions.centerLabel` picks `"total"`
11
+ * (「合計」+ the formatted total, plus `unit`), `"top"` (the largest slice and its
12
+ * share) or a custom node — plain HTML over the canvas, so it takes the page's
13
+ * type and colours. A share is printed once: the HTML legend lists every slice
14
+ * with its share, right of the ring when there is room, below it otherwise, and
15
+ * with the legend there are no outside labels (without it, a plot at least
16
+ * `DONUT_OUTSIDE_LABEL_MIN_WIDTH` wide labels its 2 largest slices).
17
+ * Renders inside `ChartFrame` (title, summary, loading skeleton, empty state,
18
+ * and a visually-hidden table of the slices).
8
19
  */
9
- import { forwardRef, useMemo, type ReactNode } from "react"
20
+ import { forwardRef, useEffect, useMemo, useState, type ForwardedRef, type ReactElement, type ReactNode, type Ref } from "react"
10
21
 
11
- import { cn } from "@squadbase/vantage/ui"
22
+ import { ChartFrame } from "@squadbase/vantage/components"
12
23
  import { EChart } from "@squadbase/vantage/components"
13
- import type { ChartColor, ChartEventPayload, ValueFormatter } from "@squadbase/vantage/components"
14
- import { useEffect, useState } from "react"
15
- import { useRef } from "react"
24
+ import type { ChartCommonProps, ChartEventPayload, ChartSeriesColor } from "@squadbase/vantage/components"
25
+ import { createContext, useCallback, useRef } from "react"
26
+ import type { ChartTone } from "@squadbase/vantage/components"
27
+ import { DEFAULT_LOCALE, EMPTY_VALUE, formatValue, toValueFormatter, type ValueFormat } from "@squadbase/vantage/components"
28
+ import type { ChartColor, ChartColors, ValueFormatter } from "@squadbase/vantage/components"
16
29
  import type { EChartsOption } from "@squadbase/vantage/components"
30
+ import { computeComparison, defaultChangeDisplay, formatChange, toneForValue, type ComparisonKind, type PeriodGrain } from "@squadbase/vantage/components"
31
+ import type { ChartThreshold, ChartAnnotation, ChartForecast, ChartForecastRow, ChartHighlight, NumericKeys } from "@squadbase/vantage/components"
32
+
33
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-theme.ts (internal to @squadbase/vantage) ---------- */
34
+
35
+ /**
36
+ * The colour of the folded「その他」series / slice / row. The ONLY place this
37
+ * grey is defined — every chart takes it from here. It is the most subdued
38
+ * colour in a chart, not the darkest: the theme's `--neutral` mixed halfway into
39
+ * `--background`, so it recedes in light and dark alike (and brand themes follow
40
+ * it). `--neutral-subtle` alone sits too close to the background to read as a
41
+ * slice. Canvas charts resolve it through `resolveChartColors`.
42
+ */
43
+ const CHART_OTHER_COLOR = "color-mix(in oklab, var(--neutral) 50%, var(--background))"
17
44
 
18
- /* ---------- inlined from src/components/chart-theme.ts (internal to @squadbase/vantage) ---------- */
45
+ /**
46
+ * True inside `ChartFrame`. The frame's plot area carries the chart's single
47
+ * `role="img"` and label, so `EChart` drops its own when it sees this.
48
+ */
49
+ const ChartFrameContext = createContext(false)
19
50
 
20
51
  /** Series palette, in order. Missing tokens are skipped, not defaulted. */
21
52
  const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
@@ -23,6 +54,8 @@ const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--ch
23
54
  interface ChartTokens {
24
55
  /** Resolved `--chart-1..5`, in order. */
25
56
  series: string[]
57
+ /** Computed `font-family` of the container, so canvas text matches the DOM. Optional. */
58
+ fontFamily?: string
26
59
  /** Body text: titles and the default `textStyle`. */
27
60
  foreground: string | null
28
61
  /** Secondary text: axis labels, legend, subtitles. */
@@ -92,6 +125,7 @@ function readChartTokens(el?: Element | null): ChartTokens | null {
92
125
  }
93
126
  return {
94
127
  series,
128
+ ...(styles.fontFamily ? { fontFamily: styles.fontFamily } : {}),
95
129
  foreground: read("--foreground"),
96
130
  mutedForeground: read("--muted-foreground"),
97
131
  border: read("--border"),
@@ -107,6 +141,7 @@ function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean
107
141
  return (
108
142
  a.series.length === b.series.length &&
109
143
  a.series.every((color, i) => color === b.series[i]) &&
144
+ a.fontFamily === b.fontFamily &&
110
145
  a.foreground === b.foreground &&
111
146
  a.mutedForeground === b.mutedForeground &&
112
147
  a.border === b.border &&
@@ -180,10 +215,11 @@ function watchChartTokens(onChange: () => void): () => void {
180
215
  function axisTheme(tokens: ChartTokens, splitLine: boolean) {
181
216
  const line = tokens.border ?? undefined
182
217
  return {
183
- axisLine: { show: true, lineStyle: { color: line } },
184
- axisTick: { show: true, lineStyle: { color: line } },
185
- axisLabel: { show: true, color: tokens.mutedForeground ?? undefined },
186
- splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined } },
218
+ axisLine: { show: false },
219
+ axisTick: { show: false },
220
+ axisLabel: { show: true, color: tokens.mutedForeground ?? undefined, fontSize: 12 },
221
+ // Faint horizontal rules only: the border colour at low opacity.
222
+ splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined, opacity: 0.5, width: 1 } },
187
223
  splitArea: { show: false },
188
224
  }
189
225
  }
@@ -200,7 +236,7 @@ function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
200
236
  // Let the page background show through: charts sit on cards, not on a canvas.
201
237
  backgroundColor: "transparent",
202
238
  ...(tokens.series.length > 0 ? { color: tokens.series } : {}),
203
- textStyle: { color: text },
239
+ textStyle: { color: text, ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}) },
204
240
  title: { textStyle: { color: text }, subtextStyle: { color: muted } },
205
241
  legend: { textStyle: { color: muted } },
206
242
  categoryAxis: axisTheme(tokens, false),
@@ -208,10 +244,19 @@ function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
208
244
  logAxis: axisTheme(tokens, true),
209
245
  timeAxis: axisTheme(tokens, true),
210
246
  tooltip: {
247
+ // ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
248
+ transitionDuration: 0,
211
249
  backgroundColor: tokens.popover ?? undefined,
212
250
  borderColor: line,
213
251
  borderWidth: 1,
214
- textStyle: { color: tokens.popoverForeground ?? undefined },
252
+ padding: [8, 12],
253
+ // Rounded card with a soft shadow; in dark mode the shadow barely shows, so the border carries the edge.
254
+ extraCssText: "border-radius:8px;box-shadow:var(--shadow-card, 0 4px 12px rgb(0 0 0 / 0.08));",
255
+ textStyle: {
256
+ color: tokens.popoverForeground ?? undefined,
257
+ fontSize: 12,
258
+ ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}),
259
+ },
215
260
  axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
216
261
  },
217
262
  }
@@ -225,12 +270,16 @@ function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
225
270
  */
226
271
  function useChartTokens(): ChartTokens | null {
227
272
  const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
273
+ // Compared here, not inside a `setTokens` updater: an updater that reads the DOM is
274
+ // replayed by React on every rebase and returns a fresh object each time, so the state
275
+ // never settles ("Maximum update depth exceeded" once the tokens change after mount).
276
+ const tokensRef = useRef(tokens)
228
277
  useEffect(() => {
229
278
  const sync = () => {
230
- setTokens((prev) => {
231
- const next = readChartTokens()
232
- return sameChartTokens(prev, next) ? prev : next
233
- })
279
+ const next = readChartTokens()
280
+ if (sameChartTokens(tokensRef.current, next)) return
281
+ tokensRef.current = next
282
+ setTokens(next)
234
283
  }
235
284
  sync()
236
285
  return watchChartTokens(sync)
@@ -239,11 +288,14 @@ function useChartTokens(): ChartTokens | null {
239
288
  }
240
289
 
241
290
  const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
291
+ const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
242
292
  const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
293
+ const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
243
294
 
244
295
  /**
245
296
  * Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
246
- * the resolved series tokens; `var(--token)` is read off the document root; any
297
+ * the resolved series tokens; `"positive"` / `"warning"` / `"negative"` / `"neutral"` (and the area
298
+ * variants `"positive-fill"`, …) are read off the document root (`--positive`, …); `var(--token)` is read off the document root; any
247
299
  * other CSS colour is normalized like the tokens are. A colour that can't be
248
300
  * resolved comes back as `""`, which ECharts treats as "use the palette".
249
301
  */
@@ -251,18 +303,119 @@ function resolveChartColors(colors: readonly string[], tokens: ChartTokens | nul
251
303
  return colors.map((color) => {
252
304
  const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
253
305
  if (token) return tokens?.series[Number(token[1]) - 1] ?? ""
306
+ // Meaning colours are the theme tokens of the same name: same path as `var(--positive)`.
307
+ if (TONE_NAME_RE.test(color.trim())) {
308
+ if (typeof document === "undefined") return ""
309
+ return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue(`--${color.trim()}`)) ?? ""
310
+ }
254
311
  if (typeof document === "undefined") return color
255
312
  let value = color.trim()
256
313
  const cssVar = CSS_VAR_RE.exec(value)
314
+ const styles = getComputedStyle(document.documentElement)
257
315
  if (cssVar) {
258
- const styles = getComputedStyle(document.documentElement)
259
316
  value = styles.getPropertyValue(cssVar[1]!).trim() || (cssVar[2] ?? "").trim()
317
+ } else if (value.includes("var(")) {
318
+ // A colour function over tokens (`color-mix(… var(--muted-foreground) …)`):
319
+ // substitute the tokens, then let the canvas resolve the rest.
320
+ value = value.replace(EMBEDDED_VAR_RE, (_, name: string) => styles.getPropertyValue(name).trim())
260
321
  }
261
322
  return toCanvasColor(value) ?? ""
262
323
  })
263
324
  }
264
325
 
265
- /* ---------- inlined from src/components/chart-utils.ts (internal to @squadbase/vantage) ---------- */
326
+ /** Every meaning colour resolved for the canvas (`""` when it can't be resolved). */
327
+ function resolveToneColors(tokens: ChartTokens | null): Record<ChartTone, string> {
328
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
329
+ ["positive", "warning", "negative", "neutral"],
330
+ tokens,
331
+ )
332
+ return { positive, warning, negative, neutral }
333
+ }
334
+
335
+ /** The area (`--<tone>-fill`) colours of every meaning tone, resolved for the canvas (`""` when it can't be resolved). */
336
+ function resolveFillColors(tokens: ChartTokens | null): Record<ChartTone, string> {
337
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
338
+ ["positive-fill", "warning-fill", "negative-fill", "neutral-fill"],
339
+ tokens,
340
+ )
341
+ return { positive, warning, negative, neutral }
342
+ }
343
+
344
+ const TRANSPARENT_RE = /^(?:transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i
345
+
346
+ /**
347
+ * The colour the chart is painted on: the first opaque `background-color` up
348
+ * from `el` (a card, the page), else `--background`. Canvas-safe, or `null`
349
+ * outside the browser.
350
+ */
351
+ function readChartSurface(el: Element | null): string | null {
352
+ if (typeof document === "undefined") return null
353
+ for (let node: Element | null = el; node; node = node.parentElement) {
354
+ const bg = getComputedStyle(node).backgroundColor.trim()
355
+ if (bg && !TRANSPARENT_RE.test(bg)) {
356
+ const color = toCanvasColor(bg)
357
+ if (color) return color
358
+ }
359
+ }
360
+ return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue("--background"))
361
+ }
362
+
363
+ /** Widths are bucketed so a resize only rebuilds the option when the label budget can change. */
364
+ const WIDTH_BUCKET = 40
365
+
366
+ /**
367
+ * The surface colour behind a chart (see `readChartSurface`), re-read when the
368
+ * tokens move (light/dark), and the plot's width (rounded down to 40px;
369
+ * `undefined` until measured). Returns a ref for the plot that also feeds the
370
+ * component's forwarded ref.
371
+ */
372
+ function useChartSurface<E extends Element>(
373
+ forwarded: ForwardedRef<E>,
374
+ tokens: ChartTokens | null,
375
+ ): { ref: (el: E | null) => void; surface: string | undefined; width: number | undefined } {
376
+ const [node, setNode] = useState<E | null>(null)
377
+ const [surface, setSurface] = useState<string | undefined>(undefined)
378
+ const [width, setWidth] = useState<number | undefined>(undefined)
379
+ const ref = useCallback(
380
+ (el: E | null) => {
381
+ setNode(el)
382
+ if (typeof forwarded === "function") forwarded(el)
383
+ else if (forwarded) forwarded.current = el
384
+ },
385
+ [forwarded],
386
+ )
387
+ useEffect(() => {
388
+ if (!node) return
389
+ setSurface(readChartSurface(node) ?? undefined)
390
+ }, [node, tokens])
391
+ useEffect(() => {
392
+ if (!node || typeof ResizeObserver === "undefined") return
393
+ const update = (w: number) => setWidth(Math.floor(w / WIDTH_BUCKET) * WIDTH_BUCKET)
394
+ update(node.getBoundingClientRect().width)
395
+ const observer = new ResizeObserver((entries) => update(entries[0]?.contentRect.width ?? 0))
396
+ observer.observe(node)
397
+ return () => observer.disconnect()
398
+ }, [node])
399
+ return { ref, surface, width }
400
+ }
401
+
402
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
403
+
404
+ const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
405
+ const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
406
+
407
+ /**
408
+ * The attributes of a typed chart's leftover props that belong on its root
409
+ * element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
410
+ * An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
411
+ */
412
+ function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
413
+ const out: Record<string, unknown> = {}
414
+ for (const [key, value] of Object.entries(rest)) {
415
+ if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
416
+ }
417
+ return out
418
+ }
266
419
 
267
420
  /** The series tokens, in palette order — the default `colors` of every typed chart. */
268
421
  const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
@@ -275,13 +428,37 @@ const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
275
428
 
276
429
  const TOKEN_NAME_RE = /^chart-[1-5]$/
277
430
 
431
+ /** The meaning colours; each is a theme token of the same name (`--positive`, …). */
432
+ const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
433
+
434
+ /** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
435
+ function isChartTone(color: string): color is ChartTone {
436
+ return (CHART_TONES as readonly string[]).includes(color.trim())
437
+ }
438
+
278
439
  /**
279
440
  * A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
280
441
  * light/dark on its own), anything else passes through unchanged.
281
442
  */
282
443
  function chartColorToCss(color: ChartColor): string {
283
444
  const value = color.trim()
284
- return TOKEN_NAME_RE.test(value) ? `var(--${value})` : value
445
+ return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
446
+ }
447
+
448
+ /**
449
+ * A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
450
+ * colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
451
+ * lightness step from the page in light and dark. `--positive` etc. are for text and icons.
452
+ */
453
+ function chartFillToCss(color: ChartColor): string {
454
+ const value = color.trim()
455
+ return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
456
+ }
457
+
458
+ /** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
459
+ function chartFillName(color: ChartColor): ChartColor {
460
+ const value = color.trim()
461
+ return isChartTone(value) ? `${value}-fill` : color
285
462
  }
286
463
 
287
464
  /** The `i`-th colour, cycling through `colors` (the token palette when empty). */
@@ -305,6 +482,79 @@ const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 }
305
482
  /** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
306
483
  const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
307
484
 
485
+ /**
486
+ * The formatter a chart actually uses: an explicit `valueFormatter` wins, else
487
+ * `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
488
+ */
489
+ function resolveValueFormatter(
490
+ valueFormatter: ValueFormatter | undefined,
491
+ format: ValueFormat | undefined,
492
+ locale?: string,
493
+ ): ValueFormatter {
494
+ return valueFormatter ?? toValueFormatter(format, locale)
495
+ }
496
+
497
+ /**
498
+ * The formatter of value-axis ticks and on-plot labels: an explicit
499
+ * `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
500
+ * the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
501
+ * too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
502
+ * form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
503
+ * so an axis tick and a KPI / tooltip of the same `format` always print the same
504
+ * currency sign and grouping.
505
+ */
506
+ function resolveAxisFormatter(
507
+ valueFormatter: ValueFormatter | undefined,
508
+ format: ValueFormat | undefined,
509
+ locale: string = DEFAULT_LOCALE,
510
+ ): ValueFormatter {
511
+ if (valueFormatter) return valueFormatter
512
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
513
+ if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
514
+ const currency = "currency" in spec ? spec.currency : undefined
515
+ const short: ValueFormat =
516
+ spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
517
+ return (value) => formatValue(value, short, locale)
518
+ }
519
+
520
+ /** The unit words of a ja number (`1.2万` / `3.4億` / `1兆`) and their sizes, largest first. */
521
+ const JA_UNITS = [
522
+ { char: "兆", size: 1e12 },
523
+ { char: "億", size: 1e8 },
524
+ { char: "万", size: 1e4 },
525
+ ] as const
526
+
527
+ const JA_NUMBER_TOKEN_RE = /\d[\d,]*(?:\.\d+)?(?:兆|億|万)?/
528
+
529
+ /**
530
+ * The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
531
+ * that largest tick, so 万 and 億 never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`).
532
+ * Only the ja short forms (`compact` / `number` / `currency`, no `valueFormatter`) have units to align;
533
+ * any other format — and an axis whose largest tick is under 1万 — keeps `resolveAxisFormatter`'s output as it is.
534
+ */
535
+ function resolveAxisTickFormatter(
536
+ valueFormatter: ValueFormatter | undefined,
537
+ format: ValueFormat | undefined,
538
+ locale: string = DEFAULT_LOCALE,
539
+ ): (top: number) => ValueFormatter {
540
+ const base = resolveAxisFormatter(valueFormatter, format, locale)
541
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
542
+ const aligns =
543
+ !valueFormatter && locale.toLowerCase().startsWith("ja") && (spec.type === "compact" || spec.type === "number" || spec.type === "currency")
544
+ if (!aligns) return () => base
545
+ const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
546
+ return (top) => {
547
+ const unit = JA_UNITS.find((u) => Math.abs(top) >= u.size)
548
+ if (!unit) return base
549
+ return (value) => {
550
+ const text = base(value)
551
+ if (value === 0 || !Number.isFinite(value)) return text
552
+ const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.char}`
553
+ return text.replace(JA_NUMBER_TOKEN_RE, () => scaled)
554
+ }
555
+ }
556
+ }
557
+
308
558
  /**
309
559
  * A data cell as a number, or `null` for a gap. Numeric strings count — SQL
310
560
  * `DECIMAL` / `BIGINT` columns usually arrive as strings.
@@ -324,6 +574,222 @@ function clamp(value: number, min: number, max: number): number {
324
574
  return Math.min(max, Math.max(min, value))
325
575
  }
326
576
 
577
+ /* ------------------------------------------------------------ aggregation */
578
+
579
+ /** How many categories a chart colours individually; the rest fold into「その他」. */
580
+ const MAX_CHART_SERIES = 5
581
+
582
+ /** The series name the folded categories get. */
583
+ const OTHER_SERIES_LABEL = "その他"
584
+
585
+ interface AggregatedItems<Item extends { name: string; value: number }> {
586
+ /** The `n` largest items, in their given order. All items when there are `n` or fewer. */
587
+ top: Item[]
588
+ /** The items folded into `other`, in their given order. */
589
+ rest: Item[]
590
+ /** The folded remainder, or `null` when nothing was folded. */
591
+ other: { name: string; value: number } | null
592
+ }
593
+
594
+ /**
595
+ * Keep the `n` largest items (by value; ties keep the earlier one) in their
596
+ * given order and fold the rest into one `otherLabel` item. Shared by every
597
+ * chart that caps its categories (Area / Line / Bar series, Donut slices,
598
+ * BarList rows).
599
+ */
600
+ function aggregateTopN<Item extends { name: string; value: number }>(
601
+ items: readonly Item[],
602
+ n: number = MAX_CHART_SERIES,
603
+ otherLabel: string = OTHER_SERIES_LABEL,
604
+ ): AggregatedItems<Item> {
605
+ if (items.length <= n) return { top: [...items], rest: [], other: null }
606
+ const ranked = items
607
+ .map((item, i) => ({ item, i }))
608
+ .sort((a, b) => b.item.value - a.item.value || a.i - b.i)
609
+ const keep = new Set(ranked.slice(0, n).map((r) => r.i))
610
+ const top = items.filter((_, i) => keep.has(i))
611
+ const rest = items.filter((_, i) => !keep.has(i))
612
+ return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
613
+ }
614
+
615
+ interface AggregatedSeries {
616
+ /** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
617
+ data: Record<string, unknown>[]
618
+ /** Series to draw: the kept categories in their given order, then `otherCategory`. */
619
+ categories: string[]
620
+ /** The folded series' name, or `null`. */
621
+ otherCategory: string | null
622
+ }
623
+
624
+ /**
625
+ * Cap a cartesian chart at `n` series: rank the categories by the sum of their
626
+ * values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
627
+ */
628
+ function aggregateSeries(
629
+ data: readonly Record<string, unknown>[],
630
+ categories: readonly string[],
631
+ n: number = MAX_CHART_SERIES,
632
+ otherLabel: string = OTHER_SERIES_LABEL,
633
+ ): AggregatedSeries {
634
+ const totals = categories.map((name) => ({
635
+ name,
636
+ value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
637
+ }))
638
+ const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
639
+ if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
640
+ const folded = rest.map((item) => item.name)
641
+ return {
642
+ data: data.map((row) => {
643
+ let sum: number | null = null
644
+ for (const name of folded) {
645
+ const v = toChartNumber(row[name])
646
+ if (v !== null) sum = (sum ?? 0) + v
647
+ }
648
+ return { ...row, [other.name]: sum }
649
+ }),
650
+ categories: [...top.map((item) => item.name), other.name],
651
+ otherCategory: other.name,
652
+ }
653
+ }
654
+
655
+ /**
656
+ * `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
657
+ * at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
658
+ */
659
+ function aggregateSeriesKeeping(
660
+ data: readonly Record<string, unknown>[],
661
+ categories: readonly string[],
662
+ keep: string | undefined,
663
+ n: number = MAX_CHART_SERIES,
664
+ ): AggregatedSeries {
665
+ if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n)
666
+ const aggregated = aggregateSeries(
667
+ data,
668
+ categories.filter((c) => c !== keep),
669
+ n,
670
+ )
671
+ return { ...aggregated, categories: [...aggregated.categories, keep] }
672
+ }
673
+
674
+ /**
675
+ * `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
676
+ * builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
677
+ * so a main series keeps its colour whether or not a comparison is drawn.
678
+ */
679
+ function seriesColorsWithComparison(
680
+ categories: readonly string[],
681
+ colors: ChartColors | undefined,
682
+ otherColor: string,
683
+ otherCategory: string | null,
684
+ allCategories: readonly string[],
685
+ comparison: string | undefined,
686
+ ): string[] {
687
+ if (comparison === undefined || !categories.includes(comparison)) {
688
+ return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
689
+ }
690
+ const main = categories.filter((c) => c !== comparison)
691
+ const mainColors = seriesColorsFor(
692
+ main,
693
+ colors,
694
+ otherColor,
695
+ otherCategory,
696
+ allCategories.filter((c) => c !== comparison),
697
+ )
698
+ return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
699
+ }
700
+
701
+ /**
702
+ * Colour per drawn series: the record's token for that category, else the
703
+ * array's token at the category's position in `allCategories` (cycled), else
704
+ * the token palette by drawn position. `otherCategory` — and a category the
705
+ * data itself names「その他」(`OTHER_SERIES_LABEL`) — always gets `otherColor`.
706
+ */
707
+ function seriesColorsFor(
708
+ categories: readonly string[],
709
+ colors: ChartColors | undefined,
710
+ otherColor: string,
711
+ otherCategory: string | null = null,
712
+ allCategories: readonly string[] = categories,
713
+ ): string[] {
714
+ const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
715
+ const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
716
+ return categories.map((category, i) => {
717
+ if ((otherCategory !== null && category === otherCategory) || category === OTHER_SERIES_LABEL) return otherColor
718
+ const fromRecord = record?.[category]
719
+ if (fromRecord) return fromRecord
720
+ if (list && list.length > 0) {
721
+ const at = allCategories.indexOf(category)
722
+ return list[(at === -1 ? i : at) % list.length]!
723
+ }
724
+ return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
725
+ })
726
+ }
727
+
728
+ /* ------------------------------------------------------------------ Donut */
729
+
730
+ /** One drawn donut slice, largest first. */
731
+ interface DonutSlice {
732
+ name: string
733
+ /** Negative and missing values count as 0. */
734
+ value: number
735
+ /** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
736
+ color: string
737
+ /** The folded「その他」slice. */
738
+ isOther: boolean
739
+ /** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
740
+ row: Record<string, unknown>
741
+ }
742
+
743
+ interface DonutSlicesConfig {
744
+ /** Label column. */
745
+ index: string
746
+ /** Value column. */
747
+ value: string
748
+ /** Slice colours by rank (cycled). Default: the token palette in order. */
749
+ colors?: readonly ChartSeriesColor[]
750
+ /** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
751
+ maxSlices?: number
752
+ /** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
753
+ otherColor: string
754
+ otherLabel?: string
755
+ }
756
+
757
+ /**
758
+ * Donut slices: sorted by value (largest first, ties keep input order), the
759
+ * `maxSlices` largest kept and coloured by rank in fixed token order, the rest
760
+ * summed into one「その他」slice in `otherColor`.
761
+ */
762
+ function donutSlices(
763
+ data: readonly Record<string, unknown>[],
764
+ { index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = OTHER_SERIES_LABEL }: DonutSlicesConfig,
765
+ ): DonutSlice[] {
766
+ const items = data
767
+ .map((row, i) => {
768
+ const n = toChartNumber(row[value])
769
+ return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
770
+ })
771
+ .sort((a, b) => b.value - a.value || a.i - b.i)
772
+ const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
773
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
774
+ const slices: DonutSlice[] = top.map((item, rank) => ({
775
+ name: item.name,
776
+ value: item.value,
777
+ color: palette[rank % palette.length]!,
778
+ isOther: false,
779
+ row: item.row,
780
+ }))
781
+ if (other) {
782
+ slices.push({
783
+ name: other.name,
784
+ value: other.value,
785
+ color: otherColor,
786
+ isOther: true,
787
+ row: { [index]: other.name, [value]: other.value },
788
+ })
789
+ }
790
+ return slices
791
+ }
792
+
327
793
  /* ---------------------------------------------------------------- BarList */
328
794
 
329
795
  type BarListSortOrder = "ascending" | "descending" | "none"
@@ -336,6 +802,78 @@ function sortBarListData<T extends { value: number }>(data: readonly T[], sortOr
336
802
  return rows
337
803
  }
338
804
 
805
+ /** BarList-only settings. */
806
+ interface BarListOptions {
807
+ /** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
808
+ sortOrder?: BarListSortOrder
809
+ /** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
810
+ maxItems?: number
811
+ /** まとめた行のラベル。既定「その他」。 */
812
+ otherLabel?: string
813
+ /** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
814
+ exclude?: readonly string[]
815
+ /** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
816
+ showShare?: boolean
817
+ }
818
+
819
+ /** One drawn BarList row. */
820
+ interface BarListRow<Row = Record<string, unknown>> {
821
+ /** React key: the row's `key`, else its name (`"__other"` for the folded row). */
822
+ key: string
823
+ name: string
824
+ value: number
825
+ /** Only for real rows; the folded row never links. */
826
+ href?: string
827
+ /** Legacy per-row colour (`BarListItem.color`). */
828
+ color?: ChartColor
829
+ /** The folded「その他」row. */
830
+ isOther: boolean
831
+ /** The input row (`null` for the folded row). */
832
+ row: Row | null
833
+ }
834
+
835
+ interface BarListRowsConfig extends BarListOptions {
836
+ /** Name column. Default `"name"`. */
837
+ index?: string
838
+ /** Value column. Default `"value"`. */
839
+ category?: string
840
+ }
841
+
842
+ /**
843
+ * The rows a BarList draws: read name / value (numeric strings count, gaps are
844
+ * 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
845
+ * the folded remainder as one「その他」row. Rows named in `exclude` skip the
846
+ * ranking and are always added to「その他」.
847
+ */
848
+ function barListRows<Row extends object>(
849
+ data: readonly Row[],
850
+ { index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = OTHER_SERIES_LABEL, exclude }: BarListRowsConfig = {},
851
+ ): BarListRow<Row>[] {
852
+ const items = data.map((row): BarListRow<Row> => {
853
+ const cells = row as Record<string, unknown>
854
+ const name = String(cells[index] ?? "")
855
+ return {
856
+ key: typeof cells.key === "string" ? cells.key : name,
857
+ name,
858
+ value: toChartNumber(cells[category]) ?? 0,
859
+ href: typeof cells.href === "string" ? cells.href : undefined,
860
+ color: typeof cells.color === "string" ? cells.color : undefined,
861
+ isOther: false,
862
+ row,
863
+ }
864
+ })
865
+ const excluded = new Set(exclude ?? [])
866
+ const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
867
+ const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
868
+ const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
869
+ const rows = sortBarListData(top, sortOrder)
870
+ if (other || outside.length > 0) {
871
+ const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
872
+ rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
873
+ }
874
+ return rows
875
+ }
876
+
339
877
  /** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
340
878
  function barListWidths(values: readonly number[]): number[] {
341
879
  const max = Math.max(0, ...values)
@@ -343,6 +881,100 @@ function barListWidths(values: readonly number[]): number[] {
343
881
  return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
344
882
  }
345
883
 
884
+ /**
885
+ * How strongly the BarList bars are painted: every row the same tint of the bar
886
+ * colour (rank is the bar's length, not its weight). A tint over transparent, so
887
+ * it sits on the card in light and dark; it must stay visible against the card
888
+ * while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
889
+ */
890
+ const BAR_LIST_TINT = 45
891
+ /** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
892
+ const BAR_LIST_OTHER_TINT = 30
893
+
894
+ /**
895
+ * The fill of each BarList row: all real rows in the same tint of `color`
896
+ * (`BAR_LIST_TINT`), the folded「その他」row in a tint of `otherColor`
897
+ * (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
898
+ * ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
899
+ * for that row. A tint, not the solid token, so the label printed over the bar
900
+ * keeps its contrast.
901
+ */
902
+ function barListFills(
903
+ rows: readonly Pick<BarListRow, "isOther" | "color">[],
904
+ color: ChartColor,
905
+ otherColor: string,
906
+ ): string[] {
907
+ return rows.map((row) =>
908
+ row.isOther ? tintCss(otherColor, BAR_LIST_OTHER_TINT) : tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
909
+ )
910
+ }
911
+
912
+ /** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
913
+ function barListShareText(value: number, total: number): string {
914
+ const v = Number.isFinite(value) && value > 0 ? value : 0
915
+ if (total <= 0 || v === 0) return "0%"
916
+ const pct = (v / total) * 100
917
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
918
+ }
919
+
920
+ /**
921
+ * The text at the end of each BarList row: the formatted value and, with
922
+ * `showShare`, its share of the total of all drawn rows (including「その他」,
923
+ * so the shares are of the whole list): `value` and `share` apart (the share is
924
+ * drawn muted), `text` as one string (「¥8,240万 · 43%」).
925
+ */
926
+ function barListValueTexts(
927
+ values: readonly number[],
928
+ formatter: ValueFormatter,
929
+ showShare = false,
930
+ ): { value: string; share?: string; text: string }[] {
931
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
932
+ return values.map((v) => {
933
+ const value = formatter(v)
934
+ if (!showShare) return { value, text: value }
935
+ const share = barListShareText(v, total)
936
+ return { value, share, text: `${value} · ${share}` }
937
+ })
938
+ }
939
+
940
+ /* -------------------------------------------------------------- DataTable */
941
+
942
+ /** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
943
+ interface ChartDataTable {
944
+ /** 表の見出し(`<caption>`)。 */
945
+ caption?: string
946
+ /** 列見出し。先頭がラベル列。 */
947
+ columns: string[]
948
+ /** 行。セルは書式済みの文字列。 */
949
+ rows: string[][]
950
+ }
951
+
952
+ /**
953
+ * The chart's numbers as a table, for screen readers: one row per data row, the
954
+ * `index` cell then each category through `formatter` (gaps → `—`). `labels`
955
+ * renames column keys for the header (`{ sessions: "セッション" }`); `indexName` is the first column's header when `labels` has none for `index` (e.g. 「項目」, instead of the raw key).
956
+ */
957
+ function chartDataTable(
958
+ data: readonly Record<string, unknown>[],
959
+ index: string,
960
+ categories: readonly string[],
961
+ formatter: ValueFormatter,
962
+ labels?: Readonly<Record<string, string>>,
963
+ indexName?: string,
964
+ ): ChartDataTable {
965
+ const label = (key: string) => labels?.[key] ?? key
966
+ return {
967
+ columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
968
+ rows: data.map((row) => [
969
+ String(row[index] ?? ""),
970
+ ...categories.map((key) => {
971
+ const n = toChartNumber(row[key])
972
+ return n === null ? EMPTY_VALUE : formatter(n)
973
+ }),
974
+ ]),
975
+ }
976
+ }
977
+
346
978
  /* ------------------------------------------------------------ CategoryBar */
347
979
 
348
980
  interface CategoryBarSegment {
@@ -377,9 +1009,11 @@ interface CategoryBarLabel {
377
1009
  * Tick labels under the bar: `0` at the start, then the running total at each
378
1010
  * segment's end. A label closer than `minGap` percent to the one before is
379
1011
  * dropped so narrow segments don't print on top of each other — except the
380
- * last one (the total), which replaces its neighbour instead.
1012
+ * last one (the total), which replaces its neighbour instead. With a
1013
+ * `markerPosition`, an inner label closer than `minGap` to the marker is dropped
1014
+ * too — the marker sits right under it and the two read as one crowded spot.
381
1015
  */
382
- function categoryBarLabels(values: readonly number[], minGap = 8): CategoryBarLabel[] {
1016
+ function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
383
1017
  const segments = categoryBarSegments(values).filter((s) => s.width > 0)
384
1018
  if (segments.length === 0) return []
385
1019
  const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
@@ -389,7 +1023,46 @@ function categoryBarLabels(values: readonly number[], minGap = 8): CategoryBarLa
389
1023
  if (label.position - prev.position >= minGap) labels.push(label)
390
1024
  else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
391
1025
  })
392
- return labels
1026
+ if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
1027
+ return labels.filter(
1028
+ (label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
1029
+ )
1030
+ }
1031
+
1032
+ /**
1033
+ * `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
1034
+ * (`texts`, same order): a label that would touch the one before is dropped — except the last (the
1035
+ * total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
1036
+ * edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
1037
+ * the rest 7 px at 12 px type).
1038
+ */
1039
+ function categoryBarFitLabels(
1040
+ labels: readonly CategoryBarLabel[],
1041
+ texts: readonly string[],
1042
+ width: number,
1043
+ gap = 8,
1044
+ ): CategoryBarLabel[] {
1045
+ const textWidth = (text: string) => {
1046
+ let w = 0
1047
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
1048
+ return w
1049
+ }
1050
+ const extent = (label: CategoryBarLabel, text: string): [number, number] => {
1051
+ const w = textWidth(text)
1052
+ if (label.position <= 0) return [0, w]
1053
+ if (label.position >= 100) return [width - w, width]
1054
+ const center = (label.position / 100) * width
1055
+ return [center - w / 2, center + w / 2]
1056
+ }
1057
+ const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
1058
+ labels.forEach((label, i) => {
1059
+ const here = extent(label, texts[i] ?? "")
1060
+ const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
1061
+ if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
1062
+ else if (touches()) return
1063
+ kept.push({ label, extent: here })
1064
+ })
1065
+ return kept.map((k) => k.label)
393
1066
  }
394
1067
 
395
1068
  /** Marker position in percent of the bar, clamped to its ends. */
@@ -434,7 +1107,63 @@ function progressCircleGeometry(
434
1107
  return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
435
1108
  }
436
1109
 
437
- /* ---------- inlined from src/components/chart-options.ts (internal to @squadbase/vantage) ---------- */
1110
+ /* ---------------------------------------------------------------- summary */
1111
+
1112
+ interface ChartSummaryInput {
1113
+ data: readonly Record<string, unknown>[]
1114
+ /** The x-axis key. */
1115
+ index: string
1116
+ /** Series keys; the first one is described. */
1117
+ categories: readonly string[]
1118
+ /** Title of the chart, put in front when given. */
1119
+ title?: string
1120
+ /** Same as the chart's `format` (default `"compact"`). */
1121
+ format?: ValueFormat
1122
+ /** Wins over `format`. */
1123
+ valueFormatter?: ValueFormatter
1124
+ }
1125
+
1126
+ /**
1127
+ * One-sentence summary built from the rows, for `summary="auto"`:
1128
+ * 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」. The direction is
1129
+ * computed from the last two non-empty points of the first series — never
1130
+ * written by hand, so it cannot contradict the data. `undefined` when there is
1131
+ * no usable point.
1132
+ */
1133
+ function buildChartSummary(input: ChartSummaryInput): string | undefined {
1134
+ const key = input.categories[0]
1135
+ if (key === undefined) return undefined
1136
+ const points: { label: string; value: number }[] = []
1137
+ for (const row of input.data) {
1138
+ const raw = row[key]
1139
+ const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
1140
+ if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
1141
+ }
1142
+ const latest = points[points.length - 1]
1143
+ if (!latest) return undefined
1144
+ const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact")
1145
+ const prev = points[points.length - 2]
1146
+ const direction = !prev ? "" : latest.value > prev.value ? "、前の点より増加" : latest.value < prev.value ? "、前の点より減少" : "、前の点と横ばい"
1147
+ const head = input.title ? `${input.title}: ` : ""
1148
+ return `${head}最新 ${latest.label} は ${text(latest.value)}${direction}`
1149
+ }
1150
+
1151
+ /**
1152
+ * `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」 from the slices
1153
+ * (largest first). `undefined` when there is nothing to describe.
1154
+ */
1155
+ function buildShareSummary(
1156
+ slices: readonly { name: string; value: number }[],
1157
+ title?: string,
1158
+ ): string | undefined {
1159
+ const total = slices.reduce((sum, s) => sum + s.value, 0)
1160
+ const top = slices[0]
1161
+ if (!top || total <= 0) return undefined
1162
+ const share = `${Math.round((top.value / total) * 1000) / 10}%`
1163
+ return `${title ? `${title}: ` : ""}最大は ${top.name}(${share})`
1164
+ }
1165
+
1166
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-options.ts (internal to @squadbase/vantage) ---------- */
438
1167
 
439
1168
  type CartesianChartKind = "area" | "bar" | "line"
440
1169
  type CartesianStackType = "default" | "stacked" | "percent"
@@ -442,18 +1171,107 @@ type CartesianCurveType = "linear" | "smooth" | "step"
442
1171
  type AreaFill = "gradient" | "solid" | "none"
443
1172
  type BarLayout = "horizontal" | "vertical"
444
1173
 
1174
+ /** AreaChart-only settings. */
1175
+ interface AreaChartOptions {
1176
+ /** `"stacked"` は積み上げ、`"percent"` は各点の合計を 100% にした積み上げ。既定 `"default"`。 */
1177
+ type?: CartesianStackType
1178
+ /** 線の形。既定 `"linear"`。 */
1179
+ curveType?: CartesianCurveType
1180
+ /** 面の塗り。既定 `"gradient"`。 */
1181
+ fill?: AreaFill
1182
+ /** 値の欠けた点(`null` など)をまたいで線をつなぐ。既定 `false`。 */
1183
+ connectNulls?: boolean
1184
+ }
1185
+
1186
+ /** LineChart-only settings. */
1187
+ interface LineChartOptions {
1188
+ /** 線の形。既定 `"linear"`。 */
1189
+ curveType?: CartesianCurveType
1190
+ /** 値の欠けた点(`null` など)をまたいで線をつなぐ。既定 `false`。 */
1191
+ connectNulls?: boolean
1192
+ /** 値軸を 0 からではなくデータの範囲に合わせる。既定 `false`(0 起点)。最小の目盛ラベルは先頭の x ラベルと重なるので出さない(グリッド線は残る)。 */
1193
+ fitToData?: boolean
1194
+ /**
1195
+ * 目標線(`target`)のラベルの置き場所。`"start"`(既定)は線の左端の上(最大・最新の強調と近いときは下)。
1196
+ * `"end"` は線の右端の上。`"legend"` は凡例だけに出し、線の上には出さない(線の周りが混み合うとき)。
1197
+ * 目標の呼び名は、どれを選んでも凡例に出る。
1198
+ */
1199
+ targetLabelPosition?: LineTargetLabelPosition
1200
+ }
1201
+
1202
+ /** Where a line chart prints its target label: at the line's left end, its right end, or in the legend only. */
1203
+ type LineTargetLabelPosition = "start" | "end" | "legend"
1204
+
1205
+ /** BarChart-only settings. */
1206
+ interface BarChartOptions<T extends Record<string, unknown> = Record<string, unknown>> {
1207
+ /** `"stacked"` は積み上げ、`"percent"` は各カテゴリの合計を 100% にした積み上げ。既定 `"default"`(横並び)。 */
1208
+ type?: CartesianStackType
1209
+ /**
1210
+ * 棒の向き。既定 `"horizontal"`(カテゴリが横に並ぶ縦棒)。`"vertical"` はカテゴリを
1211
+ * 縦に並べた横棒で、ラベルの長いランキングに向く(先頭の行が一番上)。
1212
+ */
1213
+ layout?: BarLayout
1214
+ /** カテゴリ間の隙間(`"20%"` や px)。省略時は ECharts の既定。 */
1215
+ barCategoryGap?: string | number
1216
+ /**
1217
+ * 値が 0 の棒に「0」の値ラベルを付ける。棒が描かれない 0 が「データなし」に見えるのを防ぐ
1218
+ * (在庫 0・件数 0 など)。積み上げでは付けない。0 以外の棒の見た目は変わらない。既定 `true`。
1219
+ */
1220
+ showZeroValues?: boolean
1221
+ /**
1222
+ * 棒ごとの目標値が入った `data` の列名(行ごとの目標。店舗別の月次目標など)。各棒に短い目標マーカーを
1223
+ * 引き、ツールチップに「目標 … (達成率 …%)」を足す。凡例に目標の呼び名(`targetLabel`、既定「目標」)が出る。
1224
+ * 1 系列の棒と積み上げ(達成率は合計に対して)で使える。横並びの複数系列と 100% 積み上げでは描かない。
1225
+ * 値が欠けた(null・0 以下の)行はマーカーを引かない。
1226
+ *
1227
+ * 優先順位: `targetKey` を渡すと 1 本の目標線 `target` は描かない(`targetLabel` はマーカーの呼び名として使う)。
1228
+ * 値による色分け `thresholds` とは併用できる(色は棒、マーカーは目標)。値軸は最大の目標を含む。
1229
+ * 例: `barOptions={{ targetKey: "月次目標" }}`
1230
+ */
1231
+ targetKey?: NumericKeys<T>
1232
+ /**
1233
+ * 横棒(`layout: "vertical"`)の 1 系列で伝えたい 1 本。`index` の値で渡す(例 `"東京店"`)。
1234
+ * 横棒は淡い色(`--chart-1` の薄い塗り)が既定で、この 1 本だけ濃い色(系列色そのまま)になる。省略すると全部が淡い色。
1235
+ * 縦棒・複数系列・積み上げでは効かない(色は変わらない)。意味色の `thresholds` に当たった棒はそちらの色が優先。
1236
+ * 例: `barOptions={{ layout: "vertical", highlight: "東京店" }}`
1237
+ */
1238
+ highlight?: string | number
1239
+ }
1240
+
445
1241
  /** Props every cartesian typed chart (Area / Bar / Line) shares. */
446
- interface CartesianChartBaseProps {
447
- /** 行の配列。1 行 = x 軸の 1 点。数値の列は number か数値文字列(SQL の DECIMAL など)。 */
448
- data: Record<string, unknown>[]
449
- /** x 軸(カテゴリ軸)に使う列名。 */
450
- index: string
451
- /** 系列として描く列名。並び順が凡例と配色の順になる。 */
452
- categories: string[]
453
- /** 系列色。`"chart-1"`〜`"chart-5"` か CSS カラー。省略時はテーマのトークン順。足りなければ繰り返す。 */
454
- colors?: ChartColor[]
455
- /** 軸目盛りとツールチップの数値の書式。 */
456
- valueFormatter?: ValueFormatter
1242
+ interface CartesianChartBaseProps<T extends Record<string, unknown> = Record<string, unknown>>
1243
+ extends ChartCommonProps<T> {
1244
+ /**
1245
+ * 最大値と最新値に値ラベルを付ける(最初の系列だけ・系列が 2 つ以下のときだけ・最大 2 つ)。
1246
+ * 100% 積み上げの面グラフでは、最初の系列(一番下の帯)の最初と最新の比率(「24%」「31%」)を帯の中に付ける。
1247
+ * 既定は Line / Area が `"auto"`、Bar は `index` が日付・年月・年のときだけ `"auto"`。
1248
+ */
1249
+ highlight?: ChartHighlight
1250
+ /**
1251
+ * ここから先は確定前(速報)の点。index の値で渡す(例 `"2026-09"`)。薄い色・点線(棒は薄い塗りと破線の縁)で
1252
+ * 描き、凡例・ツールチップに `provisionalLabel` を出す。線・面は確定の最終点とつなぐ。`forecast`(予測)とは別物。
1253
+ * 例: `provisionalFrom="2026-09"`
1254
+ */
1255
+ provisionalFrom?: string | number
1256
+ /** 速報の呼び名(凡例・ツールチップ)。既定「速報」。例: `provisionalLabel="暫定"` */
1257
+ provisionalLabel?: string
1258
+ /**
1259
+ * グラフが言っていることの 1 文要約(自由文)。`"auto"` なら data から機械的に組む
1260
+ * (「<見出し>: 最新 <index値> は <値>、前の点より増加/減少」。向きは最新 2 点の値で決まる)。
1261
+ * 増減の向きを文に書くなら `"auto"` を使うか data から作る — 手書きの向きは data とずれて誤る。
1262
+ * 省略時は要約なし(既存どおり)。例: `summary="auto"`
1263
+ */
1264
+ summary?: string | "auto"
1265
+ /** 目標値。点線の水平線で示し、値軸は必ずこの値を含む。棒ごとの目標(`barOptions.targetKey`)を渡したときは描かない。 */
1266
+ target?: number
1267
+ /** 目標線のラベル。既定「目標 <書式化した値>」。`barOptions.targetKey` のときはマーカーの呼び名(既定「目標」)。 */
1268
+ targetLabel?: string
1269
+ /**
1270
+ * 任意の位置への注記(縦の線、または `to` で区間の帯)。折れ線・面・縦の棒(`barOptions.layout` が既定のとき)で使え、
1271
+ * 横棒では描かない。`at` / `to` は `index` の値。色は中立で、ツールチップにも文言が出る。例:
1272
+ * `annotations={[{ at: "2026-04", label: "料金改定" }, { at: "2026-08", to: "2026-09", label: "キャンペーン" }]}`
1273
+ */
1274
+ annotations?: ChartAnnotation[]
457
1275
  /** 凡例を出す。既定 `true`。 */
458
1276
  showLegend?: boolean
459
1277
  /** ホバー時のツールチップを出す。既定 `true`。 */
@@ -466,9 +1284,18 @@ interface CartesianChartBaseProps {
466
1284
  startEndOnly?: boolean
467
1285
  /** y 軸ラベルの幅(px)。並べた複数グラフのプロット領域を揃えたいときに固定する。 */
468
1286
  yAxisWidth?: number
1287
+ /**
1288
+ * 値軸の下限。Bar / Area は常に 0 起点なので、0 以下の値だけ有効(負の値の下に余白を取る。正の値は無視)。
1289
+ * Line は指定した値から始める。データが下限を下回るときは軸を広げる(切り詰めない)。
1290
+ * 並べて比べる複数のグラフには同じ値を渡して軸をそろえる。
1291
+ */
469
1292
  minValue?: number
1293
+ /**
1294
+ * 値軸の上限(横棒は横軸)。データが上限を超えるときは軸を広げる(切り詰めない)。
1295
+ * 並べて比べる複数のグラフには同じ値を渡して軸をそろえる。
1296
+ */
470
1297
  maxValue?: number
471
- /** 値軸を 0 からではなくデータの範囲に合わせる。 */
1298
+ /** @deprecated `lineOptions.fitToData` を使う。Bar / Area では無視される(常に 0 起点)。 */
472
1299
  autoMinValue?: boolean
473
1300
  /** `false` で値軸の目盛りを整数に限る。 */
474
1301
  allowDecimals?: boolean
@@ -479,11 +1306,8 @@ interface CartesianChartBaseProps {
479
1306
  * 足して渡し、同じ点をもう一度クリックすると `null`。渡すと選択以外が薄くなる。
480
1307
  */
481
1308
  onValueChange?: (value: ChartEventPayload) => void
482
- /** 高さ。数値は px。省略時は `h-80`(320px)で、`className` の高さクラスが勝つ。 */
483
- height?: string | number
1309
+ /** @deprecated `isLoading` を使う。 */
484
1310
  loading?: boolean
485
- ariaLabel?: string
486
- className?: string
487
1311
  }
488
1312
 
489
1313
  /** The point a user clicked, used to dim everything else. */
@@ -492,6 +1316,17 @@ interface ChartActivePoint {
492
1316
  index: number
493
1317
  }
494
1318
 
1319
+ /** The forecast as the builder takes it: untyped keys, already validated by the component's props. */
1320
+ type CartesianForecastConfig = Omit<ChartForecast, "category"> & { category?: string }
1321
+
1322
+ /** The comparison series as the builder takes it (see `ChartComparison`); `label` names the baseline for `vs: "custom"`. */
1323
+ interface CartesianComparisonConfig {
1324
+ /** One of `categories`; drawn as a thin muted line, outside the `--chart-*` order. */
1325
+ category: string
1326
+ vs: ComparisonKind
1327
+ label?: string
1328
+ }
1329
+
495
1330
  interface CartesianChartConfig {
496
1331
  kind: CartesianChartKind
497
1332
  data: readonly Record<string, unknown>[]
@@ -499,7 +1334,23 @@ interface CartesianChartConfig {
499
1334
  categories: readonly string[]
500
1335
  /** Resolved series colours, by category position. `""`/missing → theme palette. */
501
1336
  palette: readonly string[]
1337
+ /** Display names for `index` values and category names (axis, legend, tooltip). Missing keys show as they are. */
1338
+ labels?: Readonly<Record<string, string>>
1339
+ /** Bar only, not stacked: colour each bar by its value (first matching rule wins). With several series (side by side) a bar that matches takes the tone as its fill and keeps its series colour as the edge. */
1340
+ thresholds?: readonly ChartThreshold[]
1341
+ /** Resolved colour of each tone (`resolveChartColors`); a tone missing here keeps the series colour. */
1342
+ toneColors?: Partial<Record<ChartTone, string>>
1343
+ /** Tooltip values. */
502
1344
  valueFormatter: (value: number) => string
1345
+ /** Value-axis ticks, highlight and target labels (short form, e.g. ¥1億). Default `valueFormatter`. */
1346
+ axisFormatter?: (value: number) => string
1347
+ /**
1348
+ * The value-axis tick formatter for an axis whose largest tick is the given number (`resolveAxisTickFormatter`):
1349
+ * all ticks read in one unit (¥0.5億 / ¥1億). Default: `axisFormatter` for every tick.
1350
+ */
1351
+ axisTicks?: (top: number) => (value: number) => string
1352
+ /** Locale of the time-axis labels. Default `"ja-JP"`. */
1353
+ locale?: string
503
1354
  type?: CartesianStackType
504
1355
  /** Bar only. `"vertical"` lays the categories down the y axis (horizontal bars). */
505
1356
  layout?: BarLayout
@@ -513,9 +1364,14 @@ interface CartesianChartConfig {
513
1364
  showYAxis?: boolean
514
1365
  startEndOnly?: boolean
515
1366
  yAxisWidth?: number
1367
+ /** Bar / Area: only a value ≤ 0 takes effect (they start at 0). Line: the axis' start. The axis widens to the data. */
516
1368
  minValue?: number
1369
+ /** The axis' top; the axis widens to the data. */
517
1370
  maxValue?: number
1371
+ /** Line only: legacy alias of `fitToData`. */
518
1372
  autoMinValue?: boolean
1373
+ /** Line only: let the value axis follow the data instead of starting at 0. */
1374
+ fitToData?: boolean
519
1375
  allowDecimals?: boolean
520
1376
  xAxisLabel?: string
521
1377
  yAxisLabel?: string
@@ -523,8 +1379,313 @@ interface CartesianChartConfig {
523
1379
  /** Always draw the line/area points (needed to click them). */
524
1380
  showDots?: boolean
525
1381
  active?: ChartActivePoint | null
1382
+ /** Default: `"auto"` for line/area, for bar only when `index` holds dates. */
1383
+ highlight?: ChartHighlight
1384
+ /** Bar only: the index value of the one horizontal bar drawn in the full colour (`BarChartOptions.highlight`). */
1385
+ barHighlight?: string | number
1386
+ target?: number
1387
+ targetLabel?: string
1388
+ /** Line only: where the target label sits (see `LineChartOptions.targetLabelPosition`). Default `"start"`. */
1389
+ targetLabelPosition?: LineTargetLabelPosition
1390
+ /** Bar only: a data column holding each bar's target (see `BarChartOptions.targetKey`). */
1391
+ targetKey?: string
1392
+ /** Notes at an index value or over a range (vertical bars, line, area). */
1393
+ annotations?: readonly ChartAnnotation[]
1394
+ /** Bar only, not stacked: label bars whose value is 0 with「0」(default true). */
1395
+ showZeroValues?: boolean
1396
+ /** Line / Area only; ignored for bar and for percent stacking. */
1397
+ forecast?: CartesianForecastConfig
1398
+ /**
1399
+ * Line / Area only; ignored for bar and for percent stacking. The series `category` is drawn as a muted 1.5px solid line
1400
+ * (no markers, no fill, outside a stack) and the first other series' tooltip row gets its difference from it.
1401
+ */
1402
+ comparison?: CartesianComparisonConfig
1403
+ /** The `format` of the values, for the comparison's difference in the tooltip (percent → points). Default: relative change. */
1404
+ comparisonFormat?: ValueFormat
1405
+ /** Index value of the first provisional point (see `CartesianChartBaseProps.provisionalFrom`). */
1406
+ provisionalFrom?: string | number
1407
+ provisionalLabel?: string
1408
+ /** The PNG action buttons are shown (top right): the legend keeps clear of them. */
1409
+ reserveActions?: boolean
1410
+ /** Colour of the target / forecast guide lines (resolved muted text). */
1411
+ guideColor?: string
1412
+ /**
1413
+ * The surface the chart sits on (resolved). Highlight labels get it as a
1414
+ * backdrop, so a guide line passing behind them never runs through the text.
1415
+ */
1416
+ labelBackground?: string
1417
+ /** Colour of the highlight labels (resolved foreground). */
1418
+ labelColor?: string
1419
+ /**
1420
+ * The plot's width in px, when known. Sets how many time labels fit, how many value ticks a
1421
+ * horizontal bar chart carries, and drops the max highlight when it would print over the latest one.
1422
+ */
1423
+ plotWidth?: number
1424
+ /** The plot's height in px (the `height` prop), when known: under 200 the value axis carries 3 intervals, else 4–5. */
1425
+ plotHeight?: number
1426
+ reducedMotion?: boolean
1427
+ /** Deep-merged onto the generated option last. */
1428
+ chartOptions?: EChartsOption
526
1429
  }
527
1430
 
1431
+ /* ----------------------------------------------------------------- motion */
1432
+
1433
+ /**
1434
+ * The typed charts' motion: no entrance animation, a short ease on updates so a
1435
+ * filter change reads as a change. Reduced motion turns animation off.
1436
+ */
1437
+ function chartMotion(reducedMotion: boolean): EChartsOption {
1438
+ if (reducedMotion) return { animation: false }
1439
+ return { animation: true, animationDuration: 0, animationDurationUpdate: 300, animationEasingUpdate: "cubicOut" }
1440
+ }
1441
+
1442
+ /* ----------------------------------------------------------------- merge */
1443
+
1444
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
1445
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false
1446
+ const proto = Object.getPrototypeOf(value)
1447
+ return proto === Object.prototype || proto === null
1448
+ }
1449
+
1450
+ /**
1451
+ * Deep-merge `override` onto `base` without mutating either: plain objects merge
1452
+ * key by key, arrays merge by position (so `series: [{ … }]` tweaks the first
1453
+ * series), anything else in `override` replaces. `undefined` keeps the base.
1454
+ */
1455
+ function mergeChartOptions<T>(base: T, override: unknown): T {
1456
+ if (override === undefined) return base
1457
+ if (Array.isArray(override)) {
1458
+ if (!Array.isArray(base)) return override as T
1459
+ const length = Math.max(base.length, override.length)
1460
+ return Array.from({ length }, (_, i) => (i < override.length ? mergeChartOptions(base[i], override[i]) : base[i])) as T
1461
+ }
1462
+ if (isPlainRecord(override) && isPlainRecord(base)) {
1463
+ const out: Record<string, unknown> = { ...base }
1464
+ for (const key of Object.keys(override)) out[key] = mergeChartOptions(base[key], override[key])
1465
+ return out as T
1466
+ }
1467
+ return override as T
1468
+ }
1469
+
1470
+ /* -------------------------------------------------------------- highlight */
1471
+
1472
+ const TIME_INDEX_RE =
1473
+ /^\d{4}(?:[-/]\d{1,2}(?:[-/]\d{1,2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?)?)?$/
1474
+
1475
+ /**
1476
+ * Whether the x values look like time: ISO dates / date-times, `YYYY-MM`,
1477
+ * `YYYY`, or `Date` objects. Blank cells are ignored; nothing at all → `false`.
1478
+ */
1479
+ function isTimeIndex(values: readonly unknown[]): boolean {
1480
+ const present = values.filter((v) => v !== null && v !== undefined && v !== "")
1481
+ if (present.length === 0) return false
1482
+ return present.every((v) =>
1483
+ v instanceof Date ? !Number.isNaN(v.getTime()) : typeof v === "string" && TIME_INDEX_RE.test(v.trim()),
1484
+ )
1485
+ }
1486
+
1487
+ /* -------------------------------------------------------------- time axis */
1488
+
1489
+ type TimeGranularity = "year" | "month" | "day"
1490
+
1491
+ interface ParsedTime {
1492
+ year: number
1493
+ /** 1–12. */
1494
+ month: number
1495
+ day: number
1496
+ }
1497
+
1498
+ const TIME_PARTS_RE = /^(\d{4})(?:[-/](\d{1,2})(?:[-/](\d{1,2}))?)?$/
1499
+
1500
+ /**
1501
+ * The x values as calendar dates, with the finest granularity they carry — or
1502
+ * `null` when any value is not a plain year / month / date (date-times with a
1503
+ * clock part stay as they are: one label per hour would need its own format).
1504
+ */
1505
+ function parseTimeIndex(values: readonly unknown[]): { granularity: TimeGranularity; times: (ParsedTime | null)[] } | null {
1506
+ if (!isTimeIndex(values)) return null
1507
+ const ranks: readonly TimeGranularity[] = ["year", "month", "day"]
1508
+ let rank = 0
1509
+ const finer = (g: TimeGranularity) => {
1510
+ rank = Math.max(rank, ranks.indexOf(g))
1511
+ }
1512
+ const times: (ParsedTime | null)[] = []
1513
+ for (const v of values) {
1514
+ if (v === null || v === undefined || v === "") {
1515
+ times.push(null)
1516
+ continue
1517
+ }
1518
+ if (v instanceof Date) {
1519
+ if (v.getHours() !== 0 || v.getMinutes() !== 0 || v.getSeconds() !== 0) return null
1520
+ finer(v.getDate() === 1 ? "month" : "day")
1521
+ times.push({ year: v.getFullYear(), month: v.getMonth() + 1, day: v.getDate() })
1522
+ continue
1523
+ }
1524
+ const text = String(v).trim()
1525
+ // A trailing midnight (`2025-09-01T00:00:00Z`) is still a date; any other time of day is not.
1526
+ const date = text.replace(/[T ]00:00(?::00(?:\.0+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/, "")
1527
+ const m = TIME_PARTS_RE.exec(date)
1528
+ if (!m) return null
1529
+ finer(m[3] !== undefined ? "day" : m[2] !== undefined ? "month" : "year")
1530
+ times.push({ year: Number(m[1]), month: Number(m[2] ?? 1), day: Number(m[3] ?? 1) })
1531
+ }
1532
+ // Date objects on the 1st read as months only when every value falls on a 1st.
1533
+ if (rank === 1 && values.some((v) => v instanceof Date) && times.some((t) => t !== null && t.day !== 1)) rank = 2
1534
+ return { granularity: ranks[rank]!, times }
1535
+ }
1536
+
1537
+ const timeFormatCache = new Map<string, Intl.DateTimeFormat>()
1538
+
1539
+ function timeFormat(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {
1540
+ const key = `${locale}|${JSON.stringify(options)}`
1541
+ let format = timeFormatCache.get(key)
1542
+ if (!format) {
1543
+ format = new Intl.DateTimeFormat(locale, options)
1544
+ timeFormatCache.set(key, format)
1545
+ }
1546
+ return format
1547
+ }
1548
+
1549
+ const toDate = (t: ParsedTime) => new Date(t.year, t.month - 1, t.day)
1550
+
1551
+ /** How many x labels a time axis shows at most (the step is picked so the labels never crowd). */
1552
+ const TIME_AXIS_MAX_LABELS = 6
1553
+ /** Under this plot width (px) the axis, legend and labels switch to their compact form. */
1554
+ const NARROW_PLOT_WIDTH = 400
1555
+ /** The most x labels a narrow plot shows (a 262px plot reads 4 at most). */
1556
+ const NARROW_TIME_AXIS_MAX_LABELS = 4
1557
+
1558
+ /** Calendar-friendly label steps per granularity (every 3 months, every week …). */
1559
+ const TIME_AXIS_STEPS: Record<TimeGranularity, readonly number[]> = {
1560
+ year: [1, 2, 5, 10, 20, 50, 100],
1561
+ month: [1, 2, 3, 4, 6, 12, 24, 36, 60, 120],
1562
+ day: [1, 2, 7, 14, 28, 56, 91, 182, 364],
1563
+ }
1564
+
1565
+ /**
1566
+ * Every how many points a time axis prints a label: the smallest calendar step
1567
+ * (1, 2, 3, 4, 6, 12 months; 1, 2, 7, 14 days; …) that keeps the labels at or
1568
+ * under `maxLabels`. Deterministic, so the year-change label is never skipped by
1569
+ * ECharts' own overlap thinning. `null` when the values are not dates.
1570
+ */
1571
+ function timeAxisLabelStep(values: readonly unknown[], maxLabels: number = TIME_AXIS_MAX_LABELS): number | null {
1572
+ const parsed = parseTimeIndex(values)
1573
+ if (!parsed) return null
1574
+ const count = values.length
1575
+ const max = Math.max(1, maxLabels)
1576
+ const steps = TIME_AXIS_STEPS[parsed.granularity]
1577
+ return steps.find((step) => Math.ceil(count / step) <= max) ?? Math.ceil(count / max)
1578
+ }
1579
+
1580
+ /**
1581
+ * Category-axis labels for time-like x values, in `locale`: monthly data reads
1582
+ * `4月`, with the year (`2025年1月`) on the first shown label and on any shown
1583
+ * label whose year differs from the previous *shown* one; daily data reads
1584
+ * `4/1` (`2025/4/1` likewise); yearly data `2025年`. `shown(i)` says which
1585
+ * labels the axis prints (default: all) — hidden ones never carry the year.
1586
+ * `null` when the values are not dates — the axis then shows them as they are.
1587
+ */
1588
+ function timeAxisLabels(
1589
+ values: readonly unknown[],
1590
+ locale: string = DEFAULT_LOCALE,
1591
+ shown: (i: number) => boolean = () => true,
1592
+ ): string[] | null {
1593
+ const parsed = parseTimeIndex(values)
1594
+ if (!parsed) return null
1595
+ const { granularity, times } = parsed
1596
+ let prevYear: number | null = null
1597
+ return times.map((t, i) => {
1598
+ if (t === null) return String(values[i] ?? "")
1599
+ const visible = shown(i)
1600
+ const withYear = visible && (prevYear === null || t.year !== prevYear)
1601
+ if (visible) prevYear = t.year
1602
+ const options: Intl.DateTimeFormatOptions =
1603
+ granularity === "year"
1604
+ ? { year: "numeric" }
1605
+ : granularity === "month"
1606
+ ? withYear
1607
+ ? { year: "numeric", month: "short" }
1608
+ : { month: "short" }
1609
+ : withYear
1610
+ ? { year: "numeric", month: "numeric", day: "numeric" }
1611
+ : { month: "numeric", day: "numeric" }
1612
+ return timeFormat(locale, options).format(toDate(t))
1613
+ })
1614
+ }
1615
+
1616
+ /** The tooltip titles for time-like x values (`2025年9月`, `2025年9月1日`), or `null` when they are not dates. */
1617
+ function timeTooltipLabels(values: readonly unknown[], locale: string = DEFAULT_LOCALE): string[] | null {
1618
+ const parsed = parseTimeIndex(values)
1619
+ if (!parsed) return null
1620
+ const options: Intl.DateTimeFormatOptions =
1621
+ parsed.granularity === "year"
1622
+ ? { year: "numeric" }
1623
+ : parsed.granularity === "month"
1624
+ ? { year: "numeric", month: "long" }
1625
+ : { year: "numeric", month: "long", day: "numeric" }
1626
+ return parsed.times.map((t, i) => (t === null ? String(values[i] ?? "") : timeFormat(locale, options).format(toDate(t))))
1627
+ }
1628
+
1629
+ interface HighlightPoint {
1630
+ kind: "max" | "latest" | "start"
1631
+ index: number
1632
+ value: number
1633
+ }
1634
+
1635
+ /**
1636
+ * The points `highlight="auto"` labels on one series: the latest (last
1637
+ * non-null) point, and the maximum unless it *is* the latest or sits next to it
1638
+ * (`|i - latest| ≤ 1`, the labels would collide) — at most 2, max first.
1639
+ */
1640
+ function pickHighlightPoints(values: readonly (number | null)[]): HighlightPoint[] {
1641
+ let latest = -1
1642
+ for (let i = values.length - 1; i >= 0; i--) {
1643
+ if (values[i] !== null && values[i] !== undefined) {
1644
+ latest = i
1645
+ break
1646
+ }
1647
+ }
1648
+ if (latest === -1) return []
1649
+ const latestValue = values[latest]!
1650
+ let max = -1
1651
+ values.forEach((v, i) => {
1652
+ if (v !== null && v !== undefined && (max === -1 || v > values[max]!)) max = i
1653
+ })
1654
+ const latestPoint: HighlightPoint = { kind: "latest", index: latest, value: latestValue }
1655
+ if (max === -1 || max === latest || latestValue >= values[max]! || Math.abs(max - latest) <= 1) return [latestPoint]
1656
+ return [{ kind: "max", index: max, value: values[max]! }, latestPoint]
1657
+ }
1658
+
1659
+ /**
1660
+ * The points a 100% stacked area labels: the first and the latest (last
1661
+ * non-null) share of one band — "24% → 31%" is the claim such a chart makes.
1662
+ */
1663
+ function pickShareHighlightPoints(values: readonly (number | null)[]): HighlightPoint[] {
1664
+ const first = values.findIndex((v) => v !== null && v !== undefined)
1665
+ if (first === -1) return []
1666
+ let latest = first
1667
+ for (let i = values.length - 1; i > first; i--) {
1668
+ if (values[i] !== null && values[i] !== undefined) {
1669
+ latest = i
1670
+ break
1671
+ }
1672
+ }
1673
+ const latestPoint: HighlightPoint = { kind: "latest", index: latest, value: values[latest]! }
1674
+ return latest === first ? [latestPoint] : [{ kind: "start", index: first, value: values[first]! }, latestPoint]
1675
+ }
1676
+
1677
+ /** Whether a chart of `kind` labels its highlights by default. */
1678
+ function defaultChartHighlight(
1679
+ kind: CartesianChartKind,
1680
+ data: readonly Record<string, unknown>[],
1681
+ index: string,
1682
+ ): ChartHighlight {
1683
+ if (kind !== "bar") return "auto"
1684
+ return isTimeIndex(data.map((row) => row[index])) ? "auto" : "none"
1685
+ }
1686
+
1687
+ /* ---------------------------------------------------------------- helpers */
1688
+
528
1689
  /** Same coercion as `toChartNumber` in chart-utils (kept local: inlined modules can't import each other). */
529
1690
  function cellNumber(value: unknown): number | null {
530
1691
  if (typeof value === "number") return Number.isFinite(value) ? value : null
@@ -580,23 +1741,173 @@ interface TooltipRow {
580
1741
  name: string
581
1742
  color: string
582
1743
  value: number | null
1744
+ /** Percent stacking: the row's share of its point's total (0–100). */
1745
+ share?: number
1746
+ /** A muted line right under the row (a comparison's difference). */
1747
+ note?: string
583
1748
  }
584
1749
 
585
- /** The tooltip body: a title, then one `● name value` row per series. */
586
- function tooltipHtml(title: string, rows: readonly TooltipRow[], valueFormatter: (value: number) => string): string {
1750
+ const shareFormat = new Intl.NumberFormat(DEFAULT_LOCALE, { maximumFractionDigits: 1 })
1751
+ const formatShare = (share: number) => `${shareFormat.format(share)}%`
1752
+
1753
+ /** The tooltip body: a title, then one `● name value` row per series, then muted one-line `notes` (target, annotation). */
1754
+ function tooltipHtml(
1755
+ title: string,
1756
+ rows: readonly TooltipRow[],
1757
+ valueFormatter: (value: number) => string,
1758
+ notes: readonly string[] = [],
1759
+ ): string {
587
1760
  const lines = rows.map(
588
1761
  (row) =>
589
1762
  `<div style="display:flex;align-items:center;gap:8px;line-height:20px">` +
590
1763
  `<span style="display:inline-block;width:8px;height:8px;border-radius:9999px;background:${escapeHtml(row.color)}"></span>` +
591
1764
  `<span style="flex:1;opacity:.8">${escapeHtml(row.name)}</span>` +
592
- `<span style="font-weight:500;font-variant-numeric:tabular-nums;margin-left:12px">${
593
- row.value === null ? "–" : escapeHtml(valueFormatter(row.value))
594
- }</span></div>`,
1765
+ `<span style="font-weight:600;font-variant-numeric:tabular-nums;margin-left:12px">${
1766
+ row.value === null ? EMPTY_VALUE : escapeHtml(valueFormatter(row.value))
1767
+ }${
1768
+ row.share === undefined ? "" : `<span style="opacity:.6;margin-left:4px">(${escapeHtml(formatShare(row.share))})</span>`
1769
+ }</span></div>` +
1770
+ (row.note === undefined
1771
+ ? ""
1772
+ : `<div style="padding-left:16px;line-height:18px;font-size:12px;opacity:.7;font-variant-numeric:tabular-nums">${escapeHtml(row.note)}</div>`),
595
1773
  )
596
- return `<div style="font-weight:500;margin-bottom:4px">${escapeHtml(title)}</div>${lines.join("")}`
1774
+ const noteLines = notes.map(
1775
+ (note) => `<div style="margin-top:4px;line-height:18px;font-size:12px;opacity:.7">${escapeHtml(note)}</div>`,
1776
+ )
1777
+ return `<div style="font-weight:500;margin-bottom:4px">${escapeHtml(title)}</div>${lines.join("")}${noteLines.join("")}`
1778
+ }
1779
+
1780
+ /* ------------------------------------------------- per-bar targets / notes */
1781
+
1782
+ /** Default name of the per-bar target marker (legend, tooltip). */
1783
+ const BAR_TARGET_LABEL = "目標"
1784
+
1785
+ /** How far (px) the target marker reaches past each side of its bar. */
1786
+ const TARGET_MARKER_OVERHANG = 4
1787
+
1788
+ /**
1789
+ * The `renderItem` of the per-bar target marker: a 2px tick across the bar. Its length
1790
+ * is the bar's own width as ECharts lays it out (`api.barLayout`, one column — a single
1791
+ * series or a stack) plus a little overhang; without that it falls back to the
1792
+ * category band times `barHalfWidth`.
1793
+ */
1794
+ function targetMarkerRenderer(horizontalBars: boolean, barCategoryGap: string | number | undefined, color: string | undefined) {
1795
+ type Api = {
1796
+ value(dim: number): number
1797
+ coord(value: number[]): number[]
1798
+ size(value: number[]): number[]
1799
+ barLayout?(opt: { count: number; barCategoryGap?: string | number }): { width: number }[]
1800
+ }
1801
+ return (_params: unknown, api: Api) => {
1802
+ const [x = 0, y = 0] = api.coord([api.value(0), api.value(1)])
1803
+ const band = Math.abs(horizontalBars ? (api.size([0, 1])[1] ?? 0) : (api.size([1, 0])[0] ?? 0))
1804
+ const barWidth = api.barLayout?.({ count: 1, barCategoryGap })?.[0]?.width
1805
+ const length = (barWidth && barWidth > 0 ? barWidth : band * 2 * barHalfWidth(barCategoryGap)) + TARGET_MARKER_OVERHANG * 2
1806
+ return {
1807
+ type: "line",
1808
+ silent: true,
1809
+ shape: horizontalBars
1810
+ ? { x1: x, y1: y - length / 2, x2: x, y2: y + length / 2 }
1811
+ : { x1: x - length / 2, y1: y, x2: x + length / 2, y2: y },
1812
+ style: { stroke: color, lineWidth: 2, lineCap: "butt" },
1813
+ }
1814
+ }
1815
+ }
1816
+
1817
+ /**
1818
+ * Each row's target from the `targetKey` column. A missing, non-numeric or
1819
+ * non-positive cell is `null` (no marker for that bar).
1820
+ */
1821
+ function barTargetValues(data: readonly Record<string, unknown>[], targetKey: string): (number | null)[] {
1822
+ return data.map((row) => {
1823
+ const value = cellNumber(row[targetKey])
1824
+ return value !== null && value > 0 ? value : null
1825
+ })
1826
+ }
1827
+
1828
+ /** `value` as a share of `target` in percent; `null` without a value or a positive target. */
1829
+ function achievementRate(value: number | null | undefined, target: number | null | undefined): number | null {
1830
+ if (value === null || value === undefined || target === null || target === undefined || !(target > 0)) return null
1831
+ return (value / target) * 100
1832
+ }
1833
+
1834
+ /** The tooltip line of a bar with a target: 「目標 ¥1,200万(達成率 85.3%)」. `null` without a target. */
1835
+ function barTargetNote(
1836
+ label: string,
1837
+ value: number | null,
1838
+ target: number | null,
1839
+ valueFormatter: (value: number) => string,
1840
+ ): string | null {
1841
+ if (target === null) return null
1842
+ const rate = achievementRate(value, target)
1843
+ return `${label} ${valueFormatter(target)}${rate === null ? "" : `(達成率 ${formatShare(rate)})`}`
1844
+ }
1845
+
1846
+ /** Half the width of a bar in category-axis units, from `barCategoryGap` (`"20%"`; a px gap or none → ECharts' 20%). */
1847
+ function barHalfWidth(barCategoryGap?: string | number): number {
1848
+ const gap = typeof barCategoryGap === "string" && /^\d+(\.\d+)?%$/.test(barCategoryGap.trim()) ? parseFloat(barCategoryGap) / 100 : 0.2
1849
+ return 0.5 / (1 + gap)
1850
+ }
1851
+
1852
+ /** An annotation placed on the category axis: positions are indexes into the x labels. */
1853
+ interface ResolvedAnnotation {
1854
+ from: number
1855
+ /** Set for a range (`to` after `from`); a single position leaves it out. */
1856
+ to?: number
1857
+ label: string
1858
+ }
1859
+
1860
+ /**
1861
+ * Place annotations on the x labels by `String(value)` equality. An annotation
1862
+ * whose `at` is not an `index` value is dropped; `to` before `at` swaps them; a
1863
+ * `to` that is unknown or equal to `at` makes it a single position.
1864
+ */
1865
+ function resolveAnnotations(
1866
+ annotations: readonly ChartAnnotation[] | undefined,
1867
+ indexValues: readonly unknown[],
1868
+ ): ResolvedAnnotation[] {
1869
+ if (!annotations?.length) return []
1870
+ const position = new Map<string, number>()
1871
+ indexValues.forEach((value, i) => {
1872
+ const key = String(value ?? "")
1873
+ if (!position.has(key)) position.set(key, i)
1874
+ })
1875
+ const out: ResolvedAnnotation[] = []
1876
+ for (const note of annotations) {
1877
+ const from = position.get(String(note.at))
1878
+ if (from === undefined || !note.label) continue
1879
+ const end = note.to === undefined ? undefined : position.get(String(note.to))
1880
+ if (end === undefined || end === from) out.push({ from, label: note.label })
1881
+ else out.push({ from: Math.min(from, end), to: Math.max(from, end), label: note.label })
1882
+ }
1883
+ return out
1884
+ }
1885
+
1886
+ /** Gap (px) under which two neighbouring vertical labels (12px text) would print over each other. */
1887
+ const ANNOTATION_LABEL_GAP = 16
1888
+ /** Assumed spacing (px) between two index positions when the plot's width is unknown. */
1889
+ const ANNOTATION_ASSUMED_GAP = 40
1890
+
1891
+ /**
1892
+ * Which end of its line each single-position annotation's label sits on. Labels
1893
+ * run along the line; neighbours closer than a label's height alternate between
1894
+ * the top and the bottom end, so they never print over one another. `lines` are
1895
+ * the annotation positions (index units) in any order; the result follows that order.
1896
+ */
1897
+ function annotationLabelEnds(lines: readonly number[], pointGap: number | null): ("top" | "bottom")[] {
1898
+ const gap = pointGap ?? ANNOTATION_ASSUMED_GAP
1899
+ const order = lines.map((at, i) => ({ at, i })).sort((a, b) => a.at - b.at || a.i - b.i)
1900
+ const ends: ("top" | "bottom")[] = Array(lines.length).fill("top")
1901
+ for (let k = 1; k < order.length; k++) {
1902
+ const prev = order[k - 1]!
1903
+ const cur = order[k]!
1904
+ if ((cur.at - prev.at) * gap < ANNOTATION_LABEL_GAP) ends[cur.i] = ends[prev.i] === "top" ? "bottom" : "top"
1905
+ }
1906
+ return ends
597
1907
  }
598
1908
 
599
1909
  interface AxisTooltipParam {
1910
+ seriesId?: string
600
1911
  seriesName?: string
601
1912
  dataIndex?: number
602
1913
  color?: unknown
@@ -604,6 +1915,239 @@ interface AxisTooltipParam {
604
1915
 
605
1916
  const DIMMED = 0.3
606
1917
 
1918
+
1919
+ /** Series ids. Ours are stable across updates so ECharts can transition them; `__` marks the helpers. */
1920
+ const SERIES_ID_PREFIX = "series:"
1921
+ const FORECAST_SERIES_ID = "__forecast"
1922
+ const PROVISIONAL_SERIES_PREFIX = "__provisional:"
1923
+ /** Provisional points are drawn at this opacity (lines, areas, bars). */
1924
+ const PROVISIONAL_OPACITY = 0.55
1925
+ /** Horizontal bars (one series, not stacked) are painted at this share of the series colour; the highlighted bar is solid. Same tint as BarList. */
1926
+ const LIGHT_BAR_ALPHA = 0.7
1927
+ const FORECAST_BAND_BASE_ID = "__forecast-band-base"
1928
+ const FORECAST_BAND_RANGE_ID = "__forecast-band-range"
1929
+ const OVERLAY_SERIES_ID = "__overlay"
1930
+ const TARGET_MARKER_SERIES_ID = "__target-marker"
1931
+ const TARGET_LEGEND_SERIES_ID = "__target-legend"
1932
+ /** A flat tick (8×8 legend box, aspect kept): the per-bar target's legend icon. */
1933
+ const TARGET_LEGEND_ICON = "path://M0,0 L100,0 L100,24 L0,24 Z"
1934
+
1935
+ const DEFAULT_FORECAST_LABEL = "予測"
1936
+
1937
+ /** The label at the top of a forecast's boundary line: the forecast's name (as in the legend) and an arrow toward the forecast side. */
1938
+ function forecastBoundaryText(label: string = DEFAULT_FORECAST_LABEL): string {
1939
+ return `${label} →`
1940
+ }
1941
+
1942
+ /** A comparison series: a thin, muted, solid line with no markers (60% of `--muted-foreground`). */
1943
+ const COMPARISON_LINE_WIDTH = 1.5
1944
+ const COMPARISON_OPACITY = 0.6
1945
+ /** Target line: 1px dotted. Forecast: 2px dashed. Different widths *and* patterns, so the two never read as one. */
1946
+ const TARGET_LINE_DASH = [2, 3]
1947
+ const FORECAST_LINE_DASH = [6, 4]
1948
+ /** Legend icons for the two (8×8 box, aspect kept): a row of dots / of dashes in the line's own proportions. */
1949
+ const TARGET_DOTTED_ICON = "path://M0,0 L12,0 L12,10 L0,10 Z M30,0 L42,0 L42,10 L30,10 Z M60,0 L72,0 L72,10 L60,10 Z M88,0 L100,0 L100,10 L88,10 Z"
1950
+ const FORECAST_DASHED_ICON = "path://M0,0 L42,0 L42,24 L0,24 Z M58,0 L100,0 L100,24 L58,24 Z"
1951
+
1952
+ /** The forecast band's fill opacity: on a dark surface it needs more to show against the background. */
1953
+ const FORECAST_BAND_ALPHA_LIGHT = 0.15
1954
+ const FORECAST_BAND_ALPHA_DARK = 0.22
1955
+
1956
+ /** Whether a resolved surface colour (`#rrggbb` / `rgb()`) is dark (relative luminance under 0.4). `false` when it can't be read. */
1957
+ function isDarkSurface(color: string | undefined): boolean {
1958
+ if (!color) return false
1959
+ const hex = /^#([0-9a-f]{6})$/i.exec(color.trim())
1960
+ const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
1961
+ let channels: number[]
1962
+ if (hex) {
1963
+ const n = Number.parseInt(hex[1]!, 16)
1964
+ channels = [(n >> 16) & 255, (n >> 8) & 255, n & 255]
1965
+ } else if (rgb) channels = [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])]
1966
+ else return false
1967
+ const [r, g, b] = channels.map((c) => {
1968
+ const v = c / 255
1969
+ return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4
1970
+ }) as [number, number, number]
1971
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b < 0.4
1972
+ }
1973
+
1974
+ interface AxisExtent {
1975
+ min: number
1976
+ max: number
1977
+ }
1978
+
1979
+ /** The label of a stack's total (highlight and tooltip). */
1980
+ const STACK_TOTAL_LABEL = "合計"
1981
+
1982
+ /** Per point, the sum of the stacked series; `null` where every series is missing. */
1983
+ function stackTotalsOf(values: readonly (readonly (number | null)[])[]): (number | null)[] {
1984
+ const length = Math.max(0, ...values.map((v) => v.length))
1985
+ return Array.from({ length }, (_, i) => {
1986
+ let total: number | null = null
1987
+ for (const series of values) {
1988
+ const v = series[i]
1989
+ if (v !== null && v !== undefined) total = (total ?? 0) + v
1990
+ }
1991
+ return total
1992
+ })
1993
+ }
1994
+
1995
+ const LEGEND_LINE_HEIGHT = 24
1996
+ /** A rough width budget per legend line (px): a narrow card fits about this much. */
1997
+ const LEGEND_LINE_BUDGET = 320
1998
+
1999
+ /** How many lines the plain legend takes, estimated from its labels (12px text + 8px dot + gaps). */
2000
+ function legendLines(items: readonly string[], plotWidth?: number, reserve = 0): number {
2001
+ const width = items.reduce((sum, name) => sum + [...name].length * 12 + 8 + 5 + 16, 0)
2002
+ // A narrow plot has no room for the PNG buttons beside the legend: they move off its line, so no reserve.
2003
+ const narrow = plotWidth !== undefined && plotWidth < NARROW_PLOT_WIDTH
2004
+ const budget = Math.max(80, (plotWidth ? (narrow ? plotWidth : Math.min(LEGEND_LINE_BUDGET, plotWidth)) : LEGEND_LINE_BUDGET) - (narrow ? 0 : reserve))
2005
+ return Math.min(3, Math.max(1, Math.ceil(width / budget)))
2006
+ }
2007
+
2008
+ /** Width (px) kept free at the legend's right for the PNG action buttons (two 32px buttons + gaps). */
2009
+ const ACTIONS_RESERVE = 80
2010
+
2011
+ /** Room (px) one time label (`2026年1月`) needs, gap included. */
2012
+ const TIME_LABEL_WIDTH = 80
2013
+ /** Room (px) one highlight label (`¥6,240万`) needs, gap included. */
2014
+ const HIGHLIGHT_LABEL_WIDTH = 96
2015
+
2016
+ /** A highlight this close under the target (share of the larger of the two) can reach its label. */
2017
+ const TARGET_NEAR_SHARE = 0.12
2018
+ /** Under this plot width (px) a target label that would run into the latest value's label is dropped from the line. */
2019
+ const TARGET_LABEL_NARROW_WIDTH = 480
2020
+ /** A typical value-axis label column (`¥8,000万`), px. */
2021
+ const Y_AXIS_ESTIMATE = 72
2022
+ /** Breathing room between two labels, px — the estimate is rough. */
2023
+ const LABEL_SLACK = 24
2024
+
2025
+ /** Rough width (px) of 12px text: full-width characters 12, the rest 7. */
2026
+ function estimateTextWidth(text: string): number {
2027
+ let w = 0
2028
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
2029
+ return w
2030
+ }
2031
+
2032
+ /**
2033
+ * How many intervals a horizontal value axis (a horizontal bar chart's x) can carry in `plot` px
2034
+ * without its tick labels touching: each tick takes the widest of `samples` (the axis' end labels
2035
+ * printed) plus a gap. At least 1, at most 5 (ECharts' default, which it rounds to a tidy step).
2036
+ */
2037
+ function valueAxisSplitNumber(plot: number, samples: readonly string[]): number {
2038
+ const widest = samples.reduce((m, t) => Math.max(m, estimateTextWidth(t)), 0)
2039
+ return Math.max(1, Math.min(5, Math.floor(plot / (widest + LABEL_SLACK))))
2040
+ }
2041
+
2042
+ /** Room (px) above a vertical bar chart's plot for the label of an annotation band. */
2043
+ const BAND_LABEL_ROOM = 18
2044
+
2045
+ /** The grid's right margin on a line / area chart (px): the last x label hangs past the plot. */
2046
+ const LINE_RIGHT_MARGIN = 32
2047
+
2048
+ /** Room (px) above the plot for a forecast's boundary label (「予測 →」). */
2049
+ const FORECAST_LABEL_ROOM = 18
2050
+
2051
+ /**
2052
+ * Which side of the forecast boundary line the flat boundary label reads from: `"left"` starts at the line and runs
2053
+ * over the forecast side; `"right"` ends at the line and runs over the actuals, when the forecast side (the room right
2054
+ * of the line, grid margin included) is narrower than the text, so it never runs off the chart.
2055
+ * `forecastSpan` is `null` when the width is unknown.
2056
+ */
2057
+ function forecastLabelAlign(forecastSpan: number | null, text: string = forecastBoundaryText()): "left" | "right" {
2058
+ return forecastSpan !== null && forecastSpan >= estimateTextWidth(text) + 8 ? "left" : "right"
2059
+ }
2060
+
2061
+ /** ECharts' "nice" tick step for a raw step (1 / 2 / 3 / 5 × 10ⁿ, rounded): the same rule its value axis uses. */
2062
+ function niceStep(raw: number): number {
2063
+ if (!(raw > 0) || !Number.isFinite(raw)) return 1
2064
+ const exp10 = 10 ** Math.floor(Math.log10(raw))
2065
+ const f = raw / exp10
2066
+ return (f < 1.5 ? 1 : f < 2.5 ? 2 : f < 4 ? 3 : f < 7 ? 5 : 10) * exp10
2067
+ }
2068
+
2069
+ /**
2070
+ * The largest tick (by size) a value axis over `[lo, hi]` will carry once ECharts has niced its ends — the number
2071
+ * that decides the unit the ticks read in (`resolveAxisTickFormatter`). `max`, when fixed, is the axis' top as is.
2072
+ */
2073
+ function estimateAxisTop(lo: number, hi: number, splitNumber: number, max?: number): number {
2074
+ const top = Math.max(Math.abs(lo), Math.abs(hi))
2075
+ if (!(top > 0)) return 0
2076
+ const step = niceStep((hi - lo) / splitNumber)
2077
+ const niceHi = max !== undefined && max >= hi ? max : Math.ceil(hi / step) * step
2078
+ const niceLo = Math.floor(lo / step) * step
2079
+ return Math.max(Math.abs(niceHi), Math.abs(niceLo))
2080
+ }
2081
+
2082
+ /** Plot heights (px) under this carry 3 value intervals, not 4–5. */
2083
+ const SHORT_PLOT_HEIGHT = 200
2084
+ /** Plot heights under this carry 4 value intervals; taller ones 5. */
2085
+ const TALL_PLOT_HEIGHT = 300
2086
+ /** The plot height assumed when it isn't known (the charts' default `height`). */
2087
+ const ASSUMED_PLOT_HEIGHT = 288
2088
+
2089
+ /** How many intervals a vertical value axis carries: 3 under 200px of plot height, 4 under 300px, else 5. */
2090
+ function valueAxisSplitCount(plotHeight: number = ASSUMED_PLOT_HEIGHT): number {
2091
+ return plotHeight < SHORT_PLOT_HEIGHT ? 3 : plotHeight < TALL_PLOT_HEIGHT ? 4 : 5
2092
+ }
2093
+
2094
+ /** The grain of time-like x values (`"month"` for `2026-04`), or `null` when they aren't plain years / months / days. */
2095
+ function indexGrain(values: readonly unknown[]): PeriodGrain | null {
2096
+ const parsed = parseTimeIndex(values)
2097
+ return parsed ? parsed.granularity : null
2098
+ }
2099
+
2100
+ /**
2101
+ * The tooltip line under the main series' row when a comparison series is drawn: the arrow, the signed change and the
2102
+ * comparison's name, as `Delta` writes it ("↑ +12.4% 前年同月比"; a minus is U+2212). "比較なし 前年同月比" when
2103
+ * either value is missing or the baseline is 0.
2104
+ */
2105
+ function comparisonNote(
2106
+ current: number | null,
2107
+ previous: number | null,
2108
+ comparison: Pick<CartesianComparisonConfig, "vs" | "label">,
2109
+ grain?: PeriodGrain,
2110
+ format?: ValueFormat,
2111
+ locale: string = DEFAULT_LOCALE,
2112
+ ): string {
2113
+ const result = computeComparison(
2114
+ current,
2115
+ comparison.vs === "custom"
2116
+ ? { previous, vs: "custom", label: comparison.label ?? "", grain }
2117
+ : { previous, vs: comparison.vs, label: comparison.label, grain },
2118
+ )
2119
+ const text = formatChange(result, defaultChangeDisplay(format), locale, format)
2120
+ if (text === null) return `比較なし ${result.label}`
2121
+ const arrow = result.direction === "up" ? "↑" : result.direction === "down" ? "↓" : "→"
2122
+ return `${arrow} ${text.replace(/^-/, "−")} ${result.label}`
2123
+ }
2124
+
2125
+ /** Bars and areas start at 0: the length / area *is* the value. */
2126
+ const zeroBasedMin = (extent: AxisExtent) => Math.min(0, extent.min)
2127
+
2128
+ /**
2129
+ * A value axis' `min` / `max` from the limits a caller asked for, so that charts shown side by side can share one scale.
2130
+ * A limit never cuts the data: when the data runs past it, the axis widens to the data (`max(maxValue, data max)`).
2131
+ * `zeroBased` (bars, areas, waterfall): the axis always reaches 0, so a `minValue` above 0 is ignored and only a
2132
+ * negative one (room below 0) takes effect. Without a limit asked for, that edge is `undefined` (ECharts' own choice)
2133
+ * — except a zero-based `min`, which is always given.
2134
+ */
2135
+ function valueAxisLimits(
2136
+ limits: { minValue?: number; maxValue?: number },
2137
+ zeroBased: boolean,
2138
+ ): { min: ((extent: AxisExtent) => number) | undefined; max: ((extent: AxisExtent) => number) | undefined } {
2139
+ const lo = Number.isFinite(limits.minValue) ? limits.minValue : undefined
2140
+ const hi = Number.isFinite(limits.maxValue) ? limits.maxValue : undefined
2141
+ return {
2142
+ min: zeroBased
2143
+ ? (extent) => Math.min(0, lo ?? 0, extent.min)
2144
+ : lo === undefined
2145
+ ? undefined
2146
+ : (extent) => Math.min(lo, extent.min),
2147
+ max: hi === undefined ? undefined : (extent) => Math.max(hi, extent.max),
2148
+ }
2149
+ }
2150
+
607
2151
  function buildCartesianOption(cfg: CartesianChartConfig): EChartsOption {
608
2152
  const {
609
2153
  kind,
@@ -611,7 +2155,12 @@ function buildCartesianOption(cfg: CartesianChartConfig): EChartsOption {
611
2155
  index,
612
2156
  categories,
613
2157
  palette,
2158
+ labels: nameLabels,
2159
+ thresholds,
2160
+ toneColors,
614
2161
  valueFormatter,
2162
+ axisFormatter = valueFormatter,
2163
+ locale = DEFAULT_LOCALE,
615
2164
  type = "default",
616
2165
  layout = "horizontal",
617
2166
  curveType = "linear",
@@ -627,38 +2176,319 @@ function buildCartesianOption(cfg: CartesianChartConfig): EChartsOption {
627
2176
  minValue,
628
2177
  maxValue,
629
2178
  autoMinValue = false,
2179
+ fitToData,
630
2180
  allowDecimals = true,
631
2181
  xAxisLabel,
632
2182
  yAxisLabel,
633
2183
  barCategoryGap,
634
2184
  showDots = false,
635
2185
  active = null,
2186
+ target,
2187
+ targetLabel,
2188
+ targetLabelPosition = "start",
2189
+ targetKey,
2190
+ showZeroValues = true,
2191
+ guideColor,
2192
+ labelBackground,
2193
+ labelColor,
2194
+ plotWidth,
2195
+ plotHeight,
2196
+ reducedMotion = false,
2197
+ chartOptions,
2198
+ reserveActions = false,
636
2199
  } = cfg
2200
+ const provisionalLabel = cfg.provisionalLabel ?? DEFAULT_PROVISIONAL_LABEL
637
2201
 
638
- const labels = data.map((row) => String(row[index] ?? ""))
639
- const values = cartesianSeriesValues(data, categories, kind === "line" ? "default" : type)
640
2202
  const stacked = kind !== "line" && type !== "default"
641
2203
  const percent = kind !== "line" && type === "percent"
642
2204
  const horizontalBars = kind === "bar" && layout === "vertical"
2205
+ /*
2206
+ * -- comparison: a plain line, outside the stack and the palette. Never with bars or a 100% stack
2207
+ * (shares of a total have no "last year" line).
2208
+ */
2209
+ const comparison = kind !== "bar" && !percent ? cfg.comparison : undefined
2210
+ const compIdx = comparison ? categories.indexOf(comparison.category) : -1
2211
+ /** Positions of the series that are not the comparison: the stack, the highlight and the forecast read these. */
2212
+ const mainIdx = categories.map((_, i) => i).filter((i) => i !== compIdx)
2213
+ const seriesType = kind === "line" ? "default" : type
2214
+ const values = (() => {
2215
+ if (compIdx === -1) return cartesianSeriesValues(data, categories, seriesType)
2216
+ const main = cartesianSeriesValues(data, mainIdx.map((i) => categories[i]!), seriesType)
2217
+ const compared = cartesianSeriesValues(data, [categories[compIdx]!], "default")[0]!
2218
+ return categories.map((_, i) => (i === compIdx ? compared : main[mainIdx.indexOf(i)]!))
2219
+ })()
2220
+ const comparisonColor = guideColor ? withAlpha(guideColor, COMPARISON_OPACITY) : undefined
2221
+
2222
+ /* -- x labels: the actual rows, then the forecast rows that extend them */
2223
+ const labels = data.map((row) => String(row[index] ?? ""))
2224
+ const rawIndex: unknown[] = data.map((row) => row[index])
2225
+ const lastActual = labels.length - 1
2226
+ // First provisional point (-1: none). Looked up among the actual rows only; unrelated to `forecast`.
2227
+ const provStart = categories.length > 0 ? provisionalStart(rawIndex, cfg.provisionalFrom) : -1
2228
+ const forecast =
2229
+ kind !== "bar" && !percent && cfg.forecast && cfg.forecast.data.length > 0 && data.length > 0 && categories.length > 0
2230
+ ? cfg.forecast
2231
+ : undefined
2232
+ const forecastAt: number[] = []
2233
+ if (forecast) {
2234
+ const position = new Map(labels.map((label, i) => [label, i]))
2235
+ for (const row of forecast.data) {
2236
+ const label = String(row[index] ?? "")
2237
+ let at = position.get(label)
2238
+ if (at === undefined || at <= lastActual) {
2239
+ // A forecast row never overwrites an actual point; repeated labels append.
2240
+ at = labels.length
2241
+ labels.push(label)
2242
+ rawIndex.push(row[index])
2243
+ position.set(label, at)
2244
+ }
2245
+ forecastAt.push(at)
2246
+ }
2247
+ }
2248
+ const pad = (series: (number | null)[]) =>
2249
+ series.length < labels.length ? [...series, ...Array<null>(labels.length - series.length).fill(null)] : series
643
2250
  const last = labels.length - 1
2251
+ /*
2252
+ * -- time-like x values read as dates in the locale (`4月`, `2026年1月`), at a
2253
+ * fixed calendar step so the year-change label is never thinned away.
2254
+ */
2255
+ const timeStep = startEndOnly
2256
+ ? null
2257
+ : timeAxisLabelStep(
2258
+ rawIndex,
2259
+ plotWidth
2260
+ ? Math.max(
2261
+ 2,
2262
+ Math.min(
2263
+ plotWidth < NARROW_PLOT_WIDTH ? NARROW_TIME_AXIS_MAX_LABELS : TIME_AXIS_MAX_LABELS,
2264
+ Math.floor(plotWidth / TIME_LABEL_WIDTH),
2265
+ ),
2266
+ )
2267
+ : undefined,
2268
+ )
2269
+ // Plain (non-date) x labels of a line chart: thinned to every n-th so they never touch, never rotated.
2270
+ const plainStep = (() => {
2271
+ if (kind !== "line" || startEndOnly || timeStep !== null || !plotWidth || labels.length < 3) return 1
2272
+ const widest = Math.max(...labels.map((l) => estimateTextWidth(nameLabels && hasLabel(nameLabels, l) ? labelOf(l, nameLabels) : l)))
2273
+ const plot = Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - LINE_RIGHT_MARGIN)
2274
+ return Math.max(1, Math.ceil(((widest + 12) * (labels.length - 1)) / plot))
2275
+ })()
2276
+ const shownLabel = startEndOnly
2277
+ ? (i: number) => i === 0 || i === last
2278
+ : timeStep !== null
2279
+ ? (i: number) => i % timeStep === 0
2280
+ : plainStep > 1
2281
+ ? (i: number) => i % plainStep === 0
2282
+ : null
2283
+ const timeLabels = timeAxisLabels(rawIndex, locale, shownLabel ?? undefined)
2284
+ const compGrain = comparison ? (indexGrain(rawIndex.slice(0, lastActual + 1)) ?? undefined) : undefined
2285
+ const tooltipTitles = (timeTooltipLabels(rawIndex, locale) ?? labels).map((title, i) =>
2286
+ nameLabels ? (hasLabel(nameLabels, labels[i] ?? "") ? labelOf(labels[i] ?? "", nameLabels) : title) : title,
2287
+ )
644
2288
 
645
- const series = categories.map((category, c) => {
646
- const color = palette[c] || undefined
2289
+ /*
2290
+ * -- highlight: max + latest. Normal stacking labels the stack's total (on the
2291
+ * top layer); otherwise the first series, ≤ 2 series. A 100% stacked area
2292
+ * labels the first series' (the bottom band's) first and latest share inside
2293
+ * the band; a 100% stacked bar labels nothing.
2294
+ */
2295
+ const highlight = cfg.highlight ?? defaultChartHighlight(kind, data, index)
2296
+ const stackTotals = stacked && !percent ? stackTotalsOf(mainIdx.map((i) => values[i]!)) : null
2297
+ const highlightSeries = (stackTotals ? mainIdx[mainIdx.length - 1] : mainIdx[0]) ?? 0
2298
+ const shareHighlight = percent && kind === "area"
2299
+ const picked =
2300
+ highlight !== "auto" || mainIdx.length === 0 || (percent && !shareHighlight)
2301
+ ? []
2302
+ : shareHighlight
2303
+ ? categories.length <= 2
2304
+ ? pickShareHighlightPoints(values[0] ?? [])
2305
+ : []
2306
+ : stackTotals
2307
+ ? pickHighlightPoints(stackTotals)
2308
+ : mainIdx.length <= 2
2309
+ ? pickHighlightPoints(values[highlightSeries] ?? [])
2310
+ : []
2311
+ // On a narrow plot the max and the latest label would print over each other: keep the latest.
2312
+ const pointGap = plotWidth && labels.length > 1 ? plotWidth / (kind === "bar" ? labels.length : labels.length - 1) : null
2313
+ // By default only the latest value is labelled; an explicit `highlight` keeps its max + latest.
2314
+ const latestOnly = cfg.highlight === undefined && !shareHighlight && picked.length === 2
2315
+ const highlightPoints =
2316
+ latestOnly
2317
+ ? [picked[1]!]
2318
+ : picked.length === 2 && pointGap !== null && Math.abs(picked[1]!.index - picked[0]!.index) * pointGap < HIGHLIGHT_LABEL_WIDTH
2319
+ ? [picked[1]!]
2320
+ : picked
2321
+
2322
+ /*
2323
+ * Points (and the outer bars) sit at the plot's edges: pull the first / last
2324
+ * label inward so it isn't clipped. A label on the forecast boundary sits left
2325
+ * of the boundary line instead of across it.
2326
+ */
2327
+ const boundaryIndex = kind !== "bar" && !percent && cfg.forecast && cfg.forecast.data.length > 0 ? lastActual : -1
2328
+ const edgeAlign = (i: number) =>
2329
+ horizontalBars || labels.length < 2
2330
+ ? undefined
2331
+ : i === boundaryIndex && i !== last
2332
+ ? { align: "right" as const, offset: [-6, 0] }
2333
+ : i === last
2334
+ ? { align: "right" as const, ...(kind === "bar" ? { offset: [8, 0] } : {}) }
2335
+ : i === 0
2336
+ ? { align: "left" as const, ...(kind === "bar" ? { offset: [-8, 0] } : {}) }
2337
+ : undefined
2338
+
2339
+ /*
2340
+ * The target label sits at the plot's start (left), above its line, so it stays clear of the latest value's label at
2341
+ * the right end. Near the label (horizontally, estimated from `plotWidth`) a line / area highlight just under the
2342
+ * target prints below its point, and one just over it moves the target label under the line instead. On a plot
2343
+ * narrower than 480px, when the *latest* point's label would still run into the target label, the target label leaves
2344
+ * the line altogether — the legend names the target.
2345
+ */
2346
+ // `barOptions.targetKey` (a target per bar) takes over from the single `target` line.
2347
+ const perBarTarget = kind === "bar" && Boolean(targetKey)
2348
+ const hasTarget = !perBarTarget && target !== undefined && Number.isFinite(target)
2349
+ const targetText = hasTarget ? (targetLabel ?? `目標 ${axisFormatter(target)}`) : ""
2350
+ const highlightText = (value: number) =>
2351
+ shareHighlight ? `${Math.round(value)}%` : `${stackTotals ? `${STACK_TOTAL_LABEL} ` : ""}${axisFormatter(value)}`
2352
+ /** Whether `p`'s label sits within the target's value band and under the target label (at the right end). */
2353
+ const nearTargetLabel = (p: HighlightPoint, side: "under" | "over") => {
2354
+ if (!hasTarget || !plotWidth || kind === "bar" || labels.length < 2) return false
2355
+ if (side === "under" ? p.value > target : p.value <= target) return false
2356
+ const scale = Math.max(Math.abs(target), ...highlightPoints.map((h) => Math.abs(h.value)))
2357
+ if (scale === 0 || Math.abs(target - p.value) / scale > TARGET_NEAR_SHARE) return false
2358
+ const plot = Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - 32)
2359
+ const x = (p.index / (labels.length - 1)) * plot
2360
+ const w = estimateTextWidth(highlightText(p.value)) + 8
2361
+ const align = edgeAlign(p.index)?.align
2362
+ const left = align === "right" ? x - w - 6 : align === "left" ? x : x - w / 2
2363
+ return left < estimateTextWidth(targetText) + 8 + LABEL_SLACK
2364
+ }
2365
+ const hideTargetLabel =
2366
+ (kind === "line" && targetLabelPosition === "legend") ||
2367
+ !shareHighlight &&
2368
+ plotWidth !== undefined &&
2369
+ plotWidth < TARGET_LABEL_NARROW_WIDTH &&
2370
+ highlightPoints.some((p) => p.index === labels.length - 1 && (nearTargetLabel(p, "under") || nearTargetLabel(p, "over")))
2371
+ const below = (p: HighlightPoint) => !shareHighlight && !hideTargetLabel && nearTargetLabel(p, "under")
2372
+ const targetLabelBelow = !shareHighlight && !hideTargetLabel && highlightPoints.some((p) => nearTargetLabel(p, "over"))
2373
+
2374
+ // One series (or a stack, against its total) can be compared to a target; grouped series and 100% stacks cannot.
2375
+ const barTargets: (number | null)[] | null =
2376
+ perBarTarget && targetKey && !percent && (stacked || categories.length === 1) ? barTargetValues(data, targetKey) : null
2377
+ const barTargetName = targetLabel ?? BAR_TARGET_LABEL
2378
+ const barTargetColor = labelColor ?? guideColor
2379
+
2380
+ const markPointFor = (c: number, color: string | undefined) =>
2381
+ c === highlightSeries && highlightPoints.length > 0
2382
+ ? {
2383
+ silent: true,
2384
+ symbol: "circle",
2385
+ symbolSize: kind === "bar" ? 0 : 7,
2386
+ itemStyle: { color, borderColor: "transparent" },
2387
+ label: {
2388
+ show: true,
2389
+ position: horizontalBars ? ("right" as const) : ("top" as const),
2390
+ distance: 6,
2391
+ fontSize: 12,
2392
+ fontWeight: 500,
2393
+ color: labelColor,
2394
+ ...(labelBackground ? { backgroundColor: labelBackground, padding: [2, 4], borderRadius: 2 } : {}),
2395
+ formatter: (p: { value?: unknown }) => highlightText(Number(p.value)),
2396
+ },
2397
+ data: highlightPoints.map((p) => {
2398
+ // Below the point; on the forecast boundary, on the forecast side (the actual line comes in from the left).
2399
+ const label = shareHighlight
2400
+ ? // Inside the bottom band, under its upper edge: the label reads as that band's share.
2401
+ { ...edgeAlign(p.index), position: "bottom" as const }
2402
+ : below(p)
2403
+ ? p.index === boundaryIndex && p.index !== last
2404
+ ? { position: "bottom" as const, align: "left" as const, offset: [6, 0] }
2405
+ : { ...edgeAlign(p.index), position: "bottom" as const }
2406
+ : edgeAlign(p.index)
2407
+ return {
2408
+ name: p.kind,
2409
+ value: p.value,
2410
+ coord: horizontalBars ? [p.value, p.index] : [p.index, p.value],
2411
+ ...(label ? { label } : {}),
2412
+ }
2413
+ }),
2414
+ }
2415
+ : undefined
2416
+
2417
+ // Threshold colours: bars side by side (one series or several). A stacked segment is a part, not a level to judge, so stacks keep their series colours.
2418
+ const byValue = kind === "bar" && !stacked && Boolean(thresholds?.length)
2419
+ const multiSeries = categories.length > 1
2420
+ // Horizontal bars of one series read light; only the highlighted bar is solid (the one the page is about).
2421
+ const lightBars = kind === "bar" && horizontalBars && !stacked && !multiSeries
2422
+ const series: Record<string, unknown>[] = categories.map((category, c) => {
2423
+ const solid = palette[c] || undefined
2424
+ const color = lightBars && solid ? withAlpha(solid, LIGHT_BAR_ALPHA) : solid
647
2425
  const dimSeries = active !== null && active.category !== category
2426
+ const seriesData = pad(values[c]!)
648
2427
  if (kind === "bar") {
649
- const radius = stacked ? 0 : horizontalBars ? [0, 3, 3, 0] : [3, 3, 0, 0]
2428
+ const rounded = horizontalBars ? [0, 4, 4, 0] : [4, 4, 0, 0]
2429
+ // Stacked: only the topmost segment is rounded.
2430
+ const radius = stacked && c !== categories.length - 1 ? 0 : rounded
650
2431
  return {
2432
+ id: SERIES_ID_PREFIX + category,
651
2433
  type: "bar" as const,
652
2434
  name: category,
653
2435
  stack: stacked ? "total" : undefined,
654
2436
  barCategoryGap,
655
2437
  itemStyle: { color, borderRadius: radius },
656
- emphasis: { focus: "series" as const },
657
- data: values[c]!.map((value, i) =>
658
- active !== null && !(active.category === category && active.index === i)
659
- ? { value, itemStyle: { opacity: DIMMED } }
660
- : value,
661
- ),
2438
+ markPoint: markPointFor(c, solid),
2439
+ markLine: undefined,
2440
+ data: seriesData.map((value, i) => {
2441
+ const tone = byValue ? toneForValue(value, thresholds) : undefined
2442
+ const toneColor = tone ? toneColors?.[tone] || undefined : undefined
2443
+ const isHighlight = lightBars && cfg.barHighlight !== undefined && String(rawIndex[i]) === String(cfg.barHighlight)
2444
+ const dimmed = active !== null && !(active.category === category && active.index === i)
2445
+ // Provisional bars: lighter fill and a dashed edge, never the solid look of a confirmed bar.
2446
+ const provisional = provStart !== -1 && i >= provStart && i <= lastActual
2447
+ const zeroLabel =
2448
+ showZeroValues && !stacked && value === 0
2449
+ ? {
2450
+ show: true,
2451
+ position: horizontalBars ? ("right" as const) : ("top" as const),
2452
+ distance: 4,
2453
+ fontSize: 12,
2454
+ color: labelColor,
2455
+ formatter: () => axisFormatter(0),
2456
+ }
2457
+ : undefined
2458
+ if (!dimmed && !toneColor && !isHighlight && !provisional && !zeroLabel) return value
2459
+ return {
2460
+ value,
2461
+ ...(zeroLabel ? { label: zeroLabel } : {}),
2462
+ itemStyle: {
2463
+ ...(isHighlight && solid ? { color: solid } : {}),
2464
+ ...(toneColor ? { color: toneColor } : {}),
2465
+ // Several series: the series colour stays on the edge so the legend still points at the bar.
2466
+ ...(toneColor && multiSeries && color && !provisional ? { borderColor: color, borderWidth: 2 } : {}),
2467
+ ...(provisional ? { opacity: PROVISIONAL_OPACITY, borderColor: toneColor ?? color, borderWidth: 1, borderType: "dashed" as const } : {}),
2468
+ ...(dimmed ? { opacity: DIMMED } : {}),
2469
+ },
2470
+ }
2471
+ }),
2472
+ }
2473
+ }
2474
+ if (c === compIdx) {
2475
+ // The comparison: thin, muted, solid, no markers, no fill, never stacked — behind the main series.
2476
+ return {
2477
+ id: SERIES_ID_PREFIX + category,
2478
+ type: "line" as const,
2479
+ name: category,
2480
+ z: 1,
2481
+ smooth: curveType === "smooth",
2482
+ step: curveType === "step" ? ("middle" as const) : undefined,
2483
+ connectNulls,
2484
+ symbol: "none",
2485
+ showSymbol: false,
2486
+ lineStyle: { width: COMPARISON_LINE_WIDTH, type: "solid" as const, color: comparisonColor, opacity: dimSeries ? DIMMED : 1 },
2487
+ itemStyle: { color: comparisonColor, opacity: dimSeries ? DIMMED : 1 },
2488
+ areaStyle: undefined,
2489
+ markPoint: undefined,
2490
+ markLine: undefined,
2491
+ data: seriesData,
662
2492
  }
663
2493
  }
664
2494
  const areaStyle =
@@ -674,12 +2504,13 @@ function buildCartesianOption(cfg: CartesianChartConfig): EChartsOption {
674
2504
  x2: 0,
675
2505
  y2: 1,
676
2506
  colorStops: [
677
- { offset: 0, color: withAlpha(color, 0.35) },
2507
+ { offset: 0, color: withAlpha(color, 0.28) },
678
2508
  { offset: 1, color: withAlpha(color, 0) },
679
2509
  ],
680
2510
  },
681
2511
  }
682
2512
  return {
2513
+ id: SERIES_ID_PREFIX + category,
683
2514
  type: "line" as const,
684
2515
  name: category,
685
2516
  stack: stacked ? "total" : undefined,
@@ -688,16 +2519,357 @@ function buildCartesianOption(cfg: CartesianChartConfig): EChartsOption {
688
2519
  connectNulls,
689
2520
  symbol: "circle",
690
2521
  symbolSize: 6,
691
- showSymbol: showDots || labels.length === 1,
692
- lineStyle: { width: 2, color, opacity: dimSeries ? DIMMED : 1 },
2522
+ showSymbol: showDots || data.length === 1,
2523
+ // 100% stacked: the top band's upper edge is the 100% line, not a value — drawn, it reads as「this band = 100%」.
2524
+ lineStyle:
2525
+ percent && c === categories.length - 1
2526
+ ? { width: 0, color, opacity: 0 }
2527
+ : { width: 2, color, opacity: dimSeries ? DIMMED : 1 },
693
2528
  itemStyle: { color, opacity: dimSeries ? DIMMED : 1 },
2529
+ // Hovering a series fades the others (not for a stack, where the bands read together).
2530
+ emphasis: stacked ? undefined : { focus: "series" as const },
694
2531
  areaStyle: areaStyle && dimSeries ? { ...areaStyle, opacity: DIMMED * 0.3 } : areaStyle,
695
- emphasis: { focus: "series" as const },
696
- data: values[c]!,
2532
+ markPoint: markPointFor(c, color),
2533
+ markLine: undefined,
2534
+ data: provStart === -1 ? seriesData : splitProvisional(seriesData, provStart).confirmed,
697
2535
  }
698
2536
  })
699
2537
 
2538
+ /* -- provisional: a dashed, lighter continuation of every series from `provStart`, joined to the last confirmed point */
2539
+ if (kind !== "bar" && provStart !== -1) {
2540
+ categories.forEach((category, c) => {
2541
+ // The comparison is not provisional: it keeps its own line to the end.
2542
+ if (c === compIdx) return
2543
+ const color = palette[c] || undefined
2544
+ const dimSeries = active !== null && active.category !== category
2545
+ const solid = series[c] as { areaStyle?: { opacity?: number } }
2546
+ const opacity = (dimSeries ? DIMMED : 1) * PROVISIONAL_OPACITY
2547
+ series.push({
2548
+ id: PROVISIONAL_SERIES_PREFIX + category,
2549
+ type: "line" as const,
2550
+ name: provisionalLabel,
2551
+ // Its own stack: the joint point repeats the confirmed value and must not pile onto it.
2552
+ stack: stacked ? "provisional" : undefined,
2553
+ smooth: curveType === "smooth",
2554
+ step: curveType === "step" ? ("middle" as const) : undefined,
2555
+ connectNulls: false,
2556
+ symbol: "circle",
2557
+ symbolSize: 6,
2558
+ showSymbol: showDots || data.length === 1,
2559
+ lineStyle:
2560
+ percent && c === categories.length - 1
2561
+ ? { width: 0, color, opacity: 0 }
2562
+ : { width: 2, type: "dashed" as const, color, opacity },
2563
+ itemStyle: { color, opacity },
2564
+ areaStyle: solid.areaStyle ? { ...solid.areaStyle, opacity: (solid.areaStyle.opacity ?? 1) * PROVISIONAL_OPACITY } : undefined,
2565
+ markPoint: undefined,
2566
+ markLine: undefined,
2567
+ data: splitProvisional(pad(values[c]!), provStart).provisional,
2568
+ })
2569
+ })
2570
+ }
2571
+ // A bar legend entry for the provisional style (an empty line series: it takes no bar slot).
2572
+ if (kind === "bar" && provStart !== -1) {
2573
+ series.push({
2574
+ id: PROVISIONAL_SERIES_PREFIX + "legend",
2575
+ type: "line" as const,
2576
+ name: provisionalLabel,
2577
+ silent: true,
2578
+ symbol: "none",
2579
+ showSymbol: false,
2580
+ tooltip: { show: false },
2581
+ legendHoverLink: false,
2582
+ lineStyle: { opacity: 0 },
2583
+ itemStyle: { color: palette[0] || undefined, opacity: PROVISIONAL_OPACITY },
2584
+ markPoint: undefined,
2585
+ markLine: undefined,
2586
+ data: [],
2587
+ })
2588
+ }
2589
+
2590
+ /* -- forecast: dashed continuation (+ optional band) of one series */
2591
+ const forecastLabel = forecast?.label ?? DEFAULT_FORECAST_LABEL
2592
+ const forecastBandAlpha = isDarkSurface(labelBackground) ? FORECAST_BAND_ALPHA_DARK : FORECAST_BAND_ALPHA_LIGHT
2593
+ const forecastValues: (number | null)[] = []
2594
+ if (forecast) {
2595
+ const category =
2596
+ forecast.category !== undefined && categories.includes(forecast.category) && forecast.category !== comparison?.category
2597
+ ? forecast.category
2598
+ : categories[mainIdx[0] ?? 0]!
2599
+ const c = categories.indexOf(category)
2600
+ const color = palette[c] || undefined
2601
+ const actual = values[c]!
2602
+ let start = -1
2603
+ for (let i = actual.length - 1; i >= 0; i--) {
2604
+ if (actual[i] !== null) {
2605
+ start = i
2606
+ break
2607
+ }
2608
+ }
2609
+ const line: (number | null)[] = Array<null>(labels.length).fill(null)
2610
+ const lower: (number | null)[] = Array<null>(labels.length).fill(null)
2611
+ const range: (number | null)[] = Array<null>(labels.length).fill(null)
2612
+ if (start !== -1) {
2613
+ line[start] = actual[start]!
2614
+ lower[start] = actual[start]!
2615
+ range[start] = 0
2616
+ }
2617
+ let hasBand = false
2618
+ forecast.data.forEach((row: ChartForecastRow, k) => {
2619
+ const at = forecastAt[k]!
2620
+ line[at] = cellNumber(row.value)
2621
+ const lo = cellNumber(row.lower)
2622
+ const hi = cellNumber(row.upper)
2623
+ if (lo !== null && hi !== null) {
2624
+ hasBand = true
2625
+ lower[at] = Math.min(lo, hi)
2626
+ range[at] = Math.abs(hi - lo)
2627
+ }
2628
+ })
2629
+ forecastValues.push(...line)
2630
+ const helper = {
2631
+ type: "line" as const,
2632
+ silent: true,
2633
+ symbol: "none",
2634
+ showSymbol: false,
2635
+ connectNulls: true,
2636
+ tooltip: { show: false },
2637
+ legendHoverLink: false,
2638
+ emphasis: { disabled: true },
2639
+ markPoint: undefined,
2640
+ markLine: undefined,
2641
+ }
2642
+ if (hasBand) {
2643
+ series.push(
2644
+ {
2645
+ ...helper,
2646
+ id: FORECAST_BAND_BASE_ID,
2647
+ name: FORECAST_BAND_BASE_ID,
2648
+ stack: FORECAST_BAND_BASE_ID,
2649
+ lineStyle: { opacity: 0 },
2650
+ areaStyle: undefined,
2651
+ data: lower,
2652
+ },
2653
+ {
2654
+ ...helper,
2655
+ id: FORECAST_BAND_RANGE_ID,
2656
+ name: FORECAST_BAND_RANGE_ID,
2657
+ stack: FORECAST_BAND_BASE_ID,
2658
+ lineStyle: { opacity: 0 },
2659
+ areaStyle: color ? { color: withAlpha(color, forecastBandAlpha), opacity: 1 } : { opacity: forecastBandAlpha },
2660
+ data: range,
2661
+ },
2662
+ )
2663
+ }
2664
+ series.push({
2665
+ ...helper,
2666
+ id: FORECAST_SERIES_ID,
2667
+ name: forecastLabel,
2668
+ silent: false,
2669
+ tooltip: undefined,
2670
+ emphasis: undefined,
2671
+ smooth: curveType === "smooth",
2672
+ // Always dashed (2px, 6-4) and lighter — a forecast must never read as a measurement, nor as the 1px dotted target.
2673
+ lineStyle: { width: 2, type: FORECAST_LINE_DASH, color, opacity: 0.7 },
2674
+ itemStyle: { color, opacity: 0.7 },
2675
+ areaStyle: undefined,
2676
+ data: line,
2677
+ })
2678
+ }
2679
+
2680
+ /* -- overlay: target line, forecast boundary, and the extent that keeps the target on the axis */
2681
+ /**
2682
+ * Horizontal bars: the target line is vertical and its label lies flat above the plot, centred
2683
+ * on the line — unless that would run past the plot's right (or left) edge, e.g. a target near
2684
+ * the axis max on a narrow chart; then it hangs to the line's left (right) instead. The axis max
2685
+ * is estimated from the data (ECharts rounds it up, which only moves the line left of the guess).
2686
+ */
2687
+ const horizontalTargetAlign = ((): "left" | "center" | "right" => {
2688
+ if (!horizontalBars || !hasTarget) return "center"
2689
+ const totals = labels.map((_, i) =>
2690
+ stacked
2691
+ ? values.reduce((sum, v) => sum + Math.max(0, v[i] ?? 0), 0)
2692
+ : Math.max(0, ...values.map((v) => v[i] ?? 0)),
2693
+ )
2694
+ const top = percent ? 100 : (maxValue ?? Math.max(target, ...totals))
2695
+ if (!(top > 0)) return "center"
2696
+ const ratio = Math.min(1, Math.max(0, target / top))
2697
+ const half = (estimateTextWidth(targetText) + 8) / 2
2698
+ if (!plotWidth) return ratio > 0.85 ? "right" : ratio < 0.15 ? "left" : "center"
2699
+ const right = highlightPoints.length > 0 ? 64 : 16
2700
+ const categoryColumn = showYAxis ? (yAxisWidth ?? Math.min(160, Math.max(0, ...labels.map(estimateTextWidth)))) + 8 : 0
2701
+ const plot = Math.max(1, plotWidth - categoryColumn - right - 4)
2702
+ const at = ratio * plot
2703
+ if (plot - at + right < half) return "right"
2704
+ if (at + categoryColumn < half) return "left"
2705
+ return "center"
2706
+ })()
2707
+ const markLines: unknown[] = []
2708
+ const markAreas: unknown[] = []
2709
+ if (hasTarget && target !== undefined) {
2710
+ markLines.push({
2711
+ name: "target",
2712
+ [horizontalBars ? "xAxis" : "yAxis"]: target,
2713
+ // 1px dotted — the forecast is 2px dashed, so the two never read as one line.
2714
+ lineStyle: { type: TARGET_LINE_DASH, width: 1, color: guideColor },
2715
+ label: {
2716
+ show: !hideTargetLabel,
2717
+ // The start (left) of the line, above it — under it when a highlight sits just above the target there.
2718
+ // Horizontal bars: the line is vertical, so the label goes flat above its top end, outside the plot (no rotation, clear of the bars).
2719
+ // The category axis is inverted there (first row on top), so the line runs top → bottom and its top end is the *start*.
2720
+ position: horizontalBars
2721
+ ? "start"
2722
+ : kind === "line" && targetLabelPosition === "end"
2723
+ ? "insideEndTop"
2724
+ : targetLabelBelow
2725
+ ? "insideStartBottom"
2726
+ : "insideStartTop",
2727
+ ...(horizontalBars ? { rotate: 0, align: horizontalTargetAlign, verticalAlign: "bottom" as const, distance: 4 } : {}),
2728
+ color: guideColor,
2729
+ formatter: targetText,
2730
+ },
2731
+ })
2732
+ }
2733
+ if (forecast) {
2734
+ const forecastSpan =
2735
+ plotWidth && labels.length > 1
2736
+ ? (Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - LINE_RIGHT_MARGIN) / (labels.length - 1)) *
2737
+ (labels.length - 1 - lastActual) +
2738
+ LINE_RIGHT_MARGIN
2739
+ : null
2740
+ markLines.push({
2741
+ name: "forecast-boundary",
2742
+ xAxis: lastActual,
2743
+ lineStyle: { type: "dashed", width: 1, color: guideColor },
2744
+ // Flat (text-xs, muted), just above the plot's top edge at the top of the line (`grid.top` makes the room; the legend
2745
+ // sits above that): along the line at its foot it ran into the x axis labels on a narrow chart.
2746
+ label: {
2747
+ show: true,
2748
+ position: "end",
2749
+ rotate: 0,
2750
+ align: forecastLabelAlign(forecastSpan, forecastBoundaryText(forecastLabel)),
2751
+ verticalAlign: "bottom" as const,
2752
+ distance: 4,
2753
+ fontSize: 12,
2754
+ color: guideColor,
2755
+ formatter: forecastBoundaryText(forecastLabel),
2756
+ },
2757
+ })
2758
+ }
2759
+ /* -- annotations: a thin neutral line, or a faint band for a range, on the category axis (vertical layouts only) */
2760
+ const notes = horizontalBars ? [] : resolveAnnotations(cfg.annotations, rawIndex)
2761
+ const noteGap = plotWidth && labels.length > 1 ? plotWidth / (kind === "bar" ? labels.length : labels.length - 1) : null
2762
+ if (notes.length > 0) {
2763
+ const singles = notes.filter((n) => n.to === undefined)
2764
+ const ends = annotationLabelEnds(singles.map((n) => n.from), noteGap)
2765
+ const background = labelBackground ? { backgroundColor: labelBackground, padding: [1, 3], borderRadius: 2 } : {}
2766
+ singles.forEach((note, k) => {
2767
+ markLines.push({
2768
+ name: `annotation:${note.label}`,
2769
+ xAxis: note.from,
2770
+ lineStyle: { type: "solid", width: 1, color: guideColor },
2771
+ // Along the line, at the top (the legend sits above the plot) or at its foot when a neighbour is close.
2772
+ label: {
2773
+ show: true,
2774
+ position: ends[k] === "top" ? "insideEndTop" : "insideStartBottom",
2775
+ color: guideColor,
2776
+ ...background,
2777
+ formatter: note.label,
2778
+ },
2779
+ })
2780
+ })
2781
+ const over = kind === "bar" ? 0.5 : 0
2782
+ for (const note of notes) {
2783
+ if (note.to === undefined) continue
2784
+ const widthPx = noteGap === null ? null : (note.to - note.from + (kind === "bar" ? 1 : 0)) * noteGap
2785
+ const fits = widthPx === null ? [...note.label].length <= 6 : estimateTextWidth(note.label) + 8 <= widthPx
2786
+ markAreas.push([
2787
+ {
2788
+ name: note.label,
2789
+ xAxis: note.from - over,
2790
+ itemStyle: { color: guideColor ? withAlpha(guideColor, 0.12) : undefined },
2791
+ // The band's foot (bars: just above the plot — inside, the text would run into the value label of a tall bar,
2792
+ // and `grid.top` makes the room); a band narrower than its text reads the text upright along the band instead.
2793
+ label: {
2794
+ show: true,
2795
+ position: kind === "bar" ? "top" : fits ? "insideBottom" : "inside",
2796
+ rotate: fits ? 0 : 90,
2797
+ color: guideColor,
2798
+ fontSize: 12,
2799
+ formatter: note.label,
2800
+ },
2801
+ },
2802
+ { xAxis: note.to + over },
2803
+ ])
2804
+ }
2805
+ }
2806
+ // The target is a legend entry too (an empty line series carries the name): the line may lose its label on a narrow plot.
2807
+ if (hasTarget) {
2808
+ series.push({
2809
+ id: TARGET_LEGEND_SERIES_ID,
2810
+ type: "line" as const,
2811
+ name: targetText,
2812
+ silent: true,
2813
+ symbol: "none",
2814
+ showSymbol: false,
2815
+ tooltip: { show: false },
2816
+ legendHoverLink: false,
2817
+ emphasis: { disabled: true },
2818
+ lineStyle: { opacity: 0 },
2819
+ itemStyle: { color: guideColor },
2820
+ markPoint: undefined,
2821
+ markLine: undefined,
2822
+ data: [],
2823
+ })
2824
+ }
2825
+ if (markLines.length > 0 || markAreas.length > 0) {
2826
+ series.push({
2827
+ id: OVERLAY_SERIES_ID,
2828
+ name: OVERLAY_SERIES_ID,
2829
+ type: "line" as const,
2830
+ silent: true,
2831
+ symbol: "none",
2832
+ showSymbol: false,
2833
+ tooltip: { show: false },
2834
+ legendHoverLink: false,
2835
+ emphasis: { disabled: true },
2836
+ lineStyle: { opacity: 0 },
2837
+ itemStyle: { color: guideColor },
2838
+ // A single invisible point at the target, so the value axis always reaches it.
2839
+ data: labels.map((_, i) => (i === 0 && hasTarget && target !== undefined ? target : null)),
2840
+ markPoint: undefined,
2841
+ // `precision`: ECharts rounds a mark line's value to 2 decimals by default (a 0.035 target would land on 0.04 — off a fitted axis,
2842
+ // where the line is then dropped). `z` keeps the guide lines above the series' own lines.
2843
+ markLine: markLines.length > 0 ? { silent: true, symbol: "none", animation: false, precision: 20, z: 6, data: markLines } : undefined,
2844
+ markArea: markAreas.length > 0 ? { silent: true, animation: false, data: markAreas } : undefined,
2845
+ })
2846
+ }
2847
+ /*
2848
+ * -- per-bar targets: a short marker across each bar at its target. A custom
2849
+ * series (the marker's length follows the bar's width, in px, whatever the chart's
2850
+ * size) whose data also keeps the value axis reaching the largest target. It is
2851
+ * the legend's entry too: the marker is named, with a tick as its icon.
2852
+ */
2853
+ if (barTargets) {
2854
+ series.push({
2855
+ id: TARGET_MARKER_SERIES_ID,
2856
+ type: "custom" as const,
2857
+ name: barTargetName,
2858
+ silent: true,
2859
+ animation: false,
2860
+ z: 5,
2861
+ tooltip: { show: false },
2862
+ legendHoverLink: false,
2863
+ emphasis: { disabled: true },
2864
+ itemStyle: { color: barTargetColor },
2865
+ encode: { x: 0, y: 1 },
2866
+ data: barTargets.flatMap((value, i) => (value === null ? [] : [horizontalBars ? [value, i] : [i, value]])),
2867
+ renderItem: targetMarkerRenderer(horizontalBars, barCategoryGap, barTargetColor),
2868
+ })
2869
+ }
2870
+
700
2871
  const categoryAxis = {
2872
+ id: horizontalBars ? "y" : "x",
701
2873
  type: "category" as const,
702
2874
  data: labels,
703
2875
  show: horizontalBars ? showYAxis : showXAxis,
@@ -706,48 +2878,137 @@ function buildCartesianOption(cfg: CartesianChartConfig): EChartsOption {
706
2878
  axisTick: { show: false },
707
2879
  axisLabel: {
708
2880
  hideOverlap: true,
709
- interval: startEndOnly ? (i: number) => i === 0 || i === last : ("auto" as const),
710
- ...(horizontalBars && yAxisWidth != null ? { width: yAxisWidth, overflow: "truncate" as const } : {}),
2881
+ rotate: kind === "line" ? 0 : undefined,
2882
+ interval: shownLabel ?? ("auto" as const),
2883
+ formatter:
2884
+ timeLabels || nameLabels
2885
+ ? (value: string, i: number) => {
2886
+ const time = timeLabels?.[i]
2887
+ if (time === "") return ""
2888
+ return hasLabel(nameLabels, value) ? labelOf(value, nameLabels) : (time ?? value)
2889
+ }
2890
+ : undefined,
2891
+ width: horizontalBars ? yAxisWidth : undefined,
2892
+ overflow: horizontalBars && yAxisWidth != null ? ("truncate" as const) : undefined,
711
2893
  },
712
2894
  name: horizontalBars ? yAxisLabel : xAxisLabel,
713
2895
  nameLocation: "middle" as const,
714
2896
  nameGap: horizontalBars ? (yAxisWidth ?? 48) + 8 : 28,
715
2897
  }
2898
+ const fit = kind === "line" && (fitToData ?? autoMinValue)
2899
+ // A horizontal bar chart's value ticks run along the (narrow) width: as many as fit side by side.
2900
+ const valueSplitNumber = (() => {
2901
+ if (!horizontalBars || !plotWidth) return undefined
2902
+ const top = percent
2903
+ ? 100
2904
+ : (maxValue ?? Math.max(0, ...(stacked ? stackTotalsOf(values) : values.flat()).map((v) => v ?? 0)))
2905
+ const categoryColumn = showYAxis ? (yAxisWidth ?? Math.min(160, Math.max(0, ...labels.map(estimateTextWidth)))) + 8 : 0
2906
+ const plot = plotWidth - categoryColumn - (highlightPoints.length > 0 ? 64 : 16) - 4
2907
+ const text = percent ? (v: number) => `${v}%` : (v: number) => axisFormatter(v)
2908
+ return valueAxisSplitNumber(plot, [text(0), text(top)])
2909
+ })()
2910
+ const limits = valueAxisLimits({ minValue, maxValue }, kind !== "line")
2911
+ // Vertical value axes carry 3 intervals on a short plot, else 4–5 (a horizontal bar chart's follows its width, above).
2912
+ const splitNumber = horizontalBars ? valueSplitNumber : valueAxisSplitCount(plotHeight)
2913
+ /*
2914
+ * Ticks read in one unit — the unit of the axis' largest tick (¥0.5億 / ¥1億, never ¥5,000万 beside ¥1億). The largest
2915
+ * tick is estimated from the data the way ECharts nices its ends.
2916
+ */
2917
+ const tickFormatter = (() => {
2918
+ if (!cfg.axisTicks || percent) return axisFormatter
2919
+ const extentValues: number[] = []
2920
+ const addAll = (list: readonly (number | null)[]) => {
2921
+ for (const v of list) if (v !== null && Number.isFinite(v)) extentValues.push(v)
2922
+ }
2923
+ if (stackTotals) addAll(stackTotals)
2924
+ else values.forEach(addAll)
2925
+ addAll(forecastValues)
2926
+ if (forecast) addAll(forecast.data.flatMap((row) => [cellNumber(row.lower), cellNumber(row.upper)]))
2927
+ if (barTargets) addAll(barTargets)
2928
+ if (hasTarget && target !== undefined) extentValues.push(target)
2929
+ if (maxValue !== undefined && Number.isFinite(maxValue)) extentValues.push(maxValue)
2930
+ if (minValue !== undefined && Number.isFinite(minValue)) extentValues.push(minValue)
2931
+ if (extentValues.length === 0) return axisFormatter
2932
+ const zeroBased = kind !== "line" || !fit
2933
+ const hi = Math.max(...extentValues, zeroBased ? 0 : -Infinity)
2934
+ const lo = Math.min(...extentValues, zeroBased ? 0 : Infinity)
2935
+ return cfg.axisTicks(estimateAxisTop(lo, hi, splitNumber ?? 5, maxValue !== undefined && Number.isFinite(maxValue) ? maxValue : undefined))
2936
+ })()
716
2937
  const valueAxis = {
2938
+ id: horizontalBars ? "x" : "y",
717
2939
  type: "value" as const,
718
2940
  show: horizontalBars ? showXAxis : showYAxis,
719
- min: percent ? 0 : minValue,
720
- max: percent ? 100 : maxValue,
721
- scale: autoMinValue && minValue == null,
2941
+ // Bars and areas always start at 0 (a positive `minValue` can't lift them, a negative one makes room below);
2942
+ // lines do too unless asked to fit the data. A limit never cuts the data: the axis widens to it.
2943
+ min: percent ? 0 : kind === "line" ? (minValue === undefined ? (fit ? undefined : zeroBasedMin) : limits.min) : limits.min,
2944
+ max: percent ? 100 : limits.max,
2945
+ scale: fit && minValue == null,
2946
+ splitNumber,
722
2947
  minInterval: allowDecimals ? undefined : 1,
723
2948
  axisLine: { show: false },
724
2949
  axisTick: { show: false },
725
2950
  splitLine: { show: showGridLines },
726
2951
  axisLabel: {
727
- formatter: percent ? (v: number) => `${v}%` : (v: number) => valueFormatter(v),
728
- ...(!horizontalBars && yAxisWidth != null ? { width: yAxisWidth, overflow: "truncate" as const } : {}),
2952
+ formatter: percent ? (v: number) => `${v}%` : (v: number) => tickFormatter(v),
2953
+ // Fitted to the data: the lowest tick would print over the first x label at the bottom left. The gridline stays.
2954
+ showMinLabel: fit && minValue == null && !horizontalBars ? false : undefined,
2955
+ // Horizontal: ticks that would still touch on a narrow plot are dropped.
2956
+ hideOverlap: horizontalBars ? true : undefined,
2957
+ // A fixed width lines up side-by-side plots, but a value tick is never cut: the grid contains it.
2958
+ width: horizontalBars ? undefined : yAxisWidth,
729
2959
  },
730
2960
  name: horizontalBars ? xAxisLabel : yAxisLabel,
731
2961
  nameLocation: "middle" as const,
732
2962
  nameGap: horizontalBars ? 28 : (yAxisWidth ?? 48) + 8,
733
2963
  }
734
2964
 
735
- return {
736
- animationDuration: 400,
2965
+ const legendItems = [
2966
+ ...categories,
2967
+ ...(forecast ? [forecastLabel] : []),
2968
+ ...(provStart !== -1 ? [provisionalLabel] : []),
2969
+ ...(barTargets ? [barTargetName] : []),
2970
+ ...(hasTarget ? [targetText] : []),
2971
+ ]
2972
+ const option = {
2973
+ ...chartMotion(reducedMotion),
737
2974
  legend: {
738
2975
  show: showLegend,
739
2976
  top: 0,
740
- right: 0,
741
- type: "scroll",
2977
+ // Narrow: left-aligned and wrapping above the plot, so nothing is cut off at the right edge.
2978
+ ...(plotWidth !== undefined && plotWidth < NARROW_PLOT_WIDTH
2979
+ ? { left: 0, right: 0 }
2980
+ : { right: reserveActions ? ACTIONS_RESERVE : 0 }),
2981
+ // Plain wraps onto a second line at narrow widths instead of hiding items behind arrows.
2982
+ type: "plain",
742
2983
  icon: "circle",
743
2984
  itemWidth: 8,
744
2985
  itemHeight: 8,
745
2986
  itemGap: 16,
2987
+ // The target marker is a tick, not a dot.
2988
+ // The target is a row of dots and the forecast a row of dashes — their lines' patterns — and a per-bar target a tick.
2989
+ data: legendItems.map((name) =>
2990
+ barTargets && name === barTargetName
2991
+ ? { name, icon: TARGET_LEGEND_ICON }
2992
+ : forecast && name === forecastLabel
2993
+ ? { name, icon: FORECAST_DASHED_ICON }
2994
+ : hasTarget && name === targetText
2995
+ ? { name, icon: TARGET_DOTTED_ICON }
2996
+ : name,
2997
+ ),
2998
+ formatter: nameLabels ? (name: string) => labelOf(name, nameLabels) : undefined,
746
2999
  },
747
3000
  grid: {
748
- top: showLegend ? 36 : 12,
749
- // Lines start and end on the outermost ticks, so the last label hangs past the plot.
750
- right: kind === "bar" ? 12 : 24,
3001
+ top:
3002
+ (showLegend ? 12 + LEGEND_LINE_HEIGHT * legendLines(legendItems, plotWidth, reserveActions ? ACTIONS_RESERVE : 0) : 12) +
3003
+ // The flat target label of a horizontal bar chart sits above the plot.
3004
+ (horizontalBars && hasTarget ? 18 : 0) +
3005
+ // The label of a band over bars sits above the plot's top edge.
3006
+ (kind === "bar" && notes.some((n) => n.to !== undefined) ? BAND_LABEL_ROOM : 0) +
3007
+ // The boundary label of a forecast sits above the plot's top edge too.
3008
+ (forecast ? FORECAST_LABEL_ROOM : 0),
3009
+ // Lines start and end on the outermost ticks, so the last x label (and an edge
3010
+ // highlight) hangs past the plot; a horizontal bar's highlight sits past its end.
3011
+ right: horizontalBars ? (highlightPoints.length > 0 ? 64 : 16) : kind === "bar" ? 16 : LINE_RIGHT_MARGIN,
751
3012
  bottom: xAxisLabel ? 24 : 4,
752
3013
  left: yAxisLabel ? 24 : 4,
753
3014
  containLabel: true,
@@ -759,38 +3020,250 @@ function buildCartesianOption(cfg: CartesianChartConfig): EChartsOption {
759
3020
  formatter: (params: unknown) => {
760
3021
  const list = (Array.isArray(params) ? params : [params]) as AxisTooltipParam[]
761
3022
  const i = list[0]?.dataIndex ?? 0
762
- const row = data[i] ?? {}
763
- return tooltipHtml(
764
- String(row[index] ?? ""),
765
- list.map((p) => ({
766
- name: p.seriesName ?? "",
767
- color: typeof p.color === "string" ? p.color : "currentColor",
768
- value: cellNumber(row[p.seriesName ?? ""]),
769
- })),
770
- valueFormatter,
771
- )
3023
+ const row = i <= lastActual ? (data[i] ?? {}) : {}
3024
+ const rows: TooltipRow[] = []
3025
+ // The main series' difference from the comparison: one muted line under its row.
3026
+ const primary = mainIdx[0]
3027
+ const noteFor = (at: number): { note?: string } => {
3028
+ if (!comparison || compIdx === -1 || at !== primary || i > lastActual) return {}
3029
+ return {
3030
+ note: comparisonNote(
3031
+ cellNumber(row[categories[at]!]),
3032
+ cellNumber(row[comparison.category]),
3033
+ comparison,
3034
+ compGrain,
3035
+ cfg.comparisonFormat,
3036
+ locale,
3037
+ ),
3038
+ }
3039
+ }
3040
+ const shares = percent ? cartesianSeriesValues(i <= lastActual ? [row] : [], categories, "percent") : null
3041
+ // Rows follow the legend order (categories first), not ECharts' own series order.
3042
+ const legendRank = (p: AxisTooltipParam) => {
3043
+ const at = categories.indexOf(p.seriesName ?? "")
3044
+ return at === -1 ? categories.length : at
3045
+ }
3046
+ for (const p of [...list].sort((a, b) => legendRank(a) - legendRank(b))) {
3047
+ const color = typeof p.color === "string" ? p.color : "currentColor"
3048
+ if (p.seriesId === FORECAST_SERIES_ID) {
3049
+ // At and before the boundary the forecast repeats the actual value.
3050
+ if (i > lastActual) rows.push({ name: p.seriesName ?? forecastLabel, color, value: forecastValues[i] ?? null })
3051
+ continue
3052
+ }
3053
+ if (p.seriesId?.startsWith("__")) continue
3054
+ if (i > lastActual) continue
3055
+ const name = p.seriesName ?? ""
3056
+ const at = categories.indexOf(name)
3057
+ const share = shares && at !== -1 ? (shares[at]![0] ?? undefined) : undefined
3058
+ rows.push({
3059
+ name: labelOf(name, nameLabels),
3060
+ color: at === compIdx ? (comparisonColor ?? color) : color,
3061
+ value: cellNumber(row[name]),
3062
+ ...(share !== undefined ? { share } : {}),
3063
+ ...(at !== -1 ? noteFor(at) : {}),
3064
+ })
3065
+ }
3066
+ if (stackTotals && i <= lastActual && rows.length > 1) {
3067
+ rows.push({ name: STACK_TOTAL_LABEL, color: "transparent", value: stackTotals[i] ?? null })
3068
+ }
3069
+ const provisional = provStart !== -1 && i >= provStart && i <= lastActual
3070
+ if (provisional) {
3071
+ // The confirmed series are empty here: rows come from the data, under a 「速報」 title.
3072
+ rows.length = 0
3073
+ categories.forEach((name, at) => {
3074
+ const share = shares ? (shares[at]![0] ?? undefined) : undefined
3075
+ rows.push({
3076
+ name,
3077
+ color: at === compIdx ? (comparisonColor ?? "currentColor") : palette[at] || "currentColor",
3078
+ value: cellNumber(row[name]),
3079
+ ...(share !== undefined ? { share } : {}),
3080
+ ...noteFor(at),
3081
+ })
3082
+ })
3083
+ if (stackTotals && rows.length > 1) rows.push({ name: STACK_TOTAL_LABEL, color: "transparent", value: stackTotals[i] ?? null })
3084
+ }
3085
+ const title = tooltipTitles[i] ?? labels[i] ?? ""
3086
+ const lines: string[] = []
3087
+ if (barTargets && i <= lastActual) {
3088
+ const total = stackTotals ? (stackTotals[i] ?? null) : (values[0]?.[i] ?? null)
3089
+ const note = barTargetNote(barTargetName, total, barTargets[i] ?? null, valueFormatter)
3090
+ if (note) lines.push(note)
3091
+ }
3092
+ for (const note of notes) {
3093
+ if (note.to === undefined ? note.from === i : note.from <= i && i <= note.to) lines.push(note.label)
3094
+ }
3095
+ return tooltipHtml(provisional ? `${title}(${provisionalLabel})` : title, rows, valueFormatter, lines)
772
3096
  },
773
3097
  },
774
3098
  xAxis: horizontalBars ? valueAxis : categoryAxis,
775
3099
  yAxis: horizontalBars ? categoryAxis : valueAxis,
776
3100
  series,
777
- } as EChartsOption
3101
+ }
3102
+ return mergeChartOptions(option as EChartsOption, chartOptions)
778
3103
  }
779
3104
 
780
3105
  /* ------------------------------------------------------------------ donut */
781
3106
 
782
3107
  type DonutVariant = "donut" | "pie"
783
3108
 
3109
+ /** What the donut prints in its hole (`donutOptions.centerLabel`). */
3110
+ type DonutCenterLabel = "none" | "total" | "top"
3111
+
3112
+ /**
3113
+ * The center of the donut as one of the three built-ins or a custom node.
3114
+ * Default `"none"`; the legacy `showLabel` (`false` → none, an explicit `true` →
3115
+ * total, the old default) and `label` (a custom node) still win over the default.
3116
+ */
3117
+ function resolveDonutCenter(
3118
+ centerLabel: DonutChartOptions["centerLabel"],
3119
+ { showLabel, label }: { showLabel?: boolean; label?: ReactNode } = {},
3120
+ ): { kind: DonutCenterLabel } | { kind: "custom"; node: ReactNode } {
3121
+ if (showLabel === false) return { kind: "none" }
3122
+ if (centerLabel === "none") return { kind: "none" }
3123
+ if (centerLabel === "total") return { kind: "total" }
3124
+ if (centerLabel === "top") return { kind: "top" }
3125
+ if (centerLabel !== undefined && centerLabel !== null && centerLabel !== false) return { kind: "custom", node: centerLabel }
3126
+ if (label !== undefined && label !== null && label !== false) return { kind: "custom", node: label }
3127
+ return { kind: showLabel === true ? "total" : "none" }
3128
+ }
3129
+
3130
+ /** Below this plot width (px) the outside labels can't fit beside the ring. */
3131
+ const DONUT_OUTSIDE_LABEL_MIN_WIDTH = 440
3132
+
3133
+ /**
3134
+ * How many slices get an outside label. A share is printed once: the legend
3135
+ * carries every slice's share, so with a legend there are no outside labels;
3136
+ * without one the 2 largest are labelled when the plot is wide enough
3137
+ * (`plotWidth` `null` = not measured yet → labelled).
3138
+ */
3139
+ function donutOutsideLabelCount(plotWidth: number | null, showLegend: boolean): number {
3140
+ if (showLegend) return 0
3141
+ return plotWidth !== null && plotWidth < DONUT_OUTSIDE_LABEL_MIN_WIDTH ? 0 : DONUT_OUTSIDE_LABELS
3142
+ }
3143
+
3144
+ /** The `"top"` center: the largest real slice's name (`label`) and share (`amount`); `null` when there is none. */
3145
+ function donutTopText(
3146
+ slices: readonly DonutOptionSlice[],
3147
+ labels?: Readonly<Record<string, string>>,
3148
+ ): { label: string; amount: string } | null {
3149
+ const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
3150
+ const top = [...slices].filter((s) => !s.isOther && sliceValue(s.value) > 0).sort((a, b) => sliceValue(b.value) - sliceValue(a.value))[0]
3151
+ return top ? { label: labelOf(top.name, labels), amount: donutShareText(top.value, total) } : null
3152
+ }
3153
+
3154
+ /** DonutChart-only settings. */
3155
+ interface DonutChartOptions {
3156
+ /** `"donut"`(中央に穴とラベル)か `"pie"`。既定 `"donut"`。 */
3157
+ variant?: DonutVariant
3158
+ /** @deprecated `centerLabel` を使う。`false` は `centerLabel: "none"` と同じ。`true` を明示すると `"total"` 扱い(以前の既定)。 */
3159
+ showLabel?: boolean
3160
+ /**
3161
+ * 穴の中央に出すもの。`"none"`(既定。何も出さない。合計は KPI と重複しがち)/ `"total"`(「合計」と
3162
+ * 合計を書式化した値。`totalLabel` / `unit` を添える)/ `"top"`(最大の切片の名前と構成比)。
3163
+ * それ以外のノードを渡すとそのまま中央に置く。donut のみ。
3164
+ */
3165
+ centerLabel?: DonutCenterLabel | ReactNode
3166
+ /** 中央ラベルの見出し(何の合計か)。既定「合計」。 */
3167
+ totalLabel?: string
3168
+ /** 中央ラベルの合計に添える単位(`"セッション"` → 「9.2万 セッション」)。 */
3169
+ unit?: string
3170
+ /** 凡例(名前と構成比、大きい順)を出す。広いときは右、狭いときは下。既定 `true`。構成比は凡例だけが持つ(凡例を消すと、広いときだけ大きい 2 切片に外ラベルで名前と構成比が出る)。 */
3171
+ showLegend?: boolean
3172
+ /** 個別に描く切片の数。超えた分は大きさ順の残りを「その他」1 切片にまとめる。既定 5。 */
3173
+ maxSlices?: number
3174
+ }
3175
+
3176
+ /** A slice as the builder takes it: already sorted, folded and coloured (see `donutSlices`). */
3177
+ interface DonutOptionSlice {
3178
+ name: string
3179
+ value: number
3180
+ /** The folded「その他」slice: never labelled outside. */
3181
+ isOther?: boolean
3182
+ }
3183
+
3184
+ /** How many of the largest slices get an outside label (「自然検索 41%」) by default. */
3185
+ const DONUT_OUTSIDE_LABELS = 2
3186
+
3187
+ const DEFAULT_TOTAL_LABEL = "合計"
3188
+
3189
+ const sliceValue = (value: number) => (Number.isFinite(value) && value > 0 ? value : 0)
3190
+
3191
+ /** A slice's share of `total` as text: whole percent, `<1%` for a sliver, `0%` for nothing. */
3192
+ function donutShareText(value: number, total: number): string {
3193
+ const v = sliceValue(value)
3194
+ if (total <= 0 || v === 0) return "0%"
3195
+ const pct = (v / total) * 100
3196
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
3197
+ }
3198
+
3199
+ /** One legend row: name, share text and the slice's position (for its colour). */
3200
+ interface DonutLegendItem {
3201
+ name: string
3202
+ value: number
3203
+ share: string
3204
+ isOther: boolean
3205
+ /** Index into the slices / palette. */
3206
+ slice: number
3207
+ }
3208
+
3209
+ /**
3210
+ * The donut legend: every slice with its share, largest first, the folded
3211
+ * 「その他」 last (it is a remainder, not a rank).
3212
+ */
3213
+ function donutLegendItems(slices: readonly DonutOptionSlice[]): DonutLegendItem[] {
3214
+ const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
3215
+ return slices
3216
+ .map((s, slice) => ({ name: s.name, value: sliceValue(s.value), share: donutShareText(s.value, total), isOther: Boolean(s.isOther), slice }))
3217
+ .sort((a, b) => Number(a.isOther) - Number(b.isOther) || b.value - a.value || a.slice - b.slice)
3218
+ }
3219
+
3220
+ /**
3221
+ * The default center label: what is totalled (「合計」), the formatted total
3222
+ * (`amount`, the big line), the unit (a small line under it) and both as one
3223
+ * string (`value`, 「9.2万 セッション」).
3224
+ */
3225
+ function donutCenterText(
3226
+ total: number,
3227
+ valueFormatter: (value: number) => string,
3228
+ { totalLabel = DEFAULT_TOTAL_LABEL, unit }: { totalLabel?: string; unit?: string } = {},
3229
+ ): { label: string; value: string; amount: string; unit?: string } {
3230
+ const amount = valueFormatter(total)
3231
+ return { label: totalLabel, value: unit ? `${amount} ${unit}` : amount, amount, ...(unit ? { unit } : {}) }
3232
+ }
3233
+
3234
+ /** The ring's inner radius, in percent of the plot's shorter side / 2 — with and without outside labels. */
3235
+ const DONUT_INNER_WITH_LABELS = 50
3236
+ const DONUT_INNER_PLAIN = 72
3237
+
3238
+ /**
3239
+ * The hole's diameter as a fraction of the plot's shorter side (ECharts reads a
3240
+ * `%` radius against half of it), so an HTML center label can be sized to fit.
3241
+ */
3242
+ function donutHoleRatio(withOutsideLabels: boolean): number {
3243
+ return (withOutsideLabels ? DONUT_INNER_WITH_LABELS : DONUT_INNER_PLAIN) / 100
3244
+ }
3245
+
784
3246
  interface DonutChartConfig {
785
- data: readonly Record<string, unknown>[]
786
- category: string
787
- value: string
788
- /** Resolved slice colours, by row position. `""`/missing → theme palette. */
3247
+ /** Slices in draw order (largest first, 「その他」 last). */
3248
+ slices: readonly DonutOptionSlice[]
3249
+ /** Resolved slice colours, by slice position. `""`/missing → theme palette. */
789
3250
  palette: readonly string[]
3251
+ /** Display names for slice names (tooltip, outside labels). Missing keys show as they are. */
3252
+ labels?: Readonly<Record<string, string>>
790
3253
  valueFormatter: (value: number) => string
3254
+ /** The value column's name, shown in the tooltip row. */
3255
+ valueName?: string
791
3256
  variant?: DonutVariant
792
3257
  showTooltip?: boolean
3258
+ /** How many of the largest (non-「その他」) slices get an outside label. Default `DONUT_OUTSIDE_LABELS` (2); 0 = none. */
3259
+ outsideLabels?: number
3260
+ /** Name of the selected slice; the others are dimmed. */
793
3261
  active?: string | null
3262
+ /** Colour of the outside labels (resolved foreground). Default: the theme's text colour. */
3263
+ labelColor?: string
3264
+ reducedMotion?: boolean
3265
+ /** Deep-merged onto the generated option last. */
3266
+ chartOptions?: EChartsOption
794
3267
  }
795
3268
 
796
3269
  /** Sum of the `value` column, ignoring gaps and negative cells. */
@@ -808,10 +3281,41 @@ interface ItemTooltipParam {
808
3281
  color?: unknown
809
3282
  }
810
3283
 
3284
+ /**
3285
+ * The donut / pie option. Only the `outsideLabels` largest slices carry an
3286
+ * outside label (name + share); the legend, center label and tooltip carry the
3287
+ * rest. No entrance animation, a short ease on updates.
3288
+ */
811
3289
  function buildDonutOption(cfg: DonutChartConfig): EChartsOption {
812
- const { data, category, value, palette, valueFormatter, variant = "donut", showTooltip = true, active = null } = cfg
813
- return {
814
- animationDuration: 400,
3290
+ const {
3291
+ slices,
3292
+ palette,
3293
+ labels: nameLabels,
3294
+ valueFormatter,
3295
+ valueName = "",
3296
+ variant = "donut",
3297
+ showTooltip = true,
3298
+ outsideLabels = DONUT_OUTSIDE_LABELS,
3299
+ active = null,
3300
+ labelColor,
3301
+ reducedMotion = false,
3302
+ chartOptions,
3303
+ } = cfg
3304
+ const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
3305
+ // The largest real slices, by value (the slices arrive sorted, but don't rely on it).
3306
+ const labelled = new Set(
3307
+ slices
3308
+ .map((s, i) => ({ i, v: sliceValue(s.value), other: Boolean(s.isOther) }))
3309
+ .filter((s) => !s.other && s.v > 0)
3310
+ .sort((a, b) => b.v - a.v || a.i - b.i)
3311
+ .slice(0, Math.max(0, outsideLabels))
3312
+ .map((s) => s.i),
3313
+ )
3314
+ const withLabels = labelled.size > 0
3315
+ // Room for the outside labels: the ring shrinks inside the plot.
3316
+ const outer = withLabels ? "70%" : "100%"
3317
+ const option = {
3318
+ ...chartMotion(reducedMotion),
815
3319
  tooltip: {
816
3320
  show: showTooltip,
817
3321
  trigger: "item",
@@ -820,37 +3324,49 @@ function buildDonutOption(cfg: DonutChartConfig): EChartsOption {
820
3324
  const n = cellNumber(p.value)
821
3325
  const share = typeof p.percent === "number" ? ` (${p.percent.toFixed(1)}%)` : ""
822
3326
  return tooltipHtml(
823
- `${p.name ?? ""}${share}`,
824
- [{ name: value, color: typeof p.color === "string" ? p.color : "currentColor", value: n }],
3327
+ `${labelOf(p.name ?? "", nameLabels)}${share}`,
3328
+ [{ name: valueName, color: typeof p.color === "string" ? p.color : "currentColor", value: n }],
825
3329
  valueFormatter,
826
3330
  )
827
3331
  },
828
3332
  },
829
3333
  series: [
830
3334
  {
3335
+ id: "slices",
831
3336
  type: "pie",
832
- radius: variant === "donut" ? ["72%", "100%"] : [0, "100%"],
3337
+ radius: variant === "donut" ? [`${donutHoleRatio(withLabels) * 100}%`, outer] : [0, outer],
833
3338
  center: ["50%", "50%"],
834
3339
  avoidLabelOverlap: true,
835
- label: { show: false },
836
- labelLine: { show: false },
3340
+ // Plain text: no outline / shadow, which reads as a halo on a dark surface.
3341
+ label: {
3342
+ show: false,
3343
+ position: "outside",
3344
+ color: labelColor,
3345
+ textBorderWidth: 0,
3346
+ textBorderColor: "transparent",
3347
+ textShadowBlur: 0,
3348
+ textShadowColor: "transparent",
3349
+ },
3350
+ labelLine: { show: false, length: 8, length2: 8 },
837
3351
  // A hairline gap between slices instead of a border — no background colour to match.
838
- padAngle: data.length > 1 ? 1 : 0,
3352
+ padAngle: slices.length > 1 ? 1 : 0,
839
3353
  itemStyle: { borderRadius: variant === "donut" ? 2 : 0 },
840
3354
  emphasis: { scale: true, scaleSize: 4 },
841
- data: data.map((row, i) => {
842
- const name = String(row[category] ?? "")
843
- const color = palette[i] || undefined
844
- const n = cellNumber(row[value])
845
- return {
846
- name,
847
- value: n !== null && n > 0 ? n : 0,
848
- itemStyle: { color, opacity: active !== null && active !== name ? DIMMED : 1 },
849
- }
850
- }),
3355
+ data: slices.map((slice, i) => ({
3356
+ name: slice.name,
3357
+ value: sliceValue(slice.value),
3358
+ itemStyle: { color: palette[i] || undefined, opacity: active !== null && active !== slice.name ? DIMMED : 1 },
3359
+ ...(labelled.has(i)
3360
+ ? {
3361
+ label: { show: true, formatter: () => `${labelOf(slice.name, nameLabels)} ${donutShareText(slice.value, total)}` },
3362
+ labelLine: { show: true },
3363
+ }
3364
+ : {}),
3365
+ })),
851
3366
  },
852
3367
  ],
853
- } as EChartsOption
3368
+ }
3369
+ return mergeChartOptions(option as EChartsOption, chartOptions)
854
3370
  }
855
3371
 
856
3372
  /* -------------------------------------------------------------- selection */
@@ -913,92 +3429,296 @@ function useChartSelection(
913
3429
  return { active: interactive ? active : null, onEvents }
914
3430
  }
915
3431
 
3432
+ /**
3433
+ * Display name for `key`: `labels[key]` when present, else `key` itself.
3434
+ * (Own keys only, so `"constructor"` is not looked up on the prototype.)
3435
+ */
3436
+ function labelOf(key: string, labels?: Readonly<Record<string, string>>): string {
3437
+ return hasLabel(labels, key) ? labels![key]! : key
3438
+ }
3439
+
3440
+ /** `data` with each row's `index` cell replaced by its display name (rows are copied, not mutated). */
3441
+ function labelRows<Row extends Record<string, unknown>>(
3442
+ data: readonly Row[],
3443
+ index: string,
3444
+ labels?: Readonly<Record<string, string>>,
3445
+ ): Row[] {
3446
+ if (!labels) return data as Row[]
3447
+ return data.map((row) => ({ ...row, [index]: labelOf(String(row[index] ?? ""), labels) }))
3448
+ }
3449
+
3450
+ /** Whether `labels` renames `key` (own keys only). */
3451
+ function hasLabel(labels: Readonly<Record<string, string>> | undefined, key: string): boolean {
3452
+ return Boolean(labels) && Object.prototype.hasOwnProperty.call(labels, key)
3453
+ }
3454
+
3455
+ /* ------------------------------------------------------------ provisional */
3456
+
3457
+ /** The default label for points that are not final yet. */
3458
+ const DEFAULT_PROVISIONAL_LABEL = "速報"
3459
+
3460
+ /**
3461
+ * Position of the first provisional point: the first entry of `indexValues`
3462
+ * that equals `from` (compared as text, so `"2026-09"` and a Date-less string
3463
+ * key both work). `-1` when `from` is unset or not among the values — the chart
3464
+ * then draws everything as confirmed.
3465
+ */
3466
+ function provisionalStart(indexValues: readonly unknown[], from: string | number | undefined | null): number {
3467
+ if (from === undefined || from === null) return -1
3468
+ const key = String(from)
3469
+ return indexValues.findIndex((value) => String(value ?? "") === key)
3470
+ }
3471
+
3472
+ /**
3473
+ * Split one series at `start` (see `provisionalStart`). `confirmed` keeps the
3474
+ * points before `start`; `provisional` keeps `start` onward plus the last
3475
+ * confirmed point, so the dashed line joins the solid one. `start <= 0` or
3476
+ * `-1` leaves nothing to join (all provisional / none provisional).
3477
+ */
3478
+ function splitProvisional(
3479
+ values: readonly (number | null)[],
3480
+ start: number,
3481
+ ): { confirmed: (number | null)[]; provisional: (number | null)[] } {
3482
+ if (start < 0) return { confirmed: [...values], provisional: values.map(() => null) }
3483
+ return {
3484
+ confirmed: values.map((v, i) => (i < start ? v : null)),
3485
+ provisional: values.map((v, i) => (i >= Math.max(0, start - 1) ? v : null)),
3486
+ }
3487
+ }
3488
+
916
3489
  /* ---------- end of inlined code ---------- */
917
3490
 
918
- export interface DonutChartProps {
919
- /** 行の配列。1 行 = 1 切片。 */
920
- data: Record<string, unknown>[]
3491
+ export interface DonutChartProps<T extends Record<string, unknown> = Record<string, unknown>>
3492
+ extends Omit<ChartCommonProps<T>, "index" | "categories" | "colors"> {
921
3493
  /** 切片の名前に使う列名。 */
922
- category: string
923
- /** 切片の大きさに使う列名(number か数値文字列)。0 以下と欠損は 0 扱い。 */
924
- value: string
925
- /** 切片の色(行の順)。`"chart-1"`〜`"chart-5"` か CSS カラー。省略時はトークン順で、足りなければ繰り返す。 */
926
- colors?: ChartColor[]
927
- /** `"donut"`(中央に穴とラベル)か `"pie"`。既定 `"donut"`。 */
928
- variant?: DonutVariant
929
- /** ツールチップと中央ラベルの数値の書式。 */
930
- valueFormatter?: ValueFormatter
931
- /** 中央ラベル。省略時は合計を `valueFormatter` で書いたもの。donut のみ。 */
932
- label?: ReactNode
933
- /** 中央ラベルを出す。既定 `true`(donut のみ)。 */
934
- showLabel?: boolean
3494
+ index?: keyof T & string
3495
+ /** 切片の大きさに使う列名を 1 つだけ入れた配列(`["売上"]`)。2 つ以上渡しても最初の 1 つだけを使う。 */
3496
+ categories?: (keyof T & string)[]
3497
+ /** 切片の色(大きい順)。`"chart-1"`〜`"chart-5"` か意味色(`"positive"` など。面用の `--<tone>-fill` で塗る)。省略時はトークン順。「その他」は常に灰色。 */
3498
+ colors?: ChartSeriesColor[]
3499
+ /** 切片の名前(`index` の値)→ 表示名。凡例・ツールチップ・外ラベル・データ表に反映。例 `{ organic: "自然検索" }`。無いキーはそのまま。データ表の列名を直すには、`index` と値のキーも渡す(`{ source: "流入元", sessions: "セッション" }`。既定は「項目」「値」)。 */
3500
+ labels?: Record<string, string>
3501
+ /** ドーナツ固有の設定(形・中央に出すもの `centerLabel`・凡例・切片の上限)。同名のフラットな props より優先。 */
3502
+ donutOptions?: DonutChartOptions
3503
+ /**
3504
+ * グラフが言っていることの 1 文要約(自由文)。`"auto"` なら slices から「<見出し>: 最大は <名前>(<構成比>)」を組む。
3505
+ * 順位や構成比を文に書くなら `"auto"` を使うか data から作る。省略時は要約なし。例: `summary="auto"`
3506
+ */
3507
+ summary?: string | "auto"
935
3508
  showTooltip?: boolean
936
3509
  /** 切片のクリックで呼ばれる。同じ切片をもう一度クリックすると `null`。渡すと選択以外が薄くなる。 */
937
3510
  onValueChange?: (value: ChartEventPayload) => void
3511
+ /** @deprecated `index` を使う。 */
3512
+ category?: keyof T & string
3513
+ /** @deprecated `categories={[value]}` を使う。 */
3514
+ value?: keyof T & string
3515
+ /** @deprecated `donutOptions.variant` を使う。 */
3516
+ variant?: DonutVariant
3517
+ /** @deprecated `donutOptions.centerLabel` を使う。 */
3518
+ label?: ReactNode
3519
+ /** @deprecated `donutOptions.centerLabel`(`"none"` で消す)を使う。 */
3520
+ showLabel?: boolean
3521
+ /** @deprecated `isLoading` を使う。 */
938
3522
  loading?: boolean
939
- ariaLabel?: string
940
- /** 外枠のクラス。既定の大きさは `size-40`(160px 四方)。 */
941
- className?: string
942
3523
  }
943
3524
 
944
- export const DonutChart = forwardRef<HTMLDivElement, DonutChartProps>(function DonutChart(
3525
+ /** The element's width, kept current (`null` until measured). */
3526
+ function useElementWidth(): [(el: HTMLDivElement | null) => void, number | null] {
3527
+ const [node, setNode] = useState<HTMLDivElement | null>(null)
3528
+ const [width, setWidth] = useState<number | null>(null)
3529
+ useEffect(() => {
3530
+ if (!node || typeof ResizeObserver === "undefined") return
3531
+ setWidth(node.getBoundingClientRect().width)
3532
+ const observer = new ResizeObserver((entries) => setWidth(entries[0]?.contentRect.width ?? null))
3533
+ observer.observe(node)
3534
+ return () => observer.disconnect()
3535
+ }, [node])
3536
+ return [setNode, width]
3537
+ }
3538
+
3539
+ /** Rows not given yet (a draft fills props in steps): draw the empty state, keep the same array between renders. */
3540
+ const NO_ROWS: never[] = []
3541
+
3542
+ function DonutChartImpl<T extends Record<string, unknown>>(
945
3543
  {
946
- data,
947
- category,
948
- value,
3544
+ data = NO_ROWS,
3545
+ index,
3546
+ categories,
949
3547
  colors,
950
- variant = "donut",
951
- valueFormatter = defaultValueFormatter,
952
- label,
953
- showLabel = true,
3548
+ labels,
3549
+ format,
3550
+ valueFormatter: valueFormatterProp,
3551
+ title,
3552
+ summary,
3553
+ actions,
3554
+ fileName,
3555
+ isLoading,
3556
+ loading,
3557
+ emptyState,
3558
+ height,
3559
+ chartOptions,
3560
+ donutOptions,
954
3561
  showTooltip = true,
955
3562
  onValueChange,
956
- loading,
3563
+ category,
3564
+ value,
3565
+ variant,
3566
+ label,
3567
+ showLabel,
957
3568
  ariaLabel,
958
3569
  className,
959
- },
960
- ref,
3570
+ ...rest
3571
+ }: DonutChartProps<T>,
3572
+ ref: ForwardedRef<HTMLDivElement>,
961
3573
  ) {
3574
+ const labelKey: string = index ?? category ?? ""
3575
+ const valueKey: string = categories?.[0] ?? value ?? ""
3576
+ const shape = donutOptions?.variant ?? variant ?? "donut"
3577
+ const center = resolveDonutCenter(donutOptions?.centerLabel, { showLabel: donutOptions?.showLabel ?? showLabel, label })
3578
+ const maxSlices = donutOptions?.maxSlices
3579
+ const showLegend = donutOptions?.showLegend ?? true
3580
+ const valueFormatter = useMemo(() => resolveValueFormatter(valueFormatterProp, format), [valueFormatterProp, format])
3581
+
962
3582
  const tokens = useChartTokens()
963
- const palette = useMemo(
964
- () => resolveChartColors(chartColorsFor(colors, data.length), tokens),
965
- [colors, data.length, tokens],
3583
+ const slices = useMemo(
3584
+ () => donutSlices(data, { index: labelKey, value: valueKey, colors, maxSlices, otherColor: CHART_OTHER_COLOR }),
3585
+ [data, labelKey, valueKey, colors, maxSlices],
966
3586
  )
967
- const { active, onEvents } = useChartSelection(data, onValueChange, "slice")
3587
+ const palette = useMemo(() => resolveChartColors(slices.map((s) => chartFillName(s.color)), tokens), [slices, tokens])
3588
+ const rows = useMemo(() => slices.map((s) => s.row), [slices])
3589
+ const { active, onEvents } = useChartSelection(rows, onValueChange, "slice")
3590
+ const [plotRef, plotWidth] = useElementWidth()
3591
+ // The legend carries every share, so outside labels (name + share) only stand in for it when it is hidden.
3592
+ const outsideLabels = donutOutsideLabelCount(plotWidth, showLegend)
3593
+ const holeRatio = donutHoleRatio(outsideLabels > 0)
968
3594
  const option = useMemo(
969
3595
  () =>
970
3596
  buildDonutOption({
971
- data,
972
- category,
973
- value,
3597
+ slices,
974
3598
  palette,
3599
+ labels,
975
3600
  valueFormatter,
976
- variant,
3601
+ valueName: valueKey,
3602
+ variant: shape,
977
3603
  showTooltip,
3604
+ outsideLabels,
978
3605
  active: active?.category ?? null,
3606
+ labelColor: tokens?.foreground ?? undefined,
3607
+ chartOptions,
979
3608
  }),
980
- [data, category, value, palette, valueFormatter, variant, showTooltip, active],
3609
+ [slices, palette, labels, valueFormatter, valueKey, shape, showTooltip, outsideLabels, active, tokens, chartOptions],
3610
+ )
3611
+ const total = slices.reduce((sum, s) => sum + s.value, 0)
3612
+ const legend = useMemo(() => donutLegendItems(slices), [slices])
3613
+ // Sized off the hole (cqmin of the plot): the small caption above, the big figure, the unit small below.
3614
+ const hole = holeRatio * 100
3615
+ const captionStyle = { fontSize: `clamp(10px, ${hole * 0.1}cqmin, 14px)` }
3616
+ const figureStyle = { fontSize: `clamp(14px, ${hole * 0.22}cqmin, 32px)` }
3617
+ const caption = (label: string, amount: string, unit?: string) => (
3618
+ <span className="flex flex-col items-center gap-[0.15em] whitespace-nowrap">
3619
+ <span className="max-w-full truncate font-normal text-muted-foreground" style={captionStyle}>
3620
+ {label}
3621
+ </span>
3622
+ <span className="leading-none" style={figureStyle}>
3623
+ {amount}
3624
+ </span>
3625
+ {unit && (
3626
+ <span className="font-normal text-muted-foreground" style={captionStyle}>
3627
+ {unit}
3628
+ </span>
3629
+ )}
3630
+ </span>
3631
+ )
3632
+ let centerLabel: ReactNode = null
3633
+ if (center.kind === "custom") centerLabel = center.node
3634
+ else if (center.kind === "total") {
3635
+ const text = donutCenterText(total, valueFormatter, { totalLabel: donutOptions?.totalLabel, unit: donutOptions?.unit })
3636
+ centerLabel = caption(text.label, text.amount, text.unit)
3637
+ } else if (center.kind === "top") {
3638
+ const top = donutTopText(slices, labels)
3639
+ centerLabel = top && caption(top.label, top.amount)
3640
+ }
3641
+ // Built from the slices (names and shares), not the column keys.
3642
+ const a11yLabel =
3643
+ ariaLabel ?? `構成比のドーナツグラフ(${legend.map((item) => `${labelOf(item.name, labels)} ${item.share}`).join("、")})`
3644
+ const dataTable = useMemo(
3645
+ () =>
3646
+ chartDataTable(
3647
+ // Fixed keys, so `labels` (which renames the rows) cannot collide with the column names.
3648
+ rows.map((row) => ({ name: labelOf(String(row[labelKey] ?? ""), labels), value: row[valueKey] })),
3649
+ "name",
3650
+ ["value"],
3651
+ valueFormatter,
3652
+ { name: labels?.[labelKey] ?? "項目", value: labels?.[valueKey] ?? "値" },
3653
+ ),
3654
+ [rows, labelKey, valueKey, valueFormatter, labels],
981
3655
  )
982
- const centerLabel = label ?? valueFormatter(donutTotal(data, value))
983
3656
 
3657
+ const resolvedSummary = useMemo(
3658
+ () => (summary === "auto" ? buildShareSummary(slices, title) : summary),
3659
+ [summary, slices, title],
3660
+ )
984
3661
  return (
985
- <div ref={ref} data-slot="donut-chart" className={cn("relative size-40", className)}>
986
- <EChart
987
- option={option}
988
- onEvents={onEvents}
989
- loading={loading}
990
- ariaLabel={ariaLabel ?? `${category}別の${value}`}
991
- className="h-full"
992
- />
993
- {variant === "donut" && showLabel && (
994
- <div
995
- data-slot="donut-chart-label"
996
- className="pointer-events-none absolute inset-0 flex items-center justify-center px-[18%] text-center text-lg font-semibold text-foreground tabular-nums"
997
- >
998
- {centerLabel}
3662
+ <ChartFrame
3663
+ {...chartRootProps(rest)}
3664
+ ref={ref}
3665
+ title={title}
3666
+ summary={resolvedSummary}
3667
+ isLoading={isLoading ?? loading ?? false}
3668
+ isEmpty={data.length === 0}
3669
+ emptyState={emptyState}
3670
+ height={height}
3671
+ variant="donut"
3672
+ ariaLabel={a11yLabel}
3673
+ dataTable={dataTable}
3674
+ className={className}
3675
+ >
3676
+ <div data-slot="donut-chart" className="@container/donut h-full w-full">
3677
+ <div className="flex h-full w-full flex-col gap-3 @md/donut:flex-row @md/donut:items-center">
3678
+ {/* A size container, so the center label can be sized in `cqmin` against the ring. */}
3679
+ <div ref={plotRef} className="relative min-h-0 min-w-0 flex-1 @md/donut:h-full" style={{ containerType: "size" }}>
3680
+ <EChart option={option} onEvents={onEvents} height="100%" ariaLabel={a11yLabel} actions={actions} fileName={fileName} exportHeader={{ title, summary: resolvedSummary }} />
3681
+ {shape === "donut" && centerLabel !== null && centerLabel !== false && (
3682
+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
3683
+ {/* A box inscribed in the hole: never wider than the ring's inside, text never wraps mid-word. */}
3684
+ <div
3685
+ data-slot="donut-chart-label"
3686
+ className="flex items-center justify-center overflow-hidden text-center leading-tight font-semibold whitespace-nowrap text-foreground tabular-nums"
3687
+ style={{ width: `${hole * 0.78}cqmin`, height: `${hole * 0.78}cqmin` }}
3688
+ >
3689
+ {centerLabel}
3690
+ </div>
3691
+ </div>
3692
+ )}
3693
+ </div>
3694
+ {showLegend && legend.length > 0 && (
3695
+ <ul
3696
+ data-slot="donut-chart-legend"
3697
+ className="flex shrink-0 flex-wrap gap-x-4 gap-y-1 text-xs @md/donut:w-44 @md/donut:flex-col @md/donut:flex-nowrap"
3698
+ >
3699
+ {legend.map((item) => (
3700
+ <li key={item.slice} data-slot="donut-chart-legend-item" className="flex min-w-0 items-center gap-1.5">
3701
+ <span
3702
+ aria-hidden="true"
3703
+ className="size-2.5 shrink-0 rounded-[2px]"
3704
+ style={{ background: chartFillToCss(slices[item.slice]!.color) }}
3705
+ />
3706
+ <span className="min-w-0 truncate text-muted-foreground">{labelOf(item.name, labels)}</span>
3707
+ <span className="ml-auto pl-2 font-medium text-foreground tabular-nums">{item.share}</span>
3708
+ </li>
3709
+ ))}
3710
+ </ul>
3711
+ )}
999
3712
  </div>
1000
- )}
1001
- </div>
3713
+ </div>
3714
+ </ChartFrame>
1002
3715
  )
1003
- })
3716
+ }
3717
+
3718
+ /** Generic over the row type, so `index` / `categories` keys are checked against `data`. */
3719
+ export const DonutChart = forwardRef(DonutChartImpl as (props: DonutChartProps, ref: ForwardedRef<HTMLDivElement>) => ReactElement) as (<
3720
+ T extends Record<string, unknown>,
3721
+ >(
3722
+ props: DonutChartProps<T> & { ref?: Ref<HTMLDivElement> },
3723
+ ) => ReactElement) & { displayName?: string }
1004
3724
  DonutChart.displayName = "DonutChart"