-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDownloadClientStatusWidget.tsx
More file actions
242 lines (219 loc) · 7.97 KB
/
DownloadClientStatusWidget.tsx
File metadata and controls
242 lines (219 loc) · 7.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// src/components/layout/DownloadClientStatusWidget.tsx
"use client"
import { useQueries, useQuery } from "@tanstack/react-query"
import clsx from "clsx"
import { useEffect, useMemo } from "react"
import { ChevronToggle } from "@/components/ui/ChevronToggle"
import { DownloadArrowIcon, UploadArrowIcon } from "@/components/ui/Icons"
import { MarqueeText } from "@/components/ui/MarqueeText"
import { Sparkline } from "@/components/ui/Sparkline"
import { useCarousel } from "@/hooks/useCarousel"
import { useLocalStorage } from "@/hooks/useLocalStorage"
import { formatSpeed, formatTimeAgo } from "@/lib/formatters"
import { clientQueryOptions } from "@/lib/query-options"
import { STORAGE_KEYS } from "@/lib/storage-keys"
interface ClientInfo {
id: number
name: string
enabled: boolean
lastError: string | null
errorSince: string | null
lastPolledAt: string | null
}
interface SpeedPoint {
up: number
down: number
}
interface ClientWithSpeeds {
client: ClientInfo
speeds: SpeedPoint[]
}
// ---------------------------------------------------------------------------
// ClientSlide
// ---------------------------------------------------------------------------
function ClientSlide({
entry,
expanded,
onToggle,
}: {
entry: ClientWithSpeeds
expanded: boolean
onToggle: () => void
}) {
const { client } = entry
const hasError = !!client.lastError
const latestSpeed = entry.speeds.at(-1)
function renderSubline(): React.ReactNode {
if (hasError) {
return (
<span className="text-danger">
Down{client.errorSince ? ` ${formatTimeAgo(client.errorSince)}` : ""}
</span>
)
}
if (!expanded && latestSpeed) {
return (
<span className="flex items-center gap-2">
<span className="text-accent">{formatSpeed(latestSpeed.up)}↑</span>
<span className="text-warn">{formatSpeed(latestSpeed.down)}↓</span>
</span>
)
}
return "Connected"
}
return (
<button
type="button"
onClick={onToggle}
onPointerDown={(e) => e.stopPropagation()}
className="flex items-center gap-2 cursor-pointer w-full text-left"
>
<span
className={clsx("color-dot", hasError ? "bg-danger" : "bg-success")}
style={hasError ? undefined : { boxShadow: "0 0 6px var(--color-success)" }}
/>
<div className="flex flex-col flex-1 min-w-0">
<MarqueeText className="text-xs font-mono text-secondary">{client.name}</MarqueeText>
<span className="text-3xs font-mono text-tertiary">{renderSubline()}</span>
</div>
<ChevronToggle expanded={expanded} variant="flip" />
</button>
)
}
// ---------------------------------------------------------------------------
// DownloadClientStatusWidget
// ---------------------------------------------------------------------------
const selectEnabled = (all: ClientInfo[]) => all.filter((c) => c.enabled)
function DownloadClientStatusWidget() {
const [expanded, setExpanded] = useLocalStorage(STORAGE_KEYS.CLIENT_WIDGET_EXPANDED, false)
// Set height-based default on first visit (when no preference is stored)
useEffect(() => {
try {
if (localStorage.getItem(STORAGE_KEYS.CLIENT_WIDGET_EXPANDED) === null) {
setExpanded(window.innerHeight >= 800)
}
} catch {}
}, [setExpanded])
// Fetch enabled clients — refetchInterval: 10_000 drives the cache for all consumers
const { data: enabledClients = [] } = useQuery({
...clientQueryOptions,
refetchInterval: 10_000,
select: selectEnabled,
})
// Fetch speeds for each enabled client
// Cache stores raw API shape so FleetSpeedSparklines (same key) gets correct data
const speedQueries = useQueries({
queries: enabledClients.map((client) => ({
queryKey: ["client-speeds", client.id] as const,
queryFn: async ({ signal }: { signal: AbortSignal }) => {
const res = await fetch(`/api/clients/${client.id}/speeds`, { signal })
if (!res.ok)
return [] as { timestamp: number; uploadSpeed: number; downloadSpeed: number }[]
return res.json() as Promise<
{ timestamp: number; uploadSpeed: number; downloadSpeed: number }[]
>
},
select: (
snaps: { timestamp: number; uploadSpeed: number; downloadSpeed: number }[]
): SpeedPoint[] => snaps.map((s) => ({ up: s.uploadSpeed, down: s.downloadSpeed })),
refetchInterval: 10_000,
})),
})
// Combine clients + speeds into entries
const entries: ClientWithSpeeds[] = useMemo(
() =>
enabledClients.map((client, i) => ({
client,
speeds: speedQueries[i]?.data ?? [],
})),
[enabledClients, speedQueries]
)
const loaded = enabledClients.length > 0
const { activeIndex, direction, animating, goTo, onPointerDownCapture, onPointerUp } =
useCarousel({ itemCount: entries.length, autoRotateMs: 8000 })
if (!loaded || entries.length === 0) return null
const current = entries[activeIndex]
return (
<div className="px-3 py-3 border-t border-border shrink-0">
<div
className="nm-inset-sm bg-control-bg px-3 pt-2.5 pb-3.5 flex flex-col gap-2 rounded-nm-md touch-pan-y"
onPointerDown={onPointerDownCapture}
onPointerUp={onPointerUp}
>
<div
key={activeIndex}
className="overflow-hidden"
style={{
animation: animating
? `slideIn${direction === "left" ? "Left" : "Right"} 300ms ease-out both`
: undefined,
}}
>
<ClientSlide
entry={current}
expanded={expanded}
onToggle={() => setExpanded((prev) => !prev)}
/>
{/* Collapsible sparklines */}
{current.speeds.length >= 2 && (
<div
className="grid transition-[grid-template-rows,opacity] duration-200 ease-out"
style={{
gridTemplateRows: expanded ? "1fr" : "0fr",
opacity: expanded ? 1 : 0,
}}
>
<div className="overflow-hidden">
<div className="flex flex-col gap-0.5 pt-1.5">
{(
[
{ key: "up", color: "accent", Icon: UploadArrowIcon },
{ key: "down", color: "warn", Icon: DownloadArrowIcon },
] as const
).map(({ key, color, Icon }) => (
<div key={key} className="flex items-center gap-2">
<Icon
width="10"
height="10"
stroke={`var(--color-${color})`}
strokeWidth={2.5}
className="shrink-0"
/>
<Sparkline
data={current.speeds.map((s) => s[key])}
color={`var(--color-${color})`}
width={160}
height={16}
/>
<span className={`text-xs font-mono text-${color} tabular-nums shrink-0`}>
{formatSpeed(current.speeds.at(-1)?.[key] ?? 0)}
</span>
</div>
))}
</div>
</div>
</div>
)}
</div>
{/* Dot indicators for carousel */}
{entries.length > 1 && (
<div className="flex items-center justify-center gap-2 pt-0.5">
{entries.map((entry, i) => (
<button
key={entry.client.id}
type="button"
onClick={() => goTo(i)}
className={clsx(
"w-1.5 h-1.5 rounded-full transition-all duration-200 cursor-pointer",
i === activeIndex ? "bg-accent scale-125" : "bg-muted hover:bg-tertiary"
)}
aria-label={`Show ${entry.client.name}`}
/>
))}
</div>
)}
</div>
</div>
)
}
export { DownloadClientStatusWidget }