"use client"; import { useSyncExternalStore } from "react"; import { formatDistanceToNow, format } from "date-fns"; import { enUS, zhCN } from "date-fns/locale"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { useI18n } from "@/i18n/i18n-context"; // Shared singleton timer — all RelativeTime instances share one tick let tick = 0; const listeners: Set<() => void> = new Set(); let timerId: ReturnType | null = null; function subscribe(listener: () => void) { listeners.add(listener); if (listeners.size === 1 && !timerId) { timerId = setInterval(() => { tick++; listeners.forEach((l) => l()); }, 60_000); } return () => { listeners.delete(listener); if (listeners.size === 0 && timerId) { clearInterval(timerId); timerId = null; } }; } function getSnapshot() { return tick; } function getServerSnapshot() { return 0; } interface RelativeTimeProps { timestamp: number; } /** * Shows a relative-time label (e.g. "2 小时前") with a styled tooltip * exposing the absolute local-timezone timestamp on hover. Replaces * the previous native `title` attribute, which had a 1.5 s delay and * unstyled OS tooltip; the shadcn Tooltip surfaces instantly with the * dashboard's own typography + shadow tokens. */ export function RelativeTime({ timestamp }: RelativeTimeProps) { useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); const { locale } = useI18n(); const dateLocale = locale === "en" ? enUS : zhCN; const date = new Date(timestamp); const relativeText = formatDistanceToNow(date, { addSuffix: true, locale: dateLocale, }); // `format` from date-fns uses the runtime's local timezone implicitly; // showing the timezone offset tag (e.g. UTC+8) makes that explicit so // users in different regions can interpret the value unambiguously. const localText = format(date, "yyyy-MM-dd HH:mm:ss (OOOO)", { locale: dateLocale, }); return ( {relativeText} {localText} ); }