/* DevBox · 公共工具与注册表(无依赖,经典脚本,可直接 file:// 打开) */ (function () { 'use strict' const DB = {} window.DB = DB DB.groups = [ { id: 'image', name: '图片', desc: '格式、体积、取色' }, { id: 'encode', name: '编码', desc: 'Base64 / URL / 进制' }, { id: 'crypto', name: '加密', desc: '哈希、AES、JWT、随机' }, { id: 'text', name: '文本', desc: 'JSON / Diff / 正则 / 转换' }, { id: 'time', name: '时间', desc: '时间戳、日期、Cron' }, { id: 'web', name: 'Web 与系统', desc: '颜色、HTTP、权限、网络' }, { id: 'format', name: '格式', desc: 'XML / YAML / SQL / 查询串' }, { id: 'creator', name: '创作者', desc: '解析、转码、网盘直链' }, { id: 'random', name: '随机', desc: '抽签、抽奖、随机数' }, { id: 'device', name: '检测', desc: '键盘鼠标、屏幕、声音' }, { id: 'study', name: '学习', desc: '成语 / 诗词 / 口算 / 记忆' }, { id: 'office', name: '办公', desc: '文档模板、纪要、文案' }, { id: 'life', name: '生活', desc: '吃什么、尺码、保存时间' }, { id: 'fun', name: '娱乐', desc: '抽签、占卜、夸夸、随机' }, ] DB.tools = [] /** 注册一个工具 */ DB.tool = function (def) { DB.tools.push(def) } /* ---------- DOM ---------- */ DB.el = function (tag, attrs, ...kids) { const node = document.createElement(tag) if (attrs) { for (const [k, v] of Object.entries(attrs)) { if (v === null || v === undefined || v === false) continue if (k === 'class') node.className = v else if (k === 'html') node.innerHTML = v else if (k === 'text') node.textContent = v else if (k === 'style' && typeof v === 'object') Object.assign(node.style, v) else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v) else if (k === 'dataset') Object.assign(node.dataset, v) else node.setAttribute(k, v === true ? '' : v) } } for (const kid of kids.flat(9)) { if (kid === null || kid === undefined || kid === false) continue node.append(kid.nodeType ? kid : document.createTextNode(String(kid))) } return node } const el = DB.el DB.el = el DB.icon = (name, cls) => `` /** 带「复制」按钮的标题行 */ DB.panelTitle = function (text, right) { return el('div', { class: 'panel-title' }, el('span', { text }), el('span', { class: 'spacer' }), right || null) } /** 输出块:返回 { node, set(text|node), copy() } */ DB.output = function (opts = {}) { const pre = el('pre', { class: 'out' + (opts.flush ? ' flush' : '') }) const btn = el('button', { class: 'btn tiny', onclick: () => { const t = pre.dataset.raw ?? pre.textContent; if (!t) return toast('没有可复制的内容', true); copy(t) }, html: DB.icon('copy') + '复制' }) const bar = el('div', { class: 'row between', style: { marginBottom: '8px' } }, el('div', { class: 'row' }), btn) const wrap = el('div', {}, bar, pre) const api = { node: wrap, pre, bar, get text() { return pre.dataset.raw ?? pre.textContent }, set(v) { if (v && v.nodeType) { pre.textContent = ''; pre.append(v) } else { pre.dataset.raw = v == null ? '' : String(v); pre.textContent = pre.dataset.raw } }, html(html) { delete pre.dataset.raw; pre.innerHTML = html }, copy() { const t = api.text; if (!t) return toast('没有可复制的内容', true); copy(t) }, hide() { btn.hidden = true; return api }, } return api } /* ---------- 剪贴板 / 提示 / 下载 ---------- */ DB.copy = async function (text) { try { if (navigator.clipboard && window.isSecureContext) await navigator.clipboard.writeText(text) else { const ta = el('textarea', { style: { position: 'fixed', opacity: '0', top: '-1000px' } }) ta.value = text; document.body.append(ta); ta.select() document.execCommand('copy'); ta.remove() } DB.toast('已复制到剪贴板') return true } catch (e) { DB.toast('复制失败,请手动选择文本', true) return false } } const copy = DB.copy DB.toast = function (msg, bad) { const host = document.getElementById('toasts') const t = el('div', { class: 'toast' + (bad ? ' bad' : ''), html: DB.icon(bad ? 'close' : 'check') + '' }) t.querySelector('span').textContent = msg host.append(t) setTimeout(() => { t.style.transition = 'opacity .25s, transform .25s'; t.style.opacity = '0'; t.style.transform = 'translateY(6px)' }, bad ? 2600 : 1500) setTimeout(() => t.remove(), bad ? 2900 : 1800) } const toast = DB.toast DB.download = function (name, blob) { const url = URL.createObjectURL(blob) const a = el('a', { href: url, download: name }) document.body.append(a); a.click(); a.remove() setTimeout(() => URL.revokeObjectURL(url), 4000) } DB.downloadText = function (name, text, mime = 'text/plain') { DB.download(name, new Blob([text], { type: mime + ';charset=utf-8' })) } /* ---------- 格式化 ---------- */ DB.bytes = function (n) { if (!n && n !== 0) return '—' if (n < 1024) return n + ' B' const u = ['KB', 'MB', 'GB', 'TB'] let i = -1, v = n do { v /= 1024; i++ } while (v >= 1024 && i < u.length - 1) return v.toFixed(v >= 100 ? 0 : v >= 10 ? 1 : 2) + ' ' + u[i] } DB.hex = (n, pad = 2) => Number(n).toString(16).padStart(pad, '0') DB.pad2 = (n) => String(n).padStart(2, '0') DB.debounce = function (fn, ms = 200) { let t return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms) } } DB.onInput = function (input, fn, ms = 160) { const run = DB.debounce(fn, ms) input.addEventListener('input', run) input.addEventListener('change', fn) return input } DB.readFile = (file, how) => new Promise((res, rej) => { const fr = new FileReader() fr.onload = () => res(fr.result) fr.onerror = () => rej(fr.error) how === 'buffer' ? fr.readAsArrayBuffer(file) : how === 'dataurl' ? fr.readAsDataURL(file) : fr.readAsText(file) }) DB.loadImage = function (file) { return new Promise((res, rej) => { if (window.createImageBitmap) { createImageBitmap(file).then((bmp) => res({ bmp, w: bmp.width, h: bmp.height })).catch(() => fallback()) } else fallback() function fallback() { const img = new Image() img.onload = () => res({ img, w: img.naturalWidth, h: img.naturalHeight }) img.onerror = () => rej(new Error('这个文件不是浏览器能识别的图片')) img.src = URL.createObjectURL(file) } }) } DB.drawToCanvas = function (src, w, h) { const c = document.createElement('canvas') c.width = w; c.height = h const g = c.getContext('2d') g.imageSmoothingQuality = 'high' g.drawImage(src, 0, 0, w, h) return c } DB.canvasToBlob = (canvas, type, quality) => new Promise((res) => canvas.toBlob(res, type, quality)) DB.fmtNum = (n) => n.toLocaleString('zh-CN') DB.clip = (s, n = 80) => (s.length > n ? s.slice(0, n) + '…' : s) /* ---------- 杂项 ---------- */ DB.parseJSON = function (text) { const v = JSON.parse(text) return v } DB.jsonError = function (err, text) { const m = /position (\d+)/.exec(err.message) if (m) { const pos = Number(m[1]) const before = text.slice(0, pos) const line = before.split('\n').length const col = pos - before.lastIndexOf('\n') return `第 ${line} 行,第 ${col} 列:${err.message.replace(/\s*in JSON at position.*$/, '')}` } return err.message } DB.safe = function (fn, fallback) { try { return fn() } catch (e) { return typeof fallback === 'function' ? fallback(e) : fallback } } DB.fmtBytes = DB.bytes })()