mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-22 12:43:32 +09:00
fix(dashboard): make metric samples readable without a pointer
The charts are a canvas and their legend showed dashes until a point was hovered, so keyboard and screen-reader users could not read any sample. The legend now shows each series' latest value when nothing is hovered, and every panel has a Show data toggle that opens a focusable table of all samples, newest first, in the chart's units. Assisted-by: LLM Signed-off-by: ZverGuy <maximbel2003@gmail.com>
This commit is contained in:
1 parent
1e1fdb740c
commit
8e6048eb4a
6 files changed
+160
-8
No files matched your search
+26
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi } from "vitest"
|
||||
import { screen, waitFor } from "@testing-library/react"
|
||||
import { screen, waitFor, within } from "@testing-library/react"
|
||||
import userEvent from "@testing-library/user-event"
|
||||
import { K8sClient } from "@cozystack/k8s-client"
|
||||
import { renderWithK8sProvider } from "../../test-utils/render.tsx"
|
||||
@@ -98,6 +98,31 @@ describe("MetricsView", () => {
|
||||
expect(screen.queryByText("Try a longer range.")).toBeNull()
|
||||
})
|
||||
|
||||
it("shows a panel's samples as a table on request", async () => {
|
||||
const { client } = clientWith(() => matrix("db-0"))
|
||||
renderWithK8sProvider(<MetricsView scope={scope} />, { client })
|
||||
await waitFor(() => expect(screen.getAllByTestId("chart")).toHaveLength(3))
|
||||
const toggle = screen.getByRole("button", { name: "Show data for CPU (cores)" })
|
||||
expect(toggle).toHaveAttribute("aria-expanded", "false")
|
||||
|
||||
await userEvent.click(toggle)
|
||||
|
||||
const table = screen.getByRole("region", { name: "CPU (cores) data" })
|
||||
expect(toggle).toHaveAttribute("aria-expanded", "true")
|
||||
expect(toggle).toHaveAttribute("aria-controls", table.id)
|
||||
expect(toggle).toHaveTextContent("Hide data")
|
||||
expect(within(table).getByRole("columnheader", { name: "db-0" })).toBeInTheDocument()
|
||||
expect(screen.queryByRole("region", { name: "Memory (working set) data" })).toBeNull()
|
||||
})
|
||||
|
||||
it("offers no table while a panel has no samples", () => {
|
||||
const { client } = clientWith(() => new Promise<Response>(() => {}))
|
||||
|
||||
renderWithK8sProvider(<MetricsView scope={scope} />, { client })
|
||||
|
||||
expect(screen.getByRole("button", { name: "Show data for Network" })).toBeDisabled()
|
||||
})
|
||||
|
||||
it("holds each chart's place while it loads", () => {
|
||||
const { client } = clientWith(() => new Promise<Response>(() => {}))
|
||||
|
||||
|
||||
+32
-4
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react"
|
||||
import { useId, useState } from "react"
|
||||
import { useQueries } from "@tanstack/react-query"
|
||||
import { useK8sClient } from "@cozystack/k8s-client"
|
||||
import { Section } from "@cozystack/ui"
|
||||
import { Button, Section } from "@cozystack/ui"
|
||||
import {
|
||||
METRIC_PANELS,
|
||||
RANGES,
|
||||
@@ -14,6 +14,7 @@ import { ProxyNotice } from "./ProxyNotice.tsx"
|
||||
import { TimeSeriesChart } from "./TimeSeriesChart.tsx"
|
||||
import { RangePicker } from "./RangePicker.tsx"
|
||||
import { EmptyState } from "./EmptyState.tsx"
|
||||
import { SeriesTable } from "./SeriesTable.tsx"
|
||||
|
||||
const REFRESH_MS = 60_000
|
||||
// The uPlot canvas plus its one-row legend, so a placeholder takes the chart's place without a jump.
|
||||
@@ -23,6 +24,8 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
|
||||
const client = useK8sClient()
|
||||
const root = metricsRoot(scope)
|
||||
const [range, setRange] = useState<RangeKey>("1h")
|
||||
const [tables, setTables] = useState<ReadonlySet<string>>(new Set())
|
||||
const idBase = useId()
|
||||
const rangeKeys = Object.keys(RANGES) as RangeKey[]
|
||||
const longestRange = range === rangeKeys[rangeKeys.length - 1]
|
||||
|
||||
@@ -57,8 +60,30 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
|
||||
) : (
|
||||
METRIC_PANELS.map((panel, i) => {
|
||||
const { data, error, isLoading } = results[i]
|
||||
const hasSeries = !error && !isLoading && !!data && data.series.length > 0
|
||||
const tableOpen = hasSeries && tables.has(panel.id)
|
||||
const tableId = `${idBase}-${panel.id}-data`
|
||||
const toggle = (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!hasSeries}
|
||||
aria-expanded={tableOpen}
|
||||
aria-controls={tableOpen ? tableId : undefined}
|
||||
onClick={() =>
|
||||
setTables((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (!next.delete(panel.id)) next.add(panel.id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
>
|
||||
{tableOpen ? "Hide data" : "Show data"}{" "}
|
||||
<span className="sr-only">for {panel.title}</span>
|
||||
</Button>
|
||||
)
|
||||
return (
|
||||
<Section key={panel.id} title={panel.title}>
|
||||
<Section key={panel.id} title={panel.title} actions={toggle}>
|
||||
{error ? (
|
||||
<ProxyNotice what="Metrics" error={error} />
|
||||
) : isLoading || !data ? (
|
||||
@@ -66,7 +91,10 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
|
||||
) : data.series.length === 0 ? (
|
||||
<EmptyState title="No data for this range." hint={longestRange ? undefined : "Try a longer range."} className={CHART_SLOT} />
|
||||
) : (
|
||||
<TimeSeriesChart data={data} format={panel.format} />
|
||||
<>
|
||||
<TimeSeriesChart data={data} format={panel.format} />
|
||||
{tableOpen && <SeriesTable id={tableId} title={panel.title} data={data} format={panel.format} />}
|
||||
</>
|
||||
)}
|
||||
</Section>
|
||||
)
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect } from "vitest"
|
||||
import { render, screen, within } from "@testing-library/react"
|
||||
import { SeriesTable } from "./SeriesTable.tsx"
|
||||
|
||||
const data = {
|
||||
timestamps: [1_700_000_000, 1_700_000_060],
|
||||
series: [
|
||||
{ label: "db-0", values: [1, 2] },
|
||||
{ label: "db-1", values: [null, 3] },
|
||||
],
|
||||
}
|
||||
|
||||
describe("SeriesTable", () => {
|
||||
it("is a named region the keyboard can reach", () => {
|
||||
render(<SeriesTable id="t" title="Memory" data={data} format={String} />)
|
||||
|
||||
const region = screen.getByRole("region", { name: "Memory data" })
|
||||
expect(region).toHaveAttribute("id", "t")
|
||||
expect(region).toHaveAttribute("tabindex", "0")
|
||||
})
|
||||
|
||||
it("has a time column and one column per series", () => {
|
||||
render(<SeriesTable id="t" title="Memory" data={data} format={String} />)
|
||||
|
||||
expect(screen.getAllByRole("columnheader").map((h) => h.textContent)).toEqual(["Time", "db-0", "db-1"])
|
||||
})
|
||||
|
||||
it("lists every sample newest first in the chart's units", () => {
|
||||
render(<SeriesTable id="t" title="Memory" data={data} format={(v) => `${v} B`} />)
|
||||
|
||||
const rows = screen.getAllByRole("row").slice(1)
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(within(rows[0]).getAllByRole("cell").map((c) => c.textContent)).toEqual(["2 B", "3 B"])
|
||||
expect(within(rows[1]).getAllByRole("cell").map((c) => c.textContent)).toEqual(["1 B", "–"])
|
||||
expect(within(rows[0]).getByRole("rowheader")).toHaveTextContent(new Date(1_700_000_060_000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }))
|
||||
})
|
||||
})
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import type { ChartData } from "../../lib/observability/metrics.ts"
|
||||
|
||||
interface SeriesTableProps {
|
||||
id: string
|
||||
title: string
|
||||
data: ChartData
|
||||
format: (value: number) => string
|
||||
}
|
||||
|
||||
const formatTime = (seconds: number) =>
|
||||
new Date(seconds * 1000).toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" })
|
||||
|
||||
export function SeriesTable({ id, title, data, format }: SeriesTableProps) {
|
||||
const newestFirst = data.timestamps.map((t, i) => ({ t, i })).reverse()
|
||||
return (
|
||||
<div
|
||||
id={id}
|
||||
role="region"
|
||||
aria-label={`${title} data`}
|
||||
tabIndex={0}
|
||||
className="mt-3 max-h-64 overflow-auto rounded-md border border-slate-200 outline-none focus-visible:ring-2 focus-visible:ring-slate-400 focus-visible:ring-offset-2"
|
||||
>
|
||||
<table className="w-full text-xs tabular-nums">
|
||||
<caption className="sr-only">{`${title}, newest first`}</caption>
|
||||
<thead className="sticky top-0 bg-slate-50 text-slate-500">
|
||||
<tr>
|
||||
<th scope="col" className="px-3 py-1.5 text-left font-medium">Time</th>
|
||||
{data.series.map((s, j) => (
|
||||
<th key={j} scope="col" className="px-3 py-1.5 text-right font-medium">{s.label}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100 text-slate-700">
|
||||
{newestFirst.map(({ t, i }) => (
|
||||
<tr key={t}>
|
||||
<th scope="row" className="px-3 py-1 text-left font-normal whitespace-nowrap">{formatTime(t)}</th>
|
||||
{data.series.map((s, j) => {
|
||||
const v = s.values[i]
|
||||
return <td key={j} className="px-3 py-1 text-right">{v === null ? "–" : format(v)}</td>
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+15
-2
@@ -1,12 +1,15 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest"
|
||||
import { render } from "@testing-library/react"
|
||||
|
||||
const created: { opts: { series: { label?: string }[] }; data: unknown[]; destroy: ReturnType<typeof vi.fn> }[] = []
|
||||
type LegendValue = (u: unknown, v: number | null, sidx: number, idx: number | null) => string
|
||||
type Opts = { series: { label?: string; value?: LegendValue }[] }
|
||||
|
||||
const created: { opts: Opts; data: unknown[]; destroy: ReturnType<typeof vi.fn> }[] = []
|
||||
|
||||
vi.mock("uplot", () => ({
|
||||
default: class {
|
||||
destroy = vi.fn()
|
||||
constructor(opts: { series: { label?: string }[] }, data: unknown[]) {
|
||||
constructor(opts: Opts, data: unknown[]) {
|
||||
created.push({ opts, data, destroy: this.destroy })
|
||||
}
|
||||
setSize() {}
|
||||
@@ -36,6 +39,16 @@ describe("TimeSeriesChart", () => {
|
||||
expect(created[0].opts.series.slice(1).map((s) => s.label)).toEqual(["db-0", "db-1"])
|
||||
})
|
||||
|
||||
it("shows each series' latest value in the legend while nothing is hovered", () => {
|
||||
render(<TimeSeriesChart data={{ ...data, timestamps: [1, 2, 3], series: [{ label: "db-0", values: [1, 2, null] }] }} format={(v) => `${v} B`} />)
|
||||
|
||||
const legend = created[0].opts.series[1].value!
|
||||
|
||||
expect(legend(null, null, 1, null)).toBe("2 B")
|
||||
expect(legend(null, 1, 1, 0)).toBe("1 B")
|
||||
expect(legend(null, null, 1, 2)).toBe("–")
|
||||
})
|
||||
|
||||
it("destroys the chart on unmount", () => {
|
||||
const { unmount } = render(<TimeSeriesChart data={data} format={String} />)
|
||||
|
||||
|
||||
+3
-1
@@ -18,6 +18,7 @@ export function TimeSeriesChart({ data, format }: TimeSeriesChartProps) {
|
||||
const el = ref.current
|
||||
if (!el) return
|
||||
const fmt = (v: number | null) => (v === null ? "–" : format(v))
|
||||
const latest = data.series.map((s) => s.values.findLast((v) => v !== null) ?? null)
|
||||
const chart = new uPlot(
|
||||
{
|
||||
width: el.clientWidth || 600,
|
||||
@@ -30,7 +31,8 @@ export function TimeSeriesChart({ data, format }: TimeSeriesChartProps) {
|
||||
label: s.label,
|
||||
stroke: COLORS[i % COLORS.length],
|
||||
width: 1.5,
|
||||
value: (_: uPlot, v: number | null) => fmt(v),
|
||||
// Without a hovered point the legend shows the latest sample instead of a dash.
|
||||
value: (_: uPlot, v: number | null, sidx: number, idx: number | null) => fmt(idx === null ? latest[sidx - 1] : v),
|
||||
})),
|
||||
],
|
||||
axes: [{}, { size: 84, values: (_: uPlot, splits: number[]) => splits.map(format) }],
|
||||
|
||||
Reference in new issue
Block a user