Refactor and enhance form recognition, mapping, and UI components (#18)
* docs: 添加组件文档注释和类型导入 refactor: 统一使用 SnackbarOptions 类型 style: 优化导入语句顺序和格式 * refactor: 简化假数据生成器中的faker导入和使用 Co-authored-by: Copilot <copilot@github.com> * feat(form-recognizer): 增强表单识别功能并优化UI交互 - 新增字段类型偏好设置功能,支持按域名保存字段类型 - 重构FieldList组件,改进字段选择和类型修改体验 - 添加字段定位闪烁功能,便于在页面上快速找到对应字段 - 优化表单填充逻辑,支持单个字段覆盖默认填充模式 - 移除独立的侧边栏页面,统一使用主页面组件 - 改进useStorageState钩子,增加加载状态管理和防抖处理 * refactor: 移除未使用的组件文件 * refactor(页面头部): 提取通用 PageHeader 组件并替换各页面头部实现 重构各页面头部为统一的 PageHeader 组件,提高代码复用性和维护性 * style(组件): 调整自动刷新开关和存储选项网格的样式 优化自动刷新开关的文本内边距,重构存储选项网格的布局结构,调整间距和边框样式 * style(ui): 调整时间戳页面和结果视图的样式 - 为时区选择器添加圆角 - 优化结果视图的布局和对齐方式 - 调整结果项的内边距和文本样式 * ci(workflow): 移除Firefox测试以简化CI流程 仅保留Chrome浏览器的构建步骤,减少CI运行时间和资源消耗 * refactor(qrcode): 重构二维码解析功能并提取为独立模块 * style(页面样式): 统一页面头部图标颜色并优化表单样式 更新各页面头部组件的图标颜色配置,移除冗余的表单标签属性,优化输入框样式和按钮悬停效果 * feat(formMapping): 添加表单映射功能 - 创建 FormMappingPage 页面组件 - 实现表单扫描器 scanner.ts - 实现高亮器 highlighter.ts - 更新路由配置 routes.ts - 更新内容脚本 content.ts - 更新类型定义 storage.d.ts - 添加 formMappingPageStyles 样式配置 * feat(表单映射): 添加配置导出功能及状态提示 添加配置导出为JSON文件的功能,包含导出按钮和错误处理。新增Snackbar组件用于显示导出成功和错误状态。优化页面布局结构,将状态提示移至全局容器外。 * feat(表单填充): 新增智能表单填充功能 添加智能表单填充功能,包括: 1. 新增表单填充页面和路由配置 2. 实现模糊匹配引擎和智能注入引擎 3. 添加Mock数据生成器和视觉反馈渲染器 4. 扩展消息接口支持填充操作 * ci: 精简触发CI的工作流分支 移除对develop分支及其变体的触发,仅保留main分支的触发 * test: 更新路由测试以匹配新增的路由数量 * test: 将测试文件中的描述和断言翻译为中文 * test(PageHeader): 添加组件测试用例验证渲染逻辑和样式 * refactor(theme): 重构主题样式并优化仪表盘卡片组件 将页面样式配置集中管理,移除各页面中硬编码的背景色 新增 DashboardCard 组件封装通用卡片逻辑 添加 dashboardCards 配置文件统一管理卡片数据 * refactor(Button): 统一按钮样式并移除重复样式定义 将按钮样式统一封装到 Button 组件中,移除各页面重复的样式定义 更新组件文档说明,提供更清晰的用法示例 * docs: 更新 README 文件中的目录结构说明 添加新组件和配置文件的说明,保持文档与代码同步 * refactor: 优化代码类型声明和UI布局 修复类型声明从any改为never以提高类型安全性 调整TimestampPage页面布局间距 移除DashboardPage中不必要的实时时钟状态 更新ESLint配置以使用推荐配置 添加选项页面打开的错误处理 * refactor(消息通信): 使用 @webext-core/messaging 重构消息处理逻辑 将原有的 chrome.runtime.onMessage 和 chrome.tabs.sendMessage 替换为类型安全的 @webext-core/messaging 实现 添加 ProtocolMap 类型定义确保消息类型安全 更新相关页面和后台脚本使用新的消息通信方式 * fix: 修复依赖项缺失导致的潜在问题 修复 useStorageState 中缺少 defaultValue 依赖的问题 重构 RouterProvider 的初始化逻辑,使用 useCallback 优化性能 * refactor: 重构表单识别和消息处理逻辑 将表单映射UI逻辑提取到独立文件 将消息处理器提取到独立文件 将表单识别页面逻辑提取到自定义hook 优化代码结构和可维护性 * feat(侧边栏): 添加侧边栏状态变化通知功能 - 在消息类型中新增侧边栏状态变化枚举和字段 - 侧边栏打开和关闭时发送状态通知 - 替换轮询检查方式为消息监听机制 * refactor: 优化高亮组件渲染逻辑并添加防抖处理 重构高亮组件渲染逻辑,使用 requestAnimationFrame 进行节流优化 在 useStorageCleaner 中添加防抖处理以避免频繁加载 * refactor: 统一组件导出方式为默认导出 * refactor: 重构样式系统并迁移至 MUI 主题 删除冗余的 CSS 文件,统一使用 MUI 主题管理样式 新增 useActiveTabDomain 和 useSidePanelState 自定义 Hook 优化各入口点的主题集成和布局处理 * docs: 更新项目文档以反映新增功能和技术栈细节 更新 AGENTS.md 文档,详细描述新增的功能模块(存储管理、URL 管理、二维码生成、表单工具套件等)和更新的技术栈信息 * feat: 添加错误边界组件以捕获子组件错误 在 popup、sidepanel 和 options 入口点添加 ErrorBoundary 组件,用于捕获并处理子组件中的 JavaScript 错误。当错误发生时,显示友好的错误界面并提供刷新功能。 * refactor(ui): 使用全局 snackbar 替换本地通知组件 重构表单页面中的通知系统,移除本地 Snackbar 和 Alert 组件,改用全局 GlobalSnackbar 组件统一管理通知 标准化主题配置中的 CSS 属性命名,移除带前缀的样式属性 * refactor(snackbar): 重构全局消息提示为 SnackbarProvider 组件 将原本分散在各页面的 GlobalSnackbar 组件重构为集中管理的 SnackbarProvider,通过 Context 提供统一的消息提示功能。主要变更包括: 1. 创建新的 SnackbarProvider 组件作为全局消息提示容器 2. 提供 useSnackbar hook 供子组件调用 3. 移除各页面中独立的 GlobalSnackbar 实例 4. 在 App 根组件中统一集成 SnackbarProvider 5. 优化消息提示样式和交互行为 * refactor(Snackbar): 重构消息提示组件并优化样式 重构 Snackbar 组件,将状态管理逻辑提取到 GlobalSnackbar 中复用 优化消息提示样式,调整阴影效果和最小尺寸 统一各页面使用 Snackbar 的方式,移除冗余配置 * refactor: 重构路由和功能配置系统 - 将路由配置和仪表盘卡片配置合并为统一的 features 配置 - 重构 RouterProvider 增加数据校验和本地快照功能 - 优化表单字段识别和填充逻辑,提取公共方法 - 更新相关组件和文档以适配新的配置系统 - 删除废弃的 dashboardCards 和 routes 配置文件
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Chrome 标签页相关工具函数
|
||||
*/
|
||||
|
||||
/**
|
||||
* 获取当前活动的标签页
|
||||
*/
|
||||
export async function getActiveTab(): Promise<chrome.tabs.Tab | null> {
|
||||
try {
|
||||
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||
return tab || null;
|
||||
} catch (error) {
|
||||
console.error('获取活动标签页失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前活动的标签页域名
|
||||
*/
|
||||
export async function getActiveTabDomain(): Promise<string> {
|
||||
const tab = await getActiveTab();
|
||||
if (tab?.url) {
|
||||
try {
|
||||
const url = new URL(tab.url);
|
||||
return url.hostname;
|
||||
} catch (e) {
|
||||
console.error('解析域名失败:', e);
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保内容脚本已注入
|
||||
*/
|
||||
export async function ensureContentScriptInjected(): Promise<boolean> {
|
||||
try {
|
||||
const tab = await getActiveTab();
|
||||
if (!tab?.id) return false;
|
||||
|
||||
// 尝试发送一个简单的探测消息
|
||||
try {
|
||||
// 这里可以根据实际情况发送一个简单的 Ping 消息
|
||||
// 目前暂时保留原有注入逻辑,由调用方决定
|
||||
return true;
|
||||
} catch (e) {
|
||||
// 如果报错,说明没注入,执行注入
|
||||
console.log('内容脚本未注入,尝试注入...');
|
||||
console.error('注入内容脚本失败:', e);
|
||||
await chrome.scripting.executeScript({
|
||||
target: { tabId: tab.id },
|
||||
files: ['/content-scripts/content.js'],
|
||||
});
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('注入内容脚本失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
import type { SnackbarOptions } from '@/components/GlobalSnackbar';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import { useSnackbarState } from '@/components/GlobalSnackbar';
|
||||
|
||||
/**
|
||||
* 复制文本到剪贴板
|
||||
@@ -27,7 +27,7 @@ export const copyToClipboard = async (
|
||||
* @returns 包含复制函数和 snackbarProps 的对象
|
||||
*/
|
||||
export const useClipboard = () => {
|
||||
const { snackbarProps, showMessage } = useSnackbar({ autoHideDuration: 1500 });
|
||||
const { snackbarProps, showMessage } = useSnackbarState({ autoHideDuration: 1500 });
|
||||
|
||||
const copy = async (text: string): Promise<boolean> => {
|
||||
return copyToClipboard(text, showMessage);
|
||||
|
||||
+125
-312
@@ -207,151 +207,75 @@ export enum FillMode {
|
||||
INVALID = 'invalid',
|
||||
}
|
||||
|
||||
/**
|
||||
* 关键词与字段类型映射
|
||||
*/
|
||||
const FIELD_TYPE_KEYWORDS: Record<
|
||||
Exclude<
|
||||
FieldType,
|
||||
| FieldType.UNKNOWN
|
||||
| FieldType.TEXT
|
||||
| FieldType.TEXTarea
|
||||
| FieldType.SELECT
|
||||
| FieldType.RADIO
|
||||
| FieldType.CHECKBOX
|
||||
>,
|
||||
string[]
|
||||
> = {
|
||||
[FieldType.EMAIL]: ['email', 'mail', '邮箱'],
|
||||
[FieldType.PHONE]: ['phone', 'tel', 'mobile', '手机', '电话'],
|
||||
[FieldType.NAME]: ['name', 'user', 'username', '姓名', '名字'],
|
||||
[FieldType.ID_CARD]: ['id', 'card', 'identity', '身份证'],
|
||||
[FieldType.PASSWORD]: ['password', 'pass', '密码'],
|
||||
[FieldType.NUMBER]: ['number', 'num', '数字'],
|
||||
[FieldType.DATE]: ['date', 'time', '日期', '时间'],
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据文本识别字段类型
|
||||
*/
|
||||
function detectTypeFromText(text: string): FieldType | null {
|
||||
const lowerText = text.toLowerCase();
|
||||
for (const [type, keywords] of Object.entries(FIELD_TYPE_KEYWORDS)) {
|
||||
if (keywords.some((kw) => lowerText.includes(kw))) {
|
||||
return type as FieldType;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 识别表单字段类型
|
||||
*/
|
||||
export function recognizeFieldType(
|
||||
element: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,
|
||||
): FieldType {
|
||||
// 基于 type 属性识别
|
||||
// 1. 基于 HTML5 type 属性识别
|
||||
if (element instanceof HTMLInputElement) {
|
||||
switch (element.type) {
|
||||
case 'email':
|
||||
return FieldType.EMAIL;
|
||||
case 'tel':
|
||||
return FieldType.PHONE;
|
||||
case 'number':
|
||||
return FieldType.NUMBER;
|
||||
case 'date':
|
||||
return FieldType.DATE;
|
||||
case 'password':
|
||||
return FieldType.PASSWORD;
|
||||
case 'radio':
|
||||
return FieldType.RADIO;
|
||||
case 'checkbox':
|
||||
return FieldType.CHECKBOX;
|
||||
case 'text':
|
||||
break;
|
||||
}
|
||||
const typeMap: Record<string, FieldType> = {
|
||||
email: FieldType.EMAIL,
|
||||
tel: FieldType.PHONE,
|
||||
number: FieldType.NUMBER,
|
||||
date: FieldType.DATE,
|
||||
password: FieldType.PASSWORD,
|
||||
radio: FieldType.RADIO,
|
||||
checkbox: FieldType.CHECKBOX,
|
||||
};
|
||||
if (typeMap[element.type]) return typeMap[element.type];
|
||||
}
|
||||
|
||||
// 基于 name 或 id 识别
|
||||
const name = (element.name || element.id || '').toLowerCase();
|
||||
if (name.includes('email') || name.includes('mail')) {
|
||||
return FieldType.EMAIL;
|
||||
}
|
||||
if (name.includes('phone') || name.includes('tel') || name.includes('mobile')) {
|
||||
return FieldType.PHONE;
|
||||
}
|
||||
if (name.includes('name') || name.includes('user') || name.includes('username')) {
|
||||
return FieldType.NAME;
|
||||
}
|
||||
if (name.includes('id') || name.includes('card') || name.includes('identity')) {
|
||||
return FieldType.ID_CARD;
|
||||
}
|
||||
if (name.includes('password') || name.includes('pass')) {
|
||||
return FieldType.PASSWORD;
|
||||
}
|
||||
if (name.includes('number') || name.includes('num')) {
|
||||
return FieldType.NUMBER;
|
||||
}
|
||||
if (name.includes('date') || name.includes('time')) {
|
||||
return FieldType.DATE;
|
||||
}
|
||||
// 2. 基于 name/id, placeholder, label 文本识别
|
||||
const name = element.name || element.id || '';
|
||||
const placeholder = 'placeholder' in element ? element.placeholder || '' : '';
|
||||
const label = getFieldLabel(element) || '';
|
||||
|
||||
// 基于 placeholder 识别
|
||||
if ('placeholder' in element) {
|
||||
const placeholder = (element.placeholder || '').toLowerCase();
|
||||
if (placeholder.includes('email') || placeholder.includes('mail')) {
|
||||
return FieldType.EMAIL;
|
||||
}
|
||||
if (
|
||||
placeholder.includes('phone') ||
|
||||
placeholder.includes('tel') ||
|
||||
placeholder.includes('mobile')
|
||||
) {
|
||||
return FieldType.PHONE;
|
||||
}
|
||||
if (
|
||||
placeholder.includes('name') ||
|
||||
placeholder.includes('user') ||
|
||||
placeholder.includes('username')
|
||||
) {
|
||||
return FieldType.NAME;
|
||||
}
|
||||
if (
|
||||
placeholder.includes('id') ||
|
||||
placeholder.includes('card') ||
|
||||
placeholder.includes('identity')
|
||||
) {
|
||||
return FieldType.ID_CARD;
|
||||
}
|
||||
if (placeholder.includes('password') || placeholder.includes('pass')) {
|
||||
return FieldType.PASSWORD;
|
||||
}
|
||||
if (placeholder.includes('number') || placeholder.includes('num')) {
|
||||
return FieldType.NUMBER;
|
||||
}
|
||||
if (placeholder.includes('date') || placeholder.includes('time')) {
|
||||
return FieldType.DATE;
|
||||
}
|
||||
}
|
||||
const detected =
|
||||
detectTypeFromText(name) || detectTypeFromText(placeholder) || detectTypeFromText(label);
|
||||
if (detected) return detected;
|
||||
|
||||
// 基于标签识别
|
||||
const label = getFieldLabel(element);
|
||||
if (label) {
|
||||
const labelText = label.toLowerCase();
|
||||
if (labelText.includes('邮箱') || labelText.includes('email') || labelText.includes('mail')) {
|
||||
return FieldType.EMAIL;
|
||||
}
|
||||
if (
|
||||
labelText.includes('手机') ||
|
||||
labelText.includes('电话') ||
|
||||
labelText.includes('tel') ||
|
||||
labelText.includes('mobile')
|
||||
) {
|
||||
return FieldType.PHONE;
|
||||
}
|
||||
if (
|
||||
labelText.includes('姓名') ||
|
||||
labelText.includes('名字') ||
|
||||
labelText.includes('name') ||
|
||||
labelText.includes('user') ||
|
||||
labelText.includes('username')
|
||||
) {
|
||||
return FieldType.NAME;
|
||||
}
|
||||
if (
|
||||
labelText.includes('身份证') ||
|
||||
labelText.includes('id') ||
|
||||
labelText.includes('card') ||
|
||||
labelText.includes('identity')
|
||||
) {
|
||||
return FieldType.ID_CARD;
|
||||
}
|
||||
if (labelText.includes('密码') || labelText.includes('pass')) {
|
||||
return FieldType.PASSWORD;
|
||||
}
|
||||
if (labelText.includes('数字') || labelText.includes('number') || labelText.includes('num')) {
|
||||
return FieldType.NUMBER;
|
||||
}
|
||||
if (
|
||||
labelText.includes('日期') ||
|
||||
labelText.includes('时间') ||
|
||||
labelText.includes('date') ||
|
||||
labelText.includes('time')
|
||||
) {
|
||||
return FieldType.DATE;
|
||||
}
|
||||
}
|
||||
|
||||
// 基于元素类型识别
|
||||
if (element instanceof HTMLTextAreaElement) {
|
||||
return FieldType.TEXTarea;
|
||||
}
|
||||
if (element instanceof HTMLSelectElement) {
|
||||
return FieldType.SELECT;
|
||||
}
|
||||
// 3. 基于元素标签识别
|
||||
if (element instanceof HTMLTextAreaElement) return FieldType.TEXTarea;
|
||||
if (element instanceof HTMLSelectElement) return FieldType.SELECT;
|
||||
|
||||
return FieldType.TEXT;
|
||||
}
|
||||
@@ -381,6 +305,49 @@ function getFieldLabel(element: HTMLElement): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量遍历并过滤表单元素
|
||||
*/
|
||||
function forEachFormElement(
|
||||
container: ParentNode,
|
||||
callback: (element: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement) => void,
|
||||
options: { includeHidden?: boolean } = {},
|
||||
): void {
|
||||
const inputs = container.querySelectorAll('input, textarea, select');
|
||||
inputs.forEach((el) => {
|
||||
if (
|
||||
(el instanceof HTMLInputElement ||
|
||||
el instanceof HTMLTextAreaElement ||
|
||||
el instanceof HTMLSelectElement) &&
|
||||
isElementValidForFill(el)
|
||||
) {
|
||||
if (!options.includeHidden && el instanceof HTMLInputElement && el.type === 'hidden') {
|
||||
return;
|
||||
}
|
||||
callback(el);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空单个字段
|
||||
*/
|
||||
export function clearField(
|
||||
element: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,
|
||||
): void {
|
||||
if (
|
||||
element instanceof HTMLInputElement &&
|
||||
(element.type === 'checkbox' || element.type === 'radio')
|
||||
) {
|
||||
element.checked = false;
|
||||
} else if (element instanceof HTMLSelectElement) {
|
||||
element.selectedIndex = 0;
|
||||
} else {
|
||||
setInputValue(element, '');
|
||||
}
|
||||
triggerEvents(element);
|
||||
}
|
||||
|
||||
/**
|
||||
* 填充表单字段
|
||||
*/
|
||||
@@ -389,74 +356,8 @@ export function fillField(
|
||||
mode: FillMode,
|
||||
): void {
|
||||
const fieldType = recognizeFieldType(element);
|
||||
let value: string | number | boolean = '';
|
||||
|
||||
switch (fieldType) {
|
||||
case FieldType.NAME:
|
||||
value =
|
||||
Math.random() > 0.5
|
||||
? DummyDataGenerator.generateChineseName()
|
||||
: DummyDataGenerator.generateEnglishName();
|
||||
break;
|
||||
case FieldType.EMAIL:
|
||||
value =
|
||||
mode === FillMode.VALID
|
||||
? DummyDataGenerator.generateValidEmail()
|
||||
: DummyDataGenerator.generateInvalidEmail();
|
||||
break;
|
||||
case FieldType.PHONE:
|
||||
value = DummyDataGenerator.generatePhoneNumber();
|
||||
break;
|
||||
case FieldType.NUMBER:
|
||||
value =
|
||||
mode === FillMode.VALID
|
||||
? DummyDataGenerator.generateNumber()
|
||||
: DummyDataGenerator.generateNegativeNumber();
|
||||
break;
|
||||
case FieldType.DATE:
|
||||
value = DummyDataGenerator.generateDate();
|
||||
break;
|
||||
case FieldType.TEXTarea:
|
||||
value =
|
||||
mode === FillMode.VALID
|
||||
? DummyDataGenerator.generateLongText()
|
||||
: DummyDataGenerator.generateBoundaryText();
|
||||
break;
|
||||
case FieldType.PASSWORD:
|
||||
value = 'password123';
|
||||
break;
|
||||
case FieldType.ID_CARD:
|
||||
value = DummyDataGenerator.generateIdCard();
|
||||
break;
|
||||
case FieldType.TEXT:
|
||||
default:
|
||||
value =
|
||||
mode === FillMode.VALID
|
||||
? DummyDataGenerator.generateShortText()
|
||||
: DummyDataGenerator.generateBoundaryText();
|
||||
break;
|
||||
}
|
||||
|
||||
// 填充值
|
||||
if (element instanceof HTMLInputElement) {
|
||||
if (element.type === 'checkbox' || element.type === 'radio') {
|
||||
element.checked = Math.random() > 0.5;
|
||||
} else {
|
||||
element.value = String(value);
|
||||
}
|
||||
} else if (element instanceof HTMLTextAreaElement) {
|
||||
element.value = String(value);
|
||||
} else if (element instanceof HTMLSelectElement) {
|
||||
// 随机选择一个非禁用的选项
|
||||
const options = Array.from(element.options).filter((option) => !option.disabled);
|
||||
if (options.length > 0) {
|
||||
const randomIndex = Math.floor(Math.random() * options.length);
|
||||
element.selectedIndex = randomIndex;
|
||||
}
|
||||
}
|
||||
|
||||
// 触发事件,确保前端框架能够监听到变化
|
||||
triggerEvents(element);
|
||||
const value = generateValueByFieldType(fieldType, mode);
|
||||
fillFieldWithInjector(element, value);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -512,16 +413,12 @@ function isElementVisible(element: HTMLElement): boolean {
|
||||
|
||||
// 3. 检查计算样式 (兜底检查 css 隐藏手段)
|
||||
const style = window.getComputedStyle(element);
|
||||
if (
|
||||
return !(
|
||||
style.display === 'none' ||
|
||||
style.visibility === 'hidden' ||
|
||||
style.opacity === '0' ||
|
||||
style.visibility === 'collapse'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -605,11 +502,7 @@ function isElementValidForFill(element: HTMLElement): boolean {
|
||||
}
|
||||
|
||||
// 5. Z轴穿透验证(最后一步,最耗时,放最后)
|
||||
if (!isElementNotObscured(element)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
return isElementNotObscured(element);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -667,7 +560,7 @@ export function scanFormFields(): ScanResult {
|
||||
const name = input.name || input.id || '';
|
||||
|
||||
fields.push({
|
||||
id: `field-${Math.random().toString(36).substr(2, 9)}`,
|
||||
id: `field-${Math.random().toString(36).substring(2, 9)}`,
|
||||
element: input,
|
||||
fieldType,
|
||||
label,
|
||||
@@ -888,29 +781,15 @@ export function unhighlightAllFields(fields: FormFieldInfo[]): void {
|
||||
* 填充所有表单字段
|
||||
*/
|
||||
export function fillAllFields(mode: FillMode, includeHidden: boolean = false): void {
|
||||
const inputs = document.querySelectorAll('input, textarea, select');
|
||||
|
||||
inputs.forEach((element) => {
|
||||
if (
|
||||
element instanceof HTMLInputElement ||
|
||||
element instanceof HTMLTextAreaElement ||
|
||||
element instanceof HTMLSelectElement
|
||||
) {
|
||||
if (!isElementValidForFill(element)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!includeHidden) {
|
||||
if (element instanceof HTMLInputElement && element.type === 'hidden') {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const fieldType = recognizeFieldType(element);
|
||||
forEachFormElement(
|
||||
document,
|
||||
(el) => {
|
||||
const fieldType = recognizeFieldType(el);
|
||||
const value = generateValueByFieldType(fieldType, mode);
|
||||
fillFieldWithInjector(element, value);
|
||||
}
|
||||
});
|
||||
fillFieldWithInjector(el, value);
|
||||
},
|
||||
{ includeHidden },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -921,29 +800,15 @@ export function fillFieldsInContainer(
|
||||
container: HTMLElement,
|
||||
includeHidden: boolean = false,
|
||||
): void {
|
||||
const inputs = container.querySelectorAll('input, textarea, select');
|
||||
|
||||
inputs.forEach((element) => {
|
||||
if (
|
||||
element instanceof HTMLInputElement ||
|
||||
element instanceof HTMLTextAreaElement ||
|
||||
element instanceof HTMLSelectElement
|
||||
) {
|
||||
if (!isElementValidForFill(element)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!includeHidden) {
|
||||
if (element instanceof HTMLInputElement && element.type === 'hidden') {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const fieldType = recognizeFieldType(element);
|
||||
forEachFormElement(
|
||||
container,
|
||||
(el) => {
|
||||
const fieldType = recognizeFieldType(el);
|
||||
const value = generateValueByFieldType(fieldType, mode);
|
||||
fillFieldWithInjector(element, value);
|
||||
}
|
||||
});
|
||||
fillFieldWithInjector(el, value);
|
||||
},
|
||||
{ includeHidden },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -962,64 +827,12 @@ export function fillFieldsInActiveModal(mode: FillMode, includeHidden: boolean =
|
||||
* 清空所有表单字段
|
||||
*/
|
||||
export function clearAllFields(): void {
|
||||
const inputs = document.querySelectorAll('input, textarea, select');
|
||||
|
||||
inputs.forEach((element) => {
|
||||
if (
|
||||
element instanceof HTMLInputElement ||
|
||||
element instanceof HTMLTextAreaElement ||
|
||||
element instanceof HTMLSelectElement
|
||||
) {
|
||||
if (!isElementValidForFill(element)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (element instanceof HTMLInputElement) {
|
||||
if (element.type === 'checkbox' || element.type === 'radio') {
|
||||
element.checked = false;
|
||||
} else {
|
||||
setInputValue(element, '');
|
||||
}
|
||||
} else if (element instanceof HTMLTextAreaElement) {
|
||||
setInputValue(element, '');
|
||||
} else if (element instanceof HTMLSelectElement) {
|
||||
element.selectedIndex = 0;
|
||||
}
|
||||
|
||||
triggerEvents(element);
|
||||
}
|
||||
});
|
||||
forEachFormElement(document, (el) => clearField(el));
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空指定容器内的表单字段
|
||||
*/
|
||||
export function clearFieldsInContainer(container: HTMLElement): void {
|
||||
const inputs = container.querySelectorAll('input, textarea, select');
|
||||
|
||||
inputs.forEach((element) => {
|
||||
if (
|
||||
element instanceof HTMLInputElement ||
|
||||
element instanceof HTMLTextAreaElement ||
|
||||
element instanceof HTMLSelectElement
|
||||
) {
|
||||
if (!isElementValidForFill(element)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (element instanceof HTMLInputElement) {
|
||||
if (element.type === 'checkbox' || element.type === 'radio') {
|
||||
element.checked = false;
|
||||
} else {
|
||||
setInputValue(element, '');
|
||||
}
|
||||
} else if (element instanceof HTMLTextAreaElement) {
|
||||
setInputValue(element, '');
|
||||
} else if (element instanceof HTMLSelectElement) {
|
||||
element.selectedIndex = 0;
|
||||
}
|
||||
|
||||
triggerEvents(element);
|
||||
}
|
||||
});
|
||||
forEachFormElement(container, (el) => clearField(el));
|
||||
}
|
||||
|
||||
@@ -7,9 +7,12 @@ export class VisualHighlighter {
|
||||
private canvas: HTMLCanvasElement | null = null;
|
||||
private ctx: CanvasRenderingContext2D | null = null;
|
||||
private isVisible = false;
|
||||
private currentEntries: FormMapEntry[] = [];
|
||||
private animationFrameId: number | null = null;
|
||||
|
||||
constructor() {
|
||||
this.handleResize = this.handleResize.bind(this);
|
||||
this.render = this.render.bind(this);
|
||||
}
|
||||
|
||||
public init() {
|
||||
@@ -37,29 +40,47 @@ export class VisualHighlighter {
|
||||
if (!this.canvas) this.init();
|
||||
this.isVisible = true;
|
||||
this.canvas!.style.display = 'block';
|
||||
this.handleResize();
|
||||
this.requestUpdate();
|
||||
}
|
||||
|
||||
public hide() {
|
||||
this.isVisible = false;
|
||||
if (this.canvas) this.canvas.style.display = 'none';
|
||||
if (this.animationFrameId !== null) {
|
||||
cancelAnimationFrame(this.animationFrameId);
|
||||
this.animationFrameId = null;
|
||||
}
|
||||
}
|
||||
|
||||
private handleResize() {
|
||||
if (!this.isVisible || !this.canvas || !this.ctx) return;
|
||||
this.canvas.width = window.innerWidth;
|
||||
this.canvas.height = window.innerHeight;
|
||||
this.draw();
|
||||
this.requestUpdate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 核心渲染循环
|
||||
* 核心更新请求,使用 requestAnimationFrame 节流
|
||||
*/
|
||||
public draw(entries: FormMapEntry[] = []) {
|
||||
if (!this.ctx || !this.isVisible) return;
|
||||
this.ctx.clearRect(0, 0, this.canvas!.width, this.canvas!.height);
|
||||
private requestUpdate() {
|
||||
if (this.animationFrameId !== null) return;
|
||||
this.animationFrameId = requestAnimationFrame(this.render);
|
||||
}
|
||||
|
||||
entries.forEach((entry) => {
|
||||
/**
|
||||
* 核心渲染逻辑
|
||||
*/
|
||||
private render() {
|
||||
this.animationFrameId = null;
|
||||
if (!this.ctx || !this.isVisible || !this.canvas) return;
|
||||
|
||||
// 适配分辨率
|
||||
if (this.canvas.width !== window.innerWidth || this.canvas.height !== window.innerHeight) {
|
||||
this.canvas.width = window.innerWidth;
|
||||
this.canvas.height = window.innerHeight;
|
||||
}
|
||||
|
||||
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||
|
||||
this.currentEntries.forEach((entry) => {
|
||||
const el = document.querySelector<HTMLElement>(entry.fingerprint.selector);
|
||||
if (!el) return;
|
||||
|
||||
@@ -103,6 +124,16 @@ export class VisualHighlighter {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 公共 draw 方法,仅更新数据并触发渲染请求
|
||||
*/
|
||||
public draw(entries: FormMapEntry[] = []) {
|
||||
this.currentEntries = entries;
|
||||
if (this.isVisible) {
|
||||
this.requestUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 开启拾取模式:拦截点击事件
|
||||
*/
|
||||
|
||||
@@ -205,6 +205,7 @@ export class SmartInjectionEngine {
|
||||
* 注入数据到目标元素
|
||||
* @param element - 目标 DOM 元素
|
||||
* @param entry - 表单映射条目
|
||||
* @param mockValue - mock数据
|
||||
* @returns 注入结果
|
||||
*/
|
||||
public static inject(element: HTMLElement, entry: FormMapEntry, mockValue: string): InjectResult {
|
||||
@@ -274,8 +275,7 @@ export class SmartInjectionEngine {
|
||||
// 随机选择
|
||||
const options = Array.from(element.options).filter((opt) => !opt.disabled);
|
||||
if (options.length > 0) {
|
||||
const randomIndex = Math.floor(Math.random() * options.length);
|
||||
element.selectedIndex = randomIndex;
|
||||
element.selectedIndex = Math.floor(Math.random() * options.length);
|
||||
}
|
||||
} else {
|
||||
// 使用固定值
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { SmartDetector } from './scanner';
|
||||
import { highlighter } from './highlighter';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
import { FormMapEntry } from '@/types/storage';
|
||||
|
||||
/**
|
||||
* 更新表单映射辅助 UI
|
||||
*/
|
||||
export async function updateMappingUI() {
|
||||
const entries = ((await storageUtil.get('active_form_map')) as FormMapEntry[]) || [];
|
||||
const isPicking = ((await storageUtil.get('app/formMapping/isPicking')) as boolean) || false;
|
||||
|
||||
if (entries.length > 0 || isPicking) {
|
||||
highlighter.show();
|
||||
highlighter.draw(entries);
|
||||
|
||||
if (isPicking) {
|
||||
highlighter.enablePicker(async (el) => {
|
||||
const fingerprint = SmartDetector.generateFingerprint(el);
|
||||
const label = SmartDetector.extractSemanticLabel(el);
|
||||
|
||||
const newEntry: FormMapEntry = {
|
||||
id: Math.random().toString(36).substring(2, 9),
|
||||
label_display: label,
|
||||
fingerprint,
|
||||
action_logic: { type: 'text', strategy: 'fixed', value: '' },
|
||||
ui_state: { is_selected: true },
|
||||
};
|
||||
|
||||
const currentMap = ((await storageUtil.get('active_form_map')) as FormMapEntry[]) || [];
|
||||
await storageUtil.set('active_form_map', [...currentMap, newEntry]);
|
||||
await storageUtil.set('app/formMapping/isPicking', false);
|
||||
});
|
||||
} else {
|
||||
highlighter.disablePicker();
|
||||
}
|
||||
} else {
|
||||
highlighter.hide();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化表单映射助手
|
||||
*/
|
||||
export function initFormMappingHelper() {
|
||||
chrome.storage.onChanged.addListener((changes, area) => {
|
||||
if (area === 'local' && (changes['active_form_map'] || changes['app/formMapping/isPicking'])) {
|
||||
updateMappingUI().catch(console.error);
|
||||
}
|
||||
});
|
||||
|
||||
// 初始加载
|
||||
updateMappingUI().catch(console.error);
|
||||
}
|
||||
+63
-21
@@ -1,9 +1,10 @@
|
||||
import { FormFieldInfo, FillMode } from './dummyDataGenerator';
|
||||
import { defineExtensionMessaging } from '@webext-core/messaging';
|
||||
|
||||
/**
|
||||
* 字段数据接口(用于消息传递)
|
||||
*/
|
||||
interface MessageFieldData extends Omit<FormFieldInfo, 'element'> {
|
||||
export interface MessageFieldData extends Omit<FormFieldInfo, 'element'> {
|
||||
useInvalidData?: boolean;
|
||||
}
|
||||
|
||||
@@ -29,10 +30,16 @@ export enum MessageAction {
|
||||
|
||||
// 字段定位/闪烁
|
||||
FLASH_FIELD = 'flashField',
|
||||
|
||||
// 智能表单注入
|
||||
FORM_INJECT = 'FORM_INJECT',
|
||||
|
||||
// 侧边栏状态变化
|
||||
SIDE_PANEL_STATE_CHANGED = 'sidePanelStateChanged',
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息载荷接口
|
||||
* 消息载荷接口 (保留兼容性)
|
||||
*/
|
||||
export interface MessagePayload {
|
||||
action: MessageAction | string;
|
||||
@@ -44,11 +51,22 @@ export interface MessagePayload {
|
||||
fieldId?: string;
|
||||
fieldIds?: string[];
|
||||
data?: unknown;
|
||||
isOpen?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息响应接口
|
||||
*/
|
||||
export interface FormInjectItem {
|
||||
entry: import('@/types/storage').FormMapEntry;
|
||||
mockValue: string;
|
||||
}
|
||||
|
||||
export interface FormInjectResult {
|
||||
id: string;
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
export interface MessageResponse {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
@@ -56,36 +74,60 @@ export interface MessageResponse {
|
||||
totalCount?: number;
|
||||
validCount?: number;
|
||||
hasModal?: boolean;
|
||||
results?: unknown[];
|
||||
results?: FormInjectResult[];
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息到内容脚本
|
||||
* 协议映射定义(用于类型安全的消息通信)
|
||||
*/
|
||||
export async function sendMessageToContent(
|
||||
action: MessageAction,
|
||||
payload?: Omit<MessagePayload, 'action'>,
|
||||
): Promise<MessageResponse> {
|
||||
export interface ProtocolMap {
|
||||
// 基础消息格式,用于逐步迁移
|
||||
[MessageAction.RELOAD_TAB](data: { tabId: number; delay?: number }): MessageResponse;
|
||||
[MessageAction.SCAN_FORM_FIELDS](): MessageResponse;
|
||||
[MessageAction.FILL_VALID_DATA](data: { includeHidden?: boolean }): MessageResponse;
|
||||
[MessageAction.FILL_INVALID_DATA](data: { includeHidden?: boolean }): MessageResponse;
|
||||
[MessageAction.FILL_SELECTED_FIELDS](data: {
|
||||
fields: MessageFieldData[];
|
||||
mode?: FillMode;
|
||||
includeHidden?: boolean;
|
||||
}): MessageResponse;
|
||||
[MessageAction.CLEAR_ALL_FIELDS](): MessageResponse;
|
||||
[MessageAction.HIGHLIGHT_FIELD](data: { fieldId: string }): MessageResponse;
|
||||
[MessageAction.UNHIGHLIGHT_FIELD](data: { fieldId: string }): MessageResponse;
|
||||
[MessageAction.HIGHLIGHT_ALL_FIELDS](data: { fieldIds: string[] }): MessageResponse;
|
||||
[MessageAction.UNHIGHLIGHT_ALL_FIELDS](): MessageResponse;
|
||||
[MessageAction.FLASH_FIELD](data: { fieldId: string }): MessageResponse;
|
||||
[MessageAction.FORM_INJECT](data: { data: FormInjectItem[] }): MessageResponse;
|
||||
[MessageAction.SIDE_PANEL_STATE_CHANGED](data: { isOpen: boolean }): void;
|
||||
}
|
||||
|
||||
export const { sendMessage, onMessage } = defineExtensionMessaging<ProtocolMap>();
|
||||
|
||||
/**
|
||||
* 发送消息到内容脚本 (旧版包装器,内部使用新机制)
|
||||
* @deprecated 建议直接使用 sendMessage
|
||||
*/
|
||||
type ProtocolData<K extends keyof ProtocolMap> = Parameters<ProtocolMap[K]>[0];
|
||||
type ProtocolReturn<K extends keyof ProtocolMap> = ReturnType<ProtocolMap[K]>;
|
||||
|
||||
export async function sendMessageToContent<K extends keyof ProtocolMap>(
|
||||
action: K,
|
||||
...args: ProtocolData<K> extends undefined ? [] : [data: ProtocolData<K>]
|
||||
): Promise<ProtocolReturn<K>> {
|
||||
try {
|
||||
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||
if (!tab?.id) {
|
||||
return { success: false, message: '无法获取当前标签页' };
|
||||
return { success: false, message: '无法获取当前标签页' } as ProtocolReturn<K>;
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
chrome.tabs.sendMessage(tab.id!, { action, ...payload }, (response) => {
|
||||
if (chrome.runtime.lastError) {
|
||||
console.error('消息发送失败:', chrome.runtime.lastError);
|
||||
resolve({ success: false, message: '无法连接到页面,请确保页面已加载' });
|
||||
} else {
|
||||
resolve((response as MessageResponse) || { success: false, message: '未收到响应' });
|
||||
}
|
||||
});
|
||||
});
|
||||
const data = args.length > 0 ? args[0] : undefined;
|
||||
return await (
|
||||
sendMessage as (type: K, data: ProtocolData<K>, arg?: number) => Promise<ProtocolReturn<K>>
|
||||
)(action, data as ProtocolData<K>, tab.id);
|
||||
} catch (error) {
|
||||
console.error('获取标签页失败:', error);
|
||||
return { success: false, message: '无法获取当前标签页' };
|
||||
console.error('发送消息失败:', error);
|
||||
return { success: false, message: '发送消息失败' } as ProtocolReturn<K>;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@ export const useStorageState = <K extends keyof StorageSchema>(
|
||||
}
|
||||
};
|
||||
|
||||
loadState();
|
||||
}, [key]); // eslint-disable-line react-hooks/exhaustive-deps -- defaultValue intentionally excluded to prevent infinite loops
|
||||
loadState().catch(console.error);
|
||||
}, [defaultValue, key]);
|
||||
|
||||
// Save to storage when value changes (after initial load)
|
||||
useEffect(() => {
|
||||
@@ -43,7 +43,7 @@ export const useStorageState = <K extends keyof StorageSchema>(
|
||||
}
|
||||
};
|
||||
|
||||
saveState();
|
||||
saveState().catch(console.error);
|
||||
}, [value, isInitialized, key]);
|
||||
|
||||
return [value, setValue, isInitialized] as const;
|
||||
|
||||
@@ -23,7 +23,7 @@ export const useUrlPreferences = () => {
|
||||
setIsLoaded(true);
|
||||
}
|
||||
};
|
||||
loadPreferences();
|
||||
loadPreferences().catch(console.error);
|
||||
}, []);
|
||||
|
||||
const savePreferences = useCallback(() => {
|
||||
|
||||
Reference in New Issue
Block a user