feat: implement Phase 7 — Logs page redesign

- Auto-refresh toggle (RefreshCw icon, animates when active, polls every 5s)
- Horizontal filter bar: level select (140px) + search input + Clear button
- Clear button only rendered when level or search is active
- Level badges: INFO=blue, WARNING=amber, ERROR=red, CRITICAL=dark red, DEBUG=grey
- Row background tints: ERROR=#FFF5F5, WARNING=#FFFBF0, CRITICAL=#FFF0F0
- Message text in font-mono, metadata line with · separators
- Right-aligned timestamp: time on first line, date below
- Skeleton loading (8× SkeletonTableRow) while fetching

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-27 15:04:29 +01:00
parent 9693fa8031
commit 71db3cc305

View File

@@ -1,194 +1,255 @@
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { Search, RefreshCw, X } from 'lucide-react';
import { logApi } from '../api'; import { logApi } from '../api';
import type { LogEntry } from '../api'; import type { LogEntry } from '../api';
import { SkeletonTableRow } from '../components/SkeletonCard';
import { cn } from '../lib/utils';
// ── Level config ───────────────────────────────────────────────────────────
const LEVEL_CONFIG: Record<string, { badge: string; row: string }> = {
DEBUG: { badge: 'bg-[#F1F3F4] text-[#5F6368]', row: '' },
INFO: { badge: 'bg-[#E8F0FE] text-[#1557B0]', row: '' },
WARNING: { badge: 'bg-[#FEF7E0] text-[#7A5200]', row: 'bg-[#FFFBF0]' },
ERROR: { badge: 'bg-[#FDECEA] text-[#A50E0E]', row: 'bg-[#FFF5F5]' },
CRITICAL: { badge: 'bg-[#FCE0DE] text-[#7D1A0E]', row: 'bg-[#FFF0F0]' },
};
const levelConfig = (level: string) =>
LEVEL_CONFIG[level] ?? LEVEL_CONFIG.DEBUG;
const formatTime = (ts: string) => {
const d = new Date(ts);
return d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
};
const formatDate = (ts: string) =>
new Date(ts).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
// ──────────────────────────────────────────────────────────────────────────
export default function Logs() { export default function Logs() {
const [logs, setLogs] = useState<LogEntry[]>([]); const [logs, setLogs] = useState<LogEntry[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1); const [totalPages, setTotalPages] = useState(1);
const [level, setLevel] = useState<string>(''); const [level, setLevel] = useState('');
const [search, setSearch] = useState(''); const [search, setSearch] = useState('');
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
const [autoRefresh, setAutoRefresh] = useState(false);
const debounceTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const intervalRef = useRef<ReturnType<typeof setInterval> | undefined>(undefined);
useEffect(() => { useEffect(() => {
loadLogs(); loadLogs();
}, [page, level, searchQuery]); }, [page, level, searchQuery]);
// Auto-refresh
useEffect(() => {
if (autoRefresh) {
intervalRef.current = setInterval(() => loadLogs(), 5000);
} else {
if (intervalRef.current) clearInterval(intervalRef.current);
}
return () => { if (intervalRef.current) clearInterval(intervalRef.current); };
}, [autoRefresh, page, level, searchQuery]);
const loadLogs = async () => { const loadLogs = async () => {
try { try {
setLoading(true); setLoading(true);
const response = await logApi.list(page, 50, level || undefined, searchQuery || undefined); const response = await logApi.list(page, 50, level || undefined, searchQuery || undefined);
setLogs(response.data.data); setLogs(response.data.data);
setTotalPages(response.data.pagination.pages); setTotalPages(response.data.pagination.pages);
} catch (error) { } catch (err) {
console.error('Failed to load logs:', error); console.error('Failed to load logs:', err);
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; };
const handleSearch = (e: React.FormEvent) => { const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
e.preventDefault(); const val = e.target.value;
setSearchQuery(search); setSearch(val);
if (debounceTimer.current) clearTimeout(debounceTimer.current);
debounceTimer.current = setTimeout(() => {
setSearchQuery(val);
setPage(1);
}, 400);
};
const handleLevelChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
setLevel(e.target.value);
setPage(1); setPage(1);
}; };
const getLevelColor = (logLevel: string) => { const clearFilters = () => {
switch (logLevel) { setLevel('');
case 'DEBUG': return 'bg-gray-100 text-gray-700'; setSearch('');
case 'INFO': return 'bg-blue-100 text-blue-700'; setSearchQuery('');
case 'WARNING': return 'bg-yellow-100 text-yellow-700'; setPage(1);
case 'ERROR': return 'bg-red-100 text-red-700';
case 'CRITICAL': return 'bg-red-200 text-red-900';
default: return 'bg-gray-100 text-gray-700';
}
}; };
const formatTimestamp = (timestamp: string) => { const hasFilters = !!(level || searchQuery);
return new Date(timestamp).toLocaleString();
};
return ( return (
<div> <div className="space-y-4">
<h2 className="text-2xl font-bold text-gray-900 mb-6">Logs</h2>
{/* Filters */} {/* ── Auto-refresh toggle (top-right of page) ──────────────── */}
<div className="bg-white rounded-lg shadow p-6 mb-6"> <div className="flex items-center justify-end">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <button
{/* Level Filter */} onClick={() => setAutoRefresh(v => !v)}
<div> className={cn(
<label htmlFor="level" className="block text-sm font-medium text-gray-700 mb-2"> 'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium border transition-colors',
Log Level autoRefresh
</label> ? 'bg-primary-container border-primary text-primary'
<select : 'bg-surface border-outline text-on-surface-variant hover:bg-surface-2',
id="level" )}
value={level} aria-label={autoRefresh ? 'Disable auto-refresh' : 'Enable auto-refresh'}
onChange={(e) => { >
setLevel(e.target.value); <RefreshCw
setPage(1); size={13}
}} className={cn(autoRefresh && 'animate-spin')}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" aria-hidden="true"
> />
<option value="">All Levels</option> {autoRefresh ? 'Auto-refreshing' : 'Auto-refresh'}
<option value="DEBUG">DEBUG</option> </button>
<option value="INFO">INFO</option> </div>
<option value="WARNING">WARNING</option>
<option value="ERROR">ERROR</option>
<option value="CRITICAL">CRITICAL</option>
</select>
</div>
{/* Search */} {/* ── Filter bar ───────────────────────────────────────────── */}
<div> <div className="flex items-center gap-3">
<label htmlFor="search" className="block text-sm font-medium text-gray-700 mb-2"> {/* Level select */}
Search Messages <select
</label> value={level}
<form onSubmit={handleSearch} className="flex space-x-2"> onChange={handleLevelChange}
<input className="h-10 w-36 px-3 border border-outline rounded-xs bg-surface text-sm text-on-surface outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 shrink-0"
type="text" aria-label="Filter by log level"
id="search" >
value={search} <option value="">All Levels</option>
onChange={(e) => setSearch(e.target.value)} <option value="DEBUG">DEBUG</option>
placeholder="Search log messages..." <option value="INFO">INFO</option>
className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" <option value="WARNING">WARNING</option>
/> <option value="ERROR">ERROR</option>
<button <option value="CRITICAL">CRITICAL</option>
type="submit" </select>
className="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-md text-sm font-medium"
> {/* Search input */}
Search <div className="relative flex-1">
</button> <Search
</form> size={16}
</div> className="absolute left-3 top-1/2 -translate-y-1/2 text-on-surface-variant pointer-events-none"
aria-hidden="true"
/>
<input
type="text"
value={search}
onChange={handleSearchChange}
placeholder="Search messages…"
className="w-full h-10 pl-9 pr-3 border border-outline rounded-xs bg-surface text-sm text-on-surface outline-none focus:border-primary focus:ring-2 focus:ring-primary/20"
aria-label="Search log messages"
/>
</div> </div>
{/* Clear Filters */} {/* Clear filters — only when active */}
{(level || searchQuery) && ( {hasFilters && (
<div className="mt-4"> <button
<button onClick={clearFilters}
onClick={() => { className="inline-flex items-center gap-1 h-10 px-3 border border-outline rounded-xs text-sm text-on-surface-variant hover:bg-surface-2 transition-colors shrink-0"
setLevel(''); aria-label="Clear filters"
setSearch(''); >
setSearchQuery(''); <X size={14} />
setPage(1); Clear
}} </button>
className="text-sm text-blue-600 hover:text-blue-700"
>
Clear Filters
</button>
</div>
)} )}
</div> </div>
{/* Logs List */} {/* ── Log list ─────────────────────────────────────────────── */}
{loading ? ( <div className="bg-surface rounded-lg shadow-level-1 overflow-hidden">
<div className="flex justify-center items-center h-64"> <div className="px-4 py-3.5 border-b border-outline">
<div className="text-gray-500">Loading logs...</div> <h2 className="text-sm font-semibold text-on-surface">Log Entries</h2>
</div> </div>
) : (
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200">
<h3 className="text-lg font-semibold text-gray-900">Log Entries</h3>
</div>
{logs.length === 0 ? ( {loading ? (
<div className="px-6 py-12 text-center text-gray-500"> <table className="w-full">
No logs found <tbody>
</div> {Array.from({ length: 8 }).map((_, i) => (
) : ( <SkeletonTableRow key={i} />
<> ))}
<div className="divide-y divide-gray-200"> </tbody>
{logs.map((log, index) => ( </table>
<div key={index} className="px-6 py-4"> ) : logs.length === 0 ? (
<div className="flex items-start space-x-3"> <p className="px-4 py-10 text-sm text-center text-on-surface-variant">
<span className={`px-2 py-1 text-xs font-medium rounded ${getLevelColor(log.level)}`}> {hasFilters ? 'No logs match the current filters.' : 'No log entries yet.'}
{log.level} </p>
</span> ) : (
<div className="flex-1 min-w-0"> <>
<p className="text-sm text-gray-900 break-words"> <div className="divide-y divide-outline">
{log.message} {logs.map((log, i) => {
</p> const cfg = levelConfig(log.level);
<div className="mt-1 flex items-center space-x-4 text-xs text-gray-500"> return (
<span>{formatTimestamp(log.timestamp)}</span> <div
{log.module && <span>Module: {log.module}</span>} key={i}
{log.function && <span>Function: {log.function}</span>} className={cn('px-4 py-3 flex items-start gap-3', cfg.row)}
{log.line && <span>Line: {log.line}</span>} >
</div> {/* Level badge */}
<span
className={cn(
'shrink-0 w-16 text-center text-xs font-semibold py-0.5 rounded-sm',
cfg.badge,
)}
>
{log.level}
</span>
{/* Message + metadata */}
<div className="flex-1 min-w-0">
<p className="font-mono text-sm text-on-surface break-all leading-snug">
{log.message}
</p>
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 text-xs text-on-surface-variant">
{log.module && <span>{log.module}</span>}
{log.function && <><span>·</span><span>{log.function}</span></>}
{log.line && <><span>·</span><span>line {log.line}</span></>}
</div> </div>
</div> </div>
</div>
))}
</div>
{/* Pagination */} {/* Timestamp */}
{totalPages > 1 && ( <div className="shrink-0 text-right">
<div className="px-6 py-4 border-t border-gray-200 flex justify-between items-center"> <p className="font-mono text-xs text-on-surface-variant">{formatTime(log.timestamp)}</p>
<div className="text-sm text-gray-500"> <p className="text-xs text-on-surface-variant opacity-60">{formatDate(log.timestamp)}</p>
Page {page} of {totalPages} </div>
</div>
<div className="flex space-x-2">
<button
onClick={() => setPage(page - 1)}
disabled={page === 1}
className="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
>
Previous
</button>
<button
onClick={() => setPage(page + 1)}
disabled={page === totalPages}
className="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
>
Next
</button>
</div> </div>
);
})}
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="px-4 py-3 border-t border-outline flex items-center justify-between">
<span className="text-sm text-on-surface-variant">
Page {page} of {totalPages}
</span>
<div className="flex gap-2">
<button
onClick={() => setPage(p => p - 1)}
disabled={page === 1}
className="px-3 py-1.5 border border-outline rounded-xs text-sm text-on-surface hover:bg-surface-2 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
>
Previous
</button>
<button
onClick={() => setPage(p => p + 1)}
disabled={page === totalPages}
className="px-3 py-1.5 border border-outline rounded-xs text-sm text-on-surface hover:bg-surface-2 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
>
Next
</button>
</div> </div>
)} </div>
</> )}
)} </>
</div> )}
)} </div>
</div> </div>
); );
} }