refactor: 使用 sonner、zustand persist、partysocket 替换手写实现
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
import { Toaster } from "sonner";
|
||||
import { HistoryList } from "./components/HistoryList";
|
||||
import { MicButton } from "./components/MicButton";
|
||||
import { PreviewBox } from "./components/PreviewBox";
|
||||
import { StatusBadge } from "./components/StatusBadge";
|
||||
import { Toast } from "./components/Toast";
|
||||
import { useRecorder } from "./hooks/useRecorder";
|
||||
import { useWebSocket } from "./hooks/useWebSocket";
|
||||
|
||||
@@ -27,7 +27,7 @@ export function App() {
|
||||
<MicButton onStart={startRecording} onStop={stopRecording} />
|
||||
<HistoryList sendJSON={sendJSON} />
|
||||
</div>
|
||||
<Toast />
|
||||
<Toaster theme="dark" position="bottom-center" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useAppStore } from "../stores/app-store";
|
||||
|
||||
function formatTime(ts: number): string {
|
||||
@@ -13,14 +14,13 @@ interface HistoryListProps {
|
||||
export function HistoryList({ sendJSON }: HistoryListProps) {
|
||||
const history = useAppStore((s) => s.history);
|
||||
const clearHistory = useAppStore((s) => s.clearHistory);
|
||||
const showToast = useAppStore((s) => s.showToast);
|
||||
|
||||
const handleItemClick = useCallback(
|
||||
(text: string) => {
|
||||
sendJSON({ type: "paste", text });
|
||||
showToast("发送粘贴…");
|
||||
toast.info("发送粘贴…");
|
||||
},
|
||||
[sendJSON, showToast],
|
||||
[sendJSON],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -39,9 +39,7 @@ export function HistoryList({ sendJSON }: HistoryListProps) {
|
||||
</div>
|
||||
|
||||
{history.length === 0 ? (
|
||||
<p className="py-10 text-center text-fg-dim text-sm">
|
||||
{"暂无记录"}
|
||||
</p>
|
||||
<p className="py-10 text-center text-fg-dim text-sm">{"暂无记录"}</p>
|
||||
) : (
|
||||
<div className="scrollbar-thin flex-1 overflow-y-auto">
|
||||
{history.map((item, i) => (
|
||||
|
||||
@@ -98,9 +98,7 @@ export function MicButton({ onStart, onStop }: MicButtonProps) {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<p className="font-medium text-fg-dim text-sm">
|
||||
{"按住说话"}
|
||||
</p>
|
||||
<p className="font-medium text-fg-dim text-sm">{"按住说话"}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useAppStore } from "../stores/app-store";
|
||||
|
||||
export function Toast() {
|
||||
const toast = useAppStore((s) => s.toast);
|
||||
const dismissToast = useAppStore((s) => s.dismissToast);
|
||||
const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
if (!toast) return;
|
||||
if (timerRef.current) clearTimeout(timerRef.current);
|
||||
timerRef.current = setTimeout(dismissToast, 2000);
|
||||
return () => {
|
||||
if (timerRef.current) clearTimeout(timerRef.current);
|
||||
};
|
||||
}, [toast, dismissToast]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`pointer-events-none fixed bottom-[calc(80px+env(safe-area-inset-bottom,0px))] left-1/2 z-[999] rounded-3xl border border-edge bg-[rgba(28,28,37,0.85)] px-[22px] py-2.5 font-medium text-[13px] text-fg shadow-[0_8px_32px_rgba(0,0,0,0.4)] backdrop-blur-[16px] transition-all duration-300 ease-[cubic-bezier(0.16,1,0.3,1)] ${
|
||||
toast
|
||||
? "-translate-x-1/2 translate-y-0 opacity-100"
|
||||
: "-translate-x-1/2 translate-y-2 opacity-0"
|
||||
}`}
|
||||
>
|
||||
{toast}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useRef } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { resampleTo16kInt16 } from "../lib/resample";
|
||||
import { useAppStore } from "../stores/app-store";
|
||||
import audioProcessorUrl from "../workers/audio-processor.ts?worker&url";
|
||||
@@ -89,9 +90,7 @@ export function useRecorder({ sendJSON, sendBinary }: UseRecorderOptions) {
|
||||
} catch (err) {
|
||||
useAppStore.getState().setPendingStart(false);
|
||||
abortRef.current = null;
|
||||
useAppStore
|
||||
.getState()
|
||||
.showToast(`麦克风错误: ${(err as Error).message}`);
|
||||
toast.error(`麦克风错误: ${(err as Error).message}`);
|
||||
}
|
||||
}, [initAudio]);
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { WebSocket as ReconnectingWebSocket } from "partysocket";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useAppStore } from "../stores/app-store";
|
||||
|
||||
function getWsUrl(): string {
|
||||
@@ -9,13 +11,8 @@ function getWsUrl(): string {
|
||||
return `${proto}//${location.host}/ws${q}`;
|
||||
}
|
||||
|
||||
const WS_RECONNECT_BASE = 1000;
|
||||
const WS_RECONNECT_MAX = 16000;
|
||||
|
||||
export function useWebSocket() {
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const reconnectDelayRef = useRef(WS_RECONNECT_BASE);
|
||||
const wsRef = useRef<ReconnectingWebSocket | null>(null);
|
||||
|
||||
const sendJSON = useCallback((obj: Record<string, unknown>) => {
|
||||
const ws = wsRef.current;
|
||||
@@ -27,78 +24,59 @@ export function useWebSocket() {
|
||||
const sendBinary = useCallback((data: Int16Array) => {
|
||||
const ws = wsRef.current;
|
||||
if (ws?.readyState === WebSocket.OPEN) {
|
||||
ws.send(data.buffer);
|
||||
ws.send(data.buffer as ArrayBuffer);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
function connect() {
|
||||
if (wsRef.current) return;
|
||||
useAppStore.getState().setConnectionStatus("connecting");
|
||||
|
||||
useAppStore.getState().setConnectionStatus("connecting");
|
||||
const ws = new WebSocket(getWsUrl());
|
||||
ws.binaryType = "arraybuffer";
|
||||
const ws = new ReconnectingWebSocket(getWsUrl(), undefined, {
|
||||
minReconnectionDelay: 1000,
|
||||
maxReconnectionDelay: 16000,
|
||||
});
|
||||
ws.binaryType = "arraybuffer";
|
||||
|
||||
ws.onopen = () => {
|
||||
reconnectDelayRef.current = WS_RECONNECT_BASE;
|
||||
useAppStore.getState().setConnectionStatus("connected");
|
||||
};
|
||||
ws.onopen = () => {
|
||||
useAppStore.getState().setConnectionStatus("connected");
|
||||
};
|
||||
|
||||
ws.onmessage = (e: MessageEvent) => {
|
||||
if (typeof e.data !== "string") return;
|
||||
try {
|
||||
const msg = JSON.parse(e.data);
|
||||
const store = useAppStore.getState();
|
||||
switch (msg.type) {
|
||||
case "partial":
|
||||
store.setPreview(msg.text || "", false);
|
||||
break;
|
||||
case "final":
|
||||
store.setPreview(msg.text || "", true);
|
||||
if (msg.text) store.addHistory(msg.text);
|
||||
break;
|
||||
case "pasted":
|
||||
store.showToast("✅ 已粘贴");
|
||||
break;
|
||||
case "error":
|
||||
store.showToast(`❌ ${msg.message || "错误"}`);
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed messages
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
wsRef.current = null;
|
||||
ws.onmessage = (e: MessageEvent) => {
|
||||
if (typeof e.data !== "string") return;
|
||||
try {
|
||||
const msg = JSON.parse(e.data);
|
||||
const store = useAppStore.getState();
|
||||
store.setConnectionStatus("disconnected");
|
||||
if (store.recording) store.setRecording(false);
|
||||
if (store.pendingStart) store.setPendingStart(false);
|
||||
scheduleReconnect();
|
||||
};
|
||||
switch (msg.type) {
|
||||
case "partial":
|
||||
store.setPreview(msg.text || "", false);
|
||||
break;
|
||||
case "final":
|
||||
store.setPreview(msg.text || "", true);
|
||||
if (msg.text) store.addHistory(msg.text);
|
||||
break;
|
||||
case "pasted":
|
||||
toast.success("已粘贴");
|
||||
break;
|
||||
case "error":
|
||||
toast.error(msg.message || "错误");
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed messages
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = () => ws.close();
|
||||
wsRef.current = ws;
|
||||
}
|
||||
ws.onclose = () => {
|
||||
const store = useAppStore.getState();
|
||||
store.setConnectionStatus("disconnected");
|
||||
if (store.recording) store.setRecording(false);
|
||||
if (store.pendingStart) store.setPendingStart(false);
|
||||
};
|
||||
|
||||
function scheduleReconnect() {
|
||||
if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
|
||||
reconnectTimerRef.current = setTimeout(
|
||||
connect,
|
||||
reconnectDelayRef.current,
|
||||
);
|
||||
reconnectDelayRef.current = Math.min(
|
||||
reconnectDelayRef.current * 2,
|
||||
WS_RECONNECT_MAX,
|
||||
);
|
||||
}
|
||||
|
||||
connect();
|
||||
wsRef.current = ws;
|
||||
|
||||
return () => {
|
||||
if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
|
||||
wsRef.current?.close();
|
||||
ws.close();
|
||||
wsRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
|
||||
export interface HistoryItem {
|
||||
text: string;
|
||||
ts: number;
|
||||
}
|
||||
|
||||
const HISTORY_KEY = "voicepaste_history";
|
||||
const HISTORY_MAX = 50;
|
||||
|
||||
type ConnectionStatus = "connected" | "disconnected" | "connecting";
|
||||
@@ -21,8 +21,6 @@ interface AppState {
|
||||
previewActive: boolean;
|
||||
// History
|
||||
history: HistoryItem[];
|
||||
// Toast
|
||||
toast: string | null;
|
||||
|
||||
// Actions
|
||||
setConnectionStatus: (status: ConnectionStatus) => void;
|
||||
@@ -32,55 +30,43 @@ interface AppState {
|
||||
clearPreview: () => void;
|
||||
addHistory: (text: string) => void;
|
||||
clearHistory: () => void;
|
||||
showToast: (message: string) => void;
|
||||
dismissToast: () => void;
|
||||
}
|
||||
|
||||
function loadHistoryFromStorage(): HistoryItem[] {
|
||||
try {
|
||||
return JSON.parse(
|
||||
localStorage.getItem(HISTORY_KEY) || "[]",
|
||||
) as HistoryItem[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
export const useAppStore = create<AppState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
connectionStatus: "connecting",
|
||||
recording: false,
|
||||
pendingStart: false,
|
||||
previewText: "",
|
||||
previewActive: false,
|
||||
history: [],
|
||||
|
||||
export const useAppStore = create<AppState>((set, get) => ({
|
||||
connectionStatus: "connecting",
|
||||
recording: false,
|
||||
pendingStart: false,
|
||||
previewText: "",
|
||||
previewActive: false,
|
||||
history: loadHistoryFromStorage(),
|
||||
toast: null,
|
||||
setConnectionStatus: (connectionStatus) => set({ connectionStatus }),
|
||||
setRecording: (recording) => set({ recording }),
|
||||
setPendingStart: (pendingStart) => set({ pendingStart }),
|
||||
|
||||
setConnectionStatus: (connectionStatus) => set({ connectionStatus }),
|
||||
setRecording: (recording) => set({ recording }),
|
||||
setPendingStart: (pendingStart) => set({ pendingStart }),
|
||||
setPreview: (text, isFinal) =>
|
||||
set({
|
||||
previewText: text,
|
||||
previewActive: !isFinal && text.length > 0,
|
||||
}),
|
||||
|
||||
setPreview: (text, isFinal) =>
|
||||
set({
|
||||
previewText: text,
|
||||
previewActive: !isFinal && text.length > 0,
|
||||
clearPreview: () => set({ previewText: "", previewActive: false }),
|
||||
|
||||
addHistory: (text) => {
|
||||
const items = [{ text, ts: Date.now() }, ...get().history].slice(
|
||||
0,
|
||||
HISTORY_MAX,
|
||||
);
|
||||
set({ history: items });
|
||||
},
|
||||
|
||||
clearHistory: () => set({ history: [] }),
|
||||
}),
|
||||
|
||||
clearPreview: () => set({ previewText: "", previewActive: false }),
|
||||
|
||||
addHistory: (text) => {
|
||||
const items = [{ text, ts: Date.now() }, ...get().history].slice(
|
||||
0,
|
||||
HISTORY_MAX,
|
||||
);
|
||||
localStorage.setItem(HISTORY_KEY, JSON.stringify(items));
|
||||
set({ history: items });
|
||||
},
|
||||
|
||||
clearHistory: () => {
|
||||
localStorage.removeItem(HISTORY_KEY);
|
||||
set({ history: [] });
|
||||
},
|
||||
|
||||
showToast: (message) => set({ toast: message }),
|
||||
dismissToast: () => set({ toast: null }),
|
||||
}));
|
||||
{
|
||||
name: "voicepaste_history",
|
||||
partialize: (state) => ({ history: state.history }),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user