forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventsSection.tsx
More file actions
394 lines (361 loc) · 14.9 KB
/
Copy pathEventsSection.tsx
File metadata and controls
394 lines (361 loc) · 14.9 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// src/components/settings/EventsSection.tsx
//
// Functions: formatTime, getDateKey, formatDateLabel, EventsSection
"use client"
import { useQuery, useQueryClient } from "@tanstack/react-query"
import clsx from "clsx"
import { useCallback, useMemo, useState } from "react"
import { SettingsSection } from "@/components/settings/SettingsSection"
import { CopyButton, DownloadButton } from "@/components/ui/ActionButtons"
import { Button } from "@/components/ui/Button"
import { ConfirmAction } from "@/components/ui/ConfirmAction"
import { FilterPill } from "@/components/ui/FilterPill"
import { RefreshIcon, TrashIcon } from "@/components/ui/Icons"
import { Input } from "@/components/ui/Input"
import { Notice } from "@/components/ui/Notice"
import { EventLogSkeleton } from "@/components/ui/skeletons"
import { useSetToggle } from "@/hooks/useSetToggle"
import { EVENT_CATEGORIES, EVENT_LEVELS, type EventCategory, type EventLevel } from "@/lib/events"
import { extractApiError } from "@/lib/extract-api-error"
import { formatBytesNum, localDateStr } from "@/lib/formatters"
import { EVENTS_LIMIT_CAP } from "@/lib/limits"
import type { EventsPageResponse } from "@/types/api"
const CATEGORY_STYLES: Record<EventCategory, { border: string; icon: string; iconColor: string }> =
{
polls: { border: "border-l-accent", icon: "✓", iconColor: "text-success" },
clients: { border: "border-l-sky-400", icon: "↕", iconColor: "text-sky-400" },
auth: { border: "border-l-violet-400", icon: "◆", iconColor: "text-violet-400" },
settings: { border: "border-l-warn", icon: "●", iconColor: "text-warn" },
backups: { border: "border-l-success", icon: "■", iconColor: "text-success" },
}
const LEVEL_TEXT_COLORS: Record<EventLevel, string> = {
debug: "text-violet-400",
info: "text-accent",
warn: "text-warn",
error: "text-danger",
}
function formatTime(iso: string): string {
return new Date(iso).toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
})
}
function getDateKey(iso: string): string {
return new Date(iso).toDateString()
}
function formatDateLabel(iso: string): string {
const d = new Date(iso)
const now = new Date()
if (d.toDateString() === now.toDateString()) return "Today"
const yesterday = new Date(now)
yesterday.setDate(yesterday.getDate() - 1)
if (d.toDateString() === yesterday.toDateString()) return "Yesterday"
return d.toLocaleDateString([], { month: "short", day: "numeric" })
}
export function EventsSection() {
const queryClient = useQueryClient()
const categories = useSetToggle<EventCategory>(EVENT_CATEGORIES)
const levels = useSetToggle<EventLevel>(["info", "warn", "error"])
const [searchQuery, setSearchQuery] = useState("")
const [expandedIds, setExpandedIds] = useState<Set<string>>(() => new Set())
const [downloadError, setDownloadError] = useState<string | null>(null)
const [clearConfirm, setClearConfirm] = useState(false)
const [clearLoading, setClearLoading] = useState(false)
const [clearError, setClearError] = useState<string | null>(null)
const {
data: eventsData,
isLoading: loading,
error: queryError,
} = useQuery({
queryKey: ["events"],
queryFn: async ({ signal }) => {
const params = new URLSearchParams({
category: "all",
limit: String(EVENTS_LIMIT_CAP),
offset: "0",
})
const res = await fetch(`/api/settings/events?${params}`, { signal })
if (!res.ok) throw new Error(await extractApiError(res, "Failed to load events"))
return res.json() as Promise<EventsPageResponse>
},
})
const events = eventsData?.events ?? []
const logSizeBytes = eventsData?.logSizeBytes ?? 0
const error = queryError
? queryError instanceof Error
? queryError.message
: "Failed to load events"
: null
const filteredEvents = useMemo(() => {
let result = events
if (categories.size < EVENT_CATEGORIES.length) {
result = result.filter((e) => categories.has(e.category))
}
if (levels.size < EVENT_LEVELS.length) {
result = result.filter((e) => levels.has(e.level))
}
if (searchQuery.trim()) {
const q = searchQuery.toLowerCase()
result = result.filter(
(e) =>
e.title.toLowerCase().includes(q) ||
e.detail?.toLowerCase().includes(q) ||
e.trackerName?.toLowerCase().includes(q)
)
}
return result
}, [events, categories, levels, searchQuery])
const copyValue = useMemo(() => {
return filteredEvents
.map((e) => {
const ts = new Date(e.timestamp)
.toISOString()
.replace("T", " ")
.replace(/\.\d{3}Z$/, "")
const parts = [`[${ts}]`, `[${e.level}]`, `[${e.category}]`, e.title]
if (e.detail) parts.push(`— ${e.detail}`)
return parts.join(" ")
})
.join("\n")
}, [filteredEvents])
async function handleClear() {
setClearLoading(true)
setClearError(null)
try {
const res = await fetch("/api/settings/logs", { method: "DELETE" })
if (!res.ok) {
setClearError(await extractApiError(res, "Failed to clear logs"))
return
}
setClearConfirm(false)
queryClient.invalidateQueries({ queryKey: ["events"] })
} catch {
setClearError("Failed to clear log file")
} finally {
setClearLoading(false)
}
}
const handleToggleExpand = useCallback((id: string) => {
setExpandedIds((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}, [])
const allCategoriesActive = categories.size === EVENT_CATEGORIES.length
// Track date separators across the render
let lastDateKey = ""
return (
<SettingsSection id="events" title="Events" cardClassName="flex flex-col gap-3">
{/* ── Search + actions ──────────────────────────────────────── */}
<div className="flex items-center gap-2">
<Input
type="search"
placeholder="Search…"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1 min-w-30 max-w-80 text-xs"
/>
<span className="flex-1" />
<CopyButton value={copyValue} />
<DownloadButton
url="/api/settings/logs/download"
fallbackFilename={`tracker-tracker-${localDateStr()}.log`}
notFoundMessage="Log file not available (file logging is only active in Docker)"
onError={setDownloadError}
/>
<Button
variant="secondary"
size="icon"
onClick={() => queryClient.invalidateQueries({ queryKey: ["events"] })}
aria-label="Refresh events"
leftIcon={<RefreshIcon width="12" height="12" />}
/>
<Button
variant={clearConfirm ? "danger" : "secondary"}
size="icon"
onClick={() => setClearConfirm((v) => !v)}
aria-label={
logSizeBytes > 0 ? `Clear logs (${formatBytesNum(logSizeBytes)})` : "Clear logs"
}
leftIcon={<TrashIcon width="12" height="12" />}
/>
</div>
<div className="border-t border-border my-3" />
{/* ── Filters (categories + levels) ─────────────────────────── */}
<div className="flex flex-wrap items-center gap-2">
<FilterPill
size="sm"
active={allCategoriesActive}
onClick={() =>
allCategoriesActive ? categories.reset([]) : categories.reset(EVENT_CATEGORIES)
}
text={allCategoriesActive ? "None" : "All"}
/>
{EVENT_CATEGORIES.map((cat) => (
<FilterPill
key={cat}
size="sm"
active={categories.has(cat)}
onClick={() => categories.toggle(cat)}
inactive="strikethrough"
text={cat.charAt(0).toUpperCase() + cat.slice(1)}
/>
))}
<span className="flex-1" />
<span className="w-px h-4 bg-border shrink-0 mx-0.5" />
{EVENT_LEVELS.map((level) => (
<FilterPill
key={level}
size="sm"
active={levels.has(level)}
onClick={() => levels.toggle(level)}
activeColor={LEVEL_TEXT_COLORS[level]}
inactive="strikethrough"
text={level.charAt(0).toUpperCase() + level.slice(1)}
/>
))}
</div>
<div className="border-t border-border my-3" />
{/* ── Clear confirmation ───────────────────────────────────── */}
{clearConfirm && (
<ConfirmAction
message="Truncate log file? DB events are not affected."
confirmLabel="Confirm"
confirmingLabel="Clearing…"
confirming={clearLoading}
onConfirm={handleClear}
onCancel={() => {
setClearConfirm(false)
setClearError(null)
}}
>
<Notice message={clearError} />
</ConfirmAction>
)}
{/* ── Error ────────────────────────────────────────────────── */}
<Notice message={error ?? downloadError} />
{/* ── Event stream ─────────────────────────────────────────── */}
<div className="nm-inset-sm bg-control-bg overflow-x-hidden overflow-y-auto max-h-140 styled-scrollbar rounded-nm-md">
{loading && events.length === 0 ? (
<EventLogSkeleton />
) : filteredEvents.length === 0 ? (
<p className="px-3 py-8 text-xs font-mono text-muted text-center">
{events.length === 0 ? "No events yet." : "No events match the current filters."}
</p>
) : (
filteredEvents.map((event, i) => {
const baseStyle = CATEGORY_STYLES[event.category]
const LEVEL_STYLES: Partial<
Record<EventLevel, { border: string; icon: string; iconColor: string }>
> = {
error: { border: "border-l-danger", icon: "✕", iconColor: "text-danger" },
warn: { border: "border-l-warn", icon: "⚠", iconColor: "text-warn" },
debug: {
border: "border-l-violet-400/50",
icon: "·",
iconColor: "text-violet-400/60",
},
}
const style = LEVEL_STYLES[event.level] ?? baseStyle
const dateKey = getDateKey(event.timestamp)
const showDateSep = dateKey !== lastDateKey
lastDateKey = dateKey
const isExpanded = expandedIds.has(event.id)
const hasBatch = Boolean(event.children?.length)
const hasDetail = Boolean(event.detail) || hasBatch
const isExpandable = hasDetail
return (
<div key={event.id}>
{showDateSep && (
<div className="sticky top-0 z-10 px-3 py-1 text-3xs font-mono text-tertiary bg-overlay/90 backdrop-blur-sm border-b border-border">
{formatDateLabel(event.timestamp)}
</div>
)}
{(() => {
const rowClass = clsx(
"flex flex-col gap-0 px-3 py-1.5 text-xs font-mono border-l-3 w-full text-left",
style.border,
i % 2 === 0 ? "bg-control-bg" : "bg-elevated/50",
isExpandable &&
"cursor-pointer hover:bg-elevated/80 transition-colors duration-100"
)
const inner = (
<>
<div className="flex items-baseline gap-2 min-w-0">
<span
className={clsx("shrink-0 w-3 text-center leading-none", style.iconColor)}
>
{hasBatch ? (isExpanded ? "▾" : "▸") : style.icon}
</span>
<span className="text-tertiary shrink-0 tabular-nums w-15.5">
{formatTime(event.timestamp)}
</span>
<span className="text-secondary shrink-0">{event.title}</span>
{hasDetail && !isExpanded && !hasBatch && (
<span className="text-tertiary truncate">— {event.detail}</span>
)}
</div>
{isExpanded && !hasBatch && event.detail && (
<pre className="text-tertiary text-2xs leading-relaxed whitespace-pre-wrap break-all pl-[calc(0.75rem+62px+0.5rem)] pt-1 pb-0.5 select-text">
{event.detail}
</pre>
)}
</>
)
const row = isExpandable ? (
<button
type="button"
onClick={() => handleToggleExpand(event.id)}
className={rowClass}
>
{inner}
</button>
) : (
<div className={rowClass}>{inner}</div>
)
return (
<>
{row}
{isExpanded && hasBatch && (
<div className="border-l-3 border-l-accent/30">
{event.children?.map((child, ci) => (
<div
key={child.id}
className={clsx(
"flex items-baseline gap-2 px-3 py-1 text-xs font-mono pl-8",
ci % 2 === 0 ? "bg-control-bg/60" : "bg-elevated/30"
)}
>
<span className="text-success shrink-0 w-3 text-center text-2xs">
✓
</span>
<span className="text-tertiary truncate">{child.detail}</span>
</div>
))}
</div>
)}
</>
)
})()}
</div>
)
})
)}
</div>
{/* ── Footer ───────────────────────────────────────────────── */}
<div className="flex items-center justify-between">
{filteredEvents.length > 0 && (
<span className="timestamp">
{filteredEvents.length === events.length
? `${events.length} events`
: `${filteredEvents.length} of ${events.length}`}
</span>
)}
</div>
</SettingsSection>
)
}