样式优化
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
export function generateUUID(): string {
|
||||
// 优先使用现代浏览器的 crypto.randomUUID
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
|
||||
// 降级方案:使用 crypto.getRandomValues 生成 UUIDv4
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
||||
// 设置版本为 4(UUIDv4)
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
// 设置变体为 RFC 4122
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
|
||||
const hex = Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
|
||||
// 最后降级:使用时间戳和随机数
|
||||
const timestamp = Date.now().toString(16).padStart(12, '0');
|
||||
const random = Math.random().toString(16).slice(2, 10).padStart(8, '0');
|
||||
return `${timestamp}-${random}-4xxx-yxxx-${Math.random().toString(16).slice(2, 12)}`.replace(/[xy]/g, (c) => {
|
||||
const r = Math.random() * 16 | 0;
|
||||
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user