feat: optimize dashboard/search UX and simplify extension architecture

Redesign Dashboard with compact tool grid and recently used tools
Improve TopBar search UX with Cmd/Ctrl+K shortcut and better history navigation
Reorganize project structure into src/
Migrate i18n from react-i18next to chrome.i18n
Remove runtime language switch and settings page
Remove HTML/Markdown conversion tools
Clean up unused code, dead animations, redundant comments, and imports
Improve component consistency with shadcn/ui patterns
Replace hardcoded strings/colors with i18n tokens and theme tokens
Add comprehensive project documentation and coding standards
Fix CI artifact upload workflow and multiple TypeScript/test issues

Includes various refactors, UI polish, i18n cleanup, CI improvements,
and maintenance updates across the codebase.
This commit is contained in:
LingandRX
2026-05-28 22:39:25 +08:00
committed by GitHub
parent d4c29a1bf4
commit 945780def8
200 changed files with 1557 additions and 4380 deletions
@@ -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>
);
}
+162
View File
@@ -0,0 +1,162 @@
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');
const [input, setInput] = useState('');
const [debouncedInput, setDebouncedInput] = useState('');
const [direction, setDirection] = useState<'encode' | 'decode'>('encode');
useEffect(() => {
const handle = setTimeout(() => {
setDebouncedInput(input);
}, 200);
return () => clearTimeout(handle);
}, [input]);
const handleContextMenuData = useCallback((payload: string) => {
setInput(payload);
setDebouncedInput(payload);
setDirection('decode');
}, []);
useContextMenuData({ featureKey: 'base64Converter', onData: handleContextMenuData });
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();
});
});
+43
View File
@@ -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,153 @@
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,
};
}