Files
vf_react/src/views/Center/utils/formatters.ts
zdl 18ba36a539 refactor(Center): 全面优化个人中心模块
- 目录重命名:Dashboard → Center(匹配路由 /home/center)
- 删除遗留代码:Default.js、InvestmentPlansAndReviews.js、InvestmentCalendarChakra.js(共 2596 行)
- 创建 src/types/center.ts 类型定义(15+ 接口)
- 性能优化:
  - 创建 useCenterColors Hook 封装 7 个 useColorModeValue
  - 创建 utils/formatters.ts 提取纯函数
  - 修复 loadRealtimeQuotes 的 useCallback 依赖项
  - InvestmentPlanningCenter 添加 useMemo 缓存
- TypeScript 迁移:Center.js → Center.tsx

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-22 18:59:09 +08:00

88 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Center 模块格式化工具函数
*
* 这些是纯函数,提取到组件外部避免每次渲染重建
*/
/**
* 格式化相对时间(如 "5分钟前"、"3天前"
* @param dateString 日期字符串
* @returns 格式化后的相对时间字符串
*/
export function formatRelativeTime(dateString: string | null | undefined): string {
if (!dateString) return '';
const date = new Date(dateString);
const now = new Date();
const diffTime = Math.abs(now.getTime() - date.getTime());
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays < 1) {
const diffHours = Math.ceil(diffTime / (1000 * 60 * 60));
if (diffHours < 1) {
const diffMinutes = Math.ceil(diffTime / (1000 * 60));
return `${diffMinutes}分钟前`;
}
return `${diffHours}小时前`;
} else if (diffDays < 7) {
return `${diffDays}天前`;
} else {
return date.toLocaleDateString('zh-CN');
}
}
/**
* 格式化数字(如 10000 → "1w"1500 → "1.5k"
* @param num 数字
* @returns 格式化后的字符串
*/
export function formatCompactNumber(num: number | null | undefined): string {
if (!num) return '0';
if (num >= 10000) {
return (num / 10000).toFixed(1) + 'w';
} else if (num >= 1000) {
return (num / 1000).toFixed(1) + 'k';
}
return num.toString();
}
/**
* 根据热度分数获取颜色
* @param score 热度分数 (0-100)
* @returns Chakra UI 颜色名称
*/
export function getHeatColor(score: number): string {
if (score >= 80) return 'red';
if (score >= 60) return 'orange';
if (score >= 40) return 'yellow';
return 'green';
}
/**
* 根据涨跌幅获取颜色
* @param changePercent 涨跌幅百分比
* @returns 颜色值
*/
export function getChangeColor(changePercent: number | null | undefined): string {
if (changePercent === null || changePercent === undefined) {
return 'rgba(255, 255, 255, 0.6)';
}
if (changePercent > 0) return '#EF4444'; // 红色(涨)
if (changePercent < 0) return '#22C55E'; // 绿色(跌)
return 'rgba(255, 255, 255, 0.6)'; // 灰色(平)
}
/**
* 格式化涨跌幅显示
* @param changePercent 涨跌幅百分比
* @returns 格式化后的字符串(如 "+5.23%"
*/
export function formatChangePercent(changePercent: number | null | undefined): string {
if (changePercent === null || changePercent === undefined) {
return '--';
}
const prefix = changePercent > 0 ? '+' : '';
return `${prefix}${Number(changePercent).toFixed(2)}%`;
}