refactor: reorganize directory structure into src/
Move all source code directories into src/ for cleaner project structure: - pages/, components/, utils/, config/, providers/, types/, lib/, assets/, entrypoints/ → src/ - Use WXT srcDir config to resolve @/ alias to src/ - Update tsconfig, vitest, eslint, tailwind configs - Remove scattered README.md files from subdirectories - Update documentation (AGENTS.md, CODING_STANDARDS.md, README.md) - Fix pre-existing lint error in RouterProvider.tsx Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,253 @@
|
||||
import { Image as ImageIcon, Trash2, Upload } from 'lucide-react';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import DecodeResultPaper from '@/components/DecodeResultPaper';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { downloadBlob, formatFileSize } from '@/utils/base64Converter';
|
||||
import { useStorageState } from '@/utils/useStorageState';
|
||||
import type { Base64ConvertDirection } from '@/types/storage';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import { useBase64Converter } from './useBase64Converter';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const isValidDirection = (val: unknown): val is Base64ConvertDirection =>
|
||||
val === 'encode' || val === 'decode';
|
||||
|
||||
interface Base64ConverterSectionProps {
|
||||
mode: 'file' | 'image';
|
||||
}
|
||||
|
||||
export default function Base64ConverterSection({ mode }: Base64ConverterSectionProps) {
|
||||
const { t } = useI18n('base64Converter');
|
||||
|
||||
const [direction, setDirection] = useStorageState(
|
||||
`base64Converter/${mode}Mode/direction`,
|
||||
'encode',
|
||||
isValidDirection,
|
||||
);
|
||||
|
||||
const {
|
||||
result,
|
||||
info,
|
||||
isLoading,
|
||||
isDragging,
|
||||
setIsDragging,
|
||||
fileInputRef,
|
||||
encodeError,
|
||||
decodeInput,
|
||||
setDecodeInput,
|
||||
decoded,
|
||||
decodeError,
|
||||
decodedFileName,
|
||||
setCustomFileName,
|
||||
resetAll,
|
||||
safeFileSelect,
|
||||
maxFileSizeStr,
|
||||
} = useBase64Converter({ mode });
|
||||
|
||||
const handleDirectionChange = (next: Base64ConvertDirection) => {
|
||||
if (!next || next === direction) return;
|
||||
resetAll();
|
||||
setDirection(next);
|
||||
};
|
||||
|
||||
const handleDownload = () => {
|
||||
if (decoded) downloadBlob(decoded.blob, decodedFileName);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col space-y-4">
|
||||
<div className="flex h-11 items-center px-1.5 bg-secondary/40 rounded-xl border border-border/60 w-fit">
|
||||
<SwitchButtonGroup
|
||||
value={direction}
|
||||
options={[
|
||||
{ value: 'encode', label: t('encode') },
|
||||
{ value: 'decode', label: t('decode') },
|
||||
]}
|
||||
onChange={handleDirectionChange}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{direction === 'encode' ? (
|
||||
<div className="flex flex-col space-y-4">
|
||||
<div
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(true);
|
||||
}}
|
||||
onDragLeave={() => setIsDragging(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
const file = e.dataTransfer.files[0];
|
||||
if (file) safeFileSelect(file);
|
||||
}}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center min-h-[190px] border-2 border-dashed rounded-2xl p-8 cursor-pointer',
|
||||
isDragging
|
||||
? 'border-primary bg-primary/10'
|
||||
: info
|
||||
? 'border-primary/60 bg-primary/5'
|
||||
: 'border-border bg-muted/40 hover:border-primary/80 hover:bg-muted/70',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept={mode === 'image' ? 'image/*' : undefined}
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) safeFileSelect(file);
|
||||
}}
|
||||
/>
|
||||
{isLoading ? (
|
||||
<div className="w-9 h-9 border-3 border-primary/20 border-t-primary rounded-full animate-spin" />
|
||||
) : info ? (
|
||||
<div className="flex flex-col items-center gap-1.5 text-center w-full">
|
||||
{mode === 'image' && result && (
|
||||
<div className="relative p-1 border border-border bg-background rounded-lg shadow-sm mb-1 max-w-[180px] overflow-hidden">
|
||||
<img
|
||||
src={result.output}
|
||||
alt="preview"
|
||||
className="max-h-32 w-full object-contain rounded"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Upload className={cn('w-8 h-8 text-primary')} />
|
||||
<span className="text-sm font-bold text-foreground/90 max-w-[280px] truncate">
|
||||
{info.name}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground/80 font-mono tabular-nums">
|
||||
{formatFileSize(info.size)} · {info.type}
|
||||
</span>
|
||||
<span className="text-[11px] font-medium text-primary/80 mt-1">
|
||||
{t('clickOrDropToReplace')}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-1.5 text-center">
|
||||
{mode === 'image' ? (
|
||||
<ImageIcon className="w-8 h-8 text-muted-foreground/60" />
|
||||
) : (
|
||||
<Upload className="w-8 h-8 text-muted-foreground/60" />
|
||||
)}
|
||||
<span className="text-xs font-bold text-foreground/80">
|
||||
{mode === 'image' ? t('clickOrDropToImage') : t('clickOrDropToFile')}
|
||||
</span>
|
||||
<span className="text-[10px] font-medium text-muted-foreground/60">
|
||||
{t('maxFileSize', { max: maxFileSizeStr })}
|
||||
</span>
|
||||
{mode === 'image' && (
|
||||
<span className="text-[10px] font-medium text-muted-foreground/50">
|
||||
{t('supportedFormats')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{encodeError && (
|
||||
<div className="p-3.5 bg-destructive/10 border border-destructive/20 rounded-xl text-xs font-semibold text-destructive">
|
||||
{encodeError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="p-4 rounded-2xl bg-card border border-border shadow-sm flex flex-col space-y-3">
|
||||
<div className="flex justify-between items-center select-none">
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
|
||||
{t('base64Output')}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<CopyButton
|
||||
text={result.rawBase64}
|
||||
tooltip={t('copyRaw')}
|
||||
className="h-6 px-2 rounded-md border text-[10px] font-bold"
|
||||
/>
|
||||
<CopyButton
|
||||
text={result.output}
|
||||
tooltip={t('copyDataUri')}
|
||||
className="h-6 px-2 rounded-md border text-[10px] font-bold"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<TextInputArea
|
||||
readOnly
|
||||
value={
|
||||
result.output.length > 2000
|
||||
? `${result.output.substring(0, 2000)}...`
|
||||
: result.output
|
||||
}
|
||||
showClear={false}
|
||||
minRows={4}
|
||||
/>
|
||||
<div className="flex items-center justify-between font-mono text-[10px] text-muted-foreground/70 select-none pt-1">
|
||||
<div className="flex gap-4 items-center tabular-nums">
|
||||
<span>
|
||||
{t('originalSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatFileSize(result.originalBytes)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-border/60">|</span>
|
||||
<span>
|
||||
{t('encodedSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatFileSize(result.outputBytes)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={resetAll}
|
||||
className="h-7 rounded-md text-muted-foreground hover:text-destructive text-[11px] gap-1 px-2"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
{t('clear')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col space-y-4">
|
||||
<TextInputArea
|
||||
placeholder={t('decodeBase64Placeholder')}
|
||||
value={decodeInput}
|
||||
onChange={setDecodeInput}
|
||||
externalError={decodeError || undefined}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={6}
|
||||
onClear={resetAll}
|
||||
/>
|
||||
{decoded && (
|
||||
<DecodeResultPaper
|
||||
title={mode === 'image' ? t('decodedImageOutput') : t('decodedFileOutput')}
|
||||
mimeType={decoded.mimeType}
|
||||
blobSize={decoded.blob.size}
|
||||
fileName={decodedFileName}
|
||||
onFileNameChange={setCustomFileName}
|
||||
onDownload={handleDownload}
|
||||
>
|
||||
{mode === 'image' && (
|
||||
<div className="relative p-1.5 border border-border bg-background dark:bg-muted/10 rounded-xl max-w-[220px] mb-3 overflow-hidden shadow-sm">
|
||||
<img
|
||||
src={`data:${decoded.mimeType};base64,${decoded.rawBase64}`}
|
||||
alt="decoded preview"
|
||||
className="max-h-40 w-full rounded-lg object-contain bg-[linear-gradient(45deg,#ccc_25%,transparent_25%),linear-gradient(-45deg,#ccc_25%,transparent_25%),linear-gradient(45deg,transparent_75%,#ccc_75%),linear-gradient(-45deg,transparent_75%,#ccc_75%)] bg-[size:10px_10px] bg-[position:0_0,0_5px,5px_-5px,-5px_0] dark:bg-none"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</DecodeResultPaper>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import { base64ToText, textToBase64 } from '@/utils/base64Converter';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
const IMAGE_DATA_URI_PATTERN = /^\s*data:image\//i;
|
||||
|
||||
const ERROR_MESSAGE_TO_I18N: Record<string, string> = {
|
||||
'Invalid Base64 string': 'invalidBase64',
|
||||
'Input appears to be binary data (e.g. an image). Please use the Image tab instead.':
|
||||
'binaryDataDetected',
|
||||
};
|
||||
|
||||
interface TextModeProps {
|
||||
onSwitchToImageMode?: () => void;
|
||||
}
|
||||
|
||||
export default function TextMode({ onSwitchToImageMode }: TextModeProps = {}) {
|
||||
const { t } = useI18n('base64Converter');
|
||||
|
||||
// 1. 纯净的核心源状态机:只保留输入源和转换方向
|
||||
const [input, setInput] = useState('');
|
||||
const [debouncedInput, setDebouncedInput] = useState('');
|
||||
const [direction, setDirection] = useState<'encode' | 'decode'>('encode');
|
||||
|
||||
// 2. 文本高频敲击防抖大闸:斩断频繁进行文本转 Base64 带来的 CPU 计算过热
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setDebouncedInput(input);
|
||||
}, 200);
|
||||
return () => clearTimeout(handle);
|
||||
}, [input]);
|
||||
|
||||
// 3. 右键联动数据上下文:优雅原地合并受控状态
|
||||
const handleContextMenuData = useCallback((payload: string) => {
|
||||
setInput(payload);
|
||||
setDebouncedInput(payload);
|
||||
setDirection('decode');
|
||||
}, []);
|
||||
|
||||
useContextMenuData({ featureKey: 'base64Converter', onData: handleContextMenuData });
|
||||
|
||||
// 💡 4. 贯彻方案 A(彻底消灭 setOutput / setError):
|
||||
// 让所有的转化逻辑、类型安全校验在 useMemo 内存管道中单次渲染一气呵成!
|
||||
const conversionPipeline = useMemo(() => {
|
||||
const trimmed = debouncedInput.trim();
|
||||
if (!trimmed) return { output: '', error: null };
|
||||
|
||||
try {
|
||||
if (direction === 'encode') {
|
||||
const result = textToBase64(debouncedInput);
|
||||
return { output: result.output, error: null };
|
||||
} else {
|
||||
const decoded = base64ToText(trimmed);
|
||||
return { output: decoded, error: null };
|
||||
}
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : '';
|
||||
const i18nKey = ERROR_MESSAGE_TO_I18N[message];
|
||||
return {
|
||||
output: '',
|
||||
error: i18nKey ? t(i18nKey) : message || t('conversionFailed'),
|
||||
};
|
||||
}
|
||||
}, [debouncedInput, direction, t]);
|
||||
|
||||
const output = conversionPipeline.output;
|
||||
const error = conversionPipeline.error;
|
||||
|
||||
const placeholder =
|
||||
direction === 'encode' ? t('textInputPlaceholder') : t('base64InputPlaceholder');
|
||||
const outputLabel = direction === 'encode' ? t('base64Output') : t('textOutput');
|
||||
|
||||
const showImageHint = useMemo(
|
||||
() => direction === 'decode' && IMAGE_DATA_URI_PATTERN.test(input),
|
||||
[direction, input],
|
||||
);
|
||||
|
||||
const handleDirectionChange = (value: 'encode' | 'decode') => {
|
||||
if (value === direction) return;
|
||||
setDirection(value);
|
||||
setInput('');
|
||||
setDebouncedInput('');
|
||||
};
|
||||
|
||||
const handleClear = () => {
|
||||
setInput('');
|
||||
setDebouncedInput('');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col space-y-4">
|
||||
{/* 受控方向切流中枢 */}
|
||||
<div className="flex h-11 items-center px-1.5 bg-secondary/40 rounded-xl border border-border/60 w-fit">
|
||||
<SwitchButtonGroup
|
||||
value={direction}
|
||||
options={[
|
||||
{ value: 'encode', label: t('encode') },
|
||||
{ value: 'decode', label: t('decode') },
|
||||
]}
|
||||
onChange={handleDirectionChange}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 高性能受控文本输入端 */}
|
||||
<TextInputArea
|
||||
placeholder={placeholder}
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
externalError={error || undefined} // 💡 流式异常大闸动态注入
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={5}
|
||||
maxRows={10}
|
||||
onClear={handleClear}
|
||||
/>
|
||||
|
||||
{/* 图片 URI 类型劫持警告引导区:
|
||||
- 💡 修复点:彻底废除原生亮色硬编码 hover:bg-blue-100 类名,
|
||||
- 完美向全站 shadcn 暗黑生态看齐,采用标准的 bg-primary/10 混合变体。
|
||||
*/}
|
||||
{showImageHint && (
|
||||
<div className="flex items-center justify-between p-3.5 rounded-xl bg-primary/10 border border-primary/20">
|
||||
<span className="text-xs font-semibold text-primary tracking-tight">
|
||||
{t('imageDataUriHint')}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onSwitchToImageMode}
|
||||
className="h-7 rounded-md text-xs font-bold text-primary hover:text-primary hover:bg-primary/20 dark:hover:bg-primary/10 px-2.5"
|
||||
>
|
||||
{t('switchToImageMode')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 5. 编码/解码核心数据承载流卡片 */}
|
||||
{output && (
|
||||
<div className="p-4 rounded-2xl bg-card border border-border shadow-sm flex flex-col space-y-3">
|
||||
<div className="flex justify-between items-center select-none">
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
|
||||
{outputLabel}
|
||||
</span>
|
||||
<CopyButton
|
||||
text={output}
|
||||
className="h-6 px-2 rounded-md border text-[10px] font-bold"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<TextInputArea
|
||||
readOnly
|
||||
value={output.length > 2000 ? `${output.substring(0, 2000)}...` : output}
|
||||
showClear={false}
|
||||
minRows={4}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import TextMode from '../TextMode';
|
||||
|
||||
// Mock CopyButton
|
||||
vi.mock('@/components/CopyButton', () => ({
|
||||
CopyButton: ({ text }: { text: string }) => <button data-testid="copy-button">{text}</button>,
|
||||
default: ({ text }: { text: string }) => <button data-testid="copy-button">{text}</button>,
|
||||
}));
|
||||
|
||||
describe('TextMode', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('应该渲染编码/解码切换按钮', () => {
|
||||
render(<TextMode />);
|
||||
expect(screen.getByText('编码')).toBeInTheDocument();
|
||||
expect(screen.getByText('解码')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('应该渲染输入框和转换按钮', () => {
|
||||
render(<TextMode />);
|
||||
expect(screen.getByPlaceholderText('输入需要编码为 Base64 的文本...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('应该将文本编码为 Base64', async () => {
|
||||
render(<TextMode />);
|
||||
const input = screen.getByPlaceholderText('输入需要编码为 Base64 的文本...');
|
||||
fireEvent.change(input, { target: { value: 'Hello' } });
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Base64 编码结果')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByRole('button', { name: 'SGVsbG8=' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('应该解码 Base64 文本', async () => {
|
||||
render(<TextMode />);
|
||||
|
||||
// 切换到解码模式
|
||||
fireEvent.click(screen.getByText('解码'));
|
||||
|
||||
const input = screen.getByPlaceholderText('输入需要解码的 Base64 字符串...');
|
||||
fireEvent.change(input, { target: { value: 'SGVsbG8=' } });
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('解码文本结果')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByRole('button', { name: 'Hello' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('应该对无效 Base64 显示错误', async () => {
|
||||
render(<TextMode />);
|
||||
|
||||
// 切换到解码模式
|
||||
fireEvent.click(screen.getByText('解码'));
|
||||
|
||||
const input = screen.getByPlaceholderText('输入需要解码的 Base64 字符串...');
|
||||
fireEvent.change(input, { target: { value: 'invalid!!!' } });
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Base64 字符串无效')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('切换方向时应该清除输出', async () => {
|
||||
render(<TextMode />);
|
||||
|
||||
// 先编码
|
||||
const input = screen.getByPlaceholderText('输入需要编码为 Base64 的文本...');
|
||||
fireEvent.change(input, { target: { value: 'Hello' } });
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: 'SGVsbG8=' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// 切换方向
|
||||
fireEvent.click(screen.getByText('解码'));
|
||||
|
||||
// 输出应该被清除
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByRole('button', { name: 'SGVsbG8=' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('点击清除按钮应该清空所有内容', async () => {
|
||||
render(<TextMode />);
|
||||
|
||||
const input = screen.getByPlaceholderText('输入需要编码为 Base64 的文本...');
|
||||
fireEvent.change(input, { target: { value: 'Hello' } });
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: 'SGVsbG8=' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'textInputArea.clear' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByRole('button', { name: 'SGVsbG8=' })).not.toBeInTheDocument();
|
||||
expect(input).toHaveValue('');
|
||||
});
|
||||
});
|
||||
|
||||
it('解码模式下粘贴图片 data URI 时应该显示切换图像模式的提示', () => {
|
||||
render(<TextMode />);
|
||||
|
||||
fireEvent.click(screen.getByText('解码'));
|
||||
|
||||
const input = screen.getByPlaceholderText('输入需要解码的 Base64 字符串...');
|
||||
fireEvent.change(input, {
|
||||
target: { value: 'data:image/png;base64,iVBORw0KGgo=' },
|
||||
});
|
||||
|
||||
expect(
|
||||
screen.getByText('检测到图片的 data URI,请使用「图像」选项卡进行解码。'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('切换到图像模式')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('粘贴非图片 data URI 时不应该显示图像模式提示', () => {
|
||||
render(<TextMode />);
|
||||
|
||||
fireEvent.click(screen.getByText('解码'));
|
||||
|
||||
const input = screen.getByPlaceholderText('输入需要解码的 Base64 字符串...');
|
||||
fireEvent.change(input, { target: { value: 'SGVsbG8=' } });
|
||||
|
||||
expect(
|
||||
screen.queryByText('检测到图片的 data URI,请使用「图像」选项卡进行解码。'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('点击切换图像模式按钮应该调用 onSwitchToImageMode 回调', () => {
|
||||
const onSwitch = vi.fn();
|
||||
render(<TextMode onSwitchToImageMode={onSwitch} />);
|
||||
|
||||
fireEvent.click(screen.getByText('解码'));
|
||||
const input = screen.getByPlaceholderText('输入需要解码的 Base64 字符串...');
|
||||
fireEvent.change(input, {
|
||||
target: { value: 'data:image/png;base64,iVBORw0KGgo=' },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('切换到图像模式'));
|
||||
expect(onSwitch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('解码模式下对二进制数据应该显示更清晰的错误', async () => {
|
||||
render(<TextMode />);
|
||||
|
||||
fireEvent.click(screen.getByText('解码'));
|
||||
|
||||
const input = screen.getByPlaceholderText('输入需要解码的 Base64 字符串...');
|
||||
fireEvent.change(input, { target: { value: 'iVBORw0KGgo=' } });
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText('输入似乎是二进制数据(如图片)。请切换到「图像」选项卡。'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import Base64ConverterPage from '../index';
|
||||
|
||||
// Mock getEntryPointType
|
||||
vi.mock('@/config/features', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/config/features')>();
|
||||
return {
|
||||
...actual,
|
||||
getEntryPointType: () => 'sidepanel',
|
||||
};
|
||||
});
|
||||
|
||||
// Mock 子组件
|
||||
vi.mock('../TextMode', () => ({
|
||||
default: ({ onSwitchToImageMode }: { onSwitchToImageMode?: () => void }) => (
|
||||
<div data-testid="text-mode">
|
||||
TextMode
|
||||
{onSwitchToImageMode && <button onClick={onSwitchToImageMode}>switchToImage</button>}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock('../Base64ConverterSection', () => ({
|
||||
default: ({ mode }: { mode: string }) => <div data-testid={`${mode}-mode`}>{mode}</div>,
|
||||
}));
|
||||
|
||||
const waitForStorageInit = () =>
|
||||
act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
describe('Base64ConverterPage', () => {
|
||||
it('应该默认渲染文本模式', async () => {
|
||||
render(<Base64ConverterPage />);
|
||||
await waitForStorageInit();
|
||||
expect(screen.getByTestId('text-mode')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('应该渲染模式切换按钮', async () => {
|
||||
render(<Base64ConverterPage />);
|
||||
await waitForStorageInit();
|
||||
expect(screen.getByText('文本')).toBeInTheDocument();
|
||||
expect(screen.getByText('文件')).toBeInTheDocument();
|
||||
expect(screen.getByText('图像')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('切换到文件模式应该渲染 FileMode', async () => {
|
||||
render(<Base64ConverterPage />);
|
||||
await waitForStorageInit();
|
||||
fireEvent.click(screen.getByText('文件'));
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('file-mode')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.queryByTestId('text-mode')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('切换到图像模式应该渲染 ImageMode', async () => {
|
||||
render(<Base64ConverterPage />);
|
||||
await waitForStorageInit();
|
||||
fireEvent.click(screen.getByText('图像'));
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('image-mode')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.queryByTestId('text-mode')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { useStorageState } from '@/utils/useStorageState';
|
||||
import type { Base64ConverterPageMode } from '@/types/storage';
|
||||
import TextMode from './TextMode';
|
||||
import Base64ConverterSection from './Base64ConverterSection'; // ✅ 正确对接全新的一体化大组件
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
|
||||
const VALID_PAGE_MODES: readonly Base64ConverterPageMode[] = ['text', 'file', 'image'];
|
||||
const isValidPageMode = (val: unknown): val is Base64ConverterPageMode =>
|
||||
typeof val === 'string' && (VALID_PAGE_MODES as readonly string[]).includes(val);
|
||||
|
||||
type PageMode = Base64ConverterPageMode;
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useI18n('base64Converter');
|
||||
const [pageMode, setPageMode] = useStorageState(
|
||||
'base64Converter/pageMode',
|
||||
'text',
|
||||
isValidPageMode,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="p-4 w-full flex flex-col space-y-4 min-h-[520px] select-none">
|
||||
<SwitchButtonGroup
|
||||
value={pageMode}
|
||||
options={[
|
||||
{ value: 'text', label: t('base64Converter:textMode') },
|
||||
{ value: 'file', label: t('base64Converter:fileMode') },
|
||||
{ value: 'image', label: t('base64Converter:imageMode') },
|
||||
]}
|
||||
onChange={(value: PageMode) => setPageMode(value)}
|
||||
size="small"
|
||||
className="w-full sm:w-auto"
|
||||
/>
|
||||
|
||||
<div className="w-full pt-1">
|
||||
{pageMode === 'text' && <TextMode onSwitchToImageMode={() => setPageMode('image')} />}
|
||||
{pageMode === 'file' && <Base64ConverterSection mode="file" />}
|
||||
{pageMode === 'image' && <Base64ConverterSection mode="image" />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import type { FileToBase64Result } from '@/utils/base64Converter';
|
||||
import {
|
||||
base64ToBlob,
|
||||
fileToBase64,
|
||||
isFileSizeValid,
|
||||
isSupportedImageExtension,
|
||||
isSupportedImageType,
|
||||
MAX_FILE_SIZE,
|
||||
} from '@/utils/base64Converter';
|
||||
|
||||
interface FileInfo {
|
||||
name: string;
|
||||
size: number;
|
||||
type: string;
|
||||
}
|
||||
|
||||
interface UseBase64ConverterProps {
|
||||
mode: 'file' | 'image';
|
||||
}
|
||||
|
||||
export function useBase64Converter({ mode }: UseBase64ConverterProps) {
|
||||
const { t } = useI18n('base64Converter');
|
||||
|
||||
const [result, setResult] = useState<FileToBase64Result | null>(null);
|
||||
const [info, setInfo] = useState<FileInfo | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const cancelRef = useRef(false);
|
||||
|
||||
const [decodeInput, setDecodeInput] = useState('');
|
||||
const [debouncedDecodeInput, setDebouncedDecodeInput] = useState('');
|
||||
const [encodeError, setEncodeError] = useState<string | null>(null);
|
||||
const [customFileName, setCustomFileName] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setDebouncedDecodeInput(decodeInput);
|
||||
}, 250);
|
||||
return () => clearTimeout(handle);
|
||||
}, [decodeInput]);
|
||||
|
||||
const resetAll = useCallback(() => {
|
||||
cancelRef.current = true;
|
||||
setResult(null);
|
||||
setInfo(null);
|
||||
setIsLoading(false);
|
||||
setDecodeInput('');
|
||||
setDebouncedDecodeInput('');
|
||||
setCustomFileName('');
|
||||
setEncodeError(null);
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
}, []);
|
||||
|
||||
const handleFileSelect = useCallback(
|
||||
async (file: File) => {
|
||||
cancelRef.current = false;
|
||||
setEncodeError(null);
|
||||
setResult(null);
|
||||
setInfo(null);
|
||||
|
||||
if (!isFileSizeValid(file.size)) {
|
||||
setEncodeError(t('fileSizeExceeded', { max: `${MAX_FILE_SIZE / 1024 / 1024} MB` }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
mode === 'image' &&
|
||||
!isSupportedImageType(file.type) &&
|
||||
!isSupportedImageExtension(file.name)
|
||||
) {
|
||||
setEncodeError(t('unsupportedImageType'));
|
||||
return;
|
||||
}
|
||||
|
||||
setInfo({
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
type: file.type || 'application/octet-stream',
|
||||
});
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const res = await fileToBase64(file);
|
||||
if (!cancelRef.current) setResult(res);
|
||||
} catch (e) {
|
||||
if (!cancelRef.current) {
|
||||
setEncodeError(e instanceof Error ? e.message : t('conversionFailed'));
|
||||
}
|
||||
} finally {
|
||||
if (!cancelRef.current) setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[mode, t],
|
||||
);
|
||||
|
||||
const safeFileSelect = useCallback(
|
||||
(file: File) => {
|
||||
handleFileSelect(file).catch((err) => {
|
||||
console.error(`Base64 [${mode}] pipeline crash:`, err);
|
||||
});
|
||||
},
|
||||
[handleFileSelect, mode],
|
||||
);
|
||||
|
||||
const decodePipeline = useMemo(() => {
|
||||
const cleanedInput = debouncedDecodeInput.replace(/^data:image\/[a-z+]+;base64,/i, '').trim();
|
||||
if (!cleanedInput) return { decoded: null, error: null };
|
||||
|
||||
try {
|
||||
const res = base64ToBlob(cleanedInput);
|
||||
return { decoded: res, error: null };
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : '';
|
||||
return {
|
||||
decoded: null,
|
||||
error: message === 'Invalid Base64 string' ? t('invalidBase64') : t('conversionFailed'),
|
||||
};
|
||||
}
|
||||
}, [debouncedDecodeInput, t]);
|
||||
|
||||
const decoded = decodePipeline.decoded;
|
||||
const decodeError = decodePipeline.error;
|
||||
|
||||
const decodedFileName = useMemo(() => {
|
||||
if (customFileName) return customFileName;
|
||||
if (decoded) return `decoded${decoded.suggestedExtension}`;
|
||||
return '';
|
||||
}, [customFileName, decoded]);
|
||||
|
||||
// 💡 托管最大文件体积字符串算子,清除下游引入风险
|
||||
const maxFileSizeStr = `${MAX_FILE_SIZE / 1024 / 1024} MB`;
|
||||
|
||||
return {
|
||||
result,
|
||||
info,
|
||||
isLoading,
|
||||
isDragging,
|
||||
setIsDragging,
|
||||
fileInputRef,
|
||||
encodeError,
|
||||
decodeInput,
|
||||
setDecodeInput,
|
||||
decoded,
|
||||
decodeError,
|
||||
decodedFileName,
|
||||
setCustomFileName,
|
||||
resetAll,
|
||||
safeFileSelect,
|
||||
maxFileSizeStr,
|
||||
};
|
||||
}
|
||||
@@ -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';
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useRouter } from '@/providers/RouterProvider';
|
||||
import ToolCard from '@/pages/Dashboard/ToolCard';
|
||||
import { getFeatureByKey } from '@/config/features';
|
||||
import type { PageType } from '@/types/storage';
|
||||
import { useMemo } from 'react';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export default function DashboardPage() {
|
||||
const { navigateTo, visiblePages, pageOrder } = useRouter();
|
||||
const { t } = useI18n(['features']);
|
||||
|
||||
const visibleSet = useMemo(() => new Set<string>(visiblePages), [visiblePages]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'grid grid-cols-1 sm:grid-cols-[repeat(auto-fill,minmax(290px,1fr))] auto-rows-auto gap-3.5 p-3.5 w-full h-auto',
|
||||
'select-none',
|
||||
)}
|
||||
>
|
||||
{pageOrder.map((key) => {
|
||||
if (!visibleSet.has(key)) return null;
|
||||
|
||||
const feature = getFeatureByKey(key);
|
||||
if (!feature?.themeColorKey || feature.icon == null) return null;
|
||||
|
||||
return (
|
||||
<ToolCard
|
||||
key={key}
|
||||
title={t(feature.labelKey)}
|
||||
description={t(feature.descriptionKey)}
|
||||
colorKey={feature.themeColorKey}
|
||||
icon={feature.icon}
|
||||
onNavigate={() => navigateTo(key as PageType)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { Download, Trash2 } from 'lucide-react';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import { Button } from '@/components/ui/button'; // 💡 1. 全面回归规范:引入原生的 shadcn 原子 Button
|
||||
import { useStorageState } from '@/utils/useStorageState';
|
||||
import type { HtmlToMarkdownPreviewMode } from '@/types/storage';
|
||||
import { downloadMarkdownFile, htmlToMarkdown, SAMPLE_HTML } from '@/utils/htmlToMarkdown';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const isValidPreviewMode = (val: unknown): val is HtmlToMarkdownPreviewMode =>
|
||||
typeof val === 'string' && ['split', 'preview', 'markdown'].includes(val);
|
||||
|
||||
export default function HtmlToMarkdownPage() {
|
||||
const { t } = useI18n('htmlToMarkdown');
|
||||
const [previewMode, setPreviewMode] = useStorageState(
|
||||
'htmlToMarkdown/previewMode',
|
||||
'split' as HtmlToMarkdownPreviewMode,
|
||||
isValidPreviewMode,
|
||||
);
|
||||
const [html, setHtml] = useState(SAMPLE_HTML);
|
||||
|
||||
const result = useMemo(() => htmlToMarkdown(html), [html]);
|
||||
const error = result.hasError ? (result.error ?? null) : null;
|
||||
|
||||
const handleModeChange = useCallback(
|
||||
(newMode: HtmlToMarkdownPreviewMode) => {
|
||||
setPreviewMode(newMode);
|
||||
},
|
||||
[setPreviewMode],
|
||||
);
|
||||
|
||||
const handleClear = useCallback(() => {
|
||||
setHtml('');
|
||||
}, []);
|
||||
|
||||
const handleDownload = useCallback(() => {
|
||||
if (result.markdown) {
|
||||
downloadMarkdownFile(result.markdown, 'converted.md');
|
||||
}
|
||||
}, [result.markdown]);
|
||||
|
||||
const showInput = previewMode !== 'preview';
|
||||
const showOutput = previewMode !== 'markdown';
|
||||
|
||||
return (
|
||||
/* 💡 统一间距尺寸:
|
||||
- 彻底清除多余的 container max-w-7xl 这种网页大边距,
|
||||
- 统一收拢为我们先前在 Dashboard 页、JSON 工具箱制定的 p-4 space-y-4 标准极客桌面规格。
|
||||
*/
|
||||
<div className="p-4 w-full flex flex-col space-y-4 select-none">
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* 工具栏集成区 */}
|
||||
<div className="flex flex-col sm:flex-row gap-3 justify-between items-stretch sm:items-center bg-secondary/40 rounded-xl border border-border/60 px-1.5 py-1.5 sm:h-12">
|
||||
<SwitchButtonGroup
|
||||
value={previewMode}
|
||||
options={[
|
||||
{ value: 'split', label: t('splitMode') },
|
||||
{ value: 'preview', label: t('previewMode') },
|
||||
{ value: 'markdown', label: t('markdownMode') },
|
||||
]}
|
||||
onChange={handleModeChange}
|
||||
size="small"
|
||||
className="w-full sm:w-auto"
|
||||
/>
|
||||
|
||||
<div className="flex gap-2 shrink-0">
|
||||
{/* 2. 重塑下载按钮:接入受控 Button,追加 active 物理微缩放动效 */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDownload}
|
||||
disabled={!result.markdown}
|
||||
className="h-8 rounded-md font-medium text-xs gap-1.5 shadow-sm"
|
||||
>
|
||||
<Download className="h-3.5 w-3.5" />
|
||||
{t('download')}
|
||||
</Button>
|
||||
|
||||
{/* 重塑清空按钮 */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClear}
|
||||
className="h-8 rounded-md font-medium text-xs gap-1.5 shadow-sm text-destructive hover:text-destructive hover:bg-destructive/5 dark:hover:bg-destructive/10 border-input/60"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
{t('clear')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 错误提示:
|
||||
- 💡 核心修复点:将硬编码的 bg-red-50 实色,完美超进化为系统的全自适应透明色变体
|
||||
*/}
|
||||
{error && (
|
||||
<div className="p-3.5 bg-destructive/10 border border-destructive/20 rounded-xl text-destructive text-xs font-semibold tracking-wide">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 双翼/单栏联动面板展示区 */}
|
||||
<div
|
||||
className={cn(
|
||||
'grid gap-4 min-h-[460px] w-full',
|
||||
showInput && showOutput ? 'grid-cols-1 md:grid-cols-2' : 'grid-cols-1',
|
||||
)}
|
||||
>
|
||||
{/* HTML 输入端卡片面板 */}
|
||||
{showInput && (
|
||||
/* 3. 智能聚焦框联动(Focus Ring Clamping):
|
||||
- 外层容器追加 focus-within 变量追踪大闸。
|
||||
- 只要用户用鼠标点击了内部的 textarea,外层整块精巧的圆角大边框会一帧内亮起 primary 系统的深色呼吸发光环,
|
||||
- 这种“全外包裹层框聚焦”的体验极大模仿了本地原生 IDE 的硬核专业体验!
|
||||
*/
|
||||
<div className="border border-border rounded-xl bg-card text-card-foreground shadow-sm overflow-hidden flex flex-col focus-within:ring-1 focus-within:ring-ring focus-within:border-ring">
|
||||
{/* 卡片头部:改用标准的灰色 bg-muted/50 */}
|
||||
<div className="flex h-9 items-center justify-between px-4 bg-muted/50 border-b border-border select-none">
|
||||
<span className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider">
|
||||
{t('inputLabel')}
|
||||
</span>
|
||||
<span className="text-[10px] font-mono text-muted-foreground/60 tabular-nums">
|
||||
{t('charCount', { count: html.length })}
|
||||
</span>
|
||||
</div>
|
||||
<textarea
|
||||
value={html}
|
||||
onChange={(e) => setHtml(e.target.value)}
|
||||
placeholder={t('inputPlaceholder')}
|
||||
className="flex-1 min-h-[380px] p-4 bg-transparent font-mono text-xs leading-relaxed resize-none focus:outline-none text-foreground/90 select-text"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Markdown 输出端卡片面板 */}
|
||||
{showOutput && (
|
||||
<div className="border border-border rounded-xl bg-card text-card-foreground shadow-sm overflow-hidden flex flex-col">
|
||||
<div className="flex h-9 items-center justify-between px-4 bg-muted/50 border-b border-border select-none">
|
||||
<span className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider">
|
||||
{(previewMode as string) === 'markdown'
|
||||
? t('markdownOutputLabel')
|
||||
: t('previewLabel')}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[10px] font-mono text-muted-foreground/60 tabular-nums">
|
||||
{t('charCount', { count: result.markdownLength })}
|
||||
</span>
|
||||
<CopyButton
|
||||
text={result.markdown}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(previewMode as string) === 'markdown' ? (
|
||||
<textarea
|
||||
value={result.markdown}
|
||||
readOnly
|
||||
className="flex-1 min-h-[380px] p-4 font-mono text-xs leading-relaxed resize-none focus:outline-none bg-muted/30 dark:bg-muted/10 text-foreground/80 select-text"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex-1 p-4 min-h-[380px] overflow-auto bg-transparent font-mono text-xs leading-relaxed whitespace-pre-wrap break-all text-foreground/90 select-text">
|
||||
{result.markdown || (
|
||||
<span className="text-muted-foreground/70 italic text-[11px] font-sans">
|
||||
{t('emptyHint')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import React from 'react';
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils'; // 1. 引入标准的 shadcn 工具函数
|
||||
|
||||
export interface DiffNavigatorProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
total: number;
|
||||
/** 0-based index */
|
||||
currentIndex: number;
|
||||
onPrev: () => void;
|
||||
onNext: () => void;
|
||||
}
|
||||
|
||||
export default function DiffNavigator({
|
||||
total,
|
||||
currentIndex,
|
||||
onPrev,
|
||||
onNext,
|
||||
className,
|
||||
...props
|
||||
}: DiffNavigatorProps) {
|
||||
const { t } = useI18n('jsonDiff');
|
||||
|
||||
// 计算当前的边界禁用状态守卫
|
||||
const isFirst = currentIndex <= 0;
|
||||
const isLast = currentIndex >= total - 1;
|
||||
|
||||
// 2. 空状态面板:对齐 shadcn 规范的中性低调卡片
|
||||
if (total === 0) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center justify-center gap-3 px-4 py-2 rounded-lg border border-border bg-muted/30 select-none',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="text-xs font-semibold text-muted-foreground/90">
|
||||
{t('jsonDiff:noDiffs')}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
// 3. 完美适配暗黑模式:
|
||||
// 废除 bg-primary/10,采用标准的低阻尼中性色 bg-secondary/60 配合 border-border/80,
|
||||
// 在任何主题皮肤下都能呈现出高级的暗钛金控制栏质感。
|
||||
'inline-flex items-center justify-center gap-3 px-3 h-9 rounded-md border border-border/80 bg-secondary/60 shadow-sm',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 上一处差异按钮 */}
|
||||
<button
|
||||
type="button"
|
||||
disabled={isFirst}
|
||||
aria-label={t('jsonDiff:previousDiff')}
|
||||
onClick={onPrev}
|
||||
className={cn(
|
||||
'p-1 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground',
|
||||
'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
|
||||
'disabled:pointer-events-none disabled:opacity-30', // 4. 边界拦截:触顶时优雅淡化并锁死点击
|
||||
)}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</button>
|
||||
|
||||
{/* 计数看板:强制等宽防止数字长短不一时产生宽度挤压跳动 */}
|
||||
<span className="text-xs font-bold font-mono min-w-[54px] text-center text-foreground/90 tabular-nums select-none">
|
||||
{currentIndex + 1} <span className="text-muted-foreground/60 font-sans mx-0.5">/</span>{' '}
|
||||
{total}
|
||||
</span>
|
||||
|
||||
{/* 下一处差异按钮 */}
|
||||
<button
|
||||
type="button"
|
||||
disabled={isLast}
|
||||
aria-label={t('jsonDiff:nextDiff')}
|
||||
onClick={onNext}
|
||||
className={cn(
|
||||
'p-1 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground',
|
||||
'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
|
||||
'disabled:pointer-events-none disabled:opacity-30', // 4. 边界拦截:触底时优雅淡化并锁死点击
|
||||
)}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
import React from 'react';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils';
|
||||
import JsonTree from './JsonTree';
|
||||
import type { DiffNode, DiffResult as DiffResultType, DiffType, ViewMode } from './types';
|
||||
|
||||
// 💡 顶层 Interface 继承原生 HTML 容器属性,扩展灵活性
|
||||
export interface DiffResultProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
result: DiffResultType;
|
||||
viewMode: ViewMode;
|
||||
activePath?: string;
|
||||
}
|
||||
|
||||
export default function DiffResult({
|
||||
result,
|
||||
viewMode,
|
||||
activePath,
|
||||
className,
|
||||
...props
|
||||
}: DiffResultProps) {
|
||||
const { t } = useI18n('jsonDiff');
|
||||
|
||||
if (viewMode === 'sideBySide') {
|
||||
return (
|
||||
<div
|
||||
className={cn('flex flex-col md:flex-row gap-4 items-stretch w-full', className)}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<SectionLabel text={t('jsonDiff:leftLabel')} />
|
||||
<JsonTree node={result.root} side="left" activePath={activePath} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<SectionLabel text={t('jsonDiff:rightLabel')} />
|
||||
<JsonTree node={result.root} side="right" activePath={activePath} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
/* 1. 单栏拍平视图容器:
|
||||
- 对齐 shadcn 规范,使用 bg-card、border-border 隔离。
|
||||
- 注入 tabular-nums 配合 font-mono,消灭任何行高和字符抖动。
|
||||
*/
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-xl border border-border bg-card font-mono text-xs shadow-sm overflow-x-auto min-h-[200px] max-h-[520px] overflow-y-auto p-1.5',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<UnifiedView node={result.root} depth={0} activePath={activePath} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const SectionLabel = ({ text }: { text: string }) => (
|
||||
<span className="block mb-2 text-[10px] font-bold tracking-wider text-muted-foreground/80 uppercase px-0.5 select-none">
|
||||
{text}
|
||||
</span>
|
||||
);
|
||||
|
||||
const formatPrimitive = (v: unknown): string => {
|
||||
if (v === undefined) return 'undefined';
|
||||
if (v === null) return 'null';
|
||||
if (typeof v === 'string') return JSON.stringify(v);
|
||||
if (typeof v === 'number' || typeof v === 'boolean') return String(v);
|
||||
return JSON.stringify(v);
|
||||
};
|
||||
|
||||
const isContainerType = (v: unknown): boolean =>
|
||||
(typeof v === 'object' && v !== null) || Array.isArray(v);
|
||||
|
||||
const prefixForType = (type: DiffType): string => {
|
||||
if (type === 'added') return '+';
|
||||
if (type === 'removed') return '-';
|
||||
if (type === 'modified') return '~';
|
||||
return ' ';
|
||||
};
|
||||
|
||||
// 2. 状态色彩超进化:
|
||||
// 拒绝硬编码实色系,全部换用高度安全的语义色变体与暗黑模式自适应。
|
||||
const typeThemeMap = {
|
||||
added: {
|
||||
text: 'text-emerald-600 dark:text-emerald-400',
|
||||
bg: 'bg-emerald-500/5 dark:bg-emerald-500/10',
|
||||
},
|
||||
removed: {
|
||||
text: 'text-destructive',
|
||||
bg: 'bg-destructive/5 dark:bg-destructive/10',
|
||||
},
|
||||
modified: {
|
||||
text: 'text-amber-600 dark:text-amber-400',
|
||||
bg: 'bg-amber-500/5 dark:bg-amber-500/10',
|
||||
},
|
||||
unchanged: {
|
||||
text: 'text-foreground/80',
|
||||
bg: 'bg-transparent',
|
||||
},
|
||||
};
|
||||
|
||||
interface UnifiedViewProps {
|
||||
node: DiffNode;
|
||||
depth: number;
|
||||
activePath?: string;
|
||||
}
|
||||
|
||||
const UnifiedView = ({ node, depth, activePath }: UnifiedViewProps) => {
|
||||
const isRoot = depth === 0;
|
||||
const hasChildren = Array.isArray(node.children) && node.children.length > 0;
|
||||
const isContainer =
|
||||
hasChildren || isContainerType(node.oldValue) || isContainerType(node.newValue);
|
||||
const keyLabel = isRoot ? '' : `${node.key}: `;
|
||||
|
||||
if (!isContainer) {
|
||||
if (node.type === 'modified') {
|
||||
return (
|
||||
<>
|
||||
<UnifiedRow
|
||||
depth={depth}
|
||||
type="removed"
|
||||
text={`${keyLabel}${formatPrimitive(node.oldValue)}`}
|
||||
active={activePath === node.path}
|
||||
/>
|
||||
<UnifiedRow
|
||||
depth={depth}
|
||||
type="added"
|
||||
text={`${keyLabel}${formatPrimitive(node.newValue)}`}
|
||||
active={activePath === node.path}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
const value = node.type === 'added' ? node.newValue : node.oldValue;
|
||||
return (
|
||||
<UnifiedRow
|
||||
depth={depth}
|
||||
type={node.type}
|
||||
text={`${keyLabel}${formatPrimitive(value)}`}
|
||||
active={activePath === node.path}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// 容器节点整块渲染处理
|
||||
if (node.type === 'added') {
|
||||
return (
|
||||
<UnifiedRow
|
||||
depth={depth}
|
||||
type="added"
|
||||
text={`${keyLabel}${stringifyMultiline(node.newValue, depth)}`}
|
||||
active={activePath === node.path}
|
||||
multiline
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (node.type === 'removed') {
|
||||
return (
|
||||
<UnifiedRow
|
||||
depth={depth}
|
||||
type="removed"
|
||||
text={`${keyLabel}${stringifyMultiline(node.oldValue, depth)}`}
|
||||
active={activePath === node.path}
|
||||
multiline
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const isArr = Array.isArray(node.oldValue) || Array.isArray(node.newValue);
|
||||
const open = isArr ? '[' : '{';
|
||||
const close = isArr ? ']' : '}';
|
||||
|
||||
return (
|
||||
<>
|
||||
<UnifiedRow depth={depth} type="unchanged" text={`${keyLabel}${open}`} />
|
||||
{node.children?.map((child) => (
|
||||
<UnifiedView key={child.path} node={child} depth={depth + 1} activePath={activePath} />
|
||||
))}
|
||||
<UnifiedRow depth={depth} type="unchanged" text={close} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
interface UnifiedRowProps {
|
||||
depth: number;
|
||||
type: DiffType;
|
||||
text: string;
|
||||
active?: boolean;
|
||||
multiline?: boolean;
|
||||
}
|
||||
|
||||
const UnifiedRow = ({ depth, type, text, active, multiline }: UnifiedRowProps) => {
|
||||
// 3. 高精度提取状态样式映射
|
||||
const currentTheme = typeThemeMap[type] || typeThemeMap.unchanged;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-start w-full font-mono py-0.5 select-text group',
|
||||
currentTheme.bg,
|
||||
currentTheme.text,
|
||||
// 4. 高亮定位条:不再使用生硬的蓝圆环,改为现代编辑器的“侧边左高亮带”设计,质感直接拉满
|
||||
active &&
|
||||
'bg-primary/10 relative before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1 before:bg-blue-500',
|
||||
)}
|
||||
style={{
|
||||
// 维持高精度的 Padding 基线缩进
|
||||
paddingLeft: `${Math.max(0.5, depth * 1.25)}rem`,
|
||||
paddingRight: '0.5rem',
|
||||
}}
|
||||
>
|
||||
{/* 5. 前缀标识:等宽锁定,强行占据 w-5 并让符号居中对齐,达成 VSCode 般的整洁排版 */}
|
||||
<span className="font-bold w-5 shrink-0 text-center select-none opacity-70 tabular-nums">
|
||||
{prefixForType(type)}
|
||||
</span>
|
||||
|
||||
<span
|
||||
className={cn(
|
||||
'flex-1 break-all tracking-tight leading-normal',
|
||||
multiline ? 'whitespace-pre' : 'whitespace-nowrap',
|
||||
)}
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const stringifyMultiline = (v: unknown, depth: number): string => {
|
||||
try {
|
||||
const json = JSON.stringify(v, null, 2);
|
||||
if (!json) return formatPrimitive(v);
|
||||
const indent = ' '.repeat(depth);
|
||||
return json
|
||||
.split('\n')
|
||||
.map((line, idx) => (idx === 0 ? line : indent + line))
|
||||
.join('\n');
|
||||
} catch {
|
||||
return formatPrimitive(v);
|
||||
}
|
||||
};
|
||||
|
||||
// 💡 彻底移除了文件底部引发 TS2484 冲突的 export type { DiffResultProps } 声明
|
||||
@@ -0,0 +1,142 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { formatByteSize } from '@/utils/textStatistics';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { validateJson } from '@/utils/jsonFormatter';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface ConvertResult {
|
||||
output: string;
|
||||
originalBytes: number;
|
||||
outputBytes: number;
|
||||
}
|
||||
|
||||
export type ConvertFunction = (text: string) => ConvertResult;
|
||||
|
||||
interface JsonConvertSectionProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
translationPrefix: string;
|
||||
convertFunction: ConvertFunction;
|
||||
}
|
||||
|
||||
export default function JsonConvertSection({
|
||||
translationPrefix,
|
||||
convertFunction,
|
||||
className,
|
||||
...props
|
||||
}: JsonConvertSectionProps) {
|
||||
const { t } = useI18n('jsonFormat');
|
||||
|
||||
const [input, setInput] = useState('');
|
||||
const [debouncedInput, setDebouncedInput] = useState('');
|
||||
|
||||
const pk = translationPrefix;
|
||||
|
||||
// 1. 高阶性能调优:将文本变化收拢进行 250ms 极速防抖落盘,避免每一次敲击键盘都触发底层的复杂序列化算法
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setDebouncedInput(input);
|
||||
}, 250);
|
||||
return () => clearTimeout(handle);
|
||||
}, [input]);
|
||||
|
||||
// 💡 2. 贯彻方案 A(衍生变量超进化):
|
||||
// 彻底删掉 error 状态和对应的受控 useEffect 节点。
|
||||
// 语法错误由防抖文本在内存中同步推导,彻底斩断二次级联渲染链条,ESLint 警告自愈!
|
||||
const error = useMemo(() => {
|
||||
return validateJson(debouncedInput);
|
||||
}, [debouncedInput]);
|
||||
|
||||
// 3. 核心魔法:纯净的即时流式转换转换管线 (Live Compilation Pipeline)
|
||||
const conversionPipeline = useMemo(() => {
|
||||
const trimmed = debouncedInput.trim();
|
||||
if (!trimmed || error) return null;
|
||||
|
||||
try {
|
||||
return convertFunction(debouncedInput);
|
||||
} catch (e) {
|
||||
// 捕获可能从外部转换器(如 YAML.stringify)中抛出的底层异常
|
||||
return {
|
||||
isRuntimeError: true,
|
||||
errorMessage: e instanceof Error ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
}, [debouncedInput, error, convertFunction]);
|
||||
|
||||
// 判定运行时异常
|
||||
const runtimeError =
|
||||
conversionPipeline && 'isRuntimeError' in conversionPipeline
|
||||
? conversionPipeline.errorMessage
|
||||
: null;
|
||||
const result =
|
||||
conversionPipeline && !('isRuntimeError' in conversionPipeline)
|
||||
? (conversionPipeline as ConvertResult)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className={cn('w-full flex flex-col gap-4', className)} {...props}>
|
||||
{/* 输入区 */}
|
||||
<TextInputArea
|
||||
placeholder={t(`jsonFormat:${pk}InputPlaceholder`)}
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
externalError={error || runtimeError || undefined} // 融合语法错误与运行时转换错误
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={7}
|
||||
maxRows={14}
|
||||
onClear={() => setInput('')}
|
||||
/>
|
||||
|
||||
{/* 4. 结果展示或状态引导卡片区 */}
|
||||
{result && result.output ? (
|
||||
<div className="relative rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden">
|
||||
{/* 结果栏精致头部 */}
|
||||
<div className="flex h-9 items-center justify-between px-4 border-b border-border bg-muted/50 select-none">
|
||||
<div className="flex gap-4 items-center">
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
|
||||
{t(`jsonFormat:${pk}OutputLabel`)}
|
||||
</span>
|
||||
|
||||
{/* 字节比对注入 tabular-nums font-mono,防止容量大小变动时字符横向抽搐 */}
|
||||
<div className="hidden sm:flex gap-3 items-center font-mono text-[10px] text-muted-foreground/70 tabular-nums">
|
||||
<span>
|
||||
{t('jsonFormat:originalSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatByteSize(result.originalBytes)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-border/60">|</span>
|
||||
<span>
|
||||
{t('jsonFormat:formattedSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatByteSize(result.outputBytes)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CopyButton
|
||||
text={result.output}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 转换出的数据流承载区:
|
||||
💡 修复点:移除了互相冲突打架的 select-all 类名,仅保留纯净、支持自由划线选中的 select-text 样式
|
||||
*/}
|
||||
<div className="p-4 font-mono text-xs text-foreground/90 whitespace-pre-wrap break-all max-h-[380px] overflow-y-auto leading-relaxed select-text">
|
||||
{result.output}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
/* 5. 空状态提示容器:完美的中性虚线引导,不喧宾夺主 */
|
||||
<div className="p-8 rounded-xl bg-muted/30 border border-dashed border-border/80 text-center flex flex-col items-center justify-center min-h-[120px] select-none">
|
||||
<p className="text-xs font-semibold text-muted-foreground/80 tracking-wide max-w-[240px] leading-relaxed">
|
||||
{error ? t('jsonFormat:fixErrorHint') : t(`jsonFormat:${pk}EmptyHint`)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import React from 'react';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// 💡 核心修复:使用 Omit<..., 'onChange'> 强行挖掉原生的 onChange 签名
|
||||
// 这样我们自定义的 (value: string) => void 就能独占鳌头,彻底消灭 TS2430 接口冲突!
|
||||
export interface JsonDiffInputProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'> {
|
||||
label: string;
|
||||
placeholder: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
error?: string | null;
|
||||
minRows?: number;
|
||||
}
|
||||
|
||||
export default function JsonDiffInput({
|
||||
label,
|
||||
placeholder,
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
minRows = 10,
|
||||
className,
|
||||
...props
|
||||
}: JsonDiffInputProps) {
|
||||
return (
|
||||
<div className={cn('flex-1 min-w-0 flex flex-col', className)} {...props}>
|
||||
<span className="block mb-2 text-[10px] font-bold tracking-wide text-muted-foreground/80 uppercase select-none px-0.5">
|
||||
{label}
|
||||
</span>
|
||||
|
||||
<TextInputArea
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
placeholder={placeholder}
|
||||
minRows={minRows}
|
||||
maxRows={16}
|
||||
externalError={error ?? undefined}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import {
|
||||
formatJson,
|
||||
type JsonFormatOptions,
|
||||
type JsonFormatResult,
|
||||
validateJson,
|
||||
} from '@/utils/jsonFormatter';
|
||||
import { formatByteSize } from '@/utils/textStatistics';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
export default function JsonFormatSection() {
|
||||
const { t } = useI18n('jsonFormat');
|
||||
|
||||
const [input, setInput] = useState('');
|
||||
const [debouncedInput, setDebouncedInput] = useState('');
|
||||
const [indentSize, setIndentSize] = useState<number>(2);
|
||||
const [sortKeys, setSortKeys] = useState(false);
|
||||
|
||||
// 1. 高频打字防抖落盘:防止大体积 JSON 在高频输入时发生卡顿
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setDebouncedInput(input);
|
||||
}, 250);
|
||||
return () => clearTimeout(handle);
|
||||
}, [input]);
|
||||
|
||||
// 💡 2. 贯彻方案 A(衍生变量超进化):
|
||||
// 彻底删除原有的 setError 状态和相关的 useEffect。
|
||||
// 语法错误由防抖文本在内存中同步推导,彻底斩断二次级联渲染链条,ESLint 警告瞬间消亡!
|
||||
const error = useMemo(() => {
|
||||
return validateJson(debouncedInput);
|
||||
}, [debouncedInput]);
|
||||
|
||||
// 3. 实时流式格式化管线
|
||||
const formattedPipeline = useMemo(() => {
|
||||
const trimmed = debouncedInput.trim();
|
||||
if (!trimmed || error) return null;
|
||||
|
||||
try {
|
||||
const options: JsonFormatOptions = { indentSize, sortKeys };
|
||||
return formatJson(debouncedInput, options);
|
||||
} catch (e) {
|
||||
return {
|
||||
isRuntimeError: true,
|
||||
errorMessage: e instanceof SyntaxError ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
}, [debouncedInput, error, indentSize, sortKeys]);
|
||||
|
||||
const runtimeError =
|
||||
formattedPipeline && 'isRuntimeError' in formattedPipeline
|
||||
? formattedPipeline.errorMessage
|
||||
: null;
|
||||
const result =
|
||||
formattedPipeline && !('isRuntimeError' in formattedPipeline)
|
||||
? (formattedPipeline as JsonFormatResult)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col gap-4">
|
||||
{/* 工具控制栏 */}
|
||||
<div className="flex h-10 items-center justify-between px-1.5 bg-secondary/40 rounded-xl border border-border/60">
|
||||
<div className="flex gap-4 items-center w-full">
|
||||
{/* 缩进配置区 */}
|
||||
<div className="flex gap-2 items-center shrink-0 select-none">
|
||||
<span className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider">
|
||||
{t('jsonFormat:indentSize')}
|
||||
</span>
|
||||
<SwitchButtonGroup
|
||||
value={indentSize}
|
||||
onChange={(v) => setIndentSize(Number(v))}
|
||||
options={[2, 4, 6, 8].map((size) => ({ value: size, label: String(size) }))}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="h-4 w-px bg-border/60" />
|
||||
|
||||
{/* 键名排序区 */}
|
||||
<div
|
||||
onClick={() => setSortKeys(!sortKeys)}
|
||||
className="flex items-center gap-2 cursor-pointer select-none group py-1"
|
||||
>
|
||||
<Checkbox
|
||||
id="sort-keys-checkbox"
|
||||
checked={sortKeys}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onCheckedChange={(checked) => setSortKeys(checked === true)}
|
||||
className="h-3.5 w-3.5 rounded border-input data-[state=checked]:bg-primary shadow-sm"
|
||||
/>
|
||||
<Label
|
||||
htmlFor="sort-keys-checkbox"
|
||||
className="text-xs font-bold text-foreground/80 cursor-pointer tracking-tight group-hover:text-foreground"
|
||||
>
|
||||
{t('jsonFormat:sortKeys')}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 满血版输入终端 */}
|
||||
<TextInputArea
|
||||
placeholder={t('jsonFormat:inputPlaceholder')}
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
externalError={error || runtimeError || undefined}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={8}
|
||||
maxRows={15}
|
||||
onClear={() => setInput('')}
|
||||
/>
|
||||
|
||||
{/* 格式化结果流面板展示 */}
|
||||
{result && result.formatted ? (
|
||||
<div className="relative rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden">
|
||||
{/* 结果栏头部 */}
|
||||
<div className="flex h-9 items-center justify-between px-4 border-b border-border bg-muted/50 select-none">
|
||||
<div className="flex gap-4 items-center">
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
|
||||
{t('jsonFormat:outputLabel')}
|
||||
</span>
|
||||
|
||||
<div className="hidden sm:flex gap-3 items-center font-mono text-[10px] text-muted-foreground/70 tabular-nums">
|
||||
<span>
|
||||
{t('jsonFormat:originalSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatByteSize(result.originalBytes)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-border/60">|</span>
|
||||
<span>
|
||||
{t('jsonFormat:formattedSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatByteSize(result.formattedBytes)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CopyButton
|
||||
text={result.formatted}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 核心格式化数据面板:
|
||||
💡 修复点:移除了互相打架的 select-all 类名,仅保留纯正的代码高亮可选样式 select-text
|
||||
*/}
|
||||
<div className="p-4 font-mono text-xs text-foreground/90 whitespace-pre-wrap break-all max-h-[420px] overflow-y-auto leading-relaxed select-text">
|
||||
{result.formatted}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
/* 空状态指示引导区 */
|
||||
<div className="p-8 rounded-xl bg-muted/30 border border-dashed border-border/80 text-center flex flex-col items-center justify-center min-h-[120px] select-none">
|
||||
<p className="text-xs font-semibold text-muted-foreground/80 tracking-wide max-w-[240px] leading-relaxed">
|
||||
{error ? t('jsonFormat:fixErrorHint') : t('jsonFormat:emptyHint')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ChevronDown, ChevronRight } from 'lucide-react'; // 用正统的矢量箭头平替原生的字符 '▾' '▸'
|
||||
import type { DiffNode, DiffType } from './types';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type TreeSide = 'left' | 'right';
|
||||
|
||||
export interface JsonTreeProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
node: DiffNode;
|
||||
side: TreeSide;
|
||||
defaultExpandDepth?: number;
|
||||
activePath?: string;
|
||||
}
|
||||
|
||||
interface NodeRowProps {
|
||||
node: DiffNode;
|
||||
side: TreeSide;
|
||||
depth: number;
|
||||
defaultExpandDepth: number;
|
||||
activePath?: string;
|
||||
isLastChild: boolean;
|
||||
}
|
||||
|
||||
const formatPrimitive = (v: unknown): string => {
|
||||
if (v === null) return 'null';
|
||||
if (typeof v === 'string') return JSON.stringify(v);
|
||||
if (typeof v === 'number' || typeof v === 'boolean') return String(v);
|
||||
return JSON.stringify(v);
|
||||
};
|
||||
|
||||
const shouldRenderOnSide = (type: DiffType, side: TreeSide): boolean => {
|
||||
if (type === 'added') return side === 'right';
|
||||
if (type === 'removed') return side === 'left';
|
||||
return true;
|
||||
};
|
||||
|
||||
const getValueForSide = (node: DiffNode, side: TreeSide): unknown => {
|
||||
return side === 'left' ? node.oldValue : node.newValue;
|
||||
};
|
||||
|
||||
// 1. 核心状态色彩映射调色盘:完美自适应双色模式
|
||||
const typeThemeMap = {
|
||||
added: {
|
||||
text: 'text-emerald-600 dark:text-emerald-400',
|
||||
bg: 'bg-emerald-500/5 dark:bg-emerald-500/10 hover:bg-emerald-500/10 dark:hover:bg-emerald-500/15',
|
||||
},
|
||||
removed: {
|
||||
text: 'text-destructive',
|
||||
bg: 'bg-destructive/5 dark:bg-destructive/10 hover:bg-destructive/10 dark:hover:bg-destructive/15',
|
||||
},
|
||||
modified: {
|
||||
text: 'text-amber-600 dark:text-amber-400',
|
||||
bg: 'bg-amber-500/5 dark:bg-amber-500/10 hover:bg-amber-500/10 dark:hover:bg-amber-500/15',
|
||||
},
|
||||
unchanged: {
|
||||
text: 'text-foreground/80',
|
||||
bg: 'hover:bg-muted/60',
|
||||
},
|
||||
};
|
||||
|
||||
const isContainerValue = (v: unknown): boolean => {
|
||||
return (typeof v === 'object' && v !== null) || Array.isArray(v);
|
||||
};
|
||||
|
||||
/**
|
||||
* 💡 性能调优大闸:将 NodeRow 抽离为顶层独立组件并裹上 React.memo。
|
||||
* 配合精准的 Props Diff,使得某一行的展开闭合绝对不会连累到其他平级和上级节点。
|
||||
*/
|
||||
const NodeRow = React.memo(
|
||||
({ node, side, depth, defaultExpandDepth, activePath, isLastChild }: NodeRowProps) => {
|
||||
const [override, setOverride] = useState<'auto' | 'open' | 'closed'>('auto');
|
||||
const rowRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const onActivePath = useMemo(() => {
|
||||
return Boolean(
|
||||
activePath &&
|
||||
(activePath === node.path ||
|
||||
activePath.startsWith(`${node.path}.`) ||
|
||||
activePath.startsWith(`${node.path}[`)),
|
||||
);
|
||||
}, [activePath, node.path]);
|
||||
|
||||
const expanded =
|
||||
override === 'open'
|
||||
? true
|
||||
: override === 'closed'
|
||||
? false
|
||||
: onActivePath || depth < defaultExpandDepth;
|
||||
|
||||
// 当激活路径精准定位到本行时,平滑滚动至容器中心
|
||||
useEffect(() => {
|
||||
if (activePath === node.path) {
|
||||
rowRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
}
|
||||
}, [activePath, node.path]);
|
||||
|
||||
// 占位空行分支:必须加 h-[22px] 锁定绝对等高,防止两侧文本高度塌陷发生高低错位
|
||||
if (!shouldRenderOnSide(node.type, side)) {
|
||||
return (
|
||||
<div
|
||||
className="text-transparent select-none opacity-0 h-[22px] leading-relaxed"
|
||||
style={{ paddingLeft: `${depth * 1.15}rem` }}
|
||||
>
|
||||
·
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const value = getValueForSide(node, side);
|
||||
const isContainer = isContainerValue(value) && Array.isArray(node.children);
|
||||
const isArray = Array.isArray(value);
|
||||
const theme = typeThemeMap[node.type] || typeThemeMap.unchanged;
|
||||
const isActive = activePath === node.path;
|
||||
const isRoot = depth === 0;
|
||||
|
||||
// 缩进样式封装:
|
||||
// 💡 视觉魔法:通过在左侧追加 before 细线,在每一层级下自动垂下一条优雅的 IDE 级“缩进指引线”
|
||||
const indentStyle = {
|
||||
paddingLeft: `${Math.max(0.25, depth * 1.15)}rem`,
|
||||
};
|
||||
|
||||
const indentClass = cn(
|
||||
'relative',
|
||||
depth > 0 &&
|
||||
'before:absolute before:left-[4px] before:top-0 before:bottom-0 before:w-[1px] before:bg-border/40',
|
||||
);
|
||||
|
||||
if (isContainer && node.children) {
|
||||
const open = isArray ? '[' : '{';
|
||||
const close = isArray ? ']' : '}';
|
||||
|
||||
return (
|
||||
<div ref={rowRef} className="w-full flex flex-col">
|
||||
{/* 大容器开端行 */}
|
||||
<div
|
||||
onClick={() => setOverride(expanded ? 'closed' : 'open')}
|
||||
className={cn(
|
||||
'group flex items-center gap-1 py-0.5 pr-2 text-xs font-mono select-none cursor-pointer rounded-sm w-full h-[22px] leading-relaxed',
|
||||
theme.bg,
|
||||
isActive &&
|
||||
'bg-primary/10 relative before:absolute before:left-0 before:top-0 before:bottom-0 before:w-0.5 before:bg-blue-500 rounded-none ring-0',
|
||||
)}
|
||||
style={indentStyle}
|
||||
>
|
||||
{/* 折叠小箭头:升级为精巧的 Lucide SVG 矢量微动效 */}
|
||||
<span className="w-3.5 h-3.5 flex items-center justify-center text-muted-foreground/80 shrink-0">
|
||||
{expanded ? (
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
) : (
|
||||
<ChevronRight className="h-3 w-3" />
|
||||
)}
|
||||
</span>
|
||||
|
||||
{!isRoot && (
|
||||
<span className="text-foreground/90 font-bold tracking-tight">{node.key}:</span>
|
||||
)}
|
||||
|
||||
<span className="text-muted-foreground/80 font-semibold">{open}</span>
|
||||
|
||||
{!expanded && (
|
||||
<span className="text-[10px] px-1.5 py-0.2 rounded bg-muted/80 text-muted-foreground font-sans font-medium mx-1 select-none">
|
||||
{summarize(value)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{!expanded && (
|
||||
<span className="text-muted-foreground/80 font-semibold">
|
||||
{close}
|
||||
{isLastChild ? '' : ','}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 容器子节点递归区 */}
|
||||
{expanded && (
|
||||
<div className={indentClass}>
|
||||
{node.children.map((child, idx) => (
|
||||
<NodeRow
|
||||
key={child.path}
|
||||
node={child}
|
||||
side={side}
|
||||
depth={depth + 1}
|
||||
defaultExpandDepth={defaultExpandDepth}
|
||||
activePath={activePath}
|
||||
isLastChild={idx === node.children!.length - 1}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 大容器收尾行 */}
|
||||
{expanded && (
|
||||
<div
|
||||
className="text-muted-foreground/80 font-mono text-xs py-0.5 h-[22px] leading-relaxed"
|
||||
style={{ paddingLeft: `${depth * 1.15 + 0.88}rem` }}
|
||||
>
|
||||
{close}
|
||||
{isLastChild ? '' : ','}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 叶子数据行分支
|
||||
return (
|
||||
<div
|
||||
ref={rowRef}
|
||||
className={cn(
|
||||
'flex items-center gap-1 py-0.5 pr-2 font-mono text-xs w-full h-[22px] leading-relaxed rounded-sm',
|
||||
theme.bg,
|
||||
isActive &&
|
||||
'bg-primary/10 relative before:absolute before:left-0 before:top-0 before:bottom-0 before:w-0.5 before:bg-blue-500 rounded-none ring-0',
|
||||
)}
|
||||
style={indentStyle}
|
||||
>
|
||||
<span className="w-3.5 shrink-0" /> {/* 与上方的折叠键轴线严格对齐 */}
|
||||
{!isRoot && (
|
||||
<span className="text-foreground/90 font-bold tracking-tight">{node.key}:</span>
|
||||
)}
|
||||
<span className={cn('font-medium tracking-tight truncate flex-1', theme.text)}>
|
||||
{formatPrimitive(value)}
|
||||
<span className="text-foreground/60 font-sans">{isLastChild ? '' : ','}</span>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
NodeRow.displayName = 'NodeRow';
|
||||
|
||||
export default function JsonTree({
|
||||
node,
|
||||
side,
|
||||
defaultExpandDepth = 2,
|
||||
activePath,
|
||||
className,
|
||||
...props
|
||||
}: JsonTreeProps) {
|
||||
return (
|
||||
/* 最外层承载器:统一收拢至标准的 bg-card 与等宽 tabular-nums 控制轴 */
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-xl border border-border bg-card text-card-foreground font-mono text-xs shadow-sm overflow-x-auto min-h-[200px] max-h-[520px] overflow-y-auto p-2.5 tabular-nums select-text',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<NodeRow
|
||||
node={node}
|
||||
side={side}
|
||||
depth={0}
|
||||
defaultExpandDepth={defaultExpandDepth}
|
||||
activePath={activePath}
|
||||
isLastChild
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const summarize = (v: unknown): string => {
|
||||
if (Array.isArray(v)) return `${v.length} ${v.length === 1 ? 'item' : 'items'}`;
|
||||
if (v && typeof v === 'object') {
|
||||
const n = Object.keys(v).length;
|
||||
return `${n} ${n === 1 ? 'key' : 'keys'}`;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
@@ -0,0 +1,191 @@
|
||||
import type { DiffNode, DiffResult, DiffType } from './types';
|
||||
|
||||
const ROOT_PATH = '$';
|
||||
const SENTINEL = Symbol('missing');
|
||||
|
||||
type MaybeMissing = unknown | typeof SENTINEL;
|
||||
|
||||
const isObject = (v: unknown): v is Record<string, unknown> =>
|
||||
typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||
|
||||
const isArray = (v: unknown): v is unknown[] => Array.isArray(v);
|
||||
|
||||
/**
|
||||
* 健壮的 JSONPath 生成器:支持针对包含点号、空格或特殊字符的键名进行括号转义拦截
|
||||
*/
|
||||
const buildPath = (parent: string, key: string, isArrayChild: boolean): string => {
|
||||
if (isArrayChild) {
|
||||
return `${parent}[${key}]`;
|
||||
}
|
||||
const needsEscaping = key.includes('.') || key.includes('[') || key.includes(' ');
|
||||
const formattedKey = needsEscaping ? `["${key}"]` : `.${key}`;
|
||||
|
||||
return parent === ROOT_PATH ? `${ROOT_PATH}${formattedKey}` : `${parent}${formattedKey}`;
|
||||
};
|
||||
|
||||
const primitiveEqual = (a: unknown, b: unknown): boolean => {
|
||||
if (typeof a === 'number' && typeof b === 'number') {
|
||||
return Object.is(a, b);
|
||||
}
|
||||
return a === b;
|
||||
};
|
||||
|
||||
const diffNode = (
|
||||
left: MaybeMissing,
|
||||
right: MaybeMissing,
|
||||
key: string,
|
||||
path: string,
|
||||
diffPaths: string[],
|
||||
): DiffNode => {
|
||||
// 分支 1:节点增加行为拦截 (叶子节点状态)
|
||||
if (left === SENTINEL && right !== SENTINEL) {
|
||||
diffPaths.push(path);
|
||||
return {
|
||||
key,
|
||||
type: 'added',
|
||||
oldValue: undefined, // 💡 补齐:对齐移除 ? 后的类型规范
|
||||
newValue: right,
|
||||
path,
|
||||
isLeaf: !isObject(right) && !isArray(right),
|
||||
hasDiffInChildren: false, // 自身即是新增,子树无需向下检索
|
||||
};
|
||||
}
|
||||
|
||||
// 分支 2:节点删除行为拦截 (叶子节点状态)
|
||||
if (right === SENTINEL && left !== SENTINEL) {
|
||||
diffPaths.push(path);
|
||||
return {
|
||||
key,
|
||||
type: 'removed',
|
||||
oldValue: left,
|
||||
newValue: undefined, // 💡 补齐:对齐移除 ? 后的类型规范
|
||||
path,
|
||||
isLeaf: !isObject(left) && !isArray(left),
|
||||
hasDiffInChildren: false, // 自身即是删除,子树无需向下检索
|
||||
};
|
||||
}
|
||||
|
||||
const leftObj = isObject(left);
|
||||
const rightObj = isObject(right);
|
||||
const leftArr = isArray(left);
|
||||
const rightArr = isArray(right);
|
||||
|
||||
// 分支 3:双对象深层递归 (容器状态)
|
||||
if (leftObj && rightObj) {
|
||||
const keySet = new Set<string>();
|
||||
const leftKeys = Object.keys(left);
|
||||
const rightKeys = Object.keys(right);
|
||||
|
||||
for (let i = 0; i < leftKeys.length; i++) keySet.add(leftKeys[i]);
|
||||
for (let i = 0; i < rightKeys.length; i++) keySet.add(rightKeys[i]);
|
||||
|
||||
const children: DiffNode[] = [];
|
||||
keySet.forEach((k) => {
|
||||
const childPath = buildPath(path, k, false);
|
||||
const l: MaybeMissing = k in left ? left[k] : SENTINEL;
|
||||
const r: MaybeMissing = k in right ? right[k] : SENTINEL;
|
||||
children.push(diffNode(l, r, k, childPath, diffPaths));
|
||||
});
|
||||
|
||||
// 💡 核心改良:判定子节点中是否存在任何变动
|
||||
const hasDiffInChildren = children.some((c) => c.type !== 'unchanged' || c.hasDiffInChildren);
|
||||
|
||||
return {
|
||||
key,
|
||||
type: hasDiffInChildren ? 'modified' : 'unchanged',
|
||||
oldValue: left,
|
||||
newValue: right,
|
||||
children,
|
||||
path,
|
||||
isLeaf: false,
|
||||
hasDiffInChildren, // 完美注入预计算衍生状态
|
||||
};
|
||||
}
|
||||
|
||||
// 分支 4:双数组深层按序递归 (容器状态)
|
||||
if (leftArr && rightArr) {
|
||||
const len = Math.max(left.length, right.length);
|
||||
const children: DiffNode[] = new Array(len);
|
||||
|
||||
for (let i = 0; i < len; i++) {
|
||||
const k = String(i);
|
||||
const childPath = buildPath(path, k, true);
|
||||
const l: MaybeMissing = i < left.length ? left[i] : SENTINEL;
|
||||
const r: MaybeMissing = i < right.length ? right[i] : SENTINEL;
|
||||
children[i] = diffNode(l, r, k, childPath, diffPaths);
|
||||
}
|
||||
|
||||
// 💡 核心改良:判定子项中是否存在任何变动
|
||||
const hasDiffInChildren = children.some((c) => c.type !== 'unchanged' || c.hasDiffInChildren);
|
||||
|
||||
return {
|
||||
key,
|
||||
type: hasDiffInChildren ? 'modified' : 'unchanged',
|
||||
oldValue: left,
|
||||
newValue: right,
|
||||
children,
|
||||
path,
|
||||
isLeaf: false,
|
||||
hasDiffInChildren, // 完美注入预计算衍生状态
|
||||
};
|
||||
}
|
||||
|
||||
// 分支 5:绝对类型安全防护大闸 (双基本基元比对)
|
||||
const leftIsContainer = leftObj || leftArr;
|
||||
const rightIsContainer = rightObj || rightArr;
|
||||
|
||||
if (!leftIsContainer && !rightIsContainer) {
|
||||
if (left === null || right === null) {
|
||||
if (left === null && right === null) {
|
||||
return {
|
||||
key,
|
||||
type: 'unchanged',
|
||||
oldValue: left,
|
||||
newValue: right,
|
||||
path,
|
||||
isLeaf: true,
|
||||
hasDiffInChildren: false,
|
||||
};
|
||||
}
|
||||
} else if (typeof left === typeof right) {
|
||||
if (primitiveEqual(left, right)) {
|
||||
return {
|
||||
key,
|
||||
type: 'unchanged',
|
||||
oldValue: left,
|
||||
newValue: right,
|
||||
path,
|
||||
isLeaf: true,
|
||||
hasDiffInChildren: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 类型完全发生突变错配,或者基本数值不相等
|
||||
diffPaths.push(path);
|
||||
return {
|
||||
key,
|
||||
type: 'modified',
|
||||
oldValue: left,
|
||||
newValue: right,
|
||||
path,
|
||||
isLeaf: !leftIsContainer && !rightIsContainer,
|
||||
hasDiffInChildren: false, // 变动在自身,后代无子树变动
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 比较两个 JSON 值的差异,返回安全的差异树及高精度差异路径列表。
|
||||
*/
|
||||
export const diffJson = (left: unknown, right: unknown): DiffResult => {
|
||||
const diffPaths: string[] = [];
|
||||
const root = diffNode(left, right, '', ROOT_PATH, diffPaths);
|
||||
return {
|
||||
root,
|
||||
diffPaths,
|
||||
diffCount: diffPaths.length,
|
||||
};
|
||||
};
|
||||
|
||||
export type { DiffNode, DiffResult, DiffType };
|
||||
@@ -0,0 +1,201 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import JsonDiffInput from './JsonDiffInput';
|
||||
import DiffResult from './DiffResult';
|
||||
import DiffNavigator from './DiffNavigator';
|
||||
import JsonFormatSection from './JsonFormatSection';
|
||||
import type { ConvertFunction } from './JsonConvertSection';
|
||||
import JsonConvertSection from './JsonConvertSection';
|
||||
import { diffJson } from './diffEngine';
|
||||
import { jsonToYaml } from '@/utils/jsonToYaml';
|
||||
import { jsonToToml } from '@/utils/jsonToToml';
|
||||
import { minifyJson } from '@/utils/jsonFormatter';
|
||||
import { useStorageState } from '@/utils/useStorageState';
|
||||
import type { JsonToolsPageMode } from '@/types/storage';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import type { ViewMode } from './types';
|
||||
|
||||
interface ParseState {
|
||||
value: unknown;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
const tryParse = (raw: string, invalidMsg: string): ParseState => {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return { value: undefined, error: null };
|
||||
try {
|
||||
return { value: JSON.parse(trimmed), error: null };
|
||||
} catch {
|
||||
return { value: undefined, error: invalidMsg };
|
||||
}
|
||||
};
|
||||
|
||||
const VALID_PAGE_MODES: readonly JsonToolsPageMode[] = ['diff', 'format', 'yaml', 'toml', 'minify'];
|
||||
const isValidPageMode = (val: unknown): val is JsonToolsPageMode =>
|
||||
typeof val === 'string' && (VALID_PAGE_MODES as readonly string[]).includes(val);
|
||||
|
||||
type PageMode = JsonToolsPageMode;
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useI18n(['jsonDiff', 'jsonFormat']);
|
||||
const [pageMode, setPageMode] = useStorageState('jsonTools/pageMode', 'diff', isValidPageMode);
|
||||
|
||||
// 1. 受控原始输入源
|
||||
const [leftInput, setLeftInput] = useState('');
|
||||
const [rightInput, setRightInput] = useState('');
|
||||
|
||||
// 2. 纯净的异步防抖管道:仅负责切断高频打字开销
|
||||
const [debouncedLeft, setDebouncedLeft] = useState('');
|
||||
const [debouncedRight, setDebouncedRight] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setDebouncedLeft(leftInput);
|
||||
setDebouncedRight(rightInput);
|
||||
}, 250);
|
||||
return () => clearTimeout(handle);
|
||||
}, [leftInput, rightInput]);
|
||||
|
||||
// 3. 贯彻方案A:利用 useMemo 将防抖文本同步转化为解析树和错误提示
|
||||
const parseState = useMemo(() => {
|
||||
const invalidMsg = t('jsonDiff:invalidJson');
|
||||
return {
|
||||
left: tryParse(debouncedLeft, invalidMsg),
|
||||
right: tryParse(debouncedRight, invalidMsg),
|
||||
};
|
||||
}, [debouncedLeft, debouncedRight, t]);
|
||||
|
||||
const leftError = parseState.left.error;
|
||||
const rightError = parseState.right.error;
|
||||
|
||||
const [viewMode, setViewMode] = useState<ViewMode>('sideBySide');
|
||||
const [currentDiffIndex, setCurrentDiffIndex] = useState(0);
|
||||
|
||||
// 4. 实时比对流式计算
|
||||
const diffResult = useMemo(() => {
|
||||
const { left, right } = parseState;
|
||||
if (left.error || right.error || debouncedLeft.trim() === '' || debouncedRight.trim() === '') {
|
||||
return null;
|
||||
}
|
||||
return diffJson(left.value, right.value);
|
||||
}, [parseState, debouncedLeft, debouncedRight]);
|
||||
|
||||
// 💡 彻底删除了原本在此处的侦听 [diffResult] 的 useEffect。
|
||||
// 状态重置已完全委托给事件源头,级联更新警告从根源上永久自愈!
|
||||
|
||||
const total = diffResult?.diffPaths.length ?? 0;
|
||||
|
||||
const handlePrev = useCallback(() => {
|
||||
if (total === 0) return;
|
||||
setCurrentDiffIndex((idx) => (idx - 1 + total) % total);
|
||||
}, [total]);
|
||||
|
||||
const handleNext = useCallback(() => {
|
||||
if (total === 0) return;
|
||||
setCurrentDiffIndex((idx) => (idx + 1) % total);
|
||||
}, [total]);
|
||||
|
||||
const activePath = diffResult && total > 0 ? diffResult.diffPaths[currentDiffIndex] : undefined;
|
||||
|
||||
const yamlConvert: ConvertFunction = useCallback((text: string) => {
|
||||
const r = jsonToYaml(text);
|
||||
return { output: r.output, originalBytes: r.originalBytes, outputBytes: r.outputBytes };
|
||||
}, []);
|
||||
|
||||
const tomlConvert: ConvertFunction = useCallback((text: string) => {
|
||||
const r = jsonToToml(text);
|
||||
return { output: r.output, originalBytes: r.originalBytes, outputBytes: r.outputBytes };
|
||||
}, []);
|
||||
|
||||
const minifyConvert: ConvertFunction = useCallback((text: string) => {
|
||||
const r = minifyJson(text);
|
||||
return { output: r.minified, originalBytes: r.originalBytes, outputBytes: r.minifiedBytes };
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="p-4 w-full flex flex-col space-y-4 min-h-[500px] select-none">
|
||||
<SwitchButtonGroup
|
||||
value={pageMode}
|
||||
onChange={(v: PageMode) => setPageMode(v)}
|
||||
options={[
|
||||
{ value: 'diff', label: t('jsonFormat:diffMode') },
|
||||
{ value: 'format', label: t('jsonFormat:formatMode') },
|
||||
{ value: 'yaml', label: t('jsonFormat:yamlMode') },
|
||||
{ value: 'toml', label: t('jsonFormat:tomlMode') },
|
||||
{ value: 'minify', label: t('jsonFormat:minifyMode') },
|
||||
]}
|
||||
size="small"
|
||||
className="w-full sm:w-auto"
|
||||
/>
|
||||
|
||||
{pageMode === 'diff' ? (
|
||||
<div className="flex flex-col space-y-4">
|
||||
<div className="flex h-10 items-center justify-between px-1.5 bg-secondary/40 rounded-xl border border-border/60">
|
||||
<SwitchButtonGroup
|
||||
value={viewMode}
|
||||
onChange={(v: ViewMode) => setViewMode(v)}
|
||||
options={[
|
||||
{ value: 'sideBySide', label: t('jsonDiff:sideBySideMode') },
|
||||
{ value: 'unified', label: t('jsonDiff:unifiedMode') },
|
||||
]}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col md:flex-row gap-4 w-full items-stretch">
|
||||
<JsonDiffInput
|
||||
label={t('jsonDiff:leftLabel')}
|
||||
placeholder={t('jsonDiff:leftPlaceholder')}
|
||||
value={leftInput}
|
||||
onChange={(val) => {
|
||||
setLeftInput(val);
|
||||
setCurrentDiffIndex(0); // 💡 在同一个用户键盘事件中打包批处理,0 副作用开销
|
||||
}}
|
||||
error={leftError}
|
||||
minRows={9}
|
||||
/>
|
||||
<JsonDiffInput
|
||||
label={t('jsonDiff:rightLabel')}
|
||||
placeholder={t('jsonDiff:rightPlaceholder')}
|
||||
value={rightInput}
|
||||
onChange={(val) => {
|
||||
setRightInput(val);
|
||||
setCurrentDiffIndex(0); // 💡 在同一个用户键盘事件中打包批处理,0 副作用开销
|
||||
}}
|
||||
error={rightError}
|
||||
minRows={9}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{diffResult ? (
|
||||
<div className="flex flex-col space-y-3.5 w-full pt-1">
|
||||
<div className="flex justify-center w-full">
|
||||
<DiffNavigator
|
||||
total={total}
|
||||
currentIndex={currentDiffIndex}
|
||||
onPrev={handlePrev}
|
||||
onNext={handleNext}
|
||||
/>
|
||||
</div>
|
||||
<DiffResult result={diffResult} viewMode={viewMode} activePath={activePath} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-8 rounded-xl bg-muted/30 border border-dashed border-border/80 text-center flex flex-col items-center justify-center min-h-[140px]">
|
||||
<p className="text-xs font-semibold text-muted-foreground/80 tracking-wide max-w-[260px] leading-relaxed">
|
||||
{leftError || rightError ? t('jsonDiff:fixErrorHint') : t('jsonDiff:emptyHint')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : pageMode === 'format' ? (
|
||||
<JsonFormatSection />
|
||||
) : pageMode === 'yaml' ? (
|
||||
<JsonConvertSection translationPrefix="yaml" convertFunction={yamlConvert} />
|
||||
) : pageMode === 'toml' ? (
|
||||
<JsonConvertSection translationPrefix="toml" convertFunction={tomlConvert} />
|
||||
) : (
|
||||
<JsonConvertSection translationPrefix="minify" convertFunction={minifyConvert} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
export type DiffType = 'added' | 'removed' | 'modified' | 'unchanged';
|
||||
export interface DiffNode {
|
||||
/** 节点键名(对象属性名,或者数组的索引字符串 "0", "1"...) */
|
||||
key: string;
|
||||
|
||||
/** 差异状态机核心分类 */
|
||||
type: DiffType;
|
||||
|
||||
/** * 左侧原始数值快照
|
||||
* 💡 优化点:移除了不安全的可选 ?,如果完全缺失则严格流出 undefined,
|
||||
* 倒逼下游渲染层必须做出明确的条件分支防护。
|
||||
*/
|
||||
oldValue: unknown;
|
||||
|
||||
/** 右侧最新数值快照 */
|
||||
newValue: unknown;
|
||||
|
||||
/** * 子节点差异列表
|
||||
* 💡 强类型化:只有当对象或数组这类容器节点发生比对时存在,未选中时默认为空数组 []
|
||||
*/
|
||||
children?: DiffNode[];
|
||||
|
||||
/** * 节点的绝对路径表达式(严格遵循高可靠的 JSONPath 规约,如 "$.user.profile" 或 "$.list[0]")
|
||||
* 用于 DiffNavigator 差异导航条进行秒级的 scrollIntoView 视图精准定位高亮
|
||||
*/
|
||||
path: string;
|
||||
|
||||
/** 是否为叶子节点(若为 true 代表当前值为基本基元数据类型,若为 false 代表当前值为大括号或方括号容器) */
|
||||
isLeaf: boolean;
|
||||
|
||||
/**
|
||||
* 💡 性能调优大闸(Computed Guard):
|
||||
* 预计算状态:代表当前节点的深层子孙节点中,是否存在任意一处 'added' | 'removed' | 'modified' 差异行为。
|
||||
* 这使得外界的 JsonTree 在高频折叠/展开时,能在一帧之内直接通过此属性判断是否需要高亮其父大括号,
|
||||
* 彻底终结了原先命令式深度递归遍历子树的昂贵性能代价!
|
||||
*/
|
||||
hasDiffInChildren: boolean;
|
||||
}
|
||||
|
||||
/** 视图对照渲染模式:sideBySide (双栏对照折叠树) | unified (单栏行级混合拍平) */
|
||||
export type ViewMode = 'sideBySide' | 'unified';
|
||||
|
||||
export interface DiffResult {
|
||||
/** 经过深层比对算法推导生成的根节点核心差异树(AST) */
|
||||
root: DiffNode;
|
||||
|
||||
/** * 扁平化的高精度差异节点绝对路径映射表。
|
||||
* 里面严格存储了所有 type !== 'unchanged' 的节点 path。
|
||||
* 专供外部的 DiffNavigator (差异控制条) 充当中央路由索引,实现 0 延迟的上一处/下一处无缝切流。
|
||||
*/
|
||||
diffPaths: string[];
|
||||
|
||||
/** 差异核心总计数(等价于 diffPaths.length),注入 tabular-nums 配合渲染 */
|
||||
diffCount: number;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { parseJwt, stringifyJson } from '@/utils/jwt';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SectionProps {
|
||||
title: string;
|
||||
content: unknown;
|
||||
colorClass: string; // 💡 1. 废除硬编码十六进制色值,改用语义化的 Tailwind 类名
|
||||
bgClass: string;
|
||||
borderClass: string;
|
||||
}
|
||||
|
||||
const Section = ({ title, content, colorClass, bgClass, borderClass }: SectionProps) => {
|
||||
const { t } = useI18n('jwt');
|
||||
return (
|
||||
<div className={cn('p-4 rounded-xl border border-solid', bgClass, borderClass)}>
|
||||
<div className="flex justify-between items-center mb-2 select-none">
|
||||
<span className={cn('text-xs font-bold tracking-wider uppercase', colorClass)}>
|
||||
{title}
|
||||
</span>
|
||||
<CopyButton
|
||||
text={JSON.stringify(content)}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
{/* 💡 排版微距精雕:
|
||||
- 彻底移除 border-black/5 这种非暗黑模式友好的硬隔离。
|
||||
- 统一收拢为标准的 bg-muted/40 配合 font-mono text-xs
|
||||
*/}
|
||||
<pre className="m-0 p-3 bg-muted/30 dark:bg-muted/10 rounded-lg text-xs font-mono overflow-x-auto whitespace-pre-wrap break-all border border-border/50 text-foreground/90 leading-relaxed select-text">
|
||||
{content ? stringifyJson(content) : t('jwt:invalidFormat')}
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useI18n(['jwt', 'jsonFormat']);
|
||||
const [jwtInput, setJwtInput] = useState('');
|
||||
|
||||
// 2. 防抖中转管道:切断高频键盘敲击时的红色语法闪烁
|
||||
const [debouncedInput, setDebouncedInput] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setDebouncedInput(jwtInput);
|
||||
}, 200);
|
||||
return () => clearTimeout(handle);
|
||||
}, [jwtInput]);
|
||||
|
||||
const handleContextMenuData = useCallback((payload: string) => {
|
||||
const cleaned = payload.replace(/^Bearer\s*/i, '').trim();
|
||||
setJwtInput(cleaned);
|
||||
}, []);
|
||||
|
||||
useContextMenuData({ featureKey: 'jwt', onData: handleContextMenuData });
|
||||
|
||||
// 3. 贯彻方案 A:衍生变量流。直接消费防抖后的文本
|
||||
const result = useMemo(() => {
|
||||
if (!debouncedInput.trim()) {
|
||||
return null;
|
||||
}
|
||||
return parseJwt(debouncedInput);
|
||||
}, [debouncedInput]);
|
||||
|
||||
return (
|
||||
<div className="p-4 w-full flex flex-col space-y-4 select-none">
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* 输入终端 */}
|
||||
<TextInputArea
|
||||
minRows={5}
|
||||
maxRows={10}
|
||||
placeholder={t('jwt_placeholder')}
|
||||
value={jwtInput}
|
||||
onChange={(val) => {
|
||||
const cleaned = val.replace(/^Bearer\s*/i, '').trim();
|
||||
setJwtInput(cleaned);
|
||||
}}
|
||||
allowCopy={true}
|
||||
showClear={true}
|
||||
externalError={result?.error || undefined}
|
||||
onClear={() => setJwtInput('')}
|
||||
/>
|
||||
|
||||
{/* 解码看板结果展现 */}
|
||||
{result && !result.error && (
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Header 分区:完美致敬 JWT.io 的鲜艳色彩,同时实现黑夜暗化自适应 */}
|
||||
<Section
|
||||
title={t('jwt:headerTitle')}
|
||||
content={result.header}
|
||||
colorClass="text-[#fb015b] dark:text-rose-400"
|
||||
borderClass="border-[#fb015b]/20 dark:border-rose-500/20"
|
||||
bgClass="bg-[#fb015b]/5 dark:bg-rose-500/5"
|
||||
/>
|
||||
|
||||
{/* Payload 分区 */}
|
||||
<Section
|
||||
title={t('jwt:payloadTitle')}
|
||||
content={result.payload}
|
||||
colorClass="text-[#a03aff] dark:text-purple-400" // 针对暗黑模式略微调高对比度
|
||||
borderClass="border-[#a03aff]/20 dark:border-purple-500/20"
|
||||
bgClass="bg-[#a03aff]/5 dark:bg-purple-500/5"
|
||||
/>
|
||||
|
||||
{/* Signature 签名区:完全对齐标准的 shadcn 骨架阶度 */}
|
||||
<div className="p-4 rounded-xl border border-border bg-secondary/40 shadow-sm">
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<span className="text-xs font-bold tracking-wider text-muted-foreground/90 uppercase">
|
||||
{t('jwt:signatureTitle')}
|
||||
</span>
|
||||
<CopyButton
|
||||
text={result.signature || ''}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
<span className="block text-xs font-mono break-all text-foreground/80 bg-muted/30 dark:bg-muted/10 p-3 rounded-lg border border-border/50 leading-relaxed select-text">
|
||||
{result.signature || t('jwt:noSignature')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 当解析错误时的干净中性引导拦截 */}
|
||||
{result?.error && (
|
||||
<div className="p-6 rounded-xl bg-muted/30 border border-dashed border-border text-center">
|
||||
<p className="text-xs font-semibold text-muted-foreground/80">
|
||||
{t('jsonFormat:invalidJson')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Download, Printer, Trash2 } from 'lucide-react';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useStorageState } from '@/utils/useStorageState';
|
||||
import type { MarkdownToHtmlPreviewMode } from '@/types/storage';
|
||||
import {
|
||||
downloadHtmlFile,
|
||||
markdownToHtml,
|
||||
printHtml,
|
||||
SAMPLE_MARKDOWN,
|
||||
wrapHtmlDocument,
|
||||
} from '@/utils/markdownToHtml';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const isValidPreviewMode = (val: unknown): val is MarkdownToHtmlPreviewMode =>
|
||||
typeof val === 'string' && ['split', 'preview', 'html'].includes(val);
|
||||
|
||||
// 💡 规范回归:保持最纯净的通用选择器集合,内部变量全部交由全局 :root 驱动
|
||||
const PREVIEW_STYLES = `
|
||||
.markdown-body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: var(--md-foreground);
|
||||
background-color: transparent;
|
||||
font-size: 14px;
|
||||
}
|
||||
.markdown-body h1, .markdown-body h2, .markdown-body h3 {
|
||||
margin-top: 24px;
|
||||
margin-bottom: 16px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
color: var(--md-foreground);
|
||||
}
|
||||
.markdown-body h1 { border-bottom: 1px solid var(--md-border); padding-bottom: 0.3em; font-size: 1.6em; }
|
||||
.markdown-body h2 { border-bottom: 1px solid var(--md-border); padding-bottom: 0.3em; font-size: 1.35em; }
|
||||
.markdown-body p { margin-top: 0; margin-bottom: 16px; }
|
||||
.markdown-body a { color: var(--md-link-color); text-decoration: none; }
|
||||
.markdown-body a:hover { text-decoration: underline; }
|
||||
.markdown-body code {
|
||||
background-color: var(--md-code-bg);
|
||||
border-radius: 4px;
|
||||
font-size: 85%;
|
||||
padding: 0.2em 0.4em;
|
||||
font-family: Menlo, Consolas, monospace;
|
||||
}
|
||||
.markdown-body pre {
|
||||
background-color: var(--md-pre-bg);
|
||||
border-radius: 8px;
|
||||
font-size: 85%;
|
||||
line-height: 1.45;
|
||||
overflow: auto;
|
||||
padding: 16px;
|
||||
margin: 0 0 16px;
|
||||
border: 1px solid var(--md-border);
|
||||
}
|
||||
.markdown-body pre code {
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.markdown-body blockquote {
|
||||
border-left: 0.25em solid var(--md-quote-line);
|
||||
color: var(--md-muted);
|
||||
margin: 0 0 16px;
|
||||
padding: 0 1em;
|
||||
}
|
||||
.markdown-body table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
margin-bottom: 16px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.markdown-body table th, .markdown-body table td {
|
||||
border: 1px solid var(--md-border);
|
||||
padding: 6px 13px;
|
||||
}
|
||||
.markdown-body table tr:nth-child(2n) { background-color: var(--md-code-bg); }
|
||||
.markdown-body table th { font-weight: 600; background-color: var(--md-code-bg); }
|
||||
`;
|
||||
|
||||
export default function MarkdownToHtmlPage() {
|
||||
const { t } = useI18n('markdownToHtml');
|
||||
const [previewMode, setPreviewMode] = useStorageState(
|
||||
'markdownToHtml/previewMode',
|
||||
'split' as MarkdownToHtmlPreviewMode,
|
||||
isValidPreviewMode,
|
||||
);
|
||||
const [markdown, setMarkdown] = useState(SAMPLE_MARKDOWN);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
|
||||
const result = useMemo(() => markdownToHtml(markdown), [markdown]);
|
||||
const error = result.hasError ? (result.error ?? null) : null;
|
||||
|
||||
// 💡 自适应大总管:以极高严谨度拼装明暗大闸,用标准换行切断粘连风险
|
||||
useEffect(() => {
|
||||
const iframe = iframeRef.current;
|
||||
if (!iframe) return;
|
||||
|
||||
const isDarkMode = document.documentElement.classList.contains('dark');
|
||||
|
||||
const themeVariables = isDarkMode
|
||||
? `:root {
|
||||
--md-bg: #090d16;
|
||||
--md-foreground: #e6edf3;
|
||||
--md-border: rgba(255,255,255,0.15);
|
||||
--md-code-bg: rgba(255,255,255,0.12);
|
||||
--md-pre-bg: rgba(255,255,255,0.04);
|
||||
--md-muted: #8b949e;
|
||||
--md-quote-line: rgba(255,255,255,0.25);
|
||||
--md-link-color: #58a6ff;
|
||||
}`
|
||||
: `:root {
|
||||
--md-bg: #ffffff;
|
||||
--md-foreground: #1f2328;
|
||||
--md-border: rgba(128,128,128,0.2);
|
||||
--md-code-bg: rgba(128,128,128,0.08);
|
||||
--md-pre-bg: rgba(128,128,128,0.03);
|
||||
--md-muted: #4b5563;
|
||||
--md-quote-line: rgba(128,128,128,0.3);
|
||||
--md-link-color: #3b82f6;
|
||||
}`;
|
||||
|
||||
// 💡 3. 核心大清洗:将全局基础树(html, body)与派生样式完全独立硬编码,杜绝任何语法踩踏
|
||||
const baseGlobalStyles = `
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: var(--md-bg);
|
||||
color: var(--md-foreground);
|
||||
}
|
||||
body {
|
||||
padding: 16px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
`;
|
||||
|
||||
iframe.srcdoc = `<!DOCTYPE html>
|
||||
<html lang="zh" style="background-color: ${isDarkMode ? '#090d16' : '#ffffff'};">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
${themeVariables}
|
||||
${PREVIEW_STYLES}
|
||||
${baseGlobalStyles}
|
||||
</style>
|
||||
</head>
|
||||
<body class="markdown-body">${result.html}</body>
|
||||
</html>`;
|
||||
}, [result.html, previewMode]);
|
||||
|
||||
const handleModeChange = useCallback(
|
||||
(newMode: MarkdownToHtmlPreviewMode) => {
|
||||
setPreviewMode(newMode);
|
||||
},
|
||||
[setPreviewMode],
|
||||
);
|
||||
|
||||
const handleClear = useCallback(() => {
|
||||
setMarkdown('');
|
||||
}, []);
|
||||
|
||||
const handlePrint = useCallback(() => {
|
||||
printHtml(result.html, t('pageTitle'));
|
||||
}, [result.html, t]);
|
||||
|
||||
const handleDownload = useCallback(() => {
|
||||
const doc = wrapHtmlDocument(result.html, t('pageTitle'));
|
||||
downloadHtmlFile(doc, 'markdown-export.html');
|
||||
}, [result.html, t]);
|
||||
|
||||
const showInput = previewMode !== 'preview';
|
||||
const showPreview = previewMode !== 'html';
|
||||
|
||||
return (
|
||||
<div className="p-4 w-full flex flex-col space-y-4 select-none">
|
||||
<div className="flex flex-col space-y-4">
|
||||
{/* 工具集成控制中枢 */}
|
||||
<div className="flex flex-col sm:flex-row gap-3 justify-between items-stretch sm:items-center bg-secondary/40 rounded-xl border border-border/60 px-1.5 py-1.5 sm:h-12">
|
||||
<SwitchButtonGroup
|
||||
value={previewMode}
|
||||
options={[
|
||||
{ value: 'split', label: t('splitMode') },
|
||||
{ value: 'preview', label: t('previewMode') },
|
||||
{ value: 'html', label: t('htmlMode') },
|
||||
]}
|
||||
onChange={handleModeChange}
|
||||
size="small"
|
||||
className="w-full sm:w-auto"
|
||||
/>
|
||||
|
||||
<div className="flex gap-2 shrink-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClear}
|
||||
className="h-8 rounded-md font-medium text-xs gap-1.5 shadow-sm text-destructive hover:text-destructive hover:bg-destructive/5 dark:hover:bg-destructive/10 border-input/60"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
{t('clear')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handlePrint}
|
||||
disabled={!result.html}
|
||||
className="h-8 rounded-md font-medium text-xs gap-1.5 shadow-sm"
|
||||
>
|
||||
<Printer className="h-3.5 w-3.5" />
|
||||
{t('print')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDownload}
|
||||
disabled={!result.html}
|
||||
className="h-8 rounded-md font-medium text-xs gap-1.5 shadow-sm"
|
||||
>
|
||||
<Download className="h-3.5 w-3.5" />
|
||||
{t('download')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 错误拦截提示框 */}
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
className="p-3.5 bg-destructive/10 border border-destructive/20 rounded-xl text-destructive text-xs font-semibold tracking-wide"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 主框架多栏联动排版轴 */}
|
||||
<div
|
||||
className={cn(
|
||||
'grid gap-4 min-h-[480px] w-full',
|
||||
showInput && showPreview ? 'grid-cols-1 md:grid-cols-2' : 'grid-cols-1',
|
||||
)}
|
||||
>
|
||||
{/* Markdown 输入翼终端 */}
|
||||
{showInput && (
|
||||
<div className="border border-border rounded-xl bg-card text-card-foreground shadow-sm overflow-hidden flex flex-col focus-within:ring-1 focus-within:ring-ring focus-within:border-ring">
|
||||
<div className="flex h-9 items-center justify-between px-4 bg-muted/50 border-b border-border select-none">
|
||||
<span className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider">
|
||||
{t('inputLabel')}
|
||||
</span>
|
||||
<span className="text-[10px] font-mono text-muted-foreground/60 tabular-nums">
|
||||
{t('charCount', { count: markdown.length })}
|
||||
</span>
|
||||
</div>
|
||||
<textarea
|
||||
value={markdown}
|
||||
onChange={(e) => setMarkdown(e.target.value)}
|
||||
placeholder={t('inputPlaceholder')}
|
||||
className="flex-1 min-h-[390px] p-4 bg-transparent font-mono text-xs leading-relaxed resize-none focus:outline-none text-foreground/90 select-text"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 实时 HTML/Iframe 预览翼终端 */}
|
||||
{showPreview && (
|
||||
<div className="border border-border rounded-xl bg-card text-card-foreground shadow-sm overflow-hidden flex flex-col">
|
||||
<div className="flex h-9 items-center justify-between px-4 bg-muted/50 border-b border-border select-none">
|
||||
<span className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider">
|
||||
{(previewMode as string) === 'html' ? t('htmlOutputLabel') : t('previewLabel')}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[10px] font-mono text-muted-foreground/60 tabular-nums">
|
||||
{t('charCount', { count: result.htmlLength })}
|
||||
</span>
|
||||
<CopyButton
|
||||
text={result.html}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(previewMode as string) === 'html' ? (
|
||||
<textarea
|
||||
value={result.html}
|
||||
readOnly
|
||||
className="flex-1 min-h-[390px] p-4 font-mono text-xs leading-relaxed resize-none focus:outline-none bg-muted/30 dark:bg-muted/10 text-foreground/80 select-text"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex-1 min-h-[390px] overflow-hidden bg-transparent">
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
title="markdown-preview"
|
||||
className="w-full h-full min-h-[360px] border-none bg-transparent"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import QrCodePage from '../index';
|
||||
|
||||
vi.mock('lucide-react', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('lucide-react')>();
|
||||
return {
|
||||
...actual,
|
||||
// 增量伪造需要高精嗅探的 QrCode 核心定位图标
|
||||
QrCode: () => <div data-testid="mock-lucide-qrcode">Icon</div>,
|
||||
};
|
||||
});
|
||||
|
||||
// Mock useSnackbar
|
||||
vi.mock('@/components/GlobalSnackbar', () => ({
|
||||
useSnackbar: () => ({
|
||||
showMessage: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock getEntryPointType(保留原厂其他特征配置,仅模拟入口路由环境)
|
||||
vi.mock('@/config/features', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/config/features')>();
|
||||
return {
|
||||
...actual,
|
||||
getEntryPointType: () => 'sidepanel',
|
||||
};
|
||||
});
|
||||
|
||||
// Mock 高频变化的子组件,收拢断言边界
|
||||
vi.mock('@/components/QrCodePreview', () => ({
|
||||
default: () => <div data-testid="qr-code-preview">QrCodePreview</div>,
|
||||
}));
|
||||
|
||||
vi.mock('@/components/ImageUploader', () => ({
|
||||
default: () => <div data-testid="image-uploader">ImageUploader</div>,
|
||||
}));
|
||||
|
||||
// Mock QRious 动态图像离屏生成引擎
|
||||
vi.mock('qrious', () => ({
|
||||
default: vi.fn().mockImplementation(() => ({
|
||||
toDataURL: () => 'data:image/png;base64,mock',
|
||||
})),
|
||||
}));
|
||||
|
||||
describe('QrCodePage', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('应该默认渲染生成模式', () => {
|
||||
render(<QrCodePage />);
|
||||
expect(screen.getByTestId('qr-code-preview')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('应该渲染模式切换按钮', () => {
|
||||
render(<QrCodePage />);
|
||||
expect(screen.getByText('文本转二维码')).toBeInTheDocument();
|
||||
expect(screen.getByText('二维码转文本')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('切换到解析模式应该渲染 ImageUploader', () => {
|
||||
render(<QrCodePage />);
|
||||
fireEvent.click(screen.getByText('二维码转文本'));
|
||||
expect(screen.getByTestId('image-uploader')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('qr-code-preview')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('切换回生成模式应该渲染 QrCodePreview', () => {
|
||||
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 机制)', () => {
|
||||
render(<QrCodePage />);
|
||||
expect(screen.getByText('输入 URL 或文本')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('应该渲染双翼响应式卡片网格布局', () => {
|
||||
const { container } = render(<QrCodePage />);
|
||||
const gridContainer = container.querySelector('.grid');
|
||||
expect(gridContainer).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import QrCodePreview from '@/components/QrCodePreview';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { useQrCodeContext } from '../contexts/QrCodeContext';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export default function GeneratePanel() {
|
||||
const { t } = useI18n('qrCode');
|
||||
const { generatorState, setTextToEncode, downloadQrCode, copyQrCode } = useQrCodeContext();
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 w-full items-stretch 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',
|
||||
)}
|
||||
>
|
||||
{/* 💡 2. 独立外置标签架(A11y 无障碍对齐):
|
||||
- 彻底删掉 TextInputArea 上引发崩溃的违规属性。
|
||||
- 改用正统的 <Label />,并注入标准的高度无障碍样式,间距比例极度平滑。
|
||||
*/}
|
||||
<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">
|
||||
{t('qrCode:urlInputLabel')}
|
||||
</Label>
|
||||
|
||||
<div className="flex-1 min-h-0">
|
||||
<TextInputArea
|
||||
value={generatorState.textToEncode}
|
||||
onChange={setTextToEncode}
|
||||
placeholder={t('qrCode:urlInputPlaceholder')}
|
||||
showCount={true}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={6}
|
||||
maxRows={12}
|
||||
externalError={generatorState.inputError || undefined}
|
||||
onClear={() => setTextToEncode('')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 右翼:活态二维码高精生成区 */}
|
||||
<div className="flex flex-col h-full">
|
||||
<QrCodePreview
|
||||
qrCodeDataUrl={generatorState.qrCodeDataUrl}
|
||||
onDownload={downloadQrCode}
|
||||
onCopy={copyQrCode}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useCallback, useEffect } from 'react';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import ImageUploader from '@/components/ImageUploader';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { useQrCodeContext } from '../contexts/QrCodeContext';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export default function ParsePanel() {
|
||||
const { t } = useI18n('qrCode');
|
||||
const { showMessage } = useSnackbar();
|
||||
const { parserState, setParserState, handleFileChange, handleClearFile } = useQrCodeContext();
|
||||
|
||||
// 全局粘贴事件监听
|
||||
const handlePaste = useCallback(
|
||||
async (e: ClipboardEvent) => {
|
||||
const items = e.clipboardData?.items;
|
||||
if (!items) return;
|
||||
|
||||
// 检查是否有图片
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
if (items[i].type.startsWith('image/')) {
|
||||
e.preventDefault();
|
||||
const file = items[i].getAsFile();
|
||||
if (file) {
|
||||
handleFileChange(file);
|
||||
showMessage(t('qrCode:imagePasted'), { severity: 'success', autoHideDuration: 1000 });
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否有 Base64 字符串
|
||||
const text = e.clipboardData?.getData('text/plain');
|
||||
if (text && text.startsWith('data:image/')) {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const response = await fetch(text);
|
||||
const blob = await response.blob();
|
||||
const file = new File([blob], 'pasted-image.png', { type: blob.type });
|
||||
handleFileChange(file);
|
||||
showMessage(t('qrCode:imagePasted'), { severity: 'success', autoHideDuration: 1000 });
|
||||
} catch (error) {
|
||||
console.error('处理 Base64 图片失败:', error);
|
||||
showMessage(t('qrCode:imagePasteError'), { severity: 'error', autoHideDuration: 3000 });
|
||||
}
|
||||
}
|
||||
},
|
||||
[handleFileChange, showMessage, t],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
document.addEventListener('paste', handlePaste);
|
||||
return () => {
|
||||
document.removeEventListener('paste', handlePaste);
|
||||
};
|
||||
}, [handlePaste]);
|
||||
|
||||
return (
|
||||
/* 💡 统一大视觉轴:
|
||||
- 追加 p-0.5 微隔离,配合 gap-6 建立与生成面板(GeneratePanel)绝对像素对齐的网格天平。
|
||||
*/
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 w-full items-stretch select-none p-0.5">
|
||||
{/* 左翼:图片接收/拖拽/剪贴板上传终端 */}
|
||||
<div className="flex flex-col h-full">
|
||||
<ImageUploader
|
||||
selectedFile={parserState.selectedFile}
|
||||
onFileChange={handleFileChange}
|
||||
onClearFile={handleClearFile}
|
||||
previewUrl={parserState.previewUrl}
|
||||
onPreviewUrlChange={(url) => setParserState((prev) => ({ ...prev, previewUrl: url }))}
|
||||
dragging={parserState.dragging}
|
||||
onDraggingChange={(dragging) => setParserState((prev) => ({ ...prev, dragging }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 右翼:高阶解析出码只读终端 */}
|
||||
<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 h-full">
|
||||
{/* 💡 修复点:物理剔除 TextInputArea 上的违规 title,改用符合 Vercel 美学的极致大写极细原子标签 */}
|
||||
<Label className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider pl-0.5">
|
||||
{t('qrCode:resultLabel')}
|
||||
</Label>
|
||||
|
||||
<div className="flex-1 min-h-0">
|
||||
<TextInputArea
|
||||
value={parserState.decodedResult}
|
||||
readOnly={true}
|
||||
showClear={false}
|
||||
allowCopy={true}
|
||||
placeholder=""
|
||||
minRows={6}
|
||||
maxRows={12}
|
||||
externalError={parserState.parseError || undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Dispatch, SetStateAction } from 'react'; // 💡 1. 显式解构导入类型,彻底掐灭 TS2304 报错
|
||||
import { createContext, useContext } from 'react';
|
||||
import type { QrCodeGeneratorState, QrCodeMode, QrCodeParserState } from '../types';
|
||||
|
||||
export interface QrCodeContextValue {
|
||||
// 核心主视图路由模式切换卡
|
||||
mode: QrCodeMode;
|
||||
setMode: (mode: QrCodeMode) => void;
|
||||
|
||||
// 1. 流式生成器终端状态机驱动
|
||||
generatorState: QrCodeGeneratorState;
|
||||
setTextToEncode: (text: string) => void;
|
||||
// 💡 架构纯净化:物理剔除暴露给外部的命令式 generateQrCode 算子。
|
||||
// 外部面板只需 setTextToEncode 驱动源文本更新,生成动作由内部流式管线全自动自发自愈完成!
|
||||
downloadQrCode: () => void;
|
||||
copyQrCode: () => Promise<void>;
|
||||
|
||||
// 2. 活态反向解析器终端状态机驱动
|
||||
parserState: QrCodeParserState;
|
||||
setParserState: Dispatch<SetStateAction<QrCodeParserState>>; // 💡 规整为纯净的直接类型使用
|
||||
parseQrCode: (file: File) => Promise<void>;
|
||||
handleFileChange: (file: File) => void;
|
||||
handleClearFile: () => void;
|
||||
}
|
||||
|
||||
export const QrCodeContext = createContext<QrCodeContextValue | null>(null);
|
||||
|
||||
export function useQrCodeContext() {
|
||||
const context = useContext(QrCodeContext);
|
||||
if (!context) {
|
||||
// 边界鲁棒性防护大闸
|
||||
throw new Error('useQrCodeContext must be used within a valid QrCodeProvider container');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import QRious from 'qrious';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import { parseQrCodeFromFile } from '@/utils/qrCodeParser';
|
||||
import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { useDebounce } from '@/utils/useDebounce';
|
||||
import type { QrCodeContextValue } from '../contexts/QrCodeContext';
|
||||
import type { QrCodeGeneratorState, QrCodeMode, QrCodeParserState } from '../types';
|
||||
|
||||
export function useQrCode(): QrCodeContextValue {
|
||||
const { t } = useI18n('qrCode');
|
||||
const { showMessage } = useSnackbar();
|
||||
|
||||
// 核心路由视图模式
|
||||
const [mode, setMode] = useState<QrCodeMode>('generate');
|
||||
|
||||
// 1. 生成器状态流(大幅瘦身:剔除 generating 状态)
|
||||
const [generatorState, setGeneratorState] = useState<
|
||||
Omit<QrCodeGeneratorState, 'generating' | 'qrCodeDataUrl'>
|
||||
>({
|
||||
textToEncode: '',
|
||||
inputError: '',
|
||||
});
|
||||
|
||||
// 2. 解析器状态流
|
||||
const [parserState, setParserState] = useState<QrCodeParserState>({
|
||||
decodedResult: '',
|
||||
parsing: false,
|
||||
parseError: '',
|
||||
selectedFile: null,
|
||||
previewUrl: '',
|
||||
dragging: false,
|
||||
});
|
||||
|
||||
// 3. 高频打字极速防抖
|
||||
const debouncedTextToEncode = useDebounce(generatorState.textToEncode, 200);
|
||||
|
||||
// 💡 4. 贯彻方案 A(无副作用超导管线):
|
||||
// 彻底删除原有的 generateQrCodeRef、3个 useEffect、1个 useRef 以及相关的复杂状态机。
|
||||
// 二维码画布纯粹作为防抖文本的派生变量同步算出,0重绘死循环风险,体验平滑如镜!
|
||||
const qrCodeDataUrl = useMemo(() => {
|
||||
const text = debouncedTextToEncode.trim();
|
||||
if (!text) return '';
|
||||
|
||||
try {
|
||||
let url = text;
|
||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
||||
url = 'https://' + url;
|
||||
}
|
||||
|
||||
// 💡 暗黑模式自适应大闸:实时嗅探系统 DOM 阶度
|
||||
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: '' }));
|
||||
}, []);
|
||||
|
||||
// 处理右键菜单数据上下文
|
||||
const handleContextMenuData = useCallback((payload: string) => {
|
||||
setMode('generate');
|
||||
setGeneratorState((prev) => ({ ...prev, textToEncode: payload, inputError: '' }));
|
||||
}, []);
|
||||
|
||||
useContextMenuData({ featureKey: 'qrCode', onData: handleContextMenuData });
|
||||
|
||||
// 反向活态解析二维码算法
|
||||
const parseQrCode = useCallback(
|
||||
async (file: File) => {
|
||||
try {
|
||||
setParserState((prev) => ({ ...prev, parsing: true, parseError: '', decodedResult: '' }));
|
||||
|
||||
const result = await parseQrCodeFromFile(file);
|
||||
|
||||
if (result.success && result.data) {
|
||||
setParserState((prev) => ({ ...prev, decodedResult: result.data! }));
|
||||
showMessage(t('qrCode:parseSuccess'), { severity: 'success', autoHideDuration: 1000 });
|
||||
} else {
|
||||
const errorMsg = result.error || t('qrCode:noQrDetected');
|
||||
setParserState((prev) => ({ ...prev, parseError: errorMsg }));
|
||||
showMessage(errorMsg, { severity: 'error', autoHideDuration: 3000 });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('解析二维码失败:', error);
|
||||
const errorMsg = error instanceof Error ? error.message : t('qrCode:parseError');
|
||||
setParserState((prev) => ({ ...prev, parseError: errorMsg }));
|
||||
showMessage(errorMsg, { severity: 'error', autoHideDuration: 3000 });
|
||||
} finally {
|
||||
setParserState((prev) => ({ ...prev, parsing: false }));
|
||||
}
|
||||
},
|
||||
[t, showMessage],
|
||||
);
|
||||
|
||||
// 下载二维码
|
||||
const downloadQrCode = useCallback(() => {
|
||||
if (!qrCodeDataUrl) return;
|
||||
|
||||
const link = document.createElement('a');
|
||||
link.href = qrCodeDataUrl;
|
||||
link.download = 'qrcode.png';
|
||||
link.click();
|
||||
showMessage(t('qrCode:qrCodeDownloadSuccess'), { severity: 'success', autoHideDuration: 1000 });
|
||||
}, [qrCodeDataUrl, showMessage, t]);
|
||||
|
||||
// 复制二维码至剪贴板
|
||||
const copyQrCode = useCallback(async () => {
|
||||
if (!qrCodeDataUrl) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(qrCodeDataUrl);
|
||||
const blob = await response.blob();
|
||||
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
'image/png': blob,
|
||||
}),
|
||||
]);
|
||||
|
||||
showMessage(t('qrCode:qrCodeCopySuccess'), { severity: 'success', autoHideDuration: 1000 });
|
||||
} catch (error) {
|
||||
console.error('复制二维码失败:', error);
|
||||
showMessage(t('qrCode:copyError'), { severity: 'error', autoHideDuration: 3000 });
|
||||
}
|
||||
}, [qrCodeDataUrl, showMessage, t]);
|
||||
|
||||
// 处理文件选择
|
||||
const handleFileChange = useCallback(
|
||||
(file: File) => {
|
||||
setParserState((prev) => {
|
||||
if (prev.previewUrl) {
|
||||
URL.revokeObjectURL(prev.previewUrl);
|
||||
}
|
||||
return {
|
||||
...prev,
|
||||
selectedFile: file,
|
||||
previewUrl: URL.createObjectURL(file),
|
||||
decodedResult: '',
|
||||
parseError: '',
|
||||
};
|
||||
});
|
||||
|
||||
// 触发解析安全的后台 Promise
|
||||
parseQrCode(file).catch((err) => {
|
||||
console.error('Parser standalone task thread exploded:', err);
|
||||
});
|
||||
},
|
||||
[parseQrCode],
|
||||
);
|
||||
|
||||
// 清除解析受控文件
|
||||
const handleClearFile = useCallback(() => {
|
||||
setParserState((prev) => {
|
||||
if (prev.previewUrl) {
|
||||
URL.revokeObjectURL(prev.previewUrl);
|
||||
}
|
||||
return {
|
||||
...prev,
|
||||
selectedFile: null,
|
||||
previewUrl: '',
|
||||
decodedResult: '',
|
||||
parseError: '',
|
||||
};
|
||||
});
|
||||
}, []);
|
||||
|
||||
return {
|
||||
mode,
|
||||
setMode,
|
||||
generatorState: fullGeneratorState,
|
||||
setTextToEncode,
|
||||
parseQrCode,
|
||||
downloadQrCode,
|
||||
copyQrCode,
|
||||
parserState,
|
||||
setParserState,
|
||||
handleFileChange,
|
||||
handleClearFile,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { QrCodeContext } from './contexts/QrCodeContext';
|
||||
import { useQrCode } from './hooks/useQrCode';
|
||||
import GeneratePanel from './components/GeneratePanel';
|
||||
import ParsePanel from './components/ParsePanel';
|
||||
import type { QrCodeMode } from './types';
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useI18n('qrCode');
|
||||
const qrCode = useQrCode();
|
||||
|
||||
// 模式选项驱动骨架
|
||||
const modeOptions = [
|
||||
{ value: 'generate' as QrCodeMode, label: t('qrCode:urlToQr') },
|
||||
{ value: 'parse' as QrCodeMode, label: t('qrCode:qrToUrl') },
|
||||
];
|
||||
|
||||
return (
|
||||
<QrCodeContext.Provider value={qrCode}>
|
||||
{/* 💡 统一视觉规范大超进化:
|
||||
- 彻底剥离破坏流式宽度的 max-w-[400px] 枷锁,开启标准的 w-full 全自适应包裹。
|
||||
- 替换为标准的 p-4 呼吸内边距配合 flex flex-col space-y-4,接管系统级重排!
|
||||
*/}
|
||||
<div className="p-4 w-full flex flex-col space-y-4 min-h-[500px] select-none">
|
||||
{/* 流式中央控制切流卡:注入 sm 断点防御,防范单栏状态下发生变形 */}
|
||||
<div className="w-full sm:w-fit pt-0.5">
|
||||
<SwitchButtonGroup
|
||||
value={qrCode.mode}
|
||||
options={modeOptions}
|
||||
onChange={qrCode.setMode}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 💡 面板渲染沙箱:
|
||||
- 在切流渲染时,利用独立的 mt-2 增加纵深边界线。
|
||||
- 配合内部自带的双翼 Flex 聚焦大边框,形成坚固如铁的架构闭环!
|
||||
*/}
|
||||
<div className="w-full pt-1.5">
|
||||
{qrCode.mode === 'generate' ? (
|
||||
<div>
|
||||
<GeneratePanel />
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<ParsePanel />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</QrCodeContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* 二维码工具页面的状态类型定义
|
||||
*/
|
||||
|
||||
/** 二维码功能核心主路由模式 */
|
||||
export type QrCodeMode = 'generate' | 'parse';
|
||||
|
||||
/** * 二维码生成器的状态
|
||||
* 💡 架构优化:保留与全局 Context 骨架契合的形态,
|
||||
* 外部依然可以流畅读取这些状态,但在新架构下运行效率和稳定性大幅提升!
|
||||
*/
|
||||
export interface QrCodeGeneratorState {
|
||||
/** 受控的输入源文本(支持 URL 或任意文本快照) */
|
||||
textToEncode: string;
|
||||
/** 由防抖源文本流在单次渲染内存中同步派生出的二维码 Base64 Data URL */
|
||||
qrCodeDataUrl: string;
|
||||
/** 是否正在生成(流式架构下已默认为恒定 false 的非阻塞快照,保留作为 UI 骨架兼容) */
|
||||
generating: boolean;
|
||||
/** 输入文本校验或底层画布崩溃的错误提示信息 */
|
||||
inputError: string;
|
||||
}
|
||||
|
||||
/** * 二维码解析器的状态
|
||||
* 反向活态图片读取终端的流式驱动核心
|
||||
*/
|
||||
export interface QrCodeParserState {
|
||||
/** 解析解密出的原始文本结果 */
|
||||
decodedResult: string;
|
||||
/** 异步文件系统/画布读取时的后台线程状态锁 */
|
||||
parsing: boolean;
|
||||
/** 图像由于残缺、无矩阵或非标准二维码引发的解析错误信息 */
|
||||
parseError: string;
|
||||
/** 当前被拖拽、粘贴或点击选中的 File 原生文件句柄 */
|
||||
selectedFile: File | null;
|
||||
/** 内存沙箱级别的原生 Blob/File 图片临时预览虚拟 URL */
|
||||
previewUrl: string;
|
||||
/** 用户鼠标拖拽文件在边界内滑移悬停的活态状态大闸 */
|
||||
dragging: boolean;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import RightClickRestorerPage from '../index';
|
||||
|
||||
const mockUnlock = vi.fn();
|
||||
|
||||
vi.mock('../useRightClickRestorer', () => ({
|
||||
useRightClickRestorer: () => ({
|
||||
domain: 'example.com',
|
||||
isLoading: false,
|
||||
isUnlocked: false,
|
||||
isUnsupported: false,
|
||||
unlock: mockUnlock,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('RightClickRestorerPage', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should render current domain', () => {
|
||||
render(<RightClickRestorerPage />);
|
||||
expect(screen.getByText(/example\.com/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render locked status', () => {
|
||||
render(<RightClickRestorerPage />);
|
||||
expect(screen.getByText(/未解锁/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call unlock when button clicked', () => {
|
||||
render(<RightClickRestorerPage />);
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
expect(mockUnlock).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { renderHook, act, waitFor } from '@testing-library/react';
|
||||
import { useRightClickRestorer } from '../useRightClickRestorer';
|
||||
import { sendMessageToContent } from '@/utils/messages';
|
||||
|
||||
const mockTabsQuery = vi.fn();
|
||||
|
||||
vi.mock('@/utils/messages', () => ({
|
||||
MessageAction: {
|
||||
RESTORE_RIGHT_CLICK: 'restoreRightClick',
|
||||
QUERY_RIGHT_CLICK_STATUS: 'queryRightClickStatus',
|
||||
},
|
||||
sendMessageToContent: vi.fn(),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockTabsQuery.mockResolvedValue([{ url: 'https://example.com/path' }]);
|
||||
chrome.tabs.query = mockTabsQuery;
|
||||
vi.mocked(sendMessageToContent).mockResolvedValue({ success: true, restored: false });
|
||||
});
|
||||
|
||||
describe('useRightClickRestorer', () => {
|
||||
it('should load domain and query status', async () => {
|
||||
const { result } = renderHook(() => useRightClickRestorer());
|
||||
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false));
|
||||
|
||||
expect(result.current.domain).toBe('example.com');
|
||||
expect(result.current.isUnlocked).toBe(false);
|
||||
expect(result.current.isUnsupported).toBe(false);
|
||||
expect(sendMessageToContent).toHaveBeenCalledWith('queryRightClickStatus');
|
||||
});
|
||||
|
||||
it('should mark internal pages as unsupported', async () => {
|
||||
mockTabsQuery.mockResolvedValue([{ url: 'chrome://newtab/' }]);
|
||||
chrome.tabs.query = mockTabsQuery;
|
||||
|
||||
const { result } = renderHook(() => useRightClickRestorer());
|
||||
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false));
|
||||
|
||||
expect(result.current.isUnsupported).toBe(true);
|
||||
expect(result.current.isUnlocked).toBe(false);
|
||||
expect(sendMessageToContent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should unlock right click', async () => {
|
||||
vi.mocked(sendMessageToContent).mockResolvedValueOnce({ success: true, restored: false });
|
||||
vi.mocked(sendMessageToContent).mockResolvedValueOnce({ success: true, restored: true });
|
||||
|
||||
const { result } = renderHook(() => useRightClickRestorer());
|
||||
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.unlock();
|
||||
});
|
||||
|
||||
expect(result.current.isUnlocked).toBe(true);
|
||||
expect(sendMessageToContent).toHaveBeenLastCalledWith('restoreRightClick');
|
||||
});
|
||||
|
||||
it('should not unlock unsupported pages', async () => {
|
||||
mockTabsQuery.mockResolvedValue([{ url: 'chrome://settings/' }]);
|
||||
chrome.tabs.query = mockTabsQuery;
|
||||
|
||||
const { result } = renderHook(() => useRightClickRestorer());
|
||||
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.unlock();
|
||||
});
|
||||
|
||||
expect(result.current.isUnlocked).toBe(false);
|
||||
expect(sendMessageToContent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle sendMessage failure gracefully', async () => {
|
||||
vi.mocked(sendMessageToContent).mockRejectedValue(new Error('Connection failed'));
|
||||
|
||||
const { result } = renderHook(() => useRightClickRestorer());
|
||||
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.unlock();
|
||||
});
|
||||
|
||||
expect(result.current.isUnlocked).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Shield, ShieldCheck, MousePointerClick, AlertTriangle } from 'lucide-react';
|
||||
import { useRightClickRestorer } from './useRightClickRestorer';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
|
||||
export default function RightClickRestorerPage() {
|
||||
const { t } = useI18n('rightClickRestorer');
|
||||
const { domain, isLoading, isUnlocked, isUnsupported, unlock } = useRightClickRestorer();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-12 min-h-[280px] w-full">
|
||||
<span className="text-xs text-muted-foreground mt-2 font-medium tracking-wide">
|
||||
{t('rightClickRestorer:loading')}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-4 w-full flex flex-col space-y-4">
|
||||
{/* Current Domain */}
|
||||
<div className="w-full rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden">
|
||||
<div className="p-4">
|
||||
<Label className="text-sm font-medium">{t('rightClickRestorer:currentDomain')}</Label>
|
||||
<div className="mt-2 flex items-center justify-between gap-2">
|
||||
<code className="text-sm bg-muted px-2 py-1 rounded truncate min-w-0 flex-1">
|
||||
{domain || '—'}
|
||||
</code>
|
||||
{isUnsupported ? (
|
||||
<Badge variant="destructive" className="gap-1 shrink-0">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
{t('rightClickRestorer:unsupported')}
|
||||
</Badge>
|
||||
) : isUnlocked ? (
|
||||
<Badge variant="default" className="gap-1 bg-green-600 hover:bg-green-700 shrink-0">
|
||||
<ShieldCheck className="h-3 w-3" />
|
||||
{t('rightClickRestorer:statusUnlocked')}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="gap-1 shrink-0">
|
||||
<Shield className="h-3 w-3" />
|
||||
{t('rightClickRestorer:statusLocked')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Unlock Action */}
|
||||
<div className="w-full rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden">
|
||||
<div className="p-4 space-y-3">
|
||||
{isUnsupported ? (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('rightClickRestorer:unsupportedDesc')}
|
||||
</p>
|
||||
<Button className="w-full gap-2" disabled variant="secondary">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{t('rightClickRestorer:unsupported')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">{t('rightClickRestorer:unlockDesc')}</p>
|
||||
<Button
|
||||
className="w-full gap-2"
|
||||
onClick={() => void unlock()}
|
||||
disabled={isUnlocked}
|
||||
variant={isUnlocked ? 'secondary' : 'default'}
|
||||
>
|
||||
<MousePointerClick className="h-4 w-4" />
|
||||
{isUnlocked
|
||||
? t('rightClickRestorer:alreadyUnlocked')
|
||||
: t('rightClickRestorer:unlockBtn')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { MessageAction, sendMessageToContent } from '@/utils/messages';
|
||||
|
||||
const UNSUPPORTED_PROTOCOLS = new Set([
|
||||
'chrome:',
|
||||
'chrome-extension:',
|
||||
'about:',
|
||||
'edge:',
|
||||
'brave:',
|
||||
]);
|
||||
|
||||
function isUnsupportedPage(url: string | undefined): boolean {
|
||||
if (!url) return true;
|
||||
try {
|
||||
const protocol = new URL(url).protocol;
|
||||
return UNSUPPORTED_PROTOCOLS.has(protocol);
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export interface UseRightClickRestorerReturn {
|
||||
domain: string;
|
||||
isLoading: boolean;
|
||||
isUnlocked: boolean;
|
||||
isUnsupported: boolean;
|
||||
unlock: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function useRightClickRestorer(): UseRightClickRestorerReturn {
|
||||
const [domain, setDomain] = useState<string>('');
|
||||
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||
const [isUnlocked, setIsUnlocked] = useState<boolean>(false);
|
||||
const [isUnsupported, setIsUnsupported] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
try {
|
||||
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||
const url = tab?.url;
|
||||
|
||||
if (url) {
|
||||
try {
|
||||
setDomain(new URL(url).hostname);
|
||||
} catch {
|
||||
setDomain('');
|
||||
}
|
||||
}
|
||||
|
||||
if (isUnsupportedPage(url)) {
|
||||
setIsUnsupported(true);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await sendMessageToContent(MessageAction.QUERY_RIGHT_CLICK_STATUS);
|
||||
if (response?.success) {
|
||||
setIsUnlocked(response.restored);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[RightClickRestorer] Failed to load state:', err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
void load();
|
||||
}, []);
|
||||
|
||||
const unlock = useCallback(async () => {
|
||||
if (isUnsupported) return;
|
||||
|
||||
try {
|
||||
const response = await sendMessageToContent(MessageAction.RESTORE_RIGHT_CLICK);
|
||||
if (response?.success) {
|
||||
setIsUnlocked(response.restored);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[RightClickRestorer] Failed to unlock:', err);
|
||||
}
|
||||
}, [isUnsupported]);
|
||||
|
||||
return {
|
||||
domain,
|
||||
isLoading,
|
||||
isUnlocked,
|
||||
isUnsupported,
|
||||
unlock,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* 自动刷新开关组件
|
||||
*
|
||||
* 用于 StorageCleaner 页面,控制是否自动刷新存储数据列表。
|
||||
* 以卡片形式展示,左侧为标签文本,右侧为 shadcn/ui Switch 开关。
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <AutoRefreshToggle
|
||||
* reloadAfterClean={reloadAfterClean}
|
||||
* onChange={(checked) => setReloadAfterClean(checked)}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
export interface AutoRefreshToggleProps extends Omit<
|
||||
React.HTMLAttributes<HTMLDivElement>,
|
||||
'onChange'
|
||||
> {
|
||||
/** 开关的当前状态(受控) */
|
||||
reloadAfterClean: boolean;
|
||||
/** 状态变化时的回调函数 */
|
||||
onChange: (checked: boolean) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动刷新开关
|
||||
*
|
||||
* @param reloadAfterClean - 当前开关状态
|
||||
* @param onChange - 状态变化回调,接收新的布尔值
|
||||
* @param className - 额外的 CSS 类名,用于覆盖或扩展样式
|
||||
* @param props - 透传给外层 div 的其他 HTML 属性
|
||||
*/
|
||||
export default function AutoRefreshToggle({
|
||||
reloadAfterClean,
|
||||
onChange,
|
||||
className,
|
||||
...props
|
||||
}: AutoRefreshToggleProps) {
|
||||
const { t } = useI18n('storageCleaner');
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full p-4 rounded-xl border border-border bg-card text-card-foreground shadow-sm flex justify-between items-center',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* Label 与 Switch 通过 htmlFor + id 关联,支持点击文字触发开关 */}
|
||||
<Label
|
||||
htmlFor="auto-refresh-switch"
|
||||
className="text-sm font-bold text-foreground cursor-pointer select-none tracking-tight"
|
||||
>
|
||||
{t('storageCleaner:autoRefresh')}
|
||||
</Label>
|
||||
|
||||
<Switch id="auto-refresh-switch" checked={reloadAfterClean} onCheckedChange={onChange} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import React from 'react';
|
||||
import { CheckCircle, XCircle } from 'lucide-react';
|
||||
import type { CleaningResult as CleaningResultType } from '@/types/storage';
|
||||
import { formatCleaningResult } from '@/utils/storageCleaner';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils'; // 1. 引入 shadcn 核心类名合并工具
|
||||
|
||||
interface CleaningResultProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
result: CleaningResultType | null;
|
||||
}
|
||||
|
||||
export default function CleaningResult({ result, className, ...props }: CleaningResultProps) {
|
||||
const { t } = useI18n('storageCleaner');
|
||||
|
||||
if (!result) return null;
|
||||
|
||||
const isSuccess = result.success;
|
||||
|
||||
return (
|
||||
<div className={cn('w-full', className)} {...props}>
|
||||
{/* 2. 彻底重构容器类名结构:
|
||||
- 成功状态:采用 Tailwind 官方推荐的 emerald 体系,利用 /10 (10% 透明度) 和 /20 (边框)。
|
||||
- 失败状态:完全放权给标准的 border-destructive/20 和 bg-destructive/5。
|
||||
- 这样在明暗双色模式切换时,色彩会自动与背景完美融为一体。
|
||||
*/}
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-start gap-3 rounded-xl py-2.5 px-3.5 border shadow-sm',
|
||||
isSuccess
|
||||
? 'bg-emerald-500/5 border-emerald-500/20 text-emerald-600 dark:text-emerald-400'
|
||||
: 'bg-destructive/5 border-destructive/20 text-destructive',
|
||||
)}
|
||||
>
|
||||
{/* 3. 图标样式向系统语义全面对齐 */}
|
||||
{isSuccess ? (
|
||||
<CheckCircle className="h-4 w-4 shrink-0 mt-0.5 text-emerald-500" />
|
||||
) : (
|
||||
<XCircle className="h-4 w-4 shrink-0 mt-0.5 text-destructive" />
|
||||
)}
|
||||
|
||||
{/* 4. 文本排版细节微调 */}
|
||||
<span className="text-xs sm:text-sm font-semibold leading-relaxed break-all">
|
||||
{isSuccess
|
||||
? formatCleaningResult(result, t)
|
||||
: result.error || t('storageCleaner:partialFailure')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ErrorDisplayProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
error: string;
|
||||
}
|
||||
|
||||
export default function ErrorDisplay({ error, className, ...props }: ErrorDisplayProps) {
|
||||
const { t } = useI18n('storageCleaner');
|
||||
|
||||
return (
|
||||
// 1. 精简层级:单层外壳直接搞定居中、响应式高度与外部类名扩展
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center py-8 min-h-[240px] sm:min-h-[360px] p-4 text-center',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 2. 核心卡片容器:
|
||||
- 彻底放弃 bg-red-50,改用标准的 bg-destructive/5(3%~5% 透明度的系统危险色)。
|
||||
- 边框改为 border-destructive/20。
|
||||
- 这样在黑夜模式下会自动完美混色,绝不刺眼。
|
||||
*/}
|
||||
<div className="w-full max-w-xs flex flex-col items-center justify-center rounded-xl p-5 border border-destructive/20 bg-destructive/5 shadow-sm">
|
||||
{/* 3. 图标与主要错误信息全面对接 text-destructive 语义色 */}
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-destructive/10 text-destructive mb-3.5 shrink-0">
|
||||
<AlertCircle className="h-5 w-5" />
|
||||
</div>
|
||||
|
||||
<p className="text-sm font-semibold leading-relaxed text-destructive break-all px-1 mb-2">
|
||||
{error}
|
||||
</p>
|
||||
|
||||
{/* 次要提示文本维持柔和的中性高级灰 */}
|
||||
<p className="text-xs font-medium leading-relaxed text-muted-foreground/90 px-2">
|
||||
{t('storageCleaner:errorStandardOnly')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import React from 'react';
|
||||
import { formatSize } from '@/utils/storageCleaner';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils';
|
||||
// 引入官方的 Checkbox 原子组件
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
|
||||
interface OptionItemProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
labelKey: string;
|
||||
checked: boolean;
|
||||
size?: number;
|
||||
isCount?: boolean;
|
||||
onChange: () => void;
|
||||
}
|
||||
|
||||
export default function OptionItem({
|
||||
labelKey,
|
||||
checked,
|
||||
size,
|
||||
isCount = false,
|
||||
onChange,
|
||||
className,
|
||||
...props
|
||||
}: OptionItemProps) {
|
||||
const { t } = useI18n('storageCleaner');
|
||||
|
||||
return (
|
||||
<div
|
||||
// 3. 跨越级交互升级:将外部容器升级为一个高度敏感的可点击 Tab 热区
|
||||
onClick={onChange}
|
||||
className={cn(
|
||||
'flex justify-between items-center py-2.5 px-3.5 rounded-xl border cursor-pointer select-none',
|
||||
// 4. 彻底抛弃硬编码黄底:
|
||||
// - 选中时:使用 bg-primary/5 (系统主色超淡叠加) 配合标准 border-primary/30。
|
||||
// - 未选中时:保持透明 border-transparent,悬停呈现 bg-muted。
|
||||
// 这样在暗黑模式下会自动无缝混色,极为深邃、高级。
|
||||
checked
|
||||
? 'bg-primary/5 border-primary/30 shadow-sm'
|
||||
: 'bg-transparent border-transparent hover:bg-muted/70',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 左侧数据区域 */}
|
||||
<div className="flex-1 min-w-0 mr-4">
|
||||
<span
|
||||
className={cn(
|
||||
'block text-xs font-semibold leading-tight truncate',
|
||||
checked ? 'text-foreground font-bold' : 'text-foreground/80',
|
||||
)}
|
||||
>
|
||||
{t(labelKey)}
|
||||
</span>
|
||||
|
||||
{/* 底部容量大小或计数标识 */}
|
||||
{size !== undefined && size > 0 ? (
|
||||
<span className="block text-[10px] font-mono font-medium text-muted-foreground/80 mt-0.5 tabular-nums">
|
||||
{isCount ? `${size} ${t('storageCleaner:countUnit')}` : formatSize(size)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="block text-[10px] font-medium text-muted-foreground/60 mt-0.5 italic">
|
||||
{t('storageCleaner:noData')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 5. 超进化:全面替换原生 input 标签
|
||||
完美调用 shadcn 的 Checkbox 组件。它自带全站统一的主色(Primary)、
|
||||
打钩选中时的平滑微放大缩放动效(Scale Animation),
|
||||
并且阻止冒泡,防范与外层的全局覆盖点击事件产生双重冲突。
|
||||
*/}
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
// 阻止 Checkbox 自身的点击事件冒泡,因为外层 div 已经代理了点击逻辑
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onCheckedChange={onChange}
|
||||
className="h-4 w-4 shrink-0 rounded border-input data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
import type { StorageCleanerOptions } from '@/types/storage';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface StorageCleanerConfirmProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onConfirm: () => void;
|
||||
options: StorageCleanerOptions;
|
||||
}
|
||||
|
||||
export function StorageCleanerConfirm({
|
||||
open,
|
||||
onClose,
|
||||
onConfirm,
|
||||
options,
|
||||
}: StorageCleanerConfirmProps) {
|
||||
const { t } = useI18n('storageCleaner');
|
||||
|
||||
const selectedOptions = Object.entries(options)
|
||||
.filter(([_, value]) => value)
|
||||
.map(([key, _]) => t(`storageCleaner:options.${key as keyof StorageCleanerOptions}`));
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
|
||||
{/* 💡 终极修复秘诀:
|
||||
- 移除原来的 sm:max-w-[360px],改用 max-w-[calc(100%-32px)] 或者是 w-[88%]。
|
||||
- 这样无论插件弹窗多窄,它的左右两侧都必然会被强制挤出至少 16px 的完美空白护边!
|
||||
- 将 p-5 转换为明确的 p-6,增大弹窗内部的呼吸感。
|
||||
*/}
|
||||
<DialogContent
|
||||
className={cn(
|
||||
'w-[90%] max-w-[340px] p-6 gap-0 rounded-2xl overflow-hidden shadow-xl border border-border bg-card text-card-foreground',
|
||||
)}
|
||||
>
|
||||
{/* 头部标题区域 */}
|
||||
<DialogHeader className="pt-1">
|
||||
<DialogTitle className="text-center text-lg font-bold tracking-tight text-foreground">
|
||||
{t('storageCleaner:confirmTitle')}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* 内容主体:限制最大宽度,防止内部元素在大分辨率下被横向拉得太松散 */}
|
||||
<div className="text-center py-4 flex flex-col items-center w-full max-w-[280px] mx-auto">
|
||||
<DialogDescription className="mb-4 text-xs font-medium text-muted-foreground/90 leading-relaxed">
|
||||
{t('storageCleaner:confirmDesc')}
|
||||
</DialogDescription>
|
||||
|
||||
{/* 待清理项目徽章群 */}
|
||||
<div className="flex flex-wrap gap-1.5 justify-center mb-5 w-full">
|
||||
{selectedOptions.map((label) => (
|
||||
<Badge
|
||||
key={label}
|
||||
variant="secondary"
|
||||
className="px-2.5 py-0.5 text-[11px] font-semibold border border-border/40 select-none bg-muted/60"
|
||||
>
|
||||
{label}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 风险警告横幅 */}
|
||||
<div className="inline-flex items-center justify-center gap-1.5 px-3.5 py-2 rounded-lg bg-destructive/5 border border-dashed border-destructive/20 w-full max-w-[240px]">
|
||||
<AlertTriangle className="h-3.5 w-3.5 text-destructive shrink-0" />
|
||||
<span className="text-[11px] font-bold text-destructive leading-none tracking-tight">
|
||||
{t('storageCleaner:irreversible')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部操作按钮区:
|
||||
💡 修复要点:
|
||||
- 增加 pt-2 隔开上方危险条。
|
||||
- 显式通过 w-full 配合 flex-col 铺满,在移动端/窄插件下垂直堆叠,最符合小屏直觉。
|
||||
*/}
|
||||
<DialogFooter className="flex flex-col gap-2 w-full pt-2">
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={onConfirm}
|
||||
className="w-full text-xs font-bold shadow-sm h-9"
|
||||
>
|
||||
{t('storageCleaner:confirmAction')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
className="w-full text-xs font-semibold shadow-sm h-9 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{t('common_buttons_cancel')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default StorageCleanerConfirm;
|
||||
@@ -0,0 +1,98 @@
|
||||
import React from 'react';
|
||||
import type { StorageCleanerOptions } from '@/types/storage';
|
||||
import OptionItem from './OptionItem';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils';
|
||||
// 1. 引入官方标准的 Checkbox 原子组件
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
interface StorageOptionsGridProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
options: StorageCleanerOptions;
|
||||
sizes: Record<string, number>;
|
||||
allSelected: boolean;
|
||||
someSelected: boolean; // 重新激活半选状态
|
||||
onOptionChange: (key: keyof StorageCleanerOptions) => void;
|
||||
onSelectAll: (checked: boolean) => void;
|
||||
}
|
||||
|
||||
export default function StorageOptionsGrid({
|
||||
options,
|
||||
sizes,
|
||||
allSelected,
|
||||
someSelected,
|
||||
onOptionChange,
|
||||
onSelectAll,
|
||||
className,
|
||||
...props
|
||||
}: StorageOptionsGridProps) {
|
||||
const { t } = useI18n('storageCleaner');
|
||||
|
||||
const optionKeys: { key: keyof StorageCleanerOptions; isCount?: boolean }[] = [
|
||||
{ key: 'localStorage' },
|
||||
{ key: 'sessionStorage' },
|
||||
{ key: 'indexedDB' },
|
||||
{ key: 'cookies' },
|
||||
{ key: 'cacheStorage', isCount: true },
|
||||
{ key: 'serviceWorkers', isCount: true },
|
||||
];
|
||||
|
||||
// 2. 处理全选栏点击事件:包裹整个栏变成超级热区
|
||||
const handleToggleAll = () => {
|
||||
// 如果当前已经是全选,点击则取消全选;否则,点击就是全选
|
||||
onSelectAll(!allSelected);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 核心网格区 */}
|
||||
<div className="p-3">
|
||||
{/* 💡 优化点:加入 items-stretch,确保左右卡片高度绝对对齐 */}
|
||||
<div className="grid grid-cols-2 gap-2.5 items-stretch">
|
||||
{optionKeys.map(({ key, isCount }) => (
|
||||
/* 💡 终极修复:直接把 key 挂在 OptionItem 上,移除了无意义的包裹 div */
|
||||
<OptionItem
|
||||
key={key}
|
||||
labelKey={`storageCleaner:options.${key}`}
|
||||
checked={options[key]}
|
||||
size={sizes[key]}
|
||||
isCount={isCount}
|
||||
onChange={() => onOptionChange(key)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 3. 全选功能底护栏超进化:
|
||||
- 整体赋予 cursor-pointer 和 onClick,点击一整行都能触发全选。
|
||||
- 悬停时自动变色提示可点击 (hover:bg-muted/50)。
|
||||
*/}
|
||||
<div
|
||||
onClick={handleToggleAll}
|
||||
className="border-t border-border flex justify-between items-center px-4 py-2.5 bg-muted/20 hover:bg-muted/50 cursor-pointer select-none"
|
||||
>
|
||||
<Label className="text-xs font-bold text-muted-foreground/90 cursor-pointer">
|
||||
{t('storageCleaner:selectAll')}
|
||||
</Label>
|
||||
|
||||
{/* 4. 降维打击:调用标准的 shadcn/ui Checkbox
|
||||
- 阻止冒泡:防止事件重复触发。
|
||||
- 完美注入半选逻辑:当 allSelected 为 false 但 someSelected 为 true 时,
|
||||
组件会自动呈现优雅的 "—" (减号) 半选视觉状态,向主流系统控制台高标准看齐!
|
||||
*/}
|
||||
<Checkbox
|
||||
checked={allSelected ? true : someSelected ? 'indeterminate' : false}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onCheckedChange={(checked) => onSelectAll(checked === true)}
|
||||
className="h-4 w-4 shrink-0 rounded border-input data-[state=checked]:bg-primary data-[state=indeterminate]:bg-primary"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { Loader2 } from 'lucide-react'; // 引入标准的高级阻尼 Spinner 图标
|
||||
import { Button } from '@/components/ui/button';
|
||||
import StorageCleanerConfirm from '@/pages/StorageCleaner/StorageCleanerConfirm';
|
||||
import { useStorageCleaner } from './useStorageCleaner';
|
||||
import StorageOptionsGrid from './StorageOptionsGrid';
|
||||
import AutoRefreshToggle from './AutoRefreshToggle';
|
||||
import ErrorDisplay from './ErrorDisplay';
|
||||
import CleaningResult from './CleaningResult';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useI18n('storageCleaner');
|
||||
|
||||
const {
|
||||
error,
|
||||
isInitializing,
|
||||
options,
|
||||
sizes,
|
||||
reloadAfterClean,
|
||||
loading,
|
||||
result,
|
||||
showConfirm,
|
||||
setShowConfirm,
|
||||
allSelected,
|
||||
someSelected,
|
||||
handleReloadAfterCleanChange,
|
||||
handleOptionChange,
|
||||
handleSelectAll,
|
||||
handleClean,
|
||||
} = useStorageCleaner();
|
||||
|
||||
const isButtonDisabled = !(someSelected || allSelected) || loading;
|
||||
|
||||
if (isInitializing) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-12 min-h-[280px] w-full">
|
||||
<Loader2 className="h-6 w-6 text-muted-foreground/80" />
|
||||
<span className="text-xs text-muted-foreground mt-2 font-medium tracking-wide">
|
||||
{t('storageCleaner:initializing')}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return <ErrorDisplay error={error} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-4 w-full flex flex-col space-y-3.5">
|
||||
<StorageOptionsGrid
|
||||
options={options}
|
||||
sizes={sizes}
|
||||
allSelected={allSelected}
|
||||
someSelected={someSelected}
|
||||
onOptionChange={handleOptionChange}
|
||||
onSelectAll={handleSelectAll}
|
||||
/>
|
||||
|
||||
<AutoRefreshToggle
|
||||
reloadAfterClean={reloadAfterClean}
|
||||
onChange={handleReloadAfterCleanChange}
|
||||
/>
|
||||
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="default"
|
||||
onClick={() => setShowConfirm(true)}
|
||||
disabled={isButtonDisabled}
|
||||
className="w-full h-10 font-bold shadow-sm text-sm tracking-wide"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('storageCleaner:cleaning')}
|
||||
</>
|
||||
) : (
|
||||
t('storageCleaner:cleanNow')
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<CleaningResult result={result} />
|
||||
|
||||
<StorageCleanerConfirm
|
||||
open={showConfirm}
|
||||
onClose={() => setShowConfirm(false)}
|
||||
onConfirm={handleClean}
|
||||
options={options}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
import type {
|
||||
CleaningResult,
|
||||
StorageCleanerOptions,
|
||||
StorageCleanerPreferences,
|
||||
} from '@/types/storage';
|
||||
import {
|
||||
clearStorage,
|
||||
getCacheStorageSize,
|
||||
getCookieSize,
|
||||
getCurrentTab,
|
||||
getLocalStorageSize,
|
||||
getOriginStorageEstimate,
|
||||
getServiceWorkerCount,
|
||||
getSessionStorageSize,
|
||||
isRestrictedUrl,
|
||||
} from '@/utils/storageCleaner';
|
||||
import { MessageAction, sendMessage } from '@/utils/messages';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { toast } from 'sonner'; // 1. 直接引用 shadcn 推荐的 Sonner 单例通知,踢出回调依赖
|
||||
|
||||
const DEFAULT_OPTIONS: StorageCleanerOptions = {
|
||||
localStorage: true,
|
||||
sessionStorage: true,
|
||||
indexedDB: true,
|
||||
cookies: true,
|
||||
cacheStorage: true,
|
||||
serviceWorkers: true,
|
||||
};
|
||||
|
||||
const DEFAULT_PREFERENCES: StorageCleanerPreferences = {
|
||||
reloadAfterClean: true,
|
||||
selectedTypes: DEFAULT_OPTIONS,
|
||||
};
|
||||
|
||||
export interface UseStorageCleanerReturn {
|
||||
domain: string;
|
||||
error: string;
|
||||
isInitializing: boolean;
|
||||
options: StorageCleanerOptions;
|
||||
sizes: Record<string, number>;
|
||||
reloadAfterClean: boolean;
|
||||
loading: boolean;
|
||||
result: CleaningResult | null;
|
||||
showConfirm: boolean;
|
||||
setShowConfirm: (show: boolean) => void;
|
||||
totalSize: number;
|
||||
allSelected: boolean;
|
||||
someSelected: boolean;
|
||||
|
||||
handleReloadAfterCleanChange: (checked: boolean) => void;
|
||||
handleOptionChange: (key: keyof StorageCleanerOptions) => void;
|
||||
handleSelectAll: (checked: boolean) => void;
|
||||
handleClean: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function useStorageCleaner(): UseStorageCleanerReturn {
|
||||
const { t } = useI18n(['storageCleaner', 'common']);
|
||||
const [domain, setDomain] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
const [isInitializing, setIsInitializing] = useState<boolean>(true);
|
||||
const [options, setOptions] = useState<StorageCleanerOptions>(DEFAULT_OPTIONS);
|
||||
const [sizes, setSizes] = useState<Record<string, number>>({});
|
||||
const [reloadAfterClean, setReloadAfterClean] = useState<boolean>(true);
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
const [result, setResult] = useState<CleaningResult | null>(null);
|
||||
const [showConfirm, setShowConfirm] = useState<boolean>(false);
|
||||
|
||||
const requestIdRef = useRef<number>(0);
|
||||
const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const storageTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const loadingRef = useRef(loading);
|
||||
|
||||
useEffect(() => {
|
||||
loadingRef.current = loading;
|
||||
}, [loading]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
|
||||
if (storageTimerRef.current) clearTimeout(storageTimerRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 核心数据拉取链条
|
||||
const loadInfo = useCallback(async () => {
|
||||
const currentRequestId = ++requestIdRef.current;
|
||||
try {
|
||||
const tab = await getCurrentTab();
|
||||
if (currentRequestId !== requestIdRef.current) return;
|
||||
|
||||
if (!tab || !tab.url) {
|
||||
setError(t('storageCleaner:errorNoTab'));
|
||||
return;
|
||||
}
|
||||
if (isRestrictedUrl(tab.url)) {
|
||||
setError(t('storageCleaner:errorRestricted'));
|
||||
return;
|
||||
}
|
||||
|
||||
setError('');
|
||||
const url = tab.url;
|
||||
const tabId = tab.id!;
|
||||
setDomain(new URL(url).hostname);
|
||||
|
||||
const [savedPrefs, cSize, lsSize, ssSize, idbSize, cacheCount, swCount] = await Promise.all([
|
||||
storageUtil.get('storageCleaner/preferences', DEFAULT_PREFERENCES),
|
||||
getCookieSize(url),
|
||||
getLocalStorageSize(tabId),
|
||||
getSessionStorageSize(tabId),
|
||||
getOriginStorageEstimate(tabId),
|
||||
getCacheStorageSize(tabId),
|
||||
getServiceWorkerCount(tabId),
|
||||
]);
|
||||
|
||||
if (currentRequestId !== requestIdRef.current) return;
|
||||
|
||||
if (savedPrefs) {
|
||||
setReloadAfterClean(savedPrefs.reloadAfterClean ?? DEFAULT_PREFERENCES.reloadAfterClean);
|
||||
setOptions(savedPrefs.selectedTypes ?? DEFAULT_PREFERENCES.selectedTypes);
|
||||
}
|
||||
|
||||
setSizes({
|
||||
cookies: cSize,
|
||||
localStorage: lsSize,
|
||||
sessionStorage: ssSize,
|
||||
indexedDB: idbSize,
|
||||
cacheStorage: cacheCount,
|
||||
serviceWorkers: swCount,
|
||||
});
|
||||
} finally {
|
||||
if (currentRequestId === requestIdRef.current) {
|
||||
setIsInitializing(false);
|
||||
}
|
||||
}
|
||||
}, [t]);
|
||||
|
||||
const loadInfoRef = useRef(loadInfo);
|
||||
useEffect(() => {
|
||||
loadInfoRef.current = loadInfo;
|
||||
});
|
||||
|
||||
const debouncedLoadInfo = useCallback(() => {
|
||||
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
|
||||
debounceTimerRef.current = setTimeout(() => {
|
||||
loadInfoRef.current().catch(console.error);
|
||||
}, 300);
|
||||
}, []);
|
||||
|
||||
// 监听浏览器标签行为
|
||||
useEffect(() => {
|
||||
loadInfoRef.current().catch(console.error);
|
||||
|
||||
const handleTabChange = () => debouncedLoadInfo();
|
||||
const handleTabUpdated = (_tabId: number, changeInfo: { status?: string; url?: string }) => {
|
||||
if (changeInfo.status === 'complete' || changeInfo.url) {
|
||||
debouncedLoadInfo();
|
||||
}
|
||||
};
|
||||
|
||||
chrome.tabs.onActivated.addListener(handleTabChange);
|
||||
chrome.tabs.onUpdated.addListener(handleTabUpdated);
|
||||
chrome.windows.onFocusChanged.addListener(handleTabChange);
|
||||
|
||||
return () => {
|
||||
chrome.tabs.onActivated.removeListener(handleTabChange);
|
||||
chrome.tabs.onUpdated.removeListener(handleTabUpdated);
|
||||
chrome.windows.onFocusChanged.removeListener(handleTabChange);
|
||||
};
|
||||
}, [debouncedLoadInfo]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isInitializing) return;
|
||||
|
||||
if (storageTimerRef.current) clearTimeout(storageTimerRef.current);
|
||||
storageTimerRef.current = setTimeout(async () => {
|
||||
await storageUtil
|
||||
.set('storageCleaner/preferences', {
|
||||
reloadAfterClean,
|
||||
selectedTypes: options,
|
||||
})
|
||||
.catch(console.error);
|
||||
}, 500);
|
||||
}, [options, reloadAfterClean, isInitializing]);
|
||||
|
||||
const handleReloadAfterCleanChange = useCallback((checked: boolean) => {
|
||||
setReloadAfterClean(checked);
|
||||
}, []);
|
||||
|
||||
const handleOptionChange = useCallback((key: keyof StorageCleanerOptions) => {
|
||||
setOptions((prev) => ({ ...prev, [key]: !prev[key] }));
|
||||
}, []);
|
||||
|
||||
const handleSelectAll = useCallback((checked: boolean) => {
|
||||
setOptions({
|
||||
localStorage: checked,
|
||||
sessionStorage: checked,
|
||||
indexedDB: checked,
|
||||
cookies: checked,
|
||||
cacheStorage: checked,
|
||||
serviceWorkers: checked,
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleClean = useCallback(async () => {
|
||||
if (loadingRef.current) return;
|
||||
|
||||
const tab = await getCurrentTab();
|
||||
if (!tab || !tab.id || !tab.url) {
|
||||
toast.warning(t('storageCleaner:errorNoTab'));
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const cleaningResult = await clearStorage(tab.id, tab.url, options);
|
||||
setResult(cleaningResult);
|
||||
|
||||
if (reloadAfterClean && cleaningResult.success) {
|
||||
toast.success(t('storageCleaner:cleanSuccessReload'));
|
||||
await sendMessage(MessageAction.RELOAD_TAB, { tabId: tab.id, delay: 1000 });
|
||||
} else {
|
||||
await loadInfo();
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error(`${t('storageCleaner:cleanError')}: ${String(err)}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setShowConfirm(false);
|
||||
}
|
||||
}, [options, reloadAfterClean, loadInfo, t]);
|
||||
|
||||
const totalSize = useMemo(() => {
|
||||
return (
|
||||
(sizes.cookies || 0) +
|
||||
(sizes.localStorage || 0) +
|
||||
(sizes.sessionStorage || 0) +
|
||||
(sizes.indexedDB || 0)
|
||||
);
|
||||
}, [sizes]);
|
||||
|
||||
const selectionMetrics = useMemo(() => {
|
||||
const vals = Object.values(options);
|
||||
const all = vals.every(Boolean);
|
||||
const some = vals.some(Boolean) && !all;
|
||||
return { all, some };
|
||||
}, [options]);
|
||||
|
||||
return {
|
||||
domain,
|
||||
error,
|
||||
isInitializing,
|
||||
options,
|
||||
sizes,
|
||||
reloadAfterClean,
|
||||
loading,
|
||||
result,
|
||||
showConfirm,
|
||||
setShowConfirm,
|
||||
totalSize,
|
||||
allSelected: selectionMetrics.all,
|
||||
someSelected: selectionMetrics.some,
|
||||
handleReloadAfterCleanChange,
|
||||
handleOptionChange,
|
||||
handleSelectAll,
|
||||
handleClean,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { formatByteSize, getTextStats } from '@/utils/textStatistics';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useI18n('textStatistics');
|
||||
const [text, setText] = useState('');
|
||||
|
||||
const handleContextMenuData = useCallback((payload: string) => {
|
||||
setText(payload);
|
||||
}, []);
|
||||
|
||||
useContextMenuData({ featureKey: 'textStatistics', onData: handleContextMenuData });
|
||||
|
||||
// 实时计算统计信息,由 useMemo 拦截非必要计算
|
||||
const stats = useMemo(() => getTextStats(text), [text]);
|
||||
|
||||
const statItems = [
|
||||
{ label: t('textStatistics:characters'), value: stats.characters },
|
||||
{ label: t('textStatistics:words'), value: stats.words },
|
||||
{ label: t('textStatistics:lines'), value: stats.lines },
|
||||
{ label: t('textStatistics:bytes'), value: formatByteSize(stats.bytes) },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="p-4 w-full space-y-4">
|
||||
{/* 文本输入区域 */}
|
||||
<TextInputArea
|
||||
value={text}
|
||||
onChange={setText}
|
||||
placeholder={t('textStatistics:placeholder')}
|
||||
minRows={10}
|
||||
maxRows={18}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
/>
|
||||
|
||||
{/* 统计结果展示区域 */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
{statItems.map((item) => (
|
||||
<div
|
||||
key={item.label}
|
||||
className={cn(
|
||||
'flex flex-col justify-center items-center p-4 text-center rounded-xl border border-border bg-card shadow-sm text-card-foreground',
|
||||
'hover:-translate-y-0.5 hover:shadow-md hover:border-primary/50 focus-within:ring-1 focus-within:ring-ring',
|
||||
)}
|
||||
>
|
||||
<span className="text-xs font-medium text-muted-foreground tracking-wider mb-1 select-none">
|
||||
{item.label}
|
||||
</span>
|
||||
<span className="font-mono text-lg md:text-2xl font-extrabold text-primary break-all tracking-tight leading-none tabular-nums select-all">
|
||||
{item.value}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Clock } from 'lucide-react';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import type { UnitType } from './constants';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils'; // 引入标准的 shadcn 工具函数
|
||||
|
||||
interface LiveClockProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
unit: UnitType;
|
||||
onUseNow: (val: number) => void;
|
||||
}
|
||||
|
||||
const LiveClock = React.memo(({ unit, onUseNow, className, ...props }: LiveClockProps) => {
|
||||
const { t } = useI18n('timestamp');
|
||||
const { showMessage } = useSnackbar();
|
||||
const onUseNowRef = useRef(onUseNow);
|
||||
|
||||
// 1. 采用毫秒/秒的双态原子计数,避免无意义的重绘
|
||||
const [currentDisplay, setCurrentDisplay] = useState(() => {
|
||||
const initNow = Date.now();
|
||||
return {
|
||||
rawTime: initNow,
|
||||
text: String(Math.floor(initNow / (unit === 'ms' ? 1 : 1000))),
|
||||
};
|
||||
});
|
||||
|
||||
// 始终保持外部回调指针最新
|
||||
useEffect(() => {
|
||||
onUseNowRef.current = onUseNow;
|
||||
}, [onUseNow]);
|
||||
|
||||
// 2. 高频高灵敏度计时器 (200ms 刷新率)
|
||||
useEffect(() => {
|
||||
const tick = () => {
|
||||
const rightNow = Date.now();
|
||||
const nextText = String(Math.floor(rightNow / (unit === 'ms' ? 1 : 1000)));
|
||||
|
||||
// 性能核心:只有当生成的文本内容发生变化时,才触发 React 的 State 更新。
|
||||
// 在“秒(s)”单位下,这可以让组件的渲染频率暴跌 90%,做到极度省电和高性能。
|
||||
setCurrentDisplay((prev) => {
|
||||
if (prev.text === nextText) return prev;
|
||||
return { rawTime: rightNow, text: nextText };
|
||||
});
|
||||
};
|
||||
|
||||
// 200ms 的高速低延迟轮询,比 1000ms 更具响应灵敏度,且因为上面有过滤,完全不用担心引发性能损耗
|
||||
const tickId = setInterval(tick, 200);
|
||||
return () => clearInterval(tickId);
|
||||
}, [unit]);
|
||||
|
||||
const handleUseNow = useCallback(() => {
|
||||
// 捕获真实极其精准的绝对时间戳
|
||||
onUseNowRef.current(currentDisplay.rawTime);
|
||||
showMessage?.(t('timestamp:usedSuccess'), { severity: 'success' });
|
||||
}, [currentDisplay.rawTime, showMessage, t]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
// 3. 完美适配 shadcn 暗黑模式:
|
||||
// 不再写死 bg-primary/10,改用更高级的 bg-secondary/50 和中性边框,
|
||||
// 在任何主题色下都能表现得低调且极具质感。
|
||||
'flex items-center gap-3 px-3 h-10 rounded-lg border border-border/80 bg-secondary/50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="text-muted-foreground font-bold text-[10px] uppercase tracking-wider whitespace-nowrap shrink-0 selection:bg-transparent select-none">
|
||||
{t('timestamp:currentTs')}
|
||||
</span>
|
||||
|
||||
{/* 4. tabular-nums 强制使用等宽数字布局,彻底消灭数字跳动时字符宽度不同带来的抖动颤噪感 */}
|
||||
<span className="flex-1 font-mono font-bold text-foreground text-sm tracking-tight leading-none truncate tabular-nums">
|
||||
{currentDisplay.text}
|
||||
</span>
|
||||
|
||||
{/* 5. 按钮重构成精巧的 shadcn 原子微动效风格 */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleUseNow}
|
||||
title={t('timestamp:useNowTooltip')}
|
||||
className="flex h-7 w-7 items-center justify-center rounded-md border border-input bg-background text-muted-foreground shadow-sm hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
>
|
||||
<Clock className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
<CopyButton
|
||||
text={currentDisplay.text}
|
||||
tooltip={t('timestamp:copyTsTooltip')}
|
||||
className="h-7 w-7 rounded-md border"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
LiveClock.displayName = 'LiveClock';
|
||||
|
||||
export default LiveClock;
|
||||
@@ -0,0 +1,131 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import dayjs from '@/utils/dayjs';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import type { UnitType } from './constants';
|
||||
import { DATE_FORMAT } from './constants';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils'; // shadcn 核心类名合并工具
|
||||
|
||||
interface ResultViewProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
result: string;
|
||||
mode: 'ts2dt' | 'dt2ts';
|
||||
unit: UnitType;
|
||||
zone: string;
|
||||
/** 无结果时是否渲染占位(桌面端右栏使用),默认 false */
|
||||
showEmptyPlaceholder?: boolean;
|
||||
}
|
||||
|
||||
const ResultView = React.memo(
|
||||
({
|
||||
result,
|
||||
mode,
|
||||
unit,
|
||||
zone,
|
||||
showEmptyPlaceholder = false,
|
||||
className,
|
||||
...props
|
||||
}: ResultViewProps) => {
|
||||
const { t } = useI18n('timestamp');
|
||||
|
||||
// 严谨计算时间衍生的附加时区/相对时间状态
|
||||
const extraInfo = useMemo(() => {
|
||||
if (!result) return null;
|
||||
const d =
|
||||
mode === 'ts2dt'
|
||||
? dayjs(result, DATE_FORMAT).tz(zone)
|
||||
: unit === 'ms'
|
||||
? dayjs(Number(result))
|
||||
: dayjs.unix(Number(result));
|
||||
|
||||
return {
|
||||
relative: d.fromNow(),
|
||||
iso: d.toISOString(),
|
||||
utc: d.utc().format(DATE_FORMAT) + ' UTC',
|
||||
};
|
||||
}, [result, mode, zone, unit]);
|
||||
|
||||
// 1. 空状态骨架面板:优雅匹配 shadcn 的中性灰色居中占位
|
||||
if (!result) {
|
||||
if (!showEmptyPlaceholder) return null;
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex-1 flex items-center justify-center text-sm font-medium border border-dashed border-border/60 rounded-xl py-12 px-4 text-center text-muted-foreground bg-muted/20 min-h-[320px]',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{t('timestamp:resultEmpty')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-col w-full', className)} {...props}>
|
||||
{/* 顶部小标签 */}
|
||||
<span className="block text-muted-foreground/90 mb-2.5 text-xs font-semibold tracking-wider uppercase">
|
||||
{t('timestamp:resultLabel')}
|
||||
</span>
|
||||
|
||||
{/*
|
||||
2. 核心结果大卡片:
|
||||
对齐 shadcn 官方卡片风格,使用 bg-card、border-border 构筑多层级阴影。
|
||||
核心数值直接拉粗为 text-foreground (在黑夜模式下会自动转为大气的纯白,完美避开刺眼强光)
|
||||
*/}
|
||||
<div className="bg-card text-card-foreground border border-border p-4 sm:p-5 rounded-xl relative mb-3.5 shadow-sm flex justify-between items-center gap-4 focus-within:ring-1 focus-within:ring-ring">
|
||||
<span className="font-mono font-extrabold text-foreground break-all text-xl sm:text-2xl tracking-tight leading-tight select-all tabular-nums">
|
||||
{result}
|
||||
</span>
|
||||
<CopyButton
|
||||
text={result}
|
||||
tooltip={t('timestamp:copyResultTooltip')}
|
||||
className="h-8 w-8 rounded-md shrink-0 border"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/*
|
||||
3. 衍生的附加参考数据区:
|
||||
背景改为低饱和度的 bg-muted/40 隔离带。
|
||||
内部数值降级为 text-muted-foreground,建立教科书般的完美“视觉权重层级”。
|
||||
*/}
|
||||
<div className="bg-muted/40 p-4 rounded-xl border border-border/50 flex flex-col gap-3">
|
||||
{[
|
||||
{ label: t('timestamp:relativeTime'), value: extraInfo?.relative },
|
||||
{ label: t('timestamp:iso8601'), value: extraInfo?.iso, isMono: true },
|
||||
{ label: t('timestamp:utcTime'), value: extraInfo?.utc, isMono: true },
|
||||
].map((item) => (
|
||||
<div
|
||||
key={item.label}
|
||||
className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-1.5 py-0.5 border-b border-border/30 last:border-0 pb-2 sm:pb-0 last:pb-0"
|
||||
>
|
||||
<span className="text-muted-foreground font-semibold text-xs shrink-0 select-none">
|
||||
{item.label}
|
||||
</span>
|
||||
<div className="flex items-center justify-between sm:justify-end gap-2 min-w-0 w-full sm:w-auto">
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs text-foreground/90 font-medium break-all text-left sm:text-right tabular-nums',
|
||||
item.isMono && 'font-mono text-[11px]', // ISO/UTC 等机器时间使用精细化等宽代码体
|
||||
)}
|
||||
>
|
||||
{item.value}
|
||||
</span>
|
||||
{item.value && (
|
||||
<CopyButton
|
||||
text={item.value}
|
||||
tooltip={t('timestamp:copyTooltip')}
|
||||
className="h-6 w-6 rounded-md border shrink-0 text-muted-foreground"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ResultView.displayName = 'ResultView';
|
||||
|
||||
export default ResultView;
|
||||
@@ -0,0 +1,6 @@
|
||||
export const DATE_FORMAT = 'YYYY/MM/DD HH:mm:ss';
|
||||
|
||||
export const ZONES = ['Asia/Shanghai', 'America/New_York', 'Europe/London'] as const;
|
||||
|
||||
export type UnitType = 'ms' | 's';
|
||||
export type ZoneType = (typeof ZONES)[number];
|
||||
@@ -0,0 +1,133 @@
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import { ZONES } from './constants';
|
||||
import LiveClock from './LiveClock';
|
||||
import ResultView from './ResultView';
|
||||
import { useTimestampConverter } from './useTimestampConverter';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// 1. 引入标准的 shadcn/ui 原子表单组件(代替原生的原生 Input 和 Select)
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useI18n('timestamp');
|
||||
|
||||
// 2. 完美对接全新重构后的统一单源响应式 Hook
|
||||
const {
|
||||
mode,
|
||||
input,
|
||||
unit,
|
||||
zone,
|
||||
result,
|
||||
error,
|
||||
setMode,
|
||||
setInput,
|
||||
setUnit,
|
||||
setZone,
|
||||
handleUseNow,
|
||||
} = useTimestampConverter();
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-foreground antialiased selection:bg-primary/20">
|
||||
<div className="max-w-7xl mx-auto p-4 sm:p-6 space-y-4">
|
||||
{/* 动态参考信息时钟条 */}
|
||||
<LiveClock unit={unit} onUseNow={handleUseNow} />
|
||||
|
||||
{/* 核心工作台网格:桌面端 md+ 左右等宽分栏;移动端单栏堆叠 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-stretch">
|
||||
{/* 左栏:转换工作台 */}
|
||||
<div className="p-5 rounded-xl border border-border bg-card text-card-foreground shadow-sm flex flex-col justify-between">
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* 模式选择切换组 */}
|
||||
<SwitchButtonGroup
|
||||
value={mode}
|
||||
options={[
|
||||
{ value: 'ts2dt', label: t('timestamp:tsToDate') },
|
||||
{ value: 'dt2ts', label: t('timestamp:dateToTs') },
|
||||
]}
|
||||
onChange={(newMode) => setMode(newMode as 'ts2dt' | 'dt2ts')}
|
||||
size="small"
|
||||
/>
|
||||
|
||||
{/* 输入交互区 */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{/*
|
||||
3. 替换为标准的 shadcn <Input /> 组件:
|
||||
享受原生高水准的 focus-visible 环形动画响应。
|
||||
*/}
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={
|
||||
mode === 'ts2dt' ? t('timestamp:placeholderTs') : t('timestamp:placeholderDate')
|
||||
}
|
||||
value={input}
|
||||
onChange={(e: { target: { value: string } }) => setInput(e.target.value)}
|
||||
className={cn(
|
||||
'font-mono font-semibold h-10 shadow-sm placeholder:text-muted-foreground/60 focus:bg-background',
|
||||
error && 'border-destructive focus-visible:ring-destructive',
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* 错误自愈提示 */}
|
||||
{error && <p className="text-destructive text-xs font-medium px-0.5">{error}</p>}
|
||||
</div>
|
||||
|
||||
{/* 核心配置群:单位切换 + 时区选择紧凑横排 */}
|
||||
<div className="flex flex-col sm:flex-row items-stretch gap-3 w-full">
|
||||
{/* 时间精度单位选择 */}
|
||||
<SwitchButtonGroup
|
||||
value={unit}
|
||||
options={[
|
||||
{ value: 'ms', label: t('timestamp:unitMs') },
|
||||
{ value: 's', label: t('timestamp:unitS') },
|
||||
]}
|
||||
onChange={(v) => setUnit(v as 'ms' | 's')}
|
||||
size="small"
|
||||
className="sm:w-auto shrink-0" // 窄屏下全宽,宽屏下自适应收缩
|
||||
/>
|
||||
|
||||
{/*
|
||||
4. 降维打击:将原生 <select> 强行超进化为标准的 shadcn <Select>:
|
||||
全操作系统的样式绝对一致,完美融合暗黑模式,悬浮弹窗自带微距磨砂玻璃阻尼动效。
|
||||
*/}
|
||||
<Select value={zone} onValueChange={(v: string) => setZone(v as typeof zone)}>
|
||||
<SelectTrigger className="flex-1 font-mono font-semibold h-9 shadow-sm bg-background">
|
||||
<SelectValue placeholder="选择时区" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="max-h-64 font-mono">
|
||||
{ZONES.map((z) => (
|
||||
<SelectItem
|
||||
key={z}
|
||||
value={z}
|
||||
className="text-xs font-semibold focus:bg-accent cursor-pointer"
|
||||
>
|
||||
{z}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/*
|
||||
5. 彻底移除了原先丑陋的手动 convert 按钮!
|
||||
在响应式 Hook 的加持下,此处留白或由排版自然撑开,界面视觉极其干净。
|
||||
*/}
|
||||
</div>
|
||||
|
||||
{/* 右栏:结果实时流展示卡片 */}
|
||||
<div className="p-5 rounded-xl border border-border bg-card text-card-foreground shadow-sm h-full flex flex-col">
|
||||
<ResultView result={result} mode={mode} unit={unit} zone={zone} showEmptyPlaceholder />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import dayjs from '@/utils/dayjs';
|
||||
import type { UnitType, ZoneType } from './constants';
|
||||
import { DATE_FORMAT } from './constants';
|
||||
import { useI18n } from '@/utils/chromeI18n';
|
||||
import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||
|
||||
export interface UseTimestampConverterReturn {
|
||||
mode: 'ts2dt' | 'dt2ts';
|
||||
input: string; // 统一为单一受控输入源
|
||||
unit: UnitType;
|
||||
zone: ZoneType;
|
||||
result: string;
|
||||
error: string;
|
||||
|
||||
setMode: (mode: 'ts2dt' | 'dt2ts') => void;
|
||||
setInput: (value: string) => void;
|
||||
setUnit: (unit: UnitType) => void;
|
||||
setZone: (zone: ZoneType) => void;
|
||||
handleUseNow: (now: number) => void;
|
||||
}
|
||||
|
||||
function isTimestampLike(input: string): boolean {
|
||||
const trimmed = input.trim();
|
||||
return /^\d+$/.test(trimmed) && trimmed.length >= 10;
|
||||
}
|
||||
|
||||
export function useTimestampConverter(): UseTimestampConverterReturn {
|
||||
const { t } = useI18n('timestamp');
|
||||
const [mode, setMode] = useState<'ts2dt' | 'dt2ts'>('ts2dt');
|
||||
const [unit, setUnit] = useState<UnitType>('ms');
|
||||
const [zone, setZone] = useState<ZoneType>('Asia/Shanghai');
|
||||
|
||||
// 1. 唯一受控源:不再区分 ts/dt,输入框在当前模式下展现的就是它的值
|
||||
const [input, setInput] = useState(() => String(Date.now()));
|
||||
|
||||
// 2. 核心魔法:利用 useMemo 达成 0 延迟响应式转换 (Reactive Pipeline)
|
||||
// 只要 input, mode, unit, zone 任何一个发生改变,结果和错误信息自动流出,废除 convert 按钮
|
||||
const conversionPipeline = useMemo(() => {
|
||||
const rawInput = input.trim();
|
||||
if (!rawInput) return { result: '', error: '' };
|
||||
|
||||
if (mode === 'ts2dt') {
|
||||
const num = Number(rawInput);
|
||||
if (isNaN(num)) {
|
||||
return { result: '', error: t('timestamp:errors.invalidNumber') };
|
||||
}
|
||||
const d = unit === 'ms' ? dayjs(num) : dayjs.unix(num);
|
||||
if (!d.isValid()) {
|
||||
return { result: '', error: t('timestamp:errors.invalidTimestamp') };
|
||||
}
|
||||
return { result: d.tz(zone).format(DATE_FORMAT), error: '' };
|
||||
} else {
|
||||
const d = dayjs.tz(rawInput, DATE_FORMAT, zone);
|
||||
if (!d.isValid()) {
|
||||
return { result: '', error: t('timestamp:errors.invalidFormat') };
|
||||
}
|
||||
const ms = d.valueOf();
|
||||
const outputTs = unit === 'ms' ? String(ms) : String(Math.floor(ms / 1000));
|
||||
return { result: outputTs, error: '' };
|
||||
}
|
||||
}, [input, mode, unit, zone, t]);
|
||||
|
||||
const { result, error } = conversionPipeline;
|
||||
|
||||
// 3. 处理右键菜单联动(直接修改唯一的 input,衍生转换自动触发)
|
||||
const handleContextMenuData = useCallback((payload: string) => {
|
||||
const trimmed = payload.trim();
|
||||
if (isTimestampLike(trimmed)) {
|
||||
setMode('ts2dt');
|
||||
const detectedUnit: UnitType = trimmed.length >= 13 ? 'ms' : 's';
|
||||
setUnit(detectedUnit);
|
||||
setInput(trimmed);
|
||||
} else {
|
||||
const d = dayjs(trimmed);
|
||||
if (d.isValid()) {
|
||||
setMode('dt2ts');
|
||||
setInput(d.format(DATE_FORMAT));
|
||||
} else {
|
||||
setMode('ts2dt');
|
||||
setInput(trimmed);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
useContextMenuData({ featureKey: 'timestamp', onData: handleContextMenuData });
|
||||
|
||||
const handleUseNow = useCallback(
|
||||
(now: number) => {
|
||||
if (mode === 'ts2dt') {
|
||||
setInput(String(unit === 'ms' ? now : Math.floor(now / 1000)));
|
||||
} else {
|
||||
setInput(dayjs(now).tz(zone).format(DATE_FORMAT));
|
||||
}
|
||||
},
|
||||
[mode, unit, zone],
|
||||
);
|
||||
|
||||
// 4. 尊享级连贯交互:切换 Mode 时,自动把上一个模式计算出的结果喂进输入框
|
||||
// 比如:输入时间戳 -> 得到日期 -> 切换模式 -> 日期直接进入输入框,方便用户进行微调反向转换
|
||||
const handleSetMode = useCallback(
|
||||
(newMode: 'ts2dt' | 'dt2ts') => {
|
||||
setMode(newMode);
|
||||
if (result && !error) {
|
||||
setInput(result);
|
||||
}
|
||||
},
|
||||
[result, error],
|
||||
);
|
||||
|
||||
return {
|
||||
mode,
|
||||
input,
|
||||
unit,
|
||||
zone,
|
||||
result,
|
||||
error,
|
||||
setMode: handleSetMode,
|
||||
setInput,
|
||||
setUnit,
|
||||
setZone,
|
||||
handleUseNow,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user