Files
PolyWeather/frontend/hooks/useRelativeTime.ts
T
2569718930@qq.com 6c08a68413 @
性能与用户体验全面优化

    前端性能:
    - 移除 Three.js 依赖(~600KB),天气粒子改为纯 CSS 动画 + Canvas 2D
    - Google Fonts 切换为 next/font 自托管,消除跨域字体请求
    - 合并 ScanTerminalLightTheme.module.css (37KB) 到主 CSS,亮/暗主题统一用 CSS 变量
    - 新增 /api/dashboard/init 聚合端点,首次加载 4 次往返 → 1 次
    - 添加 Service Worker 静态资源缓存,修复 PWA manifest 配置

    用户体验:
    - 新增全局错误边界 error.tsx / global-error.tsx,崩溃不再白屏
    - 决策卡和城市详情的更新时间改为相对时间("15秒前"),每秒自动刷新
    - 数据陈旧时状态标签从青色切换为琥珀色提示

    DEB 算法增强:
    - 市场扫描路径接入 Open-Meteo 多模型数据(ECMWF/GFS/ICON/JMA/HRDPS 等)
    - MAE 计算加入时间衰减(decay_factor=0.85),近期模型误差权重更高

    Scope-risk: MEDIUM — 全量 170 测试通过,前端 TypeScript/build 通过,ruff 零告警
    Tested: python -m pytest -q (170 passed), npx tsc --noEmit (0 errors), npm run build (success), ruff check .
@
2026-05-14 21:31:05 +08:00

38 lines
1.2 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
function relativeTime(date: Date, now: Date): string {
const diffMs = now.getTime() - date.getTime();
if (diffMs < 0) return "刚刚";
const seconds = Math.floor(diffMs / 1000);
if (seconds < 10) return "刚刚";
if (seconds < 60) return `${seconds}秒前`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}分钟前`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}小时前`;
const days = Math.floor(hours / 24);
return `${days}天前`;
}
export function useRelativeTime(isoString: string | null | undefined): string {
const [tick, setTick] = useState(0);
const date = isoString ? new Date(isoString) : null;
useEffect(() => {
if (!date) return;
const interval = setInterval(() => setTick((n) => n + 1), 30_000);
const onVisible = () => setTick((n) => n + 1);
document.addEventListener("visibilitychange", onVisible);
return () => {
clearInterval(interval);
document.removeEventListener("visibilitychange", onVisible);
};
}, [date]);
if (!date || isNaN(date.getTime())) return "";
return relativeTime(date, new Date());
}