aboutsummaryrefslogtreecommitdiffstats
path: root/src/web
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-06-28 18:43:17 -0500
committerJP Dillingham <jp@dillingham.me>2026-06-28 18:43:17 -0500
commit7bdc1e5d5f64c5095cdd7659795a535697b403e7 (patch)
tree003bfe35a118a6240de69d1b4c06f70a2af37d48 /src/web
parent4daf1f166b03bc27d723c915a680ca649d6829e5 (diff)
downloadslskd-7bdc1e5d5f64c5095cdd7659795a535697b403e7.tar.gz
initial swag at a shared graph component
Diffstat (limited to 'src/web')
-rw-r--r--src/web/src/components/Dashboard/Dashboard.jsx1
-rw-r--r--src/web/src/components/Dashboard/HistoricalStatistics.jsx30
-rw-r--r--src/web/src/components/Dashboard/TransferErrors.jsx29
-rw-r--r--src/web/src/components/Shared/Graph.jsx284
-rw-r--r--src/web/src/components/Shared/index.js1
5 files changed, 303 insertions, 42 deletions
diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx
index 959df68b..a345f593 100644
--- a/src/web/src/components/Dashboard/Dashboard.jsx
+++ b/src/web/src/components/Dashboard/Dashboard.jsx
@@ -149,7 +149,6 @@ const Dashboard = ({ server } = {}) => {
directories={data.directories}
exceptions={data.exceptions}
histogram={data.histogram}
- historyDays={historyParameters.days}
historyEnd={historyParameters.end}
historyLabel={historyLabel}
historyRanges={HISTORY_RANGES}
diff --git a/src/web/src/components/Dashboard/HistoricalStatistics.jsx b/src/web/src/components/Dashboard/HistoricalStatistics.jsx
index 91af07ae..b0963082 100644
--- a/src/web/src/components/Dashboard/HistoricalStatistics.jsx
+++ b/src/web/src/components/Dashboard/HistoricalStatistics.jsx
@@ -85,72 +85,84 @@ const HISTORY_SERIES = [
format: formatBytes,
key: 'uploadBytes',
name: 'Upload Size',
+ unit: 'bytes',
},
{
color: '#2185d0',
format: formatBytes,
key: 'downloadBytes',
name: 'Download Size',
+ unit: 'bytes',
},
{
color: '#6435c9',
format: (v) => v.toLocaleString(),
key: 'uploadCount',
name: 'Upload Count',
+ unit: 'count',
},
{
color: '#e03997',
format: (v) => v.toLocaleString(),
key: 'downloadCount',
name: 'Download Count',
+ unit: 'count',
},
{
color: '#f2711c',
format: formatSpeed,
key: 'uploadSpeed',
name: 'Upload Speed',
+ unit: 'speed',
},
{
color: '#fbbd08',
format: formatSpeed,
key: 'downloadSpeed',
name: 'Download Speed',
+ unit: 'speed',
},
{
color: '#db2828',
format: (v) => v.toLocaleString(),
key: 'uploadErrors',
name: 'Upload Errors',
+ unit: 'count',
},
{
color: '#a333c8',
format: (v) => v.toLocaleString(),
key: 'downloadErrors',
name: 'Download Errors',
+ unit: 'count',
},
{
color: '#d4500a',
format: (v) => `${v.toFixed(1)}%`,
key: 'uploadErrorRate',
name: 'Upload Error Rate',
+ unit: 'rate',
},
{
color: '#1aa9b0',
format: (v) => `${v.toFixed(1)}%`,
key: 'downloadErrorRate',
name: 'Download Error Rate',
+ unit: 'rate',
},
{
color: '#8e44ad',
format: formatWait,
key: 'uploadWait',
name: 'Upload Queue Wait',
+ unit: 'seconds',
},
{
color: '#b5cc18',
format: (v) => v.toFixed(2),
key: 'shareRatio',
name: 'Share Ratio',
+ unit: 'ratio',
},
];
@@ -161,7 +173,6 @@ const HistoricalStatistics = ({
directories,
exceptions,
histogram,
- historyDays,
historyEnd,
historyLabel,
historyRanges,
@@ -186,20 +197,6 @@ const HistoricalStatistics = ({
? 'yellow'
: 'red';
- const histogramTickFormatter = (timestamp) => {
- if (historyDays === 1) {
- return new Date(timestamp).toLocaleTimeString(undefined, {
- hour: '2-digit',
- minute: '2-digit',
- });
- }
-
- return new Date(timestamp).toLocaleDateString(undefined, {
- day: 'numeric',
- month: 'short',
- });
- };
-
const historyPanes = [
{
menuItem: { content: 'Users', icon: 'users', key: 'users' },
@@ -229,7 +226,6 @@ const HistoricalStatistics = ({
<TransferErrors
chartData={chartData}
download={exceptions.download}
- historyDays={historyDays}
upload={exceptions.upload}
/>
</Tab.Pane>
@@ -338,8 +334,6 @@ const HistoricalStatistics = ({
data={chartData}
defaultSeries={DEFAULT_HISTORY_SERIES}
series={HISTORY_SERIES}
- xFormatter={histogramTickFormatter}
- yFormatter={formatBytes}
/>
</div>
<Divider />
diff --git a/src/web/src/components/Dashboard/TransferErrors.jsx b/src/web/src/components/Dashboard/TransferErrors.jsx
index c0b79cf1..d4c9c25c 100644
--- a/src/web/src/components/Dashboard/TransferErrors.jsx
+++ b/src/web/src/components/Dashboard/TransferErrors.jsx
@@ -63,23 +63,20 @@ const ERRORS_SERIES = [
format: (v) => v.toLocaleString(),
key: 'uploadErrors',
name: 'Upload Errors',
+ unit: 'count',
},
{
color: '#a333c8',
format: (v) => v.toLocaleString(),
key: 'downloadErrors',
name: 'Download Errors',
+ unit: 'count',
},
];
const DEFAULT_ERRORS_SERIES = new Set(['uploadErrors', 'downloadErrors']);
-const TransferErrors = ({
- chartData,
- download,
- historyDays,
- upload,
-}) => {
+const TransferErrors = ({ chartData, download, upload }) => {
const isDark = useDarkMode();
const paretoRows = useMemo(
@@ -91,20 +88,6 @@ const TransferErrors = ({
[upload.recent, download.recent],
);
- const xFormatter = (timestamp) => {
- if (historyDays === 1) {
- return new Date(timestamp).toLocaleTimeString(undefined, {
- hour: '2-digit',
- minute: '2-digit',
- });
- }
-
- return new Date(timestamp).toLocaleDateString(undefined, {
- day: 'numeric',
- month: 'short',
- });
- };
-
const maxParetoCount =
paretoRows && paretoRows.length > 0 ? paretoRows[0].count : 1;
@@ -115,8 +98,6 @@ const TransferErrors = ({
data={chartData ?? []}
defaultSeries={DEFAULT_ERRORS_SERIES}
series={ERRORS_SERIES}
- xFormatter={xFormatter}
- yFormatter={(v) => v.toLocaleString()}
/>
<Divider />
<Header as="h5">
@@ -219,7 +200,9 @@ const TransferErrors = ({
)}
{recentRows &&
recentRows.map((row) => (
- <Table.Row key={`${row.direction}-${row.endedAt}-${row.filename}`}>
+ <Table.Row
+ key={`${row.direction}-${row.endedAt}-${row.filename}`}
+ >
<Table.Cell style={{ whiteSpace: 'nowrap' }}>
{formatDateTime(row.endedAt)}
</Table.Cell>
diff --git a/src/web/src/components/Shared/Graph.jsx b/src/web/src/components/Shared/Graph.jsx
new file mode 100644
index 00000000..d383345f
--- /dev/null
+++ b/src/web/src/components/Shared/Graph.jsx
@@ -0,0 +1,284 @@
+import React, { useEffect, useMemo, useState } from 'react';
+import {
+ Area,
+ AreaChart,
+ CartesianGrid,
+ Legend,
+ ResponsiveContainer,
+ Tooltip,
+ XAxis,
+ YAxis,
+} from 'recharts';
+
+export const useDarkMode = () => {
+ const [isDark, setIsDark] = useState(() =>
+ document.documentElement.classList.contains('dark'),
+ );
+
+ useEffect(() => {
+ const observer = new MutationObserver(() => {
+ setIsDark(document.documentElement.classList.contains('dark'));
+ });
+ observer.observe(document.documentElement, { attributeFilter: ['class'] });
+ return () => observer.disconnect();
+ }, []);
+
+ return isDark;
+};
+
+const formatBytes = (bytes) => {
+ if (!bytes || bytes === 0) return '0 B';
+ const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
+ const index = Math.floor(Math.log(bytes) / Math.log(1_024));
+ return `${(bytes / 1_024 ** index).toFixed(1)} ${units[index]}`;
+};
+
+const formatSpeed = (bytesPerSecond) => {
+ if (!bytesPerSecond || bytesPerSecond === 0) return '0 B/s';
+ return `${formatBytes(bytesPerSecond)}/s`;
+};
+
+const formatWait = (seconds) => {
+ if (!seconds || seconds === 0) return '0s';
+ if (seconds < 60) return `${Math.round(seconds)}s`;
+ return `${(seconds / 60).toFixed(1)}m`;
+};
+
+const UNIT_FORMATTERS = {
+ bytes: formatBytes,
+ count: (v) => v.toLocaleString(),
+ rate: (v) => `${v.toFixed(1)}%`,
+ ratio: (v) => v.toFixed(2),
+ seconds: formatWait,
+ speed: formatSpeed,
+};
+
+const mixedFormatter = (v) => {
+ if (v >= 1e9) return `${(v / 1e9).toFixed(1)}B`;
+ if (v >= 1e6) return `${(v / 1e6).toFixed(1)}M`;
+ if (v >= 1e3) return `${(v / 1e3).toFixed(1)}K`;
+ return v.toLocaleString();
+};
+
+const X_TICK_COUNT = 11;
+const ONE_DAY_MS = 86_400_000;
+
+// series: [{ key, name, color, unit?, format? }]
+// key — the data key in each data point
+// name — label shown in the legend and tooltip
+// color — stroke / fill color
+// unit — one of: 'bytes' | 'count' | 'rate' | 'ratio' | 'seconds' | 'speed'
+// used to pick the Y axis formatter; omit for unitless/mixed
+// format — (value) => string used in the tooltip; defaults to toLocaleString()
+const Graph = ({ data = [], defaultSeries, height = 200, series = [] }) => {
+ const isDark = useDarkMode();
+
+ const [visible, setVisible] = useState(
+ () => defaultSeries ?? new Set(series.map((s) => s.key)),
+ );
+
+ const axisStyle = useMemo(
+ () => ({
+ fill: isDark ? '#8b949e' : '#666',
+ fontSize: '0.8em',
+ }),
+ [isDark],
+ );
+
+ const xRange = useMemo(() => {
+ if (data.length < 2) return null;
+ const min = data[0].timestamp;
+ const max = data[data.length - 1].timestamp;
+ return { min, max };
+ }, [data]);
+
+ const xTicks = useMemo(() => {
+ if (!xRange) return [];
+ const { max, min } = xRange;
+ const step = (max - min) / (X_TICK_COUNT - 1);
+ return Array.from({ length: X_TICK_COUNT }, (_, index) =>
+ Math.round(min + index * step),
+ );
+ }, [xRange]);
+
+ const xFormatter = useMemo(() => {
+ if (!xRange) return String;
+ const isIntraday = xRange.max - xRange.min <= ONE_DAY_MS;
+ if (isIntraday) {
+ return (timestamp) =>
+ new Date(timestamp).toLocaleTimeString(undefined, {
+ hour: '2-digit',
+ minute: '2-digit',
+ });
+ }
+
+ return (timestamp) =>
+ new Date(timestamp).toLocaleDateString(undefined, {
+ day: 'numeric',
+ month: 'short',
+ });
+ }, [xRange]);
+
+ const yFormatter = useMemo(() => {
+ const units = series
+ .filter((s) => visible.has(s.key) && s.unit)
+ .map((s) => s.unit);
+ const unique = [...new Set(units)];
+ return unique.length === 1
+ ? UNIT_FORMATTERS[unique[0]] ?? mixedFormatter
+ : mixedFormatter;
+ }, [series, visible]);
+
+ const toggle = (key) => {
+ setVisible((previous) => {
+ const next = new Set(previous);
+ if (next.has(key)) {
+ next.delete(key);
+ } else {
+ next.add(key);
+ }
+
+ return next;
+ });
+ };
+
+ const renderTooltip = ({ active, label, payload }) => {
+ if (!active || !payload?.length) return null;
+ const bg = isDark ? '#161b22' : '#fff';
+ const border = isDark ? '#30363d' : '#d0d0d0';
+ const labelColor = isDark ? '#c9d1d9' : '#333';
+ const valueColor = isDark ? '#8b949e' : '#666';
+ return (
+ <div
+ style={{
+ background: bg,
+ border: `1px solid ${border}`,
+ borderRadius: 4,
+ fontSize: '0.875em',
+ padding: '6px 10px',
+ }}
+ >
+ <div
+ style={{
+ color: labelColor,
+ fontWeight: 'bold',
+ fontSize: '1.05em',
+ marginBottom: 4,
+ }}
+ >
+ {xFormatter(label)}
+ </div>
+ {payload.map((entry) => {
+ const s = series.find((item) => item.name === entry.name);
+ const formatted = s?.format
+ ? s.format(entry.value)
+ : entry.value.toLocaleString();
+ return (
+ <div
+ key={entry.dataKey}
+ style={{ color: valueColor, display: 'flex', gap: '0.5em' }}
+ >
+ <span style={{ color: entry.color }}>&#9644;</span>
+ <span>{entry.name}:</span>
+ <span>{formatted}</span>
+ </div>
+ );
+ })}
+ </div>
+ );
+ };
+
+ const renderLegend = ({ payload }) => (
+ <div
+ style={{
+ display: 'flex',
+ flexWrap: 'wrap',
+ fontSize: '0.875em',
+ gap: '1em',
+ justifyContent: 'center',
+ }}
+ >
+ {payload.map((entry) => (
+ <span
+ aria-checked={visible.has(entry.dataKey)}
+ key={entry.dataKey}
+ onClick={() => toggle(entry.dataKey)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ toggle(entry.dataKey);
+ }
+ }}
+ role="checkbox"
+ style={{
+ alignItems: 'center',
+ cursor: 'pointer',
+ display: 'flex',
+ gap: '0.4em',
+ opacity: visible.has(entry.dataKey) ? 1 : 0.35,
+ }}
+ tabIndex={0}
+ >
+ <svg
+ height="10"
+ width="16"
+ >
+ <line
+ stroke={entry.color}
+ strokeWidth="2"
+ x1="0"
+ x2="16"
+ y1="5"
+ y2="5"
+ />
+ </svg>
+ {entry.value}
+ </span>
+ ))}
+ </div>
+ );
+
+ return (
+ <ResponsiveContainer
+ height={height}
+ width="100%"
+ >
+ <AreaChart data={data}>
+ <CartesianGrid
+ stroke={isDark ? 'rgba(255,255,255,0.20)' : '#d0d0d0'}
+ strokeDasharray="3 3"
+ />
+ <XAxis
+ dataKey="timestamp"
+ domain={['dataMin', 'dataMax']}
+ style={axisStyle}
+ tickFormatter={xFormatter}
+ ticks={xTicks}
+ type="number"
+ />
+ <YAxis
+ style={axisStyle}
+ tickFormatter={yFormatter}
+ />
+ <Tooltip content={renderTooltip} />
+ <Legend content={renderLegend} />
+ {series.map(({ color, key, name }) => (
+ <Area
+ dataKey={key}
+ dot={false}
+ fill={color}
+ fillOpacity={0.15}
+ hide={!visible.has(key)}
+ isAnimationActive={false}
+ key={key}
+ name={name}
+ stroke={color}
+ strokeOpacity={visible.has(key) ? 1 : 0}
+ type="monotone"
+ />
+ ))}
+ </AreaChart>
+ </ResponsiveContainer>
+ );
+};
+
+export default Graph;
diff --git a/src/web/src/components/Shared/index.js b/src/web/src/components/Shared/index.js
index 0e36bc48..6fbf167f 100644
--- a/src/web/src/components/Shared/index.js
+++ b/src/web/src/components/Shared/index.js
@@ -2,6 +2,7 @@ export { default as CodeEditor } from './CodeEditor';
export { default as Div } from './Div';
export { default as ErrorSegment } from './ErrorSegment';
export { default as FileList } from './FileList';
+export { default as Graph, useDarkMode } from './Graph';
export { default as LoaderSegment } from './LoaderSegment';
export { default as Nbsp } from './Nbsp';
export { default as PlaceholderSegment } from './PlaceholderSegment';