Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 187fb1a773 |
@@ -1,5 +1 @@
|
|||||||
# 后台运行类型检查,结果输出到 stderr 但不阻塞提交
|
npx lint-staged
|
||||||
npx tsc --noEmit &
|
|
||||||
|
|
||||||
# 前台运行 lint-staged(自动修复 + 格式化)
|
|
||||||
npx lint-staged
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
# pre-push: 严格检查,阻塞有问题的代码推送到远程
|
|
||||||
# 类型检查(全项目,因为类型错误可能跨文件传播)
|
|
||||||
npx tsc --noEmit
|
|
||||||
|
|
||||||
# ESLint 严格检查(仅检查本次推送的变更文件,不阻塞不相关的旧代码)
|
|
||||||
# 新分支无 upstream 时,回退到与 origin/main 对比
|
|
||||||
MERGE_BASE=$(git merge-base HEAD @{upstream} 2>/dev/null || git merge-base HEAD origin/main 2>/dev/null)
|
|
||||||
if [ -n "$MERGE_BASE" ]; then
|
|
||||||
CHANGED_FILES=$(git diff --name-only --diff-filter=d "$MERGE_BASE" HEAD -- '*.ts' '*.tsx' '*.js' '*.jsx' '*.mjs')
|
|
||||||
if [ -n "$CHANGED_FILES" ]; then
|
|
||||||
echo "$CHANGED_FILES" | xargs npx eslint --max-warnings=0
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
@@ -143,7 +143,6 @@ src/pages/FeatureName/
|
|||||||
- 图标: 使用 `lucide-react` 图标库
|
- 图标: 使用 `lucide-react` 图标库
|
||||||
- 格式: Prettier (`.prettierrc`: 100 字符宽, 单引号, 尾逗号 all, LF 换行)
|
- 格式: Prettier (`.prettierrc`: 100 字符宽, 单引号, 尾逗号 all, LF 换行)
|
||||||
- ESLint 使用 `typescript-eslint` 的 `projectService: true`(无需手动维护 project 路径)
|
- ESLint 使用 `typescript-eslint` 的 `projectService: true`(无需手动维护 project 路径)
|
||||||
- **Git Commit**: 必须使用中文描述,遵循 Conventional Commits 规范(如 `fix(组件名): 描述`、`feat(功能名): 描述`)
|
|
||||||
|
|
||||||
## 关键外部库(非显而易见的)
|
## 关键外部库(非显而易见的)
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,4 @@
|
|||||||
/* global process */
|
|
||||||
|
|
||||||
const isCI = process.env.CI === 'true';
|
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
'*.{ts,tsx,js,jsx,mjs}': [
|
'*.{ts,tsx,js,jsx,mjs}': ['eslint --fix --max-warnings=0 --no-warn-ignored', 'prettier --write'],
|
||||||
'eslint --fix --no-warn-ignored',
|
|
||||||
...(isCI ? ['eslint --max-warnings=0'] : []),
|
|
||||||
'prettier --write',
|
|
||||||
],
|
|
||||||
'*.{json,css,scss,md}': ['prettier --write'],
|
'*.{json,css,scss,md}': ['prettier --write'],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
| `icon/48.png` | 48×48 图标(扩展管理页) |
|
| `icon/48.png` | 48×48 图标(扩展管理页) |
|
||||||
| `icon/96.png` | 96×96 图标 |
|
| `icon/96.png` | 96×96 图标 |
|
||||||
| `icon/128.png` | 128×128 图标(Chrome Web Store) |
|
| `icon/128.png` | 128×128 图标(Chrome Web Store) |
|
||||||
|
| `wxt.svg` | WXT 框架标志 SVG 图标 |
|
||||||
|
|
||||||
## 注意事项
|
## 注意事项
|
||||||
|
|
||||||
|
|||||||
@@ -576,50 +576,6 @@
|
|||||||
"message": "点击更换图片",
|
"message": "点击更换图片",
|
||||||
"description": "Translation key: qrCode_clickToChange"
|
"description": "Translation key: qrCode_clickToChange"
|
||||||
},
|
},
|
||||||
"qrCode_generateButton": {
|
|
||||||
"message": "生成二维码",
|
|
||||||
"description": "Translation key: qrCode_generateButton"
|
|
||||||
},
|
|
||||||
"qrCode_editButton": {
|
|
||||||
"message": "编辑",
|
|
||||||
"description": "Translation key: qrCode_editButton"
|
|
||||||
},
|
|
||||||
"qrCode_textPreviewLabel": {
|
|
||||||
"message": "原始文本",
|
|
||||||
"description": "Translation key: qrCode_textPreviewLabel"
|
|
||||||
},
|
|
||||||
"qrCode_generateFirstHint": {
|
|
||||||
"message": "输入文本后点击「生成二维码」按钮",
|
|
||||||
"description": "Translation key: qrCode_generateFirstHint"
|
|
||||||
},
|
|
||||||
"qrCode_inputRequired": {
|
|
||||||
"message": "请输入内容",
|
|
||||||
"description": "Translation key: qrCode_inputRequired"
|
|
||||||
},
|
|
||||||
"qrCode_generateError": {
|
|
||||||
"message": "生成二维码失败,请重试",
|
|
||||||
"description": "Translation key: qrCode_generateError"
|
|
||||||
},
|
|
||||||
"qrCode_uploadedImage": {
|
|
||||||
"message": "已上传图片",
|
|
||||||
"description": "Translation key: qrCode_uploadedImage"
|
|
||||||
},
|
|
||||||
"qrCode_reuploadButton": {
|
|
||||||
"message": "重新上传",
|
|
||||||
"description": "Translation key: qrCode_reuploadButton"
|
|
||||||
},
|
|
||||||
"qrCode_parsing": {
|
|
||||||
"message": "解析中...",
|
|
||||||
"description": "Translation key: qrCode_parsing"
|
|
||||||
},
|
|
||||||
"qrCode_resultPlaceholder": {
|
|
||||||
"message": "解析结果将显示在此处",
|
|
||||||
"description": "Translation key: qrCode_resultPlaceholder"
|
|
||||||
},
|
|
||||||
"qrCode_imageToQr": {
|
|
||||||
"message": "解析图片二维码",
|
|
||||||
"description": "Translation key: qrCode_imageToQr"
|
|
||||||
},
|
|
||||||
"rightClickRestorer_loading": {
|
"rightClickRestorer_loading": {
|
||||||
"message": "正在加载...",
|
"message": "正在加载...",
|
||||||
"description": "Translation key: rightClickRestorer_loading"
|
"description": "Translation key: rightClickRestorer_loading"
|
||||||
|
Before Width: | Height: | Size: 7.6 KiB After Width: | Height: | Size: 6.0 KiB |
|
Before Width: | Height: | Size: 932 B After Width: | Height: | Size: 669 B |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 5.2 KiB After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 10 KiB |
@@ -53,7 +53,6 @@ export const CopyButton: React.FC<CopyButtonProps> = ({
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={handleCopy}
|
onClick={handleCopy}
|
||||||
title={tooltip ?? t('buttons.copy')}
|
title={tooltip ?? t('buttons.copy')}
|
||||||
aria-label={tooltip ?? t('buttons.copy')}
|
|
||||||
className={cn(
|
className={cn(
|
||||||
buttonVariants({ variant, size }),
|
buttonVariants({ variant, size }),
|
||||||
copied &&
|
copied &&
|
||||||
@@ -63,7 +62,7 @@ export const CopyButton: React.FC<CopyButtonProps> = ({
|
|||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{copied ? (
|
{copied ? (
|
||||||
<Check className="h-[1.2em] w-[1.2em]" />
|
<Check className="h-[1.2em] w-[1.2em] animate-in fade-in zoom-in-75 duration-200" />
|
||||||
) : (
|
) : (
|
||||||
<Copy className="h-[1.2em] w-[1.2em]" />
|
<Copy className="h-[1.2em] w-[1.2em]" />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,194 +0,0 @@
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
||||||
import { act, render, screen, waitFor } from '@testing-library/react';
|
|
||||||
import userEvent from '@testing-library/user-event';
|
|
||||||
|
|
||||||
// unmock the globally-mocked component so we test the real implementation
|
|
||||||
vi.unmock('@/components/CopyButton');
|
|
||||||
|
|
||||||
vi.mock('@/utils/clipboard', () => ({
|
|
||||||
copyTextToClipboard: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('sonner', () => ({
|
|
||||||
toast: {
|
|
||||||
success: vi.fn(),
|
|
||||||
error: vi.fn(),
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
import { CopyButton } from '@/components/CopyButton';
|
|
||||||
import { copyTextToClipboard } from '@/utils/clipboard';
|
|
||||||
import { toast } from 'sonner';
|
|
||||||
|
|
||||||
const mockedCopy = vi.mocked(copyTextToClipboard);
|
|
||||||
const mockedToast = vi.mocked(toast);
|
|
||||||
|
|
||||||
describe('CopyButton', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
|
||||||
vi.clearAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.useRealTimers();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('复制成功时调用 copyTextToClipboard 并传入正确 text', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(true);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
render(<CopyButton text="hello world" />);
|
|
||||||
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
expect(mockedCopy).toHaveBeenCalledWith('hello world');
|
|
||||||
expect(mockedToast.success).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('复制成功后图标切换为 Check,1.5 秒后恢复', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(true);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
render(<CopyButton text="test" />);
|
|
||||||
|
|
||||||
// 点击后复制成功,按钮获得 emerald 样式(说明切到了 Check 状态)
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByRole('button').className).toContain('text-emerald');
|
|
||||||
});
|
|
||||||
|
|
||||||
// 1.5 秒后样式恢复
|
|
||||||
act(() => {
|
|
||||||
vi.advanceTimersByTime(1500);
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByRole('button').className).not.toContain('text-emerald');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('复制空文本时弹出 error toast', async () => {
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
render(<CopyButton text="" />);
|
|
||||||
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
expect(mockedCopy).not.toHaveBeenCalled();
|
|
||||||
expect(mockedToast.error).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('复制失败时弹出 error toast', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(false);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
render(<CopyButton text="something" />);
|
|
||||||
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
expect(mockedCopy).toHaveBeenCalledWith('something');
|
|
||||||
expect(mockedToast.error).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
// ==================== 新增测试 ====================
|
|
||||||
|
|
||||||
it('初始渲染时显示 Copy 图标且无 emerald 样式', () => {
|
|
||||||
render(<CopyButton text="initial" />);
|
|
||||||
|
|
||||||
const button = screen.getByRole('button');
|
|
||||||
expect(button.className).not.toContain('text-emerald');
|
|
||||||
// 通过 aria-label 确认按钮存在,图标由 lucide 渲染为 svg
|
|
||||||
expect(button).toHaveAttribute('aria-label');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('自定义 tooltip 会覆盖默认 title 和 aria-label', () => {
|
|
||||||
render(<CopyButton text="tooltip-test" tooltip="自定义提示" />);
|
|
||||||
|
|
||||||
const button = screen.getByRole('button');
|
|
||||||
expect(button).toHaveAttribute('title', '自定义提示');
|
|
||||||
expect(button).toHaveAttribute('aria-label', '自定义提示');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('className 被正确透传到按钮', () => {
|
|
||||||
render(<CopyButton text="class-test" className="my-custom-class" />);
|
|
||||||
|
|
||||||
const button = screen.getByRole('button');
|
|
||||||
expect(button.className).toContain('my-custom-class');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('点击事件阻止冒泡', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(true);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
const parentClick = vi.fn();
|
|
||||||
|
|
||||||
render(
|
|
||||||
<div onClick={parentClick}>
|
|
||||||
<CopyButton text="stop-propagation" />
|
|
||||||
</div>,
|
|
||||||
);
|
|
||||||
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
expect(mockedCopy).toHaveBeenCalled();
|
|
||||||
expect(parentClick).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('组件卸载时清除定时器,不触发状态更新警告', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(true);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
const { unmount } = render(<CopyButton text="unmount-test" />);
|
|
||||||
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
// 在 1.5 秒超时到期前卸载组件
|
|
||||||
act(() => {
|
|
||||||
vi.advanceTimersByTime(500);
|
|
||||||
});
|
|
||||||
|
|
||||||
// 卸载不应抛出 "Can't perform a React state update on an unmounted component" 警告
|
|
||||||
expect(() => unmount()).not.toThrow();
|
|
||||||
|
|
||||||
// 前进剩余时间,确认没有异常
|
|
||||||
act(() => {
|
|
||||||
vi.advanceTimersByTime(2000);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('快速连续点击不会创建多个重叠定时器', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(true);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
render(<CopyButton text="rapid-click" />);
|
|
||||||
|
|
||||||
const button = screen.getByRole('button');
|
|
||||||
|
|
||||||
// 快速点击 3 次
|
|
||||||
await user.click(button);
|
|
||||||
await user.click(button);
|
|
||||||
await user.click(button);
|
|
||||||
|
|
||||||
// copyTextToClipboard 应该被调用 3 次(每次点击都执行)
|
|
||||||
expect(mockedCopy).toHaveBeenCalledTimes(3);
|
|
||||||
|
|
||||||
// 但 setTimeout 相关的 clearTimeout + setTimeout 组合应正常工作
|
|
||||||
// advance 1.5 秒后,copied 状态应恢复为 false
|
|
||||||
act(() => {
|
|
||||||
vi.advanceTimersByTime(1500);
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(button.className).not.toContain('text-emerald');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('其他 button props 通过 ...props 透传', () => {
|
|
||||||
render(<CopyButton text="props-test" data-testid="copy-btn" disabled id="copy-button-id" />);
|
|
||||||
|
|
||||||
const button = screen.getByRole('button');
|
|
||||||
expect(button).toHaveAttribute('data-testid', 'copy-btn');
|
|
||||||
expect(button).toBeDisabled();
|
|
||||||
expect(button).toHaveAttribute('id', 'copy-button-id');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -12,15 +12,12 @@ interface QrCodePreviewProps extends React.HTMLAttributes<HTMLDivElement> {
|
|||||||
onDownload: () => void;
|
onDownload: () => void;
|
||||||
/** 复制回调 */
|
/** 复制回调 */
|
||||||
onCopy: () => void;
|
onCopy: () => void;
|
||||||
/** 自定义占位文本,用于空状态提示 */
|
|
||||||
placeholderText?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const QrCodePreview = ({
|
const QrCodePreview = ({
|
||||||
qrCodeDataUrl,
|
qrCodeDataUrl,
|
||||||
onDownload,
|
onDownload,
|
||||||
onCopy,
|
onCopy,
|
||||||
placeholderText,
|
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: QrCodePreviewProps) => {
|
}: QrCodePreviewProps) => {
|
||||||
@@ -36,9 +33,7 @@ const QrCodePreview = ({
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<p className="text-sm text-muted-foreground text-center">
|
<p className="text-sm text-muted-foreground text-center">{t('qrCode:qrCodeWillShow')}</p>
|
||||||
{placeholderText || t('qrCode:qrCodeWillShow')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -46,34 +41,34 @@ const QrCodePreview = ({
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex flex-col justify-center items-center border border-input rounded-xl p-4 bg-muted/40',
|
'flex flex-col justify-center items-center min-h-[200px] border border-input rounded-xl p-6 bg-muted/40',
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col items-center w-full max-w-xs">
|
<div className="flex flex-col items-center w-full max-w-xs">
|
||||||
{/*
|
{/*
|
||||||
二维码容器适配:
|
2. 二维码容器适配:
|
||||||
在暗黑模式下,纯黑白的二维码如果直接暴露在暗色背景下,会导致手机摄像头极难识别。
|
在暗黑模式下,纯黑白的二维码如果直接暴露在暗色背景下,会导致手机摄像头极难识别。
|
||||||
通过裹一层 bg-white 和 p-2,确保黑白对比度绝对安全,同时加入 shadow 增强卡片感。
|
通过裹一层 bg-white 和 p-3,确保黑白对比度绝对安全,同时加入 shadow 增强卡片感。
|
||||||
*/}
|
*/}
|
||||||
<div className="p-2 bg-white rounded-lg shadow-sm border border-border/40">
|
<div className="p-3 bg-white rounded-lg shadow-sm border border-border/40">
|
||||||
<img
|
<img
|
||||||
src={qrCodeDataUrl}
|
src={qrCodeDataUrl}
|
||||||
alt="QR Code Preview"
|
alt="QR Code Preview"
|
||||||
className="w-48 h-48 max-w-full object-contain block animate-in fade-in duration-300"
|
className="w-56 h-56 max-w-full object-contain block animate-in fade-in duration-300"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex w-full gap-2 mt-3">
|
<div className="flex w-full gap-2 mt-5">
|
||||||
<Button variant="outline" size="sm" onClick={onDownload} className="flex-1 h-8">
|
<Button variant="outline" size="sm" onClick={onDownload} className="flex-1">
|
||||||
<Download className="w-3.5 h-3.5 text-muted-foreground" />
|
<Download className="w-4 h-4 text-muted-foreground" />
|
||||||
<span className="truncate text-xs">{t('qrCode:downloadButton')}</span>
|
<span className="truncate">{t('qrCode:downloadButton')}</span>
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<Button variant="default" size="sm" onClick={onCopy} className="flex-1 h-8">
|
<Button variant="default" size="sm" onClick={onCopy} className="flex-1">
|
||||||
<Copy className="w-3.5 h-3.5" />
|
<Copy className="w-4 h-4" />
|
||||||
<span className="truncate text-xs">{t('qrCode:copyQrButton')}</span>
|
<span className="truncate">{t('qrCode:copyQrButton')}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,194 +0,0 @@
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
||||||
import { act, render, screen, waitFor } from '@testing-library/react';
|
|
||||||
import userEvent from '@testing-library/user-event';
|
|
||||||
|
|
||||||
// unmock the globally-mocked component so we test the real implementation
|
|
||||||
vi.unmock('@/components/CopyButton');
|
|
||||||
|
|
||||||
vi.mock('@/utils/clipboard', () => ({
|
|
||||||
copyTextToClipboard: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('sonner', () => ({
|
|
||||||
toast: {
|
|
||||||
success: vi.fn(),
|
|
||||||
error: vi.fn(),
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
import { CopyButton } from '@/components/CopyButton';
|
|
||||||
import { copyTextToClipboard } from '@/utils/clipboard';
|
|
||||||
import { toast } from 'sonner';
|
|
||||||
|
|
||||||
const mockedCopy = vi.mocked(copyTextToClipboard);
|
|
||||||
const mockedToast = vi.mocked(toast);
|
|
||||||
|
|
||||||
describe('CopyButton', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
|
||||||
vi.clearAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.useRealTimers();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('复制成功时调用 copyTextToClipboard 并传入正确 text', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(true);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
render(<CopyButton text="hello world" />);
|
|
||||||
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
expect(mockedCopy).toHaveBeenCalledWith('hello world');
|
|
||||||
expect(mockedToast.success).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('复制成功后图标切换为 Check,1.5 秒后恢复', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(true);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
render(<CopyButton text="test" />);
|
|
||||||
|
|
||||||
// 点击后复制成功,按钮获得 emerald 样式(说明切到了 Check 状态)
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByRole('button').className).toContain('text-emerald');
|
|
||||||
});
|
|
||||||
|
|
||||||
// 1.5 秒后样式恢复
|
|
||||||
act(() => {
|
|
||||||
vi.advanceTimersByTime(1500);
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByRole('button').className).not.toContain('text-emerald');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('复制空文本时弹出 error toast', async () => {
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
render(<CopyButton text="" />);
|
|
||||||
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
expect(mockedCopy).not.toHaveBeenCalled();
|
|
||||||
expect(mockedToast.error).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('复制失败时弹出 error toast', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(false);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
render(<CopyButton text="something" />);
|
|
||||||
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
expect(mockedCopy).toHaveBeenCalledWith('something');
|
|
||||||
expect(mockedToast.error).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
// ==================== 新增测试 ====================
|
|
||||||
|
|
||||||
it('初始渲染时显示 Copy 图标且无 emerald 样式', () => {
|
|
||||||
render(<CopyButton text="initial" />);
|
|
||||||
|
|
||||||
const button = screen.getByRole('button');
|
|
||||||
expect(button.className).not.toContain('text-emerald');
|
|
||||||
// 通过 aria-label 确认按钮存在,图标由 lucide 渲染为 svg
|
|
||||||
expect(button).toHaveAttribute('aria-label');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('自定义 tooltip 会覆盖默认 title 和 aria-label', () => {
|
|
||||||
render(<CopyButton text="tooltip-test" tooltip="自定义提示" />);
|
|
||||||
|
|
||||||
const button = screen.getByRole('button');
|
|
||||||
expect(button).toHaveAttribute('title', '自定义提示');
|
|
||||||
expect(button).toHaveAttribute('aria-label', '自定义提示');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('className 被正确透传到按钮', () => {
|
|
||||||
render(<CopyButton text="class-test" className="my-custom-class" />);
|
|
||||||
|
|
||||||
const button = screen.getByRole('button');
|
|
||||||
expect(button.className).toContain('my-custom-class');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('点击事件阻止冒泡', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(true);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
const parentClick = vi.fn();
|
|
||||||
|
|
||||||
render(
|
|
||||||
<div onClick={parentClick}>
|
|
||||||
<CopyButton text="stop-propagation" />
|
|
||||||
</div>,
|
|
||||||
);
|
|
||||||
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
expect(mockedCopy).toHaveBeenCalled();
|
|
||||||
expect(parentClick).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('组件卸载时清除定时器,不触发状态更新警告', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(true);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
const { unmount } = render(<CopyButton text="unmount-test" />);
|
|
||||||
|
|
||||||
await user.click(screen.getByRole('button'));
|
|
||||||
|
|
||||||
// 在 1.5 秒超时到期前卸载组件
|
|
||||||
act(() => {
|
|
||||||
vi.advanceTimersByTime(500);
|
|
||||||
});
|
|
||||||
|
|
||||||
// 卸载不应抛出 "Can't perform a React state update on an unmounted component" 警告
|
|
||||||
expect(() => unmount()).not.toThrow();
|
|
||||||
|
|
||||||
// 前进剩余时间,确认没有异常
|
|
||||||
act(() => {
|
|
||||||
vi.advanceTimersByTime(2000);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('快速连续点击不会创建多个重叠定时器', async () => {
|
|
||||||
mockedCopy.mockResolvedValue(true);
|
|
||||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
|
||||||
|
|
||||||
render(<CopyButton text="rapid-click" />);
|
|
||||||
|
|
||||||
const button = screen.getByRole('button');
|
|
||||||
|
|
||||||
// 快速点击 3 次
|
|
||||||
await user.click(button);
|
|
||||||
await user.click(button);
|
|
||||||
await user.click(button);
|
|
||||||
|
|
||||||
// copyTextToClipboard 应该被调用 3 次(每次点击都执行)
|
|
||||||
expect(mockedCopy).toHaveBeenCalledTimes(3);
|
|
||||||
|
|
||||||
// 但 setTimeout 相关的 clearTimeout + setTimeout 组合应正常工作
|
|
||||||
// advance 1.5 秒后,copied 状态应恢复为 false
|
|
||||||
act(() => {
|
|
||||||
vi.advanceTimersByTime(1500);
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(button.className).not.toContain('text-emerald');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('其他 button props 通过 ...props 透传', () => {
|
|
||||||
render(<CopyButton text="props-test" data-testid="copy-btn" disabled id="copy-button-id" />);
|
|
||||||
|
|
||||||
const button = screen.getByRole('button');
|
|
||||||
expect(button).toHaveAttribute('data-testid', 'copy-btn');
|
|
||||||
expect(button).toBeDisabled();
|
|
||||||
expect(button).toHaveAttribute('id', 'copy-button-id');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import ToolCard from '@/pages/Dashboard/ToolCard';
|
||||||
|
import { Clock } from 'lucide-react';
|
||||||
|
|
||||||
|
describe('ToolCard 组件', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('渲染测试', () => {
|
||||||
|
it('应渲染标题和描述', () => {
|
||||||
|
render(
|
||||||
|
<ToolCard
|
||||||
|
title="测试工具"
|
||||||
|
description="这是一个测试工具"
|
||||||
|
colorKey="primary"
|
||||||
|
icon={Clock}
|
||||||
|
onNavigate={() => {}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('测试工具')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('这是一个测试工具')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('无描述时仅渲染标题', () => {
|
||||||
|
render(<ToolCard title="仅标题" colorKey="primary" icon={Clock} onNavigate={() => {}} />);
|
||||||
|
|
||||||
|
expect(screen.getByText('仅标题')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应渲染图标', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<ToolCard title="带图标" colorKey="primary" icon={Clock} onNavigate={() => {}} />,
|
||||||
|
);
|
||||||
|
|
||||||
|
const svgElement = container.querySelector('svg');
|
||||||
|
expect(svgElement).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('提供快照内容时应渲染快照', () => {
|
||||||
|
render(
|
||||||
|
<ToolCard
|
||||||
|
title="带快照"
|
||||||
|
colorKey="primary"
|
||||||
|
icon={Clock}
|
||||||
|
onNavigate={() => {}}
|
||||||
|
snapshot={<div data-testid="snapshot">快照内容</div>}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByTestId('snapshot')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('未提供快照时不渲染快照区域', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<ToolCard
|
||||||
|
title="无快照"
|
||||||
|
colorKey="primary"
|
||||||
|
icon={Clock}
|
||||||
|
onClick={() => {}}
|
||||||
|
onNavigate={function (): void {
|
||||||
|
throw new Error('Function not implemented.');
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(container.querySelector('[data-testid="snapshot"]')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应使用 CardActionArea 渲染,支持键盘聚焦', () => {
|
||||||
|
render(<ToolCard title="可聚焦" colorKey="primary" icon={Clock} onNavigate={() => {}} />);
|
||||||
|
|
||||||
|
const button = screen.getByRole('button', { name: /可聚焦/ });
|
||||||
|
expect(button).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('交互测试', () => {
|
||||||
|
it('点击时应调用 onClick', () => {
|
||||||
|
const handleClick = vi.fn();
|
||||||
|
render(<ToolCard title="可点击" colorKey="primary" icon={Clock} onNavigate={handleClick} />);
|
||||||
|
|
||||||
|
const button = screen.getByRole('button', { name: /可点击/ });
|
||||||
|
fireEvent.click(button);
|
||||||
|
|
||||||
|
expect(handleClick).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('按 Enter 键时应调用 onClick', async () => {
|
||||||
|
const handleClick = vi.fn();
|
||||||
|
render(
|
||||||
|
<ToolCard title="键盘可触发" colorKey="primary" icon={Clock} onNavigate={handleClick} />,
|
||||||
|
);
|
||||||
|
|
||||||
|
const button = screen.getByRole('button', { name: /键盘可触发/ });
|
||||||
|
await act(async () => {
|
||||||
|
button.focus();
|
||||||
|
await userEvent.keyboard('{Enter}');
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(handleClick).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('样式测试', () => {
|
||||||
|
it('应应用自定义颜色代码', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<ToolCard title="自定义颜色" colorKey="warning" icon={Clock} onNavigate={() => {}} />,
|
||||||
|
);
|
||||||
|
|
||||||
|
const svgElement = container.querySelector('svg');
|
||||||
|
expect(svgElement).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import { Toaster as Sonner } from 'sonner';
|
|
||||||
import { useThemeMode } from '@/providers/ThemeModeProvider';
|
|
||||||
|
|
||||||
type ToasterProps = React.ComponentProps<typeof Sonner>;
|
|
||||||
|
|
||||||
export function Toaster(props: ToasterProps) {
|
|
||||||
const { resolvedMode } = useThemeMode();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Sonner
|
|
||||||
theme={resolvedMode}
|
|
||||||
className="toaster group"
|
|
||||||
position="bottom-center"
|
|
||||||
toastOptions={{
|
|
||||||
classNames: {
|
|
||||||
toast:
|
|
||||||
'group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg',
|
|
||||||
description: 'group-[.toast]:text-muted-foreground',
|
|
||||||
actionButton: 'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',
|
|
||||||
cancelButton: 'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -161,7 +161,7 @@ function positionPopover(popover: HTMLElement, x: number, y: number): void {
|
|||||||
|
|
||||||
let hideTimeout: ReturnType<typeof setTimeout> | null = null;
|
let hideTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
function showPopover(
|
export function showPopover(
|
||||||
x: number,
|
x: number,
|
||||||
y: number,
|
y: number,
|
||||||
contentHtml: string,
|
contentHtml: string,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Image as ImageIcon, Trash2, Upload } from 'lucide-react';
|
import { Image as ImageIcon, Trash2, Upload } from 'lucide-react';
|
||||||
import TextInputArea from '@/components/TextInputArea';
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
import { useI18n } from '@/utils/chromeI18n';
|
import { useI18n } from '@/utils/chromeI18n';
|
||||||
import { CopyButton } from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
import DecodeResultPaper from '@/components/DecodeResultPaper';
|
import DecodeResultPaper from '@/components/DecodeResultPaper';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { downloadBlob, formatFileSize } from '@/utils/base64Converter';
|
import { downloadBlob, formatFileSize } from '@/utils/base64Converter';
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
import TextInputArea from '@/components/TextInputArea';
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
import { useI18n } from '@/utils/chromeI18n';
|
import { useI18n } from '@/utils/chromeI18n';
|
||||||
import { CopyButton } from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
import { base64ToText, textToBase64 } from '@/utils/base64Converter';
|
import { base64ToText, textToBase64 } from '@/utils/base64Converter';
|
||||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||||
import { useContextMenuData } from '@/utils/useContextMenuData';
|
import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import type { ComponentType } from 'react';
|
||||||
|
import React from 'react';
|
||||||
|
import type { LucideProps } from 'lucide-react';
|
||||||
|
import { ChevronRight } from 'lucide-react';
|
||||||
|
import type { PaletteColorKey } from '@/config/features';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
const PALETTE_COLORS: Record<PaletteColorKey, string> = {
|
||||||
|
primary: '13, 148, 136', // teal
|
||||||
|
success: '22, 163, 74', // green
|
||||||
|
warning: '217, 119, 6', // amber (存储清理的橙色轴)
|
||||||
|
error: '220, 38, 38', // red
|
||||||
|
secondary: '147, 51, 232',
|
||||||
|
info: '37, 99, 235', // blue
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface ToolCardProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
snapshot?: React.ReactNode;
|
||||||
|
colorKey: PaletteColorKey;
|
||||||
|
icon: ComponentType<LucideProps>;
|
||||||
|
onNavigate: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ToolCard({
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
snapshot,
|
||||||
|
colorKey,
|
||||||
|
icon: IconComponent,
|
||||||
|
onNavigate,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: ToolCardProps) {
|
||||||
|
const rgbValues = PALETTE_COLORS[colorKey];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
['--tool-color' as string]: rgbValues,
|
||||||
|
}}
|
||||||
|
/* 💡 核心修复点:
|
||||||
|
- 坚决不用 h-full 或固定高度,锁死 h-auto(高度自适应流),配合 py-4 px-4 牢牢把内容包裹在卡片体内。
|
||||||
|
- 废除原先会乱飘的内联 style 属性擦写,全权放权给 Tailwind 的声明式 hover 变体。
|
||||||
|
*/
|
||||||
|
className={cn(
|
||||||
|
'group relative rounded-xl border border-border/70 bg-card text-card-foreground p-4 h-auto flex flex-col items-stretch justify-start gap-3 shadow-sm select-none box-border',
|
||||||
|
'hover:bg-muted/30',
|
||||||
|
'hover:border-[rgba(var(--tool-color),0.45)]',
|
||||||
|
'hover:shadow-[0_8px_24px_-8px_rgba(var(--tool-color),0.14)] dark:hover:shadow-[0_8px_30px_-10px_rgba(var(--tool-color),0.25)]',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{/* 上半部分:核心信息交互排版轴 */}
|
||||||
|
<div className="flex items-center justify-between w-full relative min-w-0 min-h-[44px]">
|
||||||
|
<div className="flex gap-3 items-center min-w-0 flex-1 pr-2">
|
||||||
|
{/* 左侧圆形图标容器 */}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'flex items-center justify-center w-10 h-10 rounded-xl shrink-0',
|
||||||
|
'bg-[rgba(var(--tool-color),0.08)] dark:bg-[rgba(var(--tool-color),0.12)]',
|
||||||
|
'text-[rgb(var(--tool-color))]',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<IconComponent className="h-5 w-5 shrink-0" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 中间文字描述区:利用 flex-1 min-w-0 防御文本过长发生恶性撑开 */}
|
||||||
|
<div className="flex-1 min-w-0 flex flex-col">
|
||||||
|
<h4 className="font-bold text-sm tracking-tight text-foreground leading-snug">
|
||||||
|
{title}
|
||||||
|
</h4>
|
||||||
|
{description && (
|
||||||
|
<p className="text-[11px] font-medium text-muted-foreground/90 mt-0.5 leading-normal w-full truncate">
|
||||||
|
{description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 右侧指示小箭头 */}
|
||||||
|
<div className="text-muted-foreground/40 group-hover:text-[rgb(var(--tool-color))] p-1 shrink-0 group-hover:translate-x-0.5">
|
||||||
|
<ChevronRight className="h-4 w-4" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 覆盖整个上半部分的绝对定位隐形跳转层(A11y 无障碍标准合规) */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onNavigate}
|
||||||
|
aria-label={`进入 ${title}`}
|
||||||
|
className="absolute inset-0 w-full h-full cursor-pointer bg-transparent border-none opacity-0 focus-visible:outline-none"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 下半部分:未来的动态预览沙箱独立承载区 */}
|
||||||
|
{snapshot != null && (
|
||||||
|
<div className="mt-1 pt-3 border-t border-dashed border-border/80 w-full relative z-10 select-text">
|
||||||
|
{snapshot}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
ToolCard.displayName = 'ToolCard';
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useEffect, useMemo, useState } from 'react';
|
import React, { useEffect, useMemo, useState } from 'react';
|
||||||
import { useI18n } from '@/utils/chromeI18n';
|
import { useI18n } from '@/utils/chromeI18n';
|
||||||
import { formatBytes } from '@/utils/format';
|
import { formatBytes } from '@/utils/format';
|
||||||
import { CopyButton } from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
import TextInputArea from '@/components/TextInputArea';
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
import { validateJson } from '@/utils/jsonFormatter';
|
import { validateJson } from '@/utils/jsonFormatter';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
validateJson,
|
validateJson,
|
||||||
} from '@/utils/jsonFormatter';
|
} from '@/utils/jsonFormatter';
|
||||||
import { formatBytes } from '@/utils/format';
|
import { formatBytes } from '@/utils/format';
|
||||||
import { CopyButton } from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||||
import TextInputArea from '@/components/TextInputArea';
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
import { Checkbox } from '@/components/ui/checkbox';
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { CopyButton } from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
import { useI18n } from '@/utils/chromeI18n';
|
import { useI18n } from '@/utils/chromeI18n';
|
||||||
import { stringifyJson } from '@/utils/jwt';
|
import { stringifyJson } from '@/utils/jwt';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import TextInputArea from '@/components/TextInputArea';
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
import { CopyButton } from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
import JwtSection from './JwtSection';
|
import JwtSection from './JwtSection';
|
||||||
import { useJwt } from './useJwt';
|
import { useJwt } from './useJwt';
|
||||||
import { useI18n } from '@/utils/chromeI18n';
|
import { useI18n } from '@/utils/chromeI18n';
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
import { fireEvent, render, screen } from '@testing-library/react';
|
||||||
import QrCodePage from '../index';
|
import QrCodePage from '../index';
|
||||||
|
|
||||||
vi.mock('lucide-react', async (importOriginal) => {
|
vi.mock('lucide-react', async (importOriginal) => {
|
||||||
@@ -7,8 +7,6 @@ vi.mock('lucide-react', async (importOriginal) => {
|
|||||||
return {
|
return {
|
||||||
...actual,
|
...actual,
|
||||||
QrCode: () => <div data-testid="mock-lucide-qrcode">Icon</div>,
|
QrCode: () => <div data-testid="mock-lucide-qrcode">Icon</div>,
|
||||||
Pencil: () => <div data-testid="mock-lucide-pencil">Icon</div>,
|
|
||||||
Loader2: () => <div data-testid="mock-lucide-loader">Icon</div>,
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -34,29 +32,20 @@ vi.mock('@/components/ImageUploader', () => ({
|
|||||||
default: () => <div data-testid="image-uploader">ImageUploader</div>,
|
default: () => <div data-testid="image-uploader">ImageUploader</div>,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock('qrious', () => {
|
vi.mock('qrious', () => ({
|
||||||
return {
|
default: vi.fn().mockImplementation(() => ({
|
||||||
default: class QRious {
|
toDataURL: () => 'data:image/png;base64,mock',
|
||||||
constructor() {
|
})),
|
||||||
return {
|
}));
|
||||||
toDataURL: () => 'data:image/png;base64,mock',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('QrCodePage', () => {
|
describe('QrCodePage', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('应该默认渲染生成模式的输入态', () => {
|
it('应该默认渲染生成模式', () => {
|
||||||
render(<QrCodePage />);
|
render(<QrCodePage />);
|
||||||
expect(screen.getByText('输入 URL 或文本')).toBeInTheDocument();
|
expect(screen.getByTestId('qr-code-preview')).toBeInTheDocument();
|
||||||
expect(screen.getByText('生成二维码')).toBeInTheDocument();
|
|
||||||
// 输入态应该隐藏二维码预览
|
|
||||||
expect(screen.queryByTestId('qr-code-preview')).not.toBeInTheDocument();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('应该渲染模式切换按钮', () => {
|
it('应该渲染模式切换按钮', () => {
|
||||||
@@ -69,139 +58,27 @@ describe('QrCodePage', () => {
|
|||||||
render(<QrCodePage />);
|
render(<QrCodePage />);
|
||||||
fireEvent.click(screen.getByText('二维码转文本'));
|
fireEvent.click(screen.getByText('二维码转文本'));
|
||||||
expect(screen.getByTestId('image-uploader')).toBeInTheDocument();
|
expect(screen.getByTestId('image-uploader')).toBeInTheDocument();
|
||||||
});
|
|
||||||
|
|
||||||
it('切换回生成模式应该渲染输入态', () => {
|
|
||||||
render(<QrCodePage />);
|
|
||||||
// 先切换到解析模式
|
|
||||||
fireEvent.click(screen.getByText('二维码转文本'));
|
|
||||||
// 再切换回生成模式
|
|
||||||
fireEvent.click(screen.getByText('文本转二维码'));
|
|
||||||
expect(screen.getByText('输入 URL 或文本')).toBeInTheDocument();
|
|
||||||
expect(screen.getByText('生成二维码')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('应该渲染输入区域的系统标签', () => {
|
|
||||||
render(<QrCodePage />);
|
|
||||||
expect(screen.getByText('输入 URL 或文本')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('输入态应该显示生成按钮', () => {
|
|
||||||
render(<QrCodePage />);
|
|
||||||
const generateButton = screen.getByText('生成二维码');
|
|
||||||
expect(generateButton).toBeInTheDocument();
|
|
||||||
expect(generateButton).toBeDisabled(); // 空输入时按钮应该禁用
|
|
||||||
});
|
|
||||||
|
|
||||||
it('有输入内容时生成按钮应该可用', () => {
|
|
||||||
render(<QrCodePage />);
|
|
||||||
const textarea = screen.getByPlaceholderText('请输入 URL 或文本内容,将自动生成二维码');
|
|
||||||
fireEvent.change(textarea, { target: { value: 'https://example.com' } });
|
|
||||||
|
|
||||||
const generateButton = screen.getByText('生成二维码');
|
|
||||||
expect(generateButton).not.toBeDisabled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('点击生成按钮应该切换到预览态', async () => {
|
|
||||||
render(<QrCodePage />);
|
|
||||||
|
|
||||||
// 输入文本
|
|
||||||
const textarea = screen.getByPlaceholderText('请输入 URL 或文本内容,将自动生成二维码');
|
|
||||||
fireEvent.change(textarea, { target: { value: 'https://example.com' } });
|
|
||||||
|
|
||||||
// 点击生成按钮
|
|
||||||
const generateButton = screen.getByText('生成二维码');
|
|
||||||
fireEvent.click(generateButton);
|
|
||||||
|
|
||||||
// 验证切换到预览态
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText('原始文本')).toBeInTheDocument();
|
|
||||||
expect(screen.getByText('编辑')).toBeInTheDocument();
|
|
||||||
expect(screen.queryByText('生成二维码')).not.toBeInTheDocument();
|
|
||||||
// 预览态应该显示二维码
|
|
||||||
expect(screen.getByTestId('qr-code-preview')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('预览态应该显示截断的文本', async () => {
|
|
||||||
render(<QrCodePage />);
|
|
||||||
|
|
||||||
// 输入长文本
|
|
||||||
const longText =
|
|
||||||
'https://example.com/very/long/path/that/should/be/truncated/in/the/preview/because/it/exceeds/the/maximum/length';
|
|
||||||
const textarea = screen.getByPlaceholderText('请输入 URL 或文本内容,将自动生成二维码');
|
|
||||||
fireEvent.change(textarea, { target: { value: longText } });
|
|
||||||
|
|
||||||
// 点击生成按钮
|
|
||||||
fireEvent.click(screen.getByText('生成二维码'));
|
|
||||||
|
|
||||||
// 验证显示截断的文本(80字符 + "...")
|
|
||||||
const truncatedText = longText.slice(0, 80) + '...';
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText(truncatedText)).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('预览态应该显示完整的短文本', async () => {
|
|
||||||
render(<QrCodePage />);
|
|
||||||
|
|
||||||
// 输入短文本
|
|
||||||
const shortText = 'https://example.com';
|
|
||||||
const textarea = screen.getByPlaceholderText('请输入 URL 或文本内容,将自动生成二维码');
|
|
||||||
fireEvent.change(textarea, { target: { value: shortText } });
|
|
||||||
|
|
||||||
// 点击生成按钮
|
|
||||||
fireEvent.click(screen.getByText('生成二维码'));
|
|
||||||
|
|
||||||
// 验证显示完整文本
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText(shortText)).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('点击编辑按钮应该返回输入态', async () => {
|
|
||||||
render(<QrCodePage />);
|
|
||||||
|
|
||||||
// 输入文本并生成
|
|
||||||
const textarea = screen.getByPlaceholderText('请输入 URL 或文本内容,将自动生成二维码');
|
|
||||||
fireEvent.change(textarea, { target: { value: 'https://example.com' } });
|
|
||||||
fireEvent.click(screen.getByText('生成二维码'));
|
|
||||||
|
|
||||||
// 等待生成完成
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText('编辑')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
// 点击编辑按钮
|
|
||||||
fireEvent.click(screen.getByText('编辑'));
|
|
||||||
|
|
||||||
// 验证返回输入态
|
|
||||||
expect(screen.getByText('输入 URL 或文本')).toBeInTheDocument();
|
|
||||||
expect(screen.getByText('生成二维码')).toBeInTheDocument();
|
|
||||||
expect(screen.queryByText('编辑')).not.toBeInTheDocument();
|
|
||||||
// 输入态应该隐藏二维码预览
|
|
||||||
expect(screen.queryByTestId('qr-code-preview')).not.toBeInTheDocument();
|
expect(screen.queryByTestId('qr-code-preview')).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('返回编辑态应该保留上次输入的内容', async () => {
|
it('切换回生成模式应该渲染 QrCodePreview', () => {
|
||||||
render(<QrCodePage />);
|
render(<QrCodePage />);
|
||||||
|
// 先切换到解析模式
|
||||||
|
fireEvent.click(screen.getByText('二维码转文本'));
|
||||||
|
expect(screen.getByTestId('image-uploader')).toBeInTheDocument();
|
||||||
|
// 再切换回生成模式
|
||||||
|
fireEvent.click(screen.getByText('文本转二维码'));
|
||||||
|
expect(screen.getByTestId('qr-code-preview')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
// 输入文本并生成
|
it('应该渲染输入区域的系统标签(对齐新版 Label 机制)', () => {
|
||||||
const textarea = screen.getByPlaceholderText('请输入 URL 或文本内容,将自动生成二维码');
|
render(<QrCodePage />);
|
||||||
fireEvent.change(textarea, { target: { value: 'https://example.com' } });
|
expect(screen.getByText('输入 URL 或文本')).toBeInTheDocument();
|
||||||
fireEvent.click(screen.getByText('生成二维码'));
|
});
|
||||||
|
|
||||||
// 等待生成完成
|
it('应该渲染双翼响应式卡片网格布局', () => {
|
||||||
await waitFor(() => {
|
const { container } = render(<QrCodePage />);
|
||||||
expect(screen.getByText('编辑')).toBeInTheDocument();
|
const gridContainer = container.querySelector('.grid');
|
||||||
});
|
expect(gridContainer).toBeInTheDocument();
|
||||||
|
|
||||||
// 点击编辑按钮
|
|
||||||
fireEvent.click(screen.getByText('编辑'));
|
|
||||||
|
|
||||||
// 验证输入框保留了上次的内容
|
|
||||||
const textareaAfterEdit =
|
|
||||||
screen.getByPlaceholderText('请输入 URL 或文本内容,将自动生成二维码');
|
|
||||||
expect(textareaAfterEdit).toHaveValue('https://example.com');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,114 +1,51 @@
|
|||||||
import { Loader2, Pencil, QrCode } from 'lucide-react';
|
|
||||||
import TextInputArea from '@/components/TextInputArea';
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
import QrCodePreview from '@/components/QrCodePreview';
|
import QrCodePreview from '@/components/QrCodePreview';
|
||||||
import { useI18n } from '@/utils/chromeI18n';
|
import { useI18n } from '@/utils/chromeI18n';
|
||||||
import { useQrCodeContext } from '../contexts/QrCodeContext';
|
import { useQrCodeContext } from '../contexts/QrCodeContext';
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
/** 文本预览的最大显示字符数 */
|
|
||||||
const TEXT_PREVIEW_MAX_LENGTH = 80;
|
|
||||||
|
|
||||||
export default function GeneratePanel() {
|
export default function GeneratePanel() {
|
||||||
const { t } = useI18n('qrCode');
|
const { t } = useI18n('qrCode');
|
||||||
const {
|
const { generatorState, setTextToEncode, downloadQrCode, copyQrCode } = useQrCodeContext();
|
||||||
generatorState,
|
|
||||||
setTextToEncode,
|
|
||||||
confirmGenerate,
|
|
||||||
backToEdit,
|
|
||||||
downloadQrCode,
|
|
||||||
copyQrCode,
|
|
||||||
} = useQrCodeContext();
|
|
||||||
|
|
||||||
const isInputStep = generatorState.step === 'input';
|
return (
|
||||||
const hasText = generatorState.textToEncode.trim().length > 0;
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 w-full items-stretch select-none p-0.5">
|
||||||
|
<div
|
||||||
/** 截断文本用于预览显示 */
|
className={cn(
|
||||||
const getTruncatedText = (text: string) => {
|
'border border-border rounded-xl bg-card text-card-foreground shadow-sm flex flex-col p-4',
|
||||||
if (text.length <= TEXT_PREVIEW_MAX_LENGTH) return text;
|
'focus-within:ring-1 focus-within:ring-ring focus-within:border-ring',
|
||||||
return text.slice(0, TEXT_PREVIEW_MAX_LENGTH) + '...';
|
)}
|
||||||
};
|
>
|
||||||
|
<div className="flex flex-col space-y-2.5 h-full">
|
||||||
// 输入态:只显示输入框和生成按钮
|
<Label className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider select-none pl-0.5">
|
||||||
if (isInputStep) {
|
{t('qrCode:urlInputLabel')}
|
||||||
return (
|
</Label>
|
||||||
<div className="w-full select-none p-0.5">
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'border border-border rounded-xl bg-card text-card-foreground shadow-sm flex flex-col p-4',
|
|
||||||
'focus-within:ring-1 focus-within:ring-ring focus-within:border-ring',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="flex flex-col space-y-2.5">
|
|
||||||
<Label className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider select-none pl-0.5">
|
|
||||||
{t('qrCode:urlInputLabel')}
|
|
||||||
</Label>
|
|
||||||
|
|
||||||
|
<div className="flex-1 min-h-0">
|
||||||
<TextInputArea
|
<TextInputArea
|
||||||
value={generatorState.textToEncode}
|
value={generatorState.textToEncode}
|
||||||
onChange={setTextToEncode}
|
onChange={setTextToEncode}
|
||||||
placeholder={t('qrCode:urlInputPlaceholder')}
|
placeholder={t('qrCode:urlInputPlaceholder')}
|
||||||
showCount={true}
|
showCount={true}
|
||||||
showClear={true}
|
showClear={true}
|
||||||
allowCopy={false}
|
allowCopy={true}
|
||||||
minRows={6}
|
minRows={6}
|
||||||
maxRows={12}
|
maxRows={12}
|
||||||
externalError={generatorState.inputError || undefined}
|
externalError={generatorState.inputError || undefined}
|
||||||
onClear={() => setTextToEncode('')}
|
onClear={() => setTextToEncode('')}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Button
|
|
||||||
onClick={confirmGenerate}
|
|
||||||
disabled={!hasText || generatorState.generating}
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
{generatorState.generating ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
{t('qrCode:generating')}
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<QrCode className="w-4 h-4 mr-2" />
|
|
||||||
{t('qrCode:generateButton')}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 预览态:显示文本预览 + 二维码(紧凑布局,适配popup窗口)
|
<div className="flex flex-col h-full">
|
||||||
return (
|
<QrCodePreview
|
||||||
<div className="w-full select-none p-0.5 flex flex-col">
|
qrCodeDataUrl={generatorState.qrCodeDataUrl}
|
||||||
{/* 文本预览区域(固定高度,单行显示) */}
|
onDownload={downloadQrCode}
|
||||||
<div className="border border-border rounded-xl bg-card text-card-foreground shadow-sm p-3 mb-3">
|
onCopy={copyQrCode}
|
||||||
<div className="flex items-center justify-between mb-1.5">
|
/>
|
||||||
<Label className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider select-none pl-0.5">
|
|
||||||
{t('qrCode:textPreviewLabel')}
|
|
||||||
</Label>
|
|
||||||
<Button variant="ghost" size="sm" onClick={backToEdit} className="h-6 px-2 text-xs">
|
|
||||||
<Pencil className="w-3 h-3 mr-1" />
|
|
||||||
{t('qrCode:editButton')}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
className="text-sm text-foreground bg-muted/50 rounded-md px-3 py-2 cursor-default line-clamp-1"
|
|
||||||
title={generatorState.savedText}
|
|
||||||
>
|
|
||||||
{getTruncatedText(generatorState.savedText)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 二维码预览区域(自适应剩余空间) */}
|
|
||||||
<QrCodePreview
|
|
||||||
qrCodeDataUrl={generatorState.qrCodeDataUrl}
|
|
||||||
onDownload={downloadQrCode}
|
|
||||||
onCopy={copyQrCode}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
import { useCallback, useEffect } from 'react';
|
import { useCallback, useEffect } from 'react';
|
||||||
import { RefreshCw } from 'lucide-react';
|
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import TextInputArea from '@/components/TextInputArea';
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
import ImageUploader from '@/components/ImageUploader';
|
import ImageUploader from '@/components/ImageUploader';
|
||||||
import { useI18n } from '@/utils/chromeI18n';
|
import { useI18n } from '@/utils/chromeI18n';
|
||||||
import { useQrCodeContext } from '../contexts/QrCodeContext';
|
import { useQrCodeContext } from '../contexts/QrCodeContext';
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
@@ -13,8 +11,6 @@ export default function ParsePanel() {
|
|||||||
const { t } = useI18n('qrCode');
|
const { t } = useI18n('qrCode');
|
||||||
const { parserState, setParserState, handleFileChange, handleClearFile } = useQrCodeContext();
|
const { parserState, setParserState, handleFileChange, handleClearFile } = useQrCodeContext();
|
||||||
|
|
||||||
const hasFile = parserState.selectedFile !== null;
|
|
||||||
|
|
||||||
// 全局粘贴事件监听
|
// 全局粘贴事件监听
|
||||||
const handlePaste = useCallback(
|
const handlePaste = useCallback(
|
||||||
async (e: ClipboardEvent) => {
|
async (e: ClipboardEvent) => {
|
||||||
@@ -58,10 +54,9 @@ export default function ParsePanel() {
|
|||||||
};
|
};
|
||||||
}, [handlePaste]);
|
}, [handlePaste]);
|
||||||
|
|
||||||
// 未上传图片:只显示上传区域
|
return (
|
||||||
if (!hasFile) {
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 w-full items-stretch select-none p-0.5">
|
||||||
return (
|
<div className="flex flex-col h-full">
|
||||||
<div className="w-full select-none p-0.5">
|
|
||||||
<ImageUploader
|
<ImageUploader
|
||||||
selectedFile={parserState.selectedFile}
|
selectedFile={parserState.selectedFile}
|
||||||
onFileChange={handleFileChange}
|
onFileChange={handleFileChange}
|
||||||
@@ -72,60 +67,30 @@ export default function ParsePanel() {
|
|||||||
onDraggingChange={(dragging) => setParserState((prev) => ({ ...prev, dragging }))}
|
onDraggingChange={(dragging) => setParserState((prev) => ({ ...prev, dragging }))}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 已上传图片:显示图片预览 + 解析结果
|
|
||||||
return (
|
|
||||||
<div className="w-full select-none p-0.5 flex flex-col">
|
|
||||||
{/* 图片预览区域(小图预览) */}
|
|
||||||
<div className="border border-border rounded-xl bg-card text-card-foreground shadow-sm p-3 mb-3">
|
|
||||||
<div className="flex items-center justify-between mb-1.5">
|
|
||||||
<Label className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider select-none pl-0.5">
|
|
||||||
{t('qrCode:uploadedImage')}
|
|
||||||
</Label>
|
|
||||||
<Button variant="ghost" size="sm" onClick={handleClearFile} className="h-6 px-2 text-xs">
|
|
||||||
<RefreshCw className="w-3 h-3 mr-1" />
|
|
||||||
{t('qrCode:reuploadButton')}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-3 bg-muted/50 rounded-md p-2">
|
|
||||||
<img
|
|
||||||
src={parserState.previewUrl}
|
|
||||||
alt="Uploaded QR Code"
|
|
||||||
className="w-16 h-16 object-contain rounded"
|
|
||||||
/>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm text-foreground truncate">{parserState.selectedFile?.name}</p>
|
|
||||||
{parserState.parsing && (
|
|
||||||
<p className="text-xs text-primary animate-pulse mt-1">{t('qrCode:parsing')}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 解析结果区域 */}
|
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
'border border-border rounded-xl bg-card text-card-foreground shadow-sm flex flex-col p-4',
|
'border border-border rounded-xl bg-card text-card-foreground shadow-sm flex flex-col p-4',
|
||||||
'focus-within:ring-1 focus-within:ring-ring focus-within:border-ring',
|
'focus-within:ring-1 focus-within:ring-ring focus-within:border-ring',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col space-y-2.5">
|
<div className="flex flex-col space-y-2.5 h-full">
|
||||||
<Label className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider pl-0.5">
|
<Label className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider pl-0.5">
|
||||||
{t('qrCode:resultLabel')}
|
{t('qrCode:resultLabel')}
|
||||||
</Label>
|
</Label>
|
||||||
|
|
||||||
<TextInputArea
|
<div className="flex-1 min-h-0">
|
||||||
value={parserState.decodedResult}
|
<TextInputArea
|
||||||
readOnly={true}
|
value={parserState.decodedResult}
|
||||||
showClear={false}
|
readOnly={true}
|
||||||
allowCopy={true}
|
showClear={false}
|
||||||
placeholder={parserState.parsing ? '' : t('qrCode:resultPlaceholder')}
|
allowCopy={true}
|
||||||
minRows={4}
|
placeholder=""
|
||||||
maxRows={8}
|
minRows={6}
|
||||||
externalError={parserState.parseError || undefined}
|
maxRows={12}
|
||||||
/>
|
externalError={parserState.parseError || undefined}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -8,10 +8,6 @@ export interface QrCodeContextValue {
|
|||||||
|
|
||||||
generatorState: QrCodeGeneratorState;
|
generatorState: QrCodeGeneratorState;
|
||||||
setTextToEncode: (text: string) => void;
|
setTextToEncode: (text: string) => void;
|
||||||
/** 显式触发生成二维码并切换到预览态 */
|
|
||||||
confirmGenerate: () => void;
|
|
||||||
/** 返回编辑态,保留上次输入内容 */
|
|
||||||
backToEdit: () => void;
|
|
||||||
|
|
||||||
downloadQrCode: () => void;
|
downloadQrCode: () => void;
|
||||||
copyQrCode: () => Promise<void>;
|
copyQrCode: () => Promise<void>;
|
||||||
|
|||||||
@@ -1,93 +1,22 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
import { useCallback, useMemo, useState } from 'react';
|
||||||
import QRious from 'qrious';
|
import QRious from 'qrious';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { parseQrCodeFromFile } from '@/utils/qrCodeParser';
|
import { parseQrCodeFromFile } from '@/utils/qrCodeParser';
|
||||||
import { useContextMenuData } from '@/utils/useContextMenuData';
|
import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||||
import { useI18n } from '@/utils/chromeI18n';
|
import { useI18n } from '@/utils/chromeI18n';
|
||||||
|
import { useDebounce } from '@/utils/useDebounce';
|
||||||
import type { QrCodeContextValue } from '../contexts/QrCodeContext';
|
import type { QrCodeContextValue } from '../contexts/QrCodeContext';
|
||||||
import type { QrCodeGeneratorState, QrCodeMode, QrCodeParserState } from '../types';
|
import type { QrCodeGeneratorState, QrCodeMode, QrCodeParserState } from '../types';
|
||||||
|
|
||||||
/** 防抖延迟时间(毫秒) */
|
|
||||||
const DEBOUNCE_DELAY = 500;
|
|
||||||
|
|
||||||
/** 检测文本是否为URL格式 */
|
|
||||||
function isUrl(text: string): boolean {
|
|
||||||
const trimmed = text.trim();
|
|
||||||
if (!trimmed) return false;
|
|
||||||
|
|
||||||
// 检查是否以 http:// 或 https:// 开头
|
|
||||||
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查是否为域名格式(包含.且不以特殊字符开头)
|
|
||||||
const domainPattern = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z]{2,})+([/:].*)?$/;
|
|
||||||
return domainPattern.test(trimmed);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 检测URL是否为图片格式 */
|
|
||||||
function isImageUrl(url: string): boolean {
|
|
||||||
const trimmedUrl = url.trim().toLowerCase();
|
|
||||||
|
|
||||||
// 检查是否为 data:image 格式
|
|
||||||
if (trimmedUrl.startsWith('data:image/')) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查是否包含图片扩展名
|
|
||||||
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg', '.ico'];
|
|
||||||
if (imageExtensions.some((ext) => trimmedUrl.includes(ext))) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查URL路径中是否包含图片相关关键词
|
|
||||||
const imageKeywords = ['/image/', '/img/', '/photo/', '/pic/', '/upload/'];
|
|
||||||
if (imageKeywords.some((keyword) => trimmedUrl.includes(keyword))) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 生成二维码的核心逻辑 */
|
|
||||||
function generateQrCodeDataUrl(text: string): string {
|
|
||||||
const trimmedText = text.trim();
|
|
||||||
if (!trimmedText) return '';
|
|
||||||
|
|
||||||
try {
|
|
||||||
let url = trimmedText;
|
|
||||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
|
||||||
url = 'https://' + url;
|
|
||||||
}
|
|
||||||
|
|
||||||
const isDark = document.documentElement.classList.contains('dark');
|
|
||||||
|
|
||||||
const qr = new QRious({
|
|
||||||
value: url,
|
|
||||||
size: 260,
|
|
||||||
level: 'H',
|
|
||||||
foreground: isDark ? '#f3f4f6' : '#0f172a',
|
|
||||||
background: isDark ? 'transparent' : '#ffffff',
|
|
||||||
});
|
|
||||||
|
|
||||||
return qr.toDataURL();
|
|
||||||
} catch (error) {
|
|
||||||
console.error('QR code generation failed:', error);
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useQrCode(): QrCodeContextValue {
|
export function useQrCode(): QrCodeContextValue {
|
||||||
const { t } = useI18n('qrCode');
|
const { t } = useI18n('qrCode');
|
||||||
|
|
||||||
const [mode, setMode] = useState<QrCodeMode>('generate');
|
const [mode, setMode] = useState<QrCodeMode>('generate');
|
||||||
|
|
||||||
const [generatorState, setGeneratorState] = useState<QrCodeGeneratorState>({
|
const [generatorState, setGeneratorState] = useState<
|
||||||
step: 'input',
|
Omit<QrCodeGeneratorState, 'generating' | 'qrCodeDataUrl'>
|
||||||
|
>({
|
||||||
textToEncode: '',
|
textToEncode: '',
|
||||||
savedText: '',
|
|
||||||
qrCodeDataUrl: '',
|
|
||||||
generating: false,
|
|
||||||
inputError: '',
|
inputError: '',
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -100,197 +29,53 @@ export function useQrCode(): QrCodeContextValue {
|
|||||||
dragging: false,
|
dragging: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const debouncedTextToEncode = useDebounce(generatorState.textToEncode, 200);
|
||||||
|
|
||||||
// 清除防抖定时器
|
const qrCodeDataUrl = useMemo(() => {
|
||||||
useEffect(() => {
|
const text = debouncedTextToEncode.trim();
|
||||||
return () => {
|
if (!text) return '';
|
||||||
if (debounceTimerRef.current) {
|
|
||||||
clearTimeout(debounceTimerRef.current);
|
try {
|
||||||
|
let url = text;
|
||||||
|
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
||||||
|
url = 'https://' + url;
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
const isDark = document.documentElement.classList.contains('dark');
|
||||||
|
|
||||||
|
const qr = new QRious({
|
||||||
|
value: url,
|
||||||
|
size: 260,
|
||||||
|
level: 'H',
|
||||||
|
foreground: isDark ? '#f3f4f6' : '#0f172a',
|
||||||
|
background: isDark ? 'transparent' : '#ffffff',
|
||||||
|
});
|
||||||
|
|
||||||
|
return qr.toDataURL();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('QR code generation sync task failed:', error);
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}, [debouncedTextToEncode]);
|
||||||
|
|
||||||
|
const fullGeneratorState = useMemo<QrCodeGeneratorState>(
|
||||||
|
() => ({
|
||||||
|
...generatorState,
|
||||||
|
qrCodeDataUrl,
|
||||||
|
generating: false,
|
||||||
|
}),
|
||||||
|
[generatorState, qrCodeDataUrl],
|
||||||
|
);
|
||||||
|
|
||||||
|
const setTextToEncode = useCallback((text: string) => {
|
||||||
|
setGeneratorState((prev) => ({ ...prev, textToEncode: text, inputError: '' }));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
/** 自动检测URL并生成二维码 */
|
const handleContextMenuData = useCallback((payload: string) => {
|
||||||
const autoGenerateIfUrl = useCallback(
|
setMode('generate');
|
||||||
(text: string) => {
|
setGeneratorState((prev) => ({ ...prev, textToEncode: payload, inputError: '' }));
|
||||||
if (debounceTimerRef.current) {
|
|
||||||
clearTimeout(debounceTimerRef.current);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isUrl(text)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
debounceTimerRef.current = setTimeout(() => {
|
|
||||||
setGeneratorState((prev) => ({ ...prev, generating: true, inputError: '' }));
|
|
||||||
|
|
||||||
const qrCodeDataUrl = generateQrCodeDataUrl(text);
|
|
||||||
|
|
||||||
if (qrCodeDataUrl) {
|
|
||||||
setGeneratorState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
step: 'preview',
|
|
||||||
savedText: text.trim(),
|
|
||||||
qrCodeDataUrl,
|
|
||||||
generating: false,
|
|
||||||
}));
|
|
||||||
} else {
|
|
||||||
setGeneratorState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
generating: false,
|
|
||||||
inputError: t('qrCode:generateError'),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}, DEBOUNCE_DELAY);
|
|
||||||
},
|
|
||||||
[t],
|
|
||||||
);
|
|
||||||
|
|
||||||
const setTextToEncode = useCallback(
|
|
||||||
(text: string) => {
|
|
||||||
setGeneratorState((prev) => ({ ...prev, textToEncode: text, inputError: '' }));
|
|
||||||
autoGenerateIfUrl(text);
|
|
||||||
},
|
|
||||||
[autoGenerateIfUrl],
|
|
||||||
);
|
|
||||||
|
|
||||||
/** 手动触发生成二维码(用于非URL文本) */
|
|
||||||
const confirmGenerate = useCallback(() => {
|
|
||||||
const text = generatorState.textToEncode.trim();
|
|
||||||
|
|
||||||
if (!text) {
|
|
||||||
setGeneratorState((prev) => ({ ...prev, inputError: t('qrCode:inputRequired') }));
|
|
||||||
toast.error(t('qrCode:inputRequired'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 先设置 loading 状态,让 React 渲染加载动画
|
|
||||||
setGeneratorState((prev) => ({ ...prev, generating: true, inputError: '' }));
|
|
||||||
|
|
||||||
// 延迟到下一帧生成,确保 loading 状态先被渲染显示
|
|
||||||
setTimeout(() => {
|
|
||||||
const qrCodeDataUrl = generateQrCodeDataUrl(text);
|
|
||||||
|
|
||||||
if (!qrCodeDataUrl) {
|
|
||||||
setGeneratorState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
generating: false,
|
|
||||||
inputError: t('qrCode:generateError'),
|
|
||||||
}));
|
|
||||||
toast.error(t('qrCode:generateError'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setGeneratorState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
step: 'preview',
|
|
||||||
savedText: text,
|
|
||||||
qrCodeDataUrl,
|
|
||||||
generating: false,
|
|
||||||
}));
|
|
||||||
}, 0);
|
|
||||||
}, [generatorState.textToEncode, t]);
|
|
||||||
|
|
||||||
/** 返回编辑态,保留上次输入内容 */
|
|
||||||
const backToEdit = useCallback(() => {
|
|
||||||
if (debounceTimerRef.current) {
|
|
||||||
clearTimeout(debounceTimerRef.current);
|
|
||||||
}
|
|
||||||
setGeneratorState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
step: 'input',
|
|
||||||
textToEncode: prev.savedText,
|
|
||||||
qrCodeDataUrl: '',
|
|
||||||
inputError: '',
|
|
||||||
}));
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
/** 从图片URL解析二维码 */
|
|
||||||
const parseQrCodeFromUrl = useCallback(
|
|
||||||
async (imageUrl: string) => {
|
|
||||||
try {
|
|
||||||
setParserState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
parsing: true,
|
|
||||||
parseError: '',
|
|
||||||
decodedResult: '',
|
|
||||||
previewUrl: imageUrl,
|
|
||||||
selectedFile: null,
|
|
||||||
}));
|
|
||||||
|
|
||||||
// 从URL获取图片并转换为File对象
|
|
||||||
const response = await fetch(imageUrl);
|
|
||||||
const blob = await response.blob();
|
|
||||||
const file = new File([blob], 'qrcode-image.png', { type: blob.type });
|
|
||||||
|
|
||||||
setParserState((prev) => ({ ...prev, selectedFile: file }));
|
|
||||||
|
|
||||||
const result = await parseQrCodeFromFile(file);
|
|
||||||
|
|
||||||
if (result.success && result.data) {
|
|
||||||
setParserState((prev) => ({ ...prev, decodedResult: result.data! }));
|
|
||||||
toast.success(t('qrCode:parseSuccess'));
|
|
||||||
} else {
|
|
||||||
const errorMsg = result.error || t('qrCode:noQrDetected');
|
|
||||||
setParserState((prev) => ({ ...prev, parseError: errorMsg }));
|
|
||||||
toast.error(errorMsg);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('解析图片二维码失败:', error);
|
|
||||||
const errorMsg = error instanceof Error ? error.message : t('qrCode:parseError');
|
|
||||||
setParserState((prev) => ({ ...prev, parseError: errorMsg }));
|
|
||||||
toast.error(errorMsg);
|
|
||||||
} finally {
|
|
||||||
setParserState((prev) => ({ ...prev, parsing: false }));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[t],
|
|
||||||
);
|
|
||||||
|
|
||||||
/** 右键菜单传入URL时,自动生成二维码或解析图片 */
|
|
||||||
const handleContextMenuData = useCallback(
|
|
||||||
(payload: string) => {
|
|
||||||
// 检测是否为图片URL,如果是则切换到解析模式
|
|
||||||
if (isImageUrl(payload)) {
|
|
||||||
setMode('parse');
|
|
||||||
void parseQrCodeFromUrl(payload);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 非图片URL,生成二维码
|
|
||||||
setMode('generate');
|
|
||||||
|
|
||||||
// 直接生成二维码,无需等待
|
|
||||||
const qrCodeDataUrl = generateQrCodeDataUrl(payload);
|
|
||||||
|
|
||||||
if (qrCodeDataUrl) {
|
|
||||||
// 生成成功,直接跳转到预览态
|
|
||||||
setGeneratorState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
step: 'preview',
|
|
||||||
textToEncode: payload,
|
|
||||||
savedText: payload.trim(),
|
|
||||||
qrCodeDataUrl,
|
|
||||||
generating: false,
|
|
||||||
inputError: '',
|
|
||||||
}));
|
|
||||||
} else {
|
|
||||||
// 生成失败,停留在输入态,显示文本供用户编辑
|
|
||||||
setGeneratorState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
step: 'input',
|
|
||||||
textToEncode: payload,
|
|
||||||
savedText: '',
|
|
||||||
qrCodeDataUrl: '',
|
|
||||||
generating: false,
|
|
||||||
inputError: '',
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[parseQrCodeFromUrl],
|
|
||||||
);
|
|
||||||
|
|
||||||
useContextMenuData({ featureKey: 'qrCode', onData: handleContextMenuData });
|
useContextMenuData({ featureKey: 'qrCode', onData: handleContextMenuData });
|
||||||
|
|
||||||
// 反向活态解析二维码算法
|
// 反向活态解析二维码算法
|
||||||
@@ -322,20 +107,20 @@ export function useQrCode(): QrCodeContextValue {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const downloadQrCode = useCallback(() => {
|
const downloadQrCode = useCallback(() => {
|
||||||
if (!generatorState.qrCodeDataUrl) return;
|
if (!qrCodeDataUrl) return;
|
||||||
|
|
||||||
const link = document.createElement('a');
|
const link = document.createElement('a');
|
||||||
link.href = generatorState.qrCodeDataUrl;
|
link.href = qrCodeDataUrl;
|
||||||
link.download = 'qrcode.png';
|
link.download = 'qrcode.png';
|
||||||
link.click();
|
link.click();
|
||||||
toast.success(t('qrCode:qrCodeDownloadSuccess'));
|
toast.success(t('qrCode:qrCodeDownloadSuccess'));
|
||||||
}, [generatorState.qrCodeDataUrl, t]);
|
}, [qrCodeDataUrl, t]);
|
||||||
|
|
||||||
const copyQrCode = useCallback(async () => {
|
const copyQrCode = useCallback(async () => {
|
||||||
if (!generatorState.qrCodeDataUrl) return;
|
if (!qrCodeDataUrl) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(generatorState.qrCodeDataUrl);
|
const response = await fetch(qrCodeDataUrl);
|
||||||
const blob = await response.blob();
|
const blob = await response.blob();
|
||||||
|
|
||||||
await navigator.clipboard.write([
|
await navigator.clipboard.write([
|
||||||
@@ -349,7 +134,7 @@ export function useQrCode(): QrCodeContextValue {
|
|||||||
console.error('复制二维码失败:', error);
|
console.error('复制二维码失败:', error);
|
||||||
toast.error(t('qrCode:copyError'));
|
toast.error(t('qrCode:copyError'));
|
||||||
}
|
}
|
||||||
}, [generatorState.qrCodeDataUrl, t]);
|
}, [qrCodeDataUrl, t]);
|
||||||
|
|
||||||
const handleFileChange = useCallback(
|
const handleFileChange = useCallback(
|
||||||
(file: File) => {
|
(file: File) => {
|
||||||
@@ -393,10 +178,8 @@ export function useQrCode(): QrCodeContextValue {
|
|||||||
return {
|
return {
|
||||||
mode,
|
mode,
|
||||||
setMode,
|
setMode,
|
||||||
generatorState,
|
generatorState: fullGeneratorState,
|
||||||
setTextToEncode,
|
setTextToEncode,
|
||||||
confirmGenerate,
|
|
||||||
backToEdit,
|
|
||||||
parseQrCode,
|
parseQrCode,
|
||||||
downloadQrCode,
|
downloadQrCode,
|
||||||
copyQrCode,
|
copyQrCode,
|
||||||
|
|||||||
@@ -5,23 +5,16 @@
|
|||||||
/** 二维码功能核心主路由模式 */
|
/** 二维码功能核心主路由模式 */
|
||||||
export type QrCodeMode = 'generate' | 'parse';
|
export type QrCodeMode = 'generate' | 'parse';
|
||||||
|
|
||||||
/** 生成器的操作步骤 */
|
|
||||||
export type GeneratorStep = 'input' | 'preview';
|
|
||||||
|
|
||||||
/** * 二维码生成器的状态
|
/** * 二维码生成器的状态
|
||||||
* 💡 架构优化:采用两步操作模式(输入态 → 预览态),
|
* 💡 架构优化:保留与全局 Context 骨架契合的形态,
|
||||||
* 用户显式点击生成按钮后才生成二维码,体验更清晰!
|
* 外部依然可以流畅读取这些状态,但在新架构下运行效率和稳定性大幅提升!
|
||||||
*/
|
*/
|
||||||
export interface QrCodeGeneratorState {
|
export interface QrCodeGeneratorState {
|
||||||
/** 当前操作步骤:输入态或预览态 */
|
|
||||||
step: GeneratorStep;
|
|
||||||
/** 受控的输入源文本(支持 URL 或任意文本快照) */
|
/** 受控的输入源文本(支持 URL 或任意文本快照) */
|
||||||
textToEncode: string;
|
textToEncode: string;
|
||||||
/** 保存的文本快照,用于预览态展示和编辑态回填 */
|
/** 由防抖源文本流在单次渲染内存中同步派生出的二维码 Base64 Data URL */
|
||||||
savedText: string;
|
|
||||||
/** 由用户显式触发生成的二维码 Base64 Data URL */
|
|
||||||
qrCodeDataUrl: string;
|
qrCodeDataUrl: string;
|
||||||
/** 是否正在生成 */
|
/** 是否正在生成(流式架构下已默认为恒定 false 的非阻塞快照,保留作为 UI 骨架兼容) */
|
||||||
generating: boolean;
|
generating: boolean;
|
||||||
/** 输入文本校验或底层画布崩溃的错误提示信息 */
|
/** 输入文本校验或底层画布崩溃的错误提示信息 */
|
||||||
inputError: string;
|
inputError: string;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Clock } from 'lucide-react';
|
import { Clock } from 'lucide-react';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { CopyButton } from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
import type { UnitType } from './constants';
|
import type { UnitType } from './constants';
|
||||||
import { msToUnit } from './constants';
|
import { msToUnit } from './constants';
|
||||||
import { useI18n } from '@/utils/chromeI18n';
|
import { useI18n } from '@/utils/chromeI18n';
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { CopyButton } from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
import { useI18n } from '@/utils/chromeI18n';
|
import { useI18n } from '@/utils/chromeI18n';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { ThemeModeProvider } from './ThemeModeProvider';
|
import { ThemeModeProvider } from './ThemeModeProvider';
|
||||||
import { RouterProvider } from './RouterProvider';
|
import { RouterProvider } from './RouterProvider';
|
||||||
import { Toaster } from '@/components/ui/sonner';
|
|
||||||
|
|
||||||
interface AppRootProps {
|
interface AppRootProps {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
@@ -12,7 +11,6 @@ export default function AppRoot({ children }: AppRootProps) {
|
|||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<ThemeModeProvider>
|
<ThemeModeProvider>
|
||||||
<RouterProvider>{children}</RouterProvider>
|
<RouterProvider>{children}</RouterProvider>
|
||||||
<Toaster />
|
|
||||||
</ThemeModeProvider>
|
</ThemeModeProvider>
|
||||||
</React.StrictMode>
|
</React.StrictMode>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,7 +1,101 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import { openExtensionPage } from '@/utils/chromeTabs';
|
import {
|
||||||
|
getActiveTab,
|
||||||
|
getActiveTabDomain,
|
||||||
|
openExtensionPage,
|
||||||
|
ensureContentScriptInjected,
|
||||||
|
} from '@/utils/chromeTabs';
|
||||||
|
|
||||||
describe('chromeTabs', () => {
|
describe('chromeTabs', () => {
|
||||||
|
describe('getActiveTab', () => {
|
||||||
|
it('应该返回当前活动标签页', async () => {
|
||||||
|
const mockTab = { id: 1, url: 'https://example.com', title: 'Example' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTab();
|
||||||
|
|
||||||
|
expect(result).toEqual(mockTab);
|
||||||
|
expect(chrome.tabs.query).toHaveBeenCalledWith({ active: true, currentWindow: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当没有活动标签页时应返回 null', async () => {
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([]);
|
||||||
|
|
||||||
|
const result = await getActiveTab();
|
||||||
|
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当查询失败时应返回 null 并记录错误', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
(chrome.tabs.query as any).mockRejectedValue(new Error('Permission denied'));
|
||||||
|
|
||||||
|
const result = await getActiveTab();
|
||||||
|
|
||||||
|
expect(result).toBeNull();
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith('获取活动标签页失败:', expect.any(Error));
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getActiveTabDomain', () => {
|
||||||
|
it('应该返回当前活动标签页的域名', async () => {
|
||||||
|
const mockTab = { id: 1, url: 'https://example.com/path?query=1' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该处理带有端口的 URL', async () => {
|
||||||
|
const mockTab = { id: 1, url: 'https://example.com:8080/path' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当标签页没有 URL 时应返回空字符串', async () => {
|
||||||
|
const mockTab = { id: 1 } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当没有活动标签页时应返回空字符串', async () => {
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当 URL 解析失败时应返回空字符串并记录错误', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
const mockTab = { id: 1, url: 'not-a-valid-url' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('');
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith('解析域名失败:', expect.any(Error));
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该处理 chrome-extension URL', async () => {
|
||||||
|
const mockTab = { id: 1, url: 'chrome-extension://abc123/popup.html' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('abc123');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('openExtensionPage', () => {
|
describe('openExtensionPage', () => {
|
||||||
it('应该在新标签页中打开扩展页面', async () => {
|
it('应该在新标签页中打开扩展页面', async () => {
|
||||||
await openExtensionPage('popup.html');
|
await openExtensionPage('popup.html');
|
||||||
@@ -22,4 +116,44 @@ describe('chromeTabs', () => {
|
|||||||
consoleSpy.mockRestore();
|
consoleSpy.mockRestore();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('ensureContentScriptInjected', () => {
|
||||||
|
it('当存在活动标签页时应返回 true', async () => {
|
||||||
|
const mockTab = { id: 123, url: 'https://example.com' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await ensureContentScriptInjected();
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当没有活动标签页时应返回 false', async () => {
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([]);
|
||||||
|
|
||||||
|
const result = await ensureContentScriptInjected();
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当标签页没有 id 时应返回 false', async () => {
|
||||||
|
const mockTab = { url: 'https://example.com' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await ensureContentScriptInjected();
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当整体操作失败时应返回 false 并记录错误', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
(chrome.tabs.query as any).mockRejectedValue(new Error('Query failed'));
|
||||||
|
|
||||||
|
const result = await ensureContentScriptInjected();
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
// getActiveTab catches the error and logs "获取活动标签页失败"
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith('获取活动标签页失败:', expect.any(Error));
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,14 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi, beforeAll } from 'vitest';
|
||||||
import { copyTextToClipboard } from '@/utils/clipboard';
|
import { copyTextToClipboard, copyImageToClipboard } from '@/utils/clipboard';
|
||||||
|
|
||||||
|
// Mock ClipboardItem for test environment
|
||||||
|
class MockClipboardItem {
|
||||||
|
constructor(public items: Record<string, Blob>) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
(globalThis as any).ClipboardItem = MockClipboardItem;
|
||||||
|
});
|
||||||
|
|
||||||
describe('clipboard', () => {
|
describe('clipboard', () => {
|
||||||
describe('copyTextToClipboard', () => {
|
describe('copyTextToClipboard', () => {
|
||||||
@@ -22,4 +31,27 @@ describe('clipboard', () => {
|
|||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('copyImageToClipboard', () => {
|
||||||
|
it('复制成功时应返回 true', async () => {
|
||||||
|
const write = vi.fn().mockResolvedValue(undefined);
|
||||||
|
Object.assign(navigator, { clipboard: { write } });
|
||||||
|
|
||||||
|
const blob = new Blob(['png data'], { type: 'image/png' });
|
||||||
|
const result = await copyImageToClipboard(blob);
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
expect(write).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('复制失败时应返回 false', async () => {
|
||||||
|
const write = vi.fn().mockRejectedValue(new Error('Permission denied'));
|
||||||
|
Object.assign(navigator, { clipboard: { write } });
|
||||||
|
|
||||||
|
const blob = new Blob(['png data'], { type: 'image/png' });
|
||||||
|
const result = await copyImageToClipboard(blob);
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ describe('contextMenu', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('CONTEXT_MENU_CONFIGS', () => {
|
describe('CONTEXT_MENU_CONFIGS', () => {
|
||||||
it('应该包含 8 个菜单项配置', () => {
|
it('应该包含 7 个菜单项配置', () => {
|
||||||
expect(CONTEXT_MENU_CONFIGS).toHaveLength(8);
|
expect(CONTEXT_MENU_CONFIGS).toHaveLength(7);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('应该有一个父级菜单项 Testing Tools', () => {
|
it('应该有一个父级菜单项 Testing Tools', () => {
|
||||||
@@ -43,22 +43,13 @@ describe('contextMenu', () => {
|
|||||||
expect(pageMenus).toHaveLength(2);
|
expect(pageMenus).toHaveLength(2);
|
||||||
expect(pageMenus.map((m) => m.id)).toEqual(['storageCleaner', 'qrCode-page']);
|
expect(pageMenus.map((m) => m.id)).toEqual(['storageCleaner', 'qrCode-page']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('应该有 1 个 image 上下文的子菜单', () => {
|
|
||||||
const imageMenus = CONTEXT_MENU_CONFIGS.filter(
|
|
||||||
(c) => c.contexts[0] === 'image' && c.parentId === 'testing-tools-parent',
|
|
||||||
);
|
|
||||||
expect(imageMenus).toHaveLength(1);
|
|
||||||
expect(imageMenus[0].id).toBe('qrCode-image');
|
|
||||||
expect(imageMenus[0].title).toBe('🖼️ 解析图片二维码');
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('createAllContextMenus', () => {
|
describe('createAllContextMenus', () => {
|
||||||
it('应该为每个配置调用 chrome.contextMenus.create', () => {
|
it('应该为每个配置调用 chrome.contextMenus.create', () => {
|
||||||
createAllContextMenus();
|
createAllContextMenus();
|
||||||
|
|
||||||
expect(chrome.contextMenus.create).toHaveBeenCalledTimes(8);
|
expect(chrome.contextMenus.create).toHaveBeenCalledTimes(7);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('应该使用正确的参数创建菜单项', () => {
|
it('应该使用正确的参数创建菜单项', () => {
|
||||||
@@ -194,33 +185,5 @@ describe('contextMenu', () => {
|
|||||||
data: { featureKey: 'textStatistics', payload: 'short text' },
|
data: { featureKey: 'textStatistics', payload: 'short text' },
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('当点击 qrCode-image 菜单时应返回 qrCode 功能和图片URL', () => {
|
|
||||||
const info = createMockOnClickData({
|
|
||||||
srcUrl: 'https://example.com/image.png',
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = parseContextMenuClick('qrCode-image', info);
|
|
||||||
|
|
||||||
expect(result).toEqual({
|
|
||||||
success: true,
|
|
||||||
data: { featureKey: 'qrCode', payload: 'https://example.com/image.png' },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('srcUrl 优先于 selectionText 和 pageUrl', () => {
|
|
||||||
const info = createMockOnClickData({
|
|
||||||
srcUrl: 'https://example.com/image.png',
|
|
||||||
selectionText: 'selected text',
|
|
||||||
pageUrl: 'https://example.com',
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = parseContextMenuClick('qrCode-image', info);
|
|
||||||
|
|
||||||
expect(result).toEqual({
|
|
||||||
success: true,
|
|
||||||
data: { featureKey: 'qrCode', payload: 'https://example.com/image.png' },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
||||||
import { renderHook, act } from '@testing-library/react';
|
import { renderHook, act } from '@testing-library/react';
|
||||||
import { useContextMenuData, saveContextMenuData } from '@/utils/useContextMenuData';
|
import {
|
||||||
|
useContextMenuData,
|
||||||
|
saveContextMenuData,
|
||||||
|
clearContextMenuData,
|
||||||
|
} from '@/utils/useContextMenuData';
|
||||||
|
|
||||||
describe('useContextMenuData', () => {
|
describe('useContextMenuData', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -44,6 +48,14 @@ describe('useContextMenuData', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('clearContextMenuData', () => {
|
||||||
|
it('应该从 storage 中删除数据', async () => {
|
||||||
|
await clearContextMenuData();
|
||||||
|
|
||||||
|
expect(chrome.storage.local.remove).toHaveBeenCalledWith(['contextMenu/pendingData']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('useContextMenuData Hook', () => {
|
describe('useContextMenuData Hook', () => {
|
||||||
it('当 storage 中有匹配数据时应调用 onData 回调', async () => {
|
it('当 storage 中有匹配数据时应调用 onData 回调', async () => {
|
||||||
const mockData = {
|
const mockData = {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { formatBytes } from './format';
|
|||||||
export const MAX_FILE_SIZE = 10 * 1024 * 1024;
|
export const MAX_FILE_SIZE = 10 * 1024 * 1024;
|
||||||
|
|
||||||
/** 支持的图像 MIME 类型 */
|
/** 支持的图像 MIME 类型 */
|
||||||
const SUPPORTED_IMAGE_TYPES = [
|
export const SUPPORTED_IMAGE_TYPES = [
|
||||||
'image/png',
|
'image/png',
|
||||||
'image/jpeg',
|
'image/jpeg',
|
||||||
'image/jpg',
|
'image/jpg',
|
||||||
@@ -20,7 +20,7 @@ const SUPPORTED_IMAGE_TYPES = [
|
|||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
/** 支持的图像文件扩展名 */
|
/** 支持的图像文件扩展名 */
|
||||||
const SUPPORTED_IMAGE_EXTENSIONS = [
|
export const SUPPORTED_IMAGE_EXTENSIONS = [
|
||||||
'.png',
|
'.png',
|
||||||
'.jpg',
|
'.jpg',
|
||||||
'.jpeg',
|
'.jpeg',
|
||||||
@@ -34,7 +34,7 @@ const SUPPORTED_IMAGE_EXTENSIONS = [
|
|||||||
/**
|
/**
|
||||||
* 文本转 Base64 编码结果
|
* 文本转 Base64 编码结果
|
||||||
*/
|
*/
|
||||||
interface TextToBase64Result {
|
export interface TextToBase64Result {
|
||||||
/** Base64 编码结果 */
|
/** Base64 编码结果 */
|
||||||
output: string;
|
output: string;
|
||||||
/** 原始字节数 */
|
/** 原始字节数 */
|
||||||
@@ -226,7 +226,7 @@ export function formatFileSize(bytes: number): string {
|
|||||||
/**
|
/**
|
||||||
* Base64 解码为二进制后的产物
|
* Base64 解码为二进制后的产物
|
||||||
*/
|
*/
|
||||||
interface Base64ToBlobResult {
|
export interface Base64ToBlobResult {
|
||||||
/** 解码后的 Blob */
|
/** 解码后的 Blob */
|
||||||
blob: Blob;
|
blob: Blob;
|
||||||
/** 推断出的 MIME 类型 */
|
/** 推断出的 MIME 类型 */
|
||||||
|
|||||||
@@ -26,8 +26,12 @@ export function useI18n(namespace?: string | string[]) {
|
|||||||
const namespaces = Array.isArray(namespace) ? namespace : namespace ? [namespace] : [];
|
const namespaces = Array.isArray(namespace) ? namespace : namespace ? [namespace] : [];
|
||||||
|
|
||||||
const t = (key: string, options?: Record<string, unknown>): string => {
|
const t = (key: string, options?: Record<string, unknown>): string => {
|
||||||
// 统一将分隔符转换为下划线,兼容 'namespace:key.path' 和 'key.path' 两种写法
|
let msgId = key;
|
||||||
const msgId = key.replace(':', '_').replace(/\./g, '_');
|
|
||||||
|
// 处理 namespace:key 格式(兼容原 i18next 用法)
|
||||||
|
if (key.includes(':')) {
|
||||||
|
msgId = key.replace(':', '_').replace(/\./g, '_');
|
||||||
|
}
|
||||||
|
|
||||||
// 先尝试直接查找 key
|
// 先尝试直接查找 key
|
||||||
let message = getMessage(msgId);
|
let message = getMessage(msgId);
|
||||||
@@ -66,3 +70,11 @@ export function useI18n(namespace?: string | string[]) {
|
|||||||
isLoaded: true,
|
isLoaded: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预加载命名空间(无操作,兼容 useLazyTranslation)
|
||||||
|
*/
|
||||||
|
export async function preloadNamespaces(_namespaces: string[]): Promise<void> {
|
||||||
|
// chrome.i18n 是同步的,无需预加载
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,35 @@
|
|||||||
* Chrome 标签页相关工具函数
|
* 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 '';
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 在新标签页中打开扩展页面
|
* 在新标签页中打开扩展页面
|
||||||
* @param page - 扩展页面路径(如 'popup.html')
|
* @param page - 扩展页面路径(如 'popup.html')
|
||||||
@@ -21,3 +50,28 @@ export async function openExtensionPage(
|
|||||||
console.error('打开扩展页面失败:', error);
|
console.error('打开扩展页面失败:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 确保内容脚本已注入
|
||||||
|
*/
|
||||||
|
export async function ensureContentScriptInjected(): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const tab = await getActiveTab();
|
||||||
|
if (!tab?.id) return false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,3 +11,21 @@ export async function copyTextToClipboard(text: string): Promise<boolean> {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 复制图片到剪贴板
|
||||||
|
* @param blob 要复制的图片
|
||||||
|
* @returns Promise<boolean> 是否复制成功
|
||||||
|
*/
|
||||||
|
export async function copyImageToClipboard(blob: Blob): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.write([
|
||||||
|
new ClipboardItem({
|
||||||
|
'image/png': blob,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
import type { PageType } from '@/types/storage';
|
import type { PageType } from '@/types/storage';
|
||||||
|
|
||||||
interface ContextMenuItemConfig {
|
export interface ContextMenuItemConfig {
|
||||||
id: string;
|
id: string;
|
||||||
title: string;
|
title: string;
|
||||||
contexts: [`${chrome.contextMenus.ContextType}`, ...`${chrome.contextMenus.ContextType}`[]];
|
contexts: [`${chrome.contextMenus.ContextType}`, ...`${chrome.contextMenus.ContextType}`[]];
|
||||||
parentId?: string;
|
parentId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ContextMenuClickedInfo {
|
export interface ContextMenuClickedInfo {
|
||||||
featureKey: PageType;
|
featureKey: PageType;
|
||||||
payload: string;
|
payload: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ParseResult {
|
export interface ParseResult {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
data?: ContextMenuClickedInfo;
|
data?: ContextMenuClickedInfo;
|
||||||
error?: string;
|
error?: string;
|
||||||
@@ -25,7 +25,6 @@ export const MAX_PAYLOAD_LENGTH = 10000;
|
|||||||
/** 菜单项 ID 到 PageType 的映射(仅处理非常规映射) */
|
/** 菜单项 ID 到 PageType 的映射(仅处理非常规映射) */
|
||||||
const MENU_ID_TO_PAGE_TYPE: Record<string, PageType> = {
|
const MENU_ID_TO_PAGE_TYPE: Record<string, PageType> = {
|
||||||
'qrCode-page': 'qrCode',
|
'qrCode-page': 'qrCode',
|
||||||
'qrCode-image': 'qrCode',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -78,12 +77,6 @@ export const CONTEXT_MENU_CONFIGS: ContextMenuItemConfig[] = [
|
|||||||
contexts: [chrome.contextMenus.ContextType.PAGE],
|
contexts: [chrome.contextMenus.ContextType.PAGE],
|
||||||
parentId: PARENT_MENU_ID,
|
parentId: PARENT_MENU_ID,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
id: 'qrCode-image',
|
|
||||||
title: '🖼️ 解析图片二维码',
|
|
||||||
contexts: [chrome.contextMenus.ContextType.IMAGE],
|
|
||||||
parentId: PARENT_MENU_ID,
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
|
|
||||||
export function createAllContextMenus(): void {
|
export function createAllContextMenus(): void {
|
||||||
@@ -103,14 +96,6 @@ export function parseContextMenuClick(
|
|||||||
): ParseResult {
|
): ParseResult {
|
||||||
const featureKey = getMenuPageType(menuItemId);
|
const featureKey = getMenuPageType(menuItemId);
|
||||||
|
|
||||||
// 处理图片 URL(仅 qrCode-image 菜单项,右键点击图片时)
|
|
||||||
if (menuItemId === 'qrCode-image' && info.srcUrl) {
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
data: { featureKey, payload: info.srcUrl },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (info.selectionText) {
|
if (info.selectionText) {
|
||||||
const text = info.selectionText;
|
const text = info.selectionText;
|
||||||
|
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ export function formatJson(text: string, options: JsonFormatOptions): JsonFormat
|
|||||||
/**
|
/**
|
||||||
* JSON 压缩结果
|
* JSON 压缩结果
|
||||||
*/
|
*/
|
||||||
interface JsonMinifyResult {
|
export interface JsonMinifyResult {
|
||||||
/** 压缩后的 JSON 字符串 */
|
/** 压缩后的 JSON 字符串 */
|
||||||
minified: string;
|
minified: string;
|
||||||
/** 原始输入的字节大小 */
|
/** 原始输入的字节大小 */
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* JSON 转 TOML 转换结果
|
* JSON 转 TOML 转换结果
|
||||||
*/
|
*/
|
||||||
interface JsonToTomlResult {
|
export interface JsonToTomlResult {
|
||||||
/** 转换后的 TOML 字符串 */
|
/** 转换后的 TOML 字符串 */
|
||||||
output: string;
|
output: string;
|
||||||
/** 原始输入的字节大小 */
|
/** 原始输入的字节大小 */
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* JSON 转 YAML 转换结果
|
* JSON 转 YAML 转换结果
|
||||||
*/
|
*/
|
||||||
interface JsonToYamlResult {
|
export interface JsonToYamlResult {
|
||||||
/** 转换后的 YAML 字符串 */
|
/** 转换后的 YAML 字符串 */
|
||||||
output: string;
|
output: string;
|
||||||
/** 原始输入的字节大小 */
|
/** 原始输入的字节大小 */
|
||||||
|
|||||||
@@ -4,13 +4,13 @@
|
|||||||
|
|
||||||
import { getMessage } from '@/utils/chromeI18n';
|
import { getMessage } from '@/utils/chromeI18n';
|
||||||
|
|
||||||
interface JwtHeader {
|
export interface JwtHeader {
|
||||||
alg: string;
|
alg: string;
|
||||||
typ?: string;
|
typ?: string;
|
||||||
[key: string]: unknown;
|
[key: string]: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface JwtPayload {
|
export interface JwtPayload {
|
||||||
iss?: string;
|
iss?: string;
|
||||||
sub?: string;
|
sub?: string;
|
||||||
aud?: string | string[];
|
aud?: string | string[];
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import QrScanner from 'qr-scanner';
|
import QrScanner from 'qr-scanner';
|
||||||
|
|
||||||
interface QrCodeParseResult {
|
export interface QrCodeParseResult {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
data?: string;
|
data?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
|
|||||||
@@ -224,7 +224,7 @@ async function runCleanScript(
|
|||||||
return { success: false, error: 'No result returned' };
|
return { success: false, error: 'No result returned' };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function injectClearLocalStorage(tabId: number): Promise<StorageCleanResult> {
|
export async function injectClearLocalStorage(tabId: number): Promise<StorageCleanResult> {
|
||||||
return runCleanScript(
|
return runCleanScript(
|
||||||
tabId,
|
tabId,
|
||||||
() => {
|
() => {
|
||||||
@@ -236,7 +236,7 @@ async function injectClearLocalStorage(tabId: number): Promise<StorageCleanResul
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function injectClearSessionStorage(tabId: number): Promise<StorageCleanResult> {
|
export async function injectClearSessionStorage(tabId: number): Promise<StorageCleanResult> {
|
||||||
return runCleanScript(
|
return runCleanScript(
|
||||||
tabId,
|
tabId,
|
||||||
() => {
|
() => {
|
||||||
@@ -248,7 +248,7 @@ async function injectClearSessionStorage(tabId: number): Promise<StorageCleanRes
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function injectClearIndexedDB(tabId: number): Promise<StorageCleanResult> {
|
export async function injectClearIndexedDB(tabId: number): Promise<StorageCleanResult> {
|
||||||
return runCleanScript(
|
return runCleanScript(
|
||||||
tabId,
|
tabId,
|
||||||
async () => {
|
async () => {
|
||||||
@@ -292,7 +292,7 @@ async function injectClearIndexedDB(tabId: number): Promise<StorageCleanResult>
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function injectClearCacheStorage(tabId: number): Promise<StorageCleanResult> {
|
export async function injectClearCacheStorage(tabId: number): Promise<StorageCleanResult> {
|
||||||
return runCleanScript(
|
return runCleanScript(
|
||||||
tabId,
|
tabId,
|
||||||
async () => {
|
async () => {
|
||||||
@@ -309,7 +309,7 @@ async function injectClearCacheStorage(tabId: number): Promise<StorageCleanResul
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function injectUnregisterServiceWorkers(tabId: number): Promise<StorageCleanResult> {
|
export async function injectUnregisterServiceWorkers(tabId: number): Promise<StorageCleanResult> {
|
||||||
return runCleanScript(
|
return runCleanScript(
|
||||||
tabId,
|
tabId,
|
||||||
async () => {
|
async () => {
|
||||||
@@ -381,3 +381,10 @@ export function formatCleaningResult(
|
|||||||
|
|
||||||
return t('storageCleaner:cleanedSummary', { items: parts.join(', ') });
|
return t('storageCleaner:cleanedSummary', { items: parts.join(', ') });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isEmptyResult(result: CleaningResult): boolean {
|
||||||
|
const values = Object.values(result).filter(
|
||||||
|
(r): r is StorageCleanResult => r?.success === true && r.count > 0,
|
||||||
|
);
|
||||||
|
return values.length === 0;
|
||||||
|
}
|
||||||
|
|||||||
@@ -90,3 +90,10 @@ export async function saveContextMenuData(
|
|||||||
};
|
};
|
||||||
await storageUtil.set(STORAGE_KEY, pendingData);
|
await storageUtil.set(STORAGE_KEY, pendingData);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除右键菜单待处理数据
|
||||||
|
*/
|
||||||
|
export async function clearContextMenuData(): Promise<void> {
|
||||||
|
await storageUtil.remove(STORAGE_KEY);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* useDebounce Hook - 防抖值
|
||||||
|
*
|
||||||
|
* @param value - 需要防抖的值
|
||||||
|
* @param delay - 延迟时间(毫秒)
|
||||||
|
* @returns 防抖后的值
|
||||||
|
*/
|
||||||
|
export function useDebounce<T>(value: T, delay: number): T {
|
||||||
|
const [debouncedValue, setDebouncedValue] = useState<T>(value);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
setDebouncedValue(value);
|
||||||
|
}, delay);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
};
|
||||||
|
}, [value, delay]);
|
||||||
|
|
||||||
|
return debouncedValue;
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import '@testing-library/jest-dom';
|
import '@testing-library/jest-dom';
|
||||||
import { afterEach, beforeEach, vi } from 'vitest';
|
import { afterEach, beforeEach, vi } from 'vitest';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import zhMessages from './public/_locales/zh_CN/messages.json';
|
import zhMessages from './public/_locales/zh/messages.json';
|
||||||
|
|
||||||
// Type assertion to allow string indexing
|
// Type assertion to allow string indexing
|
||||||
const zhMessagesMap = zhMessages as Record<string, { message: string }>;
|
const zhMessagesMap = zhMessages as Record<string, { message: string }>;
|
||||||
@@ -152,6 +152,13 @@ const webExtensionMock = {
|
|||||||
getAll: vi.fn().mockResolvedValue([]),
|
getAll: vi.fn().mockResolvedValue([]),
|
||||||
remove: vi.fn().mockResolvedValue(undefined),
|
remove: vi.fn().mockResolvedValue(undefined),
|
||||||
},
|
},
|
||||||
|
alarms: {
|
||||||
|
create: vi.fn().mockResolvedValue(undefined),
|
||||||
|
onAlarm: {
|
||||||
|
addListener: vi.fn(),
|
||||||
|
removeListener: vi.fn(),
|
||||||
|
},
|
||||||
|
},
|
||||||
contextMenus: {
|
contextMenus: {
|
||||||
create: vi.fn(),
|
create: vi.fn(),
|
||||||
onClicked: {
|
onClicked: {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { defineWebExtConfig } from 'wxt';
|
import { defineWebExtConfig } from 'wxt';
|
||||||
|
|
||||||
export default defineWebExtConfig({
|
export default defineWebExtConfig({
|
||||||
startUrls: ['https://www.bing.com', 'chrome://extensions/'],
|
startUrls: ['https://www.baidu.com', 'chrome://extensions/'],
|
||||||
chromiumArgs: ['chrome://extensions/'],
|
chromiumArgs: ['chrome://extensions/'],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ export default defineConfig({
|
|||||||
name: 'Testing Tool',
|
name: 'Testing Tool',
|
||||||
description: 'A tool for testing web applications.',
|
description: 'A tool for testing web applications.',
|
||||||
version_name: undefined,
|
version_name: undefined,
|
||||||
default_locale: 'zh_CN',
|
default_locale: 'zh',
|
||||||
permissions: [
|
permissions: [
|
||||||
'storage',
|
'storage',
|
||||||
'unlimitedStorage',
|
'unlimitedStorage',
|
||||||
@@ -56,22 +56,11 @@ export default defineConfig({
|
|||||||
'cookies',
|
'cookies',
|
||||||
'sidePanel',
|
'sidePanel',
|
||||||
'contextMenus',
|
'contextMenus',
|
||||||
|
'alarms',
|
||||||
],
|
],
|
||||||
host_permissions: ['<all_urls>'],
|
host_permissions: ['<all_urls>'],
|
||||||
icons: {
|
|
||||||
'16': 'icon/16.png',
|
|
||||||
'32': 'icon/32.png',
|
|
||||||
'48': 'icon/48.png',
|
|
||||||
'96': 'icon/96.png',
|
|
||||||
'128': 'icon/128.png',
|
|
||||||
},
|
|
||||||
action: {
|
action: {
|
||||||
default_title: '__MSG_appName__',
|
default_title: '__MSG_appName__',
|
||||||
default_icon: {
|
|
||||||
'16': 'icon/16.png',
|
|
||||||
'32': 'icon/32.png',
|
|
||||||
'48': 'icon/48.png',
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
side_panel: {
|
side_panel: {
|
||||||
default_path: 'entrypoints/sidepanel/index.html',
|
default_path: 'entrypoints/sidepanel/index.html',
|
||||||
|
|||||||