@squadbase/vantage 0.6.2-dev1.ac99e02 → 0.6.2-dev1.d7c0911

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