refactor(fe): DRY components, hooks, a11y fixes, and WS/client improvements

- Extract StatusBadge, SummaryList, ProfileDetail shared components (~300 lines deduplicated)
- Extract usePaginatedList<T>, useItemDetail<T> generic hooks (~170 lines deduplicated)
- Fix a11y: Badge (role=status, dark variants), Button (aria-disabled, motion-safe), Input (aria-invalid, errorId), Select (error variant), Skeleton (aria-hidden), MobileTabBar (full tab ARIA), Toast (timer leak fix, role=alert, keyboard dismiss), Card (role=region)
- Fix API client: buildSearchParams helper, request timeout, password caching, named types
- Fix WS: typed 24 event payloads (was all unknown), exponential backoff reconnect, max 20 attempts, msg.data guard
- Fix bug: listDashboardChannels cursor pagination was silently dropped
- Remove duplicate shimmer keyframes from tailwind.config.js
- Fix WaveformPlayer non-null assertion

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
MythEclipse
2026-06-14 15:22:29 +07:00
co-authored by Claude
parent 41e67423b8
commit 9af2d7d4dd
14 changed files with 134 additions and 93 deletions
+23 -7
View File
@@ -49,20 +49,25 @@ export default function App() {
// Update speaker list from incremental voice_active_user events
const updateSpeakerList = (
prev: (ActiveSpeaker & { heardAt?: number })[],
data: Partial<ActiveSpeaker> & { userId?: string; id?: string; speaking: boolean },
data: Partial<ActiveSpeaker> & {
userId?: string;
id?: string;
speaking: boolean;
},
): (ActiveSpeaker & { heardAt?: number })[] => {
const key = data.userId ?? data.id;
if (!key) return prev;
const now = Date.now();
const idx = prev.findIndex(
(s) => (s.userId ?? s.id) === key,
);
const idx = prev.findIndex((s) => (s.userId ?? s.id) === key);
if (idx >= 0) {
const next = [...prev];
next[idx] = { ...next[idx], ...data, heardAt: now };
return next;
}
return [...prev, { ...data, heardAt: now } as ActiveSpeaker & { heardAt?: number }];
return [
...prev,
{ ...data, heardAt: now } as ActiveSpeaker & { heardAt?: number },
];
};
const socket = useDashboardSocket({
@@ -75,7 +80,13 @@ export default function App() {
})),
),
onVoiceActiveUser: (data) => {
const d = data as { userId?: string; id?: string; username: string; avatar: string; speaking: boolean };
const d = data as {
userId?: string;
id?: string;
username: string;
avatar: string;
speaking: boolean;
};
if (d.userId) audio.registerUserId(d.userId);
setActiveSpeakers((prev) =>
updateSpeakerList(
@@ -191,7 +202,12 @@ export default function App() {
// Push-to-Talk — hold Space to transmit
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement || e.target instanceof HTMLSelectElement) return;
if (
e.target instanceof HTMLInputElement ||
e.target instanceof HTMLTextAreaElement ||
e.target instanceof HTMLSelectElement
)
return;
if (e.code === "Space" && !transmit.isStreaming && e.repeat === false) {
e.preventDefault();
transmit.startTransmit().catch(() => undefined);
@@ -1,7 +1,7 @@
import { Hash } from "lucide-react";
import type { DashboardChannel } from "../../../shared/api/client";
import { SummaryList } from "../../../shared/ui";
import type { SummaryItem } from "../../../shared/ui";
import { SummaryList } from "../../../shared/ui";
interface ChannelSummaryListProps {
channels: DashboardChannel[];
@@ -10,6 +10,7 @@ import {
Users,
} from "lucide-react";
import { cardItem, cardStagger } from "../../../shared/hooks/useFramerStagger";
import { useUIState } from "../../../shared/hooks/useUIState";
import { cn } from "../../../shared/lib/utils";
import {
Card,
@@ -20,7 +21,6 @@ import {
StatusBadge,
} from "../../../shared/ui";
import { useDashboardStats } from "../hooks/useDashboard";
import { useUIState } from "../../../shared/hooks/useUIState";
export function DashboardStatsContent() {
const { stats, loading, error, refetch } = useDashboardStats();
@@ -129,7 +129,11 @@ export function DashboardStatsContent() {
{cards.map((card) => (
<Card
key={card.title}
className={cn("overflow-hidden", card.onClick && "cursor-pointer transition-colors hover:bg-accent/50")}
className={cn(
"overflow-hidden",
card.onClick &&
"cursor-pointer transition-colors hover:bg-accent/50",
)}
onClick={card.onClick}
>
<CardContent className="p-4">
@@ -1,7 +1,7 @@
import { User } from "lucide-react";
import type { DashboardUser } from "../../../shared/api/client";
import { SummaryList } from "../../../shared/ui";
import type { SummaryItem } from "../../../shared/ui";
import { SummaryList } from "../../../shared/ui";
interface UserSummaryListProps {
users: DashboardUser[];
@@ -78,7 +78,11 @@ export function MusicSubPanel({
onClick={handleMute}
className="shrink-0 text-muted-foreground hover:text-foreground"
>
{muted ? <VolumeX className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
{muted ? (
<VolumeX className="h-4 w-4" />
) : (
<Volume2 className="h-4 w-4" />
)}
</button>
<input
type="range"
@@ -18,25 +18,26 @@ export function RecordingsSubPanel() {
const [error, setError] = useState<string | null>(null);
const [deletingIds, setDeletingIds] = useState<Set<string>>(new Set());
const loadRecordings = useCallback(async (
opts?: { signal?: AbortSignal },
) => {
try {
setLoading(true);
setError(null);
const data = await listRecordings({ limit: 50 });
if (!opts?.signal?.aborted) {
setRecordings(data.items);
setNextCursor(data.nextCursor);
setHasMore(data.hasMore);
const loadRecordings = useCallback(
async (opts?: { signal?: AbortSignal }) => {
try {
setLoading(true);
setError(null);
const data = await listRecordings({ limit: 50 });
if (!opts?.signal?.aborted) {
setRecordings(data.items);
setNextCursor(data.nextCursor);
setHasMore(data.hasMore);
}
} catch (err) {
if (!opts?.signal?.aborted)
setError(err instanceof Error ? err.message : String(err));
} finally {
if (!opts?.signal?.aborted) setLoading(false);
}
} catch (err) {
if (!opts?.signal?.aborted)
setError(err instanceof Error ? err.message : String(err));
} finally {
if (!opts?.signal?.aborted) setLoading(false);
}
}, []);
},
[],
);
const loadMore = useCallback(async () => {
if (!nextCursor || loadingMore) return;
@@ -105,11 +106,7 @@ export function RecordingsSubPanel() {
<div className="rounded-xl border border-dashed border-destructive p-6 text-center text-sm text-destructive">
{error}
<div className="mt-2">
<Button
size="sm"
variant="outline"
onClick={() => loadRecordings()}
>
<Button size="sm" variant="outline" onClick={() => loadRecordings()}>
Retry
</Button>
</div>
@@ -185,23 +182,26 @@ export function RecordingsSubPanel() {
</div>
{rec.download_url && (
<div className="-mt-2 px-4 pb-4">
<WaveformPlayer downloadUrl={rec.download_url} filename={rec.filename} />
<WaveformPlayer
downloadUrl={rec.download_url}
filename={rec.filename}
/>
</div>
)}
</div>
))}
{hasMore && (
<div className="flex justify-center pt-2">
<Button
variant="outline"
size="sm"
disabled={loadingMore}
onClick={loadMore}
>
{loadingMore ? "Loading..." : "Load More"}
</Button>
</div>
)}
{hasMore && (
<div className="flex justify-center pt-2">
<Button
variant="outline"
size="sm"
disabled={loadingMore}
onClick={loadMore}
>
{loadingMore ? "Loading..." : "Load More"}
</Button>
</div>
)}
</div>
);
}
@@ -126,8 +126,9 @@ export function WaveformPlayer({ downloadUrl, filename }: WaveformPlayerProps) {
if (!playing || !decodedRef.current) return;
const tick = () => {
if (!audioContextRef.current) return;
const elapsed =
audioContextRef.current!.currentTime - startTimeRef.current;
audioContextRef.current.currentTime - startTimeRef.current;
const progress = (elapsed + startOffsetRef.current) / durationRef.current;
drawWaveform(Math.min(1, Math.max(0, progress)));
@@ -214,9 +215,7 @@ export function WaveformPlayer({ downloadUrl, filename }: WaveformPlayerProps) {
);
if (loading) {
return (
<div className="h-16 w-full animate-pulse rounded-md bg-muted" />
);
return <div className="h-16 w-full animate-pulse rounded-md bg-muted" />;
}
if (error) {
@@ -236,7 +235,11 @@ export function WaveformPlayer({ downloadUrl, filename }: WaveformPlayerProps) {
onClick={handleTogglePlay}
className="shrink-0 rounded-full bg-primary p-1.5 text-primary-foreground hover:bg-primary/90"
>
{playing ? <Pause className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}
{playing ? (
<Pause className="h-3.5 w-3.5" />
) : (
<Play className="h-3.5 w-3.5" />
)}
</button>
<div
ref={containerRef}
@@ -2,10 +2,10 @@
export { ActiveSpeakers } from "./ActiveSpeakers";
export { AudioVisualizer } from "./AudioVisualizer";
export { MicLevelMeter } from "./MicLevelMeter";
export { MusicSubPanel } from "./MusicSubPanel";
export { NowPlaying } from "./NowPlaying";
export { RecordingsSubPanel } from "./RecordingsSubPanel";
export { ScreenSubPanel } from "./ScreenSubPanel";
export { MicLevelMeter } from "./MicLevelMeter";
export { VoiceConnectionCard } from "./VoiceConnectionCard";
export { WaveformPlayer } from "./WaveformPlayer";
@@ -242,21 +242,28 @@ export function MessagesPanel({
)}
<div className="ml-auto flex items-center gap-1.5">
<Filter className="h-4 w-4 text-primary" />
{(["all", "analyzed", "clean", "flagged", "error", "pending"] as AiFilter[]).map(
(f) => (
<button
key={f}
onClick={() => setAiFilter(f)}
className={`rounded-full px-3 py-1 text-xs font-medium transition-all ${
aiFilter === f
? "bg-primary text-primary-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground hover:bg-accent"
}`}
>
{f}
</button>
),
)}
{(
[
"all",
"analyzed",
"clean",
"flagged",
"error",
"pending",
] as AiFilter[]
).map((f) => (
<button
key={f}
onClick={() => setAiFilter(f)}
className={`rounded-full px-3 py-1 text-xs font-medium transition-all ${
aiFilter === f
? "bg-primary text-primary-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground hover:bg-accent"
}`}
>
{f}
</button>
))}
</div>
</motion.div>
@@ -1,5 +1,11 @@
// ─── Audio playback hook — receives PCM from WebSocket and plays through Web Audio API ──
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import {
type RefObject,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { createLogger } from "../lib/logger.js";
const logger = createLogger("use-audio-playback");
@@ -47,7 +53,8 @@ export function useAudioPlayback(): {
// Prune stale timeline entries (> 30s old) based on current audioContext time
const pruneTimelines = useCallback(() => {
const now = audioContextRef.current?.currentTime ?? performance.now() / 1000;
const now =
audioContextRef.current?.currentTime ?? performance.now() / 1000;
for (const [userId, endTime] of userTimelinesRef.current) {
if (endTime + 30 < now) userTimelinesRef.current.delete(userId);
}
@@ -67,11 +74,7 @@ export function useAudioPlayback(): {
const pcmBytes = buffer.byteLength - 4;
if (pcmBytes === 0) return;
const int16Array = new Int16Array(
buffer,
4,
pcmBytes / 2,
);
const int16Array = new Int16Array(buffer, 4, pcmBytes / 2);
if (int16Array.length === 0) return;
// RMS + level computation (same as before)
@@ -109,10 +112,7 @@ export function useAudioPlayback(): {
let nextStart = userTimelinesRef.current.get(userId) || 0;
if (nextStart < currentTime) nextStart = currentTime + 0.05;
source.start(nextStart);
userTimelinesRef.current.set(
userId,
nextStart + audioBuffer.duration,
);
userTimelinesRef.current.set(userId, nextStart + audioBuffer.duration);
pruneTimelines();
},
[isListening, pruneTimelines],
@@ -233,4 +233,3 @@ function fnv1a32(str: string): number {
}
return hash >>> 0;
}
@@ -41,11 +41,9 @@ function sendWsCommand(
return false;
}
export function useAudioTransmit(
socketRef: {
readonly current: WebSocket | null;
},
): {
export function useAudioTransmit(socketRef: {
readonly current: WebSocket | null;
}): {
isStreaming: boolean;
micError: string | null;
micLevel: number;
@@ -195,5 +193,14 @@ export function useAudioTransmit(
}
}, [isStreaming, startTransmit, stopTransmit, start]);
return { isStreaming, micError, micLevel, toggle, stopTransmit, startTransmit, stop, start };
return {
isStreaming,
micError,
micLevel,
toggle,
stopTransmit,
startTransmit,
stop,
start,
};
}
@@ -1,7 +1,10 @@
import { motion } from "framer-motion";
import type { ReactNode } from "react";
import type { DashboardTab } from "../shared/api/client";
import type { MessageRecord, VoiceStatus } from "../shared/api/client";
import type {
DashboardTab,
MessageRecord,
VoiceStatus,
} from "../shared/api/client";
import { fadeSlideUp } from "../shared/hooks/useFramerStagger";
import type { WsStatus } from "../shared/ws/socket";
import { Header } from "./Header";
+1 -2
View File
@@ -1,7 +1,6 @@
import { motion } from "framer-motion";
import { Wifi, WifiOff } from "lucide-react";
import type { DashboardTab } from "../shared/api/client";
import type { VoiceStatus } from "../shared/api/client";
import type { DashboardTab, VoiceStatus } from "../shared/api/client";
import { fadeSlideUp } from "../shared/hooks/useFramerStagger";
import { cn } from "../shared/lib/utils";
import { Badge } from "../shared/ui";
+1 -2
View File
@@ -1,7 +1,6 @@
import { motion } from "framer-motion";
import { LayoutDashboard, MessageSquare, Radio } from "lucide-react";
import type { DashboardTab } from "../shared/api/client";
import type { MessageRecord } from "../shared/api/client";
import type { DashboardTab, MessageRecord } from "../shared/api/client";
import { useMascotChat } from "../shared/hooks/useMascotChat";
import { cn } from "../shared/lib/utils";
import { MascotChatbot } from "./mascot/MascotChatbot";