feat: 类型定义 + Context/Reducer + 编码 Hook

This commit is contained in:
2026-06-17 00:20:32 +08:00
parent a952ebcb5f
commit 3186502edb
3 changed files with 159 additions and 0 deletions
+54
View File
@@ -0,0 +1,54 @@
import { useCallback, useRef } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { useQrState } from '../store/qrContext';
interface QrResponse {
svg: string;
version: number;
size: number;
mask: number;
}
export function useQrEncode() {
const { state, dispatch } = useQrState();
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const modeRef = useRef(state.mode);
modeRef.current = state.mode;
const encode = useCallback((text: string) => {
if (!text.trim()) {
dispatch({ type: 'SET_PREVIEW', payload: null });
return;
}
dispatch({ type: 'SET_LOADING', payload: true });
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = setTimeout(async () => {
try {
const result = await invoke<QrResponse>('encode_qr', {
text,
level: state.config.level,
margin: state.config.margin,
});
dispatch({ type: 'SET_PREVIEW', payload: result });
// 保存到历史
dispatch({
type: 'ADD_HISTORY',
payload: {
id: Date.now().toString(),
mode: modeRef.current,
content: text,
timestamp: Date.now(),
},
});
} catch (e) {
console.error('QR 编码失败:', e);
dispatch({ type: 'SET_PREVIEW', payload: null });
}
}, 200);
}, [state.config.level, state.config.margin, dispatch]);
return { encode };
}