export function createElement({ innerText, textContent, onclick, onchange, onkeydown, children = [], dataset, style, classList = [], ...attributes }, tagName = 'div') { const element = document.createElement(tagName) for (const key in attributes) element.setAttribute(key, attributes[key]) if (style) Object.assign(element.style, style) if (classList.length) element.classList.add(...classList) if (textContent) element.textContent = textContent if (innerText) element.innerText = innerText if (onkeydown) element.onkeydown = onkeydown if (onchange) element.onchange = onchange if (onclick) element.onclick = onclick if (dataset) Object.assign(element.dataset, dataset) if (children) children.forEach(child => element.appendChild(child)) return element } export function List(options) { return createElement(options, 'ul') } export function ListItem(options) { return createElement(options, 'li') } export function Span(options) { return createElement(options, 'span') } export function Button(options) { return createElement(options, 'button') } export function Input(options) { return createElement(options, 'input') } export function Avatar(options) { const element = createElement(options, 'img') element.onerror = () => element.src = '/favicon.ico' return element } // 弹出窗口, 高斯模糊背景, 进入离开动画过渡 export function Dialog(options) { const element = createElement({ tabIndex: 0, style: { position: 'fixed', top: 0, left: 0, zIndex: 1000, width: '100%', height: '100%', backdropFilter: 'blur(5px)', duration: '0.5s', transition: 'all 0.5s' }, onclick: async event => { await event.target.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 100 }).finished await event.target.remove() }, onkeydown: async event => { if (event.key !== 'Escape') return await event.target.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 100 }).finished await event.target.remove() }, children: [ createElement({ ...options, style: { position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', backgroundColor: '#fff', borderRadius: '150px', boxShadow: '0 0 1em #ccc', overflow: 'hidden', display: 'flex', justifyContent: 'center', ...options.style, } }) ] }) // 显示时自动聚焦 const observer = new MutationObserver(mutationsList => { for (const mutation of mutationsList) { if (mutation.type === 'childList' && mutation.addedNodes.length > 0) { element.focus() element.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 100 }).finished return observer.disconnect() } } }) observer.observe(document.body, { childList: true, subtree: true }) return element } // 深度代理, 用于监听数据的变化 export function useProxy(obj, callback) { return new Proxy(obj, { get(target, key) { if (typeof target[key] === 'object' && target[key] !== null) { return useProxy(target[key], callback) } return target[key] }, set(target, key, value) { target[key] = value callback(target, key, value) return true } }) }