Develop fill form (#11)
* feat(formRecognizer): 添加表单识别功能及相关组件 添加表单识别功能,包括以下内容: 1. 在路由配置中添加表单识别页面 2. 实现表单识别页面和侧边栏面板 3. 添加表单数据生成工具类 4. 实现与内容脚本的通信机制 5. 添加faker-js依赖用于生成测试数据 6. 支持不同入口点(popup/sidepanel)的组件渲染 * refactor(消息通信): 重构消息通信机制并集中管理消息协议 将分散的消息协议和通信逻辑集中到 utils/messages.ts 中 移除旧的 messages.tsx 文件并更新相关引用 添加消息动作枚举和类型定义,提高类型安全性 优化内容脚本注入失败时的处理逻辑 * feat(QR码): 添加粘贴图片功能并优化上传组件 添加全局粘贴事件监听,支持从剪贴板直接粘贴二维码图片进行解析。重构上传组件为独立组件QrCodeUploader,包含拖拽上传、预览、进度显示和错误处理功能。优化页面样式和用户体验。 - 在QrCodePage添加粘贴事件监听 - 创建QrCodeUploader组件整合上传功能 - 更新测试用例格式 - 调整多个页面的背景色样式 * feat(表单识别): 新增表单识别页面功能与模板管理 - 添加表单识别页面样式配置 - 实现表单字段扫描与展示功能 - 新增数据模板管理工具类 - 添加数据验证工具类 - 扩展表单识别页面功能,包括操作历史记录 - 支持模板的导入导出功能 - 优化表单填充操作的用户体验 * feat(消息系统): 添加标签页刷新功能 在消息系统中新增 RELOAD_TAB 动作类型和 tabId 字段,用于处理标签页刷新请求 修改 StorageCleanerPage 使用后台脚本发送刷新请求,确保弹窗关闭后仍能执行 在 background.ts 中添加标签页刷新处理逻辑,包括错误处理和响应返回 * refactor(theme): 重构主题颜色和样式配置 - 更新主题颜色以满足 WCAG AA 可访问性标准 - 提取全局样式配置到统一变量 - 使用语义化颜色变量替换硬编码值 - 为输入框样式创建统一配置 * feat: add URL entry management components and QR code generation feature - Introduced `UrlEntryItem` and `UrlEntryList` components for displaying and managing URL entries. - Added `UrlToQrCodeSection` component for generating QR codes from URLs with download and copy functionality. - Implemented `AutoRefreshToggle`, `CleaningResult`, `DomainHeader`, `ErrorDisplay`, `OptionItem`, and `StorageOptionsGrid` components for enhanced user interface in storage cleaning. - Created custom hooks `useStorageCleaner` and `useStorageState` for managing storage-related states and preferences. - Added utility hook `useUrlPreferences` for handling URL entry preferences. * feat: 新增时间戳转换器和相关组件,优化时间戳页面功能 * Refactor message handling and storage cleaning logic * feat: 添加 GitHub Actions CI/CD 工作流,支持自动化构建与发布
This commit is contained in:
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* 数据模板管理工具
|
||||
* 用于创建、编辑、保存和管理自定义测试数据模板
|
||||
*/
|
||||
|
||||
import { FieldType } from './dummyDataGenerator';
|
||||
|
||||
/**
|
||||
* 模板字段接口
|
||||
*/
|
||||
export interface TemplateField {
|
||||
id: string;
|
||||
name: string;
|
||||
label: string;
|
||||
fieldType: FieldType;
|
||||
defaultValue: string;
|
||||
rules: TemplateRule[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 模板规则接口
|
||||
*/
|
||||
export interface TemplateRule {
|
||||
type: 'required' | 'pattern' | 'minLength' | 'maxLength' | 'min' | 'max' | 'custom';
|
||||
value: string | number;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据模板接口
|
||||
*/
|
||||
export interface DataTemplate {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
fields: TemplateField[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 模板存储键名
|
||||
*/
|
||||
const TEMPLATE_STORAGE_KEY = 'dataTemplates';
|
||||
|
||||
/**
|
||||
* 数据模板管理类
|
||||
*/
|
||||
export class DataTemplateManager {
|
||||
/**
|
||||
* 获取所有模板
|
||||
*/
|
||||
static async getAllTemplates(): Promise<DataTemplate[]> {
|
||||
try {
|
||||
const stored = await chrome.storage.local.get(TEMPLATE_STORAGE_KEY);
|
||||
return (stored[TEMPLATE_STORAGE_KEY] as DataTemplate[]) || [];
|
||||
} catch (error) {
|
||||
console.error('获取模板失败:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存模板
|
||||
*/
|
||||
static async saveTemplate(template: DataTemplate): Promise<boolean> {
|
||||
try {
|
||||
const templates = await this.getAllTemplates();
|
||||
const existingIndex = templates.findIndex((t) => t.id === template.id);
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
templates[existingIndex] = {
|
||||
...template,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
} else {
|
||||
templates.push({
|
||||
...template,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
await chrome.storage.local.set({ [TEMPLATE_STORAGE_KEY]: templates });
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('保存模板失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除模板
|
||||
*/
|
||||
static async deleteTemplate(templateId: string): Promise<boolean> {
|
||||
try {
|
||||
const templates = await this.getAllTemplates();
|
||||
const filtered = templates.filter((t) => t.id !== templateId);
|
||||
await chrome.storage.local.set({ [TEMPLATE_STORAGE_KEY]: filtered });
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('删除模板失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出模板
|
||||
*/
|
||||
static exportTemplates(templates: DataTemplate[]): string {
|
||||
return JSON.stringify(templates, null, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入模板
|
||||
*/
|
||||
static async importTemplates(jsonString: string): Promise<boolean> {
|
||||
try {
|
||||
const importedTemplates = JSON.parse(jsonString) as DataTemplate[];
|
||||
if (!Array.isArray(importedTemplates)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const existingTemplates = await this.getAllTemplates();
|
||||
const mergedTemplates = [...existingTemplates];
|
||||
|
||||
for (const template of importedTemplates) {
|
||||
const existingIndex = mergedTemplates.findIndex((t) => t.id === template.id);
|
||||
if (existingIndex >= 0) {
|
||||
mergedTemplates[existingIndex] = template;
|
||||
} else {
|
||||
mergedTemplates.push(template);
|
||||
}
|
||||
}
|
||||
|
||||
await chrome.storage.local.set({ [TEMPLATE_STORAGE_KEY]: mergedTemplates });
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('导入模板失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成唯一ID
|
||||
*/
|
||||
static generateId(): string {
|
||||
return `template_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建空模板
|
||||
*/
|
||||
static createEmptyTemplate(name: string, description: string = ''): DataTemplate {
|
||||
return {
|
||||
id: this.generateId(),
|
||||
name,
|
||||
description,
|
||||
fields: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* 数据验证工具
|
||||
* 用于在数据填充前进行格式验证
|
||||
*/
|
||||
|
||||
import { FieldType } from './dummyDataGenerator';
|
||||
|
||||
/**
|
||||
* 验证结果接口
|
||||
*/
|
||||
export interface ValidationResult {
|
||||
isValid: boolean;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据验证工具类
|
||||
*/
|
||||
export class DataValidator {
|
||||
/**
|
||||
* 验证邮箱格式
|
||||
*/
|
||||
private static validateEmail(value: string): boolean {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证手机号格式(中国大陆)
|
||||
*/
|
||||
private static validatePhone(value: string): boolean {
|
||||
const phoneRegex = /^1[3-9]\d{9}$/;
|
||||
return phoneRegex.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证身份证号格式(中国大陆)
|
||||
*/
|
||||
private static validateIdCard(value: string): boolean {
|
||||
const idCardRegex =
|
||||
/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
|
||||
return idCardRegex.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证日期格式
|
||||
*/
|
||||
private static validateDate(value: string): boolean {
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(value)) return false;
|
||||
const date = new Date(value);
|
||||
return !isNaN(date.getTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证数字格式
|
||||
*/
|
||||
private static validateNumber(value: string): boolean {
|
||||
return !isNaN(Number(value)) && value.trim() !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证字段值
|
||||
*/
|
||||
static validateField(fieldType: FieldType, value: string): ValidationResult {
|
||||
const errors: string[] = [];
|
||||
|
||||
switch (fieldType) {
|
||||
case FieldType.EMAIL:
|
||||
if (!this.validateEmail(value)) {
|
||||
errors.push('邮箱格式不正确');
|
||||
}
|
||||
break;
|
||||
case FieldType.PHONE:
|
||||
if (!this.validatePhone(value)) {
|
||||
errors.push('手机号格式不正确,应为11位数字');
|
||||
}
|
||||
break;
|
||||
case FieldType.ID_CARD:
|
||||
if (!this.validateIdCard(value)) {
|
||||
errors.push('身份证号格式不正确');
|
||||
}
|
||||
break;
|
||||
case FieldType.DATE:
|
||||
if (!this.validateDate(value)) {
|
||||
errors.push('日期格式不正确,应为YYYY-MM-DD');
|
||||
}
|
||||
break;
|
||||
case FieldType.NUMBER:
|
||||
if (!this.validateNumber(value)) {
|
||||
errors.push('数字格式不正确');
|
||||
}
|
||||
break;
|
||||
case FieldType.NAME:
|
||||
if (value.length < 2 || value.length > 50) {
|
||||
errors.push('姓名长度应在2-50个字符之间');
|
||||
}
|
||||
break;
|
||||
case FieldType.PASSWORD:
|
||||
if (value.length < 6) {
|
||||
errors.push('密码长度不能少于6个字符');
|
||||
}
|
||||
break;
|
||||
case FieldType.TEXT:
|
||||
case FieldType.TEXTarea:
|
||||
if (value.length > 10000) {
|
||||
errors.push('文本长度不能超过10000个字符');
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// 未知类型不做验证
|
||||
break;
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: errors.length === 0,
|
||||
errors,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量验证字段
|
||||
*/
|
||||
static validateFields(fields: Array<{ fieldType: FieldType; value: string }>): ValidationResult {
|
||||
const allErrors: string[] = [];
|
||||
|
||||
fields.forEach((field, index) => {
|
||||
const result = this.validateField(field.fieldType, field.value);
|
||||
if (!result.isValid) {
|
||||
allErrors.push(`字段 ${index + 1}: ${result.errors.join(', ')}`);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
isValid: allErrors.length === 0,
|
||||
errors: allErrors,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字段类型的验证规则描述
|
||||
*/
|
||||
static getValidationRules(fieldType: FieldType): string[] {
|
||||
switch (fieldType) {
|
||||
case FieldType.EMAIL:
|
||||
return ['格式: user@domain.com'];
|
||||
case FieldType.PHONE:
|
||||
return ['格式: 11位中国大陆手机号', '以1开头,第二位为3-9'];
|
||||
case FieldType.ID_CARD:
|
||||
return ['格式: 18位身份证号', '前6位为地区码', '中间8位为生日', '最后1位为校验码'];
|
||||
case FieldType.DATE:
|
||||
return ['格式: YYYY-MM-DD', '例如: 2024-01-01'];
|
||||
case FieldType.NUMBER:
|
||||
return ['格式: 整数或浮点数'];
|
||||
case FieldType.NAME:
|
||||
return ['长度: 2-50个字符'];
|
||||
case FieldType.PASSWORD:
|
||||
return ['长度: 至少6个字符'];
|
||||
case FieldType.TEXT:
|
||||
case FieldType.TEXTarea:
|
||||
return ['长度: 不超过10000个字符'];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,7 @@ export class DummyDataGenerator {
|
||||
* 生成有效邮箱
|
||||
*/
|
||||
static generateValidEmail(): string {
|
||||
return faker.internet.email();
|
||||
return fakerZH_CN.internet.email();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,14 +77,14 @@ export class DummyDataGenerator {
|
||||
* 生成短文本
|
||||
*/
|
||||
static generateShortText(): string {
|
||||
return faker.lorem.sentence({ min: 3, max: 6 });
|
||||
return fakerZH_CN.lorem.sentence({ min: 3, max: 6 });
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成长文本
|
||||
*/
|
||||
static generateLongText(): string {
|
||||
return faker.lorem.paragraphs(5);
|
||||
return fakerZH_CN.lorem.paragraphs(5);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,42 +106,42 @@ export class DummyDataGenerator {
|
||||
* 生成随机数字
|
||||
*/
|
||||
static generateNumber(): number {
|
||||
return faker.number.int(10000);
|
||||
return fakerZH_CN.number.int(10000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机浮点数
|
||||
*/
|
||||
static generateFloat(): number {
|
||||
return faker.number.float({ max: 10000 });
|
||||
return fakerZH_CN.number.float({ max: 10000 });
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机负数
|
||||
*/
|
||||
static generateNegativeNumber(): number {
|
||||
return -faker.number.int(10000);
|
||||
return -fakerZH_CN.number.int(10000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机日期
|
||||
*/
|
||||
static generateDate(): string {
|
||||
return faker.date.recent({ days: 365 }).toISOString().split('T')[0];
|
||||
return fakerZH_CN.date.recent({ days: 365 }).toISOString().split('T')[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成过去的日期
|
||||
*/
|
||||
static generatePastDate(): string {
|
||||
return faker.date.past({ years: 1 }).toISOString().split('T')[0];
|
||||
return fakerZH_CN.date.past({ years: 1 }).toISOString().split('T')[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成未来的日期
|
||||
*/
|
||||
static generateFutureDate(): string {
|
||||
return faker.date.future({ years: 1 }).toISOString().split('T')[0];
|
||||
return fakerZH_CN.date.future({ years: 1 }).toISOString().split('T')[0];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+6
-1
@@ -4,6 +4,9 @@ import { FormFieldInfo, FillMode } from './dummyDataGenerator';
|
||||
* 消息动作类型
|
||||
*/
|
||||
export enum MessageAction {
|
||||
// 标签页操作
|
||||
RELOAD_TAB = 'reloadTab',
|
||||
|
||||
// 表单相关操作
|
||||
SCAN_FORM_FIELDS = 'scanFormFields',
|
||||
FILL_VALID_DATA = 'fillValidData',
|
||||
@@ -22,7 +25,9 @@ export enum MessageAction {
|
||||
* 消息载荷接口
|
||||
*/
|
||||
export interface MessagePayload {
|
||||
action: MessageAction;
|
||||
action: MessageAction | string;
|
||||
tabId?: number;
|
||||
delay?: number;
|
||||
fields?: Omit<FormFieldInfo, 'element'>[];
|
||||
mode?: FillMode;
|
||||
includeHidden?: boolean;
|
||||
|
||||
+54
-30
@@ -11,26 +11,26 @@ const RESTRICTED_PROTOCOLS = [
|
||||
] as const;
|
||||
|
||||
export async function getCurrentTab() {
|
||||
// First, try the active tab in the last focused window (works for standard popups and side panels)
|
||||
const [lastFocusedTab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
|
||||
// For popup pages, we need to get the active tab from the browser window that triggered the popup.
|
||||
// We should ONLY care about the currently active tab in the last focused window.
|
||||
// If it's a restricted URL, we return it anyway and let the caller handle the error display.
|
||||
|
||||
// If the tab is valid and NOT an extension page/restricted URL, use it
|
||||
if (lastFocusedTab && !isRestrictedUrl(lastFocusedTab.url)) {
|
||||
return lastFocusedTab;
|
||||
}
|
||||
|
||||
// Fallback: If we're in a standalone extension window (which is focused),
|
||||
// find the active tab in the most recently focused 'normal' browser window.
|
||||
const [normalTab] = await chrome.tabs.query({
|
||||
const [tab] = await chrome.tabs.query({
|
||||
active: true,
|
||||
windowType: 'normal',
|
||||
lastFocusedWindow: true,
|
||||
});
|
||||
if (normalTab) return normalTab;
|
||||
|
||||
// Final fallback: any active normal tab (if multiple windows exist, it returns all active tabs)
|
||||
const normalTabs = await chrome.tabs.query({ active: true, windowType: 'normal' });
|
||||
return normalTabs[0];
|
||||
if (tab) {
|
||||
return tab;
|
||||
}
|
||||
|
||||
// Fallback for cases where lastFocusedWindow might not work as expected (e.g. certain sidepanel scenarios)
|
||||
const [fallbackTab] = await chrome.tabs.query({
|
||||
active: true,
|
||||
currentWindow: true,
|
||||
});
|
||||
|
||||
return fallbackTab;
|
||||
}
|
||||
|
||||
export function isRestrictedUrl(url?: string): boolean {
|
||||
@@ -42,7 +42,11 @@ export async function getCookieSize(url: string): Promise<number> {
|
||||
try {
|
||||
const cookies = await chrome.cookies.getAll({ url });
|
||||
// 估算:名称 + 值 + 域名 + 路径 的长度
|
||||
return cookies.reduce((acc, c) => acc + c.name.length + c.value.length + (c.domain?.length || 0) + (c.path?.length || 0), 0);
|
||||
return cookies.reduce(
|
||||
(acc, c) =>
|
||||
acc + c.name.length + c.value.length + (c.domain?.length || 0) + (c.path?.length || 0),
|
||||
0,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Failed to get cookie size:', error);
|
||||
return 0;
|
||||
@@ -74,7 +78,10 @@ export async function getSessionStorageSize(tabId: number): Promise<number> {
|
||||
target: { tabId },
|
||||
func: () => {
|
||||
try {
|
||||
return Object.entries(sessionStorage).reduce((acc, [k, v]) => acc + k.length + v.length, 0);
|
||||
return Object.entries(sessionStorage).reduce(
|
||||
(acc, [k, v]) => acc + k.length + v.length,
|
||||
0,
|
||||
);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
@@ -172,8 +179,10 @@ export async function clearCookies(url: string): Promise<StorageCleanResult> {
|
||||
try {
|
||||
const cookies = await chrome.cookies.getAll({ url });
|
||||
for (const cookie of cookies) {
|
||||
const protocol = cookie.secure ? 'https:' : 'http:';
|
||||
const cookieUrl = `${protocol}//${cookie.domain}${cookie.path}`;
|
||||
await chrome.cookies.remove({
|
||||
url,
|
||||
url: cookieUrl,
|
||||
name: cookie.name,
|
||||
storeId: cookie.storeId,
|
||||
});
|
||||
@@ -233,15 +242,32 @@ export async function injectClearIndexedDB(tabId: number): Promise<StorageCleanR
|
||||
for (const db of databases) {
|
||||
if (db.name) {
|
||||
const dbName = db.name as string;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const deleteReq = indexedDB.deleteDatabase(dbName);
|
||||
deleteReq.onblocked = () => {
|
||||
console.warn('IndexedDB delete blocked:', dbName);
|
||||
};
|
||||
deleteReq.onsuccess = () => resolve();
|
||||
deleteReq.onerror = () => reject();
|
||||
});
|
||||
count++;
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const deleteReq = indexedDB.deleteDatabase(dbName);
|
||||
const timeout = setTimeout(() => {
|
||||
console.warn('IndexedDB delete timeout:', dbName);
|
||||
resolve(); // Timeout, move to next
|
||||
}, 5000);
|
||||
|
||||
deleteReq.onblocked = () => {
|
||||
console.warn('IndexedDB delete blocked:', dbName);
|
||||
clearTimeout(timeout);
|
||||
resolve(); // Blocked, move to next
|
||||
};
|
||||
deleteReq.onsuccess = () => {
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
};
|
||||
deleteReq.onerror = () => {
|
||||
clearTimeout(timeout);
|
||||
reject(new Error(`Failed to delete ${dbName}`));
|
||||
};
|
||||
});
|
||||
count++;
|
||||
} catch (e) {
|
||||
console.error('Delete DB error:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { count };
|
||||
@@ -287,9 +313,7 @@ export async function injectClearCacheStorage(tabId: number): Promise<StorageCle
|
||||
}
|
||||
}
|
||||
|
||||
export async function injectUnregisterServiceWorkers(
|
||||
tabId: number,
|
||||
): Promise<StorageCleanResult> {
|
||||
export async function injectUnregisterServiceWorkers(tabId: number): Promise<StorageCleanResult> {
|
||||
try {
|
||||
const [result] = await chrome.scripting.executeScript({
|
||||
target: { tabId },
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
|
||||
export const useStorageState = (
|
||||
key: 'qrCode/urlExpanded' | 'qrCode/qrExpanded',
|
||||
defaultValue: boolean,
|
||||
) => {
|
||||
const [value, setValue] = useState(defaultValue);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const loadState = async () => {
|
||||
try {
|
||||
const savedValue = await storageUtil.get(key, defaultValue);
|
||||
setValue(savedValue ?? defaultValue);
|
||||
} catch (error) {
|
||||
console.error(`加载状态失败 (${key}):`, error);
|
||||
} finally {
|
||||
setIsInitialized(true);
|
||||
}
|
||||
};
|
||||
|
||||
loadState();
|
||||
}, [key, defaultValue]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
const saveState = async () => {
|
||||
try {
|
||||
await storageUtil.set(key, value);
|
||||
} catch (error) {
|
||||
console.error(`保存状态失败 (${key}):`, error);
|
||||
}
|
||||
};
|
||||
|
||||
saveState();
|
||||
}, [value, isInitialized, key]);
|
||||
|
||||
return [value, setValue, isInitialized] as const;
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
import type { OpenUrlPreferences, OpenUrlEntry } from '@/types/storage';
|
||||
|
||||
const DEFAULT_PREFERENCES: OpenUrlPreferences = {
|
||||
entries: [],
|
||||
};
|
||||
|
||||
export const useUrlPreferences = () => {
|
||||
const [entries, setEntries] = useState<OpenUrlEntry[]>(DEFAULT_PREFERENCES.entries);
|
||||
const [isLoaded, setIsLoaded] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const loadPreferences = async () => {
|
||||
try {
|
||||
const saved = await storageUtil.get('openUrl/preferences', DEFAULT_PREFERENCES);
|
||||
if (saved && saved.entries) {
|
||||
setEntries(saved.entries);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load Open Url preferences:', error);
|
||||
} finally {
|
||||
setIsLoaded(true);
|
||||
}
|
||||
};
|
||||
loadPreferences();
|
||||
}, []);
|
||||
|
||||
const savePreferences = useCallback(() => {
|
||||
const preferences: OpenUrlPreferences = { entries };
|
||||
storageUtil.set('openUrl/preferences', preferences).catch((error) => {
|
||||
console.error('Failed to save Open Url preferences:', error);
|
||||
});
|
||||
}, [entries]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoaded) return;
|
||||
const timer = setTimeout(() => {
|
||||
savePreferences();
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, [entries, isLoaded, savePreferences]);
|
||||
|
||||
return { entries, setEntries, isLoaded };
|
||||
};
|
||||
Reference in New Issue
Block a user