Files
Cli-Proxy-API-Management-Ce…/src/utils/format.ts
Supra4E8C cd6c142324 fix: fix log page timestamp display and optimize AuthFiles layout
- Add formatUnixTimestamp utility to auto-detect timestamp precision (s/ms/μs/ns)
  - Fix incorrect file modification time display in logs page
  - Remove fixed height constraint from AuthFilesPage model list
2025-12-17 18:03:25 +08:00

102 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.
/**
* 格式化工具函数
* 从原项目 src/utils/string.js 迁移
*/
/**
* 隐藏 API Key 中间部分
*/
export function maskApiKey(key: string, visibleChars: number = 4): string {
if (!key || key.length <= visibleChars * 2) {
return key;
}
const start = key.slice(0, visibleChars);
const end = key.slice(-visibleChars);
const maskedLength = Math.min(key.length - visibleChars * 2, 20);
const masked = '*'.repeat(maskedLength);
return `${start}${masked}${end}`;
}
/**
* 格式化文件大小
*/
export function formatFileSize(bytes: number): string {
if (bytes === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB'];
const k = 1024;
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(2)} ${units[i]}`;
}
/**
* 格式化日期时间
*/
export function formatDateTime(date: string | Date): string {
const d = typeof date === 'string' ? new Date(date) : date;
if (isNaN(d.getTime())) {
return 'Invalid Date';
}
return d.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
}
/**
* 将 Unix 时间戳(秒/毫秒/微秒/纳秒)格式化为本地时间字符串
*/
export function formatUnixTimestamp(value: unknown, locale?: string): string {
if (value === null || value === undefined || value === '') return '';
const asNumber = typeof value === 'number' ? value : Number(value);
const date = (() => {
if (!Number.isFinite(asNumber) || Number.isNaN(asNumber)) {
return new Date(String(value));
}
const abs = Math.abs(asNumber);
// 秒:常见 10 位(~1e9
if (abs < 1e11) return new Date(asNumber * 1000);
// 毫秒:常见 13 位(~1e12
if (abs < 1e14) return new Date(asNumber);
// 微秒:常见 16 位(~1e15
if (abs < 1e17) return new Date(Math.round(asNumber / 1000));
// 纳秒:常见 19 位(~1e18
return new Date(Math.round(asNumber / 1e6));
})();
if (Number.isNaN(date.getTime())) return '';
return locale ? date.toLocaleString(locale) : date.toLocaleString();
}
/**
* 格式化数字(添加千位分隔符)
*/
export function formatNumber(num: number): string {
return num.toLocaleString('zh-CN');
}
/**
* 截断长文本
*/
export function truncateText(text: string, maxLength: number): string {
if (text.length <= maxLength) {
return text;
}
return text.slice(0, maxLength) + '...';
}