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