Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(quill-charts): add a gauge chart (#123010)

Sam Pennington58373b17db18
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6f92403c3002..89f201ed65bb 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1176,6 +1176,50 @@ snapshots:
hash: v1.k794b7964.442798f2e600069a7d91562610b8b7c7d3a4056ac586377a06dac861281fe95f.bESiPj85ewuYoqwKk98dJdyqFQEiE0ObW8p3BH9V6yw
components-hogcharts-funnelchart--with-step-footer--light:
hash: v1.k794b7964.0bf7642c300b844208cbb1fb7a17fbf96eb0222026882205f6d7cecebc88008a.6iZXA9vx-lh-6uP8V86vyU4_pyGgidZCpHGKj3IMQaI
+ components-hogcharts-gauge--basic--dark:
+ hash: v1.k794b7964.5977428a234205ef5ddd57ab8db0c38602d7887ae2f3e0f2180cab21cf65a501.9c64y4X8zXeYgHcJCMc_bK-b_ifbNFEbxSuqXoq2xp0
+ components-hogcharts-gauge--basic--light:
+ hash: v1.k794b7964.056cec58ea4363f088bb547b1f0bb504a4feb0da8520de55801141f08998a31e.s4qGktkWhSnuPsitdcYXYphwkEtWaOMGIyvNKNh7u3E
+ components-hogcharts-gauge--durations--dark:
+ hash: v1.k794b7964.157d68b5af945ba7d23084d244afe1747388c3986735179202589d2a2e3de6fd.Nnwg0IzgnnBN9uMjVW1YGmr1cmtblqGU2tJL6ih62ZU
+ components-hogcharts-gauge--durations--light:
+ hash: v1.k794b7964.d1423a503ffeb9b53fe2d1a3bf21d738f2a9bf50b64b210aed0c8e7e02d3edfa.blaJc52cgyz8TDEM77zL3fJwt3MuToMxvRr_s2gMepo
+ components-hogcharts-gauge--edge-cases--dark:
+ hash: v1.k794b7964.fcc787fa200dc41797225f109c2f5d03ed074015349c9c001993c0f3c5a04ab9.TNIU3OU0UyiL2xd6PjszTI3uUcpaeo2f-YsKy9O34As
+ components-hogcharts-gauge--edge-cases--light:
+ hash: v1.k794b7964.65f2523baabcad45a6bb04dd640a414d155d299e128621dd7141383eb16b7d75.NS5n7gKV4_vcHy7DsV5zxKFANDqChotmz7uvumFKUBU
+ components-hogcharts-gauge--grid-of-twelve--dark:
+ hash: v1.k794b7964.6e092ae513aa34ee7c153b55fe9f214a2039f3e47e6a38672703e21730ed16af.pb9txmRrKvASDf3AjD0T_tp5H5t9fyY_IrKDfnqasEk
+ components-hogcharts-gauge--grid-of-twelve--light:
+ hash: v1.k794b7964.ca8e75eb4bd5dd06e2ea5f5fa2b9437fca00b0f05703919d54169c9245732ca3.uX9Iu-y2krnDA1hy7kxXc_4dE0GPlGSi01yBEwIv4h0
+ components-hogcharts-gauge--large--dark:
+ hash: v1.k794b7964.cfa12d9bcd5d9686301b8333cb9c590b5cf8c664be771ecf578e732467734ee9.jOjp8mv2kBkvLgmxF01giOqkWtez-TSSGqH8YKukW_E
+ components-hogcharts-gauge--large--light:
+ hash: v1.k794b7964.29f037960574c9d02d8fc959239d67bb38d6a656bd9048b77b36a16ac7788625.zxTNWketLpsB3HCC36J_v0tcDK80GxKmYh3KiDSWwys
+ components-hogcharts-gauge--null-value--dark:
+ hash: v1.k794b7964.294395f6e9b84059366fc1223c3058affad500434bc1abbf8ad5f042e2e69a1e.p89DruXiXK99ni1VGhoTMgnNwWCXDN5Q6iUlNRxoqPY
+ components-hogcharts-gauge--null-value--light:
+ hash: v1.k794b7964.62efe95049c14e656548d6bddb255b74759b26fcd8c2505f63421d53a402653f.lMKhZCvN9Pdq_y0p6VmbuuMfdPezWN_qHWJABlrlhQs
+ components-hogcharts-gauge--shapes--dark:
+ hash: v1.k794b7964.ce7b34f73cfcc246acba08b43e658689a35d154552713dacde585572745d7531.XFpxNSVrTqWaGa0ezR86Q7aGPQYywlIr6zGUpTTdtmo
+ components-hogcharts-gauge--shapes--light:
+ hash: v1.k794b7964.dc16cfd81fbb67f6ef680dd2490a453358e55ac5cbf414d9e070390e1e4598ec.jvxWjeoIVL0xf6xrPf2DmcQ-mCDI5fwFQ-_x8CpHknE
+ components-hogcharts-gauge--target-marker--dark:
+ hash: v1.k794b7964.c0841d3829a48aaeafb5099339c0fb8a088140fb40d67421046aad0589f0a7a0.dlZR1-rxVHFl8l5VTVcw0Qushi0JlKg-fdCfGDW7IJI
+ components-hogcharts-gauge--target-marker--light:
+ hash: v1.k794b7964.6fcbc46f159116b45aa88307e19c0d5986ea0efda5bb44c6b8675ce7e6440360.162gsHDCPb7lyp56-CmR-IJFvaJvbgg6B81cnNU4dyI
+ components-hogcharts-gauge--thresholds--dark:
+ hash: v1.k794b7964.d4a603a1d428d0811682877d09ed6a5a1d6b576e930acad6f1b9542ff7dcbad3.9uQuF1Ygns-Xr_5htyTu5lCxWMWm3W5K_gH8BzvQrWA
+ components-hogcharts-gauge--thresholds--light:
+ hash: v1.k794b7964.630b94158a87e2a863dd8e56d73bfaf86a8429ff0160d1d334053914dd3e2fee.iMkWOShKEEygZ8NKEO-gxGsTNXGrsWP0_T-MxtEUZfQ
+ components-hogcharts-gauge--thresholds-hovered--dark:
+ hash: v1.k794b7964.5e3eed8dda023b5d4d0befba62d1ccbc1a7b7f0ca51ebeb6ecaf860f9f78a6b1.VMTP6Cahkngs5F3yaaDlahQOgsNnj1h8Yj_94mKeGcw
+ components-hogcharts-gauge--thresholds-hovered--light:
+ hash: v1.k794b7964.6ae45f937e62cd3e6c5e461955f7afbb281a391b252c2074d54c0e6fb3b247f8.VSjarUuYZrtYgnlQJ4Jsn8XwbiivKwM52a-J9amOvzk
+ components-hogcharts-gauge--tiny--dark:
+ hash: v1.k794b7964.2ae2b84721826c246bacd48ec3984c5151b44a1d46d71527ac3c615af836eb13.J4Jfh-RLMeXYndv9q9_ZSpszdxjNl4IvoGcNEOgpFlI
+ components-hogcharts-gauge--tiny--light:
+ hash: v1.k794b7964.d701f322fc227cdb6786a224a397ce37ce36a78be1a56a473b6c35f0b1afe51d.RUdH-TVQ5z9FPRaJHJD_zt-CbDtMdVIcb2EIKyVv9AM
components-hogcharts-highlightedrange--mirroring-drag-selection--dark:
hash: v1.k794b7964.6cabdb75668a4e0d83c77a0efc5d955045cf29752863b13587974b387194f2f1.10_3SllxBWGEb3SJCvNqQjJgB4Smu1SGPftAkKoft34
components-hogcharts-highlightedrange--mirroring-drag-selection--light:
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 6f28ff8c9de5..c69e4291fae5 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -26,6 +26,7 @@ This file is the map. Prop-level semantics live in the JSDoc on the config and p
| `SlopeChart` | Change between two points — one line per series, `data: [start, end]` |
| `Sparkline` | Tiny inline trend, no axes — gradient line or stacked bars; tooltip off by default |
| `MetricCard` | Headline number + sparkline + change pill (dashboard stat tiles) |
+| `Gauge` | One value against a min and max, colored by thresholds (Apdex, error budget, CPU); optional target tick |
Share of total over time takes a time-series chart in its 100% form: `TimeSeriesLineChart` with `fill` series and `percentStackView` for a stacked area, or `TimeSeriesBarChart` with `barLayout: 'percent'` for bars.
Pick the one that matches the design you are copying.
@@ -110,18 +111,18 @@ Import helpers from `@posthog/quill-charts/testing` (jsdom only): `setupChartTes
## Docs index
-| Doc | Covers |
-| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
-| [src/README.md](./src/README.md) | Public surface, setup, theme, custom tooltip and overlay basics, sparkline |
-| [docs/chart-types.md](./src/docs/chart-types.md) | Per-chart behavior: scatter, funnel, slope, pie, proportion bar, bar list, box plot, heatmap, sankey, sparkline, metric card |
-| [docs/axes.md](./src/docs/axes.md) | Defaults, grid and axis chrome, x-axis labels, y format, baseline and range, multi-axis, margins, blank-plot diagnosis |
-| [docs/bars.md](./src/docs/bars.md) | Layouts, per-bar overrides, `minBarSize`, `trackData`, hit-testing, trend lines, combo |
-| [docs/tooltips.md](./src/docs/tooltips.md) | `config.tooltip`, `DefaultTooltip` props, custom pieces, context fields, touch |
-| [docs/legend.md](./src/docs/legend.md) | Click model, controlled state, visibility groups, row rendering, layout caps |
-| [docs/overlays.md](./src/docs/overlays.md) | Built-in overlays and writing a custom one |
-| [docs/interactions.md](./src/docs/interactions.md) | Clicks, drag-to-zoom, 2D brush, hover |
-| [docs/CONTRIBUTING.md](./src/docs/CONTRIBUTING.md) | Layers, conventions, adding a chart type |
-| [docs/TESTING.md](./src/docs/TESTING.md) | The accessor contract and test recipes |
+| Doc | Covers |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
+| [src/README.md](./src/README.md) | Public surface, setup, theme, custom tooltip and overlay basics, sparkline |
+| [docs/chart-types.md](./src/docs/chart-types.md) | Per-chart behavior: scatter, funnel, slope, pie, proportion bar, bar list, box plot, heatmap, sankey, gauge, sparkline, metric card |
+| [docs/axes.md](./src/docs/axes.md) | Defaults, grid and axis chrome, x-axis labels, y format, baseline and range, multi-axis, margins, blank-plot diagnosis |
+| [docs/bars.md](./src/docs/bars.md) | Layouts, per-bar overrides, `minBarSize`, `trackData`, hit-testing, trend lines, combo |
+| [docs/tooltips.md](./src/docs/tooltips.md) | `config.tooltip`, `DefaultTooltip` props, custom pieces, context fields, touch |
+| [docs/legend.md](./src/docs/legend.md) | Click model, controlled state, visibility groups, row rendering, layout caps |
+| [docs/overlays.md](./src/docs/overlays.md) | Built-in overlays and writing a custom one |
+| [docs/interactions.md](./src/docs/interactions.md) | Clicks, drag-to-zoom, 2D brush, hover |
+| [docs/CONTRIBUTING.md](./src/docs/CONTRIBUTING.md) | Layers, conventions, adding a chart type |
+| [docs/TESTING.md](./src/docs/TESTING.md) | The accessor contract and test recipes |
## Maintenance
diff --git a/packages/quill/packages/charts/src/README.md b/packages/quill/packages/charts/src/README.md
index 1a0df0ba59bf..45ad7fc0e3b3 100644
--- a/packages/quill/packages/charts/src/README.md
+++ b/packages/quill/packages/charts/src/README.md
@@ -147,7 +147,7 @@ import { Sparkline } from '@posthog/quill-charts'
## More
- Choosing a chart, the gotchas, and the docs index → [AGENTS.md](../AGENTS.md)
-- Per-chart behavior (scatter, funnel, slope, pie, proportion bar, box plot, heatmap, sankey, sparkline, metric card) → [docs/chart-types.md](./docs/chart-types.md)
+- Per-chart behavior (scatter, funnel, slope, pie, proportion bar, box plot, heatmap, sankey, gauge, sparkline, metric card) → [docs/chart-types.md](./docs/chart-types.md)
- Axes, ranges, multi-axis, chrome → [docs/axes.md](./docs/axes.md)
- Bars: layouts, per-bar overrides, `minBarSize`, `trackData` → [docs/bars.md](./docs/bars.md)
- Tooltips → [docs/tooltips.md](./docs/tooltips.md); legend → [docs/legend.md](./docs/legend.md)
diff --git a/packages/quill/packages/charts/src/charts/Gauge/Gauge.stories.tsx b/packages/quill/packages/charts/src/charts/Gauge/Gauge.stories.tsx
new file mode 100644
index 000000000000..03fc1ce3b424
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Gauge/Gauge.stories.tsx
@@ -0,0 +1,284 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useEffect, useState } from 'react'
+
+import { playHoverAtFraction, Stage, useReactiveTheme } from '../../story-helpers'
+import { buildYTickFormatter } from '../../utils/y-formatters'
+import { Gauge } from './Gauge'
+import type { GaugeThreshold } from './gauge-layout'
+
+const HEALTH: GaugeThreshold[] = [
+ { value: 0, color: 'var(--data-color-7)', label: 'Healthy' },
+ { value: 70, color: 'var(--data-color-13)', label: 'Busy' },
+ { value: 90, color: 'var(--data-color-5)', label: 'Saturated' },
+]
+
+const APDEX: GaugeThreshold[] = [
+ { value: 0, color: 'var(--data-color-5)', label: 'Poor' },
+ { value: 0.7, color: 'var(--data-color-13)', label: 'Fair' },
+ { value: 0.85, color: 'var(--data-color-7)', label: 'Good' },
+]
+
+const meta: Meta = { title: 'Components/HogCharts/Gauge', parameters: { layout: 'centered' } }
+export default meta
+
+type Story = StoryObj<{}>
+
+export const Basic: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={320} height={240}>
+ <Gauge value={42} min={0} max={100} theme={theme} label="Requests in flight" />
+ </Stage>
+ )
+ },
+}
+
+export const Thresholds: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={320} height={240}>
+ <Gauge
+ value={78}
+ min={0}
+ max={100}
+ thresholds={HEALTH}
+ theme={theme}
+ label="CPU"
+ config={{ valueFormatter: buildYTickFormatter({ format: 'percentage' }) }}
+ />
+ </Stage>
+ )
+ },
+}
+
+export const ThresholdsHovered: Story = {
+ render: Thresholds.render,
+ play: async ({ canvasElement }) => {
+ await playHoverAtFraction(canvasElement, 0.5, 0.25)
+ },
+}
+
+export const TargetMarker: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={320} height={240}>
+ <Gauge
+ value={0.91}
+ min={0}
+ max={1}
+ thresholds={APDEX}
+ target={{ value: 0.94, label: 'SLO' }}
+ theme={theme}
+ label="Apdex"
+ config={{ valueFormatter: buildYTickFormatter({ decimalPlaces: 2 }) }}
+ />
+ </Stage>
+ )
+ },
+}
+
+export const NullValue: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={320} height={240}>
+ <Gauge value={null} min={0} max={100} thresholds={HEALTH} theme={theme} label="CPU" />
+ </Stage>
+ )
+ },
+}
+
+export const Durations: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={320} height={240}>
+ <Gauge
+ value={412}
+ min={0}
+ max={1000}
+ thresholds={[
+ { value: 0, color: 'var(--data-color-7)' },
+ { value: 300, color: 'var(--data-color-13)' },
+ { value: 800, color: 'var(--data-color-5)' },
+ ]}
+ target={300}
+ theme={theme}
+ label="p95 latency"
+ config={{ valueFormatter: buildYTickFormatter({ format: 'duration_ms' }) }}
+ />
+ </Stage>
+ )
+ },
+}
+
+export const Shapes: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <div className="flex gap-4">
+ {[180, 240, 300, 360].map((sweepAngle) => (
+ <Stage key={sweepAngle} width={200} height={180}>
+ <Gauge
+ value={64}
+ min={0}
+ max={100}
+ thresholds={HEALTH}
+ theme={theme}
+ label={`${sweepAngle}°`}
+ config={{ sweepAngle, valueFormatter: buildYTickFormatter({ format: 'percentage' }) }}
+ />
+ </Stage>
+ ))}
+ </div>
+ )
+ },
+}
+
+export const Tiny: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <div className="flex items-end gap-4">
+ <Stage width={80} height={70}>
+ <Gauge value={72} min={0} max={100} thresholds={HEALTH} theme={theme} label="CPU" />
+ </Stage>
+ <Stage width={100} height={90}>
+ <Gauge value={0.993} min={0.9} max={1} theme={theme} label="Availability" />
+ </Stage>
+ <Stage width={120} height={100}>
+ <Gauge
+ value={1_284_331_221}
+ thresholds={HEALTH}
+ theme={theme}
+ label="Bytes"
+ config={{ valueFormatter: buildYTickFormatter({ format: 'short' }) }}
+ />
+ </Stage>
+ </div>
+ )
+ },
+}
+
+export const Large: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={720} height={420}>
+ <Gauge
+ value={99.62}
+ min={98}
+ max={100}
+ thresholds={[
+ { value: 98, color: 'var(--data-color-5)', label: 'Budget spent' },
+ { value: 99.5, color: 'var(--data-color-13)', label: 'At risk' },
+ { value: 99.8, color: 'var(--data-color-7)', label: 'On track' },
+ ]}
+ target={{ value: 99.9, label: 'SLO' }}
+ theme={theme}
+ label="Availability, 30 days"
+ config={{ valueFormatter: buildYTickFormatter({ suffix: '%', decimalPlaces: 2 }) }}
+ />
+ </Stage>
+ )
+ },
+}
+
+const PODS = (
+ [
+ ['7f9c', 12],
+ ['a1b2', 38],
+ ['c3d4', 55],
+ ['e5f6', 71],
+ ['0a9b', 93],
+ ['77ee', 64],
+ ['4c21', 27],
+ ['b830', 88],
+ ['19fd', 49],
+ ['d6e2', 97],
+ ['5a07', 6],
+ ['8be4', 76],
+ ] as const
+).map(([suffix, value]) => ({ name: `pod=checkout-${suffix}`, value }))
+
+export const GridOfTwelve: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <div className="grid w-[720px] grid-cols-4 gap-2">
+ {PODS.map((pod) => (
+ <div key={pod.name} className="flex h-[150px] flex-col">
+ <Gauge
+ value={pod.value}
+ min={0}
+ max={100}
+ thresholds={HEALTH}
+ theme={theme}
+ label={pod.name}
+ config={{ valueFormatter: buildYTickFormatter({ format: 'percentage' }) }}
+ />
+ </div>
+ ))}
+ </div>
+ )
+ },
+}
+
+export const EdgeCases: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const cases = [
+ { label: 'Above max', value: 140, min: 0, max: 100 },
+ { label: 'Below min', value: -12, min: 0, max: 100 },
+ { label: 'Negative range', value: -18, min: -50, max: 50 },
+ { label: 'min = max', value: 5, min: 5, max: 5 },
+ { label: 'No range given', value: 0.42 },
+ { label: 'Unsorted thresholds', value: 55, thresholds: [...HEALTH].reverse() },
+ { label: 'A very long label that will not fit', value: 3_141_592.653, min: 0, max: 5_000_000 },
+ { label: 'Tiny value', value: 0.4, min: 0, max: 100 },
+ ]
+ return (
+ <div className="grid w-[720px] grid-cols-4 gap-2">
+ {cases.map(({ label, ...rest }) => (
+ <div key={label} className="flex h-[160px] flex-col">
+ <Gauge thresholds={HEALTH} {...rest} theme={theme} label={label} />
+ </div>
+ ))}
+ </div>
+ )
+ },
+}
+
+export const Animated: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const [value, setValue] = useState<number | null>(30)
+ useEffect(() => {
+ const sequence = [30, 82, 95, null, 12, 64]
+ let i = 0
+ const id = setInterval(() => {
+ i = (i + 1) % sequence.length
+ setValue(sequence[i])
+ }, 1500)
+ return () => clearInterval(id)
+ }, [])
+ return (
+ <Stage width={320} height={240}>
+ <Gauge
+ value={value}
+ min={0}
+ max={100}
+ thresholds={HEALTH}
+ target={90}
+ theme={theme}
+ label="CPU"
+ config={{ valueFormatter: buildYTickFormatter({ format: 'percentage' }) }}
+ />
+ </Stage>
+ )
+ },
+ tags: ['test-skip'],
+}
diff --git a/packages/quill/packages/charts/src/charts/Gauge/Gauge.test.tsx b/packages/quill/packages/charts/src/charts/Gauge/Gauge.test.tsx
new file mode 100644
index 000000000000..df0dbf89be77
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Gauge/Gauge.test.tsx
@@ -0,0 +1,86 @@
+import { fireEvent } from '@testing-library/react'
+
+import type { ChartTheme } from '../../core/types'
+import { createDefaultTooltipAccessor, renderChart, waitForChartTooltip } from '../../testing'
+import type { DefaultTooltipAccessor } from '../../testing'
+import { Gauge } from './Gauge'
+
+const THEME: ChartTheme = { colors: ['#111111'], backgroundColor: '#ffffff' }
+const THRESHOLDS = [
+ { value: 90, color: '#ff0000', label: 'Critical' },
+ { value: 0, color: '#00ff00', label: 'Healthy' },
+ { value: 70, color: '#ffaa00', label: 'Busy' },
+]
+
+async function hoverGauge(element: HTMLElement): Promise<DefaultTooltipAccessor> {
+ const rect = element.getBoundingClientRect()
+ fireEvent.mouseMove(element, { clientX: rect.left + rect.width / 2, clientY: rect.top + rect.height / 2 })
+ return createDefaultTooltipAccessor(await waitForChartTooltip())
+}
+
+describe('Gauge', () => {
+ beforeEach(() => {
+ document.body.style.setProperty('--gauge-test-busy', '#ffaa00')
+ })
+
+ afterEach(() => {
+ document.body.style.removeProperty('--gauge-test-busy')
+ })
+
+ it('shows a dash and no threshold for a null value, not a zero', async () => {
+ const { chart } = renderChart(
+ <Gauge value={null} min={0} max={100} thresholds={THRESHOLDS} theme={THEME} label="CPU" />
+ )
+
+ expect(chart.gauge.text()).toEqual({ value: '–', label: 'CPU', min: '0', max: '100' })
+ const tooltip = await hoverGauge(chart.element)
+ expect(tooltip.rows()).toEqual(['Value', 'Range'])
+ })
+
+ it('reports the threshold band the value falls in, whatever order the thresholds come in', async () => {
+ const { chart } = renderChart(
+ <Gauge
+ value={78}
+ min={0}
+ max={100}
+ thresholds={THRESHOLDS}
+ theme={THEME}
+ config={{ valueFormatter: (v) => `${v}%` }}
+ />
+ )
+
+ expect(chart.gauge.text()).toMatchObject({ value: '78%', min: '0%', max: '100%' })
+ expect(chart.gauge.valueColor()).toBe('rgb(255, 170, 0)')
+ expect((await hoverGauge(chart.element)).value('Threshold')).toBe('Busy · 70% – 90%')
+ })
+
+ it('does not repaint the canvas when re-rendered with equal inline props or hovered', async () => {
+ const { chart, rerender } = renderChart(
+ <Gauge value={78} thresholds={[...THRESHOLDS]} target={{ value: 80 }} theme={THEME} />
+ )
+ let paints = 0
+ const observer = new MutationObserver((records) => (paints += records.length))
+ observer.observe(chart.canvas, { attributeFilter: ['data-hog-charts-paint'] })
+
+ rerender(<Gauge value={78} thresholds={[...THRESHOLDS]} target={{ value: 80 }} theme={THEME} />)
+ await hoverGauge(chart.element)
+
+ expect(paints + observer.takeRecords().length).toBe(0)
+ observer.disconnect()
+ })
+
+ it('resolves var() threshold colors again when the theme changes', async () => {
+ const thresholds = [
+ { value: 0, color: '#00ff00' },
+ { value: 70, color: 'var(--gauge-test-busy)' },
+ ]
+ const { chart, rerender } = renderChart(
+ <Gauge value={78} min={0} max={100} thresholds={thresholds} theme={THEME} />
+ )
+ expect((await hoverGauge(chart.element)).swatchColors()).toContain('rgb(255, 170, 0)')
+
+ document.body.style.setProperty('--gauge-test-busy', '#0000ff')
+ rerender(<Gauge value={78} min={0} max={100} thresholds={thresholds} theme={{ ...THEME }} />)
+ expect((await hoverGauge(chart.element)).swatchColors()).toContain('rgb(0, 0, 255)')
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/Gauge/Gauge.tsx b/packages/quill/packages/charts/src/charts/Gauge/Gauge.tsx
new file mode 100644
index 000000000000..0fb42e595f27
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Gauge/Gauge.tsx
@@ -0,0 +1,444 @@
+import React, { useLayoutEffect, useMemo, useState } from 'react'
+
+import { ChartLayoutContext } from '../../core/chart-context'
+import type { ChartLayoutContextValue } from '../../core/chart-context'
+import { ChartShell, useCanvasBounds } from '../../core/chart-shell'
+import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
+import { useAnimatedNumber } from '../../core/hooks/useAnimatedNumber'
+import { useChartCanvas } from '../../core/hooks/useChartCanvas'
+import { useChartDraw } from '../../core/hooks/useChartDraw'
+import { useResolvedChartTheme } from '../../core/theme'
+import type { ChartDrawArgs, ChartMargins, ChartScales, ChartTheme } from '../../core/types'
+import { defaultResolveValue } from '../../core/types'
+import { Tooltip } from '../../overlays/Tooltip'
+import { humanFriendlyNumber } from '../../utils/format'
+import { measureLabelWidth } from '../../utils/text-measure'
+import { drawGauge } from './draw-gauge'
+import type { GaugePaint } from './draw-gauge'
+import { initialGaugeColors, resolveGaugeColors } from './gauge-colors'
+import {
+ clampGaugeSweep,
+ computeGaugeLayout,
+ DEFAULT_GAUGE_THICKNESS,
+ fractionToAngle,
+ gaugeFraction,
+ isOverGauge,
+ layoutGaugeText,
+ resolveGaugeBounds,
+ sortThresholds,
+ thresholdBands,
+ thresholdIndexAt,
+} from './gauge-layout'
+import type { GaugeLayout, GaugeThreshold } from './gauge-layout'
+import { GaugeLabels } from './GaugeLabels'
+import type { GaugeEndLabel, GaugeEnds } from './GaugeLabels'
+import { GAUGE_EMPTY_VALUE, GaugeTooltip } from './GaugeTooltip'
+import type { GaugeTooltipContext, GaugeTooltipThreshold } from './GaugeTooltip'
+
+export interface GaugeTarget {
+ /** Where the tick sits, in the same units as `value`. */
+ value: number
+ /** Names the target in the tooltip, such as `'SLO'`. Defaults to `'Target'`. */
+ label?: string
+}
+
+export interface GaugeConfig {
+ /** Degrees the arc spans, centered on 12 o'clock. Default 240. Clamped to 180 (a half circle)
+ * through 360 (a full ring). */
+ sweepAngle?: number
+ /** Arc thickness as a fraction of the gauge radius, so it scales with the container, up to 28px.
+ * Default 0.15. */
+ thickness?: number
+ /** Formats the value, the min and max labels, and the tooltip. `buildYTickFormatter` builds one from
+ * the axis format options (`duration`, `percentage`, `currency`, prefixes and suffixes). */
+ valueFormatter?: (value: number) => string
+ /** Show the min and max under the arc ends. Default true. Always hidden above a 300° sweep, where
+ * the ends meet, and when the two labels would overlap. */
+ showMinMax?: boolean
+ /** Draw the threshold bands as a thin ring outside the track. Default true when there are two or
+ * more thresholds. */
+ showThresholdBands?: boolean
+ /** Track color. Defaults to a faint tint of the page text color. */
+ trackColor?: string
+ /** Duration (ms) of the value arc's ease to a new value. Default 500. `0` snaps. Reduced motion
+ * always snaps. */
+ animationMs?: number
+ tooltip?: {
+ /** Show the tooltip on hover. Default true. */
+ enabled?: boolean
+ }
+}
+
+export interface GaugeProps {
+ /** The value to show. `null` draws an empty track and a dash, not a zero. */
+ value: number | null
+ /** Range start. Defaults to the lowest threshold, else 0. A value or target below that widens the
+ * range down to 0, or to the value when it is negative. */
+ min?: number
+ /** Range end. Defaults to the highest threshold, else the larger of `min + 1` and 0, raised to
+ * contain the value and the target. Out-of-range values still print as-is and the arc clamps to
+ * the end. */
+ max?: number
+ /** Color steps. The arc takes the color of the step the value falls in, and the steps draw as
+ * bands around the track. Order does not matter. Colors may be `var(--…)`. */
+ thresholds?: readonly GaugeThreshold[]
+ /** Arc color without thresholds: hex, rgb, or `var(--…)`. Defaults to `theme.colors[0]`. */
+ color?: string
+ /** Palette and chrome colors. Defaults to the nearest `ChartThemeProvider`, then the quill CSS vars.
+ * A new theme object, as on a light or dark switch, resolves every `var(--…)` color again. */
+ theme?: ChartTheme
+ /** Short caption under the value, such as the metric name. Truncates to fit the arc. */
+ label?: string
+ /** Marks a value on the track with a tick, such as an SLO target. Hidden when outside the range. */
+ target?: number | GaugeTarget
+ /** Shape, formatting, animation, and tooltip options. */
+ config?: GaugeConfig
+ /** Replaces the default tooltip content. */
+ tooltip?: (ctx: GaugeTooltipContext) => React.ReactNode
+ /** Classes for the chart wrapper. */
+ className?: string
+ /** `data-attr` applied to the chart wrapper. */
+ dataAttr?: string
+ /** Called when rendering throws. The gauge then renders a fallback instead of unmounting its parent. */
+ onError?: (error: Error, info: React.ErrorInfo) => void
+}
+
+const ZERO_MARGINS: ChartMargins = { top: 0, right: 0, bottom: 0, left: 0 }
+const PADDING = 4
+const DEFAULT_ANIMATION_MS = 500
+const MAX_MINMAX_SWEEP = 300
+const EMPTY_SERIES: never[] = []
+const EMPTY_LABELS: string[] = []
+// The ring's top-right shoulder, as a fraction of the outer radius, so the tooltip sits beside the value.
+const TOOLTIP_ANCHOR = 0.72
+
+export function Gauge({ onError, ...rest }: GaugeProps): React.ReactElement {
+ return (
+ <ChartErrorBoundary onError={onError}>
+ <GaugeInner {...rest} />
+ </ChartErrorBoundary>
+ )
+}
+
+function paintFromScales(scales: ChartScales): GaugePaint | null {
+ return (scales._private as { gauge?: GaugePaint } | undefined)?.gauge ?? null
+}
+
+function drawStatic({ ctx, scales }: ChartDrawArgs): void {
+ const paint = paintFromScales(scales)
+ if (paint) {
+ drawGauge(ctx, paint)
+ }
+}
+
+function drawHover(): boolean {
+ return false
+}
+
+function minMaxFontSize(width: number, height: number): number {
+ return Math.min(13, Math.max(9, Math.min(width, height * 1.3) * 0.045))
+}
+
+function placeMinMax(
+ layout: GaugeLayout,
+ width: number,
+ minText: string,
+ maxText: string,
+ font: string
+): { min: GaugeEndLabel; max: GaugeEndLabel } | null {
+ const { cx, radius, angles } = layout
+ const minWidth = measureLabelWidth(minText, font)
+ const maxWidth = measureLabelWidth(maxText, font)
+ const edge = 2
+ const minX = Math.min(Math.max(cx + Math.cos(angles.start) * radius, edge + minWidth / 2), width - edge)
+ const maxX = Math.max(Math.min(cx + Math.cos(angles.end) * radius, width - edge - maxWidth / 2), edge)
+ if (minX + minWidth / 2 + 6 > maxX - maxWidth / 2) {
+ return null
+ }
+ return { min: { text: minText, x: minX }, max: { text: maxText, x: maxX } }
+}
+
+function GaugeInner({
+ value: rawValue,
+ min,
+ max,
+ thresholds,
+ color,
+ theme: themeProp,
+ label,
+ target: rawTarget,
+ config,
+ tooltip,
+ className,
+ dataAttr,
+}: Omit<GaugeProps, 'onError'>): React.ReactElement {
+ const theme = useResolvedChartTheme(themeProp)
+ const {
+ sweepAngle,
+ thickness = DEFAULT_GAUGE_THICKNESS,
+ valueFormatter,
+ showMinMax = true,
+ showThresholdBands,
+ trackColor: trackColorProp,
+ animationMs: rawAnimationMs,
+ tooltip: tooltipConfig,
+ } = config ?? {}
+ const animationMs =
+ rawAnimationMs !== undefined && Number.isFinite(rawAnimationMs) ? rawAnimationMs : DEFAULT_ANIMATION_MS
+ const sweep = clampGaugeSweep(sweepAngle)
+ const value = rawValue !== null && Number.isFinite(rawValue) ? rawValue : null
+ const targetValue = typeof rawTarget === 'number' ? rawTarget : rawTarget?.value
+ const targetLabel = typeof rawTarget === 'number' ? undefined : rawTarget?.label
+ // Keyed on the fields, so an inline `target={{ … }}` does not repaint the canvas on every render.
+ const target = useMemo<GaugeTarget | null>(
+ () =>
+ targetValue !== undefined && Number.isFinite(targetValue)
+ ? { value: targetValue, label: targetLabel }
+ : null,
+ [targetValue, targetLabel]
+ )
+
+ const { canvasRef, overlayCanvasRef, wrapperRef, dimensions, ctx } = useChartCanvas({
+ margins: ZERO_MARGINS,
+ })
+
+ const formatValue = valueFormatter ?? humanFriendlyNumber
+
+ // Keyed on the content, so an inline `thresholds={[…]}` does not re-resolve colors and repaint on every render.
+ const thresholdsKey = (thresholds ?? [])
+ .map((t) => `${t.value}\u0000${t.color}\u0000${t.label ?? ''}`)
+ .join('\u0001')
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const sorted = useMemo(() => sortThresholds(thresholds), [thresholdsKey])
+ const bounds = useMemo(
+ () => resolveGaugeBounds({ value, min, max, thresholds: sorted, target: target?.value }),
+ [value, min, max, sorted, target]
+ )
+
+ // Re-read on every theme change, because a light/dark flip changes what each `var(--…)` resolves to.
+ const [colors, setColors] = useState(() => initialGaugeColors({ sorted, color, trackColor: trackColorProp, theme }))
+ useLayoutEffect(() => {
+ const root = wrapperRef.current
+ if (root) {
+ setColors(resolveGaugeColors(root, { sorted, color, trackColor: trackColorProp, theme }))
+ }
+ }, [wrapperRef, sorted, color, trackColorProp, theme])
+ const { base: baseColor, thresholds: resolvedThresholds, track: trackColor, ink, fontFamily } = colors
+
+ const targetFraction = gaugeFraction(value, bounds)
+ const animatedFraction = useAnimatedNumber(targetFraction, animationMs)
+ const settled = animatedFraction === targetFraction
+ const colorValue = settled ? value : bounds.min + animatedFraction * (bounds.max - bounds.min)
+ const valueIndex = thresholdIndexAt(value, resolvedThresholds)
+ const arcIndex = thresholdIndexAt(colorValue, resolvedThresholds)
+ const arcColor = arcIndex >= 0 ? resolvedThresholds[arcIndex].color : baseColor
+ const valueColor = valueIndex >= 0 ? resolvedThresholds[valueIndex].color : baseColor
+
+ const bandsVisible = showThresholdBands ?? resolvedThresholds.length > 1
+ const showEnds = showMinMax && sweep <= MAX_MINMAX_SWEEP
+ const minMaxFont = dimensions ? minMaxFontSize(dimensions.width, dimensions.height) : 0
+ const minText = formatValue(bounds.min)
+ const maxText = formatValue(bounds.max)
+ const hasTarget = target !== null
+
+ const { layout, ends } = useMemo<{ layout: GaugeLayout | null; ends: GaugeEnds | null }>(() => {
+ if (!dimensions) {
+ return { layout: null, ends: null }
+ }
+ const fit = (footer: number): GaugeLayout =>
+ computeGaugeLayout({
+ width: dimensions.width,
+ height: dimensions.height,
+ sweep,
+ thickness,
+ showBands: bandsVisible && resolvedThresholds.length > 0,
+ footer,
+ padding: PADDING,
+ hasTarget,
+ })
+ if (!showEnds) {
+ return { layout: fit(0), ends: null }
+ }
+ const withFooter = fit(minMaxFont * 1.6)
+ const placed = placeMinMax(withFooter, dimensions.width, minText, maxText, `${minMaxFont}px ${fontFamily}`)
+ if (!placed) {
+ return { layout: fit(0), ends: null }
+ }
+ return {
+ layout: withFooter,
+ ends: { ...placed, top: withFooter.bottom + minMaxFont * 0.3, fontSize: minMaxFont },
+ }
+ }, [
+ dimensions,
+ sweep,
+ thickness,
+ bandsVisible,
+ resolvedThresholds.length,
+ hasTarget,
+ showEnds,
+ minMaxFont,
+ minText,
+ maxText,
+ fontFamily,
+ ])
+
+ // `useChartDraw` repaints when `scales` changes, so each animation frame rides in on `_private`.
+ const scales = useMemo<ChartScales | null>(() => {
+ if (!layout) {
+ return null
+ }
+ const angleAt = (v: number): number => fractionToAngle(gaugeFraction(v, bounds), layout.angles)
+ const paint: GaugePaint = {
+ layout,
+ trackColor,
+ bands: bandsVisible
+ ? thresholdBands(resolvedThresholds, bounds).map((band) => ({
+ startAngle: angleAt(band.from),
+ endAngle: angleAt(band.to),
+ color: band.threshold.color,
+ }))
+ : [],
+ valueAngle: fractionToAngle(animatedFraction, layout.angles),
+ valueColor: arcColor,
+ targetAngle:
+ target && target.value >= bounds.min && target.value <= bounds.max ? angleAt(target.value) : null,
+ targetColor: ink,
+ }
+ return { x: () => undefined, y: () => 0, yTicks: () => [], _private: { gauge: paint } }
+ }, [layout, bounds, trackColor, bandsVisible, resolvedThresholds, animatedFraction, arcColor, target, ink])
+
+ useChartDraw({
+ ctx,
+ overlayCtx: null,
+ dimensions,
+ scales,
+ series: EMPTY_SERIES,
+ labels: EMPTY_LABELS,
+ hoverIndex: -1,
+ hoverPosition: null,
+ theme,
+ drawStatic,
+ drawHover,
+ })
+
+ const valueText = value === null ? GAUGE_EMPTY_VALUE : formatValue(value)
+
+ const text = useMemo(() => {
+ if (!layout || layout.innerRadius <= 0) {
+ return null
+ }
+ return layoutGaugeText({
+ layout,
+ measure: measureLabelWidth,
+ fontFamily,
+ valueText,
+ labelText: label || null,
+ })
+ }, [layout, fontFamily, valueText, label])
+
+ const tooltipThreshold: GaugeTooltipThreshold | null =
+ valueIndex < 0
+ ? null
+ : {
+ threshold: resolvedThresholds[valueIndex],
+ from: valueIndex === 0 ? undefined : resolvedThresholds[valueIndex].value,
+ to: valueIndex + 1 < resolvedThresholds.length ? resolvedThresholds[valueIndex + 1].value : undefined,
+ }
+
+ const canvasBounds = useCanvasBounds(canvasRef)
+ const [hoverRect, setHoverRect] = useState<DOMRect | null>(null)
+ const showTooltip = tooltipConfig?.enabled !== false
+
+ // Returning the previous rect while the gauge stays put lets React skip the re-render on every mousemove.
+ const onMouseMove = (e: React.MouseEvent<HTMLDivElement>): void => {
+ if (!layout || !showTooltip) {
+ return
+ }
+ const rect = e.currentTarget.getBoundingClientRect()
+ const hit = isOverGauge(layout, e.clientX - rect.left, e.clientY - rect.top)
+ setHoverRect((previous) =>
+ !hit ? null : previous && previous.left === rect.left && previous.top === rect.top ? previous : rect
+ )
+ }
+
+ const tooltipCtx: GaugeTooltipContext | null =
+ hoverRect && layout && showTooltip
+ ? {
+ dataIndex: 0,
+ label: label ?? '',
+ seriesData: [],
+ position: {
+ x: layout.cx + layout.outerRadius * TOOLTIP_ANCHOR,
+ y: layout.cy - layout.outerRadius * TOOLTIP_ANCHOR,
+ },
+ hoverPosition: null,
+ canvasBounds: hoverRect,
+ isPinned: false,
+ value,
+ min: bounds.min,
+ max: bounds.max,
+ threshold: tooltipThreshold,
+ thresholdCount: resolvedThresholds.length,
+ target,
+ color: valueColor,
+ formatValue,
+ }
+ : null
+
+ const layoutValue = useMemo<ChartLayoutContextValue | null>(() => {
+ if (!scales || !dimensions) {
+ return null
+ }
+ return {
+ scales,
+ dimensions,
+ labels: EMPTY_LABELS,
+ series: EMPTY_SERIES,
+ theme,
+ resolvePositionValue: defaultResolveValue,
+ canvasBounds,
+ axis: { orientation: 'vertical', xTickFormatter: undefined, isPercent: false },
+ yGutters: [],
+ }
+ }, [scales, dimensions, theme, canvasBounds])
+
+ const ariaLabel = [
+ label ? `${label}:` : 'Gauge:',
+ value === null ? 'no data' : valueText,
+ `of ${minText} to ${maxText}`,
+ tooltipThreshold?.threshold.label ? `(${tooltipThreshold.threshold.label})` : '',
+ ]
+ .filter(Boolean)
+ .join(' ')
+
+ return (
+ <ChartLayoutContext.Provider value={layoutValue}>
+ <ChartShell
+ wrapperRef={wrapperRef}
+ canvasRef={canvasRef}
+ overlayCanvasRef={overlayCanvasRef}
+ className={className}
+ dataAttr={dataAttr}
+ pointer={false}
+ ariaLabel={ariaLabel}
+ handlers={{ onMouseMove, onMouseLeave: () => setHoverRect(null), onClick: () => {} }}
+ showOverlay={!!layout}
+ >
+ <GaugeLabels
+ text={text}
+ ends={ends}
+ empty={value === null}
+ valueColor={valueColor}
+ mutedColor={theme.axisColor}
+ />
+ {tooltipCtx ? (
+ <Tooltip
+ context={tooltipCtx}
+ renderTooltip={(ctx) => (tooltip ? tooltip(ctx) : <GaugeTooltip ctx={ctx} />)}
+ placement="follow-data"
+ />
+ ) : null}
+ </ChartShell>
+ </ChartLayoutContext.Provider>
+ )
+}
diff --git a/packages/quill/packages/charts/src/charts/Gauge/GaugeLabels.tsx b/packages/quill/packages/charts/src/charts/Gauge/GaugeLabels.tsx
new file mode 100644
index 000000000000..c558b34ac4b0
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Gauge/GaugeLabels.tsx
@@ -0,0 +1,105 @@
+import React from 'react'
+
+import { GAUGE_VALUE_FONT_WEIGHT } from './gauge-layout'
+import type { GaugeTextBlock } from './gauge-layout'
+
+export interface GaugeEndLabel {
+ text: string
+ x: number
+}
+
+export interface GaugeEnds {
+ min: GaugeEndLabel
+ max: GaugeEndLabel
+ top: number
+ fontSize: number
+}
+
+interface GaugeLabelsProps {
+ text: GaugeTextBlock | null
+ ends: GaugeEnds | null
+ /** The value is missing, so it reads muted at normal weight. */
+ empty: boolean
+ valueColor: string
+ mutedColor: string | undefined
+}
+
+const TEXT_BASE_STYLE: React.CSSProperties = {
+ position: 'absolute',
+ transform: 'translate(-50%, -50%)',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ lineHeight: 1.2,
+ textAlign: 'center',
+ pointerEvents: 'none',
+}
+
+const MUTED_STYLE: React.CSSProperties = { opacity: 0.65 }
+
+export function GaugeLabels({ text, ends, empty, valueColor, mutedColor }: GaugeLabelsProps): React.ReactElement {
+ const mutedStyle = mutedColor ? { color: mutedColor } : MUTED_STYLE
+ return (
+ <>
+ {text ? (
+ <div
+ aria-hidden="true"
+ data-attr="hog-chart-gauge-value"
+ title={text.value.text}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ ...TEXT_BASE_STYLE,
+ left: text.value.x,
+ top: text.value.y,
+ maxWidth: text.value.maxWidth,
+ fontSize: text.value.fontSize,
+ fontWeight: empty ? 400 : GAUGE_VALUE_FONT_WEIGHT,
+ lineHeight: 1.1,
+ ...(empty ? mutedStyle : { color: valueColor }),
+ }}
+ >
+ {text.value.text}
+ </div>
+ ) : null}
+ {text?.label ? (
+ <div
+ aria-hidden="true"
+ data-attr="hog-chart-gauge-label"
+ title={text.label.text}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ ...TEXT_BASE_STYLE,
+ ...mutedStyle,
+ left: text.label.x,
+ top: text.label.y,
+ maxWidth: text.label.maxWidth,
+ fontSize: text.label.fontSize,
+ }}
+ >
+ {text.label.text}
+ </div>
+ ) : null}
+ {ends
+ ? (['min', 'max'] as const).map((end) => (
+ <div
+ key={end}
+ aria-hidden="true"
+ data-attr={`hog-chart-gauge-${end}`}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ ...TEXT_BASE_STYLE,
+ ...mutedStyle,
+ transform: 'translate(-50%, 0)',
+ left: ends[end].x,
+ top: ends.top,
+ fontSize: ends.fontSize,
+ fontVariantNumeric: 'tabular-nums',
+ }}
+ >
+ {ends[end].text}
+ </div>
+ ))
+ : null}
+ </>
+ )
+}
diff --git a/packages/quill/packages/charts/src/charts/Gauge/GaugeTooltip.tsx b/packages/quill/packages/charts/src/charts/Gauge/GaugeTooltip.tsx
new file mode 100644
index 000000000000..861f1fb8b4a7
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Gauge/GaugeTooltip.tsx
@@ -0,0 +1,90 @@
+import React from 'react'
+
+import type { TooltipContext } from '../../core/types'
+import { TooltipSurface, TooltipSwatch } from '../../overlays/TooltipSurface'
+import type { GaugeThreshold } from './gauge-layout'
+
+export interface GaugeTooltipThreshold {
+ /** The threshold step with its color resolved to a concrete value. */
+ threshold: GaugeThreshold
+ /** The band's unclipped range: `from` is undefined for the lowest band, `to` for the highest. */
+ from: number | undefined
+ to: number | undefined
+}
+
+/** {@link TooltipContext} with the gauge's reading. `label` is the gauge `label`, or `''` without one. */
+export interface GaugeTooltipContext extends TooltipContext {
+ value: number | null
+ min: number
+ max: number
+ /** The band the value falls in, or null without thresholds or a value. */
+ threshold: GaugeTooltipThreshold | null
+ /** Number of thresholds, so a tooltip can skip the band row when one color covers the range. */
+ thresholdCount: number
+ target: { value: number; label?: string } | null
+ /** The resolved color of the value arc. */
+ color: string
+ /** The gauge's value formatter, for formatting any of the numbers above. */
+ formatValue: (value: number) => string
+}
+
+export const GAUGE_EMPTY_VALUE = '–'
+
+export function formatGaugeBand(threshold: GaugeTooltipThreshold, formatValue: (value: number) => string): string {
+ const { from, to } = threshold
+ if (from === undefined && to === undefined) {
+ return 'All values'
+ }
+ if (from === undefined) {
+ return `Below ${formatValue(to as number)}`
+ }
+ if (to === undefined) {
+ return `${formatValue(from)} and above`
+ }
+ return `${formatValue(from)} – ${formatValue(to)}`
+}
+
+function Row({ name, children }: { name: string; children: React.ReactNode }): React.ReactElement {
+ return (
+ <div data-attr="hog-chart-tooltip-row" className="contents">
+ <span data-attr="hog-chart-tooltip-series" className="opacity-70">
+ {name}
+ </span>
+ <span
+ data-attr="hog-chart-tooltip-value"
+ className="flex items-center gap-1.5 justify-self-end font-medium tabular-nums"
+ >
+ {children}
+ </span>
+ </div>
+ )
+}
+
+export interface GaugeTooltipProps {
+ ctx: GaugeTooltipContext
+}
+
+export function GaugeTooltip({ ctx }: GaugeTooltipProps): React.ReactElement {
+ const { formatValue, threshold, target } = ctx
+ return (
+ <TooltipSurface data-attr="hog-chart-gauge-tooltip">
+ {ctx.label ? <div className="mb-1 font-semibold">{ctx.label}</div> : null}
+ <div className="grid grid-cols-[auto_auto] gap-x-4 gap-y-0.5">
+ <Row name="Value">{ctx.value === null ? GAUGE_EMPTY_VALUE : formatValue(ctx.value)}</Row>
+ <Row name="Range">
+ {formatValue(ctx.min)} – {formatValue(ctx.max)}
+ </Row>
+ {threshold && (ctx.thresholdCount > 1 || threshold.threshold.label) ? (
+ <Row name="Threshold">
+ <TooltipSwatch color={threshold.threshold.color} />
+ <span>
+ {threshold.threshold.label ? `${threshold.threshold.label} · ` : ''}
+ {formatGaugeBand(threshold, formatValue)}
+ </span>
+ </Row>
+ ) : null}
+ {target ? <Row name={target.label ?? 'Target'}>{formatValue(target.value)}</Row> : null}
+ </div>
+ </TooltipSurface>
+ )
+}
diff --git a/packages/quill/packages/charts/src/charts/Gauge/draw-gauge.ts b/packages/quill/packages/charts/src/charts/Gauge/draw-gauge.ts
new file mode 100644
index 000000000000..54b96da3f804
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Gauge/draw-gauge.ts
@@ -0,0 +1,106 @@
+import { isFullSweep, roundCapInset, targetTickSize } from './gauge-layout'
+import type { GaugeLayout } from './gauge-layout'
+
+export interface GaugePaintBand {
+ startAngle: number
+ endAngle: number
+ color: string
+}
+
+export interface GaugePaint {
+ layout: GaugeLayout
+ trackColor: string
+ bands: GaugePaintBand[]
+ /** At `layout.angles.start` the arc is empty. */
+ valueAngle: number
+ valueColor: string
+ /** Angle of the target tick, or null when there is no target in range. */
+ targetAngle: number | null
+ targetColor: string
+}
+
+// Gap between adjacent threshold bands, in px along the ring.
+const BAND_GAP_PX = 1.5
+
+/** Stroke a round-capped arc whose caps land exactly on `from` and `to`. An arc shorter than its
+ * caps paints a dot at `from`, so a small nonzero value stays visible. */
+function strokeRoundArc(
+ ctx: CanvasRenderingContext2D,
+ layout: GaugeLayout,
+ from: number,
+ to: number,
+ color: string
+): void {
+ const { cx, cy, radius, thickness } = layout
+ if (thickness <= 0 || radius <= 0) {
+ return
+ }
+ const full = isFullSweep(to - from)
+ const inset = full ? 0 : roundCapInset(radius, thickness)
+ const start = from + inset
+ const end = Math.max(start, to - inset)
+ ctx.beginPath()
+ ctx.lineCap = full ? 'butt' : 'round'
+ ctx.lineWidth = thickness
+ ctx.strokeStyle = color
+ ctx.arc(cx, cy, radius, start, end)
+ ctx.stroke()
+}
+
+function drawBands(ctx: CanvasRenderingContext2D, layout: GaugeLayout, bands: GaugePaintBand[]): void {
+ const { cx, cy, bandRadius, bandThickness, angles } = layout
+ if (bandThickness <= 0 || bands.length === 0) {
+ return
+ }
+ const halfGap = BAND_GAP_PX / 2 / bandRadius
+ ctx.lineCap = 'butt'
+ ctx.lineWidth = bandThickness
+ for (const band of bands) {
+ // Only the joins between bands get a gap. The outer ends line up with the track ends.
+ const start = band.startAngle > angles.start + 1e-9 ? band.startAngle + halfGap : band.startAngle
+ const end = band.endAngle < angles.end - 1e-9 ? band.endAngle - halfGap : band.endAngle
+ if (end <= start) {
+ continue
+ }
+ ctx.beginPath()
+ ctx.strokeStyle = band.color
+ ctx.arc(cx, cy, bandRadius, start, end)
+ ctx.stroke()
+ }
+}
+
+function drawTarget(ctx: CanvasRenderingContext2D, paint: GaugePaint, angle: number): void {
+ const { cx, cy, innerRadius, outerRadius, thickness } = paint.layout
+ const { overhang, width, gap } = targetTickSize(thickness)
+ const r0 = innerRadius - overhang
+ const r1 = outerRadius + overhang
+ const strokeTick = (): void => {
+ ctx.beginPath()
+ ctx.moveTo(cx + Math.cos(angle) * r0, cy + Math.sin(angle) * r0)
+ ctx.lineTo(cx + Math.cos(angle) * r1, cy + Math.sin(angle) * r1)
+ ctx.stroke()
+ }
+ ctx.lineCap = 'round'
+ // Erasing a wider stroke first cuts a gap through the rings, so the tick reads over any arc color
+ // and the gap shows whatever surface sits behind the transparent canvas.
+ ctx.save()
+ ctx.globalCompositeOperation = 'destination-out'
+ ctx.lineWidth = width + 2 * gap
+ strokeTick()
+ ctx.restore()
+ ctx.strokeStyle = paint.targetColor
+ ctx.lineWidth = width
+ strokeTick()
+}
+
+export function drawGauge(ctx: CanvasRenderingContext2D, paint: GaugePaint): void {
+ const { layout } = paint
+ drawBands(ctx, layout, paint.bands)
+ strokeRoundArc(ctx, layout, layout.angles.start, layout.angles.end, paint.trackColor)
+ if (paint.valueAngle > layout.angles.start) {
+ strokeRoundArc(ctx, layout, layout.angles.start, paint.valueAngle, paint.valueColor)
+ }
+ if (paint.targetAngle !== null) {
+ drawTarget(ctx, paint, paint.targetAngle)
+ }
+}
diff --git a/packages/quill/packages/charts/src/charts/Gauge/gauge-colors.ts b/packages/quill/packages/charts/src/charts/Gauge/gauge-colors.ts
new file mode 100644
index 000000000000..7b2d7a2804b5
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Gauge/gauge-colors.ts
@@ -0,0 +1,78 @@
+import { dimColor, resolveCssColor, toSrgbColor } from '../../core/color-utils'
+import { DEFAULT_CHART_COLORS } from '../../core/theme'
+import type { ChartTheme } from '../../core/types'
+import { FONT_FAMILY } from '../../utils/text-measure'
+import type { GaugeThreshold } from './gauge-layout'
+
+export interface GaugeColors {
+ base: string
+ /** Sorted like the input, each with its color resolved. */
+ thresholds: GaugeThreshold[]
+ track: string
+ /** The host's text color, for the target tick and the track tint. */
+ ink: string
+ fontFamily: string
+}
+
+interface GaugeColorInput {
+ sorted: readonly GaugeThreshold[]
+ color: string | undefined
+ trackColor: string | undefined
+ theme: ChartTheme
+}
+
+const FALLBACK_INK = '#1f2328'
+const FALLBACK_TRACK = 'rgba(128, 128, 128, 0.16)'
+const TRACK_ALPHA = 0.1
+
+const isVar = (color: string): boolean => color.trim().startsWith('var(')
+
+/** A `var(--…)` that does not resolve would reach the canvas as an invalid color, which the canvas
+ * ignores, so it paints with whatever color the previous stroke left behind. */
+function resolveColor(color: string, fallback: string, root: HTMLElement): string {
+ let resolved = resolveCssColor(color, root).trim()
+ // jsdom and other non-browser hosts do not inherit custom properties down to the wrapper.
+ if (isVar(resolved)) {
+ resolved = resolveCssColor(color).trim()
+ }
+ return resolved && !isVar(resolved) ? resolved : fallback
+}
+
+function inkTint(ink: string, theme: ChartTheme): string {
+ const srgbInk = toSrgbColor(ink)
+ const tinted = dimColor(srgbInk, TRACK_ALPHA)
+ return tinted === srgbInk ? (theme.gridColor ?? FALLBACK_TRACK) : tinted
+}
+
+/** Colors for the first render, before the wrapper mounts. No DOM reads, so it is safe during render;
+ * nothing paints with it, because the canvas waits for its first measurement. */
+export function initialGaugeColors({ sorted, color, theme }: GaugeColorInput): GaugeColors {
+ const palette = theme.colors[0] || DEFAULT_CHART_COLORS[0]
+ const base = color && !isVar(color) ? color : palette
+ return {
+ base,
+ thresholds: sorted.map((t) => (isVar(t.color) ? { ...t, color: base } : t)),
+ track: theme.gridColor ?? FALLBACK_TRACK,
+ ink: FALLBACK_INK,
+ fontFamily: FONT_FAMILY,
+ }
+}
+
+/** Resolve every color against the mounted wrapper, so a scoped theme container applies. */
+export function resolveGaugeColors(
+ root: HTMLElement,
+ { sorted, color, trackColor, theme }: GaugeColorInput
+): GaugeColors {
+ const palette = theme.colors[0] || DEFAULT_CHART_COLORS[0]
+ const base = resolveColor(color || palette, palette, root)
+ const style = getComputedStyle(root)
+ const ink = resolveColor(style.color || FALLBACK_INK, FALLBACK_INK, root)
+ const track = trackColor ? resolveColor(trackColor, FALLBACK_TRACK, root) : inkTint(ink, theme)
+ return {
+ base,
+ thresholds: sorted.map((t) => ({ ...t, color: resolveColor(t.color, base, root) })),
+ track,
+ ink,
+ fontFamily: style.fontFamily || FONT_FAMILY,
+ }
+}
diff --git a/packages/quill/packages/charts/src/charts/Gauge/gauge-layout.test.ts b/packages/quill/packages/charts/src/charts/Gauge/gauge-layout.test.ts
new file mode 100644
index 000000000000..49f2dd58e00e
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Gauge/gauge-layout.test.ts
@@ -0,0 +1,122 @@
+import {
+ computeGaugeLayout,
+ gaugeFraction,
+ layoutGaugeText,
+ resolveGaugeBounds,
+ ringSectorBox,
+ targetTickSize,
+ thresholdBands,
+} from './gauge-layout'
+import type { GaugeThreshold, ResolveGaugeBoundsInput } from './gauge-layout'
+
+const steps = (...values: number[]): GaugeThreshold[] => values.map((value, i) => ({ value, color: `c${i}` }))
+
+describe('gauge layout', () => {
+ it.each<[string, ResolveGaugeBoundsInput, { min: number; max: number }]>([
+ [
+ 'explicit min and max win over value and thresholds',
+ { value: 500, min: 0, max: 100, thresholds: steps(50, 900) },
+ { min: 0, max: 100 },
+ ],
+ ['thresholds span the range in any order', { value: 60, thresholds: steps(90, 0, 50) }, { min: 0, max: 90 }],
+ [
+ 'a value under the lowest threshold widens the range to 0',
+ { value: 30, thresholds: steps(70, 90) },
+ { min: 0, max: 90 },
+ ],
+ [
+ 'the range grows to contain a value past the last threshold',
+ { value: 150, thresholds: steps(50, 90) },
+ { min: 50, max: 150 },
+ ],
+ ['a value alone gets 0 to 1', { value: 0.4 }, { min: 0, max: 1 }],
+ ])('resolves bounds: %s', (_name, input, expected) => {
+ expect(resolveGaugeBounds(input)).toEqual(expected)
+ })
+
+ it('clamps the fraction to the range, and reads full at the value when min equals max', () => {
+ expect(gaugeFraction(140, { min: 0, max: 100 })).toBe(1)
+ expect(gaugeFraction(5, { min: 5, max: 5 })).toBe(1)
+ expect(gaugeFraction(4, { min: 5, max: 5 })).toBe(0)
+ })
+
+ it('clips threshold bands to the range and drops the ones outside it', () => {
+ const bands = thresholdBands(steps(0, 70, 90, 200), { min: 0, max: 100 })
+ expect(bands.map(({ from, to }) => ({ from, to }))).toEqual([
+ { from: 0, to: 70 },
+ { from: 70, to: 90 },
+ { from: 90, to: 100 },
+ ])
+ })
+
+ it.each([
+ [400, 120, 240, false],
+ [300, 300, 360, false],
+ [140, 400, 180, true],
+ ])(
+ 'keeps a %ipx by %ipx, %i° gauge (target: %s) inside its box with room for the footer',
+ (width, height, sweep, hasTarget) => {
+ const footer = 14
+ const padding = 4
+ const layout = computeGaugeLayout({
+ width,
+ height,
+ sweep,
+ thickness: 0.15,
+ showBands: true,
+ footer,
+ padding,
+ hasTarget,
+ })
+ const tick = targetTickSize(layout.thickness)
+ const reach = hasTarget ? tick.overhang + tick.width / 2 + tick.gap : 0
+ const box = ringSectorBox(layout.angles, layout.innerRadius, layout.outerRadius)
+ const left = layout.cx + box.minX - reach
+ const right = layout.cx + box.maxX + reach
+ const top = layout.cy + box.minY - reach
+ expect(left).toBeGreaterThanOrEqual(padding - 1e-6)
+ expect(right).toBeLessThanOrEqual(width - padding + 1e-6)
+ expect(top).toBeGreaterThanOrEqual(padding - 1e-6)
+ expect(layout.bottom + footer).toBeLessThanOrEqual(height - padding + 1e-6)
+ expect(Math.abs(left - (width - right))).toBeLessThan(1e-6)
+ }
+ )
+
+ it('shrinks a long value until it fits the inner chord, and drops the label in a tiny gauge', () => {
+ const measure = (text: string, font: string): number =>
+ text.length * Number(/(\d+(\.\d+)?)px/.exec(font)?.[1]) * 0.6
+ const layout = computeGaugeLayout({
+ width: 400,
+ height: 300,
+ sweep: 240,
+ thickness: 0.15,
+ showBands: false,
+ footer: 0,
+ padding: 4,
+ })
+ const short = layoutGaugeText({ layout, measure, fontFamily: 'x', valueText: '42%', labelText: 'CPU' })
+ const long = layoutGaugeText({
+ layout,
+ measure,
+ fontFamily: 'x',
+ valueText: '3,141,592.65 req/s',
+ labelText: 'CPU',
+ })
+ expect(long.value.fontSize).toBeLessThan(short.value.fontSize)
+ expect(measure(long.value.text, `${long.value.fontSize}px x`)).toBeLessThanOrEqual(long.value.maxWidth)
+ expect(short.label?.text).toBe('CPU')
+
+ const tiny = computeGaugeLayout({
+ width: 40,
+ height: 36,
+ sweep: 240,
+ thickness: 0.15,
+ showBands: false,
+ footer: 0,
+ padding: 0,
+ })
+ expect(
+ layoutGaugeText({ layout: tiny, measure, fontFamily: 'x', valueText: '42%', labelText: 'CPU' }).label
+ ).toBeNull()
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/Gauge/gauge-layout.ts b/packages/quill/packages/charts/src/charts/Gauge/gauge-layout.ts
new file mode 100644
index 000000000000..9674cbc2a41b
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Gauge/gauge-layout.ts
@@ -0,0 +1,422 @@
+export interface GaugeThreshold {
+ /** Lower bound of the band this step colors. The lowest step also colors every value below
+ * it, so `[{ value: 0, color: green }, { value: 80, color: red }]` reads green below 80. */
+ value: number
+ /** Band color: hex, rgb, or `var(--…)`. The gauge resolves `var()` against the page. */
+ color: string
+ /** Band name for the tooltip, such as `'Healthy'`. The tooltip shows the band's range
+ * when this is omitted. */
+ label?: string
+}
+
+/** The range a gauge spans. `min` equals `max` only when both were given and equal. */
+export interface GaugeBounds {
+ min: number
+ max: number
+}
+
+export interface GaugeBand {
+ threshold: GaugeThreshold
+ from: number
+ to: number
+}
+
+export interface GaugeAngles {
+ /** Canvas radians: 0 is 3 o'clock and angles grow clockwise. */
+ start: number
+ end: number
+ sweep: number
+}
+
+export interface GaugeLayout {
+ cx: number
+ cy: number
+ angles: GaugeAngles
+ /** Centerline radius of the track and the value arc. */
+ radius: number
+ thickness: number
+ innerRadius: number
+ /** Outer edge of the outermost ring: the threshold bands when shown, else the track. */
+ outerRadius: number
+ /** Centerline radius of the threshold band ring, 0 when the ring is hidden. */
+ bandRadius: number
+ bandThickness: number
+ /** Lowest y the rings paint, where the min and max labels hang from. */
+ bottom: number
+}
+
+export const DEFAULT_GAUGE_SWEEP = 240
+export const MIN_GAUGE_SWEEP = 180
+export const MAX_GAUGE_SWEEP = 360
+export const DEFAULT_GAUGE_THICKNESS = 0.15
+
+// Ring proportions as fractions of the outer radius, so a gauge keeps its look from 80px to 400px.
+const BAND_RING_THICKNESS = 0.055
+const BAND_RING_GAP = 0.04
+const MIN_THICKNESS = 0.04
+const MAX_THICKNESS = 0.5
+// Proportional rings turn heavy on a large gauge, so they stop growing past these sizes.
+const MAX_THICKNESS_PX = 28
+const MAX_BAND_PX = 8
+const MAX_BAND_GAP_PX = 6
+
+const FULL_TURN = 2 * Math.PI
+
+const isFiniteNumber = (n: number | null | undefined): n is number => typeof n === 'number' && Number.isFinite(n)
+
+const clamp = (n: number, lo: number, hi: number): number => Math.min(Math.max(n, lo), hi)
+
+export function sortThresholds(thresholds: readonly GaugeThreshold[] | undefined): GaugeThreshold[] {
+ return (thresholds ?? []).filter((t) => isFiniteNumber(t.value)).sort((a, b) => a.value - b.value)
+}
+
+export interface ResolveGaugeBoundsInput {
+ /** The value the gauge shows. `null` does not move the range. */
+ value: number | null
+ min?: number | null
+ max?: number | null
+ thresholds?: readonly GaugeThreshold[]
+ /** A target marker value. An inferred range grows to contain it. */
+ target?: number | null
+}
+
+/** The rules are on `GaugeProps.min` and `max`. A threshold ladder that stops short of the value is a
+ * color scale, not the range, so the range still grows to contain the value and the target. */
+export function resolveGaugeBounds({ value, min, max, thresholds, target }: ResolveGaugeBoundsInput): GaugeBounds {
+ const steps = (thresholds ?? []).map((t) => t.value).filter(isFiniteNumber)
+ const contained = [value, target].filter(isFiniteNumber)
+ const explicitMin = isFiniteNumber(min) ? min : undefined
+ const explicitMax = isFiniteNumber(max) ? max : undefined
+
+ if (explicitMin !== undefined && explicitMax !== undefined) {
+ return explicitMin <= explicitMax
+ ? { min: explicitMin, max: explicitMax }
+ : { min: explicitMax, max: explicitMin }
+ }
+
+ // A value under the lowest threshold widens the range to 0 rather than to the value itself, so a
+ // healthy value beneath an alert ladder does not sit at the empty end of the arc.
+ const base = steps.length ? Math.min(...steps) : 0
+ const lowest = Math.min(base, ...contained)
+ let lo = explicitMin ?? (lowest < base ? Math.min(0, lowest) : base)
+ if (explicitMax !== undefined && lo >= explicitMax) {
+ lo = explicitMax - 1
+ }
+ if (explicitMax !== undefined) {
+ return { min: lo, max: explicitMax }
+ }
+ const hi = Math.max(steps.length ? Math.max(...steps) : Math.max(lo + 1, 0), ...contained)
+ return { min: lo, max: hi > lo ? hi : lo + 1 }
+}
+
+/** Where `value` sits in the range, from 0 to 1. Out-of-range values clamp to the nearest end. When
+ * `min` equals `max` the gauge reads empty below that value and full at or above it. */
+export function gaugeFraction(value: number | null, { min, max }: GaugeBounds): number {
+ if (!isFiniteNumber(value)) {
+ return 0
+ }
+ if (max <= min) {
+ return value >= max ? 1 : 0
+ }
+ return clamp((value - min) / (max - min), 0, 1)
+}
+
+/** Index of the sorted threshold that colors `value`: the last step at or below it, or the lowest
+ * step when the value is below every step. -1 when there are no thresholds or no value. */
+export function thresholdIndexAt(value: number | null, sorted: readonly GaugeThreshold[]): number {
+ if (!isFiniteNumber(value) || sorted.length === 0) {
+ return -1
+ }
+ let index = 0
+ for (let i = 1; i < sorted.length; i++) {
+ if (value >= sorted[i].value) {
+ index = i
+ } else {
+ break
+ }
+ }
+ return index
+}
+
+/** Each band clipped to the range. Bands with no visible width are dropped. */
+export function thresholdBands(sorted: readonly GaugeThreshold[], bounds: GaugeBounds): GaugeBand[] {
+ const bands: GaugeBand[] = []
+ for (let i = 0; i < sorted.length; i++) {
+ const from = i === 0 ? bounds.min : Math.max(sorted[i].value, bounds.min)
+ const to = i + 1 < sorted.length ? Math.min(sorted[i + 1].value, bounds.max) : bounds.max
+ if (to > from) {
+ bands.push({ threshold: sorted[i], from, to })
+ }
+ }
+ return bands
+}
+
+/** Below 180° the inner text no longer fits inside the arc. */
+export function clampGaugeSweep(sweepDegrees: number | undefined): number {
+ return isFiniteNumber(sweepDegrees) ? clamp(sweepDegrees, MIN_GAUGE_SWEEP, MAX_GAUGE_SWEEP) : DEFAULT_GAUGE_SWEEP
+}
+
+/** Centered on 12 o'clock so the opening faces down. A full ring starts at 12 o'clock, like a progress ring. */
+export function isFullSweep(sweep: number): boolean {
+ return sweep >= FULL_TURN - 1e-9
+}
+
+export function gaugeAngles(sweepDegrees: number): GaugeAngles {
+ const sweep = (clampGaugeSweep(sweepDegrees) * Math.PI) / 180
+ const start = isFullSweep(sweep) ? -Math.PI / 2 : -Math.PI / 2 - sweep / 2
+ return { start, end: start + sweep, sweep }
+}
+
+export function fractionToAngle(fraction: number, angles: GaugeAngles): number {
+ return angles.start + clamp(fraction, 0, 1) * angles.sweep
+}
+
+interface Box {
+ minX: number
+ maxX: number
+ minY: number
+ maxY: number
+}
+
+function angleInArc(angle: number, angles: GaugeAngles): boolean {
+ const offset = (((angle - angles.start) % FULL_TURN) + FULL_TURN) % FULL_TURN
+ return offset <= angles.sweep + 1e-9
+}
+
+export function ringSectorBox(angles: GaugeAngles, innerRadius: number, outerRadius: number): Box {
+ const points: [number, number][] = []
+ for (const angle of [angles.start, angles.end]) {
+ for (const r of [innerRadius, outerRadius]) {
+ points.push([Math.cos(angle) * r, Math.sin(angle) * r])
+ }
+ }
+ for (let k = 0; k < 4; k++) {
+ const angle = (k * Math.PI) / 2
+ if (angleInArc(angle, angles)) {
+ points.push([Math.cos(angle) * outerRadius, Math.sin(angle) * outerRadius])
+ }
+ }
+ return {
+ minX: Math.min(...points.map((p) => p[0])),
+ maxX: Math.max(...points.map((p) => p[0])),
+ minY: Math.min(...points.map((p) => p[1])),
+ maxY: Math.max(...points.map((p) => p[1])),
+ }
+}
+
+export interface ComputeGaugeLayoutInput {
+ width: number
+ height: number
+ sweep: number
+ /** Arc thickness as a fraction of the outer radius. */
+ thickness: number
+ showBands: boolean
+ /** Pixels reserved under the rings for the min and max labels. */
+ footer: number
+ padding: number
+ /** Leave room past the outer ring for a target tick. */
+ hasTarget?: boolean
+}
+
+export interface TargetTickSize {
+ /** How far the tick runs past the inner and outer ring edges. */
+ overhang: number
+ width: number
+ /** Width of the gap erased around the tick on each side. */
+ gap: number
+}
+
+export function targetTickSize(thickness: number): TargetTickSize {
+ const width = Math.max(2, thickness * 0.16)
+ return { overhang: Math.max(2, thickness * 0.18), width, gap: Math.max(1.5, width * 0.6) }
+}
+
+/** A target tick reaches past the outer ring, so the layout refits with that reach as extra padding. */
+export function computeGaugeLayout(input: ComputeGaugeLayoutInput): GaugeLayout {
+ const layout = fitGaugeLayout(input)
+ if (!input.hasTarget) {
+ return layout
+ }
+ const { overhang, width, gap } = targetTickSize(layout.thickness)
+ return fitGaugeLayout({ ...input, padding: input.padding + overhang + width / 2 + gap })
+}
+
+function fitGaugeLayout({
+ width,
+ height,
+ sweep,
+ thickness,
+ showBands,
+ footer,
+ padding,
+}: ComputeGaugeLayoutInput): GaugeLayout {
+ const angles = gaugeAngles(sweep)
+ const t = isFiniteNumber(thickness) ? clamp(thickness, MIN_THICKNESS, MAX_THICKNESS) : DEFAULT_GAUGE_THICKNESS
+ const trackOuter = showBands ? 1 - BAND_RING_THICKNESS - BAND_RING_GAP : 1
+ const unitBox = ringSectorBox(angles, trackOuter - t, 1)
+ const unitWidth = unitBox.maxX - unitBox.minX
+ const unitHeight = unitBox.maxY - unitBox.minY
+
+ const availableWidth = Math.max(0, width - 2 * padding)
+ const availableHeight = Math.max(0, height - 2 * padding - footer)
+ const outerRadius = Math.max(0, Math.min(availableWidth / unitWidth, availableHeight / unitHeight))
+
+ const contentHeight = unitHeight * outerRadius + footer
+ const top = padding + (Math.max(0, height - 2 * padding) - contentHeight) / 2
+ const left = padding + (availableWidth - unitWidth * outerRadius) / 2
+ const cx = left - unitBox.minX * outerRadius
+ const cy = top - unitBox.minY * outerRadius
+
+ const bandPx = showBands ? Math.min(BAND_RING_THICKNESS * outerRadius, MAX_BAND_PX) : 0
+ const gapPx = showBands ? Math.min(BAND_RING_GAP * outerRadius, MAX_BAND_GAP_PX) : 0
+ const trackOuterPx = outerRadius - bandPx - gapPx
+ const px = Math.min(t * outerRadius, MAX_THICKNESS_PX)
+ return {
+ cx,
+ cy,
+ angles,
+ radius: trackOuterPx - px / 2,
+ thickness: px,
+ innerRadius: trackOuterPx - px,
+ outerRadius,
+ bandRadius: showBands ? outerRadius - bandPx / 2 : 0,
+ bandThickness: bandPx,
+ bottom: cy + unitBox.maxY * outerRadius,
+ }
+}
+
+/** Angle by which a round cap of `thickness` reaches past an arc end, so arcs can be shortened by
+ * it and still end on the exact value angle. */
+export function roundCapInset(radius: number, thickness: number): number {
+ if (radius <= 0) {
+ return 0
+ }
+ return Math.asin(clamp(thickness / 2 / radius, 0, 1))
+}
+
+export function isOverGauge(layout: GaugeLayout, x: number, y: number): boolean {
+ return Math.hypot(x - layout.cx, y - layout.cy) <= layout.outerRadius + 4
+}
+
+export interface GaugeTextBlockInput {
+ layout: GaugeLayout
+ /** Measures `text` in px for a CSS `font` shorthand. */
+ measure: (text: string, font: string) => number
+ fontFamily: string
+ valueText: string
+ labelText: string | null
+}
+
+export interface GaugeTextLine {
+ text: string
+ /** Center x and center y, relative to the chart wrapper. */
+ x: number
+ y: number
+ fontSize: number
+ maxWidth: number
+}
+
+export interface GaugeTextBlock {
+ value: GaugeTextLine
+ label: GaugeTextLine | null
+}
+
+export const GAUGE_VALUE_FONT_WEIGHT = 600
+const MAX_VALUE_FONT = 64
+const MIN_VALUE_FONT = 9
+const MIN_LABEL_FONT = 9
+const MAX_LABEL_FONT = 14
+const LABEL_LINE_HEIGHT = 1.25
+const TEXT_GAP_RATIO = 0.12
+// Glyph widths vary across fonts and the measure can use a different fallback font than the page,
+// so lines stop short of the chord.
+const CHORD_FILL = 0.86
+const FIT_SAFETY = 1.04
+
+function chordWidth(radius: number, dy: number): number {
+ return dy >= radius ? 0 : 2 * Math.sqrt(radius * radius - dy * dy)
+}
+
+/** Size and place the value and the label inside the arc. The value shrinks until it fits the chord
+ * of the inner circle at its line, and the label drops out when the two no longer fit together. */
+export function layoutGaugeText({
+ layout,
+ measure,
+ fontFamily,
+ valueText,
+ labelText,
+}: GaugeTextBlockInput): GaugeTextBlock {
+ const { cx, cy, innerRadius, angles } = layout
+ // The inner edge of the arc ends dips below the center on sweeps past 180°. The text block
+ // stays above those ends so the opening stays clear.
+ const endDip = Math.max(0, Math.sin((angles.sweep - Math.PI) / 2)) * innerRadius
+ const floorY = isFullSweep(angles.sweep) ? cy + innerRadius * 0.7 : cy + endDip * 0.9
+
+ const place = (label: string | null): GaugeTextBlock => {
+ const initialFont = clamp(innerRadius * 0.46, MIN_VALUE_FONT, MAX_VALUE_FONT)
+ let valueFont = initialFont
+ const labelFont = label ? clamp(valueFont * 0.3, MIN_LABEL_FONT, MAX_LABEL_FONT) : 0
+ const gap = label ? valueFont * TEXT_GAP_RATIO : 0
+ const labelHeight = labelFont * LABEL_LINE_HEIGHT
+
+ const blockFor = (font: number): { valueY: number; labelY: number; height: number } => {
+ const height = font + gap + labelHeight
+ let centerY = cy
+ if (centerY + height / 2 > floorY) {
+ centerY = floorY - height / 2
+ }
+ const blockTop = centerY - height / 2
+ return { valueY: blockTop + font / 2, labelY: blockTop + font + gap + labelHeight / 2, height }
+ }
+
+ const valueWidthAt = (font: number): number => {
+ const { valueY } = blockFor(font)
+ const dy = Math.max(Math.abs(valueY - font / 2 - cy), Math.abs(valueY + font / 2 - cy))
+ return chordWidth(innerRadius, dy) * CHORD_FILL
+ }
+
+ const measured = measure(valueText, `${GAUGE_VALUE_FONT_WEIGHT} ${initialFont}px ${fontFamily}`)
+ // Shrinking the font also moves the line, which changes the chord, so iterate a few times.
+ for (let i = 0; i < 4 && measured > 0; i++) {
+ const fit = valueWidthAt(valueFont)
+ const width = (measured * valueFont) / initialFont
+ if (width * FIT_SAFETY <= fit) {
+ break
+ }
+ valueFont = Math.max(MIN_VALUE_FONT, (valueFont * fit) / (width * FIT_SAFETY))
+ }
+
+ const { valueY, labelY } = blockFor(valueFont)
+ const value: GaugeTextLine = {
+ text: valueText,
+ x: cx,
+ y: valueY,
+ fontSize: valueFont,
+ maxWidth: valueWidthAt(valueFont),
+ }
+ if (!label) {
+ return { value, label: null }
+ }
+ const dy = Math.max(Math.abs(labelY - labelHeight / 2 - cy), Math.abs(labelY + labelHeight / 2 - cy))
+ return {
+ value,
+ label: {
+ text: label,
+ x: cx,
+ y: labelY,
+ fontSize: labelFont,
+ maxWidth: chordWidth(innerRadius, dy) * CHORD_FILL,
+ },
+ }
+ }
+
+ if (labelText) {
+ const block = place(labelText)
+ const top = block.value.y - block.value.fontSize / 2
+ const fitsAbove = top >= cy - innerRadius * 0.95
+ if (fitsAbove && block.label && block.label.maxWidth >= MIN_LABEL_FONT * 3) {
+ return block
+ }
+ }
+ return place(null)
+}
diff --git a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
index 6bb4e87990f4..a6cb9840efca 100644
--- a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
+++ b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
@@ -2,6 +2,7 @@ import React, { useMemo, useState } from 'react'
import { Sparkline } from '../../charts/Sparkline/Sparkline'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
+import { useAnimatedNumber } from '../../core/hooks/useAnimatedNumber'
import type { ChartTheme } from '../../core/types'
import {
type ChangeColor,
@@ -13,7 +14,6 @@ import {
DEFAULT_POSITIVE_COLOR,
} from './internals'
import { type MetricChange, resolveDelta } from './resolveDelta'
-import { useAnimatedNumber } from './useAnimatedNumber'
import { useHoverIntent } from './useHoverIntent'
export type { MetricChange }
diff --git a/packages/quill/packages/charts/src/components/MetricCard/useAnimatedNumber.test.tsx b/packages/quill/packages/charts/src/core/hooks/useAnimatedNumber.test.tsx
similarity index 90%
rename from packages/quill/packages/charts/src/components/MetricCard/useAnimatedNumber.test.tsx
rename to packages/quill/packages/charts/src/core/hooks/useAnimatedNumber.test.tsx
index 6d66ba7fd057..061f7e49872a 100644
--- a/packages/quill/packages/charts/src/components/MetricCard/useAnimatedNumber.test.tsx
+++ b/packages/quill/packages/charts/src/core/hooks/useAnimatedNumber.test.tsx
@@ -118,20 +118,23 @@ describe('useAnimatedNumber', () => {
expect(raf.pendingCount()).toBe(0)
})
- it('animates from the previous value toward the new target across frames', () => {
+ it.each([
+ ['an integer range', 0, 100],
+ ['a range where from + (to - from) misses the target in floating point', 0.2, 0.9],
+ ])('animates from the previous value and lands exactly on the target, for %s', (_label, from, to) => {
const { result, rerender } = renderHook(({ target }) => useAnimatedNumber(target, 100), {
- initialProps: { target: 0 },
+ initialProps: { target: from },
})
- rerender({ target: 100 })
+ rerender({ target: to })
expect(raf.pendingCount()).toBe(1)
- expect(result.current).toBe(0)
+ expect(result.current).toBe(from)
raf.step(50)
- expect(result.current).toBeGreaterThan(0)
- expect(result.current).toBeLessThan(100)
+ expect(result.current).toBeGreaterThan(from)
+ expect(result.current).toBeLessThan(to)
raf.step(100)
- expect(result.current).toBe(100)
+ expect(result.current).toBe(to)
expect(raf.pendingCount()).toBe(0)
})
diff --git a/packages/quill/packages/charts/src/components/MetricCard/useAnimatedNumber.ts b/packages/quill/packages/charts/src/core/hooks/useAnimatedNumber.ts
similarity index 80%
rename from packages/quill/packages/charts/src/components/MetricCard/useAnimatedNumber.ts
rename to packages/quill/packages/charts/src/core/hooks/useAnimatedNumber.ts
index d7279fce80a4..c4f6c6a3467e 100644
--- a/packages/quill/packages/charts/src/components/MetricCard/useAnimatedNumber.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useAnimatedNumber.ts
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react'
-import { prefersReducedMotion } from '../../core/motion'
-import { monotonicNow } from '../../core/time'
+import { prefersReducedMotion } from '../motion'
+import { monotonicNow } from '../time'
/** When `target` changes mid-animation, animation restarts from the currently-displayed value (no snap). */
export function useAnimatedNumber(target: number, duration = 120): number {
@@ -27,7 +27,9 @@ export function useAnimatedNumber(target: number, duration = 120): number {
const tick = (): void => {
const t = Math.min(1, (monotonicNow() - start) / duration)
const eased = 1 - Math.pow(1 - t, 3)
- setValue(from + (target - from) * eased)
+ // The last frame sets the target itself, because `from + (target - from) * 1` can miss it by
+ // one ulp and leave a caller that compares against the target waiting for good.
+ setValue(t >= 1 ? target : from + (target - from) * eased)
if (t < 1) {
raf = requestAnimationFrame(tick)
}
diff --git a/packages/quill/packages/charts/src/docs/CONTRIBUTING.md b/packages/quill/packages/charts/src/docs/CONTRIBUTING.md
index da84621b3bbe..660591bc9a79 100644
--- a/packages/quill/packages/charts/src/docs/CONTRIBUTING.md
+++ b/packages/quill/packages/charts/src/docs/CONTRIBUTING.md
@@ -13,7 +13,8 @@ For people working on the library itself — adding a chart type, adjusting the
Where new code goes:
-- Pure geometry (scales, layouts) → `core/scales.ts`, `core/bar-layout.ts`, or a sibling. Test these directly under `core/`.
+- Pure geometry (scales, layouts) that several chart types share → `core/scales.ts`, `core/bar-layout.ts`, or a sibling. Test these directly under `core/`.
+- Pure geometry that only one chart type uses → `charts/<name>/`, next to the chart, with its test beside it.
- Drawing primitives → `core/canvas-renderer.ts`. Stateless, no React.
- Chart-type React → `charts/<name>/<Name>.tsx`.
- DOM overlays → `overlays/<Name>.tsx`. Read context via `useChartLayout()` / `useChartHover()`.
diff --git a/packages/quill/packages/charts/src/docs/TESTING.md b/packages/quill/packages/charts/src/docs/TESTING.md
index 74cf9a405b26..4db9338245bf 100644
--- a/packages/quill/packages/charts/src/docs/TESTING.md
+++ b/packages/quill/packages/charts/src/docs/TESTING.md
@@ -60,6 +60,8 @@ chart.slope.seriesLabels() // slope series names, after collision avoidance
chart.sankey.nodeLabels() // ['/home', '/pricing', …] Sankey node labels in layout order, after overlap hiding
chart.sankey.columnLabels() // ['Step 1', 'Step 2', …] Sankey column headers, left to right
chart.pie.sliceLabels() // [{ text, lines }, …] on-slice labels, one entry per slice
+chart.gauge.text() // { value, label, min, max } text a Gauge shows, null for other charts
+chart.gauge.valueColor() // CSS color of the Gauge value text, null for other charts
```
Gestures work under any wrapper, because the chart records its label count on its root:
diff --git a/packages/quill/packages/charts/src/docs/chart-types.md b/packages/quill/packages/charts/src/docs/chart-types.md
index 1582ac0e279e..261ab7f8478c 100644
--- a/packages/quill/packages/charts/src/docs/chart-types.md
+++ b/packages/quill/packages/charts/src/docs/chart-types.md
@@ -154,6 +154,35 @@ There is no `series` or `labels`.
It does not validate its input: the checks above run in `computeSankeyLayout`, so a host that calls the engine directly validates its own graph.
Links resolve their endpoints by array index by default; for links that name string node ids, call `sankeyLayout().nodeId((node) => node.id)` first.
+## Gauge
+
+One value between a min and a max, as an arc on a track: Apdex, error budget, CPU.
+Takes `value`, `min`, `max`, and `thresholds`, not `series`, and fills its container at a fixed aspect ratio.
+
+```tsx
+<Gauge
+ value={0.91}
+ min={0}
+ max={1}
+ thresholds={[
+ { value: 0, color: 'var(--danger)', label: 'Poor' },
+ { value: 0.85, color: 'var(--success)', label: 'Good' },
+ ]}
+ target={{ value: 0.94, label: 'SLO' }}
+ label="Apdex"
+ theme={theme}
+/>
+```
+
+- `null` draws an empty track and a dash. It never reads as 0.
+- A threshold colors values from its `value` upward, and the lowest one also colors everything below it. Order does not matter. The arc and the value text take the color of the band the value is in, and with two or more thresholds the bands draw as a thin ring outside the track (`showThresholdBands`). Threshold colors may be `var(--…)`; the gauge resolves them, and an unresolvable one falls back to `color`.
+- A missing `min` is the lowest threshold, else 0. A value or target below it widens the range to 0, or to the value when it is negative, so a healthy value under an alert ladder does not read empty. A missing `max` is the highest threshold, else the larger of `min + 1` and 0, and grows to contain the value and the target, so the max label always agrees with where the arc ends. `resolveGaugeBounds` exports the same rule for a host that formats the bounds itself. An explicit range clamps the arc but the number still prints as-is. Inverted bounds swap, and `min === max` reads empty below the value and full at or above it.
+- `config.valueFormatter` formats the value, the min and max labels, and the tooltip. `buildYTickFormatter` builds one from the axis format options (`duration`, `duration_ms`, `percentage`, `currency`, prefix, suffix, decimals).
+- `config.sweepAngle` runs from 180 (a half circle) to 360 (a ring that starts at 12 o'clock); default 240. `config.thickness` is a fraction of the radius, so the look holds from 80px to 400px wide.
+- Text sizes with the radius. The value shrinks to fit the inner circle and truncates only below 9px. The label drops out when it no longer fits under the value, and the min and max labels hide when they would overlap or the sweep passes 300°. The full text stays in the tooltip and the canvas `aria-label`.
+- A value change eases over `config.animationMs` (default 500), and the arc color follows the bands as it passes them. The first render, `animationMs: 0`, and reduced motion snap.
+- The tooltip shows the value, the range, the threshold band (its `label`, else its range), and the target. A `tooltip` render prop receives `GaugeTooltipContext`: the `TooltipContext` plus the value, the range, the band, and the target. `formatGaugeBand` formats a band the way the default tooltip does.
+
## Sparkline
An axis-less preset over `LineChart` (default, gradient-filled line) or stacked bars via `type: 'bar'`.
diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.ts
index fa3270e73a00..f4b8725eca93 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -49,7 +49,7 @@ export type { MetricCardProps, ChangeColor, MetricChange } from './components/Me
export { resolveDelta } from './components/MetricCard/resolveDelta'
export type { ResolvedDelta } from './components/MetricCard/resolveDelta'
export { computeFallbackChangePercent } from './components/MetricCard/internals'
-export { useAnimatedNumber } from './components/MetricCard/useAnimatedNumber'
+export { useAnimatedNumber } from './core/hooks/useAnimatedNumber'
export { useHoverIntent } from './components/MetricCard/useHoverIntent'
// Base chart (for building new chart types)
@@ -115,6 +115,14 @@ export { useRadialLayout } from './core/radial-context'
export type { RadialLayoutContextValue } from './core/radial-context'
export type { RadialSlicePayload } from './core/hooks/useRadialInteraction'
+// Gauge
+export { Gauge } from './charts/Gauge/Gauge'
+export type { GaugeConfig, GaugeProps, GaugeTarget } from './charts/Gauge/Gauge'
+export { formatGaugeBand, GaugeTooltip } from './charts/Gauge/GaugeTooltip'
+export type { GaugeTooltipContext, GaugeTooltipProps, GaugeTooltipThreshold } from './charts/Gauge/GaugeTooltip'
+export { resolveGaugeBounds } from './charts/Gauge/gauge-layout'
+export type { GaugeBounds, GaugeThreshold, ResolveGaugeBoundsInput } from './charts/Gauge/gauge-layout'
+
// Proportion bar
export { ProportionBar } from './charts/ProportionBar/ProportionBar'
export type { ProportionBarConfig, ProportionBarProps } from './charts/ProportionBar/ProportionBar'
diff --git a/packages/quill/packages/charts/src/overlays/Tooltip.tsx b/packages/quill/packages/charts/src/overlays/Tooltip.tsx
index 8d2172543448..44e7a975dc01 100644
--- a/packages/quill/packages/charts/src/overlays/Tooltip.tsx
+++ b/packages/quill/packages/charts/src/overlays/Tooltip.tsx
@@ -4,9 +4,9 @@ import React, { createContext, useContext, useLayoutEffect, useMemo } from 'reac
import { useChartLayout } from '../core/chart-context'
import type { TooltipContext } from '../core/types'
-interface TooltipProps<Meta> {
- context: TooltipContext<Meta>
- renderTooltip: (ctx: TooltipContext<Meta>) => React.ReactNode
+interface TooltipProps<Ctx> {
+ context: Ctx
+ renderTooltip: (ctx: Ctx) => React.ReactNode
placement?: 'follow-data' | 'top' | 'cursor'
}
@@ -22,11 +22,11 @@ export function useTooltipCapture<Meta>(): (ctx: TooltipContext<Meta>) => void {
const TOOLTIP_MIDDLEWARE = [offset(12), flip(), shift({ padding: 8 })]
const DEFAULT_TOOLTIP_Z_INDEX = 9999
-export function Tooltip<Meta = unknown>({
+export function Tooltip<Meta = unknown, Ctx extends TooltipContext<Meta> = TooltipContext<Meta>>({
context,
renderTooltip,
placement = 'follow-data',
-}: TooltipProps<Meta>): React.ReactElement {
+}: TooltipProps<Ctx>): React.ReactElement {
const { theme } = useChartLayout()
useTooltipCapture<Meta>()(context)
const zIndex = theme.tooltipZIndex ?? DEFAULT_TOOLTIP_Z_INDEX
diff --git a/packages/quill/packages/charts/src/testing/accessor.ts b/packages/quill/packages/charts/src/testing/accessor.ts
index 93b55fa0e36c..3e8485c5287b 100644
--- a/packages/quill/packages/charts/src/testing/accessor.ts
+++ b/packages/quill/packages/charts/src/testing/accessor.ts
@@ -68,6 +68,13 @@ interface SlopeValueLabelSummary {
side: 'start' | 'end'
}
+interface GaugeSummary {
+ value: string
+ label: string | null
+ min: string | null
+ max: string | null
+}
+
interface PieSliceLabelSummary {
text: string
/** One entry per rendered line (label and/or value). */
@@ -124,6 +131,13 @@ export interface ChartAccessor<Meta = unknown> {
/** On-slice labels, in slice order. */
sliceLabels(): PieSliceLabelSummary[]
}
+ gauge: {
+ /** The text a `Gauge` shows, or null for other charts. `label`, `min` and `max` are null when
+ * hidden, for example when the min and max labels would overlap. */
+ text(): GaugeSummary | null
+ /** The CSS color of the value text, or null for other charts. */
+ valueColor(): string | null
+ }
/** The legend container in this chart's render scope, or null when the legend is hidden. */
legend(): HTMLElement | null
/** Legend rows in this chart's render scope — label plus the row's secondary text (a slope
@@ -251,6 +265,8 @@ export function getChart<Meta = unknown>(
}
return count
}
+ const gaugePart = (part: string): HTMLElement | null =>
+ wrapper.querySelector<HTMLElement>(`[data-attr="hog-chart-gauge-${part}"]`)
return {
element: wrapper,
@@ -319,6 +335,14 @@ export function getChart<Meta = unknown>(
})
),
},
+ gauge: {
+ text: () => {
+ const text = (part: string): string | null => gaugePart(part)?.textContent ?? null
+ const value = text('value')
+ return value === null ? null : { value, label: text('label'), min: text('min'), max: text('max') }
+ },
+ valueColor: () => gaugePart('value')?.style.color ?? null,
+ },
legend: () => scope.querySelector<HTMLElement>('[data-hog-charts-legend]'),
legendItems: () => readLegendItems(scope),
clickLegendItem(label: string, { additive = false }: { additive?: boolean } = {}): void {