Files
testing-tool/src/utils/useContextMenuData.ts
T
雨霖铃 9990d86270 refactor: 删除高优先级死代码
删除未使用的代码以提高代码质量和可维护性:

删除的文件:
- src/pages/Dashboard/ToolCard.tsx:未被使用的组件
- src/utils/useDebounce.ts:未被使用的 hook
- src/components/__tests__/ToolCard.test.tsx:对应组件的测试文件

删除的导出函数:
- chromeTabs: getActiveTab, getActiveTabDomain, ensureContentScriptInjected
- clipboard: copyImageToClipboard
- storageCleaner: isEmptyResult
- chromeI18n: preloadNamespaces
- useContextMenuData: clearContextMenuData

更新了对应的测试文件以保持一致性

总计删除 525 行代码,所有 473 个测试通过
2026-06-06 01:00:10 +08:00

93 lines
2.9 KiB
TypeScript

import { useEffect } from 'react';
import { storageUtil } from '@/utils/chromeStorage';
import type { ContextMenuPendingData, PageType } from '@/types/storage';
const STORAGE_KEY = 'contextMenu/pendingData' as const;
/** 右键菜单数据过期时间(毫秒) */
export const CONTEXT_MENU_DATA_EXPIRY_MS = 5000;
export interface UseContextMenuDataOptions {
/** 当前页面的功能标识 */
featureKey: PageType;
/** 收到数据时的回调函数 */
onData: (payload: string) => void;
}
/**
* 自定义 Hook:处理右键菜单传递的数据
*
* 使用方式:
* 1. 在页面组件中调用此 Hook
* 2. 传入当前页面的 featureKey 和数据处理回调
* 3. Hook 会自动从 storage 中读取并消费匹配的数据
*/
export function useContextMenuData({ featureKey, onData }: UseContextMenuDataOptions): void {
useEffect(() => {
const checkAndConsumeData = async () => {
try {
const data = await storageUtil.get(STORAGE_KEY, undefined);
if (!data) return;
if (data.featureKey !== featureKey) return;
if (Date.now() - data.timestamp > CONTEXT_MENU_DATA_EXPIRY_MS) {
await storageUtil.remove(STORAGE_KEY);
return;
}
await storageUtil.remove(STORAGE_KEY);
onData(data.payload);
} catch (error) {
console.error('[useContextMenuData] 处理右键菜单数据失败:', error);
}
};
void checkAndConsumeData();
}, [featureKey, onData]);
useEffect(() => {
const handleStorageChange = (changes: { [key: string]: chrome.storage.StorageChange }) => {
if (changes[STORAGE_KEY]) {
const newData = changes[STORAGE_KEY].newValue as ContextMenuPendingData | null;
if (newData && newData.featureKey === featureKey) {
void (async () => {
try {
const data = await storageUtil.get(STORAGE_KEY, undefined);
if (!data) return;
if (data.featureKey !== featureKey) return;
if (Date.now() - data.timestamp > CONTEXT_MENU_DATA_EXPIRY_MS) {
await storageUtil.remove(STORAGE_KEY);
return;
}
await storageUtil.remove(STORAGE_KEY);
onData(data.payload);
} catch (error) {
console.error('[useContextMenuData] 处理右键菜单数据失败:', error);
}
})();
}
}
};
chrome.storage.onChanged.addListener(handleStorageChange);
return () => chrome.storage.onChanged.removeListener(handleStorageChange);
}, [featureKey, onData]);
}
/**
* 保存右键菜单数据到 storage
* 由 RouterProvider 或入口组件调用
*/
export async function saveContextMenuData(
data: Omit<ContextMenuPendingData, 'timestamp'>,
): Promise<void> {
const pendingData: ContextMenuPendingData = {
...data,
timestamp: Date.now(),
};
await storageUtil.set(STORAGE_KEY, pendingData);
}