diff --git a/README.md b/README.md
index 04cd5ba..3c08705 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# DevBox · 开发者工具箱
-一个开发者工具箱:30 个工具(图片转格式与加水印、哈希与 AES、JWT、时间戳、Cron、JSON、正则、Diff、颜色、CIDR、chmod、cURL 转代码……),外加**账号系统、积分计费和 CDK 兑换**,还有一个管理员后台。
+一个开发者工具箱:44 个工具(图片转格式与加水印、哈希与 AES、JWT、时间戳、Cron、JSON、正则、Diff、颜色、CIDR、chmod、cURL 转代码……),外加**账号系统、积分计费和 CDK 兑换**,还有一个管理员后台。
工具本身仍然在浏览器里算完,数据不出本机;只有「谁在用、还剩多少积分」记到服务端的 SQLite 里。零第三方依赖,一个 `node server.mjs` 就跑起来。
@@ -115,6 +115,21 @@ curl -fsSL http://110.42.217.133:3000/gitea/devbox/raw/branch/main/install.sh |
| 创作者 | 音频转格式 | 音频或视频链接 → MP3 / M4A / WAV / FLAC / OGG / AAC |
| 创作者 | 网盘直链 | 蓝奏云、阿里云盘、百度网盘分享链接取直链;token / Cookie 存在服务端,只自己可见 |
+| 格式 | JSON ↔ YAML | 双向转换,缩进与嵌套保留,YAML 支持注释 |
+| 格式 | XML ↔ JSON | 属性转 `@key`,重复节点合并成数组,文本进 `#text` |
+| 格式 | SQL 美化 | 关键字换行大写、按括号缩进,字符串内容原样保留 |
+| 格式 | JSON ↔ 查询串 | 对象与 `a=1&b=2` 互转,数组按键重复、嵌套压成 JSON 串 |
+| 编码 | Gzip 压缩 / CRC32 | 文本压成 Gzip(Base64 或 HEX),算 CRC32,也能解回来 |
+| 编码 | Cookie ↔ JSON | Cookie 串与 JSON 互转,Path/Domain/Expires/SameSite 一并解析 |
+| 编码 | 字符编码套件 | Unicode 转义、UTF-8 字节、HEX、全角半角、罗马数字、摩斯,六合一 |
+| 加密 | RSA 密钥与签名 | 本地生成 2048/3072 位 PEM 密钥对,私钥签名、公钥验签(SHA-256) |
+| 图片 | 图片压缩 | 调质量与最大宽重编码,显示前后体积与压缩率,可批量 |
+| 图片 | 九宫格切图 | 2×2 / 3×3 / 4×4 切图,逐个下载,发朋友圈用 |
+| 图片 | 图片 EXIF | 读机型、快门、光圈、ISO、拍摄时间等元数据 |
+| 文本 | 文本提取器 | 从聊天记录或源码里批量抓手机号 / 邮箱 / 链接 / 身份证 / IP / 卡号 |
+| 文本 | 人民币 / 日期大写 | 金额转大写、日期转汉字、十二时辰、生肖与星座 |
+| 时间 | 番茄钟 / 秒表 / 倒计时 | 25+5 自动切换、秒表分段、倒计时到点响铃 |
+
## 部署
DevBox 是纯静态页面,丢到任何静态托管都能用;想在自己的服务器上装成服务,用根目录的 `install.sh`:
@@ -223,6 +238,13 @@ DB.tool({
## 更新日志
+- 2026-11-20 新增 14 个工具(参照工具狗 toolbox 的常见项补的)
+ - 新分组「格式」:JSON ↔ YAML、XML ↔ JSON、SQL 美化、JSON ↔ 查询串
+ - 编码补齐 Gzip/CRC32、Cookie ↔ JSON、字符编码套件(Unicode/UTF-8/HEX/全角/罗马/摩斯)
+ - 加密补 RSA 密钥对与签名验签(WebCrypto 本地算)
+ - 图片补压缩、九宫格切图、EXIF 读取
+ - 文本补提取器(手机号/邮箱/链接/身份证/IP/卡号)与人民币日期大写
+ - 时间补番茄钟 / 秒表 / 倒计时
- 2026-11-20 新增「创作者」分组 5 个工具:视频解析、音乐解析、视频转格式、音频转格式、网盘直链
- 服务端新增 `/api/creator/*` 接口,解析用 yt-dlp、转码用 ffmpeg 边转边传,不落临时文件
- 网盘支持蓝奏云(直连)、阿里云盘(refresh_token)、百度网盘(Cookie);凭据按用户存 SQLite
diff --git a/css/style.css b/css/style.css
index 9bf9562..64834e2 100644
--- a/css/style.css
+++ b/css/style.css
@@ -711,3 +711,11 @@ html, body { overflow-x: hidden; }
.result-list .txt { flex: 1 1 200px; font-size: 12.5px; color: var(--muted, #8b93a1); word-break: break-all; }
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
@media (max-width: 640px) { .grid2 { grid-template-columns: 1fr; } .media-head { flex-direction: column; } .media-head .thumb { width: 100%; height: 150px; } }
+
+/* ---------- 番茄钟 / 秒表 / 九宫格 ---------- */
+.big-time { font: 600 34px/1.2 var(--mono); letter-spacing: .06em; color: var(--txt); margin: 10px 0 2px; }
+.big-time.run { color: var(--accent); }
+.media-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 10px; margin-top: 12px; }
+.media-cell { display: flex; flex-direction: column; gap: 6px; }
+.media-cell img { width: 100%; border-radius: 8px; display: block; background: var(--panel-2); }
+.media-cell .btn { width: 100%; justify-content: center; }
diff --git a/index.html b/index.html
index e4b398f..42fc272 100644
--- a/index.html
+++ b/index.html
@@ -162,6 +162,12 @@
+
+
+
+
+
+
diff --git a/js/tools-codec-extra.js b/js/tools-codec-extra.js
new file mode 100644
index 0000000..a2b63b4
--- /dev/null
+++ b/js/tools-codec-extra.js
@@ -0,0 +1,182 @@
+/* DevBox · 编码补齐:Gzip / CRC32、Cookie ↔ JSON、字符编码套件 */
+(function () {
+ 'use strict'
+ const { el, panelTitle, copy, toast, onInput, downloadText } = DB
+ const btn = (label, fn, cls = '') => el('button', { class: 'btn ' + cls, text: label, onclick: fn })
+ const pane = (title, right) => { const p = el('div', { class: 'panel' }); if (title) p.append(panelTitle(title, right)); return p }
+ const ta = (ph, rows) => el('textarea', { class: 'ta', placeholder: ph, rows: rows || 10, spellcheck: 'false' })
+
+ /* ---------------- Gzip + CRC32 ---------------- */
+ const enc = (t) => new TextEncoder().encode(t)
+ const dec = (b) => new TextDecoder().decode(b)
+ const b64 = (bytes) => btoa(String.fromCharCode(...bytes))
+ const unb64 = (s) => Uint8Array.from(atob(s.replace(/\s/g, '')), (c) => c.charCodeAt(0))
+ const hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
+
+ const CRC_TABLE = (() => {
+ const t = new Uint32Array(256)
+ for (let i = 0; i < 256; i++) {
+ let c = i
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
+ t[i] = c >>> 0
+ }
+ return t
+ })()
+ function crc32(bytes) {
+ let c = 0xffffffff
+ for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8)
+ return ((c ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0')
+ }
+ async function gzip(bytes) {
+ const cs = new CompressionStream('gzip')
+ const w = cs.writable.getWriter(); w.write(bytes); w.close()
+ return new Uint8Array(await new Response(cs.readable).arrayBuffer())
+ }
+ async function gunzip(bytes) {
+ const ds = new DecompressionStream('gzip')
+ const w = ds.writable.getWriter(); w.write(bytes); w.close()
+ return new Uint8Array(await new Response(ds.readable).arrayBuffer())
+ }
+
+ DB.tool({
+ id: 'gzip-crc',
+ name: 'Gzip 压缩 / CRC32',
+ group: 'encode',
+ icon: 'archive',
+ desc: '文本压成 Gzip(Base64 / HEX 两种输出),顺带算 CRC32;也能解回来',
+ keywords: ['gzip', 'zlib', 'crc32', '压缩', '解压', '校验'],
+ mount(root) {
+ const src = ta('要压缩的文本,或者粘 Base64 / HEX 来解压…')
+ const out = el('pre', { class: 'out' })
+ const stat = el('div', { class: 'hint' })
+ const pack = async (fmt) => {
+ try {
+ const raw = enc(src.value)
+ const gz = await gzip(raw)
+ out.textContent = (fmt === 'hex' ? hex(gz) : b64(gz)) + '\n\nCRC32: ' + crc32(raw) + '\n原始: ' + raw.length + ' B → 压缩: ' + gz.length + ' B (' + (gz.length / Math.max(1, raw.length) * 100).toFixed(1) + '%)'
+ stat.textContent = '压缩完成'; stat.className = 'hint good'
+ } catch (e) { stat.textContent = '失败:' + e.message; stat.className = 'hint bad' }
+ }
+ const unpack = async () => {
+ try {
+ const t = src.value.trim()
+ const bytes = /^[0-9a-fA-F\s]+$/.test(t) && t.replace(/\s/g, '').length % 2 === 0 ? Uint8Array.from(t.replace(/\s/g, '').match(/../g), (h) => parseInt(h, 16)) : unb64(t)
+ const raw = await gunzip(bytes)
+ out.textContent = dec(raw)
+ stat.textContent = '解压完成,' + raw.length + ' B'; stat.className = 'hint good'
+ } catch (e) { stat.textContent = '解压失败:' + e.message; stat.className = 'hint bad' }
+ }
+ root.append(
+ pane('压缩 / 解压', el('div', { class: 'row' }, btn('Gzip → Base64', () => pack('b64')), btn('Gzip → HEX', () => pack('hex')), btn('解压', unpack), btn('只看 CRC32', () => { out.textContent = crc32(enc(src.value)) }, 'ghost'))),
+ src, stat, out
+ )
+ },
+ })
+
+ /* ---------------- Cookie ↔ JSON ---------------- */
+ DB.tool({
+ id: 'cookie-json',
+ name: 'Cookie ↔ JSON',
+ group: 'encode',
+ icon: 'cookie',
+ desc: 'Cookie 串与 JSON 互转,带过期时间、路径、SameSite 也能解析',
+ keywords: ['cookie', 'json', 'header', '会话', '转换'],
+ mount(root) {
+ const src = ta('session=abc123; theme=dark; lang=zh-CN', 8)
+ const out = el('pre', { class: 'out' })
+ const toJson = () => {
+ const list = []
+ let cur = null
+ for (const part of src.value.split(';')) {
+ const seg = part.trim()
+ if (!seg) continue
+ const i = seg.indexOf('=')
+ if (i < 0) continue
+ const k = seg.slice(0, i).trim(), v = seg.slice(i + 1).trim()
+ if (/^(path|domain|expires|max-age|samesite|secure|httponly)$/i.test(k)) {
+ if (cur) cur[k.toLowerCase()] = v || true
+ continue
+ }
+ cur = { name: k, value: decodeURIComponent(v) }
+ list.push(cur)
+ }
+ out.textContent = JSON.stringify(list, null, 2)
+ }
+ const toCookie = () => {
+ try {
+ const v = JSON.parse(src.value)
+ const arr = Array.isArray(v) ? v : Object.entries(v).map(([name, value]) => ({ name, value }))
+ out.textContent = arr.map((c) => `${c.name}=${encodeURIComponent(c.value ?? '')}${c.path ? '; Path=' + c.path : ''}${c.domain ? '; Domain=' + c.domain : ''}${c.expires ? '; Expires=' + c.expires : ''}${c.secure ? '; Secure' : ''}${c.httpOnly ? '; HttpOnly' : ''}${c.sameSite ? '; SameSite=' + c.sameSite : ''}`).join('; ')
+ } catch (e) { out.textContent = 'JSON 解析失败:' + e.message }
+ }
+ root.append(pane('转换', el('div', { class: 'row' }, btn('Cookie → JSON', toJson), btn('JSON → Cookie', toCookie), btn('复制当前页面 Cookie', () => { src.value = document.cookie || '(当前域名没有 Cookie)'; toJson() }, 'ghost'))), src, out)
+ toJson()
+ },
+ })
+
+ /* ---------------- 字符编码套件 ---------------- */
+ const ROMAN = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']]
+ const toRoman = (n) => { let r = ''; for (const [v, s] of ROMAN) while (n >= v) { r += s; n -= v } return r }
+ const fromRoman = (s) => { let i = 0, n = 0; const map = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }; const u = s.toUpperCase().replace(/[^IVXLCDM]/g, ''); while (i < u.length) { const a = map[u[i]], b = map[u[i + 1]]; if (b && a < b) { n += b - a; i += 2 } else { n += a; i++ } } return n }
+ const MORSE = { a: '.-', b: '-...', c: '-.-.', d: '-..', e: '.', f: '..-.', g: '--.', h: '....', i: '..', j: '.---', k: '-.-', l: '.-..', m: '--', n: '-.', o: '---', p: '.--.', q: '--.-', r: '.-.', s: '...', t: '-', u: '..-', v: '...-', w: '.--', x: '-..-', y: '-.--', z: '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '.': '.-.-.-', ',': '--..--', '?': '..--..', '!': '-.-.--', '/': '-..-.', '-': '-....-', '(': '-.--.', ')': '-.--.-', '@': '.--.-.' }
+ const MORSE_REV = Object.fromEntries(Object.entries(MORSE).map(([k, v]) => [v, k]))
+
+ DB.tool({
+ id: 'char-codec',
+ name: '字符编码套件',
+ group: 'encode',
+ icon: 'type',
+ desc: 'Unicode 转义、UTF-8 字节、HEX、全角半角、罗马数字、摩斯密码,六种一次装齐',
+ keywords: ['unicode', 'utf8', 'hex', 'fullwidth', 'roman', 'morse', '摩斯', '罗马', '全角'],
+ mount(root) {
+ const mode = el('select', { class: 'input' }, ...[
+ ['unicode', 'Unicode 转义'], ['utf8', 'UTF-8 字节'], ['hex', 'HEX ↔ 文本'], ['width', '全角 ↔ 半角'], ['roman', '阿拉伯 ↔ 罗马数字'], ['morse', '摩斯密码'],
+ ].map(([v, t]) => el('option', { value: v, text: t })))
+ const src = ta('输入文本…', 8)
+ const out = el('pre', { class: 'out' })
+ const go = (reverse) => {
+ const v = src.value
+ try {
+ let r = ''
+ switch (mode.value) {
+ case 'unicode':
+ r = reverse ? v.replace(/\\u\{?([0-9a-fA-F]{2,6})\}?/g, (_, h) => String.fromCodePoint(parseInt(h, 16)))
+ : Array.from(v).map((c) => (c.codePointAt(0) > 0xffff ? '\\u{' + c.codePointAt(0).toString(16).toUpperCase() + '}' : '\\u' + c.codePointAt(0).toString(16).toUpperCase().padStart(4, '0'))).join('')
+ break
+ case 'utf8':
+ r = reverse ? dec(Uint8Array.from(v.trim().split(/[\s,]+/).map((x) => parseInt(x, 16))))
+ : Array.from(enc(v), (b) => b.toString(16).toUpperCase().padStart(2, '0')).join(' ')
+ break
+ case 'hex':
+ r = reverse ? Array.from(v.trim().match(/.{1,2}/g) || [], (h) => parseInt(h, 16)).map((b) => String.fromCharCode(b)).join('')
+ : Array.from(enc(v), (b) => b.toString(16).padStart(2, '0')).join('')
+ break
+ case 'width':
+ r = Array.from(v, (c) => {
+ const code = c.charCodeAt(0)
+ if (reverse && code >= 0xff01 && code <= 0xff5e) return String.fromCharCode(code - 0xfee0)
+ if (reverse && code === 0x3000) return ' '
+ if (!reverse && code === 0x20) return ' '
+ if (!reverse && code >= 0x21 && code <= 0x7e) return String.fromCharCode(code + 0xfee0)
+ return c
+ }).join('')
+ break
+ case 'roman':
+ r = reverse ? String(fromRoman(v)) : toRoman(Number(v.trim()) || 0)
+ break
+ case 'morse':
+ r = reverse ? v.trim().split(/\s*\/\s*|\s{2,}/).map((w) => w.trim().split(/\s+/).map((m) => MORSE_REV[m] || '').join('')).join(' ')
+ : v.toLowerCase().split('').map((c) => c === ' ' ? '/' : (MORSE[c] || c)).join(' ')
+ break
+ }
+ out.textContent = r
+ } catch (e) { out.textContent = '转换失败:' + e.message }
+ }
+ root.append(
+ pane('模式', el('div', { class: 'row' }, mode, btn('→ 编码', () => go(false)), btn('← 解码', () => go(true)))),
+ src, out
+ )
+ onInput(src, () => go(false), 300)
+ },
+ })
+})()
diff --git a/js/tools-crypto-extra.js b/js/tools-crypto-extra.js
new file mode 100644
index 0000000..e033972
--- /dev/null
+++ b/js/tools-crypto-extra.js
@@ -0,0 +1,70 @@
+/* DevBox · 加密补齐:RSA 密钥对 / 签名 / 验签(WebCrypto,全程本地) */
+(function () {
+ 'use strict'
+ const { el, panelTitle, copy, toast } = DB
+ const btn = (label, fn, cls = '') => el('button', { class: 'btn ' + cls, text: label, onclick: fn })
+ const pane = (title, right) => { const p = el('div', { class: 'panel' }); if (title) p.append(panelTitle(title, right)); return p }
+ const ta = (ph, rows) => el('textarea', { class: 'ta', placeholder: ph, rows: rows || 8, spellcheck: 'false' })
+
+ const pem = (label, bytes) => {
+ const b = btoa(String.fromCharCode(...new Uint8Array(bytes)))
+ const lines = b.match(/.{1,64}/g).join('\n')
+ return `-----BEGIN ${label}-----\n${lines}\n-----END ${label}-----`
+ }
+ const derFromB64 = (b64) => Uint8Array.from(atob(b64.replace(/\s/g, '')), (c) => c.charCodeAt(0))
+ const pemBody = (p) => p.replace(/-----[^-]+-----/g, '').replace(/\s/g, '')
+
+ DB.tool({
+ id: 'rsa',
+ name: 'RSA 密钥与签名',
+ group: 'crypto',
+ icon: 'key',
+ desc: '本地生成 2048/3072 位密钥对(PEM),用私钥签名、公钥验签,SHA-256',
+ keywords: ['rsa', 'sign', 'verify', 'pem', '签名', '验签', '密钥'],
+ mount(root) {
+ const bits = el('select', { class: 'input' }, el('option', { value: '2048', text: '2048 位' }), el('option', { value: '3072', text: '3072 位' }), el('option', { value: '4096', text: '4096 位' }))
+ const priv = ta('-----BEGIN PRIVATE KEY-----\n…')
+ const pub = ta('-----BEGIN PUBLIC KEY-----\n…')
+ const data = ta('要签名的内容', 5)
+ const out = el('pre', { class: 'out' })
+ const stat = el('div', { class: 'hint' })
+
+ const gen = async () => {
+ stat.textContent = '生成中…'; stat.className = 'hint'
+ try {
+ const kp = await crypto.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: Number(bits.value), publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, ['sign', 'verify'])
+ priv.value = pem('PRIVATE KEY', await crypto.subtle.exportKey('pkcs8', kp.privateKey))
+ pub.value = pem('PUBLIC KEY', await crypto.subtle.exportKey('spki', kp.publicKey))
+ stat.textContent = '已生成 ' + bits.value + ' 位密钥对'; stat.className = 'hint good'
+ } catch (e) { stat.textContent = '生成失败:' + e.message; stat.className = 'hint bad' }
+ }
+ const importKey = (which) => {
+ const src = which === 'priv' ? priv.value : pub.value
+ return crypto.subtle.importKey('pkcs8', derFromB64(pemBody(src)), { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, [which === 'priv' ? 'sign' : 'verify'])
+ .catch(() => crypto.subtle.importKey('spki', derFromB64(pemBody(src)), { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, [which === 'priv' ? 'sign' : 'verify']))
+ }
+ const sign = async () => {
+ try {
+ const key = await importKey('priv')
+ const sig = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, new TextEncoder().encode(data.value))
+ out.textContent = btoa(String.fromCharCode(...new Uint8Array(sig)))
+ stat.textContent = '签名完成(Base64)'; stat.className = 'hint good'
+ } catch (e) { stat.textContent = '签名失败:' + e.message; stat.className = 'hint bad' }
+ }
+ const verify = async () => {
+ try {
+ const key = await importKey('pub')
+ const sig = Uint8Array.from(atob(out.textContent.trim()), (c) => c.charCodeAt(0))
+ const ok = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, sig, new TextEncoder().encode(data.value))
+ stat.textContent = ok ? '验签通过 ✓' : '验签不通过 ✗'; stat.className = 'hint ' + (ok ? 'good' : 'bad')
+ } catch (e) { stat.textContent = '验签失败:' + e.message; stat.className = 'hint bad' }
+ }
+ root.append(
+ pane('密钥', el('div', { class: 'row' }, bits, btn('生成密钥对', gen), btn('复制公钥', () => copy(pub.value), 'ghost'), btn('复制私钥', () => copy(priv.value), 'ghost'))),
+ el('div', { class: 'grid2' }, priv, pub),
+ pane('签名 / 验签', el('div', { class: 'row' }, btn('用私钥签名', sign), btn('用公钥验签', verify))),
+ data, stat, out
+ )
+ },
+ })
+})()
diff --git a/js/tools-format.js b/js/tools-format.js
new file mode 100644
index 0000000..93f44f4
--- /dev/null
+++ b/js/tools-format.js
@@ -0,0 +1,291 @@
+/* DevBox · 格式:JSON ↔ YAML / XML ↔ JSON / SQL 美化 / JSON ↔ 查询串 */
+(function () {
+ 'use strict'
+ const { el, panelTitle, copy, toast, onInput } = DB
+ const btn = (label, fn, cls = '') => el('button', { class: 'btn ' + cls, text: label, onclick: fn })
+ const pane = (title, right) => { const p = el('div', { class: 'panel' }); if (title) p.append(panelTitle(title, right)); return p }
+ const ta = (ph, rows) => el('textarea', { class: 'ta', placeholder: ph, rows: rows || 12, spellcheck: 'false' })
+
+ /* ---------------- YAML ---------------- */
+ const isScalar = (v) => v === null || ['string', 'number', 'boolean'].includes(typeof v)
+ const yScalar = (v) => {
+ if (v === null) return 'null'
+ if (typeof v === 'boolean' || typeof v === 'number') return String(v)
+ const s = String(v)
+ if (s === '' || /^[\s]|[\s]$|[:#\-?*&!|>'"%@`{}[\],]/.test(s) || /^(true|false|null|~|[-+]?\d)/.test(s)) return JSON.stringify(s)
+ return s
+ }
+ function toYaml(v, ind = 0) {
+ const pad = ' '.repeat(ind)
+ if (Array.isArray(v)) {
+ if (!v.length) return pad + '[]'
+ return v.map((it) => {
+ if (isScalar(it)) return pad + '- ' + yScalar(it)
+ const body = toYaml(it, ind + 1)
+ return pad + '- ' + body.trimStart()
+ }).join('\n')
+ }
+ if (v && typeof v === 'object') {
+ const keys = Object.keys(v)
+ if (!keys.length) return pad + '{}'
+ return keys.map((k) => {
+ const val = v[k]
+ if (isScalar(val)) return pad + yScalar(k) + ': ' + yScalar(val)
+ const body = toYaml(val, ind + 1)
+ const head = pad + yScalar(k) + ':'
+ return Array.isArray(val) ? head + '\n' + body : head + '\n' + body
+ }).join('\n')
+ }
+ return pad + yScalar(v)
+ }
+ function parseScalar(s) {
+ const t = s.trim()
+ if (t === '' || t === '~' || t === 'null') return null
+ if (t === 'true') return true
+ if (t === 'false') return false
+ if (/^[-+]?\d+$/.test(t)) return Number(t)
+ if (/^[-+]?\d*\.\d+$/.test(t)) return Number(t)
+ if (/^["'].*["']$/.test(t)) return t.slice(1, -1)
+ if (t === '[]') return []
+ if (t === '{}') return {}
+ return t
+ }
+ function parseYaml(text) {
+ const lines = text.replace(/\r/g, '').split('\n')
+ .map((l) => l.replace(/\t/g, ' '))
+ .filter((l) => l.trim() && !/^\s*#/.test(l))
+ .map((l) => ({ ind: l.length - l.trimStart().length, s: l.trim() }))
+ let i = 0
+ function block(ind) {
+ if (i >= lines.length) return null
+ if (lines[i].s.startsWith('- ')) {
+ const arr = []
+ while (i < lines.length && lines[i].ind === ind && lines[i].s.startsWith('- ')) {
+ const rest = lines[i].s.slice(2).trim()
+ i++
+ if (!rest) arr.push(block(ind + 2))
+ else if (/^[^:]+:(\s|$)/.test(rest) && !/^["'].*["']:/.test(rest)) {
+ const obj = {}
+ const m = /^([^:]+):\s*(.*)$/.exec(rest)
+ obj[parseScalar(m[1])] = m[2] ? parseScalar(m[2]) : (i < lines.length && lines[i].ind > ind ? block(lines[i].ind) : null)
+ while (i < lines.length && lines[i].ind > ind) {
+ const sub = lines[i]
+ if (sub.s.startsWith('- ')) break
+ const mm = /^([^:]+):\s*(.*)$/.exec(sub.s)
+ if (!mm) { i++; continue }
+ i++
+ obj[parseScalar(mm[1])] = mm[2] ? parseScalar(mm[2]) : (i < lines.length && lines[i].ind > sub.ind ? block(lines[i].ind) : null)
+ }
+ arr.push(obj)
+ } else arr.push(parseScalar(rest))
+ }
+ return arr
+ }
+ const obj = {}
+ while (i < lines.length && lines[i].ind === ind && !lines[i].s.startsWith('- ')) {
+ const m = /^([^:]+):\s*(.*)$/.exec(lines[i].s)
+ i++
+ if (!m) continue
+ const key = parseScalar(m[1])
+ const rest = m[2]
+ if (rest) obj[key] = parseScalar(rest)
+ else obj[key] = i < lines.length && lines[i].ind > ind ? block(lines[i].ind) : null
+ }
+ return obj
+ }
+ return block(lines.length ? lines[0].ind : 0)
+ }
+
+ DB.tool({
+ id: 'json-yaml',
+ name: 'JSON ↔ YAML',
+ group: 'format',
+ icon: 'braces',
+ desc: '双向转换,缩进与嵌套都保留;YAML 支持注释与列表',
+ keywords: ['json', 'yaml', 'yml', 'convert', '转换', '配置'],
+ mount(root) {
+ const src = ta('粘贴 JSON 或 YAML…')
+ const out = el('pre', { class: 'out' })
+ const stat = el('div', { class: 'hint' })
+ const run = (dir) => {
+ try {
+ if (!src.value.trim()) { out.textContent = ''; stat.textContent = ''; return }
+ if (dir === 'toYaml') {
+ const v = JSON.parse(src.value)
+ out.textContent = toYaml(v)
+ stat.textContent = 'JSON → YAML 成功'
+ } else {
+ const v = parseYaml(src.value)
+ out.textContent = JSON.stringify(v, null, 2)
+ stat.textContent = 'YAML → JSON 成功'
+ }
+ stat.className = 'hint good'
+ } catch (e) {
+ out.textContent = ''
+ stat.textContent = '解析失败:' + e.message
+ stat.className = 'hint bad'
+ }
+ }
+ root.append(
+ pane('输入', el('div', { class: 'row' }, btn('转 YAML', () => run('toYaml')), btn('转 JSON', () => run('toJson')), btn('示例', () => { src.value = '{\n "app": "devbox",\n "tools": 30,\n "list": [1, 2, 3],\n "db": { "host": "127.0.0.1", "port": 5432 }\n}'; run('toYaml') }, 'ghost'))),
+ src,
+ stat,
+ out
+ )
+ onInput(src, () => run(src.value.trim().startsWith('{') || src.value.trim().startsWith('[') ? 'toYaml' : 'toJson'), 260)
+ },
+ })
+
+ /* ---------------- XML ↔ JSON ---------------- */
+ function xmlToObj(node) {
+ const obj = {}
+ for (const a of node.attributes || []) obj['@' + a.name] = a.value
+ const kids = Array.from(node.children || [])
+ const text = Array.from(node.childNodes || []).filter((n) => n.nodeType === 3).map((n) => n.nodeValue.trim()).join('').trim()
+ if (!kids.length) {
+ if (Object.keys(obj).length) { if (text) obj['#text'] = text; return obj }
+ return text
+ }
+ for (const k of kids) {
+ const v = xmlToObj(k)
+ const name = k.nodeName
+ if (obj[name] === undefined) obj[name] = v
+ else if (Array.isArray(obj[name])) obj[name].push(v)
+ else obj[name] = [obj[name], v]
+ }
+ if (text) obj['#text'] = text
+ return obj
+ }
+ function objToXml(v, name, ind = 0) {
+ const pad = ' '.repeat(ind)
+ if (Array.isArray(v)) return v.map((it) => objToXml(it, name, ind)).join('\n')
+ if (v === null || v === undefined) return `${pad}<${name}/>`
+ if (typeof v !== 'object') return `${pad}<${name}>${String(v).replace(/[<>&]/g, (c) => ({ '<': '<', '>': '>', '&': '&' }[c]))}${name}>`
+ const attrs = Object.entries(v).filter(([k]) => k.startsWith('@')).map(([k, val]) => ` ${k.slice(1)}="${String(val).replace(/"/g, '"')}"`).join('')
+ const kids = Object.entries(v).filter(([k]) => !k.startsWith('@') && k !== '#text')
+ const text = v['#text']
+ if (!kids.length) return `${pad}<${name}${attrs}>${text ? String(text).replace(/[<>&]/g, (c) => ({ '<': '<', '>': '>', '&': '&' }[c])) : ''}${name}>`
+ const inner = kids.map(([k, val]) => objToXml(val, k, ind + 1)).join('\n')
+ return `${pad}<${name}${attrs}>\n${inner}\n${pad}${name}>`
+ }
+
+ DB.tool({
+ id: 'xml-json',
+ name: 'XML ↔ JSON',
+ group: 'format',
+ icon: 'code',
+ desc: '属性转 @key,重复节点自动变数组,文本进 #text',
+ keywords: ['xml', 'json', 'soap', 'convert', '转换'],
+ mount(root) {
+ const src = ta('- hello
', 10)
+ const out = el('pre', { class: 'out' })
+ const stat = el('div', { class: 'hint' })
+ const toJson = () => {
+ try {
+ const doc = new DOMParser().parseFromString(src.value, 'application/xml')
+ if (doc.querySelector('parsererror')) throw new Error(doc.querySelector('parsererror').textContent.split('\n')[0])
+ const r = doc.documentElement
+ out.textContent = JSON.stringify({ [r.nodeName]: xmlToObj(r) }, null, 2)
+ stat.textContent = 'XML → JSON 成功'; stat.className = 'hint good'
+ } catch (e) { out.textContent = ''; stat.textContent = 'XML 解析失败:' + e.message; stat.className = 'hint bad' }
+ }
+ const toXml = () => {
+ try {
+ const v = JSON.parse(src.value)
+ const keys = Object.keys(v)
+ out.textContent = keys.map((k) => objToXml(v[k], k, 0)).join('\n')
+ stat.textContent = 'JSON → XML 成功'; stat.className = 'hint good'
+ } catch (e) { out.textContent = ''; stat.textContent = 'JSON 解析失败:' + e.message; stat.className = 'hint bad' }
+ }
+ root.append(
+ pane('输入', el('div', { class: 'row' }, btn('XML → JSON', toJson), btn('JSON → XML', toXml))),
+ src, stat, out
+ )
+ },
+ })
+
+ /* ---------------- SQL 美化 ---------------- */
+ const SQL_KW = ['select', 'from', 'where', 'and', 'or', 'group by', 'order by', 'having', 'limit', 'offset', 'insert into', 'values', 'update', 'set', 'delete from', 'join', 'left join', 'right join', 'inner join', 'outer join', 'on', 'union all', 'union', 'as', 'case', 'when', 'then', 'else', 'end', 'with', 'distinct', 'create table', 'alter table', 'drop table', 'primary key', 'foreign key', 'not null', 'default']
+ function formatSql(sql, upper) {
+ let s = sql.replace(/\s+/g, ' ').trim()
+ // 保护字符串与反引号内的内容
+ const holders = []
+ s = s.replace(/'(?:[^']|'')*'|`[^`]*`|"[^"]*"/g, (m) => { holders.push(m); return `\u0000${holders.length - 1}\u0000` })
+ s = s.replace(/\b(select|from|where|group by|order by|having|limit|offset|insert into|values|update|set|delete from|left join|right join|inner join|outer join|join|on|union all|union|with|create table|alter table|drop table)\b/gi,
+ (m) => '\n' + (upper ? m.toUpperCase() : m.toLowerCase()))
+ s = s.replace(/\b(and|or)\b/gi, (m) => '\n ' + (upper ? m.toUpperCase() : m.toLowerCase()))
+ s = s.replace(/,\s*/g, ',\n ')
+ s = s.split('\n').map((l) => l.trim()).filter(Boolean)
+ let depth = 0
+ s = s.map((l) => {
+ if (/^\)/.test(l)) depth = Math.max(0, depth - 1)
+ const line = ' '.repeat(depth) + l
+ const opens = (l.match(/\(/g) || []).length, closes = (l.match(/\)/g) || []).length
+ depth = Math.max(0, depth + opens - closes)
+ return line
+ }).join('\n')
+ return s.replace(/\u0000(\d+)\u0000/g, (_, i) => holders[Number(i)])
+ }
+
+ DB.tool({
+ id: 'sql-format',
+ name: 'SQL 美化',
+ group: 'format',
+ icon: 'database',
+ desc: '关键字换行大写、按括号缩进;字符串内容不会被改动',
+ keywords: ['sql', 'format', 'mysql', '美化', '格式化'],
+ mount(root) {
+ const src = ta('select a,b from t where a=1 and b in (select c from d) order by a desc', 10)
+ const out = el('pre', { class: 'out' })
+ const upper = el('input', { type: 'checkbox', checked: true })
+ const run = () => { try { out.textContent = formatSql(src.value, upper.checked) } catch (e) { out.textContent = '失败:' + e.message } }
+ root.append(
+ pane('输入', el('div', { class: 'row' }, el('label', { class: 'row', style: { gap: '6px' } }, upper, el('span', { text: '关键字大写' })), btn('美化', run), btn('压缩成一行', () => { out.textContent = src.value.replace(/\s+/g, ' ').trim() }, 'ghost'))),
+ src, out
+ )
+ onInput(src, run, 240)
+ run()
+ },
+ })
+
+ /* ---------------- JSON ↔ 查询串 ---------------- */
+ DB.tool({
+ id: 'json-get',
+ name: 'JSON ↔ 查询串',
+ group: 'format',
+ icon: 'link',
+ desc: '对象与 a=1&b=2 互转,嵌套对象压成 JSON 字符串,数组按重复键',
+ keywords: ['json', 'query', 'get', 'url', 'params', '参数'],
+ mount(root) {
+ const src = ta('{"page":1,"size":20,"tags":["a","b"]}', 8)
+ const out = el('pre', { class: 'out' })
+ const toQuery = () => {
+ try {
+ const v = JSON.parse(src.value)
+ const parts = []
+ for (const [k, val] of Object.entries(v)) {
+ if (Array.isArray(val)) val.forEach((it) => parts.push(encodeURIComponent(k) + '=' + encodeURIComponent(typeof it === 'object' ? JSON.stringify(it) : it)))
+ else parts.push(encodeURIComponent(k) + '=' + encodeURIComponent(typeof val === 'object' && val !== null ? JSON.stringify(val) : val))
+ }
+ out.textContent = parts.join('&')
+ } catch (e) { out.textContent = 'JSON 解析失败:' + e.message }
+ }
+ const toJson = () => {
+ try {
+ const params = new URLSearchParams(src.value.trim().replace(/^\?/, ''))
+ const obj = {}
+ for (const [k, val] of params) {
+ if (obj[k] === undefined) obj[k] = val
+ else if (Array.isArray(obj[k])) obj[k].push(val)
+ else obj[k] = [obj[k], val]
+ }
+ out.textContent = JSON.stringify(obj, null, 2)
+ } catch (e) { out.textContent = '查询串解析失败:' + e.message }
+ }
+ root.append(
+ pane('输入', el('div', { class: 'row' }, btn('转查询串', toQuery), btn('转 JSON', toJson))),
+ src, out
+ )
+ },
+ })
+})()
diff --git a/js/tools-image-extra.js b/js/tools-image-extra.js
new file mode 100644
index 0000000..ac06731
--- /dev/null
+++ b/js/tools-image-extra.js
@@ -0,0 +1,163 @@
+/* DevBox · 图片补齐:压缩 / 九宫格切图 / EXIF */
+(function () {
+ 'use strict'
+ const { el, panelTitle, copy, toast, download, loadImage, drawToCanvas, canvasToBlob, bytes, readFile } = DB
+ const btn = (label, fn, cls = '') => el('button', { class: 'btn ' + cls, text: label, onclick: fn })
+ const pane = (title, right) => { const p = el('div', { class: 'panel' }); if (title) p.append(panelTitle(title, right)); return p }
+ const picker = (accept, onFile) => {
+ const input = el('input', { type: 'file', accept, style: { display: 'none' } })
+ input.addEventListener('change', () => { const f = input.files[0]; if (f) onFile(f) })
+ const zone = el('label', { class: 'drop' }, input, el('b', { text: '点这里选图,或把图片拖进来' }), el('span', { text: accept || 'image/*' }))
+ zone.addEventListener('dragover', (e) => { e.preventDefault(); zone.classList.add('over') })
+ zone.addEventListener('dragleave', () => zone.classList.remove('over'))
+ zone.addEventListener('drop', (e) => { e.preventDefault(); zone.classList.remove('over'); const f = e.dataTransfer.files[0]; if (f) onFile(f) })
+ return { node: zone, input }
+ }
+
+ /* ---------- 图片压缩 ---------- */
+ DB.tool({
+ id: 'img-compress',
+ name: '图片压缩',
+ group: 'image',
+ icon: 'minimize',
+ desc: '按质量与宽度重编码,显示前后体积与压缩率,可批量',
+ keywords: ['compress', 'quality', 'webp', 'jpeg', '压缩', '体积'],
+ mount(root) {
+ const files = []
+ const quality = el('input', { type: 'range', min: 30, max: 100, value: 80 })
+ const qLabel = el('b', { text: '80' })
+ const maxW = el('input', { type: 'number', value: 1920, min: 100, step: 100 })
+ const fmt = el('select', { class: 'input' }, ...['image/jpeg', 'image/webp', 'image/png'].map((t) => el('option', { value: t, text: t })))
+ const list = el('div', { class: 'result-list' })
+ const total = el('div', { class: 'hint' })
+ quality.addEventListener('input', () => { qLabel.textContent = quality.value })
+ const p = picker('image/*', async (f) => {
+ files.push(f)
+ list.textContent = ''
+ let before = 0, after = 0
+ for (const file of files) {
+ try {
+ const { bmp, img, w, h } = await loadImage(file)
+ const scale = Math.min(1, Number(maxW.value) / w)
+ const cw = Math.round(w * scale), ch = Math.round(h * scale)
+ const canvas = drawToCanvas(bmp || img, cw, ch)
+ const blob = await canvasToBlob(canvas, fmt.value, Number(quality.value) / 100)
+ before += file.size; after += blob.size
+ const row = el('div', { class: 'row between' },
+ el('div', {}, el('div', { class: 'txt', text: file.name }), el('span', { class: 'hint', text: `${w}×${h} → ${cw}×${ch} · ${bytes(file.size)} → ${bytes(blob.size)}` })),
+ el('div', { class: 'row' }, el('span', { class: 'tag', text: '-' + Math.max(0, Math.round((1 - blob.size / file.size) * 100)) + '%' }),
+ btn('下载', () => download(file.name.replace(/\.[^.]+$/, '') + '_min' + (fmt.value === 'image/png' ? '.png' : fmt.value === 'image/webp' ? '.webp' : '.jpg'), blob), 'tiny')))
+ list.append(row)
+ } catch (e) { list.append(el('div', { class: 'hint bad', text: file.name + ' 处理失败:' + e.message })) }
+ }
+ total.textContent = `共 ${files.length} 张:${bytes(before)} → ${bytes(after)}`
+ })
+ root.append(pane('参数', el('div', { class: 'row' }, el('span', { text: '质量' }), quality, qLabel, el('span', { text: '最大宽' }), maxW, fmt)),
+ p.node, total, list)
+ },
+ })
+
+ /* ---------- 九宫格切图 ---------- */
+ DB.tool({
+ id: 'img-grid',
+ name: '九宫格切图',
+ group: 'image',
+ icon: 'grid',
+ desc: '按 3×3 / 2×2 / 3×2 切图,一键全部下载,发朋友圈九宫格用',
+ keywords: ['grid', '九宫格', '切图', 'split', '朋友圈'],
+ mount(root) {
+ const rows = el('select', { class: 'input' }, ...[2, 3, 4].map((n) => el('option', { value: n, text: n + ' 行' })))
+ const cols = el('select', { class: 'input' }, ...[2, 3, 4].map((n) => el('option', { value: n, text: n + ' 列' })))
+ rows.value = '3'; cols.value = '3'
+ const grid = el('div', { class: 'media-grid' })
+ const p = picker('image/*', async (f) => {
+ const { bmp, img, w, h } = await loadImage(f)
+ grid.textContent = ''
+ const R = Number(rows.value), C = Number(cols.value)
+ const cw = Math.floor(w / C), ch = Math.floor(h / R)
+ for (let r = 0; r < R; r++) {
+ for (let c = 0; c < C; c++) {
+ const canvas = document.createElement('canvas')
+ canvas.width = cw; canvas.height = ch
+ canvas.getContext('2d').drawImage(bmp || img, c * cw, r * ch, cw, ch, 0, 0, cw, ch)
+ const blob = await canvasToBlob(canvas, 'image/jpeg', 0.92)
+ const url = URL.createObjectURL(blob)
+ const name = `tile_${r + 1}_${c + 1}.jpg`
+ grid.append(el('div', { class: 'media-cell' },
+ el('img', { src: url, alt: name }),
+ btn('下载 ' + name, () => download(name, blob), 'tiny ghost')))
+ }
+ }
+ })
+ root.append(pane('切分', el('div', { class: 'row' }, rows, cols)), p.node, grid)
+ },
+ })
+
+ /* ---------- EXIF ---------- */
+ const TAGS = {
+ 0x010f: '相机厂商', 0x0110: '相机型号', 0x0112: '方向', 0x011a: 'X 分辨率', 0x011b: 'Y 分辨率', 0x0131: '软件', 0x0132: '修改时间',
+ 0x829a: '曝光时间', 0x829d: '光圈', 0x8827: 'ISO', 0x9003: '拍摄时间', 0x920a: '焦距', 0x9209: '闪光灯',
+ 0xa002: '宽', 0xa003: '高', 0x9286: '用户注释', 0x010e: '描述', 0x013b: '作者', 0x8298: '版权',
+ }
+ function parseExif(buf) {
+ const v = new DataView(buf)
+ if (v.getUint16(0) !== 0xffd8) throw new Error('不是 JPEG')
+ let off = 2
+ while (off < buf.byteLength - 4) {
+ if (v.getUint16(off) !== 0xffe1) { off += 2 + v.getUint16(off + 2); continue }
+ const start = off + 4
+ if (String.fromCharCode(v.getUint8(start), v.getUint8(start + 1)) !== 'Ex') return null
+ const tiff = start + 6
+ const little = v.getUint16(tiff) === 0x4949
+ const get16 = (o) => v.getUint16(o, little)
+ const get32 = (o) => v.getUint32(o, little)
+ if (get16(tiff + 2) !== 0x2a) return null
+ const ifd0 = tiff + get32(tiff + 4)
+ const out = {}
+ const readIFD = (dir) => {
+ const n = get16(dir)
+ for (let i = 0; i < n; i++) {
+ const e = dir + 2 + i * 12
+ const tag = get16(e), type = get16(e + 2), count = get32(e + 4)
+ const size = { 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8 }[type] || 1
+ const ptr = count * size > 4 ? tiff + get32(e + 8) : e + 8
+ const name = TAGS[tag]
+ if (type === 2) {
+ let s = ''
+ for (let k = 0; k < count; k++) { const c = v.getUint8(ptr + k); if (!c) break; s += String.fromCharCode(c) }
+ out[name || '0x' + tag.toString(16)] = s
+ } else if (name) {
+ const num = type === 3 ? get16(ptr) : type === 4 ? get32(ptr) : v.getUint8(ptr)
+ out[name] = type === 5 ? `${get32(ptr)}/${get32(ptr + 4)}` : num
+ }
+ if (tag === 0x8769) readIFD(tiff + get32(e + 8))
+ }
+ }
+ readIFD(ifd0)
+ return out
+ }
+ return null
+ }
+
+ DB.tool({
+ id: 'img-exif',
+ name: '图片 EXIF',
+ group: 'image',
+ icon: 'info',
+ desc: '读 JPEG 的拍摄信息:机型、快门、光圈、ISO、时间、GPS 等,顺手看有没有隐私坐标',
+ keywords: ['exif', 'jpeg', 'gps', '拍摄', '隐私', '元数据'],
+ mount(root) {
+ const out = el('pre', { class: 'out' }, el('span', { class: 'hint', text: '选一张手机拍的照片…' }))
+ const p = picker('image/jpeg,image/jpg', async (f) => {
+ try {
+ const buf = await readFile(f, 'buffer')
+ const exif = parseExif(buf)
+ if (!exif) { out.textContent = '这张图没有 EXIF(可能被压缩或本来就是 PNG)'; return }
+ const lines = Object.entries(exif).map(([k, v]) => `${k.padEnd(10, ' ')} ${v}`)
+ out.textContent = `${f.name} · ${bytes(f.size)}\n\n${lines.join('\n')}`
+ } catch (e) { out.textContent = '读取失败:' + e.message }
+ })
+ root.append(pane('选图'), p.node, out)
+ },
+ })
+})()
diff --git a/js/tools-life.js b/js/tools-life.js
new file mode 100644
index 0000000..655e8f2
--- /dev/null
+++ b/js/tools-life.js
@@ -0,0 +1,191 @@
+/* DevBox · 生活与时间进位:番茄钟 / 秒表 / 倒计时、人民币大写、日期大写、十二时辰 */
+(function () {
+ 'use strict'
+ const { el, panelTitle, copy, toast, onInput, pad2 } = DB
+ const btn = (label, fn, cls = '') => el('button', { class: 'btn ' + cls, text: label, onclick: fn })
+ const pane = (title, right) => { const p = el('div', { class: 'panel' }); if (title) p.append(panelTitle(title, right)); return p }
+
+ /* ---------- 番茄钟 / 秒表 / 倒计时 ---------- */
+ DB.tool({
+ id: 'timer-suite',
+ name: '番茄钟 / 秒表 / 倒计时',
+ group: 'time',
+ icon: 'clock',
+ desc: '25 分钟专注 + 5 分钟休息自动切换,秒表带分段,倒计时到点响铃',
+ keywords: ['pomodoro', 'timer', 'stopwatch', '番茄', '秒表', '倒计时'],
+ mount(root) {
+ let pomo = { left: 25 * 60, run: false, focus: true, rounds: 0, timer: 0 }
+ let sw = { base: 0, run: false, timer: 0, laps: [] }
+ let cd = { left: 300, run: false, timer: 0 }
+ const face = (s) => `${pad2(Math.floor(s / 60))}:${pad2(s % 60)}`
+
+ // 番茄钟
+ const pFace = el('div', { class: 'big-time', text: face(pomo.left) })
+ const pTag = el('div', { class: 'hint', text: '专注 · 第 1 轮' })
+ const pRender = () => {
+ pFace.textContent = face(pomo.left)
+ pTag.textContent = (pomo.focus ? '专注' : '休息') + ' · 第 ' + (pomo.rounds + 1) + ' 轮'
+ pFace.classList.toggle('run', pomo.run)
+ }
+ const pTick = () => {
+ if (!pomo.run) return
+ pomo.left--
+ if (pomo.left <= 0) {
+ beep()
+ if (pomo.focus) { pomo.rounds++; pomo.focus = false; pomo.left = 5 * 60 }
+ else { pomo.focus = true; pomo.left = 25 * 60 }
+ }
+ pRender()
+ }
+ const pStart = () => { pomo.run = !pomo.run; if (pomo.run && !pomo.timer) pomo.timer = setInterval(pTick, 1000); pRender() }
+
+ // 秒表
+ const sFace = el('div', { class: 'big-time', text: '00:00.0' })
+ const lapList = el('div', { class: 'result-list' })
+ const sRender = () => {
+ const ms = sw.base + (sw.run ? Date.now() - sw.start : 0)
+ sFace.textContent = `${pad2(Math.floor(ms / 60000))}:${pad2(Math.floor(ms / 1000) % 60)}.${Math.floor(ms % 1000 / 100)}`
+ }
+ const sTick = () => { sRender(); if (sw.run) sw.timer = requestAnimationFrame(sTick) }
+ const sToggle = () => {
+ if (sw.run) { sw.base += Date.now() - sw.start; sw.run = false; cancelAnimationFrame(sw.timer) }
+ else { sw.run = true; sw.start = Date.now(); sTick() }
+ sRender()
+ }
+ const sLap = () => {
+ const ms = sw.base + (sw.run ? Date.now() - sw.start : 0)
+ const prev = sw.laps.length ? sw.laps[sw.laps.length - 1] : 0
+ sw.laps.push(ms)
+ lapList.prepend(el('div', { class: 'row between' },
+ el('span', { text: '第 ' + sw.laps.length + ' 段' }),
+ el('span', { class: 'tag', text: `+${((ms - prev) / 1000).toFixed(1)}s · 总 ${(ms / 1000).toFixed(1)}s` })))
+ }
+
+ // 倒计时
+ const cFace = el('div', { class: 'big-time', text: face(cd.left) })
+ const cMin = el('input', { type: 'number', value: 5, min: 1, max: 180, style: { width: '80px' } })
+ const cRender = () => { cFace.textContent = face(cd.left); cFace.classList.toggle('run', cd.run) }
+ const cTick = () => {
+ if (!cd.run) return
+ cd.left--
+ if (cd.left <= 0) { cd.left = 0; cd.run = false; beep(); beep() }
+ cRender()
+ }
+ const cToggle = () => {
+ if (!cd.run) { cd.left = Math.max(1, Number(cMin.value) * 60); cd.run = true; if (!cd.timer) cd.timer = setInterval(cTick, 1000) }
+ else cd.run = false
+ cRender()
+ }
+
+ function beep() {
+ try {
+ const ctx = new (window.AudioContext || window.webkitAudioContext)()
+ const o = ctx.createOscillator(), g = ctx.createGain()
+ o.frequency.value = 880; o.type = 'sine'; g.gain.value = 0.15
+ o.connect(g); g.connect(ctx.destination); o.start()
+ setTimeout(() => { o.stop(); ctx.close() }, 320)
+ } catch (e) { toast('浏览器不让放声音', true) }
+ }
+
+ pRender(); sRender(); cRender()
+ root.append(
+ pane('番茄钟', el('div', { class: 'row' }, btn('开始 / 暂停', pStart), btn('重置', () => { pomo = { left: 25 * 60, run: false, focus: true, rounds: 0, timer: pomo.timer } ; pRender() }, 'ghost'))),
+ pFace, pTag,
+ pane('秒表', el('div', { class: 'row' }, btn('开始 / 停', sToggle), btn('分段', sLap), btn('清零', () => { sw = { base: 0, run: false, timer: 0, laps: [] }; lapList.textContent = ''; sRender() }, 'ghost'))),
+ sFace, lapList,
+ pane('倒计时', el('div', { class: 'row' }, cMin, el('span', { text: '分钟' }), btn('开始 / 停', cToggle))),
+ cFace
+ )
+ },
+ })
+
+ /* ---------- 人民币 / 日期大写 ---------- */
+ const RMB_D = '零壹贰叁肆伍陆柒捌玖'
+ function rmbUpper(num) {
+ const n = Number(num)
+ if (!isFinite(n)) throw new Error('不是数字')
+ if (Math.abs(n) > 1e12) throw new Error('金额太大了')
+ const neg = n < 0
+ let s = Math.abs(n).toFixed(2)
+ let [int, dec] = s.split('.')
+ const units = ['', '拾', '佰', '仟']
+ const groups = ['', '万', '亿', '万亿']
+ let intPart = ''
+ if (int === '0') intPart = '零'
+ else {
+ const chunks = []
+ let rest = int
+ while (rest.length) { chunks.unshift(rest.slice(-4)); rest = rest.slice(0, -4) }
+ chunks.forEach((chunk, gi) => {
+ const g = chunks.length - 1 - gi
+ if (Number(chunk) === 0) { if (intPart && !intPart.endsWith('零')) intPart += '零'; return }
+ let part = ''
+ for (let i = 0; i < chunk.length; i++) {
+ const d = Number(chunk[i])
+ const u = units[chunk.length - 1 - i]
+ if (d === 0) { if (!part.endsWith('零') && part) part += '零' }
+ else part += RMB_D[d] + u
+ }
+ intPart += part + groups[g]
+ })
+ intPart = intPart.replace(/零+$/, '')
+ }
+ const jiao = Number(dec[0]), fen = Number(dec[1])
+ let decPart = ''
+ if (jiao === 0 && fen === 0) decPart = '整'
+ else {
+ decPart = (jiao ? RMB_D[jiao] + '角' : '零') + (fen ? RMB_D[fen] + '分' : '')
+ if (!jiao) decPart = '零' + RMB_D[fen] + '分'
+ }
+ return (neg ? '负' : '') + intPart + '元' + decPart
+ }
+ const CN_NUM = '零一二三四五六七八九'
+ function dateUpper(d) {
+ const y = d.getFullYear(), m = d.getMonth() + 1, day = d.getDate()
+ const yStr = String(y).split('').map((c) => CN_NUM[Number(c)]).join('')
+ const mStr = m <= 10 ? `十${m === 10 ? '' : CN_NUM[m]}` : `十${CN_NUM[m - 10]}`
+ const dStr = day <= 10 ? (day === 10 ? '十' : CN_NUM[day]) : day < 20 ? '十' + CN_NUM[day - 10] : (day % 10 === 0 ? CN_NUM[Math.floor(day / 10)] + '十' : CN_NUM[Math.floor(day / 10)] + '十' + CN_NUM[day % 10])
+ return `${yStr}年${mStr}月${dStr}日`
+ }
+ const SHICHEN = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥']
+ const shichen = (d) => {
+ const h = d.getHours()
+ const idx = Math.floor(((h + 1) % 24) / 2)
+ const names = ['子时 23:00-01:00', '丑时 01:00-03:00', '寅时 03:00-05:00', '卯时 05:00-07:00', '辰时 07:00-09:00', '巳时 09:00-11:00', '午时 11:00-13:00', '未时 13:00-15:00', '申时 15:00-17:00', '酉时 17:00-19:00', '戌时 19:00-21:00', '亥时 21:00-23:00']
+ return SHICHEN[idx] + '时 · ' + names[idx]
+ }
+ const ZODIAC = ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪']
+ const zodiac = (d) => ZODIAC[(d.getFullYear() - 4) % 12]
+ const XINGZUO = [[1, 20, '水瓶'], [2, 19, '双鱼'], [3, 21, '白羊'], [4, 20, '金牛'], [5, 21, '双子'], [6, 22, '巨蟹'], [7, 23, '狮子'], [8, 23, '处女'], [9, 23, '天秤'], [10, 24, '天蝎'], [11, 23, '射手'], [12, 22, '摩羯'], [13, 32, '水瓶']]
+ const xingzuo = (d) => { const m = d.getMonth() + 1, day = d.getDate(); const hit = XINGZUO.find(([mm, dd]) => m === mm && day < dd); return (hit ? hit[2] : '水瓶') + '座' }
+
+ DB.tool({
+ id: 'cn-format',
+ name: '人民币 / 日期大写',
+ group: 'text',
+ icon: 'type',
+ desc: '金额转大写、日期转汉字、十二时辰、生肖与星座,一次全给出',
+ keywords: ['rmb', '人民币', '大写', '日期', '时辰', '生肖', '星座'],
+ mount(root) {
+ const amt = el('input', { type: 'text', value: '12345.67', class: 'input' })
+ const dateIn = el('input', { type: 'date' })
+ dateIn.value = new Date().toISOString().slice(0, 10)
+ const out = el('pre', { class: 'out' })
+ const run = () => {
+ const lines = []
+ try { lines.push('金额大写:' + rmbUpper(amt.value)) } catch (e) { lines.push('金额错误:' + e.message) }
+ const d = new Date(dateIn.value + 'T12:00:00')
+ if (!isNaN(d)) {
+ lines.push('日期大写:' + dateUpper(d))
+ lines.push('十二时辰:' + shichen(d))
+ lines.push('生肖:' + zodiac(d) + ' 星座:' + xingzuo(d))
+ lines.push('星期:' + '日一二三四五六'[d.getDay()] + ' 当年第 ' + Math.ceil((d - new Date(d.getFullYear(), 0, 0)) / 86400000) + ' 天')
+ }
+ out.textContent = lines.join('\n')
+ }
+ root.append(pane('输入'), el('div', { class: 'row' }, amt, dateIn, btn('转换', run)), out)
+ onInput(amt, run, 300); dateIn.addEventListener('change', run)
+ run()
+ },
+ })
+})()
diff --git a/js/tools-text-extra.js b/js/tools-text-extra.js
new file mode 100644
index 0000000..d3b42f4
--- /dev/null
+++ b/js/tools-text-extra.js
@@ -0,0 +1,61 @@
+/* DevBox · 文本补齐:从一大段文本里抽手机号 / 邮箱 / 链接 / 身份证 / IP / 银行卡 */
+(function () {
+ 'use strict'
+ const { el, panelTitle, copy, toast, onInput } = DB
+ const btn = (label, fn, cls = '') => el('button', { class: 'btn ' + cls, text: label, onclick: fn })
+ const pane = (title, right) => { const p = el('div', { class: 'panel' }); if (title) p.append(panelTitle(title, right)); return p }
+ const ta = (ph, rows) => el('textarea', { class: 'ta', placeholder: ph, rows: rows || 10, spellcheck: 'false' })
+
+ const RULES = {
+ phone: { name: '手机号', re: /(?"'))】\]]+/g, hint: 'http / https' },
+ idcard: { name: '身份证', re: /(? {
+ picks.has(k) ? picks.delete(k) : picks.add(k)
+ chip.classList.toggle('on', picks.has(k))
+ run()
+ })
+ chips.append(chip)
+ }
+ const run = () => {
+ const text = src.value
+ if (!text.trim()) { out.textContent = ''; counts.textContent = ''; return }
+ const blocks = []
+ let total = 0
+ for (const k of Object.keys(RULES)) {
+ if (!picks.has(k)) continue
+ const found = [...new Set(text.match(RULES[k].re) || [])]
+ total += found.length
+ if (found.length) blocks.push(`# ${RULES[k].name}(${found.length})\n` + found.join('\n'))
+ }
+ out.textContent = blocks.join('\n\n') || '这些规则都没有匹配到内容'
+ counts.textContent = `共 ${total} 条,已去重`
+ }
+ root.append(
+ pane('要抓什么', el('div', { class: 'row' }, btn('全选', () => { Object.keys(RULES).forEach((k) => picks.add(k)); root.querySelectorAll('.chip-btn').forEach((c) => c.classList.add('on')); run() }, 'ghost'), btn('只留链接', () => { picks.clear(); picks.add('url'); root.querySelectorAll('.chip-btn').forEach((c, i) => c.classList.toggle('on', Object.keys(RULES)[i] === 'url')); run() }, 'ghost'))),
+ chips, src, counts, out
+ )
+ onInput(src, run, 250)
+ },
+ })
+})()
diff --git a/js/util.js b/js/util.js
index 3d6b327..972d1e3 100644
--- a/js/util.js
+++ b/js/util.js
@@ -12,6 +12,7 @@
{ 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: '解析、转码、网盘直链' },
]
DB.tools = []