Files

117 lines
5.4 KiB
JavaScript
Raw Permalink 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.
// Every supplied string is rendered as text, including names, errors and logs.
export function el(tag, attributes = {}, ...children) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(attributes)) {
if (value === undefined || value === null || value === false) continue;
if (key === 'class') node.className = value;
else if (key === 'text') node.textContent = String(value);
else if (key.startsWith('on') && typeof value === 'function') node.addEventListener(key.slice(2).toLowerCase(), value);
else if (['checked', 'disabled', 'hidden', 'value', 'multiple', 'required', 'open'].includes(key)) node[key] = value;
else node.setAttribute(key, value === true ? '' : String(value));
}
for (const child of children.flat(Infinity)) {
if (child !== null && child !== undefined && child !== false) node.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return node;
}
export const $ = (selector, root = document) => root.querySelector(selector);
export const $$ = (selector, root = document) => [...root.querySelectorAll(selector)];
export const clone = value => structuredClone(value);
export const pathKey = path => JSON.stringify(path);
const blockedKeys = new Set(['__proto__', 'prototype', 'constructor']);
export function getPath(object, path, fallback) {
let value = object;
for (const key of path || []) {
if (blockedKeys.has(String(key)) || value == null || !Object.hasOwn(value, key)) return fallback;
value = value[key];
}
return value === undefined ? fallback : value;
}
export function setPath(object, path, value) {
if (!Array.isArray(path) || !path.length || path.some(key => blockedKeys.has(String(key)))) throw new Error('配置字段路径无效');
let current = object;
path.slice(0, -1).forEach((key, index) => {
if (!current[key] || typeof current[key] !== 'object') current[key] = typeof path[index + 1] === 'number' ? [] : {};
current = current[key];
});
if (value === undefined) delete current[path.at(-1)];
else current[path.at(-1)] = clone(value);
}
export function textValue(value) {
if (value === null || value === undefined || value === '') return '—';
if (typeof value === 'boolean') return value ? '是' : '否';
if (Array.isArray(value)) return value.map(textValue).join(' / ');
if (typeof value === 'object') return Object.entries(value).map(([key, item]) => `${key}: ${textValue(item)}`).join(';');
return String(value);
}
export function number(value) {
if (value === null || value === undefined) return '—';
const numeric=Number(value);
if(!Number.isFinite(numeric))return textValue(value);
return numeric.toLocaleString('zh-CN',Number.isInteger(numeric)?{}:{maximumSignificantDigits:6});
}
export function chinaTime(value, {date=false} = {}) {
if(value===null || value===undefined || value==='')return '';
const parsed=typeof value==='number'?new Date(value<1e12?value*1000:value):new Date(value);
if(!Number.isFinite(parsed.getTime()))return String(value);
return new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',hour12:false,hour:'2-digit',minute:'2-digit',second:'2-digit',
...(date?{year:'numeric',month:'2-digit',day:'2-digit'}:{})}).format(parsed);
}
export function optionsList(options) {
if (!options) return [];
if (!Array.isArray(options)) return Object.entries(options).map(([value, label]) => ({value, label}));
return options.map(option => Array.isArray(option) ? {value: option[0], label: option[1]} : typeof option === 'object' ? {value: option.value ?? option.id ?? option.key, label: option.label ?? option.name ?? String(option.value ?? option.id), ...option} : {value: option, label: String(option)});
}
export function download(blob, filename) {
const url = URL.createObjectURL(blob);
const link = el('a', {href: url, download: filename});
document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
export function csvBlob(columns, rows) {
// Spreadsheet text must not become a formula when a nickname starts with '='.
const escape = value => {
let text = value == null ? '' : textValue(value);
if (/^[\s]*[=+@\-]/u.test(text) && !/^-?\d+(\.\d+)?$/u.test(text)) text = "'" + text;
return '"' + text.replaceAll('"', '""') + '"';
};
const lines = [columns.map(column => escape(column.label)).join(','), ...rows.map(row => columns.map(column => escape(row[column.key])).join(','))];
return new Blob(['\ufeff', lines.join('\r\n')], {type: 'text/csv;charset=utf-8'});
}
export function empty(message) {
return el('div', {class: 'empty-state'}, el('p', {text: message}));
}
export function detailsList(value, labels = {}) {
const list = el('dl', {class: 'detail-list'});
for (const [key, item] of Object.entries(value || {})) {
list.append(el('dt', {text: labels[key] || key}), el('dd', {text: textValue(item)}));
}
return list;
}
export function tabKeys(container, selector) {
container.addEventListener('keydown', event => {
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
const tabs = $$(selector, container).filter(tab => !tab.disabled);
const index = tabs.indexOf(document.activeElement);
if (index < 0) return;
const next = event.key === 'Home' ? 0 : event.key === 'End' ? tabs.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
event.preventDefault();
tabs[next]?.focus();
tabs[next]?.click();
});
}