@squadbase/vantage 0.6.1 → 0.6.2-dev1.0010f67
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/add-4GHF2TX2.js +6 -0
- package/dist/add-4GHF2TX2.js.map +1 -0
- package/dist/{build-O5TVNH4E.js → build-U7GO26HR.js} +9 -9
- package/dist/{build-O5TVNH4E.js.map → build-U7GO26HR.js.map} +1 -1
- package/dist/{check-WFBEDHDR.js → check-MRVAIHG5.js} +7 -7
- package/dist/{check-WFBEDHDR.js.map → check-MRVAIHG5.js.map} +1 -1
- package/dist/chunk-2IAPIOPS.js +152 -0
- package/dist/chunk-2IAPIOPS.js.map +1 -0
- package/dist/chunk-3RJEOP3J.js +174 -0
- package/dist/chunk-3RJEOP3J.js.map +1 -0
- package/dist/chunk-77CISBMG.js +7581 -0
- package/dist/chunk-77CISBMG.js.map +1 -0
- package/dist/{chunk-QDZA5JSL.js → chunk-AABMKHEU.js} +4 -4
- package/dist/{chunk-QDZA5JSL.js.map → chunk-AABMKHEU.js.map} +1 -1
- package/dist/{chunk-PVTHHV7X.js → chunk-ANZLVSEP.js} +28 -7
- package/dist/chunk-ANZLVSEP.js.map +1 -0
- package/dist/chunk-CKWPK4RO.js +50 -0
- package/dist/chunk-CKWPK4RO.js.map +1 -0
- package/dist/chunk-EG4PX726.js +678 -0
- package/dist/chunk-EG4PX726.js.map +1 -0
- package/dist/{chunk-3G43C6OL.js → chunk-GNXCX4WE.js} +46 -3
- package/dist/chunk-GNXCX4WE.js.map +1 -0
- package/dist/chunk-NZ5QIIG4.js +74 -0
- package/dist/chunk-NZ5QIIG4.js.map +1 -0
- package/dist/{chunk-BCE22JSM.js → chunk-PJ4SPXHS.js} +52 -16
- package/dist/chunk-PJ4SPXHS.js.map +1 -0
- package/dist/{chunk-MXI3PZFT.js → chunk-QNOX7WLZ.js} +257 -210
- package/dist/chunk-QNOX7WLZ.js.map +1 -0
- package/dist/{chunk-ZVANIULZ.js → chunk-RNTDBX6S.js} +4 -4
- package/dist/{chunk-ZVANIULZ.js.map → chunk-RNTDBX6S.js.map} +1 -1
- package/dist/chunk-ROHNXP7J.js +123 -0
- package/dist/chunk-ROHNXP7J.js.map +1 -0
- package/dist/chunk-S5MDTHH7.js +466 -0
- package/dist/chunk-S5MDTHH7.js.map +1 -0
- package/dist/chunk-SDJTTMLK.js +1877 -0
- package/dist/chunk-SDJTTMLK.js.map +1 -0
- package/dist/{chunk-EP6JHXSR.js → chunk-SHZM3EXB.js} +68 -12
- package/dist/chunk-SHZM3EXB.js.map +1 -0
- package/dist/chunk-TRMHNMMZ.js +61 -0
- package/dist/chunk-TRMHNMMZ.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-JGRMRXXZ.js → chunk-UWSQUHX6.js} +4 -99
- package/dist/chunk-UWSQUHX6.js.map +1 -0
- package/dist/cli.js +15 -11
- package/dist/cli.js.map +1 -1
- package/dist/client/index.d.ts +34 -3
- package/dist/client/index.js +211 -12
- package/dist/client/index.js.map +1 -1
- package/dist/components/index.d.ts +1768 -30
- package/dist/components/index.js +7 -3
- package/dist/delta-text-CbrOaW83.d.ts +17 -0
- package/dist/{dev-NZRLOQCL.js → dev-O42JFQ64.js} +24 -13
- package/dist/dev-O42JFQ64.js.map +1 -0
- package/dist/doc/index.d.ts +219 -2
- package/dist/doc/index.js +525 -11
- package/dist/doc/index.js.map +1 -1
- package/dist/{docs-ZGDJUHJI.js → docs-JVP4RPKT.js} +3 -3
- package/dist/{docs-ZGDJUHJI.js.map → docs-JVP4RPKT.js.map} +1 -1
- package/dist/{doctor-VFKEMR54.js → doctor-YD3XAAOT.js} +8 -8
- package/dist/doctor-YD3XAAOT.js.map +1 -0
- package/dist/format-DihQkL1N.d.ts +249 -0
- package/dist/markdown/index.js +1 -1
- package/dist/markdown/index.js.map +1 -1
- package/dist/{preview-QDCIVVSR.js → preview-T6CLSQVX.js} +12 -4
- package/dist/preview-T6CLSQVX.js.map +1 -0
- package/dist/query/index.d.ts +0 -11
- package/dist/query/index.js +2 -2
- package/dist/{routes-RHP5FVGD.js → routes-PVKNT777.js} +6 -6
- package/dist/{routes-RHP5FVGD.js.map → routes-PVKNT777.js.map} +1 -1
- package/dist/{search-RFBELGY7.js → search-5LC4XPB5.js} +3 -3
- package/dist/{search-RFBELGY7.js.map → search-5LC4XPB5.js.map} +1 -1
- package/dist/slide/index.d.ts +272 -1
- package/dist/slide/index.js +1086 -19
- package/dist/slide/index.js.map +1 -1
- package/dist/table/index.js +14 -9
- package/dist/table/index.js.map +1 -1
- package/dist/ui/index.d.ts +148 -12
- package/dist/ui/index.js +1340 -87
- package/dist/ui/index.js.map +1 -1
- package/dist/{upgrade-GF2P67M6.js → upgrade-6DT7ADRP.js} +7 -7
- package/dist/{upgrade-GF2P67M6.js.map → upgrade-6DT7ADRP.js.map} +1 -1
- package/dist/vite/index.d.ts +10 -0
- package/dist/vite/index.js +4 -4
- package/docs/en/agent-skills.md +1 -1
- package/docs/en/changelog.md +26 -0
- package/docs/en/cli-reference.md +30 -0
- package/docs/en/components.md +42 -17
- package/docs/en/doc/delta-text.md +40 -0
- package/docs/en/doc/doc-action-items.md +49 -0
- package/docs/en/doc/doc-callout.md +38 -0
- package/docs/en/doc/doc-data-table.md +60 -0
- package/docs/en/doc/doc-executive-summary.md +64 -0
- package/docs/en/doc/doc-figure.md +56 -0
- package/docs/en/doc/doc-key-findings.md +61 -0
- package/docs/en/doc/doc-kpi-scorecard.md +80 -0
- package/docs/en/doc/doc-notes-and-sources.md +43 -0
- package/docs/en/doc/doc-report-header.md +46 -0
- package/docs/en/pages-and-metadata.md +15 -0
- package/docs/en/parts/area-chart.md +99 -0
- package/docs/en/parts/bar-chart.md +91 -0
- package/docs/en/parts/bar-list.md +50 -0
- package/docs/en/parts/category-bar.md +37 -0
- package/docs/en/parts/chart-frame.md +39 -0
- package/docs/en/parts/data-table.md +22 -0
- package/docs/en/parts/delta.md +51 -0
- package/docs/en/parts/donut-chart.md +72 -0
- package/docs/en/parts/format.md +43 -0
- package/docs/en/parts/funnel-steps.md +2 -1
- package/docs/en/parts/heatmap.md +53 -0
- package/docs/en/parts/kpi-card.md +58 -0
- package/docs/en/parts/legend.md +35 -0
- package/docs/en/parts/line-chart.md +94 -0
- package/docs/en/parts/metric-value.md +3 -2
- package/docs/en/parts/page-shell.md +1 -1
- package/docs/en/parts/progress-circle.md +33 -0
- package/docs/en/parts/sample-data.md +39 -0
- package/docs/en/parts/scatter-chart.md +56 -0
- package/docs/en/parts/sparkline.md +1 -1
- package/docs/en/parts/tracker.md +36 -0
- package/docs/en/parts/trend-indicator.md +17 -1
- package/docs/en/parts/updated-at.md +30 -0
- package/docs/en/parts/waterfall-chart.md +56 -0
- package/docs/en/routing.md +4 -2
- package/docs/en/slide/slide-chart-full.md +48 -0
- package/docs/en/slide/slide-chart-insight.md +52 -0
- package/docs/en/slide/slide-columns.md +46 -0
- package/docs/en/slide/slide-comparison.md +68 -0
- package/docs/en/slide/slide-cover.md +39 -0
- package/docs/en/slide/slide-exec-summary.md +47 -0
- package/docs/en/slide/slide-heading.md +38 -0
- package/docs/en/slide/slide-kpi-grid.md +55 -0
- package/docs/en/slide/slide-kpi-hero.md +58 -0
- package/docs/en/slide/slide-next-actions.md +49 -0
- package/docs/en/slide/slide-scorecard-table.md +54 -0
- package/docs/en/slide/slide-section.md +44 -0
- package/docs/en/slide/slide-source-line.md +34 -0
- package/docs/en/ui/alert-dialog.md +42 -0
- package/docs/en/ui/avatar.md +31 -0
- package/docs/en/ui/combobox.md +74 -0
- package/docs/en/ui/drawer.md +41 -0
- package/docs/en/ui/empty.md +1 -1
- package/docs/en/ui/error-state.md +4 -3
- package/docs/en/ui/field.md +42 -0
- package/docs/en/ui/hover-card.md +21 -0
- package/docs/en/ui/kbd.md +17 -0
- package/docs/en/ui/loading.md +1 -1
- package/docs/en/ui/pagination.md +36 -0
- package/docs/en/ui/radio-group.md +21 -0
- package/docs/en/ui/toast.md +44 -0
- package/docs/en/ui/toggle-group.md +4 -3
- package/docs/en/ui-and-theming.md +1 -1
- package/docs/index.json +1184 -114
- package/docs/ja/agent-skills.md +1 -1
- package/docs/ja/changelog.md +57 -0
- package/docs/ja/cli-reference.md +29 -0
- package/docs/ja/components.md +68 -101
- package/docs/ja/doc/delta-text.md +40 -0
- package/docs/ja/doc/doc-action-items.md +49 -0
- package/docs/ja/doc/doc-callout.md +38 -0
- package/docs/ja/doc/doc-data-table.md +60 -0
- package/docs/ja/doc/doc-executive-summary.md +64 -0
- package/docs/ja/doc/doc-figure.md +56 -0
- package/docs/ja/doc/doc-key-findings.md +61 -0
- package/docs/ja/doc/doc-kpi-scorecard.md +80 -0
- package/docs/ja/doc/doc-notes-and-sources.md +43 -0
- package/docs/ja/doc/doc-report-header.md +46 -0
- package/docs/ja/page-types/csv.md +83 -0
- package/docs/ja/page-types/doc.md +83 -0
- package/docs/ja/page-types/excel.md +82 -0
- package/docs/ja/page-types/slide.md +133 -0
- package/docs/ja/page-types.md +47 -0
- package/docs/ja/pages-and-metadata.md +15 -0
- package/docs/ja/parts/area-chart.md +85 -0
- package/docs/ja/parts/bar-chart.md +95 -0
- package/docs/ja/parts/bar-list.md +58 -0
- package/docs/ja/parts/category-bar.md +36 -0
- package/docs/ja/parts/chart-frame.md +36 -0
- package/docs/ja/parts/data-table.md +22 -0
- package/docs/ja/parts/delta.md +51 -0
- package/docs/ja/parts/donut-chart.md +66 -0
- package/docs/ja/parts/echart.md +3 -0
- package/docs/ja/parts/format.md +44 -0
- package/docs/ja/parts/funnel-steps.md +27 -8
- package/docs/ja/parts/heatmap.md +45 -0
- package/docs/ja/parts/kpi-card.md +56 -0
- package/docs/ja/parts/legend.md +36 -0
- package/docs/ja/parts/line-chart.md +84 -0
- package/docs/ja/parts/metric-value.md +3 -2
- package/docs/ja/parts/page-shell.md +1 -1
- package/docs/ja/parts/progress-circle.md +34 -0
- package/docs/ja/parts/sample-data.md +61 -0
- package/docs/ja/parts/scatter-chart.md +69 -0
- package/docs/ja/parts/sparkline.md +2 -2
- package/docs/ja/parts/tracker.md +32 -0
- package/docs/ja/parts/trend-indicator.md +17 -1
- package/docs/ja/parts/updated-at.md +27 -0
- package/docs/ja/parts/waterfall-chart.md +61 -0
- package/docs/ja/routing.md +8 -84
- package/docs/ja/slide/slide-chart-full.md +48 -0
- package/docs/ja/slide/slide-chart-insight.md +52 -0
- package/docs/ja/slide/slide-columns.md +46 -0
- package/docs/ja/slide/slide-comparison.md +68 -0
- package/docs/ja/slide/slide-cover.md +39 -0
- package/docs/ja/slide/slide-exec-summary.md +47 -0
- package/docs/ja/slide/slide-heading.md +38 -0
- package/docs/ja/slide/slide-kpi-grid.md +55 -0
- package/docs/ja/slide/slide-kpi-hero.md +58 -0
- package/docs/ja/slide/slide-next-actions.md +49 -0
- package/docs/ja/slide/slide-scorecard-table.md +54 -0
- package/docs/ja/slide/slide-section.md +44 -0
- package/docs/ja/slide/slide-source-line.md +34 -0
- package/docs/ja/ui/alert-dialog.md +41 -0
- package/docs/ja/ui/avatar.md +31 -0
- package/docs/ja/ui/combobox.md +74 -0
- package/docs/ja/ui/drawer.md +41 -0
- package/docs/ja/ui/empty.md +1 -1
- package/docs/ja/ui/error-state.md +4 -3
- package/docs/ja/ui/field.md +42 -0
- package/docs/ja/ui/hover-card.md +21 -0
- package/docs/ja/ui/kbd.md +16 -0
- package/docs/ja/ui/loading.md +1 -1
- package/docs/ja/ui/pagination.md +36 -0
- package/docs/ja/ui/radio-group.md +21 -0
- package/docs/ja/ui/toast.md +46 -0
- package/docs/ja/ui/toggle-group.md +4 -3
- package/docs/ja/ui-and-theming.md +14 -7
- package/package.json +43 -29
- package/registry/ui/accordion.tsx +76 -0
- package/registry/ui/alert-dialog.tsx +189 -0
- package/registry/ui/alert.tsx +80 -0
- package/registry/ui/app-shell.tsx +424 -0
- package/registry/ui/area-chart.tsx +3960 -0
- package/registry/ui/attention-list.tsx +465 -0
- package/registry/ui/avatar.tsx +110 -0
- package/registry/ui/badge.tsx +56 -0
- package/registry/ui/bar-chart.tsx +3954 -0
- package/registry/ui/bar-list.tsx +3998 -0
- package/registry/ui/box-plot-chart.tsx +4214 -0
- package/registry/ui/breadcrumb.tsx +128 -0
- package/registry/ui/button.tsx +62 -0
- package/registry/ui/calendar.tsx +223 -0
- package/registry/ui/card.tsx +107 -0
- package/registry/ui/category-bar.tsx +1498 -0
- package/registry/ui/chart-frame.tsx +1604 -0
- package/registry/ui/checkbox.tsx +30 -0
- package/registry/ui/collapsible.tsx +23 -0
- package/registry/ui/combobox.tsx +310 -0
- package/registry/ui/command.tsx +198 -0
- package/registry/ui/dashboard-card.tsx +217 -0
- package/registry/ui/data-table.tsx +896 -157
- package/registry/ui/date-range-picker.tsx +544 -0
- package/registry/ui/delta.tsx +350 -0
- package/registry/ui/dialog.tsx +161 -0
- package/registry/ui/donut-chart.tsx +4006 -0
- package/registry/ui/drawer.tsx +229 -0
- package/registry/ui/dropdown-menu.tsx +274 -0
- package/registry/ui/echart.tsx +1178 -0
- package/registry/ui/field.tsx +240 -0
- package/registry/ui/filter-bar.tsx +551 -0
- package/registry/ui/funnel-steps.tsx +3843 -0
- package/registry/ui/heatmap.tsx +2027 -0
- package/registry/ui/histogram-chart.tsx +4284 -0
- package/registry/ui/hover-card.tsx +52 -0
- package/registry/ui/input-group.tsx +160 -0
- package/registry/ui/input.tsx +24 -0
- package/registry/ui/kbd.tsx +30 -0
- package/registry/ui/kpi-card.tsx +905 -0
- package/registry/ui/label.tsx +22 -0
- package/registry/ui/legend.tsx +3817 -0
- package/registry/ui/line-chart.tsx +3958 -0
- package/registry/ui/metric-value.tsx +62 -0
- package/registry/ui/multi-select.tsx +382 -0
- package/registry/ui/page-shell.tsx +420 -0
- package/registry/ui/pagination.tsx +140 -0
- package/registry/ui/paired-chart.tsx +4086 -0
- package/registry/ui/placeholder.tsx +36 -0
- package/registry/ui/popover.tsx +92 -0
- package/registry/ui/progress-circle.tsx +1033 -0
- package/registry/ui/progress.tsx +85 -0
- package/registry/ui/radio-group.tsx +39 -0
- package/registry/ui/sample-data.tsx +230 -0
- package/registry/ui/scatter-chart.tsx +4503 -0
- package/registry/ui/scroll-area.tsx +56 -0
- package/registry/ui/searchable-select.tsx +352 -0
- package/registry/ui/section-header.tsx +43 -0
- package/registry/ui/segmented-control.tsx +76 -0
- package/registry/ui/select.tsx +255 -0
- package/registry/ui/separator.tsx +27 -0
- package/registry/ui/sheet.tsx +139 -0
- package/registry/ui/sidebar.tsx +725 -0
- package/registry/ui/skeleton.tsx +17 -0
- package/registry/ui/slider.tsx +56 -0
- package/registry/ui/sparkline.tsx +230 -0
- package/registry/ui/spinner.tsx +14 -0
- package/registry/ui/states.tsx +247 -0
- package/registry/ui/status-badge.tsx +286 -0
- package/registry/ui/switch.tsx +34 -0
- package/registry/ui/table.tsx +118 -0
- package/registry/ui/tabs.tsx +84 -0
- package/registry/ui/textarea.tsx +22 -0
- package/registry/ui/toast.tsx +250 -0
- package/registry/ui/toggle-group.tsx +91 -0
- package/registry/ui/toggle.tsx +47 -0
- package/registry/ui/tooltip.tsx +72 -0
- package/registry/ui/tracker.tsx +1015 -0
- package/registry/ui/trend-indicator.tsx +217 -0
- package/registry/ui/updated-at.tsx +276 -0
- package/registry/ui/waterfall-chart.tsx +4561 -0
- package/skills/vantage-add-feature/SKILL.md +9 -7
- package/skills/vantage-design/SKILL.md +62 -52
- package/skills/vantage-design/references/extract.md +26 -27
- package/skills/vantage-design/references/format.md +12 -172
- package/skills/vantage-design/references/presets.md +50 -110
- package/skills/vantage-pitfalls/SKILL.md +10 -1
- package/skills/vantage-slide/SKILL.md +71 -36
- package/templates/AGENTS.md +53 -16
- package/templates/agents/api.md +29 -0
- package/templates/agents/csv.md +2 -1
- package/templates/agents/doc.md +54 -3
- package/templates/agents/page.md +55 -10
- package/templates/agents/slide.md +90 -4
- package/templates/agents/xlsx.md +2 -1
- package/theme.css +287 -128
- package/dist/add-EISGSZAH.js +0 -6
- package/dist/add-EISGSZAH.js.map +0 -1
- package/dist/chunk-3G43C6OL.js.map +0 -1
- package/dist/chunk-5ZOP4SQR.js +0 -47
- package/dist/chunk-5ZOP4SQR.js.map +0 -1
- package/dist/chunk-A2UUGASH.js.map +0 -1
- package/dist/chunk-BCE22JSM.js.map +0 -1
- package/dist/chunk-DTDVSFRY.js +0 -29
- package/dist/chunk-DTDVSFRY.js.map +0 -1
- package/dist/chunk-EP6JHXSR.js.map +0 -1
- package/dist/chunk-JGRMRXXZ.js.map +0 -1
- package/dist/chunk-KLEIVDUV.js +0 -165
- package/dist/chunk-KLEIVDUV.js.map +0 -1
- package/dist/chunk-MXI3PZFT.js.map +0 -1
- package/dist/chunk-PLST5Q7T.js +0 -2221
- package/dist/chunk-PLST5Q7T.js.map +0 -1
- package/dist/chunk-PVTHHV7X.js.map +0 -1
- package/dist/chunk-T3FLAGI6.js +0 -316
- package/dist/chunk-T3FLAGI6.js.map +0 -1
- package/dist/dev-NZRLOQCL.js.map +0 -1
- package/dist/doctor-VFKEMR54.js.map +0 -1
- package/dist/preview-QDCIVVSR.js.map +0 -1
|
@@ -0,0 +1,4214 @@
|
|
|
1
|
+
// Copied by `vantage add ui box-plot-chart`. This file is yours to edit.
|
|
2
|
+
// Generated from @squadbase/squadkit registry/charts/box-plot-chart.tsx by `pnpm run registry` (in Vantage, edit packages/squadkit, not registry/).
|
|
3
|
+
"use client"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* BoxPlotChart — a typed box plot over `EChart`: pass one group per box (`{ name, values }`, raw values) instead of an
|
|
7
|
+
* ECharts option. チームごとの残業時間、拠点ごとの解決日数。
|
|
8
|
+
*
|
|
9
|
+
* Each group is summarised by `boxStats` (a pure function): the box spans Q1–Q3 with the median line, the whiskers reach the
|
|
10
|
+
* furthest value inside `whisker` × IQR (default 1.5) and anything beyond is an outlier dot. Quartiles are linearly
|
|
11
|
+
* interpolated (Excel's QUARTILE.INC). The boxes are drawn with a `custom` series (already registered by `EChart`), a
|
|
12
|
+
* light `--chart-1` fill with a solid outline; the tooltip prints n, the quartiles, the whiskers and the outliers, so the
|
|
13
|
+
* colour is never the only carrier. A group with no usable value is kept on the axis and reads「—」.
|
|
14
|
+
* Renders inside `ChartFrame` (title, summary, loading skeleton, empty state and a visually-hidden table of the statistics).
|
|
15
|
+
*/
|
|
16
|
+
import { forwardRef, useMemo, type ForwardedRef } from "react"
|
|
17
|
+
import type { EChartsOption } from "echarts"
|
|
18
|
+
|
|
19
|
+
import { ChartFrame } from "@squadbase/vantage/components"
|
|
20
|
+
import { EChart } from "@squadbase/vantage/components"
|
|
21
|
+
import { EMPTY_VALUE } from "@squadbase/vantage/components"
|
|
22
|
+
import type { ChartCommonProps, ValueFormatter } from "@squadbase/vantage/components"
|
|
23
|
+
import { useSyncExternalStore } from "react"
|
|
24
|
+
import { createContext, useCallback, useEffect, useRef, useState, type RefObject } from "react"
|
|
25
|
+
import type { ChartTone } from "@squadbase/vantage/components"
|
|
26
|
+
import { type ReactNode } from "react"
|
|
27
|
+
import { computeComparison, defaultChangeDisplay, formatChange, toneForValue, type ComparisonKind, type PeriodGrain } from "@squadbase/vantage/components"
|
|
28
|
+
import { DEFAULT_LOCALE, type ValueFormat } from "@squadbase/vantage/components"
|
|
29
|
+
import type { ChartThreshold, ChartAnnotation, ChartEventPayload, ChartForecast, ChartForecastRow, ChartHighlight, NumericKeys } from "@squadbase/vantage/components"
|
|
30
|
+
import { formatValue, toValueFormatter } from "@squadbase/vantage/components"
|
|
31
|
+
import type { ChartColor, ChartColors, ChartSeriesColor } from "@squadbase/vantage/components"
|
|
32
|
+
|
|
33
|
+
/* ---------- inlined from @squadbase/squadkit registry/lib/locale.ts (internal to @squadbase/vantage) ---------- */
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The display language of the parts and the defaults that follow it.
|
|
37
|
+
*
|
|
38
|
+
* The language comes from `<html lang>`: a tag starting with `ja` reads Japanese, anything else English.
|
|
39
|
+
* Without a usable `lang` (missing, invalid, or no `document` — SSR, Node) the locale is `FALLBACK_LOCALE`
|
|
40
|
+
* (`en-US`). A `locale` passed explicitly (a prop, an argument) always wins.
|
|
41
|
+
*
|
|
42
|
+
* Parts read the locale through `useLocale` (`hooks/use-locale`) and pass it down; the pure helpers here
|
|
43
|
+
* and in `format` / `comparison` / `chart-*` take it as an argument and fall back to `documentLocale()`.
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
/** The language of the built-in wording: Japanese or English. */
|
|
47
|
+
type UiLanguage = "ja" | "en"
|
|
48
|
+
|
|
49
|
+
/** The locale used when `<html lang>` gives none (and on the server). */
|
|
50
|
+
const FALLBACK_LOCALE = "en-US"
|
|
51
|
+
|
|
52
|
+
/** `"ja"` when `locale` starts with `ja` (`ja`, `ja-JP`), else `"en"`. A missing locale is `"en"`. */
|
|
53
|
+
function uiLanguage(locale: string | null | undefined): UiLanguage {
|
|
54
|
+
return typeof locale === "string" && locale.trim().toLowerCase().startsWith("ja") ? "ja" : "en"
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A BCP 47 tag in its canonical form (`en-gb` → `en-GB`), or `FALLBACK_LOCALE` when it is empty or invalid. */
|
|
58
|
+
function normalizeLocale(tag: string | null | undefined): string {
|
|
59
|
+
const value = tag?.trim()
|
|
60
|
+
if (!value) return FALLBACK_LOCALE
|
|
61
|
+
try {
|
|
62
|
+
return Intl.getCanonicalLocales(value)[0] ?? FALLBACK_LOCALE
|
|
63
|
+
} catch {
|
|
64
|
+
return FALLBACK_LOCALE
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The locale of the page: `document.documentElement.lang`, canonicalized. `FALLBACK_LOCALE` when it is empty or
|
|
70
|
+
* invalid, or there is no `document`. Parts read it through `useLocale`, never while rendering.
|
|
71
|
+
*/
|
|
72
|
+
function documentLocale(): string {
|
|
73
|
+
if (typeof document === "undefined") return FALLBACK_LOCALE
|
|
74
|
+
return normalizeLocale(document.documentElement?.getAttribute("lang"))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** `locale` when given, else the page's locale (`documentLocale()`). */
|
|
78
|
+
function resolveLocale(locale?: string | null): string {
|
|
79
|
+
return locale || documentLocale()
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Picks the wording table of the locale's language. */
|
|
83
|
+
function pickLocale<T>(table: { ja: T; en: T }, locale?: string | null): T {
|
|
84
|
+
return table[uiLanguage(resolveLocale(locale))]
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The currency `format="currency"` uses without a `currency`: JPY for Japanese, USD otherwise. */
|
|
88
|
+
function defaultCurrency(locale?: string | null): string {
|
|
89
|
+
return uiLanguage(resolveLocale(locale)) === "ja" ? "JPY" : "USD"
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The month a fiscal year starts in (1–12) when none is given: April for Japanese, January otherwise. */
|
|
93
|
+
function defaultFiscalYearStartMonth(locale?: string | null): number {
|
|
94
|
+
return uiLanguage(resolveLocale(locale)) === "ja" ? 4 : 1
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** A day of the week, 0 = Sunday … 6 = Saturday (the `Date#getDay` / date-fns numbering). */
|
|
98
|
+
type WeekDay = 0 | 1 | 2 | 3 | 4 | 5 | 6
|
|
99
|
+
|
|
100
|
+
/** Locales whose week starts on Sunday when the runtime has no week data. */
|
|
101
|
+
const SUNDAY_FIRST = new Set(["en", "en-US", "en-CA"])
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The first day of the week: Monday for Japanese; otherwise the locale's convention from `Intl.Locale`
|
|
105
|
+
* (`en-US` Sunday, `en-GB` Monday). Without week data in the runtime: Sunday for `en` / `en-US` / `en-CA`,
|
|
106
|
+
* Monday for the rest.
|
|
107
|
+
*/
|
|
108
|
+
function weekStartsOn(locale?: string | null): WeekDay {
|
|
109
|
+
const tag = normalizeLocale(resolveLocale(locale))
|
|
110
|
+
if (uiLanguage(tag) === "ja") return 1
|
|
111
|
+
try {
|
|
112
|
+
const info = new Intl.Locale(tag) as Intl.Locale & {
|
|
113
|
+
getWeekInfo?: () => { firstDay: number }
|
|
114
|
+
weekInfo?: { firstDay: number }
|
|
115
|
+
}
|
|
116
|
+
const firstDay = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay
|
|
117
|
+
if (typeof firstDay === "number" && firstDay >= 1 && firstDay <= 7) return (firstDay % 7) as WeekDay
|
|
118
|
+
} catch {
|
|
119
|
+
// Fall through to the table below.
|
|
120
|
+
}
|
|
121
|
+
return SUNDAY_FIRST.has(tag) ? 0 : 1
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/* ---------- inlined from @squadbase/squadkit registry/hooks/use-locale.ts (internal to @squadbase/vantage) ---------- */
|
|
125
|
+
|
|
126
|
+
const listeners = new Set<() => void>()
|
|
127
|
+
let observer: MutationObserver | null = null
|
|
128
|
+
|
|
129
|
+
/** One observer on `<html lang>` for every subscribed part. */
|
|
130
|
+
function subscribe(onChange: () => void): () => void {
|
|
131
|
+
if (typeof document === "undefined" || typeof MutationObserver === "undefined") return () => {}
|
|
132
|
+
listeners.add(onChange)
|
|
133
|
+
if (!observer) {
|
|
134
|
+
observer = new MutationObserver(() => {
|
|
135
|
+
for (const listener of [...listeners]) listener()
|
|
136
|
+
})
|
|
137
|
+
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] })
|
|
138
|
+
}
|
|
139
|
+
return () => {
|
|
140
|
+
listeners.delete(onChange)
|
|
141
|
+
if (listeners.size === 0 && observer) {
|
|
142
|
+
observer.disconnect()
|
|
143
|
+
observer = null
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const serverLocale = () => FALLBACK_LOCALE
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The page's locale (`<html lang>`), following changes made while the page runs. On the server and during
|
|
152
|
+
* hydration it is `FALLBACK_LOCALE` (`en-US`), so the markup matches; it switches right after.
|
|
153
|
+
*/
|
|
154
|
+
function useDocumentLocale(): string {
|
|
155
|
+
return useSyncExternalStore(subscribe, documentLocale, serverLocale)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The locale a part renders in: its `locale` prop when given, else the page's (`useDocumentLocale`). */
|
|
159
|
+
function useLocale(locale?: string | null): string {
|
|
160
|
+
const page = useDocumentLocale()
|
|
161
|
+
return locale || page
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/* ---------- inlined from @squadbase/squadkit registry/lib/chart-theme.ts (internal to @squadbase/vantage) ---------- */
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The colour of the folded「その他」series / slice / row. The ONLY place this
|
|
168
|
+
* grey is defined — every chart takes it from here. It is the most subdued
|
|
169
|
+
* colour in a chart, not the darkest: the theme's `--neutral` mixed halfway into
|
|
170
|
+
* `--background`, so it recedes in light and dark alike (and brand themes follow
|
|
171
|
+
* it). `--neutral-subtle` alone sits too close to the background to read as a
|
|
172
|
+
* slice. Canvas charts resolve it through `resolveChartColors`.
|
|
173
|
+
*/
|
|
174
|
+
const CHART_OTHER_COLOR = "color-mix(in oklab, var(--neutral) 50%, var(--background))"
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* True inside `ChartFrame`. The frame's plot area carries the chart's single
|
|
178
|
+
* `role="img"` and label, so `EChart` drops its own when it sees this.
|
|
179
|
+
*/
|
|
180
|
+
const ChartFrameContext = createContext(false)
|
|
181
|
+
|
|
182
|
+
/** Series palette, in order. Missing tokens are skipped, not defaulted. */
|
|
183
|
+
const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
|
|
184
|
+
|
|
185
|
+
interface ChartTokens {
|
|
186
|
+
/** Resolved `--chart-1..5`, in order. */
|
|
187
|
+
series: string[]
|
|
188
|
+
/** Computed `font-family` of the container, so canvas text matches the DOM. Optional. */
|
|
189
|
+
fontFamily?: string
|
|
190
|
+
/** Body text: titles and the default `textStyle`. */
|
|
191
|
+
foreground: string | null
|
|
192
|
+
/** Secondary text: axis labels, legend, subtitles. */
|
|
193
|
+
mutedForeground: string | null
|
|
194
|
+
/** Axis lines, ticks, split lines, tooltip border. */
|
|
195
|
+
border: string | null
|
|
196
|
+
/** Tooltip surface. */
|
|
197
|
+
popover: string | null
|
|
198
|
+
/** Semantic and surface dependencies used by typed chart options. Optional for hand-built tokens. */
|
|
199
|
+
colors?: Record<string, string>
|
|
200
|
+
/** Actual inherited painting surface (may change without a token changing). */
|
|
201
|
+
surface?: string | null
|
|
202
|
+
/** Tooltip text. */
|
|
203
|
+
popoverForeground: string | null
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Keep scope out of the public token shape. A resolved snapshot remembers where arbitrary
|
|
207
|
+
// var(--token) expressions must be read, without retaining unmounted charts globally.
|
|
208
|
+
const tokenScopes = new WeakMap<ChartTokens, Element>()
|
|
209
|
+
const OPTION_COLOR_TOKENS = [
|
|
210
|
+
"--background", "--card", "--muted", "--primary", "--destructive",
|
|
211
|
+
...["positive", "negative", "warning", "neutral", "info"].flatMap((tone) =>
|
|
212
|
+
["", "-fill", "-subtle"].map((suffix) => `--${tone}${suffix}`)),
|
|
213
|
+
]
|
|
214
|
+
|
|
215
|
+
let normalizeContext: CanvasRenderingContext2D | null | undefined
|
|
216
|
+
|
|
217
|
+
/** The forms `fillStyle` serializes legacy colours to, and zrender can parse. */
|
|
218
|
+
const ZRENDER_COLOR_RE = /^(?:#[0-9a-f]{6}|rgba?\()/i
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Serialize a CSS colour into a canvas-safe form, or `null` if the browser
|
|
222
|
+
* rejects it. Assigning an invalid value to `fillStyle` is a no-op, so the same
|
|
223
|
+
* input is written over two different known colours: agreeing results mean the
|
|
224
|
+
* value parsed, differing ones mean it was dropped.
|
|
225
|
+
*/
|
|
226
|
+
function toCanvasColor(value: string): string | null {
|
|
227
|
+
const raw = value.trim()
|
|
228
|
+
if (!raw) return null
|
|
229
|
+
if (normalizeContext === undefined) {
|
|
230
|
+
const canvas = document.createElement("canvas")
|
|
231
|
+
canvas.width = 1
|
|
232
|
+
canvas.height = 1
|
|
233
|
+
normalizeContext = canvas.getContext("2d", { willReadFrequently: true })
|
|
234
|
+
}
|
|
235
|
+
const ctx = normalizeContext
|
|
236
|
+
if (!ctx) return raw
|
|
237
|
+
ctx.fillStyle = "#000000"
|
|
238
|
+
ctx.fillStyle = raw
|
|
239
|
+
const onBlack = ctx.fillStyle
|
|
240
|
+
ctx.fillStyle = "#ffffff"
|
|
241
|
+
ctx.fillStyle = raw
|
|
242
|
+
if (onBlack !== ctx.fillStyle || typeof onBlack !== "string") return null
|
|
243
|
+
if (ZRENDER_COLOR_RE.test(onBlack)) return onBlack
|
|
244
|
+
// Still `oklch()` / `lab()` / `color(...)`: paint it and read the pixel back.
|
|
245
|
+
// Wide-gamut colours clip to sRGB, which is all zrender can express anyway.
|
|
246
|
+
ctx.clearRect(0, 0, 1, 1)
|
|
247
|
+
ctx.fillRect(0, 0, 1, 1)
|
|
248
|
+
const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data
|
|
249
|
+
return a === 255
|
|
250
|
+
? `rgb(${r}, ${g}, ${b})`
|
|
251
|
+
: `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 1000) / 1000})`
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Read the chart tokens off `el` (the document root by default — tokens live on
|
|
256
|
+
* `:root` and inherit). Returns `null` outside the browser so callers fall back
|
|
257
|
+
* to plain ECharts defaults.
|
|
258
|
+
*/
|
|
259
|
+
function readChartTokens(el?: Element | null): ChartTokens | null {
|
|
260
|
+
if (typeof document === "undefined") return null
|
|
261
|
+
const target = el ?? document.documentElement
|
|
262
|
+
if (!target) return null
|
|
263
|
+
const styles = getComputedStyle(target)
|
|
264
|
+
const read = (name: string) => toCanvasColor(styles.getPropertyValue(name))
|
|
265
|
+
const series: string[] = []
|
|
266
|
+
for (const token of SERIES_TOKENS) {
|
|
267
|
+
const color = read(token)
|
|
268
|
+
if (color) series.push(color)
|
|
269
|
+
}
|
|
270
|
+
const tokens: ChartTokens = {
|
|
271
|
+
series,
|
|
272
|
+
colors: Object.fromEntries(OPTION_COLOR_TOKENS.map((name) => [name, styles.getPropertyValue(name).trim()])),
|
|
273
|
+
surface: readChartSurface(target),
|
|
274
|
+
...(styles.fontFamily ? { fontFamily: styles.fontFamily } : {}),
|
|
275
|
+
foreground: read("--foreground"),
|
|
276
|
+
mutedForeground: read("--muted-foreground"),
|
|
277
|
+
border: read("--border"),
|
|
278
|
+
popover: read("--popover"),
|
|
279
|
+
popoverForeground: read("--popover-foreground"),
|
|
280
|
+
}
|
|
281
|
+
tokenScopes.set(tokens, target)
|
|
282
|
+
return tokens
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Structural equality, so a theme toggle that changes nothing doesn't re-init. */
|
|
286
|
+
function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean {
|
|
287
|
+
if (a === b) return true
|
|
288
|
+
if (!a || !b) return false
|
|
289
|
+
return (
|
|
290
|
+
tokenScopes.get(a) === tokenScopes.get(b) &&
|
|
291
|
+
a.surface === b.surface &&
|
|
292
|
+
Object.keys(a.colors ?? {}).length === Object.keys(b.colors ?? {}).length &&
|
|
293
|
+
Object.entries(a.colors ?? {}).every(([name, value]) => b.colors?.[name] === value) &&
|
|
294
|
+
a.series.length === b.series.length &&
|
|
295
|
+
a.series.every((color, i) => color === b.series[i]) &&
|
|
296
|
+
a.fontFamily === b.fontFamily &&
|
|
297
|
+
a.foreground === b.foreground &&
|
|
298
|
+
a.mutedForeground === b.mutedForeground &&
|
|
299
|
+
a.border === b.border &&
|
|
300
|
+
a.popover === b.popover &&
|
|
301
|
+
a.popoverForeground === b.popoverForeground
|
|
302
|
+
)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Watch everything that can change the resolved tokens and call `onChange` when
|
|
307
|
+
* something might have. It only ever says "re-read" — the caller compares with
|
|
308
|
+
* `sameChartTokens` and decides whether anything actually moved. Returns a
|
|
309
|
+
* disposer.
|
|
310
|
+
*
|
|
311
|
+
* Two sources, not one:
|
|
312
|
+
* - light/dark flips, which land as `class` / `data-theme` (or an inline
|
|
313
|
+
* `style`) on `<html>`/`<body>`, or as an OS preference change
|
|
314
|
+
* - stylesheet changes. In dev, editing `styles.css` rewrites the injected
|
|
315
|
+
* `<style>` in `<head>` and touches nothing else, so watching the theme
|
|
316
|
+
* attributes alone leaves the chart painted in the previous palette until a
|
|
317
|
+
* reload — the tokens in the DOM are new, the canvas is not.
|
|
318
|
+
*/
|
|
319
|
+
function watchChartTokens(onChange: () => void, scope?: Element | null): () => void {
|
|
320
|
+
if (typeof document === "undefined") return () => {}
|
|
321
|
+
// Style edits arrive as bursts of mutations; coalesce them into one read, and
|
|
322
|
+
// take it after the next frame so a swapped stylesheet has been applied.
|
|
323
|
+
let frame = 0
|
|
324
|
+
const schedule = () => {
|
|
325
|
+
if (frame) return
|
|
326
|
+
frame = requestAnimationFrame(() => {
|
|
327
|
+
frame = 0
|
|
328
|
+
onChange()
|
|
329
|
+
})
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const themeObserver = new MutationObserver(schedule)
|
|
333
|
+
const attributeFilter = ["class", "style", "data-theme"]
|
|
334
|
+
// Only the chart and its ancestors can change its inherited theme. Never observe
|
|
335
|
+
// the document subtree: canvas/tooltip/rendering mutations would trigger every chart.
|
|
336
|
+
for (let node: Element | null = scope ?? document.body ?? document.documentElement; node; node = node.parentElement) {
|
|
337
|
+
themeObserver.observe(node, { attributes: true, attributeFilter })
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const styleObserver = new MutationObserver(schedule)
|
|
341
|
+
if (document.head) {
|
|
342
|
+
styleObserver.observe(document.head, {
|
|
343
|
+
childList: true,
|
|
344
|
+
subtree: true,
|
|
345
|
+
characterData: true,
|
|
346
|
+
attributes: true,
|
|
347
|
+
attributeFilter: ["href", "media", "disabled"],
|
|
348
|
+
})
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// A swapped `<link>` only applies once the sheet has loaded, after its mutation.
|
|
352
|
+
const onLoad = (event: Event) => {
|
|
353
|
+
if (event.target instanceof HTMLLinkElement) schedule()
|
|
354
|
+
}
|
|
355
|
+
document.addEventListener("load", onLoad, true)
|
|
356
|
+
|
|
357
|
+
const media = window.matchMedia("(prefers-color-scheme: dark)")
|
|
358
|
+
media.addEventListener("change", schedule)
|
|
359
|
+
|
|
360
|
+
return () => {
|
|
361
|
+
if (frame) cancelAnimationFrame(frame)
|
|
362
|
+
themeObserver.disconnect()
|
|
363
|
+
styleObserver.disconnect()
|
|
364
|
+
document.removeEventListener("load", onLoad, true)
|
|
365
|
+
media.removeEventListener("change", schedule)
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Shared shape for the four axis types ECharts themes address separately. */
|
|
370
|
+
function axisTheme(tokens: ChartTokens, splitLine: boolean) {
|
|
371
|
+
const line = tokens.border ?? undefined
|
|
372
|
+
return {
|
|
373
|
+
axisLine: { show: false },
|
|
374
|
+
axisTick: { show: false },
|
|
375
|
+
axisLabel: { show: true, color: tokens.mutedForeground ?? undefined, fontSize: 12 },
|
|
376
|
+
// Faint horizontal rules only: the border colour at low opacity.
|
|
377
|
+
splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined, opacity: 0.5, width: 1 } },
|
|
378
|
+
splitArea: { show: false },
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Build the ECharts theme. `option.color` still wins over `theme.color`, so an
|
|
384
|
+
* app that sets its own palette keeps it.
|
|
385
|
+
*/
|
|
386
|
+
function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
|
|
387
|
+
const text = tokens.foreground ?? undefined
|
|
388
|
+
const muted = tokens.mutedForeground ?? undefined
|
|
389
|
+
const line = tokens.border ?? undefined
|
|
390
|
+
return {
|
|
391
|
+
// Let the page background show through: charts sit on cards, not on a canvas.
|
|
392
|
+
backgroundColor: "transparent",
|
|
393
|
+
...(tokens.series.length > 0 ? { color: tokens.series } : {}),
|
|
394
|
+
textStyle: { color: text, ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}) },
|
|
395
|
+
title: { textStyle: { color: text }, subtextStyle: { color: muted } },
|
|
396
|
+
legend: { textStyle: { color: muted } },
|
|
397
|
+
categoryAxis: axisTheme(tokens, false),
|
|
398
|
+
valueAxis: axisTheme(tokens, true),
|
|
399
|
+
logAxis: axisTheme(tokens, true),
|
|
400
|
+
timeAxis: axisTheme(tokens, true),
|
|
401
|
+
tooltip: {
|
|
402
|
+
// ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
|
|
403
|
+
transitionDuration: 0,
|
|
404
|
+
backgroundColor: tokens.popover ?? undefined,
|
|
405
|
+
borderColor: line,
|
|
406
|
+
borderWidth: 1,
|
|
407
|
+
padding: [8, 12],
|
|
408
|
+
// Rounded card with a soft shadow; in dark mode the shadow barely shows, so the border carries the edge.
|
|
409
|
+
extraCssText: "border-radius:8px;box-shadow:var(--shadow-card, 0 4px 12px rgb(0 0 0 / 0.08));",
|
|
410
|
+
textStyle: {
|
|
411
|
+
color: tokens.popoverForeground ?? undefined,
|
|
412
|
+
fontSize: 12,
|
|
413
|
+
...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}),
|
|
414
|
+
},
|
|
415
|
+
axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
|
|
416
|
+
},
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* The resolved tokens, kept current: re-read whenever `watchChartTokens` says
|
|
422
|
+
* they may have moved, and only replaced when a value actually changed. For
|
|
423
|
+
* components that build an ECharts option from token colours themselves (the
|
|
424
|
+
* typed charts), so their palette follows light/dark like `EChart`'s theme.
|
|
425
|
+
*/
|
|
426
|
+
function useChartTokens(scope?: Element | null | RefObject<Element | null>): ChartTokens | null {
|
|
427
|
+
const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
|
|
428
|
+
// Compared here, not inside a `setTokens` updater: an updater that reads the DOM is
|
|
429
|
+
// replayed by React on every rebase and returns a fresh object each time, so the state
|
|
430
|
+
// never settles ("Maximum update depth exceeded" once the tokens change after mount).
|
|
431
|
+
const tokensRef = useRef(tokens)
|
|
432
|
+
useEffect(() => {
|
|
433
|
+
const target = scope && "current" in scope ? scope.current : scope
|
|
434
|
+
const sync = () => {
|
|
435
|
+
const next = readChartTokens(target)
|
|
436
|
+
if (sameChartTokens(tokensRef.current, next)) return
|
|
437
|
+
tokensRef.current = next
|
|
438
|
+
setTokens(next)
|
|
439
|
+
}
|
|
440
|
+
sync()
|
|
441
|
+
return watchChartTokens(sync, target)
|
|
442
|
+
}, [scope])
|
|
443
|
+
return tokens
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
|
|
447
|
+
const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
|
|
448
|
+
const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
|
|
449
|
+
const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
|
|
453
|
+
* the resolved series tokens; `"positive"` / `"warning"` / `"negative"` / `"neutral"` (and the area
|
|
454
|
+
* variants `"positive-fill"`, …) are read in the snapshot's inherited scope (`--positive`, …); `var(--token)` uses the same scope; any
|
|
455
|
+
* other CSS colour is normalized like the tokens are. A colour that can't be
|
|
456
|
+
* resolved comes back as `""`, which ECharts treats as "use the palette".
|
|
457
|
+
*/
|
|
458
|
+
function resolveChartColors(colors: readonly string[], tokens: ChartTokens | null): string[] {
|
|
459
|
+
return colors.map((color) => {
|
|
460
|
+
const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
|
|
461
|
+
if (token) return tokens?.series[Number(token[1]) - 1] ?? ""
|
|
462
|
+
// Meaning colours are the theme tokens of the same name: same path as `var(--positive)`.
|
|
463
|
+
if (TONE_NAME_RE.test(color.trim())) {
|
|
464
|
+
if (typeof document === "undefined") return ""
|
|
465
|
+
const target = (tokens && tokenScopes.get(tokens)) ?? document.documentElement
|
|
466
|
+
return toCanvasColor(getComputedStyle(target).getPropertyValue(`--${color.trim()}`)) ?? ""
|
|
467
|
+
}
|
|
468
|
+
if (typeof document === "undefined") return color
|
|
469
|
+
let value = color.trim()
|
|
470
|
+
const cssVar = CSS_VAR_RE.exec(value)
|
|
471
|
+
const styles = getComputedStyle((tokens && tokenScopes.get(tokens)) ?? document.documentElement)
|
|
472
|
+
if (cssVar) {
|
|
473
|
+
value = styles.getPropertyValue(cssVar[1]!).trim() || (cssVar[2] ?? "").trim()
|
|
474
|
+
} else if (value.includes("var(")) {
|
|
475
|
+
// A colour function over tokens (`color-mix(… var(--muted-foreground) …)`):
|
|
476
|
+
// substitute the tokens, then let the canvas resolve the rest.
|
|
477
|
+
value = value.replace(EMBEDDED_VAR_RE, (_, name: string) => styles.getPropertyValue(name).trim())
|
|
478
|
+
}
|
|
479
|
+
return toCanvasColor(value) ?? ""
|
|
480
|
+
})
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** Every meaning colour resolved for the canvas (`""` when it can't be resolved). */
|
|
484
|
+
function resolveToneColors(tokens: ChartTokens | null): Record<ChartTone, string> {
|
|
485
|
+
const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
|
|
486
|
+
["positive", "warning", "negative", "neutral"],
|
|
487
|
+
tokens,
|
|
488
|
+
)
|
|
489
|
+
return { positive, warning, negative, neutral }
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** The area (`--<tone>-fill`) colours of every meaning tone, resolved for the canvas (`""` when it can't be resolved). */
|
|
493
|
+
function resolveFillColors(tokens: ChartTokens | null): Record<ChartTone, string> {
|
|
494
|
+
const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
|
|
495
|
+
["positive-fill", "warning-fill", "negative-fill", "neutral-fill"],
|
|
496
|
+
tokens,
|
|
497
|
+
)
|
|
498
|
+
return { positive, warning, negative, neutral }
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const TRANSPARENT_RE = /^(?:transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* The colour the chart is painted on: the first opaque `background-color` up
|
|
505
|
+
* from `el` (a card, the page), else `--background`. Canvas-safe, or `null`
|
|
506
|
+
* outside the browser.
|
|
507
|
+
*/
|
|
508
|
+
function readChartSurface(el: Element | null): string | null {
|
|
509
|
+
if (typeof document === "undefined") return null
|
|
510
|
+
for (let node: Element | null = el; node; node = node.parentElement) {
|
|
511
|
+
const bg = getComputedStyle(node).backgroundColor.trim()
|
|
512
|
+
if (bg && !TRANSPARENT_RE.test(bg)) {
|
|
513
|
+
const color = toCanvasColor(bg)
|
|
514
|
+
if (color) return color
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
return toCanvasColor(getComputedStyle(el ?? document.documentElement).getPropertyValue("--background"))
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** Widths are bucketed so a resize only rebuilds the option when the label budget can change. */
|
|
521
|
+
const WIDTH_BUCKET = 40
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* The surface colour behind a chart (see `readChartSurface`), re-read when the
|
|
525
|
+
* tokens move (light/dark), and the plot's width (rounded down to 40px;
|
|
526
|
+
* `undefined` until measured). Returns a ref for the plot that also feeds the
|
|
527
|
+
* component's forwarded ref.
|
|
528
|
+
*/
|
|
529
|
+
function useChartSurface<E extends Element>(
|
|
530
|
+
forwarded: ForwardedRef<E>,
|
|
531
|
+
tokens?: ChartTokens | null,
|
|
532
|
+
): { ref: (el: E | null) => void; surface: string | undefined; width: number | undefined; tokens: ChartTokens | null } {
|
|
533
|
+
const [node, setNode] = useState<E | null>(null)
|
|
534
|
+
const scopedTokens = useChartTokens(node)
|
|
535
|
+
const [surface, setSurface] = useState<string | undefined>(undefined)
|
|
536
|
+
const [width, setWidth] = useState<number | undefined>(undefined)
|
|
537
|
+
const ref = useCallback(
|
|
538
|
+
(el: E | null) => {
|
|
539
|
+
setNode(el)
|
|
540
|
+
if (typeof forwarded === "function") forwarded(el)
|
|
541
|
+
else if (forwarded) forwarded.current = el
|
|
542
|
+
},
|
|
543
|
+
[forwarded],
|
|
544
|
+
)
|
|
545
|
+
useEffect(() => {
|
|
546
|
+
if (!node) return
|
|
547
|
+
setSurface(readChartSurface(node) ?? undefined)
|
|
548
|
+
}, [node, tokens, scopedTokens])
|
|
549
|
+
useEffect(() => {
|
|
550
|
+
if (!node || typeof ResizeObserver === "undefined") return
|
|
551
|
+
const update = (w: number) => setWidth(Math.floor(w / WIDTH_BUCKET) * WIDTH_BUCKET)
|
|
552
|
+
update(node.getBoundingClientRect().width)
|
|
553
|
+
const observer = new ResizeObserver((entries) => update(entries[0]?.contentRect.width ?? 0))
|
|
554
|
+
observer.observe(node)
|
|
555
|
+
return () => observer.disconnect()
|
|
556
|
+
}, [node])
|
|
557
|
+
return { ref, surface, width, tokens: scopedTokens }
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/* ---------- inlined from @squadbase/squadkit registry/lib/chart-options.ts (internal to @squadbase/vantage) ---------- */
|
|
561
|
+
|
|
562
|
+
/** The built-in words of the option builders, by language. */
|
|
563
|
+
const CHART_TEXT = {
|
|
564
|
+
ja: {
|
|
565
|
+
target: "目標",
|
|
566
|
+
forecast: "予測",
|
|
567
|
+
total: "合計",
|
|
568
|
+
provisional: "速報",
|
|
569
|
+
noComparison: "比較なし",
|
|
570
|
+
share: (share: string) => `(${share})`,
|
|
571
|
+
targetRate: (rate: string) => `(達成率 ${rate})`,
|
|
572
|
+
provisionalTitle: (title: string, label: string) => `${title}(${label})`,
|
|
573
|
+
},
|
|
574
|
+
en: {
|
|
575
|
+
target: "Target",
|
|
576
|
+
forecast: "Forecast",
|
|
577
|
+
total: "Total",
|
|
578
|
+
provisional: "Preliminary",
|
|
579
|
+
noComparison: "No comparison",
|
|
580
|
+
share: (share: string) => ` (${share})`,
|
|
581
|
+
targetRate: (rate: string) => ` (${rate} achieved)`,
|
|
582
|
+
provisionalTitle: (title: string, label: string) => `${title} (${label})`,
|
|
583
|
+
},
|
|
584
|
+
} satisfies Record<UiLanguage, unknown>
|
|
585
|
+
|
|
586
|
+
const chartText = (locale?: string) => CHART_TEXT[uiLanguage(resolveLocale(locale))]
|
|
587
|
+
|
|
588
|
+
type CartesianChartKind = "area" | "bar" | "line"
|
|
589
|
+
type CartesianStackType = "default" | "stacked" | "percent"
|
|
590
|
+
type CartesianCurveType = "linear" | "smooth" | "step"
|
|
591
|
+
type AreaFill = "gradient" | "solid" | "none"
|
|
592
|
+
type BarLayout = "horizontal" | "vertical"
|
|
593
|
+
|
|
594
|
+
/** AreaChart-only settings. */
|
|
595
|
+
interface AreaChartOptions {
|
|
596
|
+
/** `"stacked"` は積み上げ、`"percent"` は各点の合計を 100% にした積み上げ。既定 `"default"`。 */
|
|
597
|
+
type?: CartesianStackType
|
|
598
|
+
/** 線の形。既定 `"linear"`。 */
|
|
599
|
+
curveType?: CartesianCurveType
|
|
600
|
+
/** 面の塗り。既定 `"gradient"`。 */
|
|
601
|
+
fill?: AreaFill
|
|
602
|
+
/** 値の欠けた点(`null` など)をまたいで線をつなぐ。既定 `false`。 */
|
|
603
|
+
connectNulls?: boolean
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/** LineChart-only settings. */
|
|
607
|
+
interface LineChartOptions {
|
|
608
|
+
/** 線の形。既定 `"linear"`。 */
|
|
609
|
+
curveType?: CartesianCurveType
|
|
610
|
+
/** 値の欠けた点(`null` など)をまたいで線をつなぐ。既定 `false`。 */
|
|
611
|
+
connectNulls?: boolean
|
|
612
|
+
/** 値軸を 0 からではなくデータの範囲に合わせる。既定 `false`(0 起点)。最小の目盛ラベルは先頭の x ラベルと重なるので出さない(グリッド線は残る)。 */
|
|
613
|
+
fitToData?: boolean
|
|
614
|
+
/**
|
|
615
|
+
* 目標線(`target`)のラベルの置き場所。`"start"`(既定)は線の左端の上(最大・最新の強調と近いときは下)。
|
|
616
|
+
* `"end"` は線の右端の上。`"legend"` は凡例だけに出し、線の上には出さない(線の周りが混み合うとき)。
|
|
617
|
+
* 目標の呼び名は、どれを選んでも凡例に出る。
|
|
618
|
+
*/
|
|
619
|
+
targetLabelPosition?: LineTargetLabelPosition
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/** Where a line chart prints its target label: at the line's left end, its right end, or in the legend only. */
|
|
623
|
+
type LineTargetLabelPosition = "start" | "end" | "legend"
|
|
624
|
+
|
|
625
|
+
/** BarChart-only settings. */
|
|
626
|
+
interface BarChartOptions<T extends Record<string, unknown> = Record<string, unknown>> {
|
|
627
|
+
/** `"stacked"` は積み上げ、`"percent"` は各カテゴリの合計を 100% にした積み上げ。既定 `"default"`(横並び)。 */
|
|
628
|
+
type?: CartesianStackType
|
|
629
|
+
/**
|
|
630
|
+
* 棒の向き。既定 `"horizontal"`(カテゴリが横に並ぶ縦棒)。`"vertical"` はカテゴリを
|
|
631
|
+
* 縦に並べた横棒で、ラベルの長いランキングに向く(先頭の行が一番上)。
|
|
632
|
+
*/
|
|
633
|
+
layout?: BarLayout
|
|
634
|
+
/** カテゴリ間の隙間(`"20%"` や px)。省略時は ECharts の既定。 */
|
|
635
|
+
barCategoryGap?: string | number
|
|
636
|
+
/**
|
|
637
|
+
* 値が 0 の棒に「0」の値ラベルを付ける。棒が描かれない 0 が「データなし」に見えるのを防ぐ
|
|
638
|
+
* (在庫 0・件数 0 など)。積み上げでは付けない。0 以外の棒の見た目は変わらない。既定 `true`。
|
|
639
|
+
*/
|
|
640
|
+
showZeroValues?: boolean
|
|
641
|
+
/**
|
|
642
|
+
* 棒ごとの目標値が入った `data` の列名(行ごとの目標。店舗別の月次目標など)。各棒に短い目標マーカーを
|
|
643
|
+
* 引き、ツールチップに「目標 … (達成率 …%)」を足す。凡例に目標の呼び名(`targetLabel`、既定「目標」)が出る。
|
|
644
|
+
* 1 系列の棒と積み上げ(達成率は合計に対して)で使える。横並びの複数系列と 100% 積み上げでは描かない。
|
|
645
|
+
* 値が欠けた(null・0 以下の)行はマーカーを引かない。
|
|
646
|
+
*
|
|
647
|
+
* 優先順位: `targetKey` を渡すと 1 本の目標線 `target` は描かない(`targetLabel` はマーカーの呼び名として使う)。
|
|
648
|
+
* 値による色分け `thresholds` とは併用できる(色は棒、マーカーは目標)。値軸は最大の目標を含む。
|
|
649
|
+
* 例: `barOptions={{ targetKey: "月次目標" }}`
|
|
650
|
+
*/
|
|
651
|
+
targetKey?: NumericKeys<T>
|
|
652
|
+
/**
|
|
653
|
+
* 横棒(`layout: "vertical"`)の 1 系列で伝えたい 1 本。`index` の値で渡す(例 `"東京店"`)。
|
|
654
|
+
* 横棒は淡い色(`--chart-1` の薄い塗り)が既定で、この 1 本だけ濃い色(系列色そのまま)になる。省略すると全部が淡い色。
|
|
655
|
+
* 縦棒・複数系列・積み上げでは効かない(色は変わらない)。意味色の `thresholds` に当たった棒はそちらの色が優先。
|
|
656
|
+
* 例: `barOptions={{ layout: "vertical", highlight: "東京店" }}`
|
|
657
|
+
*/
|
|
658
|
+
highlight?: string | number
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** Props every cartesian typed chart (Area / Bar / Line) shares. */
|
|
662
|
+
interface CartesianChartBaseProps<T extends Record<string, unknown> = Record<string, unknown>>
|
|
663
|
+
extends ChartCommonProps<T> {
|
|
664
|
+
/**
|
|
665
|
+
* 最大値と最新値に値ラベルを付ける(最初の系列だけ・系列が 2 つ以下のときだけ・最大 2 つ)。
|
|
666
|
+
* 100% 積み上げの面グラフでは、最初の系列(一番下の帯)の最初と最新の比率(「24%」「31%」)を帯の中に付ける。
|
|
667
|
+
* 既定は Line / Area が `"auto"`、Bar は `index` が日付・年月・年のときだけ `"auto"`。
|
|
668
|
+
*/
|
|
669
|
+
highlight?: ChartHighlight
|
|
670
|
+
/**
|
|
671
|
+
* ここから先は確定前(速報)の点。index の値で渡す(例 `"2026-09"`)。薄い色・点線(棒は薄い塗りと破線の縁)で
|
|
672
|
+
* 描き、凡例・ツールチップに `provisionalLabel` を出す。線・面は確定の最終点とつなぐ。`forecast`(予測)とは別物。
|
|
673
|
+
* 例: `provisionalFrom="2026-09"`
|
|
674
|
+
*/
|
|
675
|
+
provisionalFrom?: string | number
|
|
676
|
+
/** 速報の呼び名(凡例・ツールチップ)。既定「速報」。例: `provisionalLabel="暫定"` */
|
|
677
|
+
provisionalLabel?: string
|
|
678
|
+
/**
|
|
679
|
+
* グラフが言っていることの 1 文要約(自由文)。`"auto"` なら data から機械的に組む
|
|
680
|
+
* (「<見出し>: 最新 <index値> は <値>、前の点より増加/減少」。向きは最新 2 点の値で決まる)。
|
|
681
|
+
* 増減の向きを文に書くなら `"auto"` を使うか data から作る — 手書きの向きは data とずれて誤る。
|
|
682
|
+
* 省略時は要約なし(既存どおり)。例: `summary="auto"`
|
|
683
|
+
*/
|
|
684
|
+
summary?: string | "auto"
|
|
685
|
+
/** 目標値。点線の水平線で示し、値軸は必ずこの値を含む。棒ごとの目標(`barOptions.targetKey`)を渡したときは描かない。 */
|
|
686
|
+
target?: number
|
|
687
|
+
/** 目標線のラベル。既定「目標 <書式化した値>」。`barOptions.targetKey` のときはマーカーの呼び名(既定「目標」)。 */
|
|
688
|
+
targetLabel?: string
|
|
689
|
+
/**
|
|
690
|
+
* 任意の位置への注記(縦の線、または `to` で区間の帯)。折れ線・面・縦の棒(`barOptions.layout` が既定のとき)で使え、
|
|
691
|
+
* 横棒では描かない。`at` / `to` は `index` の値。色は中立で、ツールチップにも文言が出る。例:
|
|
692
|
+
* `annotations={[{ at: "2026-04", label: "料金改定" }, { at: "2026-08", to: "2026-09", label: "キャンペーン" }]}`
|
|
693
|
+
*/
|
|
694
|
+
annotations?: ChartAnnotation[]
|
|
695
|
+
/** 凡例を出す。既定 `true`。 */
|
|
696
|
+
showLegend?: boolean
|
|
697
|
+
/** ホバー時のツールチップを出す。既定 `true`。 */
|
|
698
|
+
showTooltip?: boolean
|
|
699
|
+
/** 値軸の目盛り線を出す。既定 `true`。 */
|
|
700
|
+
showGridLines?: boolean
|
|
701
|
+
showXAxis?: boolean
|
|
702
|
+
showYAxis?: boolean
|
|
703
|
+
/** x 軸のラベルを最初と最後だけにする。 */
|
|
704
|
+
startEndOnly?: boolean
|
|
705
|
+
/** y 軸ラベルの幅(px)。並べた複数グラフのプロット領域を揃えたいときに固定する。 */
|
|
706
|
+
yAxisWidth?: number
|
|
707
|
+
/**
|
|
708
|
+
* 値軸の下限。Bar / Area は常に 0 起点なので、0 以下の値だけ有効(負の値の下に余白を取る。正の値は無視)。
|
|
709
|
+
* Line は指定した値から始める。データが下限を下回るときは軸を広げる(切り詰めない)。
|
|
710
|
+
* 並べて比べる複数のグラフには同じ値を渡して軸をそろえる。
|
|
711
|
+
*/
|
|
712
|
+
minValue?: number
|
|
713
|
+
/**
|
|
714
|
+
* 値軸の上限(横棒は横軸)。データが上限を超えるときは軸を広げる(切り詰めない)。
|
|
715
|
+
* 並べて比べる複数のグラフには同じ値を渡して軸をそろえる。
|
|
716
|
+
*/
|
|
717
|
+
maxValue?: number
|
|
718
|
+
/** @deprecated `lineOptions.fitToData` を使う。Bar / Area では無視される(常に 0 起点)。 */
|
|
719
|
+
autoMinValue?: boolean
|
|
720
|
+
/** `false` で値軸の目盛りを整数に限る。 */
|
|
721
|
+
allowDecimals?: boolean
|
|
722
|
+
xAxisLabel?: string
|
|
723
|
+
yAxisLabel?: string
|
|
724
|
+
/**
|
|
725
|
+
* 点(棒)のクリックで呼ばれる。クリックした行に `eventType` / `categoryClicked` を
|
|
726
|
+
* 足して渡し、同じ点をもう一度クリックすると `null`。渡すと選択以外が薄くなる。
|
|
727
|
+
*/
|
|
728
|
+
onValueChange?: (value: ChartEventPayload) => void
|
|
729
|
+
/** @deprecated `isLoading` を使う。 */
|
|
730
|
+
loading?: boolean
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** The point a user clicked, used to dim everything else. */
|
|
734
|
+
interface ChartActivePoint {
|
|
735
|
+
category: string
|
|
736
|
+
index: number
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/** The forecast as the builder takes it: untyped keys, already validated by the component's props. */
|
|
740
|
+
type CartesianForecastConfig = Omit<ChartForecast, "category"> & { category?: string }
|
|
741
|
+
|
|
742
|
+
/** The comparison series as the builder takes it (see `ChartComparison`); `label` names the baseline for `vs: "custom"`. */
|
|
743
|
+
interface CartesianComparisonConfig {
|
|
744
|
+
/** One of `categories`; drawn as a thin muted line, outside the `--chart-*` order. */
|
|
745
|
+
category: string
|
|
746
|
+
vs: ComparisonKind
|
|
747
|
+
label?: string
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
interface CartesianChartConfig {
|
|
751
|
+
kind: CartesianChartKind
|
|
752
|
+
data: readonly Record<string, unknown>[]
|
|
753
|
+
index: string
|
|
754
|
+
categories: readonly string[]
|
|
755
|
+
/** Resolved series colours, by category position. `""`/missing → theme palette. */
|
|
756
|
+
palette: readonly string[]
|
|
757
|
+
/** Display names for `index` values and category names (axis, legend, tooltip). Missing keys show as they are. */
|
|
758
|
+
labels?: Readonly<Record<string, string>>
|
|
759
|
+
/** 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. */
|
|
760
|
+
thresholds?: readonly ChartThreshold[]
|
|
761
|
+
/** Resolved colour of each tone (`resolveChartColors`); a tone missing here keeps the series colour. */
|
|
762
|
+
toneColors?: Partial<Record<ChartTone, string>>
|
|
763
|
+
/** Tooltip values. */
|
|
764
|
+
valueFormatter: (value: number) => string
|
|
765
|
+
/** Value-axis ticks, highlight and target labels (short form, e.g. ¥1億). Default `valueFormatter`. */
|
|
766
|
+
axisFormatter?: (value: number) => string
|
|
767
|
+
/**
|
|
768
|
+
* The value-axis tick formatter for an axis whose largest tick is the given number (`resolveAxisTickFormatter`):
|
|
769
|
+
* all ticks read in one unit (¥0.5億 / ¥1億). Default: `axisFormatter` for every tick.
|
|
770
|
+
*/
|
|
771
|
+
axisTicks?: (top: number) => (value: number) => string
|
|
772
|
+
/** Locale of the time-axis labels and the built-in words (total, target, forecast). Default the page's (`<html lang>`). */
|
|
773
|
+
locale?: string
|
|
774
|
+
type?: CartesianStackType
|
|
775
|
+
/** Bar only. `"vertical"` lays the categories down the y axis (horizontal bars). */
|
|
776
|
+
layout?: BarLayout
|
|
777
|
+
curveType?: CartesianCurveType
|
|
778
|
+
fill?: AreaFill
|
|
779
|
+
connectNulls?: boolean
|
|
780
|
+
showLegend?: boolean
|
|
781
|
+
showTooltip?: boolean
|
|
782
|
+
showGridLines?: boolean
|
|
783
|
+
showXAxis?: boolean
|
|
784
|
+
showYAxis?: boolean
|
|
785
|
+
startEndOnly?: boolean
|
|
786
|
+
yAxisWidth?: number
|
|
787
|
+
/** Bar / Area: only a value ≤ 0 takes effect (they start at 0). Line: the axis' start. The axis widens to the data. */
|
|
788
|
+
minValue?: number
|
|
789
|
+
/** The axis' top; the axis widens to the data. */
|
|
790
|
+
maxValue?: number
|
|
791
|
+
/** Line only: legacy alias of `fitToData`. */
|
|
792
|
+
autoMinValue?: boolean
|
|
793
|
+
/** Line only: let the value axis follow the data instead of starting at 0. */
|
|
794
|
+
fitToData?: boolean
|
|
795
|
+
allowDecimals?: boolean
|
|
796
|
+
xAxisLabel?: string
|
|
797
|
+
yAxisLabel?: string
|
|
798
|
+
barCategoryGap?: string | number
|
|
799
|
+
/** Always draw the line/area points (needed to click them). */
|
|
800
|
+
showDots?: boolean
|
|
801
|
+
active?: ChartActivePoint | null
|
|
802
|
+
/** Default: `"auto"` for line/area, for bar only when `index` holds dates. */
|
|
803
|
+
highlight?: ChartHighlight
|
|
804
|
+
/** Bar only: the index value of the one horizontal bar drawn in the full colour (`BarChartOptions.highlight`). */
|
|
805
|
+
barHighlight?: string | number
|
|
806
|
+
target?: number
|
|
807
|
+
targetLabel?: string
|
|
808
|
+
/** Line only: where the target label sits (see `LineChartOptions.targetLabelPosition`). Default `"start"`. */
|
|
809
|
+
targetLabelPosition?: LineTargetLabelPosition
|
|
810
|
+
/** Bar only: a data column holding each bar's target (see `BarChartOptions.targetKey`). */
|
|
811
|
+
targetKey?: string
|
|
812
|
+
/** Notes at an index value or over a range (vertical bars, line, area). */
|
|
813
|
+
annotations?: readonly ChartAnnotation[]
|
|
814
|
+
/** Bar only, not stacked: label bars whose value is 0 with「0」(default true). */
|
|
815
|
+
showZeroValues?: boolean
|
|
816
|
+
/** Line / Area only; ignored for bar and for percent stacking. */
|
|
817
|
+
forecast?: CartesianForecastConfig
|
|
818
|
+
/**
|
|
819
|
+
* Line / Area only; ignored for bar and for percent stacking. The series `category` is drawn as a muted 1.5px solid line
|
|
820
|
+
* (no markers, no fill, outside a stack) and the first other series' tooltip row gets its difference from it.
|
|
821
|
+
*/
|
|
822
|
+
comparison?: CartesianComparisonConfig
|
|
823
|
+
/** The `format` of the values, for the comparison's difference in the tooltip (percent → points). Default: relative change. */
|
|
824
|
+
comparisonFormat?: ValueFormat
|
|
825
|
+
/** Index value of the first provisional point (see `CartesianChartBaseProps.provisionalFrom`). */
|
|
826
|
+
provisionalFrom?: string | number
|
|
827
|
+
provisionalLabel?: string
|
|
828
|
+
/** The PNG action buttons are shown (top right): the legend keeps clear of them. */
|
|
829
|
+
reserveActions?: boolean
|
|
830
|
+
/** Colour of the target / forecast guide lines (resolved muted text). */
|
|
831
|
+
guideColor?: string
|
|
832
|
+
/**
|
|
833
|
+
* The surface the chart sits on (resolved). Highlight labels get it as a
|
|
834
|
+
* backdrop, so a guide line passing behind them never runs through the text.
|
|
835
|
+
*/
|
|
836
|
+
labelBackground?: string
|
|
837
|
+
/** Colour of the highlight labels (resolved foreground). */
|
|
838
|
+
labelColor?: string
|
|
839
|
+
/**
|
|
840
|
+
* The plot's width in px, when known. Sets how many time labels fit, how many value ticks a
|
|
841
|
+
* horizontal bar chart carries, and drops the max highlight when it would print over the latest one.
|
|
842
|
+
*/
|
|
843
|
+
plotWidth?: number
|
|
844
|
+
/** The plot's height in px (the `height` prop), when known: under 200 the value axis carries 3 intervals, else 4–5. */
|
|
845
|
+
plotHeight?: number
|
|
846
|
+
reducedMotion?: boolean
|
|
847
|
+
/** Deep-merged onto the generated option last. */
|
|
848
|
+
chartOptions?: EChartsOption
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/* ----------------------------------------------------------------- motion */
|
|
852
|
+
|
|
853
|
+
/**
|
|
854
|
+
* The typed charts' motion: no entrance animation, a short ease on updates so a
|
|
855
|
+
* filter change reads as a change. Reduced motion turns animation off.
|
|
856
|
+
*/
|
|
857
|
+
function chartMotion(reducedMotion: boolean): EChartsOption {
|
|
858
|
+
if (reducedMotion) return { animation: false }
|
|
859
|
+
return { animation: true, animationDuration: 0, animationDurationUpdate: 300, animationEasingUpdate: "cubicOut" }
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/* ----------------------------------------------------------------- merge */
|
|
863
|
+
|
|
864
|
+
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
865
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false
|
|
866
|
+
const proto = Object.getPrototypeOf(value)
|
|
867
|
+
return proto === Object.prototype || proto === null
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/**
|
|
871
|
+
* Deep-merge `override` onto `base` without mutating either: plain objects merge
|
|
872
|
+
* key by key, arrays merge by position (so `series: [{ … }]` tweaks the first
|
|
873
|
+
* series), anything else in `override` replaces. `undefined` keeps the base.
|
|
874
|
+
*/
|
|
875
|
+
function mergeChartOptions<T>(base: T, override: unknown): T {
|
|
876
|
+
if (override === undefined) return base
|
|
877
|
+
if (Array.isArray(override)) {
|
|
878
|
+
if (!Array.isArray(base)) return override as T
|
|
879
|
+
const length = Math.max(base.length, override.length)
|
|
880
|
+
return Array.from({ length }, (_, i) => (i < override.length ? mergeChartOptions(base[i], override[i]) : base[i])) as T
|
|
881
|
+
}
|
|
882
|
+
if (isPlainRecord(override) && isPlainRecord(base)) {
|
|
883
|
+
const out: Record<string, unknown> = { ...base }
|
|
884
|
+
for (const key of Object.keys(override)) out[key] = mergeChartOptions(base[key], override[key])
|
|
885
|
+
return out as T
|
|
886
|
+
}
|
|
887
|
+
return override as T
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
/* -------------------------------------------------------------- highlight */
|
|
891
|
+
|
|
892
|
+
const TIME_INDEX_RE =
|
|
893
|
+
/^\d{4}(?:[-/]\d{1,2}(?:[-/]\d{1,2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?)?)?$/
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* Whether the x values look like time: ISO dates / date-times, `YYYY-MM`,
|
|
897
|
+
* `YYYY`, or `Date` objects. Blank cells are ignored; nothing at all → `false`.
|
|
898
|
+
*/
|
|
899
|
+
function isTimeIndex(values: readonly unknown[]): boolean {
|
|
900
|
+
const present = values.filter((v) => v !== null && v !== undefined && v !== "")
|
|
901
|
+
if (present.length === 0) return false
|
|
902
|
+
return present.every((v) =>
|
|
903
|
+
v instanceof Date ? !Number.isNaN(v.getTime()) : typeof v === "string" && TIME_INDEX_RE.test(v.trim()),
|
|
904
|
+
)
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/* -------------------------------------------------------------- time axis */
|
|
908
|
+
|
|
909
|
+
type TimeGranularity = "year" | "month" | "day"
|
|
910
|
+
|
|
911
|
+
interface ParsedTime {
|
|
912
|
+
year: number
|
|
913
|
+
/** 1–12. */
|
|
914
|
+
month: number
|
|
915
|
+
day: number
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
const TIME_PARTS_RE = /^(\d{4})(?:[-/](\d{1,2})(?:[-/](\d{1,2}))?)?$/
|
|
919
|
+
|
|
920
|
+
/**
|
|
921
|
+
* The x values as calendar dates, with the finest granularity they carry — or
|
|
922
|
+
* `null` when any value is not a plain year / month / date (date-times with a
|
|
923
|
+
* clock part stay as they are: one label per hour would need its own format).
|
|
924
|
+
*/
|
|
925
|
+
function parseTimeIndex(values: readonly unknown[]): { granularity: TimeGranularity; times: (ParsedTime | null)[] } | null {
|
|
926
|
+
if (!isTimeIndex(values)) return null
|
|
927
|
+
const ranks: readonly TimeGranularity[] = ["year", "month", "day"]
|
|
928
|
+
let rank = 0
|
|
929
|
+
const finer = (g: TimeGranularity) => {
|
|
930
|
+
rank = Math.max(rank, ranks.indexOf(g))
|
|
931
|
+
}
|
|
932
|
+
const times: (ParsedTime | null)[] = []
|
|
933
|
+
for (const v of values) {
|
|
934
|
+
if (v === null || v === undefined || v === "") {
|
|
935
|
+
times.push(null)
|
|
936
|
+
continue
|
|
937
|
+
}
|
|
938
|
+
if (v instanceof Date) {
|
|
939
|
+
if (v.getHours() !== 0 || v.getMinutes() !== 0 || v.getSeconds() !== 0) return null
|
|
940
|
+
finer(v.getDate() === 1 ? "month" : "day")
|
|
941
|
+
times.push({ year: v.getFullYear(), month: v.getMonth() + 1, day: v.getDate() })
|
|
942
|
+
continue
|
|
943
|
+
}
|
|
944
|
+
const text = String(v).trim()
|
|
945
|
+
// A trailing midnight (`2025-09-01T00:00:00Z`) is still a date; any other time of day is not.
|
|
946
|
+
const date = text.replace(/[T ]00:00(?::00(?:\.0+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/, "")
|
|
947
|
+
const m = TIME_PARTS_RE.exec(date)
|
|
948
|
+
if (!m) return null
|
|
949
|
+
finer(m[3] !== undefined ? "day" : m[2] !== undefined ? "month" : "year")
|
|
950
|
+
times.push({ year: Number(m[1]), month: Number(m[2] ?? 1), day: Number(m[3] ?? 1) })
|
|
951
|
+
}
|
|
952
|
+
// Date objects on the 1st read as months only when every value falls on a 1st.
|
|
953
|
+
if (rank === 1 && values.some((v) => v instanceof Date) && times.some((t) => t !== null && t.day !== 1)) rank = 2
|
|
954
|
+
return { granularity: ranks[rank]!, times }
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
const timeFormatCache = new Map<string, Intl.DateTimeFormat>()
|
|
958
|
+
|
|
959
|
+
function timeFormat(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {
|
|
960
|
+
const key = `${locale}|${JSON.stringify(options)}`
|
|
961
|
+
let format = timeFormatCache.get(key)
|
|
962
|
+
if (!format) {
|
|
963
|
+
format = new Intl.DateTimeFormat(locale, options)
|
|
964
|
+
timeFormatCache.set(key, format)
|
|
965
|
+
}
|
|
966
|
+
return format
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
const toDate = (t: ParsedTime) => new Date(t.year, t.month - 1, t.day)
|
|
970
|
+
|
|
971
|
+
/** How many x labels a time axis shows at most (the step is picked so the labels never crowd). */
|
|
972
|
+
const TIME_AXIS_MAX_LABELS = 6
|
|
973
|
+
/** Under this plot width (px) the axis, legend and labels switch to their compact form. */
|
|
974
|
+
const NARROW_PLOT_WIDTH = 400
|
|
975
|
+
/** The most x labels a narrow plot shows (a 262px plot reads 4 at most). */
|
|
976
|
+
const NARROW_TIME_AXIS_MAX_LABELS = 4
|
|
977
|
+
|
|
978
|
+
/** Calendar-friendly label steps per granularity (every 3 months, every week …). */
|
|
979
|
+
const TIME_AXIS_STEPS: Record<TimeGranularity, readonly number[]> = {
|
|
980
|
+
year: [1, 2, 5, 10, 20, 50, 100],
|
|
981
|
+
month: [1, 2, 3, 4, 6, 12, 24, 36, 60, 120],
|
|
982
|
+
day: [1, 2, 7, 14, 28, 56, 91, 182, 364],
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
/**
|
|
986
|
+
* Every how many points a time axis prints a label: the smallest calendar step
|
|
987
|
+
* (1, 2, 3, 4, 6, 12 months; 1, 2, 7, 14 days; …) that keeps the labels at or
|
|
988
|
+
* under `maxLabels`. Deterministic, so the year-change label is never skipped by
|
|
989
|
+
* ECharts' own overlap thinning. `null` when the values are not dates.
|
|
990
|
+
*/
|
|
991
|
+
function timeAxisLabelStep(values: readonly unknown[], maxLabels: number = TIME_AXIS_MAX_LABELS): number | null {
|
|
992
|
+
const parsed = parseTimeIndex(values)
|
|
993
|
+
if (!parsed) return null
|
|
994
|
+
const count = values.length
|
|
995
|
+
const max = Math.max(1, maxLabels)
|
|
996
|
+
const steps = TIME_AXIS_STEPS[parsed.granularity]
|
|
997
|
+
return steps.find((step) => Math.ceil(count / step) <= max) ?? Math.ceil(count / max)
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/**
|
|
1001
|
+
* Category-axis labels for time-like x values, in `locale`: monthly data reads
|
|
1002
|
+
* `4月`, with the year (`2025年1月`) on the first shown label and on any shown
|
|
1003
|
+
* label whose year differs from the previous *shown* one; daily data reads
|
|
1004
|
+
* `4/1` (`2025/4/1` likewise); yearly data `2025年`. `shown(i)` says which
|
|
1005
|
+
* labels the axis prints (default: all) — hidden ones never carry the year.
|
|
1006
|
+
* `null` when the values are not dates — the axis then shows them as they are.
|
|
1007
|
+
*/
|
|
1008
|
+
function timeAxisLabels(
|
|
1009
|
+
values: readonly unknown[],
|
|
1010
|
+
localeArg?: string,
|
|
1011
|
+
shown: (i: number) => boolean = () => true,
|
|
1012
|
+
): string[] | null {
|
|
1013
|
+
const parsed = parseTimeIndex(values)
|
|
1014
|
+
if (!parsed) return null
|
|
1015
|
+
const locale = resolveLocale(localeArg)
|
|
1016
|
+
const { granularity, times } = parsed
|
|
1017
|
+
let prevYear: number | null = null
|
|
1018
|
+
return times.map((t, i) => {
|
|
1019
|
+
if (t === null) return String(values[i] ?? "")
|
|
1020
|
+
const visible = shown(i)
|
|
1021
|
+
const withYear = visible && (prevYear === null || t.year !== prevYear)
|
|
1022
|
+
if (visible) prevYear = t.year
|
|
1023
|
+
const options: Intl.DateTimeFormatOptions =
|
|
1024
|
+
granularity === "year"
|
|
1025
|
+
? { year: "numeric" }
|
|
1026
|
+
: granularity === "month"
|
|
1027
|
+
? withYear
|
|
1028
|
+
? { year: "numeric", month: "short" }
|
|
1029
|
+
: { month: "short" }
|
|
1030
|
+
: withYear
|
|
1031
|
+
? { year: "numeric", month: "numeric", day: "numeric" }
|
|
1032
|
+
: { month: "numeric", day: "numeric" }
|
|
1033
|
+
return timeFormat(locale, options).format(toDate(t))
|
|
1034
|
+
})
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
/** The tooltip titles for time-like x values (`2025年9月`, `2025年9月1日`), or `null` when they are not dates. */
|
|
1038
|
+
function timeTooltipLabels(values: readonly unknown[], localeArg?: string): string[] | null {
|
|
1039
|
+
const parsed = parseTimeIndex(values)
|
|
1040
|
+
if (!parsed) return null
|
|
1041
|
+
const locale = resolveLocale(localeArg)
|
|
1042
|
+
const options: Intl.DateTimeFormatOptions =
|
|
1043
|
+
parsed.granularity === "year"
|
|
1044
|
+
? { year: "numeric" }
|
|
1045
|
+
: parsed.granularity === "month"
|
|
1046
|
+
? { year: "numeric", month: "long" }
|
|
1047
|
+
: { year: "numeric", month: "long", day: "numeric" }
|
|
1048
|
+
return parsed.times.map((t, i) => (t === null ? String(values[i] ?? "") : timeFormat(locale, options).format(toDate(t))))
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
interface HighlightPoint {
|
|
1052
|
+
kind: "max" | "latest" | "start"
|
|
1053
|
+
index: number
|
|
1054
|
+
value: number
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
/**
|
|
1058
|
+
* The points `highlight="auto"` labels on one series: the latest (last
|
|
1059
|
+
* non-null) point, and the maximum unless it *is* the latest or sits next to it
|
|
1060
|
+
* (`|i - latest| ≤ 1`, the labels would collide) — at most 2, max first.
|
|
1061
|
+
*/
|
|
1062
|
+
function pickHighlightPoints(values: readonly (number | null)[]): HighlightPoint[] {
|
|
1063
|
+
let latest = -1
|
|
1064
|
+
for (let i = values.length - 1; i >= 0; i--) {
|
|
1065
|
+
if (values[i] !== null && values[i] !== undefined) {
|
|
1066
|
+
latest = i
|
|
1067
|
+
break
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
if (latest === -1) return []
|
|
1071
|
+
const latestValue = values[latest]!
|
|
1072
|
+
let max = -1
|
|
1073
|
+
values.forEach((v, i) => {
|
|
1074
|
+
if (v !== null && v !== undefined && (max === -1 || v > values[max]!)) max = i
|
|
1075
|
+
})
|
|
1076
|
+
const latestPoint: HighlightPoint = { kind: "latest", index: latest, value: latestValue }
|
|
1077
|
+
if (max === -1 || max === latest || latestValue >= values[max]! || Math.abs(max - latest) <= 1) return [latestPoint]
|
|
1078
|
+
return [{ kind: "max", index: max, value: values[max]! }, latestPoint]
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
/**
|
|
1082
|
+
* The points a 100% stacked area labels: the first and the latest (last
|
|
1083
|
+
* non-null) share of one band — "24% → 31%" is the claim such a chart makes.
|
|
1084
|
+
*/
|
|
1085
|
+
function pickShareHighlightPoints(values: readonly (number | null)[]): HighlightPoint[] {
|
|
1086
|
+
const first = values.findIndex((v) => v !== null && v !== undefined)
|
|
1087
|
+
if (first === -1) return []
|
|
1088
|
+
let latest = first
|
|
1089
|
+
for (let i = values.length - 1; i > first; i--) {
|
|
1090
|
+
if (values[i] !== null && values[i] !== undefined) {
|
|
1091
|
+
latest = i
|
|
1092
|
+
break
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
const latestPoint: HighlightPoint = { kind: "latest", index: latest, value: values[latest]! }
|
|
1096
|
+
return latest === first ? [latestPoint] : [{ kind: "start", index: first, value: values[first]! }, latestPoint]
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/** Whether a chart of `kind` labels its highlights by default. */
|
|
1100
|
+
function defaultChartHighlight(
|
|
1101
|
+
kind: CartesianChartKind,
|
|
1102
|
+
data: readonly Record<string, unknown>[],
|
|
1103
|
+
index: string,
|
|
1104
|
+
): ChartHighlight {
|
|
1105
|
+
if (kind !== "bar") return "auto"
|
|
1106
|
+
return isTimeIndex(data.map((row) => row[index])) ? "auto" : "none"
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/* ---------------------------------------------------------------- helpers */
|
|
1110
|
+
|
|
1111
|
+
/** Same coercion as `toChartNumber` in chart-utils (kept local: inlined modules can't import each other). */
|
|
1112
|
+
function cellNumber(value: unknown): number | null {
|
|
1113
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : null
|
|
1114
|
+
if (typeof value === "bigint") return Number(value)
|
|
1115
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
1116
|
+
const n = Number(value)
|
|
1117
|
+
return Number.isFinite(n) ? n : null
|
|
1118
|
+
}
|
|
1119
|
+
return null
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
/**
|
|
1123
|
+
* Series values per category. `"percent"` turns each row into shares of that
|
|
1124
|
+
* row's total (0–100); a row whose total is 0 stays at 0.
|
|
1125
|
+
*/
|
|
1126
|
+
function cartesianSeriesValues(
|
|
1127
|
+
data: readonly Record<string, unknown>[],
|
|
1128
|
+
categories: readonly string[],
|
|
1129
|
+
type: CartesianStackType = "default",
|
|
1130
|
+
): (number | null)[][] {
|
|
1131
|
+
const raw = categories.map((category) => data.map((row) => cellNumber(row[category])))
|
|
1132
|
+
if (type !== "percent") return raw
|
|
1133
|
+
return raw.map((values) =>
|
|
1134
|
+
values.map((value, i) => {
|
|
1135
|
+
if (value === null) return null
|
|
1136
|
+
const total = categories.reduce((sum, _, k) => sum + Math.abs(raw[k]![i] ?? 0), 0)
|
|
1137
|
+
return total === 0 ? 0 : (Math.abs(value) / total) * 100
|
|
1138
|
+
}),
|
|
1139
|
+
)
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
/** A colour with alpha, for gradient stops. Understands `#rgb`, `#rrggbb`, `rgb()`/`rgba()`. */
|
|
1143
|
+
function withAlpha(color: string, alpha: number): string {
|
|
1144
|
+
const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim())
|
|
1145
|
+
if (hex) {
|
|
1146
|
+
const h = hex[1]!
|
|
1147
|
+
const full = h.length === 3 ? h.replace(/./g, (c) => c + c) : h
|
|
1148
|
+
const n = Number.parseInt(full, 16)
|
|
1149
|
+
return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`
|
|
1150
|
+
}
|
|
1151
|
+
const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
|
|
1152
|
+
if (rgb) return `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})`
|
|
1153
|
+
return color
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
const HTML_ESCAPES: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }
|
|
1157
|
+
|
|
1158
|
+
function escapeHtml(value: string): string {
|
|
1159
|
+
return value.replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]!)
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
interface TooltipRow {
|
|
1163
|
+
name: string
|
|
1164
|
+
color: string
|
|
1165
|
+
value: number | null
|
|
1166
|
+
/** Percent stacking: the row's share of its point's total (0–100). */
|
|
1167
|
+
share?: number
|
|
1168
|
+
/** A muted line right under the row (a comparison's difference). */
|
|
1169
|
+
note?: string
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
const shareFormat = new Intl.NumberFormat(DEFAULT_LOCALE, { maximumFractionDigits: 1 })
|
|
1173
|
+
const formatShare = (share: number) => `${shareFormat.format(share)}%`
|
|
1174
|
+
|
|
1175
|
+
/** The tooltip body: a title, then one `● name value` row per series, then muted one-line `notes` (target, annotation). */
|
|
1176
|
+
function tooltipHtml(
|
|
1177
|
+
title: string,
|
|
1178
|
+
rows: readonly TooltipRow[],
|
|
1179
|
+
valueFormatter: (value: number) => string,
|
|
1180
|
+
notes: readonly string[] = [],
|
|
1181
|
+
locale?: string,
|
|
1182
|
+
): string {
|
|
1183
|
+
const t = chartText(locale)
|
|
1184
|
+
const lines = rows.map(
|
|
1185
|
+
(row) =>
|
|
1186
|
+
`<div style="display:flex;align-items:center;gap:8px;line-height:20px">` +
|
|
1187
|
+
`<span style="display:inline-block;width:8px;height:8px;border-radius:9999px;background:${escapeHtml(row.color)}"></span>` +
|
|
1188
|
+
`<span style="flex:1;opacity:.8">${escapeHtml(row.name)}</span>` +
|
|
1189
|
+
`<span style="font-weight:600;font-variant-numeric:tabular-nums;margin-left:12px">${
|
|
1190
|
+
row.value === null ? EMPTY_VALUE : escapeHtml(valueFormatter(row.value))
|
|
1191
|
+
}${
|
|
1192
|
+
row.share === undefined ? "" : `<span style="opacity:.6;margin-left:4px">${escapeHtml(t.share(formatShare(row.share)))}</span>`
|
|
1193
|
+
}</span></div>` +
|
|
1194
|
+
(row.note === undefined
|
|
1195
|
+
? ""
|
|
1196
|
+
: `<div style="padding-left:16px;line-height:18px;font-size:12px;opacity:.7;font-variant-numeric:tabular-nums">${escapeHtml(row.note)}</div>`),
|
|
1197
|
+
)
|
|
1198
|
+
const noteLines = notes.map(
|
|
1199
|
+
(note) => `<div style="margin-top:4px;line-height:18px;font-size:12px;opacity:.7">${escapeHtml(note)}</div>`,
|
|
1200
|
+
)
|
|
1201
|
+
return `<div style="font-weight:500;margin-bottom:4px">${escapeHtml(title)}</div>${lines.join("")}${noteLines.join("")}`
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
/* ------------------------------------------------- per-bar targets / notes */
|
|
1205
|
+
|
|
1206
|
+
/** Default name of the per-bar target marker (legend, tooltip) in `locale`: "Target" / 「目標」. Default the page's locale. */
|
|
1207
|
+
function barTargetLabel(locale?: string): string {
|
|
1208
|
+
return chartText(locale).target
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
/** How far (px) the target marker reaches past each side of its bar. */
|
|
1212
|
+
const TARGET_MARKER_OVERHANG = 4
|
|
1213
|
+
|
|
1214
|
+
/**
|
|
1215
|
+
* The `renderItem` of the per-bar target marker: a 2px tick across the bar. Its length
|
|
1216
|
+
* is the bar's own width as ECharts lays it out (`api.barLayout`, one column — a single
|
|
1217
|
+
* series or a stack) plus a little overhang; without that it falls back to the
|
|
1218
|
+
* category band times `barHalfWidth`.
|
|
1219
|
+
*/
|
|
1220
|
+
function targetMarkerRenderer(horizontalBars: boolean, barCategoryGap: string | number | undefined, color: string | undefined) {
|
|
1221
|
+
type Api = {
|
|
1222
|
+
value(dim: number): number
|
|
1223
|
+
coord(value: number[]): number[]
|
|
1224
|
+
size(value: number[]): number[]
|
|
1225
|
+
barLayout?(opt: { count: number; barCategoryGap?: string | number }): { width: number }[]
|
|
1226
|
+
}
|
|
1227
|
+
return (_params: unknown, api: Api) => {
|
|
1228
|
+
const [x = 0, y = 0] = api.coord([api.value(0), api.value(1)])
|
|
1229
|
+
const band = Math.abs(horizontalBars ? (api.size([0, 1])[1] ?? 0) : (api.size([1, 0])[0] ?? 0))
|
|
1230
|
+
const barWidth = api.barLayout?.({ count: 1, barCategoryGap })?.[0]?.width
|
|
1231
|
+
const length = (barWidth && barWidth > 0 ? barWidth : band * 2 * barHalfWidth(barCategoryGap)) + TARGET_MARKER_OVERHANG * 2
|
|
1232
|
+
return {
|
|
1233
|
+
type: "line",
|
|
1234
|
+
silent: true,
|
|
1235
|
+
shape: horizontalBars
|
|
1236
|
+
? { x1: x, y1: y - length / 2, x2: x, y2: y + length / 2 }
|
|
1237
|
+
: { x1: x - length / 2, y1: y, x2: x + length / 2, y2: y },
|
|
1238
|
+
style: { stroke: color, lineWidth: 2, lineCap: "butt" },
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/**
|
|
1244
|
+
* Each row's target from the `targetKey` column. A missing, non-numeric or
|
|
1245
|
+
* non-positive cell is `null` (no marker for that bar).
|
|
1246
|
+
*/
|
|
1247
|
+
function barTargetValues(data: readonly Record<string, unknown>[], targetKey: string): (number | null)[] {
|
|
1248
|
+
return data.map((row) => {
|
|
1249
|
+
const value = cellNumber(row[targetKey])
|
|
1250
|
+
return value !== null && value > 0 ? value : null
|
|
1251
|
+
})
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
/** `value` as a share of `target` in percent; `null` without a value or a positive target. */
|
|
1255
|
+
function achievementRate(value: number | null | undefined, target: number | null | undefined): number | null {
|
|
1256
|
+
if (value === null || value === undefined || target === null || target === undefined || !(target > 0)) return null
|
|
1257
|
+
return (value / target) * 100
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
/** The tooltip line of a bar with a target: 「目標 ¥1,200万(達成率 85.3%)」 / "Target $12M (85.3% achieved)". `null` without a target. */
|
|
1261
|
+
function barTargetNote(
|
|
1262
|
+
label: string,
|
|
1263
|
+
value: number | null,
|
|
1264
|
+
target: number | null,
|
|
1265
|
+
valueFormatter: (value: number) => string,
|
|
1266
|
+
locale?: string,
|
|
1267
|
+
): string | null {
|
|
1268
|
+
if (target === null) return null
|
|
1269
|
+
const rate = achievementRate(value, target)
|
|
1270
|
+
return `${label} ${valueFormatter(target)}${rate === null ? "" : chartText(locale).targetRate(formatShare(rate))}`
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/** Half the width of a bar in category-axis units, from `barCategoryGap` (`"20%"`; a px gap or none → ECharts' 20%). */
|
|
1274
|
+
function barHalfWidth(barCategoryGap?: string | number): number {
|
|
1275
|
+
const gap = typeof barCategoryGap === "string" && /^\d+(\.\d+)?%$/.test(barCategoryGap.trim()) ? parseFloat(barCategoryGap) / 100 : 0.2
|
|
1276
|
+
return 0.5 / (1 + gap)
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
/** An annotation placed on the category axis: positions are indexes into the x labels. */
|
|
1280
|
+
interface ResolvedAnnotation {
|
|
1281
|
+
from: number
|
|
1282
|
+
/** Set for a range (`to` after `from`); a single position leaves it out. */
|
|
1283
|
+
to?: number
|
|
1284
|
+
label: string
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
/**
|
|
1288
|
+
* Place annotations on the x labels by `String(value)` equality. An annotation
|
|
1289
|
+
* whose `at` is not an `index` value is dropped; `to` before `at` swaps them; a
|
|
1290
|
+
* `to` that is unknown or equal to `at` makes it a single position.
|
|
1291
|
+
*/
|
|
1292
|
+
function resolveAnnotations(
|
|
1293
|
+
annotations: readonly ChartAnnotation[] | undefined,
|
|
1294
|
+
indexValues: readonly unknown[],
|
|
1295
|
+
): ResolvedAnnotation[] {
|
|
1296
|
+
if (!annotations?.length) return []
|
|
1297
|
+
const position = new Map<string, number>()
|
|
1298
|
+
indexValues.forEach((value, i) => {
|
|
1299
|
+
const key = String(value ?? "")
|
|
1300
|
+
if (!position.has(key)) position.set(key, i)
|
|
1301
|
+
})
|
|
1302
|
+
const out: ResolvedAnnotation[] = []
|
|
1303
|
+
for (const note of annotations) {
|
|
1304
|
+
const from = position.get(String(note.at))
|
|
1305
|
+
if (from === undefined || !note.label) continue
|
|
1306
|
+
const end = note.to === undefined ? undefined : position.get(String(note.to))
|
|
1307
|
+
if (end === undefined || end === from) out.push({ from, label: note.label })
|
|
1308
|
+
else out.push({ from: Math.min(from, end), to: Math.max(from, end), label: note.label })
|
|
1309
|
+
}
|
|
1310
|
+
return out
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
/** Gap (px) under which two neighbouring vertical labels (12px text) would print over each other. */
|
|
1314
|
+
const ANNOTATION_LABEL_GAP = 16
|
|
1315
|
+
/** Assumed spacing (px) between two index positions when the plot's width is unknown. */
|
|
1316
|
+
const ANNOTATION_ASSUMED_GAP = 40
|
|
1317
|
+
|
|
1318
|
+
/**
|
|
1319
|
+
* Which end of its line each single-position annotation's label sits on. Labels
|
|
1320
|
+
* run along the line; neighbours closer than a label's height alternate between
|
|
1321
|
+
* the top and the bottom end, so they never print over one another. `lines` are
|
|
1322
|
+
* the annotation positions (index units) in any order; the result follows that order.
|
|
1323
|
+
*/
|
|
1324
|
+
function annotationLabelEnds(lines: readonly number[], pointGap: number | null): ("top" | "bottom")[] {
|
|
1325
|
+
const gap = pointGap ?? ANNOTATION_ASSUMED_GAP
|
|
1326
|
+
const order = lines.map((at, i) => ({ at, i })).sort((a, b) => a.at - b.at || a.i - b.i)
|
|
1327
|
+
const ends: ("top" | "bottom")[] = Array(lines.length).fill("top")
|
|
1328
|
+
for (let k = 1; k < order.length; k++) {
|
|
1329
|
+
const prev = order[k - 1]!
|
|
1330
|
+
const cur = order[k]!
|
|
1331
|
+
if ((cur.at - prev.at) * gap < ANNOTATION_LABEL_GAP) ends[cur.i] = ends[prev.i] === "top" ? "bottom" : "top"
|
|
1332
|
+
}
|
|
1333
|
+
return ends
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
interface AxisTooltipParam {
|
|
1337
|
+
seriesId?: string
|
|
1338
|
+
seriesName?: string
|
|
1339
|
+
dataIndex?: number
|
|
1340
|
+
color?: unknown
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
const DIMMED = 0.3
|
|
1344
|
+
|
|
1345
|
+
|
|
1346
|
+
/** Series ids. Ours are stable across updates so ECharts can transition them; `__` marks the helpers. */
|
|
1347
|
+
const SERIES_ID_PREFIX = "series:"
|
|
1348
|
+
const FORECAST_SERIES_ID = "__forecast"
|
|
1349
|
+
const PROVISIONAL_SERIES_PREFIX = "__provisional:"
|
|
1350
|
+
/** Provisional points are drawn at this opacity (lines, areas, bars). */
|
|
1351
|
+
const PROVISIONAL_OPACITY = 0.55
|
|
1352
|
+
/** Horizontal bars (one series, not stacked) are painted at this share of the series colour; the highlighted bar is solid. Same tint as BarList. */
|
|
1353
|
+
const LIGHT_BAR_ALPHA = 0.7
|
|
1354
|
+
const FORECAST_BAND_BASE_ID = "__forecast-band-base"
|
|
1355
|
+
const FORECAST_BAND_RANGE_ID = "__forecast-band-range"
|
|
1356
|
+
const OVERLAY_SERIES_ID = "__overlay"
|
|
1357
|
+
const TARGET_MARKER_SERIES_ID = "__target-marker"
|
|
1358
|
+
const TARGET_LEGEND_SERIES_ID = "__target-legend"
|
|
1359
|
+
/** A flat tick (8×8 legend box, aspect kept): the per-bar target's legend icon. */
|
|
1360
|
+
const TARGET_LEGEND_ICON = "path://M0,0 L100,0 L100,24 L0,24 Z"
|
|
1361
|
+
|
|
1362
|
+
/**
|
|
1363
|
+
* 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.
|
|
1364
|
+
* Without a `label`, "Forecast" / 「予測」 in `locale` (default the page's).
|
|
1365
|
+
*/
|
|
1366
|
+
function forecastBoundaryText(label?: string, locale?: string): string {
|
|
1367
|
+
return `${label ?? chartText(locale).forecast} →`
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
/** A comparison series: a thin, muted, solid line with no markers (60% of `--muted-foreground`). */
|
|
1371
|
+
const COMPARISON_LINE_WIDTH = 1.5
|
|
1372
|
+
const COMPARISON_OPACITY = 0.6
|
|
1373
|
+
/** Target line: 1px dotted. Forecast: 2px dashed. Different widths *and* patterns, so the two never read as one. */
|
|
1374
|
+
const TARGET_LINE_DASH = [2, 3]
|
|
1375
|
+
const FORECAST_LINE_DASH = [6, 4]
|
|
1376
|
+
/** Legend icons for the two (8×8 box, aspect kept): a row of dots / of dashes in the line's own proportions. */
|
|
1377
|
+
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"
|
|
1378
|
+
const FORECAST_DASHED_ICON = "path://M0,0 L42,0 L42,24 L0,24 Z M58,0 L100,0 L100,24 L58,24 Z"
|
|
1379
|
+
|
|
1380
|
+
/** The forecast band's fill opacity: on a dark surface it needs more to show against the background. */
|
|
1381
|
+
const FORECAST_BAND_ALPHA_LIGHT = 0.15
|
|
1382
|
+
const FORECAST_BAND_ALPHA_DARK = 0.22
|
|
1383
|
+
|
|
1384
|
+
/** Whether a resolved surface colour (`#rrggbb` / `rgb()`) is dark (relative luminance under 0.4). `false` when it can't be read. */
|
|
1385
|
+
function isDarkSurface(color: string | undefined): boolean {
|
|
1386
|
+
if (!color) return false
|
|
1387
|
+
const hex = /^#([0-9a-f]{6})$/i.exec(color.trim())
|
|
1388
|
+
const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
|
|
1389
|
+
let channels: number[]
|
|
1390
|
+
if (hex) {
|
|
1391
|
+
const n = Number.parseInt(hex[1]!, 16)
|
|
1392
|
+
channels = [(n >> 16) & 255, (n >> 8) & 255, n & 255]
|
|
1393
|
+
} else if (rgb) channels = [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])]
|
|
1394
|
+
else return false
|
|
1395
|
+
const [r, g, b] = channels.map((c) => {
|
|
1396
|
+
const v = c / 255
|
|
1397
|
+
return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4
|
|
1398
|
+
}) as [number, number, number]
|
|
1399
|
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b < 0.4
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
interface AxisExtent {
|
|
1403
|
+
min: number
|
|
1404
|
+
max: number
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
/** The label of a stack's total (highlight and tooltip) in `locale`: "Total" / 「合計」. Default the page's locale. */
|
|
1408
|
+
function stackTotalLabel(locale?: string): string {
|
|
1409
|
+
return chartText(locale).total
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
/** Per point, the sum of the stacked series; `null` where every series is missing. */
|
|
1413
|
+
function stackTotalsOf(values: readonly (readonly (number | null)[])[]): (number | null)[] {
|
|
1414
|
+
const length = Math.max(0, ...values.map((v) => v.length))
|
|
1415
|
+
return Array.from({ length }, (_, i) => {
|
|
1416
|
+
let total: number | null = null
|
|
1417
|
+
for (const series of values) {
|
|
1418
|
+
const v = series[i]
|
|
1419
|
+
if (v !== null && v !== undefined) total = (total ?? 0) + v
|
|
1420
|
+
}
|
|
1421
|
+
return total
|
|
1422
|
+
})
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
const LEGEND_LINE_HEIGHT = 24
|
|
1426
|
+
/** A rough width budget per legend line (px): a narrow card fits about this much. */
|
|
1427
|
+
const LEGEND_LINE_BUDGET = 320
|
|
1428
|
+
|
|
1429
|
+
/** How many lines the plain legend takes, estimated from its labels (12px text + 8px dot + gaps). */
|
|
1430
|
+
function legendLines(items: readonly string[], plotWidth?: number, reserve = 0): number {
|
|
1431
|
+
const width = items.reduce((sum, name) => sum + [...name].length * 12 + 8 + 5 + 16, 0)
|
|
1432
|
+
// A narrow plot has no room for the PNG buttons beside the legend: they move off its line, so no reserve.
|
|
1433
|
+
const narrow = plotWidth !== undefined && plotWidth < NARROW_PLOT_WIDTH
|
|
1434
|
+
const budget = Math.max(80, (plotWidth ? (narrow ? plotWidth : Math.min(LEGEND_LINE_BUDGET, plotWidth)) : LEGEND_LINE_BUDGET) - (narrow ? 0 : reserve))
|
|
1435
|
+
return Math.min(3, Math.max(1, Math.ceil(width / budget)))
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
/** Width (px) kept free at the legend's right for the PNG action buttons (two 32px buttons + gaps). */
|
|
1439
|
+
const ACTIONS_RESERVE = 80
|
|
1440
|
+
|
|
1441
|
+
/** Room (px) one time label (`2026年1月`) needs, gap included. */
|
|
1442
|
+
const TIME_LABEL_WIDTH = 80
|
|
1443
|
+
/** Room (px) one highlight label (`¥6,240万`) needs, gap included. */
|
|
1444
|
+
const HIGHLIGHT_LABEL_WIDTH = 96
|
|
1445
|
+
|
|
1446
|
+
/** A highlight this close under the target (share of the larger of the two) can reach its label. */
|
|
1447
|
+
const TARGET_NEAR_SHARE = 0.12
|
|
1448
|
+
/** Under this plot width (px) a target label that would run into the latest value's label is dropped from the line. */
|
|
1449
|
+
const TARGET_LABEL_NARROW_WIDTH = 480
|
|
1450
|
+
/** A typical value-axis label column (`¥8,000万`), px. */
|
|
1451
|
+
const Y_AXIS_ESTIMATE = 72
|
|
1452
|
+
/** Breathing room between two labels, px — the estimate is rough. */
|
|
1453
|
+
const LABEL_SLACK = 24
|
|
1454
|
+
|
|
1455
|
+
/** Rough width (px) of 12px text: full-width characters 12, the rest 7. */
|
|
1456
|
+
function estimateTextWidth(text: string): number {
|
|
1457
|
+
let w = 0
|
|
1458
|
+
for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
|
|
1459
|
+
return w
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
/**
|
|
1463
|
+
* How many intervals a horizontal value axis (a horizontal bar chart's x) can carry in `plot` px
|
|
1464
|
+
* without its tick labels touching: each tick takes the widest of `samples` (the axis' end labels
|
|
1465
|
+
* printed) plus a gap. At least 1, at most 5 (ECharts' default, which it rounds to a tidy step).
|
|
1466
|
+
*/
|
|
1467
|
+
function valueAxisSplitNumber(plot: number, samples: readonly string[]): number {
|
|
1468
|
+
const widest = samples.reduce((m, t) => Math.max(m, estimateTextWidth(t)), 0)
|
|
1469
|
+
return Math.max(1, Math.min(5, Math.floor(plot / (widest + LABEL_SLACK))))
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
/** Room (px) above a vertical bar chart's plot for the label of an annotation band. */
|
|
1473
|
+
const BAND_LABEL_ROOM = 18
|
|
1474
|
+
|
|
1475
|
+
/** The grid's right margin on a line / area chart (px): the last x label hangs past the plot. */
|
|
1476
|
+
const LINE_RIGHT_MARGIN = 32
|
|
1477
|
+
|
|
1478
|
+
/** Room (px) above the plot for a forecast's boundary label (「予測 →」). */
|
|
1479
|
+
const FORECAST_LABEL_ROOM = 18
|
|
1480
|
+
|
|
1481
|
+
/**
|
|
1482
|
+
* Which side of the forecast boundary line the flat boundary label reads from: `"left"` starts at the line and runs
|
|
1483
|
+
* over the forecast side; `"right"` ends at the line and runs over the actuals, when the forecast side (the room right
|
|
1484
|
+
* of the line, grid margin included) is narrower than the text, so it never runs off the chart.
|
|
1485
|
+
* `forecastSpan` is `null` when the width is unknown.
|
|
1486
|
+
*/
|
|
1487
|
+
function forecastLabelAlign(forecastSpan: number | null, text: string = forecastBoundaryText()): "left" | "right" {
|
|
1488
|
+
return forecastSpan !== null && forecastSpan >= estimateTextWidth(text) + 8 ? "left" : "right"
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
/** ECharts' "nice" tick step for a raw step (1 / 2 / 3 / 5 × 10ⁿ, rounded): the same rule its value axis uses. */
|
|
1492
|
+
function niceStep(raw: number): number {
|
|
1493
|
+
if (!(raw > 0) || !Number.isFinite(raw)) return 1
|
|
1494
|
+
const exp10 = 10 ** Math.floor(Math.log10(raw))
|
|
1495
|
+
const f = raw / exp10
|
|
1496
|
+
return (f < 1.5 ? 1 : f < 2.5 ? 2 : f < 4 ? 3 : f < 7 ? 5 : 10) * exp10
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
/**
|
|
1500
|
+
* The largest tick (by size) a value axis over `[lo, hi]` will carry once ECharts has niced its ends — the number
|
|
1501
|
+
* that decides the unit the ticks read in (`resolveAxisTickFormatter`). `max`, when fixed, is the axis' top as is.
|
|
1502
|
+
*/
|
|
1503
|
+
function estimateAxisTop(lo: number, hi: number, splitNumber: number, max?: number): number {
|
|
1504
|
+
const top = Math.max(Math.abs(lo), Math.abs(hi))
|
|
1505
|
+
if (!(top > 0)) return 0
|
|
1506
|
+
const step = niceStep((hi - lo) / splitNumber)
|
|
1507
|
+
const niceHi = max !== undefined && max >= hi ? max : Math.ceil(hi / step) * step
|
|
1508
|
+
const niceLo = Math.floor(lo / step) * step
|
|
1509
|
+
return Math.max(Math.abs(niceHi), Math.abs(niceLo))
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
/** Plot heights (px) under this carry 3 value intervals, not 4–5. */
|
|
1513
|
+
const SHORT_PLOT_HEIGHT = 200
|
|
1514
|
+
/** Plot heights under this carry 4 value intervals; taller ones 5. */
|
|
1515
|
+
const TALL_PLOT_HEIGHT = 300
|
|
1516
|
+
/** The plot height assumed when it isn't known (the charts' default `height`). */
|
|
1517
|
+
const ASSUMED_PLOT_HEIGHT = 288
|
|
1518
|
+
|
|
1519
|
+
/** How many intervals a vertical value axis carries: 3 under 200px of plot height, 4 under 300px, else 5. */
|
|
1520
|
+
function valueAxisSplitCount(plotHeight: number = ASSUMED_PLOT_HEIGHT): number {
|
|
1521
|
+
return plotHeight < SHORT_PLOT_HEIGHT ? 3 : plotHeight < TALL_PLOT_HEIGHT ? 4 : 5
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
/** The grain of time-like x values (`"month"` for `2026-04`), or `null` when they aren't plain years / months / days. */
|
|
1525
|
+
function indexGrain(values: readonly unknown[]): PeriodGrain | null {
|
|
1526
|
+
const parsed = parseTimeIndex(values)
|
|
1527
|
+
return parsed ? parsed.granularity : null
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
/**
|
|
1531
|
+
* The tooltip line under the main series' row when a comparison series is drawn: the arrow, the signed change and the
|
|
1532
|
+
* comparison's name, as `Delta` writes it ("↑ +12.4% vs. same month last year" / "↑ +12.4% 前年同月比"; a minus is U+2212).
|
|
1533
|
+
* "No comparison vs. same month last year" / "比較なし 前年同月比" when either value is missing or the baseline is 0.
|
|
1534
|
+
*/
|
|
1535
|
+
function comparisonNote(
|
|
1536
|
+
current: number | null,
|
|
1537
|
+
previous: number | null,
|
|
1538
|
+
comparison: Pick<CartesianComparisonConfig, "vs" | "label">,
|
|
1539
|
+
grain?: PeriodGrain,
|
|
1540
|
+
format?: ValueFormat,
|
|
1541
|
+
localeArg?: string,
|
|
1542
|
+
): string {
|
|
1543
|
+
const locale = resolveLocale(localeArg)
|
|
1544
|
+
const result = computeComparison(
|
|
1545
|
+
current,
|
|
1546
|
+
comparison.vs === "custom"
|
|
1547
|
+
? { previous, vs: "custom", label: comparison.label ?? "", grain }
|
|
1548
|
+
: { previous, vs: comparison.vs, label: comparison.label, grain },
|
|
1549
|
+
{ locale },
|
|
1550
|
+
)
|
|
1551
|
+
const text = formatChange(result, defaultChangeDisplay(format), locale, format)
|
|
1552
|
+
if (text === null) return `${chartText(locale).noComparison} ${result.label}`
|
|
1553
|
+
const arrow = result.direction === "up" ? "↑" : result.direction === "down" ? "↓" : "→"
|
|
1554
|
+
return `${arrow} ${text.replace(/^-/, "−")} ${result.label}`
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
/** Bars and areas start at 0: the length / area *is* the value. */
|
|
1558
|
+
const zeroBasedMin = (extent: AxisExtent) => Math.min(0, extent.min)
|
|
1559
|
+
|
|
1560
|
+
/**
|
|
1561
|
+
* A value axis' `min` / `max` from the limits a caller asked for, so that charts shown side by side can share one scale.
|
|
1562
|
+
* A limit never cuts the data: when the data runs past it, the axis widens to the data (`max(maxValue, data max)`).
|
|
1563
|
+
* `zeroBased` (bars, areas, waterfall): the axis always reaches 0, so a `minValue` above 0 is ignored and only a
|
|
1564
|
+
* negative one (room below 0) takes effect. Without a limit asked for, that edge is `undefined` (ECharts' own choice)
|
|
1565
|
+
* — except a zero-based `min`, which is always given.
|
|
1566
|
+
*/
|
|
1567
|
+
function valueAxisLimits(
|
|
1568
|
+
limits: { minValue?: number; maxValue?: number },
|
|
1569
|
+
zeroBased: boolean,
|
|
1570
|
+
): { min: ((extent: AxisExtent) => number) | undefined; max: ((extent: AxisExtent) => number) | undefined } {
|
|
1571
|
+
const lo = Number.isFinite(limits.minValue) ? limits.minValue : undefined
|
|
1572
|
+
const hi = Number.isFinite(limits.maxValue) ? limits.maxValue : undefined
|
|
1573
|
+
return {
|
|
1574
|
+
min: zeroBased
|
|
1575
|
+
? (extent) => Math.min(0, lo ?? 0, extent.min)
|
|
1576
|
+
: lo === undefined
|
|
1577
|
+
? undefined
|
|
1578
|
+
: (extent) => Math.min(lo, extent.min),
|
|
1579
|
+
max: hi === undefined ? undefined : (extent) => Math.max(hi, extent.max),
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
function buildCartesianOption(cfg: CartesianChartConfig): EChartsOption {
|
|
1584
|
+
const {
|
|
1585
|
+
kind,
|
|
1586
|
+
data,
|
|
1587
|
+
index,
|
|
1588
|
+
categories,
|
|
1589
|
+
palette,
|
|
1590
|
+
labels: nameLabels,
|
|
1591
|
+
thresholds,
|
|
1592
|
+
toneColors,
|
|
1593
|
+
valueFormatter,
|
|
1594
|
+
axisFormatter = valueFormatter,
|
|
1595
|
+
type = "default",
|
|
1596
|
+
layout = "horizontal",
|
|
1597
|
+
curveType = "linear",
|
|
1598
|
+
fill = "gradient",
|
|
1599
|
+
connectNulls = false,
|
|
1600
|
+
showLegend = true,
|
|
1601
|
+
showTooltip = true,
|
|
1602
|
+
showGridLines = true,
|
|
1603
|
+
showXAxis = true,
|
|
1604
|
+
showYAxis = true,
|
|
1605
|
+
startEndOnly = false,
|
|
1606
|
+
yAxisWidth,
|
|
1607
|
+
minValue,
|
|
1608
|
+
maxValue,
|
|
1609
|
+
autoMinValue = false,
|
|
1610
|
+
fitToData,
|
|
1611
|
+
allowDecimals = true,
|
|
1612
|
+
xAxisLabel,
|
|
1613
|
+
yAxisLabel,
|
|
1614
|
+
barCategoryGap,
|
|
1615
|
+
showDots = false,
|
|
1616
|
+
active = null,
|
|
1617
|
+
target,
|
|
1618
|
+
targetLabel,
|
|
1619
|
+
targetLabelPosition = "start",
|
|
1620
|
+
targetKey,
|
|
1621
|
+
showZeroValues = true,
|
|
1622
|
+
guideColor,
|
|
1623
|
+
labelBackground,
|
|
1624
|
+
labelColor,
|
|
1625
|
+
plotWidth,
|
|
1626
|
+
plotHeight,
|
|
1627
|
+
reducedMotion = false,
|
|
1628
|
+
chartOptions,
|
|
1629
|
+
reserveActions = false,
|
|
1630
|
+
} = cfg
|
|
1631
|
+
const locale = resolveLocale(cfg.locale)
|
|
1632
|
+
const text = chartText(locale)
|
|
1633
|
+
const provisionalLabel = cfg.provisionalLabel ?? text.provisional
|
|
1634
|
+
|
|
1635
|
+
const stacked = kind !== "line" && type !== "default"
|
|
1636
|
+
const percent = kind !== "line" && type === "percent"
|
|
1637
|
+
const horizontalBars = kind === "bar" && layout === "vertical"
|
|
1638
|
+
/*
|
|
1639
|
+
* -- comparison: a plain line, outside the stack and the palette. Never with bars or a 100% stack
|
|
1640
|
+
* (shares of a total have no "last year" line).
|
|
1641
|
+
*/
|
|
1642
|
+
const comparison = kind !== "bar" && !percent ? cfg.comparison : undefined
|
|
1643
|
+
const compIdx = comparison ? categories.indexOf(comparison.category) : -1
|
|
1644
|
+
/** Positions of the series that are not the comparison: the stack, the highlight and the forecast read these. */
|
|
1645
|
+
const mainIdx = categories.map((_, i) => i).filter((i) => i !== compIdx)
|
|
1646
|
+
const seriesType = kind === "line" ? "default" : type
|
|
1647
|
+
const values = (() => {
|
|
1648
|
+
if (compIdx === -1) return cartesianSeriesValues(data, categories, seriesType)
|
|
1649
|
+
const main = cartesianSeriesValues(data, mainIdx.map((i) => categories[i]!), seriesType)
|
|
1650
|
+
const compared = cartesianSeriesValues(data, [categories[compIdx]!], "default")[0]!
|
|
1651
|
+
return categories.map((_, i) => (i === compIdx ? compared : main[mainIdx.indexOf(i)]!))
|
|
1652
|
+
})()
|
|
1653
|
+
const comparisonColor = guideColor ? withAlpha(guideColor, COMPARISON_OPACITY) : undefined
|
|
1654
|
+
|
|
1655
|
+
/* -- x labels: the actual rows, then the forecast rows that extend them */
|
|
1656
|
+
const labels = data.map((row) => String(row[index] ?? ""))
|
|
1657
|
+
const rawIndex: unknown[] = data.map((row) => row[index])
|
|
1658
|
+
const lastActual = labels.length - 1
|
|
1659
|
+
// First provisional point (-1: none). Looked up among the actual rows only; unrelated to `forecast`.
|
|
1660
|
+
const provStart = categories.length > 0 ? provisionalStart(rawIndex, cfg.provisionalFrom) : -1
|
|
1661
|
+
const forecast =
|
|
1662
|
+
kind !== "bar" && !percent && cfg.forecast && cfg.forecast.data.length > 0 && data.length > 0 && categories.length > 0
|
|
1663
|
+
? cfg.forecast
|
|
1664
|
+
: undefined
|
|
1665
|
+
const forecastAt: number[] = []
|
|
1666
|
+
if (forecast) {
|
|
1667
|
+
const position = new Map(labels.map((label, i) => [label, i]))
|
|
1668
|
+
for (const row of forecast.data) {
|
|
1669
|
+
const label = String(row[index] ?? "")
|
|
1670
|
+
let at = position.get(label)
|
|
1671
|
+
if (at === undefined || at <= lastActual) {
|
|
1672
|
+
// A forecast row never overwrites an actual point; repeated labels append.
|
|
1673
|
+
at = labels.length
|
|
1674
|
+
labels.push(label)
|
|
1675
|
+
rawIndex.push(row[index])
|
|
1676
|
+
position.set(label, at)
|
|
1677
|
+
}
|
|
1678
|
+
forecastAt.push(at)
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
const pad = (series: (number | null)[]) =>
|
|
1682
|
+
series.length < labels.length ? [...series, ...Array<null>(labels.length - series.length).fill(null)] : series
|
|
1683
|
+
const last = labels.length - 1
|
|
1684
|
+
/*
|
|
1685
|
+
* -- time-like x values read as dates in the locale (`4月`, `2026年1月`), at a
|
|
1686
|
+
* fixed calendar step so the year-change label is never thinned away.
|
|
1687
|
+
*/
|
|
1688
|
+
const timeStep = startEndOnly
|
|
1689
|
+
? null
|
|
1690
|
+
: timeAxisLabelStep(
|
|
1691
|
+
rawIndex,
|
|
1692
|
+
plotWidth
|
|
1693
|
+
? Math.max(
|
|
1694
|
+
2,
|
|
1695
|
+
Math.min(
|
|
1696
|
+
plotWidth < NARROW_PLOT_WIDTH ? NARROW_TIME_AXIS_MAX_LABELS : TIME_AXIS_MAX_LABELS,
|
|
1697
|
+
Math.floor(plotWidth / TIME_LABEL_WIDTH),
|
|
1698
|
+
),
|
|
1699
|
+
)
|
|
1700
|
+
: undefined,
|
|
1701
|
+
)
|
|
1702
|
+
// Plain (non-date) x labels of a line chart: thinned to every n-th so they never touch, never rotated.
|
|
1703
|
+
const plainStep = (() => {
|
|
1704
|
+
if (kind !== "line" || startEndOnly || timeStep !== null || !plotWidth || labels.length < 3) return 1
|
|
1705
|
+
const widest = Math.max(...labels.map((l) => estimateTextWidth(nameLabels && hasLabel(nameLabels, l) ? labelOf(l, nameLabels) : l)))
|
|
1706
|
+
const plot = Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - LINE_RIGHT_MARGIN)
|
|
1707
|
+
return Math.max(1, Math.ceil(((widest + 12) * (labels.length - 1)) / plot))
|
|
1708
|
+
})()
|
|
1709
|
+
const shownLabel = startEndOnly
|
|
1710
|
+
? (i: number) => i === 0 || i === last
|
|
1711
|
+
: timeStep !== null
|
|
1712
|
+
? (i: number) => i % timeStep === 0
|
|
1713
|
+
: plainStep > 1
|
|
1714
|
+
? (i: number) => i % plainStep === 0
|
|
1715
|
+
: null
|
|
1716
|
+
const timeLabels = timeAxisLabels(rawIndex, locale, shownLabel ?? undefined)
|
|
1717
|
+
const compGrain = comparison ? (indexGrain(rawIndex.slice(0, lastActual + 1)) ?? undefined) : undefined
|
|
1718
|
+
const tooltipTitles = (timeTooltipLabels(rawIndex, locale) ?? labels).map((title, i) =>
|
|
1719
|
+
nameLabels ? (hasLabel(nameLabels, labels[i] ?? "") ? labelOf(labels[i] ?? "", nameLabels) : title) : title,
|
|
1720
|
+
)
|
|
1721
|
+
|
|
1722
|
+
/*
|
|
1723
|
+
* -- highlight: max + latest. Normal stacking labels the stack's total (on the
|
|
1724
|
+
* top layer); otherwise the first series, ≤ 2 series. A 100% stacked area
|
|
1725
|
+
* labels the first series' (the bottom band's) first and latest share inside
|
|
1726
|
+
* the band; a 100% stacked bar labels nothing.
|
|
1727
|
+
*/
|
|
1728
|
+
const highlight = cfg.highlight ?? defaultChartHighlight(kind, data, index)
|
|
1729
|
+
const stackTotals = stacked && !percent ? stackTotalsOf(mainIdx.map((i) => values[i]!)) : null
|
|
1730
|
+
const highlightSeries = (stackTotals ? mainIdx[mainIdx.length - 1] : mainIdx[0]) ?? 0
|
|
1731
|
+
const shareHighlight = percent && kind === "area"
|
|
1732
|
+
const picked =
|
|
1733
|
+
highlight !== "auto" || mainIdx.length === 0 || (percent && !shareHighlight)
|
|
1734
|
+
? []
|
|
1735
|
+
: shareHighlight
|
|
1736
|
+
? categories.length <= 2
|
|
1737
|
+
? pickShareHighlightPoints(values[0] ?? [])
|
|
1738
|
+
: []
|
|
1739
|
+
: stackTotals
|
|
1740
|
+
? pickHighlightPoints(stackTotals)
|
|
1741
|
+
: mainIdx.length <= 2
|
|
1742
|
+
? pickHighlightPoints(values[highlightSeries] ?? [])
|
|
1743
|
+
: []
|
|
1744
|
+
// On a narrow plot the max and the latest label would print over each other: keep the latest.
|
|
1745
|
+
const pointGap = plotWidth && labels.length > 1 ? plotWidth / (kind === "bar" ? labels.length : labels.length - 1) : null
|
|
1746
|
+
// By default only the latest value is labelled; an explicit `highlight` keeps its max + latest.
|
|
1747
|
+
const latestOnly = cfg.highlight === undefined && !shareHighlight && picked.length === 2
|
|
1748
|
+
const highlightPoints =
|
|
1749
|
+
latestOnly
|
|
1750
|
+
? [picked[1]!]
|
|
1751
|
+
: picked.length === 2 && pointGap !== null && Math.abs(picked[1]!.index - picked[0]!.index) * pointGap < HIGHLIGHT_LABEL_WIDTH
|
|
1752
|
+
? [picked[1]!]
|
|
1753
|
+
: picked
|
|
1754
|
+
|
|
1755
|
+
/*
|
|
1756
|
+
* Points (and the outer bars) sit at the plot's edges: pull the first / last
|
|
1757
|
+
* label inward so it isn't clipped. A label on the forecast boundary sits left
|
|
1758
|
+
* of the boundary line instead of across it.
|
|
1759
|
+
*/
|
|
1760
|
+
const boundaryIndex = kind !== "bar" && !percent && cfg.forecast && cfg.forecast.data.length > 0 ? lastActual : -1
|
|
1761
|
+
const edgeAlign = (i: number) =>
|
|
1762
|
+
horizontalBars || labels.length < 2
|
|
1763
|
+
? undefined
|
|
1764
|
+
: i === boundaryIndex && i !== last
|
|
1765
|
+
? { align: "right" as const, offset: [-6, 0] }
|
|
1766
|
+
: i === last
|
|
1767
|
+
? { align: "right" as const, ...(kind === "bar" ? { offset: [8, 0] } : {}) }
|
|
1768
|
+
: i === 0
|
|
1769
|
+
? { align: "left" as const, ...(kind === "bar" ? { offset: [-8, 0] } : {}) }
|
|
1770
|
+
: undefined
|
|
1771
|
+
|
|
1772
|
+
/*
|
|
1773
|
+
* The target label sits at the plot's start (left), above its line, so it stays clear of the latest value's label at
|
|
1774
|
+
* the right end. Near the label (horizontally, estimated from `plotWidth`) a line / area highlight just under the
|
|
1775
|
+
* target prints below its point, and one just over it moves the target label under the line instead. On a plot
|
|
1776
|
+
* narrower than 480px, when the *latest* point's label would still run into the target label, the target label leaves
|
|
1777
|
+
* the line altogether — the legend names the target.
|
|
1778
|
+
*/
|
|
1779
|
+
// `barOptions.targetKey` (a target per bar) takes over from the single `target` line.
|
|
1780
|
+
const perBarTarget = kind === "bar" && Boolean(targetKey)
|
|
1781
|
+
const hasTarget = !perBarTarget && target !== undefined && Number.isFinite(target)
|
|
1782
|
+
const targetText = hasTarget ? (targetLabel ?? `${text.target} ${axisFormatter(target)}`) : ""
|
|
1783
|
+
const highlightText = (value: number) =>
|
|
1784
|
+
shareHighlight ? `${Math.round(value)}%` : `${stackTotals ? `${text.total} ` : ""}${axisFormatter(value)}`
|
|
1785
|
+
/** Whether `p`'s label sits within the target's value band and under the target label (at the right end). */
|
|
1786
|
+
const nearTargetLabel = (p: HighlightPoint, side: "under" | "over") => {
|
|
1787
|
+
if (!hasTarget || !plotWidth || kind === "bar" || labels.length < 2) return false
|
|
1788
|
+
if (side === "under" ? p.value > target : p.value <= target) return false
|
|
1789
|
+
const scale = Math.max(Math.abs(target), ...highlightPoints.map((h) => Math.abs(h.value)))
|
|
1790
|
+
if (scale === 0 || Math.abs(target - p.value) / scale > TARGET_NEAR_SHARE) return false
|
|
1791
|
+
const plot = Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - 32)
|
|
1792
|
+
const x = (p.index / (labels.length - 1)) * plot
|
|
1793
|
+
const w = estimateTextWidth(highlightText(p.value)) + 8
|
|
1794
|
+
const align = edgeAlign(p.index)?.align
|
|
1795
|
+
const left = align === "right" ? x - w - 6 : align === "left" ? x : x - w / 2
|
|
1796
|
+
return left < estimateTextWidth(targetText) + 8 + LABEL_SLACK
|
|
1797
|
+
}
|
|
1798
|
+
const hideTargetLabel =
|
|
1799
|
+
(kind === "line" && targetLabelPosition === "legend") ||
|
|
1800
|
+
!shareHighlight &&
|
|
1801
|
+
plotWidth !== undefined &&
|
|
1802
|
+
plotWidth < TARGET_LABEL_NARROW_WIDTH &&
|
|
1803
|
+
highlightPoints.some((p) => p.index === labels.length - 1 && (nearTargetLabel(p, "under") || nearTargetLabel(p, "over")))
|
|
1804
|
+
const below = (p: HighlightPoint) => !shareHighlight && !hideTargetLabel && nearTargetLabel(p, "under")
|
|
1805
|
+
const targetLabelBelow = !shareHighlight && !hideTargetLabel && highlightPoints.some((p) => nearTargetLabel(p, "over"))
|
|
1806
|
+
|
|
1807
|
+
// One series (or a stack, against its total) can be compared to a target; grouped series and 100% stacks cannot.
|
|
1808
|
+
const barTargets: (number | null)[] | null =
|
|
1809
|
+
perBarTarget && targetKey && !percent && (stacked || categories.length === 1) ? barTargetValues(data, targetKey) : null
|
|
1810
|
+
const barTargetName = targetLabel ?? text.target
|
|
1811
|
+
const barTargetColor = labelColor ?? guideColor
|
|
1812
|
+
|
|
1813
|
+
const markPointFor = (c: number, color: string | undefined) =>
|
|
1814
|
+
c === highlightSeries && highlightPoints.length > 0
|
|
1815
|
+
? {
|
|
1816
|
+
silent: true,
|
|
1817
|
+
symbol: "circle",
|
|
1818
|
+
symbolSize: kind === "bar" ? 0 : 7,
|
|
1819
|
+
itemStyle: { color, borderColor: "transparent" },
|
|
1820
|
+
label: {
|
|
1821
|
+
show: true,
|
|
1822
|
+
position: horizontalBars ? ("right" as const) : ("top" as const),
|
|
1823
|
+
distance: 6,
|
|
1824
|
+
fontSize: 12,
|
|
1825
|
+
fontWeight: 500,
|
|
1826
|
+
color: labelColor,
|
|
1827
|
+
...(labelBackground ? { backgroundColor: labelBackground, padding: [2, 4], borderRadius: 2 } : {}),
|
|
1828
|
+
formatter: (p: { value?: unknown }) => highlightText(Number(p.value)),
|
|
1829
|
+
},
|
|
1830
|
+
data: highlightPoints.map((p) => {
|
|
1831
|
+
// Below the point; on the forecast boundary, on the forecast side (the actual line comes in from the left).
|
|
1832
|
+
const label = shareHighlight
|
|
1833
|
+
? // Inside the bottom band, under its upper edge: the label reads as that band's share.
|
|
1834
|
+
{ ...edgeAlign(p.index), position: "bottom" as const }
|
|
1835
|
+
: below(p)
|
|
1836
|
+
? p.index === boundaryIndex && p.index !== last
|
|
1837
|
+
? { position: "bottom" as const, align: "left" as const, offset: [6, 0] }
|
|
1838
|
+
: { ...edgeAlign(p.index), position: "bottom" as const }
|
|
1839
|
+
: edgeAlign(p.index)
|
|
1840
|
+
return {
|
|
1841
|
+
name: p.kind,
|
|
1842
|
+
value: p.value,
|
|
1843
|
+
coord: horizontalBars ? [p.value, p.index] : [p.index, p.value],
|
|
1844
|
+
...(label ? { label } : {}),
|
|
1845
|
+
}
|
|
1846
|
+
}),
|
|
1847
|
+
}
|
|
1848
|
+
: undefined
|
|
1849
|
+
|
|
1850
|
+
// 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.
|
|
1851
|
+
const byValue = kind === "bar" && !stacked && Boolean(thresholds?.length)
|
|
1852
|
+
const multiSeries = categories.length > 1
|
|
1853
|
+
// Horizontal bars of one series read light; only the highlighted bar is solid (the one the page is about).
|
|
1854
|
+
const lightBars = kind === "bar" && horizontalBars && !stacked && !multiSeries
|
|
1855
|
+
const series: Record<string, unknown>[] = categories.map((category, c) => {
|
|
1856
|
+
const solid = palette[c] || undefined
|
|
1857
|
+
const color = lightBars && solid ? withAlpha(solid, LIGHT_BAR_ALPHA) : solid
|
|
1858
|
+
const dimSeries = active !== null && active.category !== category
|
|
1859
|
+
const seriesData = pad(values[c]!)
|
|
1860
|
+
if (kind === "bar") {
|
|
1861
|
+
const rounded = horizontalBars ? [0, 4, 4, 0] : [4, 4, 0, 0]
|
|
1862
|
+
// Stacked: only the topmost segment is rounded.
|
|
1863
|
+
const radius = stacked && c !== categories.length - 1 ? 0 : rounded
|
|
1864
|
+
return {
|
|
1865
|
+
id: SERIES_ID_PREFIX + category,
|
|
1866
|
+
type: "bar" as const,
|
|
1867
|
+
name: category,
|
|
1868
|
+
stack: stacked ? "total" : undefined,
|
|
1869
|
+
barCategoryGap,
|
|
1870
|
+
itemStyle: { color, borderRadius: radius },
|
|
1871
|
+
markPoint: markPointFor(c, solid),
|
|
1872
|
+
markLine: undefined,
|
|
1873
|
+
data: seriesData.map((value, i) => {
|
|
1874
|
+
const tone = byValue ? toneForValue(value, thresholds) : undefined
|
|
1875
|
+
const toneColor = tone ? toneColors?.[tone] || undefined : undefined
|
|
1876
|
+
const isHighlight = lightBars && cfg.barHighlight !== undefined && String(rawIndex[i]) === String(cfg.barHighlight)
|
|
1877
|
+
const dimmed = active !== null && !(active.category === category && active.index === i)
|
|
1878
|
+
// Provisional bars: lighter fill and a dashed edge, never the solid look of a confirmed bar.
|
|
1879
|
+
const provisional = provStart !== -1 && i >= provStart && i <= lastActual
|
|
1880
|
+
const zeroLabel =
|
|
1881
|
+
showZeroValues && !stacked && value === 0
|
|
1882
|
+
? {
|
|
1883
|
+
show: true,
|
|
1884
|
+
position: horizontalBars ? ("right" as const) : ("top" as const),
|
|
1885
|
+
distance: 4,
|
|
1886
|
+
fontSize: 12,
|
|
1887
|
+
color: labelColor,
|
|
1888
|
+
formatter: () => axisFormatter(0),
|
|
1889
|
+
}
|
|
1890
|
+
: undefined
|
|
1891
|
+
if (!dimmed && !toneColor && !isHighlight && !provisional && !zeroLabel) return value
|
|
1892
|
+
return {
|
|
1893
|
+
value,
|
|
1894
|
+
...(zeroLabel ? { label: zeroLabel } : {}),
|
|
1895
|
+
itemStyle: {
|
|
1896
|
+
...(isHighlight && solid ? { color: solid } : {}),
|
|
1897
|
+
...(toneColor ? { color: toneColor } : {}),
|
|
1898
|
+
// Several series: the series colour stays on the edge so the legend still points at the bar.
|
|
1899
|
+
...(toneColor && multiSeries && color && !provisional ? { borderColor: color, borderWidth: 2 } : {}),
|
|
1900
|
+
...(provisional ? { opacity: PROVISIONAL_OPACITY, borderColor: toneColor ?? color, borderWidth: 1, borderType: "dashed" as const } : {}),
|
|
1901
|
+
...(dimmed ? { opacity: DIMMED } : {}),
|
|
1902
|
+
},
|
|
1903
|
+
}
|
|
1904
|
+
}),
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
if (c === compIdx) {
|
|
1908
|
+
// The comparison: thin, muted, solid, no markers, no fill, never stacked — behind the main series.
|
|
1909
|
+
return {
|
|
1910
|
+
id: SERIES_ID_PREFIX + category,
|
|
1911
|
+
type: "line" as const,
|
|
1912
|
+
name: category,
|
|
1913
|
+
z: 1,
|
|
1914
|
+
smooth: curveType === "smooth",
|
|
1915
|
+
step: curveType === "step" ? ("middle" as const) : undefined,
|
|
1916
|
+
connectNulls,
|
|
1917
|
+
symbol: "none",
|
|
1918
|
+
showSymbol: false,
|
|
1919
|
+
lineStyle: { width: COMPARISON_LINE_WIDTH, type: "solid" as const, color: comparisonColor, opacity: dimSeries ? DIMMED : 1 },
|
|
1920
|
+
itemStyle: { color: comparisonColor, opacity: dimSeries ? DIMMED : 1 },
|
|
1921
|
+
areaStyle: undefined,
|
|
1922
|
+
markPoint: undefined,
|
|
1923
|
+
markLine: undefined,
|
|
1924
|
+
data: seriesData,
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
const areaStyle =
|
|
1928
|
+
kind !== "area" || fill === "none"
|
|
1929
|
+
? undefined
|
|
1930
|
+
: fill === "solid" || !color
|
|
1931
|
+
? { opacity: fill === "solid" ? 0.3 : 0.2 }
|
|
1932
|
+
: {
|
|
1933
|
+
color: {
|
|
1934
|
+
type: "linear" as const,
|
|
1935
|
+
x: 0,
|
|
1936
|
+
y: 0,
|
|
1937
|
+
x2: 0,
|
|
1938
|
+
y2: 1,
|
|
1939
|
+
colorStops: [
|
|
1940
|
+
{ offset: 0, color: withAlpha(color, 0.28) },
|
|
1941
|
+
{ offset: 1, color: withAlpha(color, 0) },
|
|
1942
|
+
],
|
|
1943
|
+
},
|
|
1944
|
+
}
|
|
1945
|
+
return {
|
|
1946
|
+
id: SERIES_ID_PREFIX + category,
|
|
1947
|
+
type: "line" as const,
|
|
1948
|
+
name: category,
|
|
1949
|
+
stack: stacked ? "total" : undefined,
|
|
1950
|
+
smooth: curveType === "smooth",
|
|
1951
|
+
step: curveType === "step" ? ("middle" as const) : undefined,
|
|
1952
|
+
connectNulls,
|
|
1953
|
+
symbol: "circle",
|
|
1954
|
+
symbolSize: 6,
|
|
1955
|
+
showSymbol: showDots || data.length === 1,
|
|
1956
|
+
// 100% stacked: the top band's upper edge is the 100% line, not a value — drawn, it reads as「this band = 100%」.
|
|
1957
|
+
lineStyle:
|
|
1958
|
+
percent && c === categories.length - 1
|
|
1959
|
+
? { width: 0, color, opacity: 0 }
|
|
1960
|
+
: { width: 2, color, opacity: dimSeries ? DIMMED : 1 },
|
|
1961
|
+
itemStyle: { color, opacity: dimSeries ? DIMMED : 1 },
|
|
1962
|
+
// Hovering a series fades the others (not for a stack, where the bands read together).
|
|
1963
|
+
emphasis: stacked ? undefined : { focus: "series" as const },
|
|
1964
|
+
areaStyle: areaStyle && dimSeries ? { ...areaStyle, opacity: DIMMED * 0.3 } : areaStyle,
|
|
1965
|
+
markPoint: markPointFor(c, color),
|
|
1966
|
+
markLine: undefined,
|
|
1967
|
+
data: provStart === -1 ? seriesData : splitProvisional(seriesData, provStart).confirmed,
|
|
1968
|
+
}
|
|
1969
|
+
})
|
|
1970
|
+
|
|
1971
|
+
/* -- provisional: a dashed, lighter continuation of every series from `provStart`, joined to the last confirmed point */
|
|
1972
|
+
if (kind !== "bar" && provStart !== -1) {
|
|
1973
|
+
categories.forEach((category, c) => {
|
|
1974
|
+
// The comparison is not provisional: it keeps its own line to the end.
|
|
1975
|
+
if (c === compIdx) return
|
|
1976
|
+
const color = palette[c] || undefined
|
|
1977
|
+
const dimSeries = active !== null && active.category !== category
|
|
1978
|
+
const solid = series[c] as { areaStyle?: { opacity?: number } }
|
|
1979
|
+
const opacity = (dimSeries ? DIMMED : 1) * PROVISIONAL_OPACITY
|
|
1980
|
+
series.push({
|
|
1981
|
+
id: PROVISIONAL_SERIES_PREFIX + category,
|
|
1982
|
+
type: "line" as const,
|
|
1983
|
+
name: provisionalLabel,
|
|
1984
|
+
// Its own stack: the joint point repeats the confirmed value and must not pile onto it.
|
|
1985
|
+
stack: stacked ? "provisional" : undefined,
|
|
1986
|
+
smooth: curveType === "smooth",
|
|
1987
|
+
step: curveType === "step" ? ("middle" as const) : undefined,
|
|
1988
|
+
connectNulls: false,
|
|
1989
|
+
symbol: "circle",
|
|
1990
|
+
symbolSize: 6,
|
|
1991
|
+
showSymbol: showDots || data.length === 1,
|
|
1992
|
+
lineStyle:
|
|
1993
|
+
percent && c === categories.length - 1
|
|
1994
|
+
? { width: 0, color, opacity: 0 }
|
|
1995
|
+
: { width: 2, type: "dashed" as const, color, opacity },
|
|
1996
|
+
itemStyle: { color, opacity },
|
|
1997
|
+
areaStyle: solid.areaStyle ? { ...solid.areaStyle, opacity: (solid.areaStyle.opacity ?? 1) * PROVISIONAL_OPACITY } : undefined,
|
|
1998
|
+
markPoint: undefined,
|
|
1999
|
+
markLine: undefined,
|
|
2000
|
+
data: splitProvisional(pad(values[c]!), provStart).provisional,
|
|
2001
|
+
})
|
|
2002
|
+
})
|
|
2003
|
+
}
|
|
2004
|
+
// A bar legend entry for the provisional style (an empty line series: it takes no bar slot).
|
|
2005
|
+
if (kind === "bar" && provStart !== -1) {
|
|
2006
|
+
series.push({
|
|
2007
|
+
id: PROVISIONAL_SERIES_PREFIX + "legend",
|
|
2008
|
+
type: "line" as const,
|
|
2009
|
+
name: provisionalLabel,
|
|
2010
|
+
silent: true,
|
|
2011
|
+
symbol: "none",
|
|
2012
|
+
showSymbol: false,
|
|
2013
|
+
tooltip: { show: false },
|
|
2014
|
+
legendHoverLink: false,
|
|
2015
|
+
lineStyle: { opacity: 0 },
|
|
2016
|
+
itemStyle: { color: palette[0] || undefined, opacity: PROVISIONAL_OPACITY },
|
|
2017
|
+
markPoint: undefined,
|
|
2018
|
+
markLine: undefined,
|
|
2019
|
+
data: [],
|
|
2020
|
+
})
|
|
2021
|
+
}
|
|
2022
|
+
|
|
2023
|
+
/* -- forecast: dashed continuation (+ optional band) of one series */
|
|
2024
|
+
const forecastLabel = forecast?.label ?? text.forecast
|
|
2025
|
+
const forecastBandAlpha = isDarkSurface(labelBackground) ? FORECAST_BAND_ALPHA_DARK : FORECAST_BAND_ALPHA_LIGHT
|
|
2026
|
+
const forecastValues: (number | null)[] = []
|
|
2027
|
+
if (forecast) {
|
|
2028
|
+
const category =
|
|
2029
|
+
forecast.category !== undefined && categories.includes(forecast.category) && forecast.category !== comparison?.category
|
|
2030
|
+
? forecast.category
|
|
2031
|
+
: categories[mainIdx[0] ?? 0]!
|
|
2032
|
+
const c = categories.indexOf(category)
|
|
2033
|
+
const color = palette[c] || undefined
|
|
2034
|
+
const actual = values[c]!
|
|
2035
|
+
let start = -1
|
|
2036
|
+
for (let i = actual.length - 1; i >= 0; i--) {
|
|
2037
|
+
if (actual[i] !== null) {
|
|
2038
|
+
start = i
|
|
2039
|
+
break
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
const line: (number | null)[] = Array<null>(labels.length).fill(null)
|
|
2043
|
+
const lower: (number | null)[] = Array<null>(labels.length).fill(null)
|
|
2044
|
+
const range: (number | null)[] = Array<null>(labels.length).fill(null)
|
|
2045
|
+
if (start !== -1) {
|
|
2046
|
+
line[start] = actual[start]!
|
|
2047
|
+
lower[start] = actual[start]!
|
|
2048
|
+
range[start] = 0
|
|
2049
|
+
}
|
|
2050
|
+
let hasBand = false
|
|
2051
|
+
forecast.data.forEach((row: ChartForecastRow, k) => {
|
|
2052
|
+
const at = forecastAt[k]!
|
|
2053
|
+
line[at] = cellNumber(row.value)
|
|
2054
|
+
const lo = cellNumber(row.lower)
|
|
2055
|
+
const hi = cellNumber(row.upper)
|
|
2056
|
+
if (lo !== null && hi !== null) {
|
|
2057
|
+
hasBand = true
|
|
2058
|
+
lower[at] = Math.min(lo, hi)
|
|
2059
|
+
range[at] = Math.abs(hi - lo)
|
|
2060
|
+
}
|
|
2061
|
+
})
|
|
2062
|
+
forecastValues.push(...line)
|
|
2063
|
+
const helper = {
|
|
2064
|
+
type: "line" as const,
|
|
2065
|
+
silent: true,
|
|
2066
|
+
symbol: "none",
|
|
2067
|
+
showSymbol: false,
|
|
2068
|
+
connectNulls: true,
|
|
2069
|
+
tooltip: { show: false },
|
|
2070
|
+
legendHoverLink: false,
|
|
2071
|
+
emphasis: { disabled: true },
|
|
2072
|
+
markPoint: undefined,
|
|
2073
|
+
markLine: undefined,
|
|
2074
|
+
}
|
|
2075
|
+
if (hasBand) {
|
|
2076
|
+
series.push(
|
|
2077
|
+
{
|
|
2078
|
+
...helper,
|
|
2079
|
+
id: FORECAST_BAND_BASE_ID,
|
|
2080
|
+
name: FORECAST_BAND_BASE_ID,
|
|
2081
|
+
stack: FORECAST_BAND_BASE_ID,
|
|
2082
|
+
lineStyle: { opacity: 0 },
|
|
2083
|
+
areaStyle: undefined,
|
|
2084
|
+
data: lower,
|
|
2085
|
+
},
|
|
2086
|
+
{
|
|
2087
|
+
...helper,
|
|
2088
|
+
id: FORECAST_BAND_RANGE_ID,
|
|
2089
|
+
name: FORECAST_BAND_RANGE_ID,
|
|
2090
|
+
stack: FORECAST_BAND_BASE_ID,
|
|
2091
|
+
lineStyle: { opacity: 0 },
|
|
2092
|
+
areaStyle: color ? { color: withAlpha(color, forecastBandAlpha), opacity: 1 } : { opacity: forecastBandAlpha },
|
|
2093
|
+
data: range,
|
|
2094
|
+
},
|
|
2095
|
+
)
|
|
2096
|
+
}
|
|
2097
|
+
series.push({
|
|
2098
|
+
...helper,
|
|
2099
|
+
id: FORECAST_SERIES_ID,
|
|
2100
|
+
name: forecastLabel,
|
|
2101
|
+
silent: false,
|
|
2102
|
+
tooltip: undefined,
|
|
2103
|
+
emphasis: undefined,
|
|
2104
|
+
smooth: curveType === "smooth",
|
|
2105
|
+
// Always dashed (2px, 6-4) and lighter — a forecast must never read as a measurement, nor as the 1px dotted target.
|
|
2106
|
+
lineStyle: { width: 2, type: FORECAST_LINE_DASH, color, opacity: 0.7 },
|
|
2107
|
+
itemStyle: { color, opacity: 0.7 },
|
|
2108
|
+
areaStyle: undefined,
|
|
2109
|
+
data: line,
|
|
2110
|
+
})
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2113
|
+
/* -- overlay: target line, forecast boundary, and the extent that keeps the target on the axis */
|
|
2114
|
+
/**
|
|
2115
|
+
* Horizontal bars: the target line is vertical and its label lies flat above the plot, centred
|
|
2116
|
+
* on the line — unless that would run past the plot's right (or left) edge, e.g. a target near
|
|
2117
|
+
* the axis max on a narrow chart; then it hangs to the line's left (right) instead. The axis max
|
|
2118
|
+
* is estimated from the data (ECharts rounds it up, which only moves the line left of the guess).
|
|
2119
|
+
*/
|
|
2120
|
+
const horizontalTargetAlign = ((): "left" | "center" | "right" => {
|
|
2121
|
+
if (!horizontalBars || !hasTarget) return "center"
|
|
2122
|
+
const totals = labels.map((_, i) =>
|
|
2123
|
+
stacked
|
|
2124
|
+
? values.reduce((sum, v) => sum + Math.max(0, v[i] ?? 0), 0)
|
|
2125
|
+
: Math.max(0, ...values.map((v) => v[i] ?? 0)),
|
|
2126
|
+
)
|
|
2127
|
+
const top = percent ? 100 : (maxValue ?? Math.max(target, ...totals))
|
|
2128
|
+
if (!(top > 0)) return "center"
|
|
2129
|
+
const ratio = Math.min(1, Math.max(0, target / top))
|
|
2130
|
+
const half = (estimateTextWidth(targetText) + 8) / 2
|
|
2131
|
+
if (!plotWidth) return ratio > 0.85 ? "right" : ratio < 0.15 ? "left" : "center"
|
|
2132
|
+
const right = highlightPoints.length > 0 ? 64 : 16
|
|
2133
|
+
const categoryColumn = showYAxis ? (yAxisWidth ?? Math.min(160, Math.max(0, ...labels.map(estimateTextWidth)))) + 8 : 0
|
|
2134
|
+
const plot = Math.max(1, plotWidth - categoryColumn - right - 4)
|
|
2135
|
+
const at = ratio * plot
|
|
2136
|
+
if (plot - at + right < half) return "right"
|
|
2137
|
+
if (at + categoryColumn < half) return "left"
|
|
2138
|
+
return "center"
|
|
2139
|
+
})()
|
|
2140
|
+
const markLines: unknown[] = []
|
|
2141
|
+
const markAreas: unknown[] = []
|
|
2142
|
+
if (hasTarget && target !== undefined) {
|
|
2143
|
+
markLines.push({
|
|
2144
|
+
name: "target",
|
|
2145
|
+
[horizontalBars ? "xAxis" : "yAxis"]: target,
|
|
2146
|
+
// 1px dotted — the forecast is 2px dashed, so the two never read as one line.
|
|
2147
|
+
lineStyle: { type: TARGET_LINE_DASH, width: 1, color: guideColor },
|
|
2148
|
+
label: {
|
|
2149
|
+
show: !hideTargetLabel,
|
|
2150
|
+
// The start (left) of the line, above it — under it when a highlight sits just above the target there.
|
|
2151
|
+
// Horizontal bars: the line is vertical, so the label goes flat above its top end, outside the plot (no rotation, clear of the bars).
|
|
2152
|
+
// The category axis is inverted there (first row on top), so the line runs top → bottom and its top end is the *start*.
|
|
2153
|
+
position: horizontalBars
|
|
2154
|
+
? "start"
|
|
2155
|
+
: kind === "line" && targetLabelPosition === "end"
|
|
2156
|
+
? "insideEndTop"
|
|
2157
|
+
: targetLabelBelow
|
|
2158
|
+
? "insideStartBottom"
|
|
2159
|
+
: "insideStartTop",
|
|
2160
|
+
...(horizontalBars ? { rotate: 0, align: horizontalTargetAlign, verticalAlign: "bottom" as const, distance: 4 } : {}),
|
|
2161
|
+
color: guideColor,
|
|
2162
|
+
formatter: targetText,
|
|
2163
|
+
},
|
|
2164
|
+
})
|
|
2165
|
+
}
|
|
2166
|
+
if (forecast) {
|
|
2167
|
+
const forecastSpan =
|
|
2168
|
+
plotWidth && labels.length > 1
|
|
2169
|
+
? (Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - LINE_RIGHT_MARGIN) / (labels.length - 1)) *
|
|
2170
|
+
(labels.length - 1 - lastActual) +
|
|
2171
|
+
LINE_RIGHT_MARGIN
|
|
2172
|
+
: null
|
|
2173
|
+
markLines.push({
|
|
2174
|
+
name: "forecast-boundary",
|
|
2175
|
+
xAxis: lastActual,
|
|
2176
|
+
lineStyle: { type: "dashed", width: 1, color: guideColor },
|
|
2177
|
+
// Flat (text-xs, muted), just above the plot's top edge at the top of the line (`grid.top` makes the room; the legend
|
|
2178
|
+
// sits above that): along the line at its foot it ran into the x axis labels on a narrow chart.
|
|
2179
|
+
label: {
|
|
2180
|
+
show: true,
|
|
2181
|
+
position: "end",
|
|
2182
|
+
rotate: 0,
|
|
2183
|
+
align: forecastLabelAlign(forecastSpan, forecastBoundaryText(forecastLabel)),
|
|
2184
|
+
verticalAlign: "bottom" as const,
|
|
2185
|
+
distance: 4,
|
|
2186
|
+
fontSize: 12,
|
|
2187
|
+
color: guideColor,
|
|
2188
|
+
formatter: forecastBoundaryText(forecastLabel),
|
|
2189
|
+
},
|
|
2190
|
+
})
|
|
2191
|
+
}
|
|
2192
|
+
/* -- annotations: a thin neutral line, or a faint band for a range, on the category axis (vertical layouts only) */
|
|
2193
|
+
const notes = horizontalBars ? [] : resolveAnnotations(cfg.annotations, rawIndex)
|
|
2194
|
+
const noteGap = plotWidth && labels.length > 1 ? plotWidth / (kind === "bar" ? labels.length : labels.length - 1) : null
|
|
2195
|
+
if (notes.length > 0) {
|
|
2196
|
+
const singles = notes.filter((n) => n.to === undefined)
|
|
2197
|
+
const ends = annotationLabelEnds(singles.map((n) => n.from), noteGap)
|
|
2198
|
+
const background = labelBackground ? { backgroundColor: labelBackground, padding: [1, 3], borderRadius: 2 } : {}
|
|
2199
|
+
singles.forEach((note, k) => {
|
|
2200
|
+
markLines.push({
|
|
2201
|
+
name: `annotation:${note.label}`,
|
|
2202
|
+
xAxis: note.from,
|
|
2203
|
+
lineStyle: { type: "solid", width: 1, color: guideColor },
|
|
2204
|
+
// Along the line, at the top (the legend sits above the plot) or at its foot when a neighbour is close.
|
|
2205
|
+
label: {
|
|
2206
|
+
show: true,
|
|
2207
|
+
position: ends[k] === "top" ? "insideEndTop" : "insideStartBottom",
|
|
2208
|
+
color: guideColor,
|
|
2209
|
+
...background,
|
|
2210
|
+
formatter: note.label,
|
|
2211
|
+
},
|
|
2212
|
+
})
|
|
2213
|
+
})
|
|
2214
|
+
const over = kind === "bar" ? 0.5 : 0
|
|
2215
|
+
for (const note of notes) {
|
|
2216
|
+
if (note.to === undefined) continue
|
|
2217
|
+
const widthPx = noteGap === null ? null : (note.to - note.from + (kind === "bar" ? 1 : 0)) * noteGap
|
|
2218
|
+
const fits = widthPx === null ? [...note.label].length <= 6 : estimateTextWidth(note.label) + 8 <= widthPx
|
|
2219
|
+
markAreas.push([
|
|
2220
|
+
{
|
|
2221
|
+
name: note.label,
|
|
2222
|
+
xAxis: note.from - over,
|
|
2223
|
+
itemStyle: { color: guideColor ? withAlpha(guideColor, 0.12) : undefined },
|
|
2224
|
+
// The band's foot (bars: just above the plot — inside, the text would run into the value label of a tall bar,
|
|
2225
|
+
// and `grid.top` makes the room); a band narrower than its text reads the text upright along the band instead.
|
|
2226
|
+
label: {
|
|
2227
|
+
show: true,
|
|
2228
|
+
position: kind === "bar" ? "top" : fits ? "insideBottom" : "inside",
|
|
2229
|
+
rotate: fits ? 0 : 90,
|
|
2230
|
+
color: guideColor,
|
|
2231
|
+
fontSize: 12,
|
|
2232
|
+
formatter: note.label,
|
|
2233
|
+
},
|
|
2234
|
+
},
|
|
2235
|
+
{ xAxis: note.to + over },
|
|
2236
|
+
])
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
// The target is a legend entry too (an empty line series carries the name): the line may lose its label on a narrow plot.
|
|
2240
|
+
if (hasTarget) {
|
|
2241
|
+
series.push({
|
|
2242
|
+
id: TARGET_LEGEND_SERIES_ID,
|
|
2243
|
+
type: "line" as const,
|
|
2244
|
+
name: targetText,
|
|
2245
|
+
silent: true,
|
|
2246
|
+
symbol: "none",
|
|
2247
|
+
showSymbol: false,
|
|
2248
|
+
tooltip: { show: false },
|
|
2249
|
+
legendHoverLink: false,
|
|
2250
|
+
emphasis: { disabled: true },
|
|
2251
|
+
lineStyle: { opacity: 0 },
|
|
2252
|
+
itemStyle: { color: guideColor },
|
|
2253
|
+
markPoint: undefined,
|
|
2254
|
+
markLine: undefined,
|
|
2255
|
+
data: [],
|
|
2256
|
+
})
|
|
2257
|
+
}
|
|
2258
|
+
if (markLines.length > 0 || markAreas.length > 0) {
|
|
2259
|
+
series.push({
|
|
2260
|
+
id: OVERLAY_SERIES_ID,
|
|
2261
|
+
name: OVERLAY_SERIES_ID,
|
|
2262
|
+
type: "line" as const,
|
|
2263
|
+
silent: true,
|
|
2264
|
+
symbol: "none",
|
|
2265
|
+
showSymbol: false,
|
|
2266
|
+
tooltip: { show: false },
|
|
2267
|
+
legendHoverLink: false,
|
|
2268
|
+
emphasis: { disabled: true },
|
|
2269
|
+
lineStyle: { opacity: 0 },
|
|
2270
|
+
itemStyle: { color: guideColor },
|
|
2271
|
+
// A single invisible point at the target, so the value axis always reaches it.
|
|
2272
|
+
data: labels.map((_, i) => (i === 0 && hasTarget && target !== undefined ? target : null)),
|
|
2273
|
+
markPoint: undefined,
|
|
2274
|
+
// `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,
|
|
2275
|
+
// where the line is then dropped). `z` keeps the guide lines above the series' own lines.
|
|
2276
|
+
markLine: markLines.length > 0 ? { silent: true, symbol: "none", animation: false, precision: 20, z: 6, data: markLines } : undefined,
|
|
2277
|
+
markArea: markAreas.length > 0 ? { silent: true, animation: false, data: markAreas } : undefined,
|
|
2278
|
+
})
|
|
2279
|
+
}
|
|
2280
|
+
/*
|
|
2281
|
+
* -- per-bar targets: a short marker across each bar at its target. A custom
|
|
2282
|
+
* series (the marker's length follows the bar's width, in px, whatever the chart's
|
|
2283
|
+
* size) whose data also keeps the value axis reaching the largest target. It is
|
|
2284
|
+
* the legend's entry too: the marker is named, with a tick as its icon.
|
|
2285
|
+
*/
|
|
2286
|
+
if (barTargets) {
|
|
2287
|
+
series.push({
|
|
2288
|
+
id: TARGET_MARKER_SERIES_ID,
|
|
2289
|
+
type: "custom" as const,
|
|
2290
|
+
name: barTargetName,
|
|
2291
|
+
silent: true,
|
|
2292
|
+
animation: false,
|
|
2293
|
+
z: 5,
|
|
2294
|
+
tooltip: { show: false },
|
|
2295
|
+
legendHoverLink: false,
|
|
2296
|
+
emphasis: { disabled: true },
|
|
2297
|
+
itemStyle: { color: barTargetColor },
|
|
2298
|
+
encode: { x: 0, y: 1 },
|
|
2299
|
+
data: barTargets.flatMap((value, i) => (value === null ? [] : [horizontalBars ? [value, i] : [i, value]])),
|
|
2300
|
+
renderItem: targetMarkerRenderer(horizontalBars, barCategoryGap, barTargetColor),
|
|
2301
|
+
})
|
|
2302
|
+
}
|
|
2303
|
+
|
|
2304
|
+
const categoryAxis = {
|
|
2305
|
+
id: horizontalBars ? "y" : "x",
|
|
2306
|
+
type: "category" as const,
|
|
2307
|
+
data: labels,
|
|
2308
|
+
show: horizontalBars ? showYAxis : showXAxis,
|
|
2309
|
+
boundaryGap: kind === "bar",
|
|
2310
|
+
inverse: horizontalBars,
|
|
2311
|
+
axisTick: { show: false },
|
|
2312
|
+
axisLabel: {
|
|
2313
|
+
hideOverlap: true,
|
|
2314
|
+
rotate: kind === "line" ? 0 : undefined,
|
|
2315
|
+
interval: shownLabel ?? ("auto" as const),
|
|
2316
|
+
formatter:
|
|
2317
|
+
timeLabels || nameLabels
|
|
2318
|
+
? (value: string, i: number) => {
|
|
2319
|
+
const time = timeLabels?.[i]
|
|
2320
|
+
if (time === "") return ""
|
|
2321
|
+
return hasLabel(nameLabels, value) ? labelOf(value, nameLabels) : (time ?? value)
|
|
2322
|
+
}
|
|
2323
|
+
: undefined,
|
|
2324
|
+
width: horizontalBars ? yAxisWidth : undefined,
|
|
2325
|
+
overflow: horizontalBars && yAxisWidth != null ? ("truncate" as const) : undefined,
|
|
2326
|
+
},
|
|
2327
|
+
name: horizontalBars ? yAxisLabel : xAxisLabel,
|
|
2328
|
+
nameLocation: "middle" as const,
|
|
2329
|
+
nameGap: horizontalBars ? (yAxisWidth ?? 48) + 8 : 28,
|
|
2330
|
+
}
|
|
2331
|
+
const fit = kind === "line" && (fitToData ?? autoMinValue)
|
|
2332
|
+
// A horizontal bar chart's value ticks run along the (narrow) width: as many as fit side by side.
|
|
2333
|
+
const valueSplitNumber = (() => {
|
|
2334
|
+
if (!horizontalBars || !plotWidth) return undefined
|
|
2335
|
+
const top = percent
|
|
2336
|
+
? 100
|
|
2337
|
+
: (maxValue ?? Math.max(0, ...(stacked ? stackTotalsOf(values) : values.flat()).map((v) => v ?? 0)))
|
|
2338
|
+
const categoryColumn = showYAxis ? (yAxisWidth ?? Math.min(160, Math.max(0, ...labels.map(estimateTextWidth)))) + 8 : 0
|
|
2339
|
+
const plot = plotWidth - categoryColumn - (highlightPoints.length > 0 ? 64 : 16) - 4
|
|
2340
|
+
const text = percent ? (v: number) => `${v}%` : (v: number) => axisFormatter(v)
|
|
2341
|
+
return valueAxisSplitNumber(plot, [text(0), text(top)])
|
|
2342
|
+
})()
|
|
2343
|
+
const limits = valueAxisLimits({ minValue, maxValue }, kind !== "line")
|
|
2344
|
+
// Vertical value axes carry 3 intervals on a short plot, else 4–5 (a horizontal bar chart's follows its width, above).
|
|
2345
|
+
const splitNumber = horizontalBars ? valueSplitNumber : valueAxisSplitCount(plotHeight)
|
|
2346
|
+
/*
|
|
2347
|
+
* Ticks read in one unit — the unit of the axis' largest tick (¥0.5億 / ¥1億, never ¥5,000万 beside ¥1億). The largest
|
|
2348
|
+
* tick is estimated from the data the way ECharts nices its ends.
|
|
2349
|
+
*/
|
|
2350
|
+
const tickFormatter = (() => {
|
|
2351
|
+
if (!cfg.axisTicks || percent) return axisFormatter
|
|
2352
|
+
const extentValues: number[] = []
|
|
2353
|
+
const addAll = (list: readonly (number | null)[]) => {
|
|
2354
|
+
for (const v of list) if (v !== null && Number.isFinite(v)) extentValues.push(v)
|
|
2355
|
+
}
|
|
2356
|
+
if (stackTotals) addAll(stackTotals)
|
|
2357
|
+
else values.forEach(addAll)
|
|
2358
|
+
addAll(forecastValues)
|
|
2359
|
+
if (forecast) addAll(forecast.data.flatMap((row) => [cellNumber(row.lower), cellNumber(row.upper)]))
|
|
2360
|
+
if (barTargets) addAll(barTargets)
|
|
2361
|
+
if (hasTarget && target !== undefined) extentValues.push(target)
|
|
2362
|
+
if (maxValue !== undefined && Number.isFinite(maxValue)) extentValues.push(maxValue)
|
|
2363
|
+
if (minValue !== undefined && Number.isFinite(minValue)) extentValues.push(minValue)
|
|
2364
|
+
if (extentValues.length === 0) return axisFormatter
|
|
2365
|
+
const zeroBased = kind !== "line" || !fit
|
|
2366
|
+
const hi = Math.max(...extentValues, zeroBased ? 0 : -Infinity)
|
|
2367
|
+
const lo = Math.min(...extentValues, zeroBased ? 0 : Infinity)
|
|
2368
|
+
return cfg.axisTicks(estimateAxisTop(lo, hi, splitNumber ?? 5, maxValue !== undefined && Number.isFinite(maxValue) ? maxValue : undefined))
|
|
2369
|
+
})()
|
|
2370
|
+
const valueAxis = {
|
|
2371
|
+
id: horizontalBars ? "x" : "y",
|
|
2372
|
+
type: "value" as const,
|
|
2373
|
+
show: horizontalBars ? showXAxis : showYAxis,
|
|
2374
|
+
// Bars and areas always start at 0 (a positive `minValue` can't lift them, a negative one makes room below);
|
|
2375
|
+
// lines do too unless asked to fit the data. A limit never cuts the data: the axis widens to it.
|
|
2376
|
+
min: percent ? 0 : kind === "line" ? (minValue === undefined ? (fit ? undefined : zeroBasedMin) : limits.min) : limits.min,
|
|
2377
|
+
max: percent ? 100 : limits.max,
|
|
2378
|
+
scale: fit && minValue == null,
|
|
2379
|
+
splitNumber,
|
|
2380
|
+
minInterval: allowDecimals ? undefined : 1,
|
|
2381
|
+
axisLine: { show: false },
|
|
2382
|
+
axisTick: { show: false },
|
|
2383
|
+
splitLine: { show: showGridLines },
|
|
2384
|
+
axisLabel: {
|
|
2385
|
+
formatter: percent ? (v: number) => `${v}%` : (v: number) => tickFormatter(v),
|
|
2386
|
+
// Fitted to the data: the lowest tick would print over the first x label at the bottom left. The gridline stays.
|
|
2387
|
+
showMinLabel: fit && minValue == null && !horizontalBars ? false : undefined,
|
|
2388
|
+
// Horizontal: ticks that would still touch on a narrow plot are dropped.
|
|
2389
|
+
hideOverlap: horizontalBars ? true : undefined,
|
|
2390
|
+
// A fixed width lines up side-by-side plots, but a value tick is never cut: the grid contains it.
|
|
2391
|
+
width: horizontalBars ? undefined : yAxisWidth,
|
|
2392
|
+
},
|
|
2393
|
+
name: horizontalBars ? xAxisLabel : yAxisLabel,
|
|
2394
|
+
nameLocation: "middle" as const,
|
|
2395
|
+
nameGap: horizontalBars ? 28 : (yAxisWidth ?? 48) + 8,
|
|
2396
|
+
}
|
|
2397
|
+
|
|
2398
|
+
const legendItems = [
|
|
2399
|
+
...categories,
|
|
2400
|
+
...(forecast ? [forecastLabel] : []),
|
|
2401
|
+
...(provStart !== -1 ? [provisionalLabel] : []),
|
|
2402
|
+
...(barTargets ? [barTargetName] : []),
|
|
2403
|
+
...(hasTarget ? [targetText] : []),
|
|
2404
|
+
]
|
|
2405
|
+
const option = {
|
|
2406
|
+
...chartMotion(reducedMotion),
|
|
2407
|
+
legend: {
|
|
2408
|
+
show: showLegend,
|
|
2409
|
+
top: 0,
|
|
2410
|
+
// Narrow: left-aligned and wrapping above the plot, so nothing is cut off at the right edge.
|
|
2411
|
+
...(plotWidth !== undefined && plotWidth < NARROW_PLOT_WIDTH
|
|
2412
|
+
? { left: 0, right: 0 }
|
|
2413
|
+
: { right: reserveActions ? ACTIONS_RESERVE : 0 }),
|
|
2414
|
+
// Plain wraps onto a second line at narrow widths instead of hiding items behind arrows.
|
|
2415
|
+
type: "plain",
|
|
2416
|
+
icon: "circle",
|
|
2417
|
+
itemWidth: 8,
|
|
2418
|
+
itemHeight: 8,
|
|
2419
|
+
itemGap: 16,
|
|
2420
|
+
// The target marker is a tick, not a dot.
|
|
2421
|
+
// The target is a row of dots and the forecast a row of dashes — their lines' patterns — and a per-bar target a tick.
|
|
2422
|
+
data: legendItems.map((name) =>
|
|
2423
|
+
barTargets && name === barTargetName
|
|
2424
|
+
? { name, icon: TARGET_LEGEND_ICON }
|
|
2425
|
+
: forecast && name === forecastLabel
|
|
2426
|
+
? { name, icon: FORECAST_DASHED_ICON }
|
|
2427
|
+
: hasTarget && name === targetText
|
|
2428
|
+
? { name, icon: TARGET_DOTTED_ICON }
|
|
2429
|
+
: name,
|
|
2430
|
+
),
|
|
2431
|
+
formatter: nameLabels ? (name: string) => labelOf(name, nameLabels) : undefined,
|
|
2432
|
+
},
|
|
2433
|
+
grid: {
|
|
2434
|
+
top:
|
|
2435
|
+
(showLegend ? 12 + LEGEND_LINE_HEIGHT * legendLines(legendItems, plotWidth, reserveActions ? ACTIONS_RESERVE : 0) : 12) +
|
|
2436
|
+
// The flat target label of a horizontal bar chart sits above the plot.
|
|
2437
|
+
(horizontalBars && hasTarget ? 18 : 0) +
|
|
2438
|
+
// The label of a band over bars sits above the plot's top edge.
|
|
2439
|
+
(kind === "bar" && notes.some((n) => n.to !== undefined) ? BAND_LABEL_ROOM : 0) +
|
|
2440
|
+
// The boundary label of a forecast sits above the plot's top edge too.
|
|
2441
|
+
(forecast ? FORECAST_LABEL_ROOM : 0),
|
|
2442
|
+
// Lines start and end on the outermost ticks, so the last x label (and an edge
|
|
2443
|
+
// highlight) hangs past the plot; a horizontal bar's highlight sits past its end.
|
|
2444
|
+
right: horizontalBars ? (highlightPoints.length > 0 ? 64 : 16) : kind === "bar" ? 16 : LINE_RIGHT_MARGIN,
|
|
2445
|
+
bottom: xAxisLabel ? 24 : 4,
|
|
2446
|
+
left: yAxisLabel ? 24 : 4,
|
|
2447
|
+
containLabel: true,
|
|
2448
|
+
},
|
|
2449
|
+
tooltip: {
|
|
2450
|
+
show: showTooltip,
|
|
2451
|
+
trigger: "axis",
|
|
2452
|
+
axisPointer: { type: kind === "bar" ? "shadow" : "line" },
|
|
2453
|
+
formatter: (params: unknown) => {
|
|
2454
|
+
const list = (Array.isArray(params) ? params : [params]) as AxisTooltipParam[]
|
|
2455
|
+
const i = list[0]?.dataIndex ?? 0
|
|
2456
|
+
const row = i <= lastActual ? (data[i] ?? {}) : {}
|
|
2457
|
+
const rows: TooltipRow[] = []
|
|
2458
|
+
// The main series' difference from the comparison: one muted line under its row.
|
|
2459
|
+
const primary = mainIdx[0]
|
|
2460
|
+
const noteFor = (at: number): { note?: string } => {
|
|
2461
|
+
if (!comparison || compIdx === -1 || at !== primary || i > lastActual) return {}
|
|
2462
|
+
return {
|
|
2463
|
+
note: comparisonNote(
|
|
2464
|
+
cellNumber(row[categories[at]!]),
|
|
2465
|
+
cellNumber(row[comparison.category]),
|
|
2466
|
+
comparison,
|
|
2467
|
+
compGrain,
|
|
2468
|
+
cfg.comparisonFormat,
|
|
2469
|
+
locale,
|
|
2470
|
+
),
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
const shares = percent ? cartesianSeriesValues(i <= lastActual ? [row] : [], categories, "percent") : null
|
|
2474
|
+
// Rows follow the legend order (categories first), not ECharts' own series order.
|
|
2475
|
+
const legendRank = (p: AxisTooltipParam) => {
|
|
2476
|
+
const at = categories.indexOf(p.seriesName ?? "")
|
|
2477
|
+
return at === -1 ? categories.length : at
|
|
2478
|
+
}
|
|
2479
|
+
for (const p of [...list].sort((a, b) => legendRank(a) - legendRank(b))) {
|
|
2480
|
+
const color = typeof p.color === "string" ? p.color : "currentColor"
|
|
2481
|
+
if (p.seriesId === FORECAST_SERIES_ID) {
|
|
2482
|
+
// At and before the boundary the forecast repeats the actual value.
|
|
2483
|
+
if (i > lastActual) rows.push({ name: p.seriesName ?? forecastLabel, color, value: forecastValues[i] ?? null })
|
|
2484
|
+
continue
|
|
2485
|
+
}
|
|
2486
|
+
if (p.seriesId?.startsWith("__")) continue
|
|
2487
|
+
if (i > lastActual) continue
|
|
2488
|
+
const name = p.seriesName ?? ""
|
|
2489
|
+
const at = categories.indexOf(name)
|
|
2490
|
+
const share = shares && at !== -1 ? (shares[at]![0] ?? undefined) : undefined
|
|
2491
|
+
rows.push({
|
|
2492
|
+
name: labelOf(name, nameLabels),
|
|
2493
|
+
color: at === compIdx ? (comparisonColor ?? color) : color,
|
|
2494
|
+
value: cellNumber(row[name]),
|
|
2495
|
+
...(share !== undefined ? { share } : {}),
|
|
2496
|
+
...(at !== -1 ? noteFor(at) : {}),
|
|
2497
|
+
})
|
|
2498
|
+
}
|
|
2499
|
+
if (stackTotals && i <= lastActual && rows.length > 1) {
|
|
2500
|
+
rows.push({ name: text.total, color: "transparent", value: stackTotals[i] ?? null })
|
|
2501
|
+
}
|
|
2502
|
+
const provisional = provStart !== -1 && i >= provStart && i <= lastActual
|
|
2503
|
+
if (provisional) {
|
|
2504
|
+
// The confirmed series are empty here: rows come from the data, under a 「速報」 title.
|
|
2505
|
+
rows.length = 0
|
|
2506
|
+
categories.forEach((name, at) => {
|
|
2507
|
+
const share = shares ? (shares[at]![0] ?? undefined) : undefined
|
|
2508
|
+
rows.push({
|
|
2509
|
+
name,
|
|
2510
|
+
color: at === compIdx ? (comparisonColor ?? "currentColor") : palette[at] || "currentColor",
|
|
2511
|
+
value: cellNumber(row[name]),
|
|
2512
|
+
...(share !== undefined ? { share } : {}),
|
|
2513
|
+
...noteFor(at),
|
|
2514
|
+
})
|
|
2515
|
+
})
|
|
2516
|
+
if (stackTotals && rows.length > 1) rows.push({ name: text.total, color: "transparent", value: stackTotals[i] ?? null })
|
|
2517
|
+
}
|
|
2518
|
+
const title = tooltipTitles[i] ?? labels[i] ?? ""
|
|
2519
|
+
const lines: string[] = []
|
|
2520
|
+
if (barTargets && i <= lastActual) {
|
|
2521
|
+
const total = stackTotals ? (stackTotals[i] ?? null) : (values[0]?.[i] ?? null)
|
|
2522
|
+
const note = barTargetNote(barTargetName, total, barTargets[i] ?? null, valueFormatter, locale)
|
|
2523
|
+
if (note) lines.push(note)
|
|
2524
|
+
}
|
|
2525
|
+
for (const note of notes) {
|
|
2526
|
+
if (note.to === undefined ? note.from === i : note.from <= i && i <= note.to) lines.push(note.label)
|
|
2527
|
+
}
|
|
2528
|
+
return tooltipHtml(provisional ? text.provisionalTitle(title, provisionalLabel) : title, rows, valueFormatter, lines, locale)
|
|
2529
|
+
},
|
|
2530
|
+
},
|
|
2531
|
+
xAxis: horizontalBars ? valueAxis : categoryAxis,
|
|
2532
|
+
yAxis: horizontalBars ? categoryAxis : valueAxis,
|
|
2533
|
+
series,
|
|
2534
|
+
}
|
|
2535
|
+
return mergeChartOptions(option as EChartsOption, chartOptions)
|
|
2536
|
+
}
|
|
2537
|
+
|
|
2538
|
+
/* ------------------------------------------------------------------ donut */
|
|
2539
|
+
|
|
2540
|
+
type DonutVariant = "donut" | "pie"
|
|
2541
|
+
|
|
2542
|
+
/** What the donut prints in its hole (`donutOptions.centerLabel`). */
|
|
2543
|
+
type DonutCenterLabel = "none" | "total" | "top"
|
|
2544
|
+
|
|
2545
|
+
/**
|
|
2546
|
+
* The center of the donut as one of the three built-ins or a custom node.
|
|
2547
|
+
* Default `"none"`; the legacy `showLabel` (`false` → none, an explicit `true` →
|
|
2548
|
+
* total, the old default) and `label` (a custom node) still win over the default.
|
|
2549
|
+
*/
|
|
2550
|
+
function resolveDonutCenter(
|
|
2551
|
+
centerLabel: DonutChartOptions["centerLabel"],
|
|
2552
|
+
{ showLabel, label }: { showLabel?: boolean; label?: ReactNode } = {},
|
|
2553
|
+
): { kind: DonutCenterLabel } | { kind: "custom"; node: ReactNode } {
|
|
2554
|
+
if (showLabel === false) return { kind: "none" }
|
|
2555
|
+
if (centerLabel === "none") return { kind: "none" }
|
|
2556
|
+
if (centerLabel === "total") return { kind: "total" }
|
|
2557
|
+
if (centerLabel === "top") return { kind: "top" }
|
|
2558
|
+
if (centerLabel !== undefined && centerLabel !== null && centerLabel !== false) return { kind: "custom", node: centerLabel }
|
|
2559
|
+
if (label !== undefined && label !== null && label !== false) return { kind: "custom", node: label }
|
|
2560
|
+
return { kind: showLabel === true ? "total" : "none" }
|
|
2561
|
+
}
|
|
2562
|
+
|
|
2563
|
+
/** Below this plot width (px) the outside labels can't fit beside the ring. */
|
|
2564
|
+
const DONUT_OUTSIDE_LABEL_MIN_WIDTH = 440
|
|
2565
|
+
|
|
2566
|
+
/**
|
|
2567
|
+
* How many slices get an outside label. A share is printed once: the legend
|
|
2568
|
+
* carries every slice's share, so with a legend there are no outside labels;
|
|
2569
|
+
* without one the 2 largest are labelled when the plot is wide enough
|
|
2570
|
+
* (`plotWidth` `null` = not measured yet → labelled).
|
|
2571
|
+
*/
|
|
2572
|
+
function donutOutsideLabelCount(plotWidth: number | null, showLegend: boolean): number {
|
|
2573
|
+
if (showLegend) return 0
|
|
2574
|
+
return plotWidth !== null && plotWidth < DONUT_OUTSIDE_LABEL_MIN_WIDTH ? 0 : DONUT_OUTSIDE_LABELS
|
|
2575
|
+
}
|
|
2576
|
+
|
|
2577
|
+
/** The `"top"` center: the largest real slice's name (`label`) and share (`amount`); `null` when there is none. */
|
|
2578
|
+
function donutTopText(
|
|
2579
|
+
slices: readonly DonutOptionSlice[],
|
|
2580
|
+
labels?: Readonly<Record<string, string>>,
|
|
2581
|
+
): { label: string; amount: string } | null {
|
|
2582
|
+
const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
|
|
2583
|
+
const top = [...slices].filter((s) => !s.isOther && sliceValue(s.value) > 0).sort((a, b) => sliceValue(b.value) - sliceValue(a.value))[0]
|
|
2584
|
+
return top ? { label: labelOf(top.name, labels), amount: donutShareText(top.value, total) } : null
|
|
2585
|
+
}
|
|
2586
|
+
|
|
2587
|
+
/** DonutChart-only settings. */
|
|
2588
|
+
interface DonutChartOptions {
|
|
2589
|
+
/** `"donut"`(中央に穴とラベル)か `"pie"`。既定 `"donut"`。 */
|
|
2590
|
+
variant?: DonutVariant
|
|
2591
|
+
/** @deprecated `centerLabel` を使う。`false` は `centerLabel: "none"` と同じ。`true` を明示すると `"total"` 扱い(以前の既定)。 */
|
|
2592
|
+
showLabel?: boolean
|
|
2593
|
+
/**
|
|
2594
|
+
* 穴の中央に出すもの。`"none"`(既定。何も出さない。合計は KPI と重複しがち)/ `"total"`(「合計」と
|
|
2595
|
+
* 合計を書式化した値。`totalLabel` / `unit` を添える)/ `"top"`(最大の切片の名前と構成比)。
|
|
2596
|
+
* それ以外のノードを渡すとそのまま中央に置く。donut のみ。
|
|
2597
|
+
*/
|
|
2598
|
+
centerLabel?: DonutCenterLabel | ReactNode
|
|
2599
|
+
/** 中央ラベルの見出し(何の合計か)。既定「合計」。 */
|
|
2600
|
+
totalLabel?: string
|
|
2601
|
+
/** 中央ラベルの合計に添える単位(`"セッション"` → 「9.2万 セッション」)。 */
|
|
2602
|
+
unit?: string
|
|
2603
|
+
/** 凡例(名前と構成比、大きい順)を出す。広いときは右、狭いときは下。既定 `true`。構成比は凡例だけが持つ(凡例を消すと、広いときだけ大きい 2 切片に外ラベルで名前と構成比が出る)。 */
|
|
2604
|
+
showLegend?: boolean
|
|
2605
|
+
/** 個別に描く切片の数。超えた分は大きさ順の残りを「その他」1 切片にまとめる。既定 5。 */
|
|
2606
|
+
maxSlices?: number
|
|
2607
|
+
}
|
|
2608
|
+
|
|
2609
|
+
/** A slice as the builder takes it: already sorted, folded and coloured (see `donutSlices`). */
|
|
2610
|
+
interface DonutOptionSlice {
|
|
2611
|
+
name: string
|
|
2612
|
+
value: number
|
|
2613
|
+
/** The folded「その他」slice: never labelled outside. */
|
|
2614
|
+
isOther?: boolean
|
|
2615
|
+
}
|
|
2616
|
+
|
|
2617
|
+
/** How many of the largest slices get an outside label (「自然検索 41%」) by default. */
|
|
2618
|
+
const DONUT_OUTSIDE_LABELS = 2
|
|
2619
|
+
|
|
2620
|
+
const sliceValue = (value: number) => (Number.isFinite(value) && value > 0 ? value : 0)
|
|
2621
|
+
|
|
2622
|
+
/** A slice's share of `total` as text: whole percent, `<1%` for a sliver, `0%` for nothing. */
|
|
2623
|
+
function donutShareText(value: number, total: number): string {
|
|
2624
|
+
const v = sliceValue(value)
|
|
2625
|
+
if (total <= 0 || v === 0) return "0%"
|
|
2626
|
+
const pct = (v / total) * 100
|
|
2627
|
+
return pct < 1 ? "<1%" : `${Math.round(pct)}%`
|
|
2628
|
+
}
|
|
2629
|
+
|
|
2630
|
+
/** One legend row: name, share text and the slice's position (for its colour). */
|
|
2631
|
+
interface DonutLegendItem {
|
|
2632
|
+
name: string
|
|
2633
|
+
value: number
|
|
2634
|
+
share: string
|
|
2635
|
+
isOther: boolean
|
|
2636
|
+
/** Index into the slices / palette. */
|
|
2637
|
+
slice: number
|
|
2638
|
+
}
|
|
2639
|
+
|
|
2640
|
+
/**
|
|
2641
|
+
* The donut legend: every slice with its share, largest first, the folded
|
|
2642
|
+
* 「その他」 last (it is a remainder, not a rank).
|
|
2643
|
+
*/
|
|
2644
|
+
function donutLegendItems(slices: readonly DonutOptionSlice[]): DonutLegendItem[] {
|
|
2645
|
+
const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
|
|
2646
|
+
return slices
|
|
2647
|
+
.map((s, slice) => ({ name: s.name, value: sliceValue(s.value), share: donutShareText(s.value, total), isOther: Boolean(s.isOther), slice }))
|
|
2648
|
+
.sort((a, b) => Number(a.isOther) - Number(b.isOther) || b.value - a.value || a.slice - b.slice)
|
|
2649
|
+
}
|
|
2650
|
+
|
|
2651
|
+
/**
|
|
2652
|
+
* The default center label: what is totalled (「合計」 / "Total" in `locale`, default the page's), the formatted total
|
|
2653
|
+
* (`amount`, the big line), the unit (a small line under it) and both as one
|
|
2654
|
+
* string (`value`, 「9.2万 セッション」).
|
|
2655
|
+
*/
|
|
2656
|
+
function donutCenterText(
|
|
2657
|
+
total: number,
|
|
2658
|
+
valueFormatter: (value: number) => string,
|
|
2659
|
+
{ totalLabel, unit, locale }: { totalLabel?: string; unit?: string; locale?: string } = {},
|
|
2660
|
+
): { label: string; value: string; amount: string; unit?: string } {
|
|
2661
|
+
totalLabel ??= chartText(locale).total
|
|
2662
|
+
const amount = valueFormatter(total)
|
|
2663
|
+
return { label: totalLabel, value: unit ? `${amount} ${unit}` : amount, amount, ...(unit ? { unit } : {}) }
|
|
2664
|
+
}
|
|
2665
|
+
|
|
2666
|
+
/** The ring's inner radius, in percent of the plot's shorter side / 2 — with and without outside labels. */
|
|
2667
|
+
const DONUT_INNER_WITH_LABELS = 50
|
|
2668
|
+
const DONUT_INNER_PLAIN = 72
|
|
2669
|
+
|
|
2670
|
+
/**
|
|
2671
|
+
* The hole's diameter as a fraction of the plot's shorter side (ECharts reads a
|
|
2672
|
+
* `%` radius against half of it), so an HTML center label can be sized to fit.
|
|
2673
|
+
*/
|
|
2674
|
+
function donutHoleRatio(withOutsideLabels: boolean): number {
|
|
2675
|
+
return (withOutsideLabels ? DONUT_INNER_WITH_LABELS : DONUT_INNER_PLAIN) / 100
|
|
2676
|
+
}
|
|
2677
|
+
|
|
2678
|
+
interface DonutChartConfig {
|
|
2679
|
+
/** Slices in draw order (largest first, 「その他」 last). */
|
|
2680
|
+
slices: readonly DonutOptionSlice[]
|
|
2681
|
+
/** Resolved slice colours, by slice position. `""`/missing → theme palette. */
|
|
2682
|
+
palette: readonly string[]
|
|
2683
|
+
/** Display names for slice names (tooltip, outside labels). Missing keys show as they are. */
|
|
2684
|
+
labels?: Readonly<Record<string, string>>
|
|
2685
|
+
valueFormatter: (value: number) => string
|
|
2686
|
+
/** The value column's name, shown in the tooltip row. */
|
|
2687
|
+
valueName?: string
|
|
2688
|
+
variant?: DonutVariant
|
|
2689
|
+
showTooltip?: boolean
|
|
2690
|
+
/** How many of the largest (non-「その他」) slices get an outside label. Default `DONUT_OUTSIDE_LABELS` (2); 0 = none. */
|
|
2691
|
+
outsideLabels?: number
|
|
2692
|
+
/** Name of the selected slice; the others are dimmed. */
|
|
2693
|
+
active?: string | null
|
|
2694
|
+
/** Colour of the outside labels (resolved foreground). Default: the theme's text colour. */
|
|
2695
|
+
labelColor?: string
|
|
2696
|
+
reducedMotion?: boolean
|
|
2697
|
+
/** Deep-merged onto the generated option last. */
|
|
2698
|
+
chartOptions?: EChartsOption
|
|
2699
|
+
}
|
|
2700
|
+
|
|
2701
|
+
/** Sum of the `value` column, ignoring gaps and negative cells. */
|
|
2702
|
+
function donutTotal(data: readonly Record<string, unknown>[], value: string): number {
|
|
2703
|
+
return data.reduce((sum, row) => {
|
|
2704
|
+
const n = cellNumber(row[value])
|
|
2705
|
+
return n !== null && n > 0 ? sum + n : sum
|
|
2706
|
+
}, 0)
|
|
2707
|
+
}
|
|
2708
|
+
|
|
2709
|
+
interface ItemTooltipParam {
|
|
2710
|
+
name?: string
|
|
2711
|
+
value?: unknown
|
|
2712
|
+
percent?: number
|
|
2713
|
+
color?: unknown
|
|
2714
|
+
}
|
|
2715
|
+
|
|
2716
|
+
/**
|
|
2717
|
+
* The donut / pie option. Only the `outsideLabels` largest slices carry an
|
|
2718
|
+
* outside label (name + share); the legend, center label and tooltip carry the
|
|
2719
|
+
* rest. No entrance animation, a short ease on updates.
|
|
2720
|
+
*/
|
|
2721
|
+
function buildDonutOption(cfg: DonutChartConfig): EChartsOption {
|
|
2722
|
+
const {
|
|
2723
|
+
slices,
|
|
2724
|
+
palette,
|
|
2725
|
+
labels: nameLabels,
|
|
2726
|
+
valueFormatter,
|
|
2727
|
+
valueName = "",
|
|
2728
|
+
variant = "donut",
|
|
2729
|
+
showTooltip = true,
|
|
2730
|
+
outsideLabels = DONUT_OUTSIDE_LABELS,
|
|
2731
|
+
active = null,
|
|
2732
|
+
labelColor,
|
|
2733
|
+
reducedMotion = false,
|
|
2734
|
+
chartOptions,
|
|
2735
|
+
} = cfg
|
|
2736
|
+
const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
|
|
2737
|
+
// The largest real slices, by value (the slices arrive sorted, but don't rely on it).
|
|
2738
|
+
const labelled = new Set(
|
|
2739
|
+
slices
|
|
2740
|
+
.map((s, i) => ({ i, v: sliceValue(s.value), other: Boolean(s.isOther) }))
|
|
2741
|
+
.filter((s) => !s.other && s.v > 0)
|
|
2742
|
+
.sort((a, b) => b.v - a.v || a.i - b.i)
|
|
2743
|
+
.slice(0, Math.max(0, outsideLabels))
|
|
2744
|
+
.map((s) => s.i),
|
|
2745
|
+
)
|
|
2746
|
+
const withLabels = labelled.size > 0
|
|
2747
|
+
// Room for the outside labels: the ring shrinks inside the plot.
|
|
2748
|
+
const outer = withLabels ? "70%" : "100%"
|
|
2749
|
+
const option = {
|
|
2750
|
+
...chartMotion(reducedMotion),
|
|
2751
|
+
tooltip: {
|
|
2752
|
+
show: showTooltip,
|
|
2753
|
+
trigger: "item",
|
|
2754
|
+
formatter: (params: unknown) => {
|
|
2755
|
+
const p = params as ItemTooltipParam
|
|
2756
|
+
const n = cellNumber(p.value)
|
|
2757
|
+
const share = typeof p.percent === "number" ? ` (${p.percent.toFixed(1)}%)` : ""
|
|
2758
|
+
return tooltipHtml(
|
|
2759
|
+
`${labelOf(p.name ?? "", nameLabels)}${share}`,
|
|
2760
|
+
[{ name: valueName, color: typeof p.color === "string" ? p.color : "currentColor", value: n }],
|
|
2761
|
+
valueFormatter,
|
|
2762
|
+
)
|
|
2763
|
+
},
|
|
2764
|
+
},
|
|
2765
|
+
series: [
|
|
2766
|
+
{
|
|
2767
|
+
id: "slices",
|
|
2768
|
+
type: "pie",
|
|
2769
|
+
radius: variant === "donut" ? [`${donutHoleRatio(withLabels) * 100}%`, outer] : [0, outer],
|
|
2770
|
+
center: ["50%", "50%"],
|
|
2771
|
+
avoidLabelOverlap: true,
|
|
2772
|
+
// Plain text: no outline / shadow, which reads as a halo on a dark surface.
|
|
2773
|
+
label: {
|
|
2774
|
+
show: false,
|
|
2775
|
+
position: "outside",
|
|
2776
|
+
color: labelColor,
|
|
2777
|
+
textBorderWidth: 0,
|
|
2778
|
+
textBorderColor: "transparent",
|
|
2779
|
+
textShadowBlur: 0,
|
|
2780
|
+
textShadowColor: "transparent",
|
|
2781
|
+
},
|
|
2782
|
+
labelLine: { show: false, length: 8, length2: 8 },
|
|
2783
|
+
// A hairline gap between slices instead of a border — no background colour to match.
|
|
2784
|
+
padAngle: slices.length > 1 ? 1 : 0,
|
|
2785
|
+
itemStyle: { borderRadius: variant === "donut" ? 2 : 0 },
|
|
2786
|
+
emphasis: { scale: true, scaleSize: 4 },
|
|
2787
|
+
data: slices.map((slice, i) => ({
|
|
2788
|
+
name: slice.name,
|
|
2789
|
+
value: sliceValue(slice.value),
|
|
2790
|
+
itemStyle: { color: palette[i] || undefined, opacity: active !== null && active !== slice.name ? DIMMED : 1 },
|
|
2791
|
+
...(labelled.has(i)
|
|
2792
|
+
? {
|
|
2793
|
+
label: { show: true, formatter: () => `${labelOf(slice.name, nameLabels)} ${donutShareText(slice.value, total)}` },
|
|
2794
|
+
labelLine: { show: true },
|
|
2795
|
+
}
|
|
2796
|
+
: {}),
|
|
2797
|
+
})),
|
|
2798
|
+
},
|
|
2799
|
+
],
|
|
2800
|
+
}
|
|
2801
|
+
return mergeChartOptions(option as EChartsOption, chartOptions)
|
|
2802
|
+
}
|
|
2803
|
+
|
|
2804
|
+
/* -------------------------------------------------------------- selection */
|
|
2805
|
+
|
|
2806
|
+
/** Toggle: clicking the active point again clears the selection. */
|
|
2807
|
+
function nextChartSelection(
|
|
2808
|
+
current: ChartActivePoint | null,
|
|
2809
|
+
category: string,
|
|
2810
|
+
index: number,
|
|
2811
|
+
): ChartActivePoint | null {
|
|
2812
|
+
return current && current.category === category && current.index === index ? null : { category, index }
|
|
2813
|
+
}
|
|
2814
|
+
|
|
2815
|
+
/** What `onValueChange` receives: the clicked row plus what was clicked (ours win over row keys). */
|
|
2816
|
+
function chartSelectionPayload(
|
|
2817
|
+
selection: ChartActivePoint | null,
|
|
2818
|
+
data: readonly Record<string, unknown>[],
|
|
2819
|
+
eventType: NonNullable<ChartEventPayload>["eventType"],
|
|
2820
|
+
): ChartEventPayload {
|
|
2821
|
+
if (!selection) return null
|
|
2822
|
+
return { ...data[selection.index], eventType, categoryClicked: selection.category }
|
|
2823
|
+
}
|
|
2824
|
+
|
|
2825
|
+
interface ChartClickParams {
|
|
2826
|
+
componentType?: string
|
|
2827
|
+
seriesName?: string
|
|
2828
|
+
name?: string
|
|
2829
|
+
dataIndex?: number
|
|
2830
|
+
}
|
|
2831
|
+
|
|
2832
|
+
/**
|
|
2833
|
+
* Click-to-select for the typed charts: the `onEvents` to hand `EChart`, and
|
|
2834
|
+
* the active point to dim the rest with. Inert (no handler, nothing active)
|
|
2835
|
+
* without `onValueChange`.
|
|
2836
|
+
*/
|
|
2837
|
+
function useChartSelection(
|
|
2838
|
+
data: readonly Record<string, unknown>[],
|
|
2839
|
+
onValueChange: ((value: ChartEventPayload) => void) | undefined,
|
|
2840
|
+
eventType: NonNullable<ChartEventPayload>["eventType"],
|
|
2841
|
+
): { active: ChartActivePoint | null; onEvents: Record<string, (params: unknown) => void> | undefined } {
|
|
2842
|
+
const [active, setActive] = useState<ChartActivePoint | null>(null)
|
|
2843
|
+
// Handlers read the latest props without re-subscribing on every render.
|
|
2844
|
+
const latest = useRef({ data, onValueChange, active })
|
|
2845
|
+
latest.current = { data, onValueChange, active }
|
|
2846
|
+
const interactive = onValueChange !== undefined
|
|
2847
|
+
const onEvents = useMemo(() => {
|
|
2848
|
+
if (!interactive) return undefined
|
|
2849
|
+
return {
|
|
2850
|
+
click: (raw: unknown) => {
|
|
2851
|
+
const p = raw as ChartClickParams
|
|
2852
|
+
if (p.componentType !== "series" || typeof p.dataIndex !== "number") return
|
|
2853
|
+
const category = eventType === "slice" ? (p.name ?? "") : (p.seriesName ?? "")
|
|
2854
|
+
const next = nextChartSelection(latest.current.active, category, p.dataIndex)
|
|
2855
|
+
latest.current.active = next
|
|
2856
|
+
setActive(next)
|
|
2857
|
+
latest.current.onValueChange?.(chartSelectionPayload(next, latest.current.data, eventType))
|
|
2858
|
+
},
|
|
2859
|
+
}
|
|
2860
|
+
}, [interactive, eventType])
|
|
2861
|
+
return { active: interactive ? active : null, onEvents }
|
|
2862
|
+
}
|
|
2863
|
+
|
|
2864
|
+
/**
|
|
2865
|
+
* Display name for `key`: `labels[key]` when present, else `key` itself.
|
|
2866
|
+
* (Own keys only, so `"constructor"` is not looked up on the prototype.)
|
|
2867
|
+
*/
|
|
2868
|
+
function labelOf(key: string, labels?: Readonly<Record<string, string>>): string {
|
|
2869
|
+
return hasLabel(labels, key) ? labels![key]! : key
|
|
2870
|
+
}
|
|
2871
|
+
|
|
2872
|
+
/** `data` with each row's `index` cell replaced by its display name (rows are copied, not mutated). */
|
|
2873
|
+
function labelRows<Row extends Record<string, unknown>>(
|
|
2874
|
+
data: readonly Row[],
|
|
2875
|
+
index: string,
|
|
2876
|
+
labels?: Readonly<Record<string, string>>,
|
|
2877
|
+
): Row[] {
|
|
2878
|
+
if (!labels) return data as Row[]
|
|
2879
|
+
return data.map((row) => ({ ...row, [index]: labelOf(String(row[index] ?? ""), labels) }))
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
/** Whether `labels` renames `key` (own keys only). */
|
|
2883
|
+
function hasLabel(labels: Readonly<Record<string, string>> | undefined, key: string): boolean {
|
|
2884
|
+
return Boolean(labels) && Object.prototype.hasOwnProperty.call(labels, key)
|
|
2885
|
+
}
|
|
2886
|
+
|
|
2887
|
+
/* ------------------------------------------------------------ provisional */
|
|
2888
|
+
|
|
2889
|
+
/** The default label for points that are not final yet, in `locale`: "Preliminary" / 「速報」. Default the page's locale. */
|
|
2890
|
+
function defaultProvisionalLabel(locale?: string): string {
|
|
2891
|
+
return chartText(locale).provisional
|
|
2892
|
+
}
|
|
2893
|
+
|
|
2894
|
+
/**
|
|
2895
|
+
* Position of the first provisional point: the first entry of `indexValues`
|
|
2896
|
+
* that equals `from` (compared as text, so `"2026-09"` and a Date-less string
|
|
2897
|
+
* key both work). `-1` when `from` is unset or not among the values — the chart
|
|
2898
|
+
* then draws everything as confirmed.
|
|
2899
|
+
*/
|
|
2900
|
+
function provisionalStart(indexValues: readonly unknown[], from: string | number | undefined | null): number {
|
|
2901
|
+
if (from === undefined || from === null) return -1
|
|
2902
|
+
const key = String(from)
|
|
2903
|
+
return indexValues.findIndex((value) => String(value ?? "") === key)
|
|
2904
|
+
}
|
|
2905
|
+
|
|
2906
|
+
/**
|
|
2907
|
+
* Split one series at `start` (see `provisionalStart`). `confirmed` keeps the
|
|
2908
|
+
* points before `start`; `provisional` keeps `start` onward plus the last
|
|
2909
|
+
* confirmed point, so the dashed line joins the solid one. `start <= 0` or
|
|
2910
|
+
* `-1` leaves nothing to join (all provisional / none provisional).
|
|
2911
|
+
*/
|
|
2912
|
+
function splitProvisional(
|
|
2913
|
+
values: readonly (number | null)[],
|
|
2914
|
+
start: number,
|
|
2915
|
+
): { confirmed: (number | null)[]; provisional: (number | null)[] } {
|
|
2916
|
+
if (start < 0) return { confirmed: [...values], provisional: values.map(() => null) }
|
|
2917
|
+
return {
|
|
2918
|
+
confirmed: values.map((v, i) => (i < start ? v : null)),
|
|
2919
|
+
provisional: values.map((v, i) => (i >= Math.max(0, start - 1) ? v : null)),
|
|
2920
|
+
}
|
|
2921
|
+
}
|
|
2922
|
+
|
|
2923
|
+
/* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
|
|
2924
|
+
|
|
2925
|
+
const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
|
|
2926
|
+
const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
|
|
2927
|
+
|
|
2928
|
+
/**
|
|
2929
|
+
* The attributes of a typed chart's leftover props that belong on its root
|
|
2930
|
+
* element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
|
|
2931
|
+
* An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
|
|
2932
|
+
*/
|
|
2933
|
+
function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
|
|
2934
|
+
const out: Record<string, unknown> = {}
|
|
2935
|
+
for (const [key, value] of Object.entries(rest)) {
|
|
2936
|
+
if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
|
|
2937
|
+
}
|
|
2938
|
+
return out
|
|
2939
|
+
}
|
|
2940
|
+
|
|
2941
|
+
/** The series tokens, in palette order — the default `colors` of every typed chart. */
|
|
2942
|
+
const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
|
|
2943
|
+
"chart-1",
|
|
2944
|
+
"chart-2",
|
|
2945
|
+
"chart-3",
|
|
2946
|
+
"chart-4",
|
|
2947
|
+
"chart-5",
|
|
2948
|
+
]
|
|
2949
|
+
|
|
2950
|
+
const TOKEN_NAME_RE = /^chart-[1-5]$/
|
|
2951
|
+
|
|
2952
|
+
/** The meaning colours; each is a theme token of the same name (`--positive`, …). */
|
|
2953
|
+
const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
|
|
2954
|
+
|
|
2955
|
+
/** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
|
|
2956
|
+
function isChartTone(color: string): color is ChartTone {
|
|
2957
|
+
return (CHART_TONES as readonly string[]).includes(color.trim())
|
|
2958
|
+
}
|
|
2959
|
+
|
|
2960
|
+
/**
|
|
2961
|
+
* A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
|
|
2962
|
+
* light/dark on its own), anything else passes through unchanged.
|
|
2963
|
+
*/
|
|
2964
|
+
function chartColorToCss(color: ChartColor): string {
|
|
2965
|
+
const value = color.trim()
|
|
2966
|
+
return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
|
|
2967
|
+
}
|
|
2968
|
+
|
|
2969
|
+
/**
|
|
2970
|
+
* A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
|
|
2971
|
+
* colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
|
|
2972
|
+
* lightness step from the page in light and dark. `--positive` etc. are for text and icons.
|
|
2973
|
+
*/
|
|
2974
|
+
function chartFillToCss(color: ChartColor): string {
|
|
2975
|
+
const value = color.trim()
|
|
2976
|
+
return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
|
|
2977
|
+
}
|
|
2978
|
+
|
|
2979
|
+
/** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
|
|
2980
|
+
function chartFillName(color: ChartColor): ChartColor {
|
|
2981
|
+
const value = color.trim()
|
|
2982
|
+
return isChartTone(value) ? `${value}-fill` : color
|
|
2983
|
+
}
|
|
2984
|
+
|
|
2985
|
+
/** The `i`-th colour, cycling through `colors` (the token palette when empty). */
|
|
2986
|
+
function chartColorAt(colors: readonly ChartColor[] | undefined, i: number): ChartColor {
|
|
2987
|
+
const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
|
|
2988
|
+
return palette[i % palette.length]!
|
|
2989
|
+
}
|
|
2990
|
+
|
|
2991
|
+
/** `colors` extended (by cycling) to exactly `count` entries. */
|
|
2992
|
+
function chartColorsFor(colors: readonly ChartColor[] | undefined, count: number): ChartColor[] {
|
|
2993
|
+
return Array.from({ length: count }, (_, i) => chartColorAt(colors, i))
|
|
2994
|
+
}
|
|
2995
|
+
|
|
2996
|
+
/** A translucent version of a CSS colour (works for `var(--…)` too). */
|
|
2997
|
+
function tintCss(cssColor: string, percent: number): string {
|
|
2998
|
+
return `color-mix(in oklab, ${cssColor} ${percent}%, transparent)`
|
|
2999
|
+
}
|
|
3000
|
+
|
|
3001
|
+
const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 })
|
|
3002
|
+
|
|
3003
|
+
/** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
|
|
3004
|
+
const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
|
|
3005
|
+
|
|
3006
|
+
/**
|
|
3007
|
+
* The formatter a chart actually uses: an explicit `valueFormatter` wins, else
|
|
3008
|
+
* `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
|
|
3009
|
+
*/
|
|
3010
|
+
function resolveValueFormatter(
|
|
3011
|
+
valueFormatter: ValueFormatter | undefined,
|
|
3012
|
+
format: ValueFormat | undefined,
|
|
3013
|
+
locale?: string,
|
|
3014
|
+
): ValueFormatter {
|
|
3015
|
+
return valueFormatter ?? toValueFormatter(format, locale)
|
|
3016
|
+
}
|
|
3017
|
+
|
|
3018
|
+
/**
|
|
3019
|
+
* The formatter of value-axis ticks and on-plot labels: an explicit
|
|
3020
|
+
* `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
|
|
3021
|
+
* the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
|
|
3022
|
+
* too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
|
|
3023
|
+
* form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
|
|
3024
|
+
* so an axis tick and a KPI / tooltip of the same `format` always print the same
|
|
3025
|
+
* currency sign and grouping.
|
|
3026
|
+
*/
|
|
3027
|
+
function resolveAxisFormatter(
|
|
3028
|
+
valueFormatter: ValueFormatter | undefined,
|
|
3029
|
+
format: ValueFormat | undefined,
|
|
3030
|
+
localeArg?: string,
|
|
3031
|
+
): ValueFormatter {
|
|
3032
|
+
if (valueFormatter) return valueFormatter
|
|
3033
|
+
const locale = resolveLocale(localeArg)
|
|
3034
|
+
const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
|
|
3035
|
+
if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
|
|
3036
|
+
const currency = "currency" in spec ? spec.currency : undefined
|
|
3037
|
+
const short: ValueFormat =
|
|
3038
|
+
spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
|
|
3039
|
+
return (value) => formatValue(value, short, locale)
|
|
3040
|
+
}
|
|
3041
|
+
|
|
3042
|
+
interface CompactUnit {
|
|
3043
|
+
token: string
|
|
3044
|
+
size: number
|
|
3045
|
+
}
|
|
3046
|
+
|
|
3047
|
+
const compactUnitCache = new Map<string, CompactUnit[] | null>()
|
|
3048
|
+
|
|
3049
|
+
/**
|
|
3050
|
+
* The compact-notation unit words of a locale and their sizes, largest first: `兆` / `億` / `万` in ja,
|
|
3051
|
+
* `T` / `B` / `M` / `K` in en. `null` when the locale's compact form puts anything between the number and its
|
|
3052
|
+
* word (`1,5 Mio.`), where a token cannot be swapped in place.
|
|
3053
|
+
*/
|
|
3054
|
+
function compactUnits(locale: string): CompactUnit[] | null {
|
|
3055
|
+
const cached = compactUnitCache.get(locale)
|
|
3056
|
+
if (cached !== undefined) return cached
|
|
3057
|
+
let units: CompactUnit[] | null = []
|
|
3058
|
+
try {
|
|
3059
|
+
const compact = new Intl.NumberFormat(locale, { notation: "compact" })
|
|
3060
|
+
const seen = new Set<string>()
|
|
3061
|
+
for (let exp = 3; exp <= 15; exp++) {
|
|
3062
|
+
const parts = compact.formatToParts(10 ** exp)
|
|
3063
|
+
const at = parts.findIndex((p) => p.type === "compact")
|
|
3064
|
+
if (at === -1) continue
|
|
3065
|
+
if (parts[at - 1]?.type !== "integer" || at !== parts.length - 1) {
|
|
3066
|
+
units = null
|
|
3067
|
+
break
|
|
3068
|
+
}
|
|
3069
|
+
const token = parts[at]!.value
|
|
3070
|
+
if (seen.has(token)) continue
|
|
3071
|
+
seen.add(token)
|
|
3072
|
+
units.push({ token, size: 10 ** exp })
|
|
3073
|
+
}
|
|
3074
|
+
} catch {
|
|
3075
|
+
units = null
|
|
3076
|
+
}
|
|
3077
|
+
const sorted = units && units.length > 0 ? units.sort((a, b) => b.size - a.size) : null
|
|
3078
|
+
compactUnitCache.set(locale, sorted)
|
|
3079
|
+
return sorted
|
|
3080
|
+
}
|
|
3081
|
+
|
|
3082
|
+
const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
|
3083
|
+
|
|
3084
|
+
/**
|
|
3085
|
+
* The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
|
|
3086
|
+
* that largest tick, so units never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`;
|
|
3087
|
+
* `$0.5M` / `$1M` / `$1.5M`, not `$500K` / `$1M`). Only the short forms (`compact` / `number` / `currency`,
|
|
3088
|
+
* no `valueFormatter`) have units to align; any other format — an axis whose largest tick is under the smallest
|
|
3089
|
+
* unit (1万 / 1K), or a locale whose compact form cannot be aligned in place — keeps `resolveAxisFormatter`'s output as it is.
|
|
3090
|
+
*/
|
|
3091
|
+
function resolveAxisTickFormatter(
|
|
3092
|
+
valueFormatter: ValueFormatter | undefined,
|
|
3093
|
+
format: ValueFormat | undefined,
|
|
3094
|
+
localeArg?: string,
|
|
3095
|
+
): (top: number) => ValueFormatter {
|
|
3096
|
+
const locale = resolveLocale(localeArg)
|
|
3097
|
+
const base = resolveAxisFormatter(valueFormatter, format, locale)
|
|
3098
|
+
const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
|
|
3099
|
+
const units = !valueFormatter && (spec.type === "compact" || spec.type === "number" || spec.type === "currency") ? compactUnits(locale) : null
|
|
3100
|
+
if (!units) return () => base
|
|
3101
|
+
const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
|
|
3102
|
+
const numberToken = new RegExp(`\\d[\\d,]*(?:\\.\\d+)?(?:${units.map((u) => escapeRegExp(u.token)).join("|")})?`)
|
|
3103
|
+
return (top) => {
|
|
3104
|
+
const unit = units.find((u) => Math.abs(top) >= u.size)
|
|
3105
|
+
if (!unit) return base
|
|
3106
|
+
return (value) => {
|
|
3107
|
+
const text = base(value)
|
|
3108
|
+
if (value === 0 || !Number.isFinite(value)) return text
|
|
3109
|
+
const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.token}`
|
|
3110
|
+
return text.replace(numberToken, () => scaled)
|
|
3111
|
+
}
|
|
3112
|
+
}
|
|
3113
|
+
}
|
|
3114
|
+
|
|
3115
|
+
/**
|
|
3116
|
+
* A data cell as a number, or `null` for a gap. Numeric strings count — SQL
|
|
3117
|
+
* `DECIMAL` / `BIGINT` columns usually arrive as strings.
|
|
3118
|
+
*/
|
|
3119
|
+
function toChartNumber(value: unknown): number | null {
|
|
3120
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : null
|
|
3121
|
+
if (typeof value === "bigint") return Number(value)
|
|
3122
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
3123
|
+
const n = Number(value)
|
|
3124
|
+
return Number.isFinite(n) ? n : null
|
|
3125
|
+
}
|
|
3126
|
+
return null
|
|
3127
|
+
}
|
|
3128
|
+
|
|
3129
|
+
/** Clamp `value` into `[min, max]`. */
|
|
3130
|
+
function clamp(value: number, min: number, max: number): number {
|
|
3131
|
+
return Math.min(max, Math.max(min, value))
|
|
3132
|
+
}
|
|
3133
|
+
|
|
3134
|
+
/* ------------------------------------------------------------ aggregation */
|
|
3135
|
+
|
|
3136
|
+
/** How many categories a chart colours individually; the rest fold into「その他」. */
|
|
3137
|
+
const MAX_CHART_SERIES = 5
|
|
3138
|
+
|
|
3139
|
+
/** The series name the folded categories get, by language. */
|
|
3140
|
+
const OTHER_SERIES_LABELS: Record<UiLanguage, string> = { ja: "その他", en: "Other" }
|
|
3141
|
+
|
|
3142
|
+
/** The series name the folded categories get in `locale` ("Other" / "その他"). Default the page's locale (`<html lang>`). */
|
|
3143
|
+
function otherSeriesLabel(locale?: string): string {
|
|
3144
|
+
return OTHER_SERIES_LABELS[uiLanguage(resolveLocale(locale))]
|
|
3145
|
+
}
|
|
3146
|
+
|
|
3147
|
+
const OTHER_NAMES = new Set(Object.values(OTHER_SERIES_LABELS))
|
|
3148
|
+
|
|
3149
|
+
/** Whether a category / row is the "other" bucket by name (「その他」 or "Other", whatever the page language). */
|
|
3150
|
+
function isOtherName(name: string | null | undefined): boolean {
|
|
3151
|
+
return typeof name === "string" && OTHER_NAMES.has(name)
|
|
3152
|
+
}
|
|
3153
|
+
|
|
3154
|
+
interface AggregatedItems<Item extends { name: string; value: number }> {
|
|
3155
|
+
/** The `n` largest items, in their given order. All items when there are `n` or fewer. */
|
|
3156
|
+
top: Item[]
|
|
3157
|
+
/** The items folded into `other`, in their given order. */
|
|
3158
|
+
rest: Item[]
|
|
3159
|
+
/** The folded remainder, or `null` when nothing was folded. */
|
|
3160
|
+
other: { name: string; value: number } | null
|
|
3161
|
+
}
|
|
3162
|
+
|
|
3163
|
+
/**
|
|
3164
|
+
* Keep the `n` largest items (by value; ties keep the earlier one) in their
|
|
3165
|
+
* given order and fold the rest into one `otherLabel` item. Shared by every
|
|
3166
|
+
* chart that caps its categories (Area / Line / Bar series, Donut slices,
|
|
3167
|
+
* BarList rows).
|
|
3168
|
+
*/
|
|
3169
|
+
function aggregateTopN<Item extends { name: string; value: number }>(
|
|
3170
|
+
items: readonly Item[],
|
|
3171
|
+
n: number = MAX_CHART_SERIES,
|
|
3172
|
+
otherLabel: string = otherSeriesLabel(),
|
|
3173
|
+
): AggregatedItems<Item> {
|
|
3174
|
+
if (items.length <= n) return { top: [...items], rest: [], other: null }
|
|
3175
|
+
const ranked = items
|
|
3176
|
+
.map((item, i) => ({ item, i }))
|
|
3177
|
+
.sort((a, b) => b.item.value - a.item.value || a.i - b.i)
|
|
3178
|
+
const keep = new Set(ranked.slice(0, n).map((r) => r.i))
|
|
3179
|
+
const top = items.filter((_, i) => keep.has(i))
|
|
3180
|
+
const rest = items.filter((_, i) => !keep.has(i))
|
|
3181
|
+
return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
|
|
3182
|
+
}
|
|
3183
|
+
|
|
3184
|
+
interface AggregatedSeries {
|
|
3185
|
+
/** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
|
|
3186
|
+
data: Record<string, unknown>[]
|
|
3187
|
+
/** Series to draw: the kept categories in their given order, then `otherCategory`. */
|
|
3188
|
+
categories: string[]
|
|
3189
|
+
/** The folded series' name, or `null`. */
|
|
3190
|
+
otherCategory: string | null
|
|
3191
|
+
}
|
|
3192
|
+
|
|
3193
|
+
/**
|
|
3194
|
+
* Cap a cartesian chart at `n` series: rank the categories by the sum of their
|
|
3195
|
+
* values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
|
|
3196
|
+
*/
|
|
3197
|
+
function aggregateSeries(
|
|
3198
|
+
data: readonly Record<string, unknown>[],
|
|
3199
|
+
categories: readonly string[],
|
|
3200
|
+
n: number = MAX_CHART_SERIES,
|
|
3201
|
+
otherLabel: string = otherSeriesLabel(),
|
|
3202
|
+
): AggregatedSeries {
|
|
3203
|
+
const totals = categories.map((name) => ({
|
|
3204
|
+
name,
|
|
3205
|
+
value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
|
|
3206
|
+
}))
|
|
3207
|
+
const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
|
|
3208
|
+
if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
|
|
3209
|
+
const folded = rest.map((item) => item.name)
|
|
3210
|
+
return {
|
|
3211
|
+
data: data.map((row) => {
|
|
3212
|
+
let sum: number | null = null
|
|
3213
|
+
for (const name of folded) {
|
|
3214
|
+
const v = toChartNumber(row[name])
|
|
3215
|
+
if (v !== null) sum = (sum ?? 0) + v
|
|
3216
|
+
}
|
|
3217
|
+
return { ...row, [other.name]: sum }
|
|
3218
|
+
}),
|
|
3219
|
+
categories: [...top.map((item) => item.name), other.name],
|
|
3220
|
+
otherCategory: other.name,
|
|
3221
|
+
}
|
|
3222
|
+
}
|
|
3223
|
+
|
|
3224
|
+
/**
|
|
3225
|
+
* `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
|
|
3226
|
+
* at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
|
|
3227
|
+
*/
|
|
3228
|
+
function aggregateSeriesKeeping(
|
|
3229
|
+
data: readonly Record<string, unknown>[],
|
|
3230
|
+
categories: readonly string[],
|
|
3231
|
+
keep: string | undefined,
|
|
3232
|
+
n: number = MAX_CHART_SERIES,
|
|
3233
|
+
otherLabel: string = otherSeriesLabel(),
|
|
3234
|
+
): AggregatedSeries {
|
|
3235
|
+
if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n, otherLabel)
|
|
3236
|
+
const aggregated = aggregateSeries(
|
|
3237
|
+
data,
|
|
3238
|
+
categories.filter((c) => c !== keep),
|
|
3239
|
+
n,
|
|
3240
|
+
otherLabel,
|
|
3241
|
+
)
|
|
3242
|
+
return { ...aggregated, categories: [...aggregated.categories, keep] }
|
|
3243
|
+
}
|
|
3244
|
+
|
|
3245
|
+
/**
|
|
3246
|
+
* `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
|
|
3247
|
+
* builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
|
|
3248
|
+
* so a main series keeps its colour whether or not a comparison is drawn.
|
|
3249
|
+
*/
|
|
3250
|
+
function seriesColorsWithComparison(
|
|
3251
|
+
categories: readonly string[],
|
|
3252
|
+
colors: ChartColors | undefined,
|
|
3253
|
+
otherColor: string,
|
|
3254
|
+
otherCategory: string | null,
|
|
3255
|
+
allCategories: readonly string[],
|
|
3256
|
+
comparison: string | undefined,
|
|
3257
|
+
): string[] {
|
|
3258
|
+
if (comparison === undefined || !categories.includes(comparison)) {
|
|
3259
|
+
return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
|
|
3260
|
+
}
|
|
3261
|
+
const main = categories.filter((c) => c !== comparison)
|
|
3262
|
+
const mainColors = seriesColorsFor(
|
|
3263
|
+
main,
|
|
3264
|
+
colors,
|
|
3265
|
+
otherColor,
|
|
3266
|
+
otherCategory,
|
|
3267
|
+
allCategories.filter((c) => c !== comparison),
|
|
3268
|
+
)
|
|
3269
|
+
return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
|
|
3270
|
+
}
|
|
3271
|
+
|
|
3272
|
+
/**
|
|
3273
|
+
* Colour per drawn series: the record's token for that category, else the
|
|
3274
|
+
* array's token at the category's position in `allCategories` (cycled), else
|
|
3275
|
+
* the token palette by drawn position. `otherCategory` — and a category the
|
|
3276
|
+
* data itself names「その他」/ "Other" (`OTHER_SERIES_LABELS`) — always gets `otherColor`.
|
|
3277
|
+
*/
|
|
3278
|
+
function seriesColorsFor(
|
|
3279
|
+
categories: readonly string[],
|
|
3280
|
+
colors: ChartColors | undefined,
|
|
3281
|
+
otherColor: string,
|
|
3282
|
+
otherCategory: string | null = null,
|
|
3283
|
+
allCategories: readonly string[] = categories,
|
|
3284
|
+
): string[] {
|
|
3285
|
+
const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
|
|
3286
|
+
const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
|
|
3287
|
+
return categories.map((category, i) => {
|
|
3288
|
+
if ((otherCategory !== null && category === otherCategory) || isOtherName(category)) return otherColor
|
|
3289
|
+
const fromRecord = record?.[category]
|
|
3290
|
+
if (fromRecord) return fromRecord
|
|
3291
|
+
if (list && list.length > 0) {
|
|
3292
|
+
const at = allCategories.indexOf(category)
|
|
3293
|
+
return list[(at === -1 ? i : at) % list.length]!
|
|
3294
|
+
}
|
|
3295
|
+
return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
|
|
3296
|
+
})
|
|
3297
|
+
}
|
|
3298
|
+
|
|
3299
|
+
/* ------------------------------------------------------------------ Donut */
|
|
3300
|
+
|
|
3301
|
+
/** One drawn donut slice, largest first. */
|
|
3302
|
+
interface DonutSlice {
|
|
3303
|
+
name: string
|
|
3304
|
+
/** Negative and missing values count as 0. */
|
|
3305
|
+
value: number
|
|
3306
|
+
/** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
|
|
3307
|
+
color: string
|
|
3308
|
+
/** The folded「その他」slice. */
|
|
3309
|
+
isOther: boolean
|
|
3310
|
+
/** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
|
|
3311
|
+
row: Record<string, unknown>
|
|
3312
|
+
}
|
|
3313
|
+
|
|
3314
|
+
interface DonutSlicesConfig {
|
|
3315
|
+
/** Label column. */
|
|
3316
|
+
index: string
|
|
3317
|
+
/** Value column. */
|
|
3318
|
+
value: string
|
|
3319
|
+
/** Slice colours by rank (cycled). Default: the token palette in order. */
|
|
3320
|
+
colors?: readonly ChartSeriesColor[]
|
|
3321
|
+
/** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
|
|
3322
|
+
maxSlices?: number
|
|
3323
|
+
/** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
|
|
3324
|
+
otherColor: string
|
|
3325
|
+
otherLabel?: string
|
|
3326
|
+
}
|
|
3327
|
+
|
|
3328
|
+
/**
|
|
3329
|
+
* Donut slices: sorted by value (largest first, ties keep input order), the
|
|
3330
|
+
* `maxSlices` largest kept and coloured by rank in fixed token order, the rest
|
|
3331
|
+
* summed into one「その他」slice in `otherColor`.
|
|
3332
|
+
*/
|
|
3333
|
+
function donutSlices(
|
|
3334
|
+
data: readonly Record<string, unknown>[],
|
|
3335
|
+
{ index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = otherSeriesLabel() }: DonutSlicesConfig,
|
|
3336
|
+
): DonutSlice[] {
|
|
3337
|
+
const items = data
|
|
3338
|
+
.map((row, i) => {
|
|
3339
|
+
const n = toChartNumber(row[value])
|
|
3340
|
+
return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
|
|
3341
|
+
})
|
|
3342
|
+
.sort((a, b) => b.value - a.value || a.i - b.i)
|
|
3343
|
+
const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
|
|
3344
|
+
const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
|
|
3345
|
+
const slices: DonutSlice[] = top.map((item, rank) => ({
|
|
3346
|
+
name: item.name,
|
|
3347
|
+
value: item.value,
|
|
3348
|
+
// A row the data itself names「その他」/ "Other" is the same remainder: grey, like the folded slice.
|
|
3349
|
+
color: isOtherName(item.name) ? otherColor : palette[rank % palette.length]!,
|
|
3350
|
+
isOther: false,
|
|
3351
|
+
row: item.row,
|
|
3352
|
+
}))
|
|
3353
|
+
if (other) {
|
|
3354
|
+
slices.push({
|
|
3355
|
+
name: other.name,
|
|
3356
|
+
value: other.value,
|
|
3357
|
+
color: otherColor,
|
|
3358
|
+
isOther: true,
|
|
3359
|
+
row: { [index]: other.name, [value]: other.value },
|
|
3360
|
+
})
|
|
3361
|
+
}
|
|
3362
|
+
return slices
|
|
3363
|
+
}
|
|
3364
|
+
|
|
3365
|
+
/* ---------------------------------------------------------------- BarList */
|
|
3366
|
+
|
|
3367
|
+
type BarListSortOrder = "ascending" | "descending" | "none"
|
|
3368
|
+
|
|
3369
|
+
/** Sort a copy of the rows by value; `"none"` keeps the given order. */
|
|
3370
|
+
function sortBarListData<T extends { value: number }>(data: readonly T[], sortOrder: BarListSortOrder): T[] {
|
|
3371
|
+
const rows = [...data]
|
|
3372
|
+
if (sortOrder === "ascending") rows.sort((a, b) => a.value - b.value)
|
|
3373
|
+
else if (sortOrder === "descending") rows.sort((a, b) => b.value - a.value)
|
|
3374
|
+
return rows
|
|
3375
|
+
}
|
|
3376
|
+
|
|
3377
|
+
/** BarList-only settings. */
|
|
3378
|
+
interface BarListOptions {
|
|
3379
|
+
/** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
|
|
3380
|
+
sortOrder?: BarListSortOrder
|
|
3381
|
+
/** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
|
|
3382
|
+
maxItems?: number
|
|
3383
|
+
/** まとめた行のラベル。既定「その他」。 */
|
|
3384
|
+
otherLabel?: string
|
|
3385
|
+
/** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
|
|
3386
|
+
exclude?: readonly string[]
|
|
3387
|
+
/** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
|
|
3388
|
+
showShare?: boolean
|
|
3389
|
+
}
|
|
3390
|
+
|
|
3391
|
+
/** One drawn BarList row. */
|
|
3392
|
+
interface BarListRow<Row = Record<string, unknown>> {
|
|
3393
|
+
/** React key: the row's `key`, else its name (`"__other"` for the folded row). */
|
|
3394
|
+
key: string
|
|
3395
|
+
name: string
|
|
3396
|
+
value: number
|
|
3397
|
+
/** Only for real rows; the folded row never links. */
|
|
3398
|
+
href?: string
|
|
3399
|
+
/** Legacy per-row colour (`BarListItem.color`). */
|
|
3400
|
+
color?: ChartColor
|
|
3401
|
+
/** The folded「その他」row. */
|
|
3402
|
+
isOther: boolean
|
|
3403
|
+
/** The input row (`null` for the folded row). */
|
|
3404
|
+
row: Row | null
|
|
3405
|
+
}
|
|
3406
|
+
|
|
3407
|
+
interface BarListRowsConfig extends BarListOptions {
|
|
3408
|
+
/** Name column. Default `"name"`. */
|
|
3409
|
+
index?: string
|
|
3410
|
+
/** Value column. Default `"value"`. */
|
|
3411
|
+
category?: string
|
|
3412
|
+
}
|
|
3413
|
+
|
|
3414
|
+
/**
|
|
3415
|
+
* The rows a BarList draws: read name / value (numeric strings count, gaps are
|
|
3416
|
+
* 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
|
|
3417
|
+
* the folded remainder as one「その他」row. Rows named in `exclude` skip the
|
|
3418
|
+
* ranking and are always added to「その他」.
|
|
3419
|
+
*/
|
|
3420
|
+
function barListRows<Row extends object>(
|
|
3421
|
+
data: readonly Row[],
|
|
3422
|
+
{ index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = otherSeriesLabel(), exclude }: BarListRowsConfig = {},
|
|
3423
|
+
): BarListRow<Row>[] {
|
|
3424
|
+
const items = data.map((row): BarListRow<Row> => {
|
|
3425
|
+
const cells = row as Record<string, unknown>
|
|
3426
|
+
const name = String(cells[index] ?? "")
|
|
3427
|
+
return {
|
|
3428
|
+
key: typeof cells.key === "string" ? cells.key : name,
|
|
3429
|
+
name,
|
|
3430
|
+
value: toChartNumber(cells[category]) ?? 0,
|
|
3431
|
+
href: typeof cells.href === "string" ? cells.href : undefined,
|
|
3432
|
+
color: typeof cells.color === "string" ? cells.color : undefined,
|
|
3433
|
+
isOther: false,
|
|
3434
|
+
row,
|
|
3435
|
+
}
|
|
3436
|
+
})
|
|
3437
|
+
const excluded = new Set(exclude ?? [])
|
|
3438
|
+
const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
|
|
3439
|
+
const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
|
|
3440
|
+
const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
|
|
3441
|
+
const rows = sortBarListData(top, sortOrder)
|
|
3442
|
+
if (other || outside.length > 0) {
|
|
3443
|
+
const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
|
|
3444
|
+
rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
|
|
3445
|
+
}
|
|
3446
|
+
return rows
|
|
3447
|
+
}
|
|
3448
|
+
|
|
3449
|
+
/** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
|
|
3450
|
+
function barListWidths(values: readonly number[]): number[] {
|
|
3451
|
+
const max = Math.max(0, ...values)
|
|
3452
|
+
if (max === 0) return values.map(() => 0)
|
|
3453
|
+
return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
|
|
3454
|
+
}
|
|
3455
|
+
|
|
3456
|
+
/**
|
|
3457
|
+
* How strongly the BarList bars are painted: every row the same tint of the bar
|
|
3458
|
+
* colour (rank is the bar's length, not its weight). A tint over transparent, so
|
|
3459
|
+
* it sits on the card in light and dark; it must stay visible against the card
|
|
3460
|
+
* while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
|
|
3461
|
+
*/
|
|
3462
|
+
const BAR_LIST_TINT = 45
|
|
3463
|
+
/** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
|
|
3464
|
+
const BAR_LIST_OTHER_TINT = 30
|
|
3465
|
+
|
|
3466
|
+
/**
|
|
3467
|
+
* The fill of each BarList row: all real rows in the same tint of `color`
|
|
3468
|
+
* (`BAR_LIST_TINT`), the folded「その他」row (and a row the data names「その他」/ "Other") in a tint of `otherColor`
|
|
3469
|
+
* (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
|
|
3470
|
+
* ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
|
|
3471
|
+
* for that row. A tint, not the solid token, so the label printed over the bar
|
|
3472
|
+
* keeps its contrast.
|
|
3473
|
+
*/
|
|
3474
|
+
function barListFills(
|
|
3475
|
+
rows: readonly (Pick<BarListRow, "isOther" | "color"> & { name?: string })[],
|
|
3476
|
+
color: ChartColor,
|
|
3477
|
+
otherColor: string,
|
|
3478
|
+
): string[] {
|
|
3479
|
+
return rows.map((row) =>
|
|
3480
|
+
row.isOther || isOtherName(row.name)
|
|
3481
|
+
? tintCss(otherColor, BAR_LIST_OTHER_TINT)
|
|
3482
|
+
: tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
|
|
3483
|
+
)
|
|
3484
|
+
}
|
|
3485
|
+
|
|
3486
|
+
/** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
|
|
3487
|
+
function barListShareText(value: number, total: number): string {
|
|
3488
|
+
const v = Number.isFinite(value) && value > 0 ? value : 0
|
|
3489
|
+
if (total <= 0 || v === 0) return "0%"
|
|
3490
|
+
const pct = (v / total) * 100
|
|
3491
|
+
return pct < 1 ? "<1%" : `${Math.round(pct)}%`
|
|
3492
|
+
}
|
|
3493
|
+
|
|
3494
|
+
/**
|
|
3495
|
+
* The text at the end of each BarList row: the formatted value and, with
|
|
3496
|
+
* `showShare`, its share of the total of all drawn rows (including「その他」,
|
|
3497
|
+
* so the shares are of the whole list): `value` and `share` apart (the share is
|
|
3498
|
+
* drawn muted), `text` as one string (「¥8,240万 · 43%」).
|
|
3499
|
+
*/
|
|
3500
|
+
function barListValueTexts(
|
|
3501
|
+
values: readonly number[],
|
|
3502
|
+
formatter: ValueFormatter,
|
|
3503
|
+
showShare = false,
|
|
3504
|
+
): { value: string; share?: string; text: string }[] {
|
|
3505
|
+
const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
|
|
3506
|
+
return values.map((v) => {
|
|
3507
|
+
const value = formatter(v)
|
|
3508
|
+
if (!showShare) return { value, text: value }
|
|
3509
|
+
const share = barListShareText(v, total)
|
|
3510
|
+
return { value, share, text: `${value} · ${share}` }
|
|
3511
|
+
})
|
|
3512
|
+
}
|
|
3513
|
+
|
|
3514
|
+
/* -------------------------------------------------------------- DataTable */
|
|
3515
|
+
|
|
3516
|
+
/** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
|
|
3517
|
+
interface ChartDataTable {
|
|
3518
|
+
/** 表の見出し(`<caption>`)。 */
|
|
3519
|
+
caption?: string
|
|
3520
|
+
/** 列見出し。先頭がラベル列。 */
|
|
3521
|
+
columns: string[]
|
|
3522
|
+
/** 行。セルは書式済みの文字列。 */
|
|
3523
|
+
rows: string[][]
|
|
3524
|
+
}
|
|
3525
|
+
|
|
3526
|
+
/**
|
|
3527
|
+
* The chart's numbers as a table, for screen readers: one row per data row, the
|
|
3528
|
+
* `index` cell then each category through `formatter` (gaps → `—`). `labels`
|
|
3529
|
+
* 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).
|
|
3530
|
+
*/
|
|
3531
|
+
function chartDataTable(
|
|
3532
|
+
data: readonly Record<string, unknown>[],
|
|
3533
|
+
index: string,
|
|
3534
|
+
categories: readonly string[],
|
|
3535
|
+
formatter: ValueFormatter,
|
|
3536
|
+
labels?: Readonly<Record<string, string>>,
|
|
3537
|
+
indexName?: string,
|
|
3538
|
+
): ChartDataTable {
|
|
3539
|
+
const label = (key: string) => labels?.[key] ?? key
|
|
3540
|
+
return {
|
|
3541
|
+
columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
|
|
3542
|
+
rows: data.map((row) => [
|
|
3543
|
+
String(row[index] ?? ""),
|
|
3544
|
+
...categories.map((key) => {
|
|
3545
|
+
const n = toChartNumber(row[key])
|
|
3546
|
+
return n === null ? EMPTY_VALUE : formatter(n)
|
|
3547
|
+
}),
|
|
3548
|
+
]),
|
|
3549
|
+
}
|
|
3550
|
+
}
|
|
3551
|
+
|
|
3552
|
+
/* ------------------------------------------------------------ CategoryBar */
|
|
3553
|
+
|
|
3554
|
+
interface CategoryBarSegment {
|
|
3555
|
+
/** Width in percent of the whole bar. */
|
|
3556
|
+
width: number
|
|
3557
|
+
/** Where the segment starts, in percent. */
|
|
3558
|
+
start: number
|
|
3559
|
+
/** The running total at the segment's end — what its right-hand label shows. */
|
|
3560
|
+
end: number
|
|
3561
|
+
}
|
|
3562
|
+
|
|
3563
|
+
/** Lay the values side by side; negative values count as zero. */
|
|
3564
|
+
function categoryBarSegments(values: readonly number[]): CategoryBarSegment[] {
|
|
3565
|
+
const clean = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0))
|
|
3566
|
+
const total = clean.reduce((sum, v) => sum + v, 0)
|
|
3567
|
+
let running = 0
|
|
3568
|
+
return clean.map((v) => {
|
|
3569
|
+
const start = total === 0 ? 0 : (running / total) * 100
|
|
3570
|
+
running += v
|
|
3571
|
+
return { width: total === 0 ? 0 : (v / total) * 100, start, end: running }
|
|
3572
|
+
})
|
|
3573
|
+
}
|
|
3574
|
+
|
|
3575
|
+
interface CategoryBarLabel {
|
|
3576
|
+
/** Position in percent of the bar. */
|
|
3577
|
+
position: number
|
|
3578
|
+
/** The running total printed there. */
|
|
3579
|
+
value: number
|
|
3580
|
+
}
|
|
3581
|
+
|
|
3582
|
+
/**
|
|
3583
|
+
* Tick labels under the bar: `0` at the start, then the running total at each
|
|
3584
|
+
* segment's end. A label closer than `minGap` percent to the one before is
|
|
3585
|
+
* dropped so narrow segments don't print on top of each other — except the
|
|
3586
|
+
* last one (the total), which replaces its neighbour instead. With a
|
|
3587
|
+
* `markerPosition`, an inner label closer than `minGap` to the marker is dropped
|
|
3588
|
+
* too — the marker sits right under it and the two read as one crowded spot.
|
|
3589
|
+
*/
|
|
3590
|
+
function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
|
|
3591
|
+
const segments = categoryBarSegments(values).filter((s) => s.width > 0)
|
|
3592
|
+
if (segments.length === 0) return []
|
|
3593
|
+
const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
|
|
3594
|
+
segments.forEach((s, i) => {
|
|
3595
|
+
const label = { position: s.start + s.width, value: s.end }
|
|
3596
|
+
const prev = labels[labels.length - 1]!
|
|
3597
|
+
if (label.position - prev.position >= minGap) labels.push(label)
|
|
3598
|
+
else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
|
|
3599
|
+
})
|
|
3600
|
+
if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
|
|
3601
|
+
return labels.filter(
|
|
3602
|
+
(label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
|
|
3603
|
+
)
|
|
3604
|
+
}
|
|
3605
|
+
|
|
3606
|
+
/**
|
|
3607
|
+
* `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
|
|
3608
|
+
* (`texts`, same order): a label that would touch the one before is dropped — except the last (the
|
|
3609
|
+
* total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
|
|
3610
|
+
* edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
|
|
3611
|
+
* the rest 7 px at 12 px type).
|
|
3612
|
+
*/
|
|
3613
|
+
function categoryBarFitLabels(
|
|
3614
|
+
labels: readonly CategoryBarLabel[],
|
|
3615
|
+
texts: readonly string[],
|
|
3616
|
+
width: number,
|
|
3617
|
+
gap = 8,
|
|
3618
|
+
): CategoryBarLabel[] {
|
|
3619
|
+
const textWidth = (text: string) => {
|
|
3620
|
+
let w = 0
|
|
3621
|
+
for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
|
|
3622
|
+
return w
|
|
3623
|
+
}
|
|
3624
|
+
const extent = (label: CategoryBarLabel, text: string): [number, number] => {
|
|
3625
|
+
const w = textWidth(text)
|
|
3626
|
+
if (label.position <= 0) return [0, w]
|
|
3627
|
+
if (label.position >= 100) return [width - w, width]
|
|
3628
|
+
const center = (label.position / 100) * width
|
|
3629
|
+
return [center - w / 2, center + w / 2]
|
|
3630
|
+
}
|
|
3631
|
+
const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
|
|
3632
|
+
labels.forEach((label, i) => {
|
|
3633
|
+
const here = extent(label, texts[i] ?? "")
|
|
3634
|
+
const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
|
|
3635
|
+
if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
|
|
3636
|
+
else if (touches()) return
|
|
3637
|
+
kept.push({ label, extent: here })
|
|
3638
|
+
})
|
|
3639
|
+
return kept.map((k) => k.label)
|
|
3640
|
+
}
|
|
3641
|
+
|
|
3642
|
+
/** Marker position in percent of the bar, clamped to its ends. */
|
|
3643
|
+
function categoryBarMarkerPosition(value: number, values: readonly number[]): number {
|
|
3644
|
+
const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
|
|
3645
|
+
if (total === 0) return 0
|
|
3646
|
+
return clamp((value / total) * 100, 0, 100)
|
|
3647
|
+
}
|
|
3648
|
+
|
|
3649
|
+
/** Index of the segment the marker sits on (the last one for a value past the end). */
|
|
3650
|
+
function categoryBarMarkerSegment(value: number, values: readonly number[]): number {
|
|
3651
|
+
const segments = categoryBarSegments(values)
|
|
3652
|
+
const index = segments.findIndex((s) => s.width > 0 && value <= s.end)
|
|
3653
|
+
if (index !== -1) return index
|
|
3654
|
+
for (let i = segments.length - 1; i >= 0; i--) if (segments[i]!.width > 0) return i
|
|
3655
|
+
return 0
|
|
3656
|
+
}
|
|
3657
|
+
|
|
3658
|
+
/* --------------------------------------------------------- ProgressCircle */
|
|
3659
|
+
|
|
3660
|
+
interface ProgressCircleGeometry {
|
|
3661
|
+
/** SVG width/height. */
|
|
3662
|
+
size: number
|
|
3663
|
+
/** Radius of the stroke's centre line. */
|
|
3664
|
+
normalizedRadius: number
|
|
3665
|
+
circumference: number
|
|
3666
|
+
/** `stroke-dashoffset` for the value arc. */
|
|
3667
|
+
offset: number
|
|
3668
|
+
/** The value as a fraction of `max`, clamped to `[0, 1]`. */
|
|
3669
|
+
ratio: number
|
|
3670
|
+
}
|
|
3671
|
+
|
|
3672
|
+
function progressCircleGeometry(
|
|
3673
|
+
value: number,
|
|
3674
|
+
max: number,
|
|
3675
|
+
radius: number,
|
|
3676
|
+
strokeWidth: number,
|
|
3677
|
+
): ProgressCircleGeometry {
|
|
3678
|
+
const ratio = max > 0 && Number.isFinite(value) ? clamp(value / max, 0, 1) : 0
|
|
3679
|
+
const normalizedRadius = Math.max(0, radius - strokeWidth / 2)
|
|
3680
|
+
const circumference = 2 * Math.PI * normalizedRadius
|
|
3681
|
+
return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
|
|
3682
|
+
}
|
|
3683
|
+
|
|
3684
|
+
/* ---------------------------------------------------------------- summary */
|
|
3685
|
+
|
|
3686
|
+
interface ChartSummaryInput {
|
|
3687
|
+
data: readonly Record<string, unknown>[]
|
|
3688
|
+
/** The x-axis key. */
|
|
3689
|
+
index: string
|
|
3690
|
+
/** Series keys; the first one is described. */
|
|
3691
|
+
categories: readonly string[]
|
|
3692
|
+
/** Title of the chart, put in front when given. */
|
|
3693
|
+
title?: string
|
|
3694
|
+
/** Same as the chart's `format` (default `"compact"`). */
|
|
3695
|
+
format?: ValueFormat
|
|
3696
|
+
/** Wins over `format`. */
|
|
3697
|
+
valueFormatter?: ValueFormatter
|
|
3698
|
+
/** Language of the sentence. Default the page's locale (`<html lang>`). */
|
|
3699
|
+
locale?: string
|
|
3700
|
+
}
|
|
3701
|
+
|
|
3702
|
+
const SUMMARY_TEXT = {
|
|
3703
|
+
ja: {
|
|
3704
|
+
up: "、前の点より増加",
|
|
3705
|
+
down: "、前の点より減少",
|
|
3706
|
+
flat: "、前の点と横ばい",
|
|
3707
|
+
latest: (label: string, value: string) => `最新 ${label} は ${value}`,
|
|
3708
|
+
top: (name: string, share: string) => `最大は ${name}(${share})`,
|
|
3709
|
+
},
|
|
3710
|
+
en: {
|
|
3711
|
+
up: ", up from the previous point",
|
|
3712
|
+
down: ", down from the previous point",
|
|
3713
|
+
flat: ", flat from the previous point",
|
|
3714
|
+
latest: (label: string, value: string) => `Latest ${label}: ${value}`,
|
|
3715
|
+
top: (name: string, share: string) => `Largest: ${name} (${share})`,
|
|
3716
|
+
},
|
|
3717
|
+
}
|
|
3718
|
+
|
|
3719
|
+
/**
|
|
3720
|
+
* One-sentence summary built from the rows, for `summary="auto"`:
|
|
3721
|
+
* 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」("<title>: Latest <index>: <value>, up from the previous point"). The direction is
|
|
3722
|
+
* computed from the last two non-empty points of the first series — never
|
|
3723
|
+
* written by hand, so it cannot contradict the data. `undefined` when there is
|
|
3724
|
+
* no usable point.
|
|
3725
|
+
*/
|
|
3726
|
+
function buildChartSummary(input: ChartSummaryInput): string | undefined {
|
|
3727
|
+
const key = input.categories[0]
|
|
3728
|
+
if (key === undefined) return undefined
|
|
3729
|
+
const points: { label: string; value: number }[] = []
|
|
3730
|
+
for (const row of input.data) {
|
|
3731
|
+
const raw = row[key]
|
|
3732
|
+
const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
|
|
3733
|
+
if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
|
|
3734
|
+
}
|
|
3735
|
+
const latest = points[points.length - 1]
|
|
3736
|
+
if (!latest) return undefined
|
|
3737
|
+
const locale = resolveLocale(input.locale)
|
|
3738
|
+
const t = SUMMARY_TEXT[uiLanguage(locale)]
|
|
3739
|
+
const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact", locale)
|
|
3740
|
+
const prev = points[points.length - 2]
|
|
3741
|
+
const direction = !prev ? "" : latest.value > prev.value ? t.up : latest.value < prev.value ? t.down : t.flat
|
|
3742
|
+
const head = input.title ? `${input.title}: ` : ""
|
|
3743
|
+
return `${head}${t.latest(latest.label, text(latest.value))}${direction}`
|
|
3744
|
+
}
|
|
3745
|
+
|
|
3746
|
+
/**
|
|
3747
|
+
* `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」("<title>: Largest: <name> (<share>)") from the slices
|
|
3748
|
+
* (largest first). `undefined` when there is nothing to describe. `locale` picks the language; default the page's.
|
|
3749
|
+
*/
|
|
3750
|
+
function buildShareSummary(
|
|
3751
|
+
slices: readonly { name: string; value: number }[],
|
|
3752
|
+
title?: string,
|
|
3753
|
+
locale?: string,
|
|
3754
|
+
): string | undefined {
|
|
3755
|
+
const total = slices.reduce((sum, s) => sum + s.value, 0)
|
|
3756
|
+
const top = slices[0]
|
|
3757
|
+
if (!top || total <= 0) return undefined
|
|
3758
|
+
const share = `${Math.round((top.value / total) * 1000) / 10}%`
|
|
3759
|
+
return `${title ? `${title}: ` : ""}${SUMMARY_TEXT[uiLanguage(resolveLocale(locale))].top(top.name, share)}`
|
|
3760
|
+
}
|
|
3761
|
+
|
|
3762
|
+
/* ---------- inlined from @squadbase/squadkit registry/lib/distribution.ts (internal to @squadbase/vantage) ---------- */
|
|
3763
|
+
|
|
3764
|
+
/**
|
|
3765
|
+
* 分布の集計(ヒストグラムの階級分け・箱ひげの四分位)の純関数。
|
|
3766
|
+
* 生の値の配列を受け、number でない値(null・NaN・数値にならない文字列)は数えずに捨てる。
|
|
3767
|
+
*/
|
|
3768
|
+
|
|
3769
|
+
/** 値を数にする。number・数値文字列だけ通し、それ以外(null・NaN・∞)は `null`。 */
|
|
3770
|
+
function toFinite(value: unknown): number | null {
|
|
3771
|
+
const n = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN
|
|
3772
|
+
return Number.isFinite(n) ? n : null
|
|
3773
|
+
}
|
|
3774
|
+
|
|
3775
|
+
/** 数にできる値だけを昇順で返す。 */
|
|
3776
|
+
function sortedNumbers(values: readonly unknown[]): number[] {
|
|
3777
|
+
const out: number[] = []
|
|
3778
|
+
for (const v of values) {
|
|
3779
|
+
const n = toFinite(v)
|
|
3780
|
+
if (n !== null) out.push(n)
|
|
3781
|
+
}
|
|
3782
|
+
return out.sort((a, b) => a - b)
|
|
3783
|
+
}
|
|
3784
|
+
|
|
3785
|
+
/**
|
|
3786
|
+
* 昇順の配列の分位点(線形補間。Excel の QUARTILE.INC・numpy の既定と同じ)。`p` は 0〜1。空配列は `null`。
|
|
3787
|
+
*/
|
|
3788
|
+
function quantile(sorted: readonly number[], p: number): number | null {
|
|
3789
|
+
if (sorted.length === 0) return null
|
|
3790
|
+
const pos = (sorted.length - 1) * Math.min(1, Math.max(0, p))
|
|
3791
|
+
const lo = Math.floor(pos)
|
|
3792
|
+
const hi = Math.ceil(pos)
|
|
3793
|
+
return sorted[lo]! + (sorted[hi]! - sorted[lo]!) * (pos - lo)
|
|
3794
|
+
}
|
|
3795
|
+
|
|
3796
|
+
interface BoxStats {
|
|
3797
|
+
/** 数えた値の個数。 */
|
|
3798
|
+
count: number
|
|
3799
|
+
/** 最小・最大(外れ値を含む)。 */
|
|
3800
|
+
min: number
|
|
3801
|
+
max: number
|
|
3802
|
+
q1: number
|
|
3803
|
+
median: number
|
|
3804
|
+
q3: number
|
|
3805
|
+
/** ひげの下端・上端: 柵(Q1−k×IQR / Q3+k×IQR)の内側にある最小・最大の実測値。 */
|
|
3806
|
+
whiskerLow: number
|
|
3807
|
+
whiskerHigh: number
|
|
3808
|
+
/** 柵の外側の値(昇順)。 */
|
|
3809
|
+
outliers: number[]
|
|
3810
|
+
}
|
|
3811
|
+
|
|
3812
|
+
/**
|
|
3813
|
+
* 値の配列 → 箱ひげの統計。ひげは四分位範囲(IQR)の `whisker` 倍(既定 1.5)の柵の内側にある実測値まで、
|
|
3814
|
+
* その外側は外れ値。数にできる値が無ければ `null`。
|
|
3815
|
+
*/
|
|
3816
|
+
function boxStats(values: readonly unknown[], whisker = 1.5): BoxStats | null {
|
|
3817
|
+
const sorted = sortedNumbers(values)
|
|
3818
|
+
if (sorted.length === 0) return null
|
|
3819
|
+
const q1 = quantile(sorted, 0.25)!
|
|
3820
|
+
const median = quantile(sorted, 0.5)!
|
|
3821
|
+
const q3 = quantile(sorted, 0.75)!
|
|
3822
|
+
const reach = Math.max(0, whisker) * (q3 - q1)
|
|
3823
|
+
const low = q1 - reach
|
|
3824
|
+
const high = q3 + reach
|
|
3825
|
+
const inside = sorted.filter((v) => v >= low && v <= high)
|
|
3826
|
+
return {
|
|
3827
|
+
count: sorted.length,
|
|
3828
|
+
min: sorted[0]!,
|
|
3829
|
+
max: sorted[sorted.length - 1]!,
|
|
3830
|
+
q1,
|
|
3831
|
+
median,
|
|
3832
|
+
q3,
|
|
3833
|
+
whiskerLow: inside[0] ?? q1,
|
|
3834
|
+
whiskerHigh: inside[inside.length - 1] ?? q3,
|
|
3835
|
+
outliers: sorted.filter((v) => v < low || v > high),
|
|
3836
|
+
}
|
|
3837
|
+
}
|
|
3838
|
+
|
|
3839
|
+
interface HistogramBin {
|
|
3840
|
+
/** 階級の下端(以上)・上端(未満。最後の階級だけ上端を含む)。 */
|
|
3841
|
+
from: number
|
|
3842
|
+
to: number
|
|
3843
|
+
/** 階級に入った個数。 */
|
|
3844
|
+
count: number
|
|
3845
|
+
/** 上限超えをまとめた階級(`from` = 上限、`to` = 実測の最大。幅は他と違う)。 */
|
|
3846
|
+
overflow: boolean
|
|
3847
|
+
}
|
|
3848
|
+
|
|
3849
|
+
interface HistogramBinsConfig {
|
|
3850
|
+
/** 階級の幅。省略すると値の範囲から区切りのよい数(1・2・2.5・5 × 10^n)を選ぶ。 */
|
|
3851
|
+
binWidth?: number
|
|
3852
|
+
/** 階級の始まり。省略は幅の倍数に切り下げた最小値。 */
|
|
3853
|
+
start?: number
|
|
3854
|
+
/** 上限。これ以上の値は 1 つの「上限超え」階級にまとめる。省略するとまとめない。 */
|
|
3855
|
+
max?: number
|
|
3856
|
+
}
|
|
3857
|
+
|
|
3858
|
+
/** 範囲 `span` を 10 本ほどの階級に分ける、区切りのよい幅。 */
|
|
3859
|
+
function niceBinWidth(span: number, target = 10): number {
|
|
3860
|
+
if (!(span > 0) || !Number.isFinite(span)) return 1
|
|
3861
|
+
const raw = span / target
|
|
3862
|
+
const pow = 10 ** Math.floor(Math.log10(raw))
|
|
3863
|
+
const f = raw / pow
|
|
3864
|
+
return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * pow
|
|
3865
|
+
}
|
|
3866
|
+
|
|
3867
|
+
/** 階級数の上限(上限超えの階級を除く)。幅が細かすぎて超えるときは、幅を広げて収める。 */
|
|
3868
|
+
const MAX_BINS = 200
|
|
3869
|
+
|
|
3870
|
+
/** 小数の誤差(0.1 を 3 回足すなど)を、幅の桁に合わせて丸める。固定桁だと微小な幅が 0 に潰れて前に進まない。 */
|
|
3871
|
+
function tidy(n: number, step: number): number {
|
|
3872
|
+
const digits = Math.min(100, Math.max(0, Math.ceil(-Math.log10(step)) + 6))
|
|
3873
|
+
const rounded = Number(n.toFixed(digits))
|
|
3874
|
+
return Number.isFinite(rounded) ? rounded : n
|
|
3875
|
+
}
|
|
3876
|
+
|
|
3877
|
+
/**
|
|
3878
|
+
* 値の配列 → 階級ごとの個数。値が 1 つも無ければ `[]`。
|
|
3879
|
+
* `max` を指定すると、`start` から `max` までを幅で刻み(割り切れない端は最後の階級を短くする)、`max` 以上の値を末尾の上限超え階級にまとめる。
|
|
3880
|
+
* 個数が 0 の階級も省かない(間が空いていることが分布の事実のため)。上限超えは 0 件なら作らない。
|
|
3881
|
+
* 階級は添字から数える(`MAX_BINS` 本まで)ので、どんな値でも必ず有限回で終わる。幅が細かすぎて `MAX_BINS` を超えるときは幅を広げる。
|
|
3882
|
+
*/
|
|
3883
|
+
function histogramBins(values: readonly unknown[], config: HistogramBinsConfig = {}): HistogramBin[] {
|
|
3884
|
+
const sorted = sortedNumbers(values)
|
|
3885
|
+
if (sorted.length === 0) return []
|
|
3886
|
+
const width = config.binWidth !== undefined && Number.isFinite(config.binWidth) && config.binWidth > 0 ? config.binWidth : null
|
|
3887
|
+
const lo = sorted[0]!
|
|
3888
|
+
const hi = sorted[sorted.length - 1]!
|
|
3889
|
+
const cap = config.max !== undefined && Number.isFinite(config.max) ? config.max : null
|
|
3890
|
+
const end = cap !== null ? cap : hi
|
|
3891
|
+
const first = config.start !== undefined && Number.isFinite(config.start) ? config.start : null
|
|
3892
|
+
let step = width ?? niceBinWidth((cap !== null ? Math.min(hi, cap) : hi) - (first ?? lo))
|
|
3893
|
+
const start = first ?? tidy(Math.floor(lo / step) * step, step)
|
|
3894
|
+
const countFor = (w: number) => Math.ceil((end - start) / w - 1e-9)
|
|
3895
|
+
// 範囲が空(全部が上限以上など)でも、上限超えの階級だけは作る。上限なしなら最低 1 本は作る。
|
|
3896
|
+
if (countFor(step) > MAX_BINS) step = niceBinWidth(end - start, MAX_BINS)
|
|
3897
|
+
const n = Math.min(MAX_BINS, Math.max(cap === null ? 1 : 0, countFor(step)))
|
|
3898
|
+
const bins: HistogramBin[] = []
|
|
3899
|
+
for (let i = 0; i < n; i++) {
|
|
3900
|
+
const from = i === 0 ? start : bins[i - 1]!.to
|
|
3901
|
+
let to = tidy(start + (i + 1) * step, step)
|
|
3902
|
+
if (!(to > from)) to = start + (i + 1) * step
|
|
3903
|
+
if (cap !== null) to = Math.min(to, cap)
|
|
3904
|
+
bins.push({ from, to, count: 0, overflow: false })
|
|
3905
|
+
}
|
|
3906
|
+
const inRange = cap === null ? sorted : sorted.filter((v) => v < cap)
|
|
3907
|
+
const over = cap === null ? [] : sorted.filter((v) => v >= cap)
|
|
3908
|
+
for (const v of inRange) {
|
|
3909
|
+
if (v < start || bins.length === 0) continue
|
|
3910
|
+
const i = Math.min(bins.length - 1, Math.floor((v - start) / step + 1e-9))
|
|
3911
|
+
bins[i]!.count += 1
|
|
3912
|
+
}
|
|
3913
|
+
if (over.length > 0) bins.push({ from: cap!, to: Math.max(hi, cap!), count: over.length, overflow: true })
|
|
3914
|
+
return bins
|
|
3915
|
+
}
|
|
3916
|
+
|
|
3917
|
+
/* ---------- end of inlined code ---------- */
|
|
3918
|
+
|
|
3919
|
+
export interface BoxPlotGroup {
|
|
3920
|
+
/** 箱の名前(横軸)。 */
|
|
3921
|
+
name: string
|
|
3922
|
+
/** 生の値の配列。number か数値文字列。null・数にならない値は数えない。 */
|
|
3923
|
+
values: unknown[]
|
|
3924
|
+
}
|
|
3925
|
+
|
|
3926
|
+
export interface BoxPlotChartProps extends Omit<ChartCommonProps, "data" | "index" | "categories" | "colors" | "labels" | "summary"> {
|
|
3927
|
+
/** 群ごとの値。並びがそのまま左から右の順。 */
|
|
3928
|
+
groups: BoxPlotGroup[]
|
|
3929
|
+
/** ひげの長さ(四分位範囲の何倍までを外れ値にしないか)。既定 1.5。 */
|
|
3930
|
+
whisker?: number
|
|
3931
|
+
/** 値(縦軸)の名前。ツールチップとデータ表に出る。既定「値」。例「残業時間」 */
|
|
3932
|
+
valueLabel?: string
|
|
3933
|
+
/** 1 文要約(自由文)。`"auto"` なら中央値が最大・最小の群と外れ値の数を組む。省略時は要約なし。 */
|
|
3934
|
+
summary?: string | "auto"
|
|
3935
|
+
/** ホバー時のツールチップを出す。既定 `true`。 */
|
|
3936
|
+
showTooltip?: boolean
|
|
3937
|
+
}
|
|
3938
|
+
|
|
3939
|
+
/* ------------------------------------------------------------------ model */
|
|
3940
|
+
|
|
3941
|
+
const TEXT = {
|
|
3942
|
+
ja: {
|
|
3943
|
+
value: "値",
|
|
3944
|
+
valueInSentence: "値",
|
|
3945
|
+
medianOf: (name: string, label: string, median: string) => `${name}の${label}の中央値は ${median}`,
|
|
3946
|
+
medianRange: (label: string, top: string, topMedian: string, low: string, lowMedian: string) =>
|
|
3947
|
+
`${label}の中央値が最も高いのは ${top}(${topMedian})、最も低いのは ${low}(${lowMedian})`,
|
|
3948
|
+
outliers: (n: number) => `外れ値は ${n} 件`,
|
|
3949
|
+
sentenceJoin: "。",
|
|
3950
|
+
columns: ["群", "件数", "最小(ひげ)", "第1四分位", "中央値", "第3四分位", "最大(ひげ)", "外れ値"],
|
|
3951
|
+
listJoin: "、",
|
|
3952
|
+
none: "なし",
|
|
3953
|
+
tooltipTitle: (name: string, label: string, count: number) => `${name}(${label}・${count}件)`,
|
|
3954
|
+
max: "最大(ひげ)",
|
|
3955
|
+
q3: "第3四分位",
|
|
3956
|
+
median: "中央値",
|
|
3957
|
+
q1: "第1四分位",
|
|
3958
|
+
min: "最小(ひげ)",
|
|
3959
|
+
outlierRow: "外れ値",
|
|
3960
|
+
chart: (label: string) => `${label}の箱ひげ図`,
|
|
3961
|
+
},
|
|
3962
|
+
en: {
|
|
3963
|
+
value: "Value",
|
|
3964
|
+
valueInSentence: "value",
|
|
3965
|
+
medianOf: (name: string, label: string, median: string) => `Median ${label} for ${name}: ${median}`,
|
|
3966
|
+
medianRange: (label: string, top: string, topMedian: string, low: string, lowMedian: string) =>
|
|
3967
|
+
`Highest median ${label}: ${top} (${topMedian}); lowest: ${low} (${lowMedian})`,
|
|
3968
|
+
outliers: (n: number) => (n === 1 ? "1 outlier" : `${n} outliers`),
|
|
3969
|
+
sentenceJoin: ". ",
|
|
3970
|
+
columns: ["Group", "Count", "Min (whisker)", "Q1", "Median", "Q3", "Max (whisker)", "Outliers"],
|
|
3971
|
+
listJoin: ", ",
|
|
3972
|
+
none: "None",
|
|
3973
|
+
tooltipTitle: (name: string, label: string, count: number) => `${name} (${label}, n=${count})`,
|
|
3974
|
+
max: "Max (whisker)",
|
|
3975
|
+
q3: "Q3",
|
|
3976
|
+
median: "Median",
|
|
3977
|
+
q1: "Q1",
|
|
3978
|
+
min: "Min (whisker)",
|
|
3979
|
+
outlierRow: "Outliers",
|
|
3980
|
+
chart: (label: string) => `Box plot of ${label}`,
|
|
3981
|
+
},
|
|
3982
|
+
}
|
|
3983
|
+
|
|
3984
|
+
const textOf = (locale?: string) => TEXT[uiLanguage(resolveLocale(locale))]
|
|
3985
|
+
|
|
3986
|
+
export interface BoxPlotEntry {
|
|
3987
|
+
name: string
|
|
3988
|
+
stats: BoxStats | null
|
|
3989
|
+
}
|
|
3990
|
+
|
|
3991
|
+
/** Groups → one entry each, in order. */
|
|
3992
|
+
export function boxPlotEntries(groups: readonly BoxPlotGroup[], whisker?: number): BoxPlotEntry[] {
|
|
3993
|
+
return groups.map((g) => ({ name: g.name, stats: boxStats(g.values, whisker) }))
|
|
3994
|
+
}
|
|
3995
|
+
|
|
3996
|
+
/**
|
|
3997
|
+
* `summary="auto"`: the groups with the highest / lowest median and the outlier count. `undefined` with no usable group.
|
|
3998
|
+
* `locale` picks the language; default the page's (`<html lang>`).
|
|
3999
|
+
*/
|
|
4000
|
+
export function buildBoxPlotSummary(
|
|
4001
|
+
entries: readonly BoxPlotEntry[],
|
|
4002
|
+
formatter: ValueFormatter,
|
|
4003
|
+
valueLabel?: string,
|
|
4004
|
+
locale?: string,
|
|
4005
|
+
): string | undefined {
|
|
4006
|
+
const t = textOf(locale)
|
|
4007
|
+
const label = valueLabel ?? t.valueInSentence
|
|
4008
|
+
const real = entries.filter((e): e is BoxPlotEntry & { stats: BoxStats } => e.stats !== null)
|
|
4009
|
+
if (real.length === 0) return undefined
|
|
4010
|
+
const top = real.reduce((a, b) => (b.stats.median > a.stats.median ? b : a))
|
|
4011
|
+
const low = real.reduce((a, b) => (b.stats.median < a.stats.median ? b : a))
|
|
4012
|
+
const parts = [
|
|
4013
|
+
real.length === 1
|
|
4014
|
+
? t.medianOf(top.name, label, formatter(top.stats.median))
|
|
4015
|
+
: t.medianRange(label, top.name, formatter(top.stats.median), low.name, formatter(low.stats.median)),
|
|
4016
|
+
]
|
|
4017
|
+
const outliers = real.reduce((sum, e) => sum + e.stats.outliers.length, 0)
|
|
4018
|
+
if (outliers > 0) parts.push(t.outliers(outliers))
|
|
4019
|
+
return parts.join(t.sentenceJoin)
|
|
4020
|
+
}
|
|
4021
|
+
|
|
4022
|
+
/** The screen-reader table: one row per group with n, the quartiles, the whisker ends and the outliers. */
|
|
4023
|
+
export function boxPlotDataTable(entries: readonly BoxPlotEntry[], formatter: ValueFormatter, locale?: string): ChartDataTable {
|
|
4024
|
+
const t = textOf(locale)
|
|
4025
|
+
const f = (n: number | undefined) => (n === undefined ? EMPTY_VALUE : formatter(n))
|
|
4026
|
+
return {
|
|
4027
|
+
columns: [...t.columns],
|
|
4028
|
+
rows: entries.map(({ name, stats: s }) => [
|
|
4029
|
+
name,
|
|
4030
|
+
s ? `${s.count}` : EMPTY_VALUE,
|
|
4031
|
+
f(s?.whiskerLow),
|
|
4032
|
+
f(s?.q1),
|
|
4033
|
+
f(s?.median),
|
|
4034
|
+
f(s?.q3),
|
|
4035
|
+
f(s?.whiskerHigh),
|
|
4036
|
+
s ? (s.outliers.length > 0 ? s.outliers.map(formatter).join(t.listJoin) : t.none) : EMPTY_VALUE,
|
|
4037
|
+
]),
|
|
4038
|
+
}
|
|
4039
|
+
}
|
|
4040
|
+
|
|
4041
|
+
/* ----------------------------------------------------------------- option */
|
|
4042
|
+
|
|
4043
|
+
export interface BoxPlotOptionConfig {
|
|
4044
|
+
entries: readonly BoxPlotEntry[]
|
|
4045
|
+
/** Resolved (canvas-safe) colour of the boxes; `""` leaves the theme palette. */
|
|
4046
|
+
color: string
|
|
4047
|
+
valueFormatter: ValueFormatter
|
|
4048
|
+
axisFormatter?: ValueFormatter
|
|
4049
|
+
valueLabel?: string
|
|
4050
|
+
showTooltip?: boolean
|
|
4051
|
+
labelColor?: string
|
|
4052
|
+
chartOptions?: EChartsOption
|
|
4053
|
+
/** Language of the tooltip. Default the page's locale (`<html lang>`). */
|
|
4054
|
+
locale?: string
|
|
4055
|
+
}
|
|
4056
|
+
|
|
4057
|
+
const ROW_STYLE = "display:flex;align-items:center;gap:8px;line-height:20px"
|
|
4058
|
+
|
|
4059
|
+
/** Fraction of a category band the box fills. */
|
|
4060
|
+
const BOX_SHARE = 0.4
|
|
4061
|
+
|
|
4062
|
+
/** The `renderItem` of the boxes: whiskers with end caps, the box, the median line and the outlier dots. */
|
|
4063
|
+
/** `outliers` は元の群の順(空の群も含む)。描く箱は `api.value(0)` の群の添字で引く(空の群を除いても、ずれない)。 */
|
|
4064
|
+
export function boxPlotRenderer(color: string, outliers: readonly (readonly number[])[]) {
|
|
4065
|
+
type Api = { value(dim: number): number; coord(value: number[]): number[]; size(value: number[]): number[] }
|
|
4066
|
+
return (_params: unknown, api: Api) => {
|
|
4067
|
+
const x = api.coord([api.value(0), api.value(3)])[0] ?? 0
|
|
4068
|
+
const y = (dim: number) => api.coord([api.value(0), api.value(dim)])[1] ?? 0
|
|
4069
|
+
const band = Math.abs(api.size([1, 0])[0] ?? 0)
|
|
4070
|
+
const half = (band * BOX_SHARE) / 2
|
|
4071
|
+
const cap = half / 2
|
|
4072
|
+
const [yLow, yQ1, yMed, yQ3, yHigh] = [y(1), y(2), y(3), y(4), y(5)] as [number, number, number, number, number]
|
|
4073
|
+
const stroke = { stroke: color, lineWidth: 1.5, fill: "none" }
|
|
4074
|
+
const line = (x1: number, y1: number, x2: number, y2: number) => ({ type: "line" as const, shape: { x1, y1, x2, y2 }, style: stroke })
|
|
4075
|
+
return {
|
|
4076
|
+
type: "group" as const,
|
|
4077
|
+
children: [
|
|
4078
|
+
line(x, yHigh, x, yQ3),
|
|
4079
|
+
line(x, yQ1, x, yLow),
|
|
4080
|
+
line(x - cap, yHigh, x + cap, yHigh),
|
|
4081
|
+
line(x - cap, yLow, x + cap, yLow),
|
|
4082
|
+
{
|
|
4083
|
+
type: "rect" as const,
|
|
4084
|
+
shape: { x: x - half, y: Math.min(yQ3, yQ1), width: half * 2, height: Math.abs(yQ1 - yQ3), r: 2 },
|
|
4085
|
+
style: { fill: withAlpha(color, 0.25), stroke: color, lineWidth: 1.5 },
|
|
4086
|
+
},
|
|
4087
|
+
line(x - half, yMed, x + half, yMed),
|
|
4088
|
+
...(outliers[api.value(0)] ?? []).map((v) => ({
|
|
4089
|
+
type: "circle" as const,
|
|
4090
|
+
shape: { cx: x, cy: api.coord([api.value(0), v])[1] ?? 0, r: 3 },
|
|
4091
|
+
style: { fill: "transparent", stroke: color, lineWidth: 1.5 },
|
|
4092
|
+
})),
|
|
4093
|
+
],
|
|
4094
|
+
}
|
|
4095
|
+
}
|
|
4096
|
+
}
|
|
4097
|
+
|
|
4098
|
+
/** The ECharts option: one `custom` series, a box per group. Groups with no value draw nothing. */
|
|
4099
|
+
export function buildBoxPlotOption(config: BoxPlotOptionConfig): EChartsOption {
|
|
4100
|
+
const t = textOf(config.locale)
|
|
4101
|
+
const { entries, valueFormatter, showTooltip = true, valueLabel = t.value } = config
|
|
4102
|
+
const axisFormatter = config.axisFormatter ?? valueFormatter
|
|
4103
|
+
const color = config.color || "#888"
|
|
4104
|
+
// [index, whisker low, Q1, median, Q3, whisker high, min, max]: the last two stretch the value axis over the outliers.
|
|
4105
|
+
const data = entries.flatMap((e, i) => (e.stats ? [[i, e.stats.whiskerLow, e.stats.q1, e.stats.median, e.stats.q3, e.stats.whiskerHigh, e.stats.min, e.stats.max]] : []))
|
|
4106
|
+
const entryAt = (i: number) => entries[i]
|
|
4107
|
+
const option = {
|
|
4108
|
+
...chartMotion(false),
|
|
4109
|
+
legend: { show: false },
|
|
4110
|
+
grid: { top: 16, right: 16, bottom: 4, left: 4, containLabel: true },
|
|
4111
|
+
tooltip: {
|
|
4112
|
+
show: showTooltip,
|
|
4113
|
+
trigger: "item",
|
|
4114
|
+
formatter: (params: unknown) => {
|
|
4115
|
+
const entry = entryAt((params as { value?: number[] }).value?.[0] ?? -1)
|
|
4116
|
+
const s = entry?.stats
|
|
4117
|
+
if (!entry || !s) return ""
|
|
4118
|
+
const line = (name: string, text: string) =>
|
|
4119
|
+
`<div style="${ROW_STYLE}"><span style="flex:1;opacity:.8">${escapeHtml(name)}</span>` +
|
|
4120
|
+
`<span style="font-weight:500;font-variant-numeric:tabular-nums;margin-left:12px">${escapeHtml(text)}</span></div>`
|
|
4121
|
+
return (
|
|
4122
|
+
`<div style="font-weight:500;margin-bottom:4px">${escapeHtml(t.tooltipTitle(entry.name, valueLabel, s.count))}</div>` +
|
|
4123
|
+
line(t.max, valueFormatter(s.whiskerHigh)) +
|
|
4124
|
+
line(t.q3, valueFormatter(s.q3)) +
|
|
4125
|
+
line(t.median, valueFormatter(s.median)) +
|
|
4126
|
+
line(t.q1, valueFormatter(s.q1)) +
|
|
4127
|
+
line(t.min, valueFormatter(s.whiskerLow)) +
|
|
4128
|
+
(s.outliers.length > 0 ? line(t.outlierRow, s.outliers.map(valueFormatter).join(t.listJoin)) : "")
|
|
4129
|
+
)
|
|
4130
|
+
},
|
|
4131
|
+
},
|
|
4132
|
+
xAxis: { type: "category" as const, data: entries.map((e) => e.name), axisTick: { show: false }, axisLabel: { interval: 0, hideOverlap: false } },
|
|
4133
|
+
yAxis: {
|
|
4134
|
+
type: "value" as const,
|
|
4135
|
+
axisLine: { show: false },
|
|
4136
|
+
axisTick: { show: false },
|
|
4137
|
+
splitLine: { show: true },
|
|
4138
|
+
axisLabel: { formatter: (v: number) => axisFormatter(v) },
|
|
4139
|
+
},
|
|
4140
|
+
series: [
|
|
4141
|
+
{
|
|
4142
|
+
id: "box",
|
|
4143
|
+
type: "custom" as const,
|
|
4144
|
+
encode: { x: 0, y: [1, 2, 3, 4, 5, 6, 7] },
|
|
4145
|
+
data,
|
|
4146
|
+
renderItem: boxPlotRenderer(color, entries.map((e) => e.stats?.outliers ?? [])),
|
|
4147
|
+
},
|
|
4148
|
+
],
|
|
4149
|
+
}
|
|
4150
|
+
return mergeChartOptions(option as EChartsOption, config.chartOptions)
|
|
4151
|
+
}
|
|
4152
|
+
|
|
4153
|
+
/* -------------------------------------------------------------- component */
|
|
4154
|
+
|
|
4155
|
+
const NO_GROUPS: never[] = []
|
|
4156
|
+
|
|
4157
|
+
export const BoxPlotChart = forwardRef(function BoxPlotChart(
|
|
4158
|
+
{
|
|
4159
|
+
groups = NO_GROUPS,
|
|
4160
|
+
whisker,
|
|
4161
|
+
valueLabel,
|
|
4162
|
+
format,
|
|
4163
|
+
valueFormatter: valueFormatterProp,
|
|
4164
|
+
showTooltip = true,
|
|
4165
|
+
title,
|
|
4166
|
+
summary,
|
|
4167
|
+
actions,
|
|
4168
|
+
fileName,
|
|
4169
|
+
isLoading,
|
|
4170
|
+
emptyState,
|
|
4171
|
+
height,
|
|
4172
|
+
chartOptions,
|
|
4173
|
+
ariaLabel,
|
|
4174
|
+
className,
|
|
4175
|
+
...rest
|
|
4176
|
+
}: BoxPlotChartProps,
|
|
4177
|
+
ref: ForwardedRef<HTMLDivElement>,
|
|
4178
|
+
) {
|
|
4179
|
+
const { ref: frameRef, tokens } = useChartSurface(ref)
|
|
4180
|
+
const locale = useLocale()
|
|
4181
|
+
const t = TEXT[uiLanguage(locale)]
|
|
4182
|
+
const valueFormatter = useMemo(() => resolveValueFormatter(valueFormatterProp, format, locale), [valueFormatterProp, format, locale])
|
|
4183
|
+
const entries = useMemo(() => boxPlotEntries(groups, whisker), [groups, whisker])
|
|
4184
|
+
const [color = ""] = useMemo(() => resolveChartColors(["chart-1"], tokens), [tokens])
|
|
4185
|
+
const option = useMemo(
|
|
4186
|
+
() => buildBoxPlotOption({ entries, color, valueFormatter, valueLabel, showTooltip, labelColor: tokens?.foreground ?? undefined, chartOptions, locale }),
|
|
4187
|
+
[entries, color, valueFormatter, valueLabel, showTooltip, tokens, chartOptions, locale],
|
|
4188
|
+
)
|
|
4189
|
+
const dataTable = useMemo(() => boxPlotDataTable(entries, valueFormatter, locale), [entries, valueFormatter, locale])
|
|
4190
|
+
const resolvedSummary = useMemo(
|
|
4191
|
+
() => (summary === "auto" ? buildBoxPlotSummary(entries, valueFormatter, valueLabel, locale) : summary),
|
|
4192
|
+
[summary, entries, valueFormatter, valueLabel, locale],
|
|
4193
|
+
)
|
|
4194
|
+
const label = ariaLabel ?? t.chart(valueLabel ?? t.valueInSentence)
|
|
4195
|
+
return (
|
|
4196
|
+
<ChartFrame
|
|
4197
|
+
{...chartRootProps(rest)}
|
|
4198
|
+
ref={frameRef}
|
|
4199
|
+
title={title}
|
|
4200
|
+
summary={resolvedSummary}
|
|
4201
|
+
isLoading={isLoading ?? false}
|
|
4202
|
+
isEmpty={entries.length === 0}
|
|
4203
|
+
emptyState={emptyState}
|
|
4204
|
+
height={height}
|
|
4205
|
+
variant="bar"
|
|
4206
|
+
ariaLabel={label}
|
|
4207
|
+
className={className}
|
|
4208
|
+
dataTable={dataTable}
|
|
4209
|
+
>
|
|
4210
|
+
<EChart option={option} height="100%" ariaLabel={label} actions={actions} fileName={fileName} exportHeader={{ title, summary: resolvedSummary }} />
|
|
4211
|
+
</ChartFrame>
|
|
4212
|
+
)
|
|
4213
|
+
})
|
|
4214
|
+
BoxPlotChart.displayName = "BoxPlotChart"
|