41 lines
957 B
TypeScript
41 lines
957 B
TypeScript
/**
|
|
* MetonaToast Utils — 工具函数
|
|
* @module utils
|
|
* @version 0.5.0
|
|
*/
|
|
|
|
/**
|
|
* 生成唯一ID
|
|
*/
|
|
export const generateId = (): string => {
|
|
return 'met-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);
|
|
};
|
|
|
|
/**
|
|
* HTML转义
|
|
* @param s - 输入字符串
|
|
*/
|
|
export const escapeHTML = (s: string | null | undefined): string => {
|
|
if (typeof document === 'undefined') {
|
|
return String(s == null ? '' : s)
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/"/g, '"')
|
|
.replace(/'/g, ''');
|
|
}
|
|
|
|
const div = document.createElement('div');
|
|
div.textContent = String(s == null ? '' : s);
|
|
return div.innerHTML;
|
|
};
|
|
|
|
/**
|
|
* 检测暗色模式偏好
|
|
*/
|
|
export const prefersDark = (): boolean => {
|
|
return typeof window !== 'undefined' &&
|
|
typeof window.matchMedia === 'function' &&
|
|
window.matchMedia('(prefers-color-scheme: dark)').matches;
|
|
};
|