A year of history, one chart, and a read API with personal tokens

History: server load, memory and disks are also kept as hourly (four months) and
daily (over two years) averages with lowest and highest; endpoint answers as
hourly (four months) beside the daily figures. Charts ask for 24 hours to a year
and are drawn from whichever is fine enough. A disk that two weeks call flat is
looked at again over ninety days for the forecast. Built once from what is kept.

One chart: TimeChart replaces the sparkline and the multi-line chart: hover and
arrow-key readout, a lowest/highest band, gaps shown as gaps, the same ranges
everywhere and the choice remembered. Used for server trends, comparing servers,
a check's availability and answer times (Endpoints > History) and a server's
availability.

Read API: /api/v1 (servers, metrics, alerts, incidents, inventory, network,
endpoints and their history, maintenance) with personal read-only tokens made
under the user menu: shown once, hashed, 30/90/365 days or none, ten at most,
removed with their owner. GET only. Documented in API.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-20 20:22:58 +02:00
1 parent 5e26e77340
commit 68b41b5586
47 files changed
+12360 -247

No files matched your search

+2
View File
@@ -8,6 +8,7 @@ import Secrets from "./pages/Secrets";
import Ipam from "./pages/Ipam";
import NetworkDevices from "./pages/NetworkDevices";
import MyWorkPage from "./pages/MyWork";
import ApiTokens from "./pages/ApiTokens";
import Ports from "./pages/Ports";
import Dns from "./pages/Dns";
import Servers from "./pages/Servers";
@@ -136,6 +137,7 @@ function Shelled({ user }: { user: CurrentUser }) {
<Routes>
<Route path="/" element={<Dashboard user={user} />} />
<Route path="/my-work" element={<MyWorkPage user={user} />} />
<Route path="/api-tokens" element={<ApiTokens />} />
<Route path="/map" element={<MapPage user={user} />} />
<Route path="/servers" element={<Servers user={user} />} />
<Route path="/servers/compare" element={<ServerCompare />} />
+32 -2
View File
@@ -305,7 +305,8 @@ export interface ServerMetricSeries {
metric: string;
kind: "cpu" | "mem" | "disk";
label: string;
points: { t: string; v: number }[];
/** `lo` and `hi` are there when a point stands for an hour or a day: the lowest and highest figure in it. */
points: { t: string; v: number; lo?: number; hi?: number }[];
latest: number | null;
/** Disks only: the rate of change in points a day, and the days until full when it is rising. */
trend: { perDay: number; fit: number; spanDays: number; daysToFull: number | null } | null;
@@ -907,6 +908,29 @@ export interface EndpointCheck {
server: { id: number; name: string } | null;
stats?: EndpointStats;
}
/** How one check has done over a stretch (GET /api/endpoints/:id/history). */
export interface EndpointHistory {
check: { id: number; name: string };
days: number;
/** Which figures it is drawn from: each answer (a day or two), the hourly figures, or the daily ones. */
source: "results" | "hourly" | "daily";
points: { t: string; availability: number | null; avgMs: number | null; maxMs: number | null; checks: number }[];
availability: number | null;
avgMs: number | null;
checks: number;
}
/** One of a person's own read-only API tokens; the secret is only ever shown when it is made. */
export interface ApiToken {
id: number;
label: string;
tokenPrefix: string;
createdAt: string;
lastUsedAt: string | null;
expiresAt: string | null;
expired: boolean;
}
export interface EndpointInput {
name: string;
kind: EndpointKind;
@@ -2155,7 +2179,12 @@ export const api = {
markChangesSeen: () => request<{ lastLookedAt: string }>("/api/me/changes/seen", { method: "POST" }),
}),
uptime: {
get: () => request<UptimeReport>("/api/uptime"),
get: (days?: number) => request<UptimeReport>(days ? `/api/uptime?days=${days}` : "/api/uptime"),
},
apiTokens: {
list: () => request<{ tokens: ApiToken[]; max: number; expiryChoices: number[] }>("/api/me/tokens"),
create: (data: { label: string; expiresInDays: number | null }) => request<{ token: ApiToken; secret: string }>("/api/me/tokens", { method: "POST", body: JSON.stringify(data) }),
remove: (id: number) => request<void>(`/api/me/tokens/${id}`, { method: "DELETE" }),
},
metricsTokens: {
list: () => request<{ tokens: MetricsToken[] }>("/api/metrics-tokens"),
@@ -2204,6 +2233,7 @@ export const api = {
update: (id: number, data: EndpointInput) => request<{ check: EndpointCheck }>(`/api/endpoints/${id}`, { method: "PUT", body: JSON.stringify(data) }),
remove: (id: number) => request<void>(`/api/endpoints/${id}`, { method: "DELETE" }),
check: (id: number) => request<{ result: { ok: boolean; ms: number | null; message: string } }>(`/api/endpoints/${id}/check`, { method: "POST" }),
history: (id: number, days: number) => request<EndpointHistory>(`/api/endpoints/${id}/history?days=${days}`),
suggestions: () => request<{ suggestions: EndpointSuggestion[]; dismissed: EndpointSuggestion[] }>("/api/endpoints/suggestions"),
addSuggestions: (keys: string[]) => request<{ added: { id: number; name: string }[] }>("/api/endpoints/suggestions/add", { method: "POST", body: JSON.stringify({ keys }) }),
dismissSuggestions: (keys: string[]) => request<{ suggestions: EndpointSuggestion[]; dismissed: EndpointSuggestion[] }>("/api/endpoints/suggestions/dismiss", { method: "POST", body: JSON.stringify({ keys }) }),
+1
View File
@@ -322,6 +322,7 @@ export default function CommandPalette({
items.push({ key: `dep-int-${i.id}`, category: "Dependencies", title: `What depends on ${i.name}?`, subtitle: `${i.type} · opens the dependency map`, path: `/map?view=dependencies&select=integration:${i.id}`, keywords: "depends dependency impact down" });
}
}
items.push({ key: "act-tokens", category: "Actions", title: "API tokens", subtitle: "Read-only access for scripts and Home Assistant", path: "/api-tokens", keywords: "api token key read home assistant script bearer" });
items.push({ key: "act-shortcuts", category: "Actions", title: "Show keyboard shortcuts", subtitle: "", hint: "?", run: () => void window.dispatchEvent(new Event(SHOW_SHORTCUTS_EVENT)), keywords: "keys help" });
if (user.role === "admin") {
// Each setting, so "quiet hours" or "flapping" finds the place it is set.
+86
View File
@@ -0,0 +1,86 @@
import { useEffect, useMemo, useState } from "react";
import { api, type EndpointHistory as History } from "../api/client";
import DetailDrawer from "./DetailDrawer";
import RangeSelect from "./RangeSelect";
import TimeChart from "./TimeChart";
import { BlockSkeleton } from "./Skeleton";
import { ErrorNotice } from "./Notice";
import { CHART_RANGES, useChartRange } from "../utils/chartRanges";
import { readableError } from "../utils/errors";
const SOURCE_WORDS: Record<History["source"], string> = {
results: "each answer",
hourly: "the hourly figures",
daily: "the daily figures",
};
/** How one check has done: availability and answer times over a day to a year, drawn with the same chart as everything else. */
export default function EndpointHistory({ checkId, name, onClose }: { checkId: number; name: string; onClose: () => void }) {
const [days, setDays] = useChartRange(7);
const [history, setHistory] = useState<History | null>(null);
const [error, setError] = useState<string | null>(null);
const [to, setTo] = useState(() => Date.now());
useEffect(() => {
let alive = true;
setError(null);
api.endpoints
.history(checkId, days)
.then((res) => {
if (!alive) return;
setHistory(res);
setTo(Date.now());
})
.catch((err) => alive && setError(readableError(err)));
return () => {
alive = false;
};
}, [checkId, days]);
const from = to - days * 86_400_000;
const rangeLabel = CHART_RANGES.find((r) => r.days === days)?.label ?? `${days} days`;
const availability = useMemo(() => [{ name: "Availability", color: "#2fb344", points: (history?.points ?? []).filter((p) => p.availability !== null).map((p) => ({ t: p.t, v: p.availability as number })) }], [history]);
// The line is the average answer time; the band reaches up to the slowest.
const answer = useMemo(() => [{ name: "Answer time", color: "#4299e1", points: (history?.points ?? []).filter((p) => p.avgMs !== null).map((p) => ({ t: p.t, v: p.avgMs as number, lo: p.avgMs as number, hi: (p.maxMs ?? p.avgMs) as number })) }], [history]);
return (
<DetailDrawer title={name} subtitle="How it has done" onClose={onClose}>
<div className="mb-3">
<RangeSelect value={days} onChange={setDays} />
</div>
<ErrorNotice error={error} />
{!history && !error && <BlockSkeleton lines={5} />}
{history && (
<>
<div className="row g-3 mb-3">
<div className="col-4">
<div className="h3 mb-0">{history.availability === null ? "—" : `${history.availability}%`}</div>
<div className="text-secondary small">answered</div>
</div>
<div className="col-4">
<div className="h3 mb-0">{history.avgMs === null ? "—" : `${history.avgMs} ms`}</div>
<div className="text-secondary small">average answer</div>
</div>
<div className="col-4">
<div className="h3 mb-0">{history.checks}</div>
<div className="text-secondary small">checks</div>
</div>
</div>
<h4 className="mb-1">Availability</h4>
<div className="mb-3">
<TimeChart series={availability} from={from} to={to} label={`${name}: availability over the last ${rangeLabel}`} bars={history.points.length <= 120} barColor={(v) => (v >= 99.9 ? "#2fb344" : v >= 90 ? "#f59f00" : "#f03e3e")} empty="No checks in this stretch yet." />
</div>
<h4 className="mb-1">Answer time</h4>
<TimeChart series={answer} from={from} to={to} unit="ms" label={`${name}: answer time over the last ${rangeLabel}`} empty="No timed answers in this stretch yet." />
<div className="text-secondary small mt-2">
Drawn from {SOURCE_WORDS[history.source]}.
{history.source !== "results" && " Each point is an average of the answers in it; the shaded band reaches up to the slowest."}
{history.source === "daily" && " A day's slowest answer is not kept, so the band follows the average."}
</div>
</>
)}
</DetailDrawer>
);
}
-53
View File
@@ -1,53 +0,0 @@
import { formatDate, formatTime } from "../utils/date";
export interface ChartSeries {
name: string;
color: string;
/** SVG dash pattern, so lines can be told apart without their colour. Empty for a solid line. */
dash: string;
points: { t: string; v: number }[];
}
const W = 720;
const H = 260;
const PAD = { left: 40, right: 12, top: 10, bottom: 26 };
/**
* Several percentage lines over the same stretch of time, on a fixed 0–100% scale (so a quiet server never looks as busy as a loaded
* one). Each line has its own colour and dash pattern. It is a picture: the numbers are in the table beside it.
*/
export default function MultiLineChart({ series, from, to, label }: { series: ChartSeries[]; from: number; to: number; label: string }) {
const x = (t: number) => PAD.left + ((t - from) / Math.max(to - from, 1)) * (W - PAD.left - PAD.right);
const y = (v: number) => PAD.top + (1 - Math.min(100, Math.max(0, v)) / 100) * (H - PAD.top - PAD.bottom);
const ticks = [0, 0.25, 0.5, 0.75, 1].map((f) => from + f * (to - from));
const spanDays = (to - from) / 86_400_000;
const tickLabel = (t: number) => (spanDays <= 1.5 ? formatTime(new Date(t), false) : formatDate(new Date(t)).replace(/^\d{4}-|\/\d{4}$/, ""));
return (
<svg viewBox={`0 0 ${W} ${H}`} className="multi-chart" role="img" aria-label={label}>
{[0, 25, 50, 75, 100].map((v) => (
<g key={v}>
<line x1={PAD.left} x2={W - PAD.right} y1={y(v)} y2={y(v)} stroke="currentColor" strokeOpacity={v === 0 ? 0.4 : 0.15} />
<text x={PAD.left - 6} y={y(v) + 4} textAnchor="end" fontSize="11" fill="currentColor" fillOpacity="0.7">
{v}%
</text>
</g>
))}
{ticks.map((t, i) => (
<text key={i} x={x(t)} y={H - 6} textAnchor={i === 0 ? "start" : i === ticks.length - 1 ? "end" : "middle"} fontSize="11" fill="currentColor" fillOpacity="0.7">
{tickLabel(t)}
</text>
))}
{series.map((s) => {
if (s.points.length === 0) return null;
const d = s.points.map((p, i) => `${i === 0 ? "M" : "L"}${x(Date.parse(p.t)).toFixed(1)},${y(p.v).toFixed(1)}`).join(" ");
return s.points.length === 1 ? (
<circle key={s.name} cx={x(Date.parse(s.points[0].t))} cy={y(s.points[0].v)} r="3" fill={s.color} />
) : (
<path key={s.name} d={d} fill="none" stroke={s.color} strokeWidth="2" strokeDasharray={s.dash || undefined} strokeLinejoin="round" strokeLinecap="round" />
);
})}
</svg>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { CHART_RANGES } from "../utils/chartRanges";
/** The one way to choose how far back a chart looks: 24 hours, 7, 30 or 90 days, or a year. */
export default function RangeSelect({ value, onChange, label = "Time range", only }: { value: number; onChange: (days: number) => void; label?: string; /** Offer only these (in days), for a chart that has no use for the shortest. */ only?: number[] }) {
return (
<div className="btn-group btn-group-sm" role="group" aria-label={label}>
{CHART_RANGES.filter((r) => !only || only.includes(r.days)).map((r) => (
<button key={r.days} type="button" className={`btn ${value === r.days ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={value === r.days} onClick={() => onChange(r.days)}>
{r.label}
</button>
))}
</div>
);
}
+38 -38
View File
@@ -1,13 +1,9 @@
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { api, type ServerMetricSeries } from "../api/client";
import Sparkline from "./Sparkline";
import TimeChart from "./TimeChart";
import RangeSelect from "./RangeSelect";
import { BlockSkeleton } from "./Skeleton";
const RANGES = [
{ days: 1, label: "24 hours" },
{ days: 7, label: "7 days" },
{ days: 30, label: "30 days" },
];
import { CHART_RANGES, useChartRange } from "../utils/chartRanges";
function levelColor(series: ServerMetricSeries): string {
const v = series.latest ?? 0;
@@ -26,40 +22,48 @@ function describeTrend(series: ServerMetricSeries): string {
if (series.kind === "disk") return "not enough history for a trend yet";
const values = series.points.map((p) => p.v);
if (values.length === 0) return "";
return `${Math.round(Math.min(...values))}–${Math.round(Math.max(...values))}% over this time`;
// With hourly or daily figures the line is an average: the real lowest and highest are in the band.
const lo = Math.min(...series.points.map((p) => p.lo ?? p.v));
const hi = Math.max(...series.points.map((p) => p.hi ?? p.v));
return `${Math.round(lo)}–${Math.round(hi)}% over this time`;
}
/** How an agent-reported server's load, memory and disks have moved lately, with a forecast for a filling disk. */
/** How an agent-reported server's load, memory and disks have moved over a day to a year, with a forecast for a filling disk. */
export default function ServerTrends({ serverId }: { serverId: number }) {
const [days, setDays] = useState(7);
const [days, setDays] = useChartRange(7);
const [series, setSeries] = useState<ServerMetricSeries[] | null>(null);
const [failed, setFailed] = useState(false);
// Fixed per load, so the right-hand end of a chart is when it was read and does not creep as the page re-renders.
const [to, setTo] = useState(() => Date.now());
useEffect(() => {
let alive = true;
setFailed(false);
api.servers
.metrics(serverId, days)
.then((res) => alive && setSeries(res.series))
.then((res) => {
if (!alive) return;
setSeries(res.series);
setTo(Date.now());
})
.catch(() => alive && setFailed(true));
return () => {
alive = false;
};
}, [serverId, days]);
const from = to - days * 86_400_000;
const rangeLabel = CHART_RANGES.find((r) => r.days === days)?.label ?? `${days} days`;
const charts = useMemo(
() => (series ?? []).map((s) => ({ s, words: describeTrend(s), series: [{ name: s.label, color: levelColor(s), points: s.points }] })),
[series],
);
return (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Trends</h3>
<div className="card-actions">
<select className="form-select form-select-sm" value={days} onChange={(e) => setDays(Number(e.target.value))} aria-label="Time range">
{RANGES.map((r) => (
<option key={r.days} value={r.days}>
Last {r.label}
</option>
))}
</select>
</div>
<div className="card-header d-flex flex-wrap gap-2">
<h3 className="card-title me-auto">Trends</h3>
<RangeSelect value={days} onChange={setDays} />
</div>
<div className="card-body">
{failed ? (
@@ -68,25 +72,21 @@ export default function ServerTrends({ serverId }: { serverId: number }) {
<BlockSkeleton lines={4} />
) : series.length === 0 ? (
<div className="text-secondary">
No history yet. A sample is kept about every ten minutes once the agent has reported, so lines appear here after a short while.
No history in this stretch yet. A sample is kept about every ten minutes once the agent has reported, and its hours and days after that, so lines appear here after a short while.
</div>
) : (
<div className="trend-grid">
{series.map((s) => {
const words = describeTrend(s);
return (
<div key={s.metric} className="trend-row">
<div className="trend-label">{s.label}</div>
<Sparkline
points={s.points}
color={levelColor(s)}
label={`${s.label}, ${s.latest !== null ? `${Math.round(s.latest)}% now` : "no reading"}${words ? `, ${words}` : ""}`}
/>
<div className="trend-now">{s.latest !== null ? `${Math.round(s.latest)}%` : "—"}</div>
<div className="trend-words text-secondary small">{words}</div>
{charts.map(({ s, words, series: lines }) => (
<div key={s.metric} className="trend-block mb-3">
<div className="d-flex flex-wrap align-items-baseline gap-2 mb-1">
<strong>{s.label}</strong>
<span>{s.latest !== null ? `${Math.round(s.latest)}%` : "—"}</span>
<span className="text-secondary small">{words}</span>
</div>
);
})}
<TimeChart series={lines} from={from} to={to} compact label={`${s.label} over the last ${rangeLabel}, ${s.latest !== null ? `${Math.round(s.latest)}% now` : "no reading"}`} />
</div>
))}
{days > 35 && <div className="text-secondary small">Over {days > 120 ? "more than four months" : "more than five weeks"} each point is {days > 120 ? "a day" : "an hour"}&rsquo;s average, and the shaded band is its lowest and highest.</div>}
</div>
)}
</div>
-37
View File
@@ -1,37 +0,0 @@
/**
* A small line of how a percentage moved. The scale is always 0–100%, so a disk at 40% looks half-empty and one at 95% looks full
* however little it moved — a line that stretched to fit its own ups and downs would make every wobble look alarming.
*/
export default function Sparkline({
points,
color = "#4299e1",
label,
}: {
points: { t: string; v: number }[];
color?: string;
/** Read out by screen readers in place of the picture. */
label: string;
}) {
const W = 160;
const H = 36;
if (points.length < 2) {
return (
<svg viewBox={`0 0 ${W} ${H}`} className="sparkline" role="img" aria-label={label}>
<line x1="0" y1={H - 1} x2={W} y2={H - 1} stroke="currentColor" strokeOpacity="0.25" />
</svg>
);
}
const t0 = Date.parse(points[0].t);
const span = Math.max(Date.parse(points[points.length - 1].t) - t0, 1);
const xy = points.map((p) => {
const x = ((Date.parse(p.t) - t0) / span) * (W - 2) + 1;
const y = H - 2 - (Math.min(100, Math.max(0, p.v)) / 100) * (H - 4);
return `${x.toFixed(1)},${y.toFixed(1)}`;
});
return (
<svg viewBox={`0 0 ${W} ${H}`} className="sparkline" role="img" aria-label={label} preserveAspectRatio="none">
<polyline points={`1,${H - 1} ${xy.join(" ")} ${W - 1},${H - 1}`} fill={color} fillOpacity="0.15" stroke="none" />
<polyline points={xy.join(" ")} fill="none" stroke={color} strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
</svg>
);
}
+241
View File
@@ -0,0 +1,241 @@
import { useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from "react";
import { formatDate, formatDateTime, formatTime } from "../utils/date";
export interface ChartPoint {
/** ISO time. */
t: string;
v: number;
/** The lowest and highest of what this point stands for (an hour's or a day's figures); drawn as a band round the line. */
lo?: number;
hi?: number;
}
export interface ChartSeries {
name: string;
color: string;
/** SVG dash pattern, so lines can be told apart without their colour. Empty for a solid line. */
dash?: string;
points: ChartPoint[];
}
const W = 720;
const PAD = { left: 46, right: 12, top: 10, bottom: 24 };
/** A round number at or above `v`: 1, 2, 5 or 10 times a power of ten. */
function niceCeil(v: number): number {
if (!(v > 0)) return 10;
const pow = 10 ** Math.floor(Math.log10(v));
const f = v / pow;
return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * pow;
}
const median = (xs: number[]) => {
if (xs.length === 0) return 0;
const s = [...xs].sort((a, b) => a - b);
return s[Math.floor(s.length / 2)];
};
/**
* The one chart: lines (or bars) over a stretch of time, the same everywhere — server load and disks, a check's answer times and availability, uptime.
* Hover (or arrow keys, once it has focus) reads off the values at that moment. A band shows the lowest and highest where a point stands for an hour or a day, and
* a gap in the data is a gap in the line. The scale is 0–100 for percentages, so a quiet server never looks as busy as a loaded one; for times it fits the data.
*/
export default function TimeChart({
series,
from,
to,
label,
unit = "%",
compact = false,
bars = false,
barColor,
format,
empty = "No history in this stretch yet.",
}: {
series: ChartSeries[];
from: number;
to: number;
/** Read out by screen readers in place of the picture. */
label: string;
unit?: "%" | "ms";
compact?: boolean;
/** One bar per point instead of a line (daily availability). */
bars?: boolean;
barColor?: (v: number) => string;
format?: (v: number) => string;
empty?: string;
}) {
const H = compact ? 116 : 250;
const wrap = useRef<HTMLDivElement>(null);
// Where the cursor is, as a time (null: nowhere), and whether the keyboard put it there.
const [cursor, setCursor] = useState<number | null>(null);
const fmt = format ?? ((v: number) => (unit === "%" ? `${Math.round(v * 10) / 10}%` : `${Math.round(v)} ms`));
const parsed = useMemo(() => series.map((s) => ({ ...s, pts: s.points.map((p) => ({ ...p, x: Date.parse(p.t) })).filter((p) => Number.isFinite(p.x)) })), [series]);
const any = parsed.some((s) => s.pts.length > 0);
const top = unit === "%" ? 100 : niceCeil(Math.max(0, ...parsed.flatMap((s) => s.pts.map((p) => p.hi ?? p.v))) * 1.05);
const x = (t: number) => PAD.left + ((t - from) / Math.max(to - from, 1)) * (W - PAD.left - PAD.right);
const y = (v: number) => PAD.top + (1 - Math.min(top, Math.max(0, v)) / top) * (H - PAD.top - PAD.bottom);
const spanDays = (to - from) / 86_400_000;
const tickLabel = (t: number) =>
spanDays <= 1.5 ? formatTime(new Date(t), false) : spanDays <= 45 ? new Date(t).toLocaleDateString(undefined, { day: "numeric", month: "short" }) : new Date(t).toLocaleDateString(undefined, { month: "short", year: "2-digit" });
const ticks = (compact ? [0, 0.5, 1] : [0, 0.25, 0.5, 0.75, 1]).map((f) => from + f * (to - from));
const grid = compact ? [0, top / 2, top] : [0, top / 4, top / 2, (3 * top) / 4, top];
// Every moment any series has a point, for the arrow keys to step through.
const moments = useMemo(() => [...new Set(parsed.flatMap((s) => s.pts.map((p) => p.x)))].sort((a, b) => a - b), [parsed]);
const nearest = (s: (typeof parsed)[number], t: number) => {
let best: (typeof s.pts)[number] | null = null;
for (const p of s.pts) if (best === null || Math.abs(p.x - t) < Math.abs(best.x - t)) best = p;
return best;
};
// The moment closest to the cursor, so the vertical line sits on a real point.
const at = cursor === null || moments.length === 0 ? null : moments.reduce((b, m) => (Math.abs(m - cursor) < Math.abs(b - cursor) ? m : b), moments[0]);
const readings = at === null ? [] : parsed.map((s) => ({ s, p: nearest(s, at) })).filter((r): r is { s: (typeof parsed)[number]; p: NonNullable<typeof r.p> } => r.p !== null && Math.abs(r.p.x - at) <= Math.max((to - from) / 40, 1));
function move(e: PointerEvent<HTMLDivElement>) {
const box = wrap.current?.getBoundingClientRect();
if (!box || box.width === 0) return;
const vx = ((e.clientX - box.left) / box.width) * W;
setCursor(from + ((vx - PAD.left) / (W - PAD.left - PAD.right)) * (to - from));
}
function key(e: KeyboardEvent<HTMLDivElement>) {
if (moments.length === 0) return;
if (e.key === "Escape") return setCursor(null);
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight" && e.key !== "Home" && e.key !== "End") return;
e.preventDefault();
const i = at === null ? moments.length - 1 : moments.indexOf(at);
const next = e.key === "Home" ? 0 : e.key === "End" ? moments.length - 1 : Math.min(moments.length - 1, Math.max(0, i + (e.key === "ArrowRight" ? 1 : -1)));
setCursor(moments[next]);
}
const summary = parsed
.filter((s) => s.pts.length > 0)
.map((s) => {
const vs = s.pts.map((p) => p.v);
return `${s.name}: now ${fmt(vs[vs.length - 1])}, from ${fmt(Math.min(...vs))} to ${fmt(Math.max(...vs))}`;
})
.join(". ");
if (!any) {
return (
<div className="time-chart time-chart-empty text-secondary small" style={{ minHeight: compact ? 50 : 120 }} role="status">
{empty}
</div>
);
}
const spacing = median(parsed.flatMap((s) => s.pts.slice(1).map((p, i) => p.x - s.pts[i].x)));
const barW = Math.max(1.5, Math.min(24, ((W - PAD.left - PAD.right) * (spacing > 0 ? spacing : (to - from) / 30)) / Math.max(to - from, 1) * 0.8));
const tipLeft = at === null ? 0 : ((x(at) / W) * 100);
return (
<div
ref={wrap}
className="time-chart"
tabIndex={0}
role="group"
aria-label={`${label}. Use the arrow keys to read it off.`}
onPointerMove={move}
onPointerLeave={() => setCursor(null)}
onKeyDown={key}
onBlur={() => setCursor(null)}
>
<svg viewBox={`0 0 ${W} ${H}`} className="time-chart-svg" role="img" aria-label={`${label}. ${summary}`}>
{grid.map((v) => (
<g key={v}>
<line x1={PAD.left} x2={W - PAD.right} y1={y(v)} y2={y(v)} stroke="currentColor" strokeOpacity={v === 0 ? 0.4 : 0.15} />
<text x={PAD.left - 6} y={y(v) + 4} textAnchor="end" fontSize="11" fill="currentColor" fillOpacity="0.7">
{unit === "%" ? `${v}%` : `${Math.round(v)}`}
</text>
</g>
))}
{unit === "ms" && (
<text x={4} y={PAD.top + 10} fontSize="10" fill="currentColor" fillOpacity="0.6">
ms
</text>
)}
{ticks.map((t, i) => (
<text key={i} x={x(t)} y={H - 6} textAnchor={i === 0 ? "start" : i === ticks.length - 1 ? "end" : "middle"} fontSize="11" fill="currentColor" fillOpacity="0.7">
{tickLabel(t)}
</text>
))}
{parsed.map((s) => {
if (s.pts.length === 0) return null;
if (bars) {
return (
<g key={s.name}>
{s.pts.map((p, i) => (
<rect key={i} x={x(p.x) - barW / 2} y={y(p.v)} width={barW} height={Math.max(0, y(0) - y(p.v))} fill={barColor ? barColor(p.v) : s.color} opacity={at !== null && p.x !== at ? 0.55 : 1} />
))}
</g>
);
}
// Where the data stops for a while, so does the line.
const limit = Math.max(spacing * 3, (to - from) / 60);
let d = "";
const bands: string[] = [];
s.pts.forEach((p, i) => {
const gap = i > 0 && p.x - s.pts[i - 1].x > limit;
d += `${i === 0 || gap ? "M" : "L"}${x(p.x).toFixed(1)},${y(p.v).toFixed(1)} `;
});
// The band: along the highs, then back along the lows, one shape for each unbroken stretch.
const hasBand = s.pts.some((p) => p.hi !== undefined);
if (hasBand) {
let run: typeof s.pts = [];
const close = () => {
if (run.length > 1) {
const up = run.map((p) => `${x(p.x).toFixed(1)},${y(p.hi ?? p.v).toFixed(1)}`);
const down = [...run].reverse().map((p) => `${x(p.x).toFixed(1)},${y(p.lo ?? p.v).toFixed(1)}`);
bands.push([...up, ...down].join(" "));
}
run = [];
};
s.pts.forEach((p, i) => {
if (i > 0 && p.x - s.pts[i - 1].x > limit) close();
run.push(p);
});
close();
}
return (
<g key={s.name}>
{hasBand && bands.map((b, i) => <polygon key={i} points={b} fill={s.color} fillOpacity="0.14" stroke="none" />)}
{s.pts.length === 1 ? (
<circle cx={x(s.pts[0].x)} cy={y(s.pts[0].v)} r="3" fill={s.color} />
) : (
<path d={d} fill="none" stroke={s.color} strokeWidth={compact ? 1.6 : 2} strokeDasharray={s.dash || undefined} strokeLinejoin="round" strokeLinecap="round" />
)}
</g>
);
})}
{at !== null && (
<g pointerEvents="none">
<line x1={x(at)} x2={x(at)} y1={PAD.top} y2={H - PAD.bottom} stroke="currentColor" strokeOpacity="0.5" strokeDasharray="3 3" />
{!bars && readings.map((r) => <circle key={r.s.name} cx={x(r.p.x)} cy={y(r.p.v)} r="3.5" fill={r.s.color} stroke="var(--tblr-bg-surface, #fff)" strokeWidth="1.5" />)}
</g>
)}
</svg>
{at !== null && readings.length > 0 && (
<div className="time-chart-tip" style={{ left: `${tipLeft}%`, transform: tipLeft > 60 ? "translateX(calc(-100% - 10px))" : "translateX(10px)" }} role="status" aria-live="polite">
<div className="time-chart-tip-time">{spanDays > 120 ? formatDate(new Date(at)) : formatDateTime(new Date(at))}</div>
{readings.map((r) => (
<div key={r.s.name} className="time-chart-tip-row">
<span className="time-chart-swatch" style={{ background: bars && barColor ? barColor(r.p.v) : r.s.color }} aria-hidden="true" />
<span className="time-chart-tip-name">{r.s.name}</span>
<strong>{fmt(r.p.v)}</strong>
{r.p.lo !== undefined && r.p.hi !== undefined && r.p.hi !== r.p.lo && (
<span className="text-secondary small">
{" "}
({fmt(r.p.lo)}–{fmt(r.p.hi)})
</span>
)}
</div>
))}
</div>
)}
</div>
);
}
+78
View File
@@ -0,0 +1,78 @@
import { useEffect, useMemo, useState } from "react";
import { api, type UptimeReport } from "../api/client";
import RangeSelect from "./RangeSelect";
import TimeChart from "./TimeChart";
import { BlockSkeleton } from "./Skeleton";
import { useChartRange } from "../utils/chartRanges";
const DAY_MS = 24 * 3600_000;
/** A day of uptime is drawn green when nothing was wrong, amber for some time down, red for most of the day. */
const dayColor = (v: number) => (v >= 99.9 ? "#2fb344" : v >= 50 ? "#f59f00" : "#f03e3e");
/**
* How a server (or an integration) has done, a day at a time, as far back as the record goes: the share of each day it was up. The thin ribbon on the lists is the
* last 30 days of the same thing; this is the chart, with a value for any day and a range up to a year.
*/
export default function UptimeHistory({ kind, id, name }: { kind: "servers" | "integrations"; id: number; name: string }) {
const [chosen, setDays] = useChartRange(30);
// A day is the smallest thing recorded, so 24 hours is not offered here: a chart of a single bar says nothing.
const days = chosen < 30 ? 30 : chosen;
const [report, setReport] = useState<UptimeReport | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let alive = true;
setFailed(false);
api.uptime
.get(days)
.then((res) => alive && setReport(res))
.catch(() => alive && setFailed(true));
return () => {
alive = false;
};
}, [days]);
const series = report?.[kind][id];
const to = report ? Date.parse(report.endsAt) : Date.now();
const lines = useMemo(() => {
if (!report || !series) return [];
const end = Date.parse(report.endsAt);
return [
{
name: "Up",
color: "#2fb344",
// One point per day with something known about it, in the middle of that day.
points: series.buckets.flatMap((b, i) => (b.k === 0 ? [] : [{ t: new Date(end - (report.days - i - 0.5) * DAY_MS).toISOString(), v: Math.round((1 - b.d / b.k) * 1000) / 10 }])),
},
];
}, [report, series]);
return (
<div className="card mb-3">
<div className="card-header d-flex flex-wrap gap-2">
<h3 className="card-title me-auto">Availability</h3>
<RangeSelect value={days} onChange={setDays} only={[30, 90, 365]} />
</div>
<div className="card-body">
{failed ? (
<div className="text-secondary">Couldn't load the record.</div>
) : !report ? (
<BlockSkeleton lines={3} />
) : !series ? (
<div className="text-secondary">Nothing is known about {name} in this stretch yet.</div>
) : (
<>
<div className="mb-2">
<span className="h3 me-2">{series.percent}%</span>
<span className="text-secondary">up over the last {days} days</span>
</div>
<TimeChart series={lines} from={to - days * DAY_MS} to={to} bars barColor={dayColor} label={`${name}: share of each day it was up, over the last ${days} days. ${series.percent}% in all.`} />
<div className="text-secondary small mt-2">
Worked out from when it stopped reporting and reported again, so it goes back as far as the change log does; days before it was known are left blank.
</div>
</>
)}
</div>
</div>
);
}
+13 -1
View File
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { Link, NavLink, useLocation } from "react-router-dom";
import { IconMenu2, IconSun, IconMoon, IconShieldLock, IconTool, IconChevronUp, IconLogout, IconDeviceDesktop, IconChevronsLeft, IconChevronsRight } from "@tabler/icons-react";
import { IconKey, IconMenu2, IconSun, IconMoon, IconShieldLock, IconTool, IconChevronUp, IconLogout, IconDeviceDesktop, IconChevronsLeft, IconChevronsRight } from "@tabler/icons-react";
import { api, type CurrentUser, type MaintenanceWindow } from "../api/client";
import { isCurrent, isGroup, visibleNav, type NavGroup } from "./nav";
import SidebarNav, { type NavBadge } from "./SidebarNav";
@@ -305,6 +305,18 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
<IconShieldLock size={16} />
Privacy
</NavLink>
<NavLink
to="/api-tokens"
className="user-menu-item"
role="menuitem"
onClick={() => {
setMenuOpen(false);
setSidebarOpen(false);
}}
>
<IconKey size={16} />
API tokens
</NavLink>
<NavLink
to="/wall"
className="user-menu-item"
+221
View File
@@ -0,0 +1,221 @@
import { useEffect, useState } from "react";
import { api, type ApiToken } from "../api/client";
import CopyButton from "../components/CopyButton";
import { EmptyRow } from "../components/EmptyState";
import { ErrorNotice } from "../components/Notice";
import { BlockSkeleton } from "../components/Skeleton";
import TimeAgo from "../components/TimeAgo";
import { confirmDialog } from "../utils/dialogs";
import { formatDate } from "../utils/date";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
const EXPIRY = [
{ value: "90", label: "90 days" },
{ value: "30", label: "30 days" },
{ value: "365", label: "1 year" },
{ value: "", label: "No end — until I remove it" },
];
const READS = [
["/api/v1/servers", "every server: whether it is online, its addresses, load, memory, disks and waiting updates"],
["/api/v1/servers/:id/metrics?days=365", "a server's load, memory and disks, up to a year back"],
["/api/v1/alerts", "what is wrong now, and whether somebody is on it"],
["/api/v1/incidents?status=open", "the record of alerts that began and ended"],
["/api/v1/inventory", "the hardware"],
["/api/v1/network", "switches, access points and gateways, networks and Wi-Fi names"],
["/api/v1/endpoints", "the checks, and /endpoints/:id/history for how one has done"],
["/api/v1/maintenance", "what is under maintenance now, and what is coming"],
];
/**
* A person's own read-only tokens for the API (/api/v1): a script, Home Assistant or a dashboard sends one in a header and gets JSON back. A token can only read, sees
* what its owner sees, and is gone when its owner is. The secret is shown once, here, when it is made.
*/
export default function ApiTokens() {
const [tokens, setTokens] = useState<ApiToken[] | null>(null);
const [max, setMax] = useState(10);
const [error, setError] = useState<string | null>(null);
const [label, setLabel] = useState("");
const [expiry, setExpiry] = useState("90");
const [busy, setBusy] = useState(false);
const [fresh, setFresh] = useState<{ label: string; secret: string } | null>(null);
function load() {
api.apiTokens
.list()
.then((res) => {
setTokens(res.tokens);
setMax(res.max);
})
.catch((err) => setError(readableError(err)));
}
useEffect(load, []);
async function make(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
const res = await api.apiTokens.create({ label: label.trim(), expiresInDays: expiry === "" ? null : Number(expiry) });
setFresh({ label: res.token.label, secret: res.secret });
setLabel("");
load();
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
async function remove(t: ApiToken) {
// Not undoable: the secret is not kept, so a token cannot be made again the same.
if (!(await confirmDialog({ title: "Remove a token", message: `Remove "${t.label}"? Whatever uses it stops working at once, and it cannot be put back.`, confirmLabel: "Remove", danger: true }))) return;
try {
await api.apiTokens.remove(t.id);
toast.success(`Removed "${t.label}".`);
load();
} catch (err) {
toast.error(readableError(err));
}
}
const origin = window.location.origin;
return (
<>
<div className="d-flex align-items-center mb-1">
<h2 className="page-title mb-0">API tokens</h2>
</div>
<div className="text-secondary mb-3">
Read-only access to your installation&rsquo;s data for scripts, Home Assistant and dashboards. A token can only read, sees what you see, and stops working when you are removed. Make one for each thing that reads, so each can be removed on its own.
</div>
<ErrorNotice error={error} />
{fresh && (
<div className="alert alert-success" role="status">
<div className="w-100">
<div className="fw-bold mb-1">Your token &ldquo;{fresh.label}&rdquo; — copy it now, it is not shown again</div>
<div className="d-flex flex-wrap align-items-center gap-2 mb-2">
<code className="text-break">{fresh.secret}</code>
<CopyButton text={fresh.secret} />
</div>
<div className="small">Send it in a header, never in the address:</div>
<pre className="mb-2 mt-1 small">{`curl -H "Authorization: Bearer ${fresh.secret}" ${origin}/api/v1/alerts`}</pre>
<button type="button" className="btn btn-sm" onClick={() => setFresh(null)}>
I have copied it
</button>
</div>
</div>
)}
<form className="card mb-3" onSubmit={make}>
<div className="card-header">
<h3 className="card-title">Make a token</h3>
</div>
<div className="card-body row g-3 align-items-end">
<div className="col-md-5">
<label className="form-label" htmlFor="tok-label">
What it is for
</label>
<input id="tok-label" className="form-control" maxLength={60} required placeholder="e.g. Home Assistant" value={label} onChange={(e) => setLabel(e.target.value)} />
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="tok-exp">
Works for
</label>
<select id="tok-exp" className="form-select" value={expiry} onChange={(e) => setExpiry(e.target.value)}>
{EXPIRY.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
</div>
<div className="col-md-3">
<button type="submit" className="btn btn-primary w-100" disabled={busy || label.trim() === "" || (tokens?.length ?? 0) >= max}>
{busy ? "Making…" : "Make the token"}
</button>
</div>
{(tokens?.length ?? 0) >= max && <div className="col-12 text-secondary small">You have {max} tokens, the most there can be. Remove one you do not use.</div>}
</div>
</form>
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Your tokens</h3>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<thead>
<tr>
<th>Name</th>
<th>Starts with</th>
<th>Made</th>
<th>Last used</th>
<th>Ends</th>
<th className="w-1">
<span className="visually-hidden">Actions</span>
</th>
</tr>
</thead>
<tbody>
{tokens === null && !error && (
<tr>
<td colSpan={6}>
<BlockSkeleton lines={2} />
</td>
</tr>
)}
{tokens?.map((t) => (
<tr key={t.id}>
<td className="stack-wide">
<strong>{t.label}</strong>
{t.expired && <span className="badge bg-red-lt text-red ms-2">expired</span>}
</td>
<td className="stack-label font-monospace" data-label="Starts with">
{t.tokenPrefix}…
</td>
<td className="stack-label" data-label="Made">
<TimeAgo value={t.createdAt} fromDb />
</td>
<td className="stack-label" data-label="Last used">
{t.lastUsedAt ? <TimeAgo value={t.lastUsedAt} /> : <span className="text-secondary">never</span>}
</td>
<td className="stack-label" data-label="Ends">
{t.expiresAt ? formatDate(new Date(t.expiresAt)) : <span className="text-secondary">no end</span>}
</td>
<td className="stack-wide">
<button className="btn btn-sm btn-outline-danger" onClick={() => void remove(t)}>
Remove
</button>
</td>
</tr>
))}
{tokens !== null && tokens.length === 0 && <EmptyRow colSpan={6} title="No tokens yet" hint="Make one above, and copy it when it is shown: that is the only time it is." />}
</tbody>
</table>
</div>
</div>
<div className="card">
<div className="card-header">
<h3 className="card-title">What it can read</h3>
</div>
<div className="card-body">
<p className="text-secondary">
Everything is a <code>GET</code> that answers JSON, under <code>{origin}/api/v1</code>, with the token as <code>Authorization: Bearer …</code>. Nothing can be changed through it. Dates are ISO 8601 in UTC and sizes are in bytes.
</p>
<ul className="mb-2">
{READS.map(([path, what]) => (
<li key={path}>
<code>{path}</code> — {what}
</li>
))}
</ul>
<div className="text-secondary small">The full list, with an example of each answer, is in API.md.</div>
</div>
</div>
</>
);
}
+6
View File
@@ -16,6 +16,7 @@ import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
import { EmptyRow } from "../components/EmptyState";
import EndpointSuggestions from "../components/EndpointSuggestions";
import EndpointHistory from "../components/EndpointHistory";
const KIND_LABELS: Record<EndpointKind, string> = { http: "Web address", tcp: "Port", tls: "Certificate" };
const KIND_HINTS: Record<EndpointKind, string> = {
@@ -128,6 +129,7 @@ export default function Endpoints({ user }: { user: CurrentUser }) {
const [draft, setDraft] = useState<Draft | null>(null);
const [busy, setBusy] = useState(false);
const [asking, setAsking] = useState<number | null>(null);
const [historyFor, setHistoryFor] = useState<{ id: number; name: string } | null>(null);
function load() {
api.endpoints
@@ -438,6 +440,9 @@ export default function Endpoints({ user }: { user: CurrentUser }) {
<div>
<Ticks recent={c.stats?.recent ?? []} />
</div>
<button type="button" className="btn btn-link btn-sm p-0" onClick={() => setHistoryFor({ id: c.id, name: c.name })}>
History…
</button>
</td>
<td className="stack-label" data-label="Certificate">
{c.certDays === null ? (
@@ -488,6 +493,7 @@ export default function Endpoints({ user }: { user: CurrentUser }) {
</div>
<Pagination page={page.page} pageCount={page.pageCount} totalCount={page.totalCount} onPageChange={page.setPage} />
</div>
{historyFor && <EndpointHistory checkId={historyFor.id} name={historyFor.name} onClose={() => setHistoryFor(null)} />}
</>
);
}
+7 -16
View File
@@ -1,16 +1,13 @@
import { useEffect, useMemo, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { api, type ServerMetricSeries, type ServerRecord } from "../api/client";
import MultiLineChart, { type ChartSeries } from "../components/MultiLineChart";
import TimeChart, { type ChartSeries } from "../components/TimeChart";
import RangeSelect from "../components/RangeSelect";
import { CHART_RANGES, useChartRange } from "../utils/chartRanges";
import { BlockSkeleton } from "../components/Skeleton";
import ExportTableButton from "../components/ExportTableButton";
const MAX_SERVERS = 4;
const RANGES = [
{ days: 1, label: "24 hours" },
{ days: 7, label: "7 days" },
{ days: 30, label: "30 days" },
];
// A colour and a dash pattern for each line, so they can be told apart by either.
const LOOKS = [
{ color: "#4299e1", dash: "" },
@@ -43,7 +40,7 @@ export default function ServerCompare() {
return [...seen].slice(0, MAX_SERVERS);
}, [params]);
const [days, setDays] = useState(7);
const [days, setDays] = useChartRange(7);
const [metric, setMetric] = useState("cpu");
const [loaded, setLoaded] = useState<Loaded[] | null>(null);
const [failed, setFailed] = useState(false);
@@ -98,7 +95,7 @@ export default function ServerCompare() {
};
});
const chart: ChartSeries[] = rows.filter((r) => r.series).map((r) => ({ name: r.server.name, color: r.look.color, dash: r.look.dash, points: r.series!.points }));
const summary = `${metricName} over the last ${RANGES.find((r) => r.days === days)?.label}: ${rows.map((r) => `${r.server.name} ${percent(r.now)} now`).join(", ")}`;
const summary = `${metricName} over the last ${CHART_RANGES.find((r) => r.days === days)?.label}: ${rows.map((r) => `${r.server.name} ${percent(r.now)} now`).join(", ")}`;
return (
<>
@@ -126,13 +123,7 @@ export default function ServerCompare() {
</option>
))}
</select>
<select className="form-select form-select-sm w-auto" aria-label="Time range" value={days} onChange={(e) => setDays(Number(e.target.value))}>
{RANGES.map((r) => (
<option key={r.days} value={r.days}>
Last {r.label}
</option>
))}
</select>
<RangeSelect value={days} onChange={setDays} />
<ExportTableButton filename={`compare-${metric}`} />
</div>
<div className="card-body">
@@ -145,7 +136,7 @@ export default function ServerCompare() {
{chart.length === 0 ? (
<div className="text-secondary mb-3">None of these servers has a history for this yet. A sample is kept about every ten minutes once an agent has reported.</div>
) : (
<MultiLineChart series={chart} from={to - days * 86_400_000} to={to} label={summary} />
<TimeChart series={chart} from={to - days * 86_400_000} to={to} label={summary} />
)}
<div className="table-responsive mt-3">
<table className="table table-vcenter">
+2
View File
@@ -14,6 +14,7 @@ import {
} from "../api/client";
import ServerPorts from "../components/ServerPorts";
import ServerTrends from "../components/ServerTrends";
import UptimeHistory from "../components/UptimeHistory";
import ServerActivity from "../components/ServerActivity";
import TimeAgo from "../components/TimeAgo";
import UptimeRibbon from "../components/UptimeRibbon";
@@ -800,6 +801,7 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
{view === "history" && (
<>
<UptimeHistory kind="servers" id={server.id} name={server.name} />
{hardware.source === "agent" && <ServerTrends serverId={serverId} />}
{(user.role === "admin" || user.role === "operator") && <ServerActivity serverId={serverId} />}
</>
+65
View File
@@ -992,6 +992,71 @@ a.map-node:focus-visible {
border-left-color: #48bb78;
}
/* The one chart (components/TimeChart.tsx). */
.time-chart {
position: relative;
width: 100%;
border-radius: var(--tblr-border-radius, 4px);
}
.time-chart:focus-visible {
outline: 2px solid var(--tblr-primary, #206bc4);
outline-offset: 2px;
}
.time-chart-svg {
display: block;
width: 100%;
height: auto;
color: var(--tblr-body-color);
touch-action: pan-y;
}
.time-chart-empty {
display: flex;
align-items: center;
justify-content: center;
border: 1px dashed var(--tblr-border-color);
text-align: center;
}
.time-chart-tip {
position: absolute;
top: 4px;
z-index: 5;
padding: 0.35rem 0.6rem;
font-size: 0.8rem;
white-space: nowrap;
pointer-events: none;
background: var(--tblr-bg-surface);
border: 1px solid var(--tblr-border-color);
border-radius: 6px;
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.25);
}
.time-chart-tip-time {
margin-bottom: 0.15rem;
color: var(--tblr-secondary-color, #667085);
}
.time-chart-tip-row {
display: flex;
gap: 0.3rem;
align-items: baseline;
}
.time-chart-swatch {
display: inline-block;
flex-shrink: 0;
width: 0.7rem;
height: 0.7rem;
border-radius: 2px;
}
.time-chart-tip-name {
margin-right: 0.3rem;
}
.map-label {
display: flex;
flex-direction: column;
+43
View File
@@ -0,0 +1,43 @@
import { useCallback, useState } from "react";
/** The stretches of time every chart can show, the same everywhere: a day to a year. */
export const CHART_RANGES = [
{ days: 1, label: "24 hours" },
{ days: 7, label: "7 days" },
{ days: 30, label: "30 days" },
{ days: 90, label: "90 days" },
{ days: 365, label: "1 year" },
] as const;
export type ChartDays = (typeof CHART_RANGES)[number]["days"];
const KEY = "chart.range";
const isRange = (n: number): n is ChartDays => CHART_RANGES.some((r) => r.days === n);
function remembered(fallback: ChartDays): ChartDays {
try {
const n = Number(localStorage.getItem(KEY));
return isRange(n) ? n : fallback;
} catch {
return fallback;
}
}
/**
* The range a chart shows, remembered between charts and visits: choosing 30 days on one page means the next chart opens on 30 days as well. A convenience only —
* without storage it is just the default each time.
*/
export function useChartRange(fallback: ChartDays = 7): [ChartDays, (days: number) => void] {
const [days, setDays] = useState<ChartDays>(() => remembered(fallback));
const choose = useCallback((n: number) => {
if (!isRange(n)) return;
setDays(n);
try {
localStorage.setItem(KEY, String(n));
} catch {
// not remembered
}
}, []);
return [days, choose];
}