Develop fastapi (#6)
* feat: add side panel with navigation and storage cleaner functionality * feat: add OpenUrlPage and integrate into app navigation * feat: 添加 GlobalSnackbar 组件并在多个页面中集成,替换原有 Snackbar 实现 * feat: fix OpenUrl sidebar issue with architecture refactor - 修复原问题:不再直接替换侧边栏 URL,保持插件导航可见 - 采用配置页 + 查看页分离架构:OpenUrlPage (配置) + OpenUrlViewerPage (查看) - 支持多个 URL 快捷方式管理(添加/删除) - 每个 URL 提供两种打开方式:在侧边栏打开 / 在新标签页打开 - 侧边栏查看页使用 iframe 占满全部剩余空间 - 更新 TypeScript 类型定义 - 保留原有混合内容警告检查 - 数据持久化到 Chrome Storage * refactor: centralized route management - consolidate routing config into single source * feat: 更换logo * refactor: code review fixes - security and race condition improvements Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> Changes: - wxt.config.ts: Remove unused `debugger` permission (no code uses it) - OpenUrlPage.tsx: Fix unreachable showMessage after window.close() - OpenUrlPage.tsx: Replace unnecessary div wrapper with Fragment to reduce DOM nesting - OpenUrlViewerPage.tsx: Add URL validation to prevent XSS via javascript:/data: URLs - OpenUrlViewerPage.tsx: Add sandbox attribute to iframe for security isolation - OpenUrlViewerPage.tsx: Add error handling for invalid URLs - StorageCleanerPage.tsx: Fix race condition in handleOptionChange preference saving - StorageCleanerPage.tsx: Remove unnecessary storage reads when saving preferences (use state directly) - StorageCleanerPage.tsx: Add timeout cleanup for setTimeout to follow React best practices * feat: implement drill-down navigation with master-detail dashboard * feat: enhance dashboard dynamism and refine options UI * feat: overhaul storage cleaner UI with real-time size estimation and modern aesthetics * feat: overhaul TimestampPage UI/UX and fix GlobalSnackbar positioning * fix: decouple popup routing from storage sync and enhance OpenUrlPage UI * fix: avoid closing sidepanel when opening URL preview from within sidepanel
@@ -0,0 +1,178 @@
|
||||
import { useState } from 'react';
|
||||
import { Snackbar, Alert, type SxProps, type Theme, alpha } from '@mui/material';
|
||||
|
||||
export type SnackbarSeverity = 'success' | 'info' | 'warning' | 'error';
|
||||
|
||||
export interface GlobalSnackbarProps {
|
||||
/** 消息内容 */
|
||||
message: string;
|
||||
/** 是否显示 */
|
||||
open: boolean;
|
||||
/** 关闭回调 */
|
||||
onClose: () => void;
|
||||
/** 消息级别:影响颜色 */
|
||||
severity?: SnackbarSeverity;
|
||||
/** 自动隐藏时间,毫秒,0 不自动关闭 */
|
||||
autoHideDuration?: number;
|
||||
/** 弹出位置 */
|
||||
anchorOrigin?: {
|
||||
vertical: 'top' | 'bottom';
|
||||
horizontal: 'left' | 'center' | 'right';
|
||||
};
|
||||
/** 是否使用 Alert 包裹(false 则使用原生 Snackbar message) */
|
||||
showAlert?: boolean;
|
||||
/** Alert 是否隐藏图标 */
|
||||
hideIcon?: boolean;
|
||||
/** 自定义样式,透传给 Snackbar */
|
||||
sx?: SxProps<Theme>;
|
||||
/** 自定义样式,透传给 Alert(仅当 showAlert=true 时生效) */
|
||||
alertSx?: SxProps<Theme>;
|
||||
}
|
||||
|
||||
export interface SnackbarOptions {
|
||||
severity?: SnackbarSeverity;
|
||||
autoHideDuration?: number;
|
||||
hideIcon?: boolean;
|
||||
showAlert?: boolean;
|
||||
}
|
||||
|
||||
export interface UseSnackbarResult {
|
||||
snackbarProps: GlobalSnackbarProps;
|
||||
showMessage: (message: string, options?: SnackbarOptions) => void;
|
||||
closeMessage: () => void;
|
||||
}
|
||||
|
||||
const defaultProps: Required<
|
||||
Pick<
|
||||
GlobalSnackbarProps,
|
||||
'severity' | 'autoHideDuration' | 'anchorOrigin' | 'showAlert' | 'hideIcon'
|
||||
>
|
||||
> = {
|
||||
severity: 'info',
|
||||
autoHideDuration: 2000,
|
||||
anchorOrigin: { vertical: 'bottom', horizontal: 'center' },
|
||||
showAlert: true,
|
||||
hideIcon: false,
|
||||
};
|
||||
|
||||
export function GlobalSnackbar({
|
||||
message,
|
||||
open,
|
||||
onClose,
|
||||
severity = defaultProps.severity,
|
||||
autoHideDuration = defaultProps.autoHideDuration,
|
||||
anchorOrigin = defaultProps.anchorOrigin,
|
||||
showAlert = defaultProps.showAlert,
|
||||
hideIcon = defaultProps.hideIcon,
|
||||
sx,
|
||||
alertSx,
|
||||
}: GlobalSnackbarProps) {
|
||||
// 共享的固定定位样式
|
||||
const fixedSx: SxProps<Theme> = {
|
||||
position: 'fixed',
|
||||
bottom: '24px !important', // 固定在视口底部
|
||||
left: '50% !important',
|
||||
transform: 'translateX(-50%) !important',
|
||||
zIndex: (theme) => theme.zIndex.tooltip + 100,
|
||||
maxWidth: '90%',
|
||||
width: 'max-content',
|
||||
};
|
||||
|
||||
if (showAlert) {
|
||||
return (
|
||||
<Snackbar
|
||||
open={open}
|
||||
autoHideDuration={autoHideDuration}
|
||||
onClose={onClose}
|
||||
anchorOrigin={anchorOrigin}
|
||||
disableWindowBlurListener
|
||||
sx={[fixedSx, ...(Array.isArray(sx) ? sx : [sx])]}
|
||||
>
|
||||
<Alert
|
||||
severity={severity}
|
||||
variant="filled"
|
||||
icon={hideIcon ? false : undefined}
|
||||
sx={[
|
||||
{
|
||||
borderRadius: '50px',
|
||||
px: 2.5,
|
||||
py: 0.2,
|
||||
minWidth: '140px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontWeight: 800,
|
||||
fontSize: '0.75rem',
|
||||
letterSpacing: '0.02em',
|
||||
backgroundImage: 'none',
|
||||
boxShadow: (theme: Theme) => `0 12px 32px ${alpha(theme.palette[severity].main, 0.35)}`,
|
||||
|
||||
'& .MuiAlert-icon': {
|
||||
mr: 0.5,
|
||||
fontSize: '1.1rem',
|
||||
color: '#fff'
|
||||
},
|
||||
'& .MuiAlert-message': {
|
||||
color: '#fff',
|
||||
padding: '6px 0',
|
||||
textAlign: 'center'
|
||||
}
|
||||
},
|
||||
...(Array.isArray(alertSx) ? alertSx : [alertSx]),
|
||||
]}
|
||||
>
|
||||
{message}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Snackbar
|
||||
open={open}
|
||||
autoHideDuration={autoHideDuration}
|
||||
onClose={onClose}
|
||||
anchorOrigin={anchorOrigin}
|
||||
message={message}
|
||||
sx={[fixedSx, ...(Array.isArray(sx) ? sx : [sx])]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function useSnackbar(initialOptions?: SnackbarOptions): UseSnackbarResult {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [options, setOptions] = useState<SnackbarOptions>(initialOptions || {});
|
||||
|
||||
const showMessage = (newMessage: string, newOptions: SnackbarOptions = {}) => {
|
||||
setMessage(newMessage);
|
||||
setOptions({ ...initialOptions, ...newOptions });
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const closeMessage = () => {
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleClose = (_event?: React.SyntheticEvent | Event, reason?: string) => {
|
||||
if (reason === 'clickaway') return;
|
||||
closeMessage();
|
||||
};
|
||||
|
||||
const snackbarProps: GlobalSnackbarProps = {
|
||||
message,
|
||||
open,
|
||||
onClose: handleClose,
|
||||
severity: options.severity,
|
||||
autoHideDuration: options.autoHideDuration,
|
||||
hideIcon: options.hideIcon,
|
||||
};
|
||||
|
||||
return {
|
||||
snackbarProps,
|
||||
showMessage,
|
||||
closeMessage,
|
||||
};
|
||||
}
|
||||
|
||||
export default GlobalSnackbar;
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Box } from '@mui/material';
|
||||
import { ROUTES } from '@/config/routes';
|
||||
import { useRouter } from '@/providers/RouterProvider';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
export default function RouterContainer() {
|
||||
const { currentPage, isLoaded } = useRouter();
|
||||
|
||||
const animationClass = useMemo(() => {
|
||||
return currentPage === 'dashboard' ? 'page-transition-dashboard' : 'page-transition-enter';
|
||||
}, [currentPage]);
|
||||
|
||||
if (!isLoaded) {
|
||||
return <div className="app">Loading...</div>;
|
||||
}
|
||||
|
||||
const currentRoute = ROUTES.find(route => route.key === currentPage);
|
||||
|
||||
return (
|
||||
<Box
|
||||
key={currentPage} // Trigger animation on navigation
|
||||
className={animationClass}
|
||||
sx={{
|
||||
flex: 1,
|
||||
overflowY: 'auto',
|
||||
overflowX: 'hidden',
|
||||
scrollbarGutter: 'stable',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
{currentRoute && <currentRoute.component />}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
DialogActions,
|
||||
Typography,
|
||||
Box,
|
||||
Chip,
|
||||
} from '@mui/material';
|
||||
import type { StorageCleanerOptions } from '@/types/storage';
|
||||
import Button from '@/components/Button';
|
||||
@@ -22,6 +23,10 @@ export function StorageCleanerConfirm({
|
||||
onConfirm,
|
||||
options,
|
||||
}: StorageCleanerConfirmProps) {
|
||||
const selectedOptions = Object.entries(options)
|
||||
.filter(([_, value]) => value)
|
||||
.map(([key, _]) => key);
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
@@ -31,47 +36,67 @@ export function StorageCleanerConfirm({
|
||||
slotProps={{
|
||||
paper: {
|
||||
sx: {
|
||||
borderRadius: 4,
|
||||
borderRadius: 5,
|
||||
backgroundImage: 'none',
|
||||
boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
|
||||
boxShadow: '0 24px 48px -12px rgba(0,0,0,0.15)',
|
||||
p: 1
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<DialogTitle sx={{ textAlign: 'center', pb: 1, pt: 3, fontWeight: 700 }}>
|
||||
确认清理
|
||||
<DialogTitle sx={{ textAlign: 'center', pt: 3, pb: 1, fontWeight: 900, letterSpacing: '-0.5px', fontSize: '1.25rem' }}>
|
||||
确认清理数据?
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent sx={{ textAlign: 'center', pb: 2 }}>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
|
||||
将清理以下存储类型:
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 3, fontWeight: 500 }}>
|
||||
您将清除当前页面的选定存储项。
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
bgcolor: 'grey.50',
|
||||
borderRadius: 3,
|
||||
p: 2,
|
||||
mb: 2,
|
||||
display: 'inline-block',
|
||||
textAlign: 'left',
|
||||
minWidth: '60%',
|
||||
}}
|
||||
>
|
||||
{options.localStorage && <Typography variant="body2">- localStorage</Typography>}
|
||||
{options.sessionStorage && <Typography variant="body2">- sessionStorage</Typography>}
|
||||
{options.indexedDB && <Typography variant="body2">- IndexedDB</Typography>}
|
||||
{options.cookies && <Typography variant="body2">- Cookies</Typography>}
|
||||
{options.cacheStorage && <Typography variant="body2">- Cache Storage</Typography>}
|
||||
{options.serviceWorkers && <Typography variant="body2">- Service Workers</Typography>}
|
||||
|
||||
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, justifyContent: 'center', mb: 3 }}>
|
||||
{selectedOptions.map((opt) => (
|
||||
<Chip
|
||||
key={opt}
|
||||
label={opt}
|
||||
size="small"
|
||||
sx={{
|
||||
bgcolor: 'grey.50',
|
||||
fontWeight: 600,
|
||||
color: 'text.secondary',
|
||||
fontSize: '0.7rem',
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.200'
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
此操作不可撤销。
|
||||
|
||||
<Typography variant="caption" sx={{ color: '#ff9800', fontWeight: 700, bgcolor: '#fff4e5', px: 1.5, py: 0.5, borderRadius: 2 }}>
|
||||
⚠️ 此操作不可撤销
|
||||
</Typography>
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ p: 3, pt: 1, gap: 1 }}>
|
||||
<Button variant="outlined" onClick={onClose} fullWidth>
|
||||
|
||||
<DialogActions sx={{ p: 2.5, gap: 1.5 }}>
|
||||
<Button
|
||||
variant="text"
|
||||
onClick={onClose}
|
||||
fullWidth
|
||||
sx={{ fontWeight: 700, color: 'text.secondary', borderRadius: 3 }}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button variant="contained" color="error" onClick={onConfirm} fullWidth>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={onConfirm}
|
||||
fullWidth
|
||||
sx={{
|
||||
bgcolor: '#ff9800',
|
||||
'&:hover': { bgcolor: '#f57c00' },
|
||||
fontWeight: 800,
|
||||
borderRadius: 3,
|
||||
boxShadow: 'none'
|
||||
}}
|
||||
>
|
||||
确认清理
|
||||
</Button>
|
||||
</DialogActions>
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { Box, Typography, Stack } from '@mui/material';
|
||||
import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome'; // Sparkles for AI
|
||||
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos';
|
||||
import React from 'react';
|
||||
|
||||
interface ToolCardProps {
|
||||
title: string;
|
||||
description?: string;
|
||||
snapshot?: React.ReactNode;
|
||||
colorCode: string;
|
||||
icon: React.ReactNode;
|
||||
onClick: () => void;
|
||||
hasAI?: boolean;
|
||||
}
|
||||
|
||||
export default function ToolCard({ title, description, snapshot, colorCode, icon, onClick, hasAI }: ToolCardProps) {
|
||||
return (
|
||||
<Box
|
||||
onClick={onClick}
|
||||
sx={{
|
||||
position: 'relative',
|
||||
bgcolor: 'background.paper',
|
||||
borderRadius: 4,
|
||||
p: 2.5,
|
||||
cursor: 'pointer',
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.100',
|
||||
transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 1.5,
|
||||
'&:hover': {
|
||||
borderColor: colorCode,
|
||||
transform: 'translateY(-4px)',
|
||||
boxShadow: `0 12px 24px -10px ${colorCode}33`, // 20% opacity of colorCode
|
||||
'& .arrow-icon': {
|
||||
transform: 'translateX(4px)',
|
||||
color: colorCode
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" justifyContent="space-between" alignItems="flex-start">
|
||||
<Stack direction="row" spacing={1.5} alignItems="center">
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 3,
|
||||
bgcolor: `${colorCode}11`, // 7% opacity
|
||||
color: colorCode
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
</Box>
|
||||
<Box>
|
||||
<Typography
|
||||
variant="subtitle1"
|
||||
sx={{
|
||||
fontWeight: 700,
|
||||
lineHeight: 1.2,
|
||||
color: 'text.primary',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 0.5
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
{hasAI && <AutoAwesomeIcon sx={{ fontSize: 14, color: '#f5b041' }} />}
|
||||
</Typography>
|
||||
{description && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
color: 'text.secondary',
|
||||
fontWeight: 500,
|
||||
display: 'block',
|
||||
mt: 0.5
|
||||
}}
|
||||
>
|
||||
{description}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Stack>
|
||||
<ArrowForwardIosIcon
|
||||
className="arrow-icon"
|
||||
sx={{
|
||||
fontSize: 12,
|
||||
color: 'grey.300',
|
||||
mt: 0.5,
|
||||
transition: 'all 0.3s ease'
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
{snapshot && (
|
||||
<Box
|
||||
sx={{
|
||||
mt: 'auto',
|
||||
pt: 1.5,
|
||||
borderTop: '1px dashed',
|
||||
borderColor: 'grey.100'
|
||||
}}
|
||||
>
|
||||
{snapshot}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { Box, IconButton, Typography, Stack, Tooltip } from '@mui/material';
|
||||
import SettingsIcon from '@mui/icons-material/Settings';
|
||||
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
|
||||
import ArrowBackIosNewIcon from '@mui/icons-material/ArrowBackIosNew';
|
||||
import { useRouter } from '@/providers/RouterProvider';
|
||||
|
||||
export default function TopBar({ onOpenOptions }: { onOpenOptions: () => void }) {
|
||||
const { currentPage, goBack } = useRouter();
|
||||
|
||||
const handleDetach = () => {
|
||||
// 弹出脱离窗口 (以独立面板形式打开当前 URL)
|
||||
chrome.windows.create({
|
||||
url: window.location.href,
|
||||
type: 'panel',
|
||||
width: 420,
|
||||
height: 600
|
||||
});
|
||||
};
|
||||
|
||||
const isDashboard = currentPage === 'dashboard';
|
||||
|
||||
return (
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="space-between"
|
||||
alignItems="center"
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1.5,
|
||||
borderBottom: '1px solid',
|
||||
borderColor: 'grey.100',
|
||||
bgcolor: 'background.paper',
|
||||
zIndex: 1100
|
||||
}}
|
||||
>
|
||||
<Box sx={{ width: 40 }}>
|
||||
{!isDashboard && (
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={goBack}
|
||||
sx={{
|
||||
bgcolor: 'grey.50',
|
||||
'&:hover': { bgcolor: 'grey.200' }
|
||||
}}
|
||||
>
|
||||
<ArrowBackIosNewIcon sx={{ fontSize: 14 }} />
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Typography
|
||||
variant="subtitle2"
|
||||
sx={{
|
||||
fontWeight: 800,
|
||||
letterSpacing: '0.5px',
|
||||
textTransform: 'uppercase',
|
||||
fontSize: '0.75rem',
|
||||
color: 'text.secondary'
|
||||
}}
|
||||
>
|
||||
Testing Tools
|
||||
</Typography>
|
||||
|
||||
<Stack direction="row" spacing={1} sx={{ width: 80, justifyContent: 'flex-end' }}>
|
||||
<Tooltip title="独立窗口模式">
|
||||
<IconButton size="small" onClick={handleDetach}>
|
||||
<OpenInNewIcon sx={{ fontSize: 18 }} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title="设置">
|
||||
<IconButton size="small" onClick={onOpenOptions}>
|
||||
<SettingsIcon sx={{ fontSize: 18 }} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { PageType } from '@/types/storage';
|
||||
import DashboardPage from '@/entrypoints/popup/pages/DashboardPage';
|
||||
import TimestampPage from '@/entrypoints/popup/pages/TimestampPage';
|
||||
import StorageCleanerPage from '@/entrypoints/popup/pages/StorageCleanerPage';
|
||||
import OpenUrlPage from '@/entrypoints/popup/pages/OpenUrlPage';
|
||||
import OpenUrlViewerPage from '@/entrypoints/popup/pages/OpenUrlViewerPage';
|
||||
|
||||
export interface RouteConfig {
|
||||
key: PageType;
|
||||
label: string;
|
||||
defaultVisible: boolean;
|
||||
component: React.ComponentType;
|
||||
}
|
||||
|
||||
export const ROUTES: RouteConfig[] = [
|
||||
{
|
||||
key: 'dashboard',
|
||||
label: 'Dashboard',
|
||||
defaultVisible: true,
|
||||
component: DashboardPage,
|
||||
},
|
||||
{
|
||||
key: 'timestamp',
|
||||
label: '时间戳',
|
||||
defaultVisible: true,
|
||||
component: TimestampPage,
|
||||
},
|
||||
{
|
||||
key: 'storageCleaner',
|
||||
label: '存储清理',
|
||||
defaultVisible: true,
|
||||
component: StorageCleanerPage,
|
||||
},
|
||||
{
|
||||
key: 'openUrl',
|
||||
label: 'Open Url',
|
||||
defaultVisible: true,
|
||||
component: OpenUrlPage,
|
||||
},
|
||||
{
|
||||
key: 'openUrlViewer',
|
||||
label: '查看',
|
||||
defaultVisible: false,
|
||||
component: OpenUrlViewerPage,
|
||||
},
|
||||
];
|
||||
|
||||
export function getRouteByKey(key: PageType): RouteConfig | undefined {
|
||||
return ROUTES.find(route => route.key === key);
|
||||
}
|
||||
|
||||
export function getDefaultVisibleRoutes(): PageType[] {
|
||||
return ROUTES.filter(route => route.defaultVisible).map(route => route.key);
|
||||
}
|
||||
|
||||
export function getAllRouteKeys(): PageType[] {
|
||||
return ROUTES.map(route => route.key);
|
||||
}
|
||||
@@ -2,6 +2,17 @@ import '../.wxt/types/imports.d.ts';
|
||||
import { browser } from 'wxt/browser';
|
||||
|
||||
export default defineBackground(() => {
|
||||
// 监听扩展图标点击事件,打开侧边栏
|
||||
browser.action.onClicked.addListener(async (tab) => {
|
||||
if (tab.id) {
|
||||
try {
|
||||
await browser.sidePanel.open({ tabId: tab.id });
|
||||
} catch (err) {
|
||||
console.error('Failed to open side panel:', err);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 监听扩展安装或更新事件
|
||||
browser.runtime.onInstalled.addListener(async ({ reason }) => {
|
||||
if (reason === 'install') {
|
||||
|
||||
@@ -3,21 +3,17 @@ import {
|
||||
Box,
|
||||
Typography,
|
||||
Paper,
|
||||
FormControlLabel,
|
||||
Switch,
|
||||
Button,
|
||||
Snackbar,
|
||||
Alert,
|
||||
CircularProgress,
|
||||
Stack,
|
||||
} from '@mui/material';
|
||||
import RefreshIcon from '@mui/icons-material/Refresh';
|
||||
import type { PageType } from '@/types/storage';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
|
||||
const PAGE_CONFIG = {
|
||||
timestamp: { label: '时间戳', defaultVisible: true },
|
||||
storageCleaner: { label: '存储清理', defaultVisible: true },
|
||||
} as const satisfies Record<PageType, { label: string; defaultVisible: boolean }>;
|
||||
import { ROUTES } from '@/config/routes';
|
||||
|
||||
function App() {
|
||||
const [visiblePages, setVisiblePages] = useState<PageType[]>([]);
|
||||
@@ -34,12 +30,12 @@ function App() {
|
||||
const saved = await storageUtil.get('app/visiblePages', [
|
||||
'timestamp',
|
||||
'storageCleaner',
|
||||
'openUrl',
|
||||
] as PageType[]);
|
||||
// Ensure we always have an array
|
||||
setVisiblePages(saved ?? ['timestamp', 'storageCleaner']);
|
||||
setVisiblePages(saved ?? ['timestamp', 'storageCleaner', 'openUrl']);
|
||||
} catch (error) {
|
||||
console.error('Failed to load config:', error);
|
||||
setVisiblePages(['timestamp', 'storageCleaner']);
|
||||
setVisiblePages(['timestamp', 'storageCleaner', 'openUrl']);
|
||||
} finally {
|
||||
setIsLoaded(true);
|
||||
}
|
||||
@@ -50,7 +46,6 @@ function App() {
|
||||
let newPages: PageType[];
|
||||
|
||||
if (isCurrentlyVisible) {
|
||||
// 尝试隐藏,但至少保留一个
|
||||
if (visiblePages.length <= 1) {
|
||||
showToast('至少需要保留一个可见页面', 'warning');
|
||||
return;
|
||||
@@ -63,27 +58,23 @@ function App() {
|
||||
try {
|
||||
await storageUtil.set('app/visiblePages', newPages);
|
||||
setVisiblePages(newPages);
|
||||
showToast(
|
||||
`已${isCurrentlyVisible ? '隐藏' : '显示'} ${PAGE_CONFIG[page].label}`,
|
||||
'success',
|
||||
);
|
||||
const route = ROUTES.find((r) => r.key === page);
|
||||
showToast(`已${isCurrentlyVisible ? '隐藏' : '显示'} ${route?.label || page}`, 'success');
|
||||
} catch (error) {
|
||||
console.error('Failed to save config:', error);
|
||||
showToast('保存失败,请重试', 'warning');
|
||||
showToast('保存失败', 'warning');
|
||||
}
|
||||
};
|
||||
|
||||
const handleRestoreDefaults = async () => {
|
||||
try {
|
||||
const defaults = (Object.keys(PAGE_CONFIG) as PageType[]).filter(
|
||||
(key) => PAGE_CONFIG[key].defaultVisible,
|
||||
);
|
||||
const defaults = ROUTES.filter((route) => route.defaultVisible).map((route) => route.key);
|
||||
await storageUtil.set('app/visiblePages', defaults);
|
||||
setVisiblePages(defaults);
|
||||
showToast('已恢复默认设置', 'success');
|
||||
showToast('已恢复默认', 'success');
|
||||
} catch (error) {
|
||||
console.error('Failed to restore defaults:', error);
|
||||
showToast('恢复失败,请重试', 'warning');
|
||||
showToast('恢复失败', 'warning');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -92,82 +83,82 @@ function App() {
|
||||
setToastSeverity(severity);
|
||||
};
|
||||
|
||||
const handleCloseToast = () => {
|
||||
setToast(null);
|
||||
};
|
||||
const handleCloseToast = () => setToast(null);
|
||||
|
||||
if (!isLoaded) {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
minHeight: '100vh',
|
||||
}}
|
||||
sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh' }}
|
||||
>
|
||||
<CircularProgress />
|
||||
<CircularProgress size={24} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ p: 3, maxWidth: 600, mx: 'auto' }}>
|
||||
<Typography variant="h5" gutterBottom fontWeight="bold">
|
||||
⚙️ 扩展设置
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
paragraph
|
||||
sx={{ mb: 3 }}
|
||||
>
|
||||
自定义 popup 弹窗中显示的功能页面。更改将立即生效,无需保存。
|
||||
</Typography>
|
||||
|
||||
<Paper elevation={0} sx={{ p: 3, border: '1px solid', borderColor: 'divider', mb: 2 }}>
|
||||
<Typography variant="subtitle1" gutterBottom fontWeight="medium" sx={{ mb: 2 }}>
|
||||
可见页面设置
|
||||
</Typography>
|
||||
|
||||
{(Object.keys(PAGE_CONFIG) as PageType[]).map((pageKey) => {
|
||||
const config = PAGE_CONFIG[pageKey];
|
||||
const isChecked = visiblePages.includes(pageKey);
|
||||
const isDisabled = !isChecked && visiblePages.length === 1;
|
||||
|
||||
return (
|
||||
<FormControlLabel
|
||||
key={pageKey}
|
||||
control={
|
||||
<Switch
|
||||
checked={isChecked}
|
||||
onChange={() => handlePageToggle(pageKey)}
|
||||
disabled={isDisabled}
|
||||
color="primary"
|
||||
/>
|
||||
}
|
||||
label={config.label}
|
||||
sx={{
|
||||
width: '100%',
|
||||
mb: 1,
|
||||
'&:last-child': { mb: 0 },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Paper>
|
||||
|
||||
<Box display="flex" justifyContent="flex-start" sx={{ mb: 3 }}>
|
||||
<Box sx={{ p: 4, maxWidth: 600, mx: 'auto', minHeight: '100vh', bgcolor: 'grey.50' }}>
|
||||
<Stack direction="row" justifyContent="space-between" alignItems="flex-start" sx={{ mb: 4 }}>
|
||||
<Button
|
||||
variant="outlined"
|
||||
onClick={handleRestoreDefaults}
|
||||
startIcon={<RefreshIcon />}
|
||||
variant="text"
|
||||
size="small"
|
||||
onClick={handleRestoreDefaults}
|
||||
startIcon={<RefreshIcon sx={{ fontSize: 16 }} />}
|
||||
sx={{ color: 'text.secondary', fontWeight: 600 }}
|
||||
>
|
||||
恢复默认
|
||||
</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
|
||||
<Paper
|
||||
elevation={0}
|
||||
sx={{
|
||||
borderRadius: 4,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.200',
|
||||
overflow: 'hidden',
|
||||
bgcolor: 'background.paper',
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
|
||||
{ROUTES.filter((route) => route.key !== 'dashboard' && route.key !== 'openUrlViewer').map(
|
||||
(route, index, array) => {
|
||||
const isChecked = visiblePages.includes(route.key);
|
||||
const isDisabled = isChecked && visiblePages.length === 1;
|
||||
|
||||
return (
|
||||
<Box
|
||||
key={route.key}
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
p: 2.5,
|
||||
borderBottom: index === array.length - 1 ? 'none' : '1px solid',
|
||||
borderColor: 'grey.100',
|
||||
transition: 'all 0.2s',
|
||||
'&:hover': { bgcolor: 'grey.50' },
|
||||
}}
|
||||
>
|
||||
<Box>
|
||||
<Typography variant="body1" sx={{ fontWeight: 700, color: 'text.primary' }}>
|
||||
{route.label}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{isChecked ? '已在 Dashboard 启用' : '已在 Dashboard 隐藏'}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Switch
|
||||
size="small"
|
||||
checked={isChecked}
|
||||
onChange={() => handlePageToggle(route.key)}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
},
|
||||
)}
|
||||
</Box>
|
||||
</Paper>
|
||||
|
||||
<Snackbar
|
||||
open={!!toast}
|
||||
@@ -179,17 +170,11 @@ function App() {
|
||||
onClose={handleCloseToast}
|
||||
severity={toastSeverity}
|
||||
variant="filled"
|
||||
sx={{ width: '100%' }}
|
||||
sx={{ borderRadius: 2, fontWeight: 600 }}
|
||||
>
|
||||
{toast}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
|
||||
<Box mt={4} pt={2} borderTop={1} borderColor="divider">
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
提示:更改将立即应用到 popup 弹窗。如需查看效果,请关闭并重新打开扩展弹窗。
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -61,54 +61,31 @@ body,
|
||||
overflow: hidden; /* 内部由 flex 子项控制滚动 */
|
||||
}
|
||||
|
||||
/* Animations */
|
||||
@keyframes slideInRight {
|
||||
from {
|
||||
transform: translateX(30px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-5px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* 导航容器 */
|
||||
.nav-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding-top: 16px;
|
||||
padding-bottom: 16px;
|
||||
gap: 8px;
|
||||
flex-shrink: 0; /* 禁止导航栏被挤压缩放 */
|
||||
background-color: #fff;
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
|
||||
.page-transition-enter {
|
||||
animation: slideInRight 0.3s cubic-bezier(0.25, 0.8, 0.25, 1) forwards;
|
||||
}
|
||||
|
||||
/* 导航按钮 */
|
||||
.nav-button {
|
||||
padding: 8px 16px;
|
||||
border: 1px solid var(--btn-bg);
|
||||
border-radius: var(--radius);
|
||||
background: transparent;
|
||||
color: var(--btn-text);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.nav-button:hover {
|
||||
background: var(--btn-bg);
|
||||
}
|
||||
|
||||
.nav-button.active {
|
||||
background: var(--btn-bg);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.nav-button.settings-button {
|
||||
padding: 8px 12px;
|
||||
min-width: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
.page-transition-dashboard {
|
||||
animation: fadeIn 0.3s ease-out forwards;
|
||||
}
|
||||
|
||||
@@ -1,113 +1,20 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box } from '@mui/material';
|
||||
import SettingsIcon from '@mui/icons-material/Settings';
|
||||
import type { PageType } from '@/types/storage';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
import TimestampPage from './pages/TimestampPage';
|
||||
import StorageCleanerPage from './pages/StorageCleanerPage';
|
||||
import './App.css';
|
||||
|
||||
|
||||
const PAGE_CONFIG = {
|
||||
timestamp: { label: '时间戳', defaultVisible: true },
|
||||
storageCleaner: { label: '存储清理', defaultVisible: true },
|
||||
} as const satisfies Record<PageType, { label: string; defaultVisible: boolean }>;
|
||||
import RouterProvider from '@/providers/RouterProvider';
|
||||
import TopBar from '@/components/TopBar';
|
||||
import RouterContainer from '@/components/RouterContainer';
|
||||
|
||||
function App() {
|
||||
const [currentPage, setCurrentPage] = useState<PageType>('timestamp');
|
||||
const [visiblePages, setVisiblePages] = useState<PageType[]>(['timestamp', 'storageCleaner']);
|
||||
const [isLoaded, setIsLoaded] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadInitialData();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (isLoaded) {
|
||||
storageUtil.set('app/currentRoute', currentPage);
|
||||
}
|
||||
}, [currentPage, isLoaded]);
|
||||
|
||||
const loadInitialData = async () => {
|
||||
try {
|
||||
const [savedRoute, savedVisiblePages] = await Promise.all([
|
||||
storageUtil.get('app/currentRoute', 'timestamp'),
|
||||
storageUtil.get('app/visiblePages', ['timestamp', 'storageCleaner'] as PageType[]),
|
||||
]);
|
||||
|
||||
if (savedRoute) {
|
||||
setCurrentPage(savedRoute);
|
||||
}
|
||||
|
||||
if (savedVisiblePages) {
|
||||
setVisiblePages(savedVisiblePages);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load initial data:', error);
|
||||
} finally {
|
||||
setIsLoaded(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePageChange = (page: PageType) => {
|
||||
setCurrentPage(page);
|
||||
};
|
||||
|
||||
const handleOpenOptions = () => {
|
||||
chrome.runtime.openOptionsPage();
|
||||
};
|
||||
|
||||
const NavButton = ({ pageKey }: { pageKey: PageType }) => {
|
||||
const config = PAGE_CONFIG[pageKey];
|
||||
if (!config) return null;
|
||||
|
||||
return (
|
||||
<Box key={pageKey}>
|
||||
<button
|
||||
className={currentPage === pageKey ? 'nav-button active' : 'nav-button'}
|
||||
onClick={() => handlePageChange(pageKey)}
|
||||
>
|
||||
{config.label}
|
||||
</button>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
if (!isLoaded) {
|
||||
return <div className="app">Loading...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<Box className="nav-container">
|
||||
{(Object.keys(PAGE_CONFIG) as PageType[])
|
||||
.filter((key) => visiblePages.includes(key))
|
||||
.map((key) => <NavButton key={key} pageKey={key} />)}
|
||||
<Box key="settings" sx={{ display: 'inline-block' }}>
|
||||
<button
|
||||
className="nav-button settings-button"
|
||||
onClick={handleOpenOptions}
|
||||
title="打开设置"
|
||||
>
|
||||
<SettingsIcon sx={{ fontSize: 18, verticalAlign: 'middle' }} />
|
||||
</button>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* 统一滚动容器 */}
|
||||
<Box
|
||||
sx={{
|
||||
flex: 1,
|
||||
overflowY: 'auto',
|
||||
scrollbarGutter: 'stable',
|
||||
display: 'flex',
|
||||
flexDirection: 'column'
|
||||
}}
|
||||
>
|
||||
{currentPage === 'timestamp' && <TimestampPage />}
|
||||
{currentPage === 'storageCleaner' && <StorageCleanerPage />}
|
||||
</Box>
|
||||
</div>
|
||||
<RouterProvider defaultRoute="dashboard" syncRoute={false}>
|
||||
<div className="app" style={{ display: 'flex', flexDirection: 'column', height: '100vh', overflow: 'hidden' }}>
|
||||
<TopBar onOpenOptions={handleOpenOptions} />
|
||||
<RouterContainer />
|
||||
</div>
|
||||
</RouterProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { Box, Typography, Container } from '@mui/material';
|
||||
import { useRouter } from '@/providers/RouterProvider';
|
||||
import ToolCard from '@/components/ToolCard';
|
||||
import AccessTimeIcon from '@mui/icons-material/AccessTime';
|
||||
import StorageIcon from '@mui/icons-material/Storage';
|
||||
import LanguageIcon from '@mui/icons-material/Language';
|
||||
import type { PageType } from '@/types/storage';
|
||||
import { useEffect, useState } from 'react';
|
||||
import dayjs from '@/utils/dayjs';
|
||||
|
||||
export default function DashboardPage() {
|
||||
const { navigateTo, visiblePages } = useRouter();
|
||||
const [now, setNow] = useState(dayjs());
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => setNow(dayjs()), 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
const isVisible = (key: string) => visiblePages.includes(key as PageType);
|
||||
|
||||
return (
|
||||
<Box sx={{ bgcolor: 'grey.50', minHeight: '100%', pb: 4 }}>
|
||||
<Container maxWidth="sm" sx={{ py: 3, px: 2 }}>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
{isVisible('timestamp') && (
|
||||
<ToolCard
|
||||
title="时间戳"
|
||||
description="Unix 毫秒数转换与格式化"
|
||||
colorCode="#2196f3"
|
||||
icon={<AccessTimeIcon sx={{ fontSize: 20 }} />}
|
||||
onClick={() => navigateTo('timestamp')}
|
||||
snapshot={
|
||||
<Box
|
||||
sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
fontFamily: 'monospace',
|
||||
fontWeight: 600,
|
||||
color: '#2196f3',
|
||||
fontSize: '0.85rem',
|
||||
}}
|
||||
>
|
||||
{now.valueOf()}
|
||||
</Typography>
|
||||
<Typography sx={{ fontSize: '0.7rem', color: 'text.secondary' }}>
|
||||
{now.format('HH:mm:ss')}
|
||||
</Typography>
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isVisible('storageCleaner') && (
|
||||
<ToolCard
|
||||
title="存储管理"
|
||||
description="清理缓存、Cookies 及本地存储"
|
||||
colorCode="#ff9800"
|
||||
icon={<StorageIcon sx={{ fontSize: 20 }} />}
|
||||
onClick={() => navigateTo('storageCleaner')}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isVisible('openUrl') && (
|
||||
<ToolCard
|
||||
title="URL 实验室"
|
||||
description="多环境跳转与安全性预检"
|
||||
colorCode="#9c27b0"
|
||||
icon={<LanguageIcon sx={{ fontSize: 20 }} />}
|
||||
onClick={() => navigateTo('openUrl')}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
</Container>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
import { useState, useEffect, useCallback, Fragment } from 'react';
|
||||
import {
|
||||
Box,
|
||||
TextField,
|
||||
Alert,
|
||||
List,
|
||||
ListItem,
|
||||
IconButton,
|
||||
Typography,
|
||||
Divider,
|
||||
Container,
|
||||
Stack,
|
||||
alpha,
|
||||
Theme,
|
||||
Tooltip,
|
||||
} from '@mui/material';
|
||||
import DeleteIcon from '@mui/icons-material/Delete';
|
||||
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
|
||||
import VisibilityIcon from '@mui/icons-material/Visibility';
|
||||
import AddIcon from '@mui/icons-material/Add';
|
||||
import LanguageIcon from '@mui/icons-material/Language';
|
||||
import LinkIcon from '@mui/icons-material/Link';
|
||||
import Button from '@/components/Button';
|
||||
import GlobalSnackbar, { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
import { useRouter } from '@/providers/RouterProvider';
|
||||
import type { OpenUrlPreferences, OpenUrlEntry } from '@/types/storage';
|
||||
|
||||
const THEME_COLOR = '#9c27b0';
|
||||
|
||||
const INPUT_STYLE = {
|
||||
'& .MuiOutlinedInput-root': {
|
||||
bgcolor: 'background.paper',
|
||||
borderRadius: 3.5,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.100',
|
||||
transition: 'all 0.25s cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
'& fieldset': { border: 'none' },
|
||||
'&:hover': { borderColor: 'grey.300', bgcolor: 'grey.50' },
|
||||
'&.Mui-focused': {
|
||||
bgcolor: '#fff',
|
||||
borderColor: THEME_COLOR,
|
||||
boxShadow: (_theme: Theme) => `0 0 0 4px ${alpha(THEME_COLOR, 0.1)}`,
|
||||
},
|
||||
},
|
||||
'& .MuiInputBase-input': {
|
||||
py: 1.2,
|
||||
px: 2,
|
||||
fontSize: '0.85rem',
|
||||
fontWeight: 600,
|
||||
},
|
||||
'& .MuiInputLabel-root': {
|
||||
fontSize: '0.85rem',
|
||||
fontWeight: 700,
|
||||
color: 'text.secondary',
|
||||
mb: 0.5,
|
||||
'&.Mui-focused': { color: THEME_COLOR },
|
||||
},
|
||||
};
|
||||
|
||||
const DEFAULT_PREFERENCES: OpenUrlPreferences = {
|
||||
entries: [],
|
||||
};
|
||||
|
||||
export default function OpenUrlPage() {
|
||||
const [entries, setEntries] = useState<OpenUrlEntry[]>(DEFAULT_PREFERENCES.entries);
|
||||
const [newName, setNewName] = useState<string>('');
|
||||
const [newUrl, setNewUrl] = useState<string>('');
|
||||
const [isLoaded, setIsLoaded] = useState(false);
|
||||
const { snackbarProps, showMessage } = useSnackbar();
|
||||
const { syncNavigation } = useRouter();
|
||||
|
||||
const showMixedContentWarning =
|
||||
newUrl.startsWith('http://') && !newUrl.includes('localhost') && !newUrl.includes('127.0.0.1');
|
||||
|
||||
const isValidUrl = (url: string) => {
|
||||
if (!url.trim()) return false;
|
||||
try {
|
||||
new URL(url);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const loadPreferences = async () => {
|
||||
try {
|
||||
const saved = await storageUtil.get('openUrl/preferences', DEFAULT_PREFERENCES);
|
||||
if (saved && saved.entries) {
|
||||
setEntries(saved.entries);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load Open Url preferences:', error);
|
||||
} finally {
|
||||
setIsLoaded(true);
|
||||
}
|
||||
};
|
||||
loadPreferences();
|
||||
}, []);
|
||||
|
||||
const savePreferences = useCallback(() => {
|
||||
const preferences: OpenUrlPreferences = { entries };
|
||||
storageUtil.set('openUrl/preferences', preferences).catch((error) => {
|
||||
console.error('Failed to save Open Url preferences:', error);
|
||||
});
|
||||
}, [entries]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoaded) return;
|
||||
const timer = setTimeout(() => {
|
||||
savePreferences();
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, [entries, isLoaded, savePreferences]);
|
||||
|
||||
const handleAddEntry = () => {
|
||||
if (!newName.trim()) {
|
||||
showMessage('请输入名称', { severity: 'error' });
|
||||
return;
|
||||
}
|
||||
if (!isValidUrl(newUrl)) {
|
||||
showMessage('请输入有效的 URL', { severity: 'error' });
|
||||
return;
|
||||
}
|
||||
|
||||
setEntries([...entries, { name: newName.trim(), url: newUrl.trim() }]);
|
||||
setNewName('');
|
||||
setNewUrl('');
|
||||
showMessage('添加成功', { severity: 'success' });
|
||||
};
|
||||
|
||||
const handleDeleteEntry = (index: number) => {
|
||||
const newEntries = [...entries];
|
||||
newEntries.splice(index, 1);
|
||||
setEntries(newEntries);
|
||||
showMessage('删除成功', { severity: 'success' });
|
||||
};
|
||||
|
||||
const handleOpenInSidebar = async (entry: OpenUrlEntry) => {
|
||||
try {
|
||||
await storageUtil.set('openUrl/currentUrl', entry.url);
|
||||
syncNavigation('openUrlViewer');
|
||||
|
||||
const [currentTab] = await chrome.tabs.query({
|
||||
active: true,
|
||||
currentWindow: true,
|
||||
});
|
||||
const tabId = currentTab.id;
|
||||
if (!tabId) {
|
||||
showMessage('无法获取当前标签页', { severity: 'error' });
|
||||
return;
|
||||
}
|
||||
|
||||
await chrome.sidePanel.setOptions({
|
||||
tabId,
|
||||
path: 'sidepanel.html',
|
||||
enabled: true,
|
||||
});
|
||||
await chrome.sidePanel.open({ windowId: currentTab.windowId });
|
||||
|
||||
// 仅当在 Popup 中时才关闭窗口,防止在侧边栏内点击预览时导致侧边栏关闭
|
||||
if (window.location.pathname.includes('popup.html')) {
|
||||
window.close();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to open side panel:', error);
|
||||
showMessage(`打开失败: ${(error as Error).message}`, { severity: 'error' });
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenInNewTab = (entry: OpenUrlEntry) => {
|
||||
chrome.tabs.create({ url: entry.url });
|
||||
window.close();
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ pb: 3 }}>
|
||||
<Container sx={{ py: 2 }}>
|
||||
{/* Header */}
|
||||
<Stack direction="row" spacing={1.5} alignItems="center" sx={{ mb: 2.5 }}>
|
||||
<Box
|
||||
sx={{
|
||||
p: 1,
|
||||
borderRadius: 2.5,
|
||||
bgcolor: alpha(THEME_COLOR, 0.1),
|
||||
color: THEME_COLOR,
|
||||
display: 'flex',
|
||||
}}
|
||||
>
|
||||
<LanguageIcon sx={{ fontSize: 20 }} />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography
|
||||
variant="subtitle1"
|
||||
fontWeight={900}
|
||||
sx={{ letterSpacing: '-0.5px', lineHeight: 1.2 }}
|
||||
>
|
||||
URL 实验室
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ fontWeight: 600 }}>
|
||||
多环境跳转与安全性预检
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
|
||||
{/* Form Section */}
|
||||
<Box
|
||||
sx={{
|
||||
bgcolor: 'background.paper',
|
||||
p: 2,
|
||||
borderRadius: 4,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.100',
|
||||
mb: 3,
|
||||
boxShadow: '0 4px 12px rgba(0,0,0,0.02)',
|
||||
}}
|
||||
>
|
||||
<Stack spacing={2}>
|
||||
<TextField
|
||||
label="环境名称"
|
||||
placeholder="例如: 本地文档"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
sx={INPUT_STYLE}
|
||||
InputLabelProps={{ shrink: true }}
|
||||
/>
|
||||
<TextField
|
||||
label="目标 URL"
|
||||
placeholder="例如: http://localhost:8000/docs"
|
||||
value={newUrl}
|
||||
onChange={(e) => setNewUrl(e.target.value)}
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
sx={INPUT_STYLE}
|
||||
InputLabelProps={{ shrink: true }}
|
||||
/>
|
||||
|
||||
{showMixedContentWarning && (
|
||||
<Alert
|
||||
severity="warning"
|
||||
sx={{
|
||||
borderRadius: 3,
|
||||
'& .MuiAlert-message': { fontSize: '0.7rem', fontWeight: 600, lineHeight: 1.4 },
|
||||
}}
|
||||
>
|
||||
混合内容警告:当前 HTTPS 页面无法加载 HTTP 资源。
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={handleAddEntry}
|
||||
disabled={!newName.trim() || !isValidUrl(newUrl)}
|
||||
fullWidth
|
||||
startIcon={<AddIcon />}
|
||||
sx={{
|
||||
py: 1.2,
|
||||
borderRadius: 4,
|
||||
bgcolor: THEME_COLOR,
|
||||
fontWeight: 800,
|
||||
boxShadow: 'none',
|
||||
'&:hover': {
|
||||
bgcolor: alpha(THEME_COLOR, 0.85),
|
||||
boxShadow: `0 8px 24px ${alpha(THEME_COLOR, 0.2)}`,
|
||||
},
|
||||
}}
|
||||
>
|
||||
添加快捷方式
|
||||
</Button>
|
||||
</Stack>
|
||||
</Box>
|
||||
|
||||
{/* List Section */}
|
||||
<Box>
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{ color: 'text.secondary', fontWeight: 800, px: 1, mb: 1, display: 'block' }}
|
||||
>
|
||||
已保存的快捷方式 ({entries.length})
|
||||
</Typography>
|
||||
|
||||
{entries.length === 0 ? (
|
||||
<Box
|
||||
sx={{
|
||||
textAlign: 'center',
|
||||
py: 4,
|
||||
bgcolor: 'grey.50',
|
||||
borderRadius: 4,
|
||||
border: '1px dashed',
|
||||
borderColor: 'grey.200',
|
||||
}}
|
||||
>
|
||||
<LinkIcon sx={{ color: 'grey.300', fontSize: 40, mb: 1 }} />
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="text.disabled"
|
||||
sx={{ display: 'block', fontWeight: 600 }}
|
||||
>
|
||||
暂无快捷方式,请在上方添加
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<List
|
||||
disablePadding
|
||||
sx={{
|
||||
bgcolor: 'background.paper',
|
||||
borderRadius: 4,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.100',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{entries.map((entry, index) => (
|
||||
<Fragment key={index}>
|
||||
<ListItem
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1.5,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 2,
|
||||
transition: 'background-color 0.2s',
|
||||
'&:hover': { bgcolor: 'grey.50' },
|
||||
}}
|
||||
>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ fontWeight: 800, color: 'text.primary' }}
|
||||
noWrap
|
||||
>
|
||||
{entry.name}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="text.secondary"
|
||||
noWrap
|
||||
sx={{
|
||||
fontSize: '0.65rem',
|
||||
fontWeight: 500,
|
||||
display: 'block',
|
||||
mt: 0.2,
|
||||
fontFamily: 'monospace',
|
||||
}}
|
||||
>
|
||||
{entry.url}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Stack direction="row" spacing={0.5}>
|
||||
<Tooltip title="在侧边栏预览">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() => handleOpenInSidebar(entry)}
|
||||
sx={{
|
||||
color: THEME_COLOR,
|
||||
bgcolor: alpha(THEME_COLOR, 0.05),
|
||||
'&:hover': { bgcolor: THEME_COLOR, color: '#fff' },
|
||||
}}
|
||||
>
|
||||
<VisibilityIcon sx={{ fontSize: 16 }} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title="新标签页打开">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() => handleOpenInNewTab(entry)}
|
||||
sx={{
|
||||
color: 'grey.500',
|
||||
bgcolor: 'grey.100',
|
||||
'&:hover': { bgcolor: 'grey.600', color: '#fff' },
|
||||
}}
|
||||
>
|
||||
<OpenInNewIcon sx={{ fontSize: 16 }} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title="删除">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() => handleDeleteEntry(index)}
|
||||
sx={{
|
||||
color: 'error.main',
|
||||
'&:hover': { color: 'error.dark', bgcolor: alpha('#f44336', 0.05) },
|
||||
}}
|
||||
>
|
||||
<DeleteIcon sx={{ fontSize: 16 }} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Stack>
|
||||
</ListItem>
|
||||
{index < entries.length - 1 && <Divider sx={{ mx: 2, borderColor: 'grey.50' }} />}
|
||||
</Fragment>
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
</Box>
|
||||
</Container>
|
||||
<GlobalSnackbar {...snackbarProps} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Typography } from '@mui/material';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
|
||||
// 只允许 HTTP/HTTPS 协议,阻止危险协议
|
||||
const ALLOWED_PROTOCOLS = ['http:', 'https:'];
|
||||
|
||||
export default function OpenUrlViewerPage() {
|
||||
const [currentUrl, setCurrentUrl] = useState<string>('');
|
||||
const [isLoaded, setIsLoaded] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// 验证 URL 是否安全
|
||||
const validateUrl = (url: string): string | null => {
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
if (!ALLOWED_PROTOCOLS.includes(urlObj.protocol)) {
|
||||
return `不支持的 URL 协议: ${urlObj.protocol}。仅允许 HTTP 和 HTTPS。`;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return '无效的 URL 格式';
|
||||
}
|
||||
};
|
||||
|
||||
// 从存储加载当前选中的 URL
|
||||
useEffect(() => {
|
||||
const loadCurrentUrl = async () => {
|
||||
try {
|
||||
const saved = await storageUtil.get('openUrl/currentUrl', '');
|
||||
if (saved) {
|
||||
const validationError = validateUrl(saved);
|
||||
if (validationError) {
|
||||
setError(validationError);
|
||||
} else {
|
||||
setCurrentUrl(saved);
|
||||
setError(null);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load current URL:', error);
|
||||
setError('加载 URL 失败');
|
||||
} finally {
|
||||
setIsLoaded(true);
|
||||
}
|
||||
};
|
||||
loadCurrentUrl();
|
||||
}, []);
|
||||
|
||||
if (!isLoaded) {
|
||||
return (
|
||||
<Box sx={{ p: 2, flex: 1 }}>
|
||||
<Typography color="text.secondary">Loading...</Typography>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Box sx={{ p: 2, flex: 1 }}>
|
||||
<Typography color="error">{error}</Typography>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (!currentUrl) {
|
||||
return (
|
||||
<Box sx={{ p: 2, flex: 1 }}>
|
||||
<Typography color="text.secondary">
|
||||
没有选中的 URL,请先在 OpenUrl 页面选择一个 URL 打开。
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
|
||||
<iframe
|
||||
src={currentUrl}
|
||||
title="OpenUrl Viewer"
|
||||
sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-navigation"
|
||||
style={{
|
||||
flex: 1,
|
||||
width: '100%',
|
||||
border: 'none',
|
||||
display: 'block',
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -1,33 +1,35 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import {
|
||||
Paper,
|
||||
Typography,
|
||||
Box,
|
||||
Checkbox,
|
||||
FormControlLabel,
|
||||
Alert,
|
||||
Snackbar,
|
||||
Accordion,
|
||||
AccordionSummary,
|
||||
AccordionDetails,
|
||||
Divider,
|
||||
Container,
|
||||
Stack,
|
||||
Switch,
|
||||
Grid,
|
||||
} from '@mui/material';
|
||||
import RefreshIcon from '@mui/icons-material/Refresh';
|
||||
import WarningIcon from '@mui/icons-material/Warning';
|
||||
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
|
||||
import StorageIcon from '@mui/icons-material/Storage';
|
||||
import Button from '@/components/Button';
|
||||
import GlobalSnackbar, { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import StorageCleanerConfirm from '@/components/StorageCleanerConfirm';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
import type {
|
||||
StorageCleanerOptions,
|
||||
CleaningResult,
|
||||
StorageCleanerPreferences,
|
||||
} from 'types/storage';
|
||||
} from '@/types/storage';
|
||||
import {
|
||||
getCurrentTab,
|
||||
isRestrictedUrl,
|
||||
clearStorage,
|
||||
formatCleaningResult,
|
||||
getCookieSize,
|
||||
getLocalStorageSize,
|
||||
getSessionStorageSize,
|
||||
formatSize,
|
||||
} from '@/utils/storageCleaner';
|
||||
|
||||
const DEFAULT_OPTIONS: StorageCleanerOptions = {
|
||||
@@ -48,327 +50,403 @@ export default function StorageCleanerPage() {
|
||||
const [domain, setDomain] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
const [options, setOptions] = useState<StorageCleanerOptions>(DEFAULT_OPTIONS);
|
||||
const [sizes, setSizes] = useState<Record<string, number>>({});
|
||||
const [autoRefresh, setAutoRefresh] = useState<boolean>(true);
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
const [result, setResult] = useState<CleaningResult | null>(null);
|
||||
const [showConfirm, setShowConfirm] = useState<boolean>(false);
|
||||
const [snackbar, setSnackbar] = useState<{ open: boolean; message: string }>({
|
||||
open: false,
|
||||
message: '',
|
||||
});
|
||||
const { snackbarProps, showMessage } = useSnackbar();
|
||||
const reloadTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// Load tab info and user preferences
|
||||
useEffect(() => {
|
||||
const loadInfo = async () => {
|
||||
const tab = await getCurrentTab();
|
||||
|
||||
if (!tab || !tab.url) {
|
||||
setError('无法获取当前标签页');
|
||||
return;
|
||||
}
|
||||
|
||||
if (isRestrictedUrl(tab.url)) {
|
||||
setError('存储清理功能不支持此页面');
|
||||
return;
|
||||
}
|
||||
|
||||
setDomain(new URL(tab.url).hostname);
|
||||
|
||||
// Load user preferences
|
||||
const prefs = await storageUtil.get('storageCleaner/preferences', DEFAULT_PREFERENCES);
|
||||
setAutoRefresh(prefs?.autoRefresh ?? DEFAULT_PREFERENCES.autoRefresh);
|
||||
setOptions(prefs?.selectedTypes ?? DEFAULT_PREFERENCES.selectedTypes);
|
||||
return () => {
|
||||
if (reloadTimeoutRef.current) clearTimeout(reloadTimeoutRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const loadInfo = async () => {
|
||||
const tab = await getCurrentTab();
|
||||
if (!tab || !tab.url) {
|
||||
setError('无法获取当前标签页');
|
||||
return;
|
||||
}
|
||||
if (isRestrictedUrl(tab.url)) {
|
||||
setError('存储清理功能不支持此页面');
|
||||
return;
|
||||
}
|
||||
const url = tab.url;
|
||||
const tabId = tab.id!;
|
||||
setDomain(new URL(url).hostname);
|
||||
|
||||
const [savedPrefs, cSize, lsSize, ssSize] = await Promise.all([
|
||||
storageUtil.get('storageCleaner/preferences', DEFAULT_PREFERENCES),
|
||||
getCookieSize(url),
|
||||
getLocalStorageSize(tabId),
|
||||
getSessionStorageSize(tabId),
|
||||
]);
|
||||
|
||||
setAutoRefresh(savedPrefs?.autoRefresh ?? DEFAULT_PREFERENCES.autoRefresh);
|
||||
setOptions(savedPrefs?.selectedTypes ?? DEFAULT_PREFERENCES.selectedTypes);
|
||||
setSizes({
|
||||
cookies: cSize,
|
||||
localStorage: lsSize,
|
||||
sessionStorage: ssSize,
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadInfo();
|
||||
}, []);
|
||||
|
||||
const handleAutoRefreshChange = useCallback(async (checked: boolean) => {
|
||||
setAutoRefresh(checked);
|
||||
// Save preference immediately
|
||||
const prefs = await storageUtil.get('storageCleaner/preferences', DEFAULT_PREFERENCES);
|
||||
await storageUtil.set('storageCleaner/preferences', {
|
||||
...(prefs || DEFAULT_PREFERENCES),
|
||||
autoRefresh: checked,
|
||||
});
|
||||
}, []);
|
||||
const handleAutoRefreshChange = useCallback(
|
||||
async (checked: boolean) => {
|
||||
setAutoRefresh(checked);
|
||||
await storageUtil.set('storageCleaner/preferences', {
|
||||
autoRefresh: checked,
|
||||
selectedTypes: options,
|
||||
});
|
||||
},
|
||||
[options],
|
||||
);
|
||||
|
||||
const handleOptionChange = useCallback(async (key: keyof StorageCleanerOptions) => {
|
||||
setOptions((prev) => {
|
||||
const newOptions = { ...prev, [key]: !prev[key] };
|
||||
// Save options immediately
|
||||
storageUtil.get('storageCleaner/preferences', DEFAULT_PREFERENCES).then((prefs) => {
|
||||
const handleOptionChange = useCallback(
|
||||
async (key: keyof StorageCleanerOptions) => {
|
||||
setOptions((prev) => {
|
||||
const newOptions = { ...prev, [key]: !prev[key] };
|
||||
storageUtil.set('storageCleaner/preferences', {
|
||||
...(prefs || DEFAULT_PREFERENCES),
|
||||
autoRefresh,
|
||||
selectedTypes: newOptions,
|
||||
});
|
||||
return newOptions;
|
||||
});
|
||||
return newOptions;
|
||||
});
|
||||
}, []);
|
||||
},
|
||||
[autoRefresh],
|
||||
);
|
||||
|
||||
const allSelected = Object.values(options).every(Boolean);
|
||||
const someSelected = Object.values(options).some(Boolean) && !allSelected;
|
||||
|
||||
const handleSelectAll = useCallback(async (checked: boolean) => {
|
||||
const newOptions = {
|
||||
localStorage: checked,
|
||||
sessionStorage: checked,
|
||||
indexedDB: checked,
|
||||
cookies: checked,
|
||||
cacheStorage: checked,
|
||||
serviceWorkers: checked,
|
||||
};
|
||||
setOptions(newOptions);
|
||||
|
||||
// Save options immediately
|
||||
const prefs = await storageUtil.get('storageCleaner/preferences', DEFAULT_PREFERENCES);
|
||||
await storageUtil.set('storageCleaner/preferences', {
|
||||
...(prefs || DEFAULT_PREFERENCES),
|
||||
selectedTypes: newOptions,
|
||||
});
|
||||
}, []);
|
||||
const handleSelectAll = useCallback(
|
||||
async (checked: boolean) => {
|
||||
const newOptions = {
|
||||
localStorage: checked,
|
||||
sessionStorage: checked,
|
||||
indexedDB: checked,
|
||||
cookies: checked,
|
||||
cacheStorage: checked,
|
||||
serviceWorkers: checked,
|
||||
};
|
||||
setOptions(newOptions);
|
||||
await storageUtil.set('storageCleaner/preferences', {
|
||||
autoRefresh,
|
||||
selectedTypes: newOptions,
|
||||
});
|
||||
},
|
||||
[autoRefresh],
|
||||
);
|
||||
|
||||
const handleClean = useCallback(async () => {
|
||||
const tab = await getCurrentTab();
|
||||
|
||||
if (!tab || !tab.id || !tab.url) {
|
||||
setSnackbar({ open: true, message: '无法获取当前标签页' });
|
||||
showMessage('无法获取当前标签页');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const cleaningResult = await clearStorage(tab.id, tab.url, options);
|
||||
setResult(cleaningResult);
|
||||
|
||||
// Save user preferences
|
||||
await storageUtil.set('storageCleaner/preferences', {
|
||||
autoRefresh,
|
||||
selectedTypes: options,
|
||||
});
|
||||
|
||||
// Auto refresh if enabled
|
||||
if (autoRefresh && cleaningResult.success && tab.id !== undefined) {
|
||||
setSnackbar({ open: true, message: '页面即将刷新,Popup 将关闭' });
|
||||
setTimeout(() => {
|
||||
showMessage('清理成功,即将刷新页面');
|
||||
reloadTimeoutRef.current = setTimeout(() => {
|
||||
chrome.tabs.reload(tab.id!);
|
||||
}, 1500);
|
||||
} else {
|
||||
loadInfo();
|
||||
}
|
||||
} catch (err) {
|
||||
setSnackbar({ open: true, message: `清理失败: ${String(err)}` });
|
||||
showMessage(`清理失败: ${String(err)}`, { severity: 'error' });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setShowConfirm(false);
|
||||
}
|
||||
}, [options, autoRefresh]);
|
||||
|
||||
const handleRefresh = useCallback(async () => {
|
||||
const tab = await getCurrentTab();
|
||||
if (tab?.id !== undefined) {
|
||||
setSnackbar({ open: true, message: '页面即将刷新,Popup 将关闭' });
|
||||
setTimeout(() => {
|
||||
chrome.tabs.reload(tab.id!);
|
||||
}, 1500);
|
||||
}
|
||||
}, []);
|
||||
}, [options, autoRefresh, showMessage]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Paper sx={{ p: 2, m: 1, borderRadius: 2 }}>
|
||||
<Alert severity="error" icon={<WarningIcon />}>
|
||||
<Container sx={{ py: 4 }}>
|
||||
<Alert severity="error" icon={<WarningIcon />} sx={{ borderRadius: 3 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
</Paper>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Paper sx={{ p: 2, m: 1, borderRadius: 2 }}>
|
||||
{/* Header */}
|
||||
<Box sx={{ textAlign: 'center', mb: 2 }}>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
当前页面: {domain || '加载中...'}
|
||||
</Typography>
|
||||
</Box>
|
||||
const totalSize = Object.values(sizes).reduce((acc, curr) => acc + curr, 0);
|
||||
|
||||
{/* Storage Type Options */}
|
||||
<Accordion
|
||||
disableGutters
|
||||
elevation={0}
|
||||
sx={{
|
||||
bgcolor: 'grey.50',
|
||||
borderRadius: 2,
|
||||
mb: 2,
|
||||
'&:before': { display: 'none' },
|
||||
'&.Mui-expanded': { m: 0, mb: 2 },
|
||||
}}
|
||||
>
|
||||
<AccordionSummary
|
||||
expandIcon={<ExpandMoreIcon sx={{ fontSize: '1.1rem' }} />}
|
||||
const OptionItem = ({
|
||||
label,
|
||||
checked,
|
||||
size,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
checked: boolean;
|
||||
size?: number;
|
||||
onChange: () => void;
|
||||
}) => (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
py: 0.6,
|
||||
px: 1.2,
|
||||
borderRadius: 2.5,
|
||||
transition: 'all 0.2s',
|
||||
'&:hover': { bgcolor: 'grey.50' },
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" spacing={0.8} alignItems="baseline">
|
||||
<Typography
|
||||
variant="caption"
|
||||
fontWeight={700}
|
||||
color="text.primary"
|
||||
sx={{ fontSize: '0.75rem' }}
|
||||
>
|
||||
{label}
|
||||
</Typography>
|
||||
{size !== undefined && size > 0 && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{ color: 'text.disabled', fontSize: '0.65rem', fontWeight: 500 }}
|
||||
>
|
||||
{formatSize(size)}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={checked}
|
||||
onChange={onChange}
|
||||
color="warning"
|
||||
sx={{ p: 0.5 }}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
|
||||
return (
|
||||
<Box sx={{ pb: 2 }}>
|
||||
<Container sx={{ py: 2 }}>
|
||||
{/* Domain Header */}
|
||||
<Stack direction="row" spacing={1.5} alignItems="center" sx={{ mb: 2 }}>
|
||||
<Box
|
||||
sx={{
|
||||
p: 1,
|
||||
borderRadius: 2.5,
|
||||
bgcolor: '#fff4e5',
|
||||
color: '#ff9800',
|
||||
display: 'flex',
|
||||
}}
|
||||
>
|
||||
<StorageIcon sx={{ fontSize: 20 }} />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Stack direction="row" justifyContent="space-between" alignItems="center">
|
||||
<Typography
|
||||
variant="subtitle1"
|
||||
fontWeight={900}
|
||||
sx={{ letterSpacing: '-0.5px', lineHeight: 1.2 }}
|
||||
>
|
||||
存储清理
|
||||
</Typography>
|
||||
{totalSize > 0 && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
bgcolor: '#fff4e5',
|
||||
color: '#ff9800',
|
||||
px: 1,
|
||||
py: 0.2,
|
||||
borderRadius: 1.5,
|
||||
fontWeight: 800,
|
||||
fontSize: '0.65rem',
|
||||
}}
|
||||
>
|
||||
已占用 {formatSize(totalSize)}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="text.secondary"
|
||||
sx={{
|
||||
fontWeight: 600,
|
||||
display: 'block',
|
||||
maxWidth: 220,
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
{domain || '加载中...'}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
|
||||
{/* Storage Options Grid */}
|
||||
<Box
|
||||
sx={{
|
||||
px: 2,
|
||||
minHeight: 48,
|
||||
'&.Mui-expanded': { minHeight: 48 },
|
||||
'& .MuiAccordionSummary-content': { my: 1, '&.Mui-expanded': { my: 1 } },
|
||||
mb: 2,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.100',
|
||||
borderRadius: 4,
|
||||
p: 0.8,
|
||||
bgcolor: 'background.paper',
|
||||
}}
|
||||
>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 600, color: 'text.primary' }}>
|
||||
清理选项 {allSelected ? '(全部)' : someSelected ? '(部分)' : '(未选)'}
|
||||
</Typography>
|
||||
</AccordionSummary>
|
||||
<AccordionDetails sx={{ px: 2, pt: 0, pb: 1.5 }}>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={options.localStorage}
|
||||
onChange={() => handleOptionChange('localStorage')}
|
||||
/>
|
||||
}
|
||||
label={<Typography variant="body2">localStorage</Typography>}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={options.sessionStorage}
|
||||
onChange={() => handleOptionChange('sessionStorage')}
|
||||
/>
|
||||
}
|
||||
label={<Typography variant="body2">sessionStorage</Typography>}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={options.indexedDB}
|
||||
onChange={() => handleOptionChange('indexedDB')}
|
||||
/>
|
||||
}
|
||||
label={<Typography variant="body2">IndexedDB</Typography>}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={options.cookies}
|
||||
onChange={() => handleOptionChange('cookies')}
|
||||
/>
|
||||
}
|
||||
label={<Typography variant="body2">Cookies</Typography>}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={options.cacheStorage}
|
||||
onChange={() => handleOptionChange('cacheStorage')}
|
||||
/>
|
||||
}
|
||||
label={<Typography variant="body2">Cache Storage</Typography>}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={options.serviceWorkers}
|
||||
onChange={() => handleOptionChange('serviceWorkers')}
|
||||
/>
|
||||
}
|
||||
label={<Typography variant="body2">Service Workers</Typography>}
|
||||
/>
|
||||
<Divider sx={{ my: 1, opacity: 0.6 }} />
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={allSelected}
|
||||
indeterminate={someSelected}
|
||||
onChange={(e) => handleSelectAll(e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label={
|
||||
<Typography variant="body2" sx={{ fontWeight: 600 }}>
|
||||
全选
|
||||
</Typography>
|
||||
}
|
||||
<Grid container spacing={0}>
|
||||
<Grid size={6}>
|
||||
<OptionItem
|
||||
label="LocalStorage"
|
||||
checked={options.localStorage}
|
||||
size={sizes.localStorage}
|
||||
onChange={() => handleOptionChange('localStorage')}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<OptionItem
|
||||
label="Session"
|
||||
checked={options.sessionStorage}
|
||||
size={sizes.sessionStorage}
|
||||
onChange={() => handleOptionChange('sessionStorage')}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<OptionItem
|
||||
label="IndexedDB"
|
||||
checked={options.indexedDB}
|
||||
onChange={() => handleOptionChange('indexedDB')}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<OptionItem
|
||||
label="Cookies"
|
||||
checked={options.cookies}
|
||||
size={sizes.cookies}
|
||||
onChange={() => handleOptionChange('cookies')}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<OptionItem
|
||||
label="Cache"
|
||||
checked={options.cacheStorage}
|
||||
onChange={() => handleOptionChange('cacheStorage')}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<OptionItem
|
||||
label="Workers"
|
||||
checked={options.serviceWorkers}
|
||||
onChange={() => handleOptionChange('serviceWorkers')}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
<Divider sx={{ my: 0.8, borderColor: 'grey.50' }} />
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
px: 1.2,
|
||||
py: 0.4,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="caption"
|
||||
fontWeight={800}
|
||||
sx={{ color: 'text.secondary', fontSize: '0.65rem' }}
|
||||
>
|
||||
全选所有项
|
||||
</Typography>
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={allSelected}
|
||||
indeterminate={someSelected}
|
||||
onChange={(e) => handleSelectAll(e.target.checked)}
|
||||
color="warning"
|
||||
sx={{ p: 0.5 }}
|
||||
/>
|
||||
</Box>
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
</Box>
|
||||
|
||||
{/* Auto Refresh Option */}
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
checked={autoRefresh}
|
||||
onChange={(e) => handleAutoRefreshChange(e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label="清理完成后自动刷新页面"
|
||||
/>
|
||||
</Box>
|
||||
{/* Auto Refresh Toggle */}
|
||||
<Box
|
||||
sx={{
|
||||
mb: 2,
|
||||
p: 1.2,
|
||||
borderRadius: 4,
|
||||
bgcolor: 'background.paper',
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.100',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="caption" fontWeight={700}>
|
||||
清理后自动刷新页面
|
||||
</Typography>
|
||||
<Switch
|
||||
size="small"
|
||||
checked={autoRefresh}
|
||||
onChange={(e) => handleAutoRefreshChange(e.target.checked)}
|
||||
color="warning"
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<Box sx={{ display: 'flex', gap: 1, mb: 2 }}>
|
||||
{/* Primary Action */}
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={() => setShowConfirm(true)}
|
||||
sx={{
|
||||
bgcolor: 'primary.main',
|
||||
'&:hover': { bgcolor: 'primary.dark' },
|
||||
py: 1.2,
|
||||
borderRadius: 4,
|
||||
bgcolor: '#ff9800',
|
||||
fontWeight: 800,
|
||||
fontSize: '0.85rem',
|
||||
boxShadow: 'none',
|
||||
'&:hover': { bgcolor: '#f57c00', boxShadow: '0 8px 16px rgba(255, 152, 0, 0.2)' },
|
||||
}}
|
||||
disabled={loading}
|
||||
fullWidth
|
||||
>
|
||||
{loading ? '清理中...' : '清理'}
|
||||
{loading ? '正在清理...' : '立即清理'}
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
{/* Result Display */}
|
||||
{result && (
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Alert
|
||||
severity={result.success ? 'success' : 'error'}
|
||||
sx={{ mb: !autoRefresh && result.success ? 1 : 0 }}
|
||||
>
|
||||
{result.success ? formatCleaningResult(result) : result.error || '清理失败'}
|
||||
</Alert>
|
||||
{!autoRefresh && result.success && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
startIcon={<RefreshIcon />}
|
||||
onClick={handleRefresh}
|
||||
fullWidth
|
||||
{/* Result & Refresh Secondary Action */}
|
||||
{result && (
|
||||
<Box sx={{ mt: 2 }}>
|
||||
<Alert
|
||||
severity={result.success ? 'success' : 'error'}
|
||||
sx={{
|
||||
borderRadius: 2.5,
|
||||
py: 0,
|
||||
'& .MuiAlert-message': { fontSize: '0.75rem', fontWeight: 600 },
|
||||
}}
|
||||
>
|
||||
刷新页面
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
{result.success ? formatCleaningResult(result) : result.error || '清理失败'}
|
||||
</Alert>
|
||||
</Box>
|
||||
)}
|
||||
</Container>
|
||||
|
||||
{/* Confirmation Dialog */}
|
||||
<StorageCleanerConfirm
|
||||
open={showConfirm}
|
||||
onClose={() => setShowConfirm(false)}
|
||||
onConfirm={handleClean}
|
||||
options={options}
|
||||
/>
|
||||
|
||||
{/* Snackbar */}
|
||||
<Snackbar
|
||||
open={snackbar.open}
|
||||
autoHideDuration={3000}
|
||||
onClose={() => setSnackbar({ ...snackbar, open: false })}
|
||||
>
|
||||
<Alert severity="info" variant="filled">
|
||||
{snackbar.message}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
</Paper>
|
||||
<GlobalSnackbar {...snackbarProps} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,20 +4,19 @@ import {
|
||||
TextField,
|
||||
Select,
|
||||
MenuItem,
|
||||
Paper,
|
||||
Stack,
|
||||
Typography,
|
||||
Box,
|
||||
IconButton,
|
||||
Snackbar,
|
||||
Alert,
|
||||
InputAdornment,
|
||||
alpha,
|
||||
Tooltip,
|
||||
Theme,
|
||||
Container,
|
||||
Fade,
|
||||
Divider,
|
||||
} from '@mui/material';
|
||||
import GlobalSnackbar, { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
|
||||
import SwapHorizIcon from '@mui/icons-material/SwapHoriz';
|
||||
import CheckIcon from '@mui/icons-material/Check';
|
||||
import AccessTimeIcon from '@mui/icons-material/AccessTime';
|
||||
import Button from '@/components/Button';
|
||||
@@ -31,33 +30,45 @@ type ZoneType = (typeof ZONES)[number];
|
||||
|
||||
const INPUT_STYLE = {
|
||||
'& .MuiOutlinedInput-root': {
|
||||
bgcolor: 'grey.50',
|
||||
borderRadius: 3,
|
||||
bgcolor: 'background.paper',
|
||||
borderRadius: 3.5,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.100',
|
||||
transition: 'all 0.25s cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
'& fieldset': { border: 'none' },
|
||||
'&:hover': { bgcolor: 'grey.100' },
|
||||
'&:hover': { borderColor: 'grey.300', bgcolor: 'grey.50' },
|
||||
'&.Mui-focused': {
|
||||
bgcolor: '#fff',
|
||||
boxShadow: (theme: Theme) => `0 0 0 2px ${alpha(theme.palette.primary.main, 0.2)}, 0 4px 12px rgba(0,0,0,0.03)`,
|
||||
borderColor: 'primary.main',
|
||||
boxShadow: (theme: Theme) => `0 0 0 4px ${alpha(theme.palette.primary.main, 0.1)}`,
|
||||
},
|
||||
'&.Mui-error': {
|
||||
boxShadow: (theme: Theme) => `0 0 0 2px ${alpha(theme.palette.error.main, 0.2)}`,
|
||||
borderColor: 'error.main',
|
||||
boxShadow: (theme: Theme) => `0 0 0 4px ${alpha(theme.palette.error.main, 0.1)}`,
|
||||
},
|
||||
},
|
||||
'& .MuiInputBase-input': { py: 1.5, fontFamily: 'monospace' },
|
||||
'& .MuiInputBase-input': {
|
||||
py: 1.4,
|
||||
px: 2,
|
||||
fontSize: '0.9rem',
|
||||
fontFamily: 'monospace',
|
||||
fontWeight: 600
|
||||
},
|
||||
};
|
||||
|
||||
// ================= 子组件:实时时钟 =================
|
||||
// ================= 子组件:实时时钟 (优化交互) =================
|
||||
interface LiveClockProps {
|
||||
unit: UnitType;
|
||||
onCopy: (val: string) => void;
|
||||
onUseNow: (val: number) => void;
|
||||
onUnitChange: (u: UnitType) => void;
|
||||
}
|
||||
|
||||
const LiveClock = React.memo(({
|
||||
unit,
|
||||
onCopy,
|
||||
onUseNow
|
||||
onUseNow,
|
||||
onUnitChange
|
||||
}: LiveClockProps) => {
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
|
||||
@@ -71,36 +82,78 @@ const LiveClock = React.memo(({
|
||||
[now, unit]);
|
||||
|
||||
return (
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 4 }}>
|
||||
<Stack direction="row" spacing={1} alignItems="baseline">
|
||||
<Typography variant="h5" sx={{ fontWeight: 300, letterSpacing: '-1px', color: 'text.primary', fontFamily: 'monospace' }}>
|
||||
<Box sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
p: 1.8,
|
||||
mb: 2.5,
|
||||
bgcolor: alpha('#2196f3', 0.04),
|
||||
borderRadius: 4,
|
||||
border: '1px solid',
|
||||
borderColor: alpha('#2196f3', 0.1)
|
||||
}}>
|
||||
<Stack spacing={0.5}>
|
||||
<Typography variant="caption" sx={{ color: 'primary.main', fontWeight: 800, fontSize: '0.6rem', textTransform: 'uppercase', letterSpacing: 1 }}>
|
||||
当前时间戳
|
||||
</Typography>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, color: 'text.primary', fontFamily: 'monospace', fontSize: '1.2rem', letterSpacing: '-0.5px', lineHeight: 1.2 }}>
|
||||
{displayVal}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ color: 'text.secondary', fontWeight: 600, textTransform: 'uppercase' }}>
|
||||
{unit}
|
||||
</Typography>
|
||||
</Stack>
|
||||
<Stack direction="row" spacing={0.5}>
|
||||
<Tooltip title="填充到下方">
|
||||
|
||||
<Stack direction="row" spacing={1} alignItems="center">
|
||||
{/* 胶囊式单位切换器 */}
|
||||
<Box sx={{
|
||||
display: 'flex',
|
||||
p: 0.4,
|
||||
bgcolor: alpha('#2196f3', 0.08),
|
||||
borderRadius: 2.5,
|
||||
border: '1px solid',
|
||||
borderColor: alpha('#2196f3', 0.1)
|
||||
}}>
|
||||
{(['ms', 's'] as const).map((u) => (
|
||||
<Box
|
||||
key={u}
|
||||
onClick={() => onUnitChange(u)}
|
||||
sx={{
|
||||
px: 1.2,
|
||||
py: 0.35,
|
||||
borderRadius: 2,
|
||||
cursor: 'pointer',
|
||||
fontSize: '0.65rem',
|
||||
fontWeight: 900,
|
||||
transition: 'all 0.2s',
|
||||
bgcolor: unit === u ? '#fff' : 'transparent',
|
||||
color: unit === u ? 'primary.main' : alpha('#2196f3', 0.4),
|
||||
boxShadow: unit === u ? '0 2px 6px rgba(33, 150, 243, 0.2)' : 'none',
|
||||
}}
|
||||
>
|
||||
{u.toUpperCase()}
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
<Divider orientation="vertical" flexItem sx={{ mx: 0.5, my: 1, borderColor: alpha('#2196f3', 0.1) }} />
|
||||
|
||||
<Stack direction="row" spacing={0.5}>
|
||||
<Tooltip title="填充到下方">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() => onUseNow(now)}
|
||||
sx={{ color: 'primary.main', bgcolor: '#fff', boxShadow: '0 2px 4px rgba(0,0,0,0.05)', '&:hover': { bgcolor: 'primary.main', color: '#fff' } }}
|
||||
>
|
||||
<AccessTimeIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<IconButton
|
||||
aria-label="use current time"
|
||||
size="small"
|
||||
onClick={() => onUseNow(now)}
|
||||
sx={{ color: 'primary.main', transition: 'all 0.2s', '&:hover': { bgcolor: alpha('#2563eb', 0.08) } }}
|
||||
>
|
||||
<AccessTimeIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title="复制当前时间戳">
|
||||
<IconButton
|
||||
aria-label="copy current timestamp"
|
||||
size="small"
|
||||
onClick={() => onCopy(displayVal)}
|
||||
sx={{ color: 'grey.400', transition: 'all 0.2s', '&:hover': { color: 'primary.main', transform: 'scale(1.1)' } }}
|
||||
sx={{ color: 'grey.400', '&:hover': { color: 'primary.main' } }}
|
||||
>
|
||||
<ContentCopyIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
@@ -146,73 +199,79 @@ const ResultView = React.memo(({
|
||||
if (!result) return null;
|
||||
|
||||
return (
|
||||
<Box sx={{
|
||||
mt: 3, pt: 3, borderTop: '1px solid', borderColor: 'grey.50',
|
||||
animation: 'fadeIn 0.3s ease-out',
|
||||
'@keyframes fadeIn': { from: { opacity: 0, transform: 'translateY(10px)' }, to: { opacity: 1, transform: 'translateY(0)' } }
|
||||
}}>
|
||||
<Typography variant="caption" sx={{ color: 'text.disabled', mb: 1, display: 'block', ml: 1, fontWeight: 500 }}>
|
||||
转换结果
|
||||
</Typography>
|
||||
<TextField
|
||||
fullWidth
|
||||
value={result}
|
||||
slotProps={{
|
||||
input: {
|
||||
readOnly: true,
|
||||
endAdornment: (
|
||||
<InputAdornment position="end">
|
||||
<IconButton
|
||||
aria-label="copy result"
|
||||
size="small"
|
||||
onClick={handleCopy}
|
||||
sx={{
|
||||
color: copied ? 'success.main' : 'primary.main',
|
||||
transition: 'all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)',
|
||||
transform: copied ? 'scale(1.2)' : 'scale(1)',
|
||||
}}
|
||||
>
|
||||
{copied ? <CheckIcon fontSize="small" /> : <ContentCopyIcon fontSize="small" />}
|
||||
</IconButton>
|
||||
</InputAdornment>
|
||||
),
|
||||
},
|
||||
}}
|
||||
sx={{
|
||||
...INPUT_STYLE,
|
||||
mb: 2,
|
||||
'& .MuiOutlinedInput-root': {
|
||||
...INPUT_STYLE['& .MuiOutlinedInput-root'],
|
||||
bgcolor: alpha('#2563eb', 0.03),
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Fade in={!!result}>
|
||||
<Box sx={{ mt: 3, pt: 2.5, borderTop: '1px solid', borderColor: 'grey.50' }}>
|
||||
<Typography variant="caption" sx={{ color: 'text.secondary', mb: 1.2, display: 'block', fontWeight: 800, fontSize: '0.7rem' }}>
|
||||
转换结果
|
||||
</Typography>
|
||||
|
||||
{/* 辅助信息预览 */}
|
||||
<Stack spacing={1} sx={{ px: 1 }}>
|
||||
{[
|
||||
{ label: '相对时间', value: extraInfo?.relative },
|
||||
{ label: 'ISO 8601', value: extraInfo?.iso },
|
||||
{ label: 'UTC 时间', value: extraInfo?.utc },
|
||||
].map((item) => (
|
||||
<Box key={item.label} sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<Typography variant="caption" sx={{ color: 'text.secondary' }}>{item.label}</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
onClick={() => { if (item.value) onCopy(item.value); }}
|
||||
sx={{
|
||||
fontFamily: 'monospace',
|
||||
color: 'text.primary',
|
||||
cursor: 'pointer',
|
||||
'&:hover': { color: 'primary.main', textDecoration: 'underline' }
|
||||
}}
|
||||
>
|
||||
{item.value}
|
||||
</Typography>
|
||||
</Box>
|
||||
))}
|
||||
</Stack>
|
||||
</Box>
|
||||
<Box sx={{
|
||||
bgcolor: alpha('#2196f3', 0.05),
|
||||
p: 2,
|
||||
borderRadius: 4,
|
||||
position: 'relative',
|
||||
mb: 2.5,
|
||||
border: '1px solid',
|
||||
borderColor: alpha('#2196f3', 0.1)
|
||||
}}>
|
||||
<Typography
|
||||
variant="body1"
|
||||
sx={{
|
||||
fontFamily: 'monospace',
|
||||
fontWeight: 700,
|
||||
color: 'primary.main',
|
||||
wordBreak: 'break-all',
|
||||
pr: 4,
|
||||
fontSize: '1rem'
|
||||
}}
|
||||
>
|
||||
{result}
|
||||
</Typography>
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={handleCopy}
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
right: 8,
|
||||
top: '50%',
|
||||
transform: 'translateY(-50%)',
|
||||
color: copied ? 'success.main' : 'primary.main',
|
||||
bgcolor: '#fff',
|
||||
boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
|
||||
'&:hover': { bgcolor: copied ? 'success.main' : 'primary.main', color: '#fff' }
|
||||
}}
|
||||
>
|
||||
{copied ? <CheckIcon fontSize="small" /> : <ContentCopyIcon fontSize="small" />}
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
<Stack spacing={1.2}>
|
||||
{[
|
||||
{ label: '相对时间', value: extraInfo?.relative },
|
||||
{ label: 'ISO 8601', value: extraInfo?.iso },
|
||||
{ label: 'UTC 时间', value: extraInfo?.utc },
|
||||
].map((item) => (
|
||||
<Box key={item.label} sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', px: 1 }}>
|
||||
<Typography variant="caption" sx={{ color: 'text.disabled', fontWeight: 700, fontSize: '0.65rem' }}>{item.label}</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
onClick={() => { if (item.value) onCopy(item.value); }}
|
||||
sx={{
|
||||
fontFamily: 'monospace',
|
||||
color: 'text.secondary',
|
||||
fontWeight: 600,
|
||||
fontSize: '0.65rem',
|
||||
cursor: 'pointer',
|
||||
'&:hover': { color: 'primary.main' }
|
||||
}}
|
||||
>
|
||||
{item.value}
|
||||
</Typography>
|
||||
</Box>
|
||||
))}
|
||||
</Stack>
|
||||
</Box>
|
||||
</Fade>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -227,16 +286,16 @@ export default function TimestampPage() {
|
||||
const [zone, setZone] = useState<ZoneType>('Asia/Shanghai');
|
||||
const [result, setResult] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [snack, setSnack] = useState<{ open: boolean; msg: string }>({ open: false, msg: '' });
|
||||
const { snackbarProps, showMessage } = useSnackbar({ autoHideDuration: 1500 });
|
||||
|
||||
const copy = useCallback(async (text: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setSnack({ open: true, msg: '已复制' });
|
||||
showMessage('已复制', { severity: 'success' });
|
||||
} catch {
|
||||
setSnack({ open: true, msg: '复制失败' });
|
||||
showMessage('复制失败', { severity: 'error' });
|
||||
}
|
||||
}, []);
|
||||
}, [showMessage]);
|
||||
|
||||
const convert = useCallback(() => {
|
||||
if (mode === 'ts2dt') {
|
||||
@@ -259,14 +318,9 @@ export default function TimestampPage() {
|
||||
}
|
||||
}, [mode, tsInput, dtInput, unit, zone]);
|
||||
|
||||
// 智能实时转换 (Debounce Effect)
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
convert();
|
||||
}, 400);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
};
|
||||
const timer = setTimeout(convert, 400);
|
||||
return () => clearTimeout(timer);
|
||||
}, [convert]);
|
||||
|
||||
const handleUseNow = useCallback((now: number) => {
|
||||
@@ -278,59 +332,71 @@ export default function TimestampPage() {
|
||||
}, [mode, unit, zone]);
|
||||
|
||||
return (
|
||||
<Box sx={{ p: 1, width: '100%', bgcolor: 'transparent', boxSizing: 'border-box' }}>
|
||||
<Paper
|
||||
elevation={0}
|
||||
sx={{
|
||||
p: 2.5,
|
||||
<Box sx={{ pb: 3 }}>
|
||||
<Container sx={{ py: 2 }}>
|
||||
{/* Header with Icon */}
|
||||
<Stack direction="row" spacing={1.5} alignItems="center" sx={{ mb: 2.5 }}>
|
||||
<Box sx={{ p: 1, borderRadius: 2.5, bgcolor: alpha('#2196f3', 0.1), color: 'primary.main', display: 'flex' }}>
|
||||
<AccessTimeIcon sx={{ fontSize: 20 }} />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography variant="subtitle1" fontWeight={900} sx={{ letterSpacing: '-0.5px', lineHeight: 1.2 }}>
|
||||
时间戳转换
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ fontWeight: 600 }}>
|
||||
Unix 毫秒数转换与格式化
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
|
||||
{/* Live Clock Card */}
|
||||
<LiveClock unit={unit} onCopy={copy} onUseNow={handleUseNow} onUnitChange={setUnit} />
|
||||
|
||||
{/* Mode Switcher */}
|
||||
<Box sx={{
|
||||
position: 'relative',
|
||||
display: 'flex',
|
||||
p: 0.6,
|
||||
bgcolor: 'grey.100',
|
||||
borderRadius: 4,
|
||||
mb: 2.5,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.100',
|
||||
transition: 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
'&:hover': { boxShadow: '0 12px 40px rgba(0,0,0,0.06)', borderColor: 'grey.200' },
|
||||
}}
|
||||
>
|
||||
{/* 1. 实时时钟 */}
|
||||
<Box sx={{ position: 'relative' }}>
|
||||
<LiveClock unit={unit} onCopy={copy} onUseNow={handleUseNow} />
|
||||
<Tooltip title="切换单位">
|
||||
<IconButton
|
||||
aria-label="switch unit"
|
||||
size="small"
|
||||
onClick={() => { setUnit((u) => (u === 'ms' ? 's' : 'ms')); }}
|
||||
borderColor: 'grey.200'
|
||||
}}>
|
||||
<Box sx={{
|
||||
position: 'absolute',
|
||||
height: 'calc(100% - 10px)',
|
||||
width: 'calc(50% - 5px)',
|
||||
bgcolor: '#fff',
|
||||
borderRadius: 3.5,
|
||||
boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
|
||||
transition: 'transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
transform: mode === 'ts2dt' ? 'translateX(0)' : 'translateX(100%)',
|
||||
top: 5, left: 5,
|
||||
}} />
|
||||
{(['ts2dt', 'dt2ts'] as const).map((m) => (
|
||||
<Box
|
||||
key={m}
|
||||
onClick={() => { setMode(m); setError(''); setResult(''); }}
|
||||
sx={{
|
||||
position: 'absolute', right: 80, top: 4, color: 'grey.400',
|
||||
transition: 'transform 0.3s ease',
|
||||
'&:hover': { transform: 'rotate(180deg)', color: 'primary.main' }
|
||||
flex: 1,
|
||||
py: 1,
|
||||
textAlign: 'center',
|
||||
position: 'relative',
|
||||
zIndex: 1,
|
||||
cursor: 'pointer',
|
||||
fontWeight: 800,
|
||||
fontSize: '0.75rem',
|
||||
color: mode === m ? 'primary.main' : 'text.secondary',
|
||||
transition: 'color 0.3s'
|
||||
}}
|
||||
>
|
||||
<SwapHorizIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
|
||||
{/* 2. 模式切换 */}
|
||||
<Box sx={{ position: 'relative', display: 'flex', p: 0.5, bgcolor: 'grey.100', borderRadius: 3.5, mb: 3, overflow: 'hidden' }}>
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute', height: 'calc(100% - 8px)', width: 'calc(50% - 4px)',
|
||||
bgcolor: '#fff', borderRadius: 3, boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
|
||||
transition: 'transform 0.25s cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
transform: mode === 'ts2dt' ? 'translateX(0)' : 'translateX(100%)',
|
||||
top: 4, left: 4,
|
||||
}}
|
||||
/>
|
||||
{(['ts2dt', 'dt2ts'] as const).map((m) => (
|
||||
<Button
|
||||
key={m} fullWidth disableRipple
|
||||
onClick={() => { setMode(m); setError(''); setResult(''); }}
|
||||
>
|
||||
{m === 'ts2dt' ? '时间戳 → 日期' : '日期 → 时间戳'}
|
||||
</Button>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
{/* 3. 输入与设置 */}
|
||||
{/* Input Area */}
|
||||
<Stack spacing={2} sx={{ mb: 3 }}>
|
||||
<TextField
|
||||
placeholder={mode === 'ts2dt' ? "输入时间戳..." : DATE_FORMAT}
|
||||
@@ -350,51 +416,76 @@ export default function TimestampPage() {
|
||||
sx={INPUT_STYLE}
|
||||
/>
|
||||
|
||||
<Stack direction="row" spacing={2}>
|
||||
<Select
|
||||
fullWidth value={unit}
|
||||
onChange={(e) => { setUnit(e.target.value as UnitType); }}
|
||||
sx={{ ...INPUT_STYLE, flex: 1 }}
|
||||
MenuProps={{ PaperProps: { sx: { borderRadius: 3, mt: 1, boxShadow: '0 10px 40px rgba(0,0,0,0.1)' } } }}
|
||||
>
|
||||
<MenuItem value="ms">毫秒 (ms)</MenuItem>
|
||||
<MenuItem value="s">秒 (s)</MenuItem>
|
||||
</Select>
|
||||
<Stack direction="row" spacing={1.5}>
|
||||
{/* 优化后的单位选择按钮组 */}
|
||||
<Box sx={{
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
bgcolor: 'grey.50',
|
||||
p: 0.5,
|
||||
borderRadius: 3.5,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.100'
|
||||
}}>
|
||||
{(['ms', 's'] as const).map((u) => (
|
||||
<Box
|
||||
key={u}
|
||||
onClick={() => setUnit(u)}
|
||||
sx={{
|
||||
flex: 1,
|
||||
py: 0.8,
|
||||
textAlign: 'center',
|
||||
borderRadius: 3,
|
||||
cursor: 'pointer',
|
||||
fontSize: '0.75rem',
|
||||
fontWeight: 800,
|
||||
transition: 'all 0.2s',
|
||||
bgcolor: unit === u ? '#fff' : 'transparent',
|
||||
color: unit === u ? 'primary.main' : 'text.disabled',
|
||||
boxShadow: unit === u ? '0 2px 8px rgba(0,0,0,0.05)' : 'none',
|
||||
}}
|
||||
>
|
||||
{u === 'ms' ? '毫秒 (ms)' : '秒 (s)'}
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
<Select
|
||||
fullWidth value={zone}
|
||||
onChange={(e) => { setZone(e.target.value as ZoneType); }}
|
||||
sx={{ ...INPUT_STYLE, flex: 1.5 }}
|
||||
MenuProps={{ PaperProps: { sx: { borderRadius: 3, mt: 1, boxShadow: '0 10px 40px rgba(0,0,0,0.1)' } } }}
|
||||
onChange={(e) => setZone(e.target.value as ZoneType)}
|
||||
sx={{ ...INPUT_STYLE, flex: 1 }}
|
||||
MenuProps={{ PaperProps: { sx: { borderRadius: 3, mt: 1, boxShadow: '0 12px 32px rgba(0,0,0,0.1)' } } }}
|
||||
>
|
||||
{ZONES.map((z) => (
|
||||
<MenuItem key={z} value={z}>{z}</MenuItem>
|
||||
<MenuItem key={z} value={z} sx={{ fontSize: '0.8rem', fontWeight: 600 }}>{z}</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
{/* 4. 转换操作 (作为手动确认) */}
|
||||
{/* Main Action */}
|
||||
<Button
|
||||
fullWidth variant="contained" disableElevation disableRipple
|
||||
fullWidth
|
||||
variant="contained"
|
||||
onClick={convert}
|
||||
sx={{
|
||||
py: 1.4,
|
||||
borderRadius: 4,
|
||||
bgcolor: 'primary.main',
|
||||
fontWeight: 800,
|
||||
fontSize: '0.9rem',
|
||||
boxShadow: 'none',
|
||||
'&:hover': { bgcolor: 'primary.dark', boxShadow: `0 8px 24px ${alpha('#2196f3', 0.2)}` }
|
||||
}}
|
||||
>
|
||||
立即转换
|
||||
</Button>
|
||||
|
||||
{/* 5. 结果展示 */}
|
||||
{/* Result View */}
|
||||
<ResultView result={result} mode={mode} unit={unit} zone={zone} onCopy={copy} />
|
||||
</Paper>
|
||||
</Container>
|
||||
|
||||
<Snackbar
|
||||
open={snack.open} autoHideDuration={1500}
|
||||
onClose={() => { setSnack((s) => ({ ...s, open: false })); }}
|
||||
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
|
||||
>
|
||||
<Alert severity="success" variant="filled" icon={false} sx={{ borderRadius: 2.5, bgcolor: 'grey.900' }}>
|
||||
{snack.msg}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
<GlobalSnackbar {...snackbarProps} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/* 极简滚动条变量 */
|
||||
:root {
|
||||
/* 统一圆角变量 */
|
||||
--radius: 8px;
|
||||
/* 统一背景颜色变量 */
|
||||
--bg-color: #fafafa;
|
||||
/* 统一文字颜色变量 */
|
||||
--text-color: #333333;
|
||||
/* 统一按钮颜色变量 */
|
||||
--btn-bg: #e0e0e0;
|
||||
/* 统一按钮文字颜色变量 */
|
||||
--btn-text: #333333;
|
||||
--border: 1px solid #e0e0e0;
|
||||
|
||||
/* 滚动条变量 */
|
||||
--sb-width: 6px;
|
||||
--sb-thumb-color: rgba(0, 0, 0, 0.1);
|
||||
--sb-thumb-hover: rgba(0, 0, 0, 0.2);
|
||||
--sb-track-color: transparent;
|
||||
}
|
||||
|
||||
/* 适配侧边栏 - 使用百分比而非固定尺寸 */
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
overflow: hidden; /* 禁用外层滚动 */
|
||||
}
|
||||
|
||||
/* 全局极简滚动条定制 */
|
||||
*::-webkit-scrollbar {
|
||||
width: var(--sb-width);
|
||||
}
|
||||
|
||||
*::-webkit-scrollbar-track {
|
||||
background: var(--sb-track-color);
|
||||
}
|
||||
|
||||
*::-webkit-scrollbar-thumb {
|
||||
background: var(--sb-thumb-color);
|
||||
border-radius: 10px;
|
||||
background-clip: content-box;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
*::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--sb-thumb-hover);
|
||||
}
|
||||
|
||||
.app {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
overflow: hidden; /* 内部由 flex 子项控制滚动 */
|
||||
}
|
||||
|
||||
/* Animations */
|
||||
@keyframes slideInRight {
|
||||
from {
|
||||
transform: translateX(30px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.page-transition-enter {
|
||||
animation: slideInRight 0.3s cubic-bezier(0.25, 0.8, 0.25, 1) forwards;
|
||||
}
|
||||
|
||||
.page-transition-dashboard {
|
||||
animation: fadeIn 0.3s ease-out forwards;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import './App.css';
|
||||
import RouterProvider from '@/providers/RouterProvider';
|
||||
import TopBar from '@/components/TopBar';
|
||||
import RouterContainer from '@/components/RouterContainer';
|
||||
|
||||
function App() {
|
||||
const handleOpenOptions = () => {
|
||||
chrome.runtime.openOptionsPage();
|
||||
};
|
||||
|
||||
return (
|
||||
<RouterProvider defaultRoute="dashboard">
|
||||
<div className="app" style={{ display: 'flex', flexDirection: 'column', height: '100vh', overflow: 'hidden' }}>
|
||||
<TopBar onOpenOptions={handleOpenOptions} />
|
||||
<RouterContainer />
|
||||
</div>
|
||||
</RouterProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Testing Tools - Side Panel</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,10 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App.tsx';
|
||||
import './style.css';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,22 @@
|
||||
body {
|
||||
margin: 0;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Ubuntu', 'Cantarell', 'Fira Sans',
|
||||
'Droid Sans', 'Helvetica Neue', sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5,
|
||||
h6 {
|
||||
font-size: inherit; /* 先全部重置为继承大小 */
|
||||
font-weight: inherit;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||
import type { PageType } from '@/types/storage';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
import { getDefaultVisibleRoutes } from '@/config/routes';
|
||||
|
||||
interface RouterContextType {
|
||||
currentPage: PageType;
|
||||
visiblePages: PageType[];
|
||||
isLoaded: boolean;
|
||||
navigateTo: (page: PageType) => void;
|
||||
navigateLocal: (page: PageType) => void;
|
||||
syncNavigation: (page: PageType) => void;
|
||||
goBack: () => void;
|
||||
setVisiblePages: (pages: PageType[]) => void;
|
||||
}
|
||||
|
||||
const RouterContext = createContext<RouterContextType | null>(null);
|
||||
|
||||
interface RouterProviderProps {
|
||||
children: ReactNode;
|
||||
defaultRoute?: PageType;
|
||||
syncRoute?: boolean;
|
||||
}
|
||||
|
||||
export function RouterProvider({
|
||||
children,
|
||||
defaultRoute = 'dashboard',
|
||||
syncRoute = true
|
||||
}: RouterProviderProps) {
|
||||
const [currentPage, setCurrentPage] = useState<PageType>(defaultRoute);
|
||||
const [visiblePages, setVisiblePages] = useState<PageType[]>(getDefaultVisibleRoutes());
|
||||
const [isLoaded, setIsLoaded] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadInitialData();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (isLoaded && syncRoute) {
|
||||
storageUtil.set('app/currentRoute', currentPage);
|
||||
}
|
||||
}, [currentPage, isLoaded, syncRoute]);
|
||||
|
||||
// Listen for storage changes if sync is enabled
|
||||
useEffect(() => {
|
||||
if (!syncRoute) return;
|
||||
|
||||
const handleStorageChange = (changes: { [key: string]: chrome.storage.StorageChange }) => {
|
||||
if (changes['app/currentRoute']) {
|
||||
const newRoute = changes['app/currentRoute'].newValue as PageType;
|
||||
if (newRoute && newRoute !== currentPage) {
|
||||
setCurrentPage(newRoute);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
chrome.storage.onChanged.addListener(handleStorageChange);
|
||||
return () => chrome.storage.onChanged.removeListener(handleStorageChange);
|
||||
}, [syncRoute, currentPage]);
|
||||
|
||||
const loadInitialData = async () => {
|
||||
try {
|
||||
const [savedRoute, savedVisiblePages] = await Promise.all([
|
||||
storageUtil.get('app/currentRoute', defaultRoute),
|
||||
storageUtil.get('app/visiblePages', getDefaultVisibleRoutes()),
|
||||
]);
|
||||
|
||||
if (savedRoute && syncRoute) {
|
||||
setCurrentPage(savedRoute);
|
||||
}
|
||||
if (savedVisiblePages) {
|
||||
setVisiblePages(savedVisiblePages);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load initial routing data:', error);
|
||||
} finally {
|
||||
setIsLoaded(true);
|
||||
}
|
||||
};
|
||||
|
||||
const navigateTo = (page: PageType) => {
|
||||
setCurrentPage(page);
|
||||
};
|
||||
|
||||
const navigateLocal = (page: PageType) => {
|
||||
setCurrentPage(page);
|
||||
};
|
||||
|
||||
const syncNavigation = (page: PageType) => {
|
||||
storageUtil.set('app/currentRoute', page);
|
||||
};
|
||||
|
||||
const goBack = () => {
|
||||
setCurrentPage('dashboard');
|
||||
};
|
||||
|
||||
return (
|
||||
<RouterContext.Provider
|
||||
value={{
|
||||
currentPage,
|
||||
visiblePages,
|
||||
isLoaded,
|
||||
navigateTo,
|
||||
navigateLocal,
|
||||
syncNavigation,
|
||||
goBack,
|
||||
setVisiblePages
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</RouterContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useRouter() {
|
||||
const context = useContext(RouterContext);
|
||||
if (!context) {
|
||||
throw new Error('useRouter must be used within a RouterProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
export default RouterProvider;
|
||||
|
Before Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 559 B After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 916 B After Width: | Height: | Size: 2.5 KiB |
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 716 KiB |
@@ -1,19 +1,14 @@
|
||||
{
|
||||
"extends": "./.wxt/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
/* --- 原有配置保持 --- */
|
||||
"allowImportingTsExtensions": true,
|
||||
"jsx": "react-jsx",
|
||||
"esModuleInterop": true,
|
||||
"module": "ESNext", // 支持 import.meta
|
||||
"moduleResolution": "Bundler", // 或者用 "Node"
|
||||
|
||||
/* --- 1. 严格类型检查 (关键) --- */
|
||||
// 开启所有严格检查,包括 noImplicitAny。
|
||||
// 这能帮你捕获 "timer" 隐式 any 等错误,强制你写出更高质量的代码。
|
||||
"strict": true,
|
||||
|
||||
/* --- 2. 代码质量检查 --- */
|
||||
/* --- 代码质量检查 --- */
|
||||
// 声明了但没使用的变量报错(防止代码冗余)
|
||||
"noUnusedLocals": true,
|
||||
// 函数参数没使用报错
|
||||
@@ -23,28 +18,22 @@
|
||||
// switch 语句没有 break 时报错
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
|
||||
/* --- 3. 路径与环境 --- */
|
||||
// 设置基础目录,方便解析相对路径
|
||||
"baseUrl": ".",
|
||||
/* --- 路径与环境 --- */
|
||||
// 确保包含 DOM 类型(解决 setTimeout、document 等报错)
|
||||
"lib": ["DOM", "DOM.Iterable", "ESNext"],
|
||||
// 编译目标设置为最新,WXT 底层 Vite 会处理降级兼容
|
||||
"target": "ESNext",
|
||||
|
||||
/* --- 4. 路径别名 (可选) --- */
|
||||
// 如果你的 @/utils/... 爆红,可以手动添加这个映射。
|
||||
// WXT 通常会自动处理,但在这里显式声明有助于 VS Code 智能提示。
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
},
|
||||
"types": ["chrome", "webextension-polyfill"],
|
||||
"noImplicitAny": false
|
||||
},
|
||||
// 确保包含你的源代码目录
|
||||
"include": [
|
||||
"vite-env.d.ts",
|
||||
"entrypoints/**/*",
|
||||
"components/**/*",
|
||||
"utils/**/*",
|
||||
"types/**/*",
|
||||
"assets/**/*",
|
||||
"hooks/**/*",
|
||||
".wxt/types/**/*.ts",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type PageType = 'timestamp' | 'storageCleaner';
|
||||
export type PageType = 'dashboard' | 'timestamp' | 'storageCleaner' | 'openUrl' | 'openUrlViewer';
|
||||
|
||||
export interface StorageSchema {
|
||||
'app/currentRoute': PageType;
|
||||
@@ -6,6 +6,8 @@ export interface StorageSchema {
|
||||
'app/lastRoute': string;
|
||||
'app/theme': string;
|
||||
'storageCleaner/preferences': StorageCleanerPreferences;
|
||||
'openUrl/preferences': OpenUrlPreferences;
|
||||
'openUrl/currentUrl': string;
|
||||
}
|
||||
|
||||
export interface StorageCleanerPreferences {
|
||||
@@ -13,6 +15,15 @@ export interface StorageCleanerPreferences {
|
||||
selectedTypes: StorageCleanerOptions;
|
||||
}
|
||||
|
||||
export interface OpenUrlEntry {
|
||||
name: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface OpenUrlPreferences {
|
||||
entries: OpenUrlEntry[];
|
||||
}
|
||||
|
||||
export interface StorageCleanerOptions {
|
||||
localStorage: boolean;
|
||||
sessionStorage: boolean;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { StorageSchema } from 'types/storage';
|
||||
import { StorageSchema } from '@/types/storage';
|
||||
|
||||
class StorageUtils {
|
||||
async get<K extends keyof StorageSchema>(key: K): Promise<StorageSchema[K]>;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { StorageCleanerOptions, CleaningResult, StorageCleanResult } from 'types/storage';
|
||||
import type { StorageCleanerOptions, CleaningResult, StorageCleanResult } from '@/types/storage';
|
||||
|
||||
const RESTRICTED_PROTOCOLS = [
|
||||
'chrome:',
|
||||
@@ -20,6 +20,51 @@ export function isRestrictedUrl(url?: string): boolean {
|
||||
return RESTRICTED_PROTOCOLS.some((p) => url.startsWith(p));
|
||||
}
|
||||
|
||||
export async function getCookieSize(url: string): Promise<number> {
|
||||
try {
|
||||
const cookies = await chrome.cookies.getAll({ url });
|
||||
return cookies.reduce((acc, c) => acc + c.name.length + c.value.length, 0);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getLocalStorageSize(tabId: number): Promise<number> {
|
||||
try {
|
||||
const [result] = await chrome.scripting.executeScript({
|
||||
target: { tabId },
|
||||
func: () => {
|
||||
return Object.entries(localStorage).reduce((acc, [k, v]) => acc + k.length + v.length, 0);
|
||||
},
|
||||
});
|
||||
return (result?.result as number) || 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSessionStorageSize(tabId: number): Promise<number> {
|
||||
try {
|
||||
const [result] = await chrome.scripting.executeScript({
|
||||
target: { tabId },
|
||||
func: () => {
|
||||
return Object.entries(sessionStorage).reduce((acc, [k, v]) => acc + k.length + v.length, 0);
|
||||
},
|
||||
});
|
||||
return (result?.result as number) || 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export function formatSize(bytes: number): string {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
export async function clearCookies(url: string): Promise<StorageCleanResult> {
|
||||
try {
|
||||
const cookies = await chrome.cookies.getAll({ url });
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -14,23 +14,20 @@ export default defineConfig({
|
||||
'activeTab',
|
||||
'scripting',
|
||||
'tabs',
|
||||
'debugger',
|
||||
'cookies',
|
||||
'sidePanel',
|
||||
],
|
||||
host_permissions: ['<all_urls>'],
|
||||
action: {
|
||||
default_title: 'Testing Tools',
|
||||
},
|
||||
side_panel: {
|
||||
default_path: 'entrypoints/sidepanel/index.html',
|
||||
},
|
||||
options_ui: {
|
||||
page: 'entrypoints/options/index.html',
|
||||
open_in_tab: true,
|
||||
},
|
||||
// 将 favicon.ico 放入 public/ 文件夹中
|
||||
icons: {
|
||||
16: 'favicon.ico',
|
||||
48: 'favicon.ico',
|
||||
128: 'favicon.ico',
|
||||
},
|
||||
},
|
||||
vite: () => ({
|
||||
build: {
|
||||
|
||||