import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react'; import { Stack, Typography, Box, IconButton, Tooltip, Divider, alpha } from '@mui/material'; import AccessTimeIcon from '@mui/icons-material/AccessTime'; import CopyButton from '@/components/CopyButton'; import { timestampPageStyles } from '@/config/pageTheme'; import type { UnitType } from '@/config/pageTheme'; import type { SnackbarOptions } from '@/components/GlobalSnackbar'; interface LiveClockProps { unit: UnitType; onUseNow: (val: number) => void; onUnitChange: (u: UnitType) => void; showMessage?: (message: string, options?: SnackbarOptions) => void; } const LiveClock = React.memo(({ unit, onUseNow, onUnitChange, showMessage }: LiveClockProps) => { const [now, setNow] = useState(() => Date.now()); const onUseNowRef = useRef(onUseNow); const showMessageRef = useRef(showMessage); useEffect(() => { onUseNowRef.current = onUseNow; showMessageRef.current = showMessage; }, [onUseNow, showMessage]); useEffect(() => { const t = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(t); }, []); const displayVal = useMemo( () => String(Math.floor(now / (unit === 'ms' ? 1 : 1000))), [now, unit], ); const handleUseNow = useCallback(() => { onUseNowRef.current(now); showMessageRef.current?.('已使用当前时间戳', { severity: 'success' }); }, [now, showMessageRef]); return ( 当前时间戳 {displayVal} {/* 胶囊式单位切换器 */} {(['ms', 's'] as const).map((u) => ( 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(timestampPageStyles.primaryColor, 0.4), boxShadow: unit === u ? '0 2px 6px rgba(33, 150, 243, 0.2)' : 'none', }} > {u.toUpperCase()} ))} ); }); LiveClock.displayName = 'LiveClock'; export default LiveClock;