Files
devbox/js/tools-extra.js
T
2026-11-17 14:58:39 +08:00

310 lines
16 KiB
JavaScript
Raw 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.
/* DevBox · 进阶:JSON → TypeScript / 图片水印 / cURL 转代码 */
(function () {
'use strict'
const { el, panelTitle, copy, output, toast, download, loadImage, canvasToBlob, onInput } = DB
const pane = (title, right) => { const p = el('div', { class: 'panel' }); if (title) p.append(panelTitle(title, right)); return p }
const btn = (label, fn, cls = '') => el('button', { class: 'btn ' + cls, text: label, onclick: fn })
const field = (label, control) => el('label', { class: 'field' }, el('span', { text: label }), control)
const area = (ph, rows = 8) => el('textarea', { rows, placeholder: ph || '', spellcheck: 'false' })
/* ================= JSON → TypeScript ================= */
DB.tool({
id: 'json2ts',
name: 'JSON 转 TypeScript',
group: 'text',
icon: 'code',
desc: '把一段 JSON 变成带嵌套接口的 TS 类型,数组元素自动合并、缺失字段标成可选',
keywords: ['json', 'typescript', 'ts', 'interface', 'type', '类型', '接口'],
mount(root) {
const input = area('粘贴 JSON,自动生成 interface', 9)
input.value = '{\n "id": 1024,\n "name": "鲸鱼娘",\n "tags": ["dev", "whale"],\n "profile": { "level": 9, "vip": true },\n "posts": [\n { "title": "部署脚本", "likes": 12 },\n { "title": "图床", "likes": 8, "pinned": true }\n ]\n}'
const rootName = el('input', { type: 'text', value: 'Root' })
const out = output()
const err = el('div', { class: 'err' })
const hint = el('div', { class: 'hint' })
const pascal = (s) => {
const parts = String(s).replace(/[^A-Za-z0-9]+/g, ' ').trim().split(/\s+/).filter(Boolean)
const joined = parts.map((w) => w[0].toUpperCase() + w.slice(1)).join('')
return /^\d/.test(joined) ? 'T' + joined : joined || 'Item'
}
const singular = (s) => s.replace(/(ies)$/i, 'y').replace(/(ses|xes|zes|ches|shes)$/i, '').replace(/s$/i, '') || s
const propKey = (k) => (/^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k))
const convert = (value, name) => {
const blocks = []
const used = new Map()
const unique = (base) => {
const n = used.get(base) || 0
used.set(base, n + 1)
return n === 0 ? base : base + (n + 1)
}
const typeOf = (v, hintName) => {
if (v === null) return 'null'
if (Array.isArray(v)) {
if (!v.length) return 'unknown[]'
const objs = v.filter((x) => x && typeof x === 'object' && !Array.isArray(x))
if (objs.length === v.length) return objType(objs, singular(hintName)) + '[]'
const parts = [...new Set(v.map((x) => typeOf(x, singular(hintName))))]
return parts.length === 1 ? parts[0] + '[]' : '(' + parts.join(' | ') + ')[]'
}
if (typeof v === 'object') return objType([v], hintName)
if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') return typeof v
return 'unknown'
}
const objType = (objs, hintName) => {
const name = unique(pascal(hintName) || 'Item')
const keys = [...new Set(objs.flatMap((o) => Object.keys(o)))]
const lines = keys.map((k) => {
const present = objs.filter((o) => k in o)
const types = [...new Set(present.map((o) => typeOf(o[k], name + pascal(k))))]
const opt = present.length < objs.length ? '?' : ''
return ` ${propKey(k)}${opt}: ${types.length === 1 ? types[0] : types.join(' | ')}`
})
blocks.push(`export interface ${name} {\n${lines.join('\n')}\n}`)
return name
}
const topName = pascal(name || 'Root')
const topType = Array.isArray(value)
? typeOf(value, singular(topName))
: objType([value], topName)
return { code: blocks.slice().reverse().join('\n\n') + `\n\nexport type ${topName}Result = ${topType}\n`, topType }
}
const run = () => {
err.textContent = ''
hint.textContent = ''
if (!input.value.trim()) { out.set(''); hint.textContent = '粘贴 JSON 后自动生成类型'; return }
let value
try { value = JSON.parse(input.value) } catch (e) { out.set(''); err.textContent = 'JSON 不合法:' + DB.jsonError(e, input.value); return }
if (value === null || typeof value !== 'object') {
out.set(`export type ${pascal(rootName.value || 'Root')} = ${typeof value}`)
return
}
const r = convert(value, rootName.value || 'Root')
out.set(r.code)
hint.textContent = `生成 ${(r.code.match(/export interface/g) || []).length} 个接口`
}
onInput(input, run, 240)
onInput(rootName, run, 240)
rootName.addEventListener('change', run)
const p1 = pane('JSON 输入')
p1.append(input, el('div', { class: 'row', style: { marginTop: '10px', alignItems: 'flex-end' } },
el('label', { class: 'field', style: { flex: '0 1 220px' } }, el('span', { text: '根类型名' }), rootName),
btn('载入示例', () => { input.value = '{\n "id": 1,\n "tags": ["a"],\n "items": [{ "n": 1 }]\n}'; run() })))
const p2 = pane('生成的类型')
p2.append(err, out.node, hint)
root.append(p1, p2)
run()
},
})
/* ================= 图片水印 ================= */
DB.tool({
id: 'watermark',
name: '图片加水印',
group: 'image',
icon: 'image',
desc: '给图片压一段文字水印,位置、大小、透明度、颜色都能调,导出 PNG/JPEG',
keywords: ['watermark', '水印', '版权', 'logo', '图片'],
mount(root) {
const fileInput = el('input', { type: 'file', accept: 'image/*', hidden: true })
const drop = el('div', { class: 'drop' }, el('div', { class: 'drop-in' },
el('b', { text: '拖一张图进来,或点击选择' }),
el('span', { text: '只在浏览器里处理,不会上传' })))
const textIn = el('input', { type: 'text', value: 'DevBox · syc65535' })
const posSel = el('select', {}, ...[['br', '右下角'], ['bl', '左下角'], ['tr', '右上角'], ['tl', '左上角'], ['center', '居中'], ['tile', '平铺']].map(([v, t]) => el('option', { value: v, text: t })))
const sizeIn = el('input', { type: 'range', min: 2, max: 12, step: 0.5, value: 4 })
const sizeLabel = el('b', { text: '4%' })
const opIn = el('input', { type: 'range', min: 0.1, max: 1, step: 0.05, value: 0.55 })
const opLabel = el('b', { text: '55%' })
const colorIn = el('input', { type: 'color', value: '#ffffff', class: 'color-input-mini' })
const shadowIn = el('input', { type: 'checkbox', checked: true })
const fmtSel = el('select', {}, el('option', { value: 'image/png', text: 'PNG' }), el('option', { value: 'image/jpeg', text: 'JPEG(补白底)' }))
const canvas = el('canvas', { class: 'wm-canvas' })
const empty = el('div', { class: 'hint', text: '还没有图片' })
const dl = btn('下载水印图', () => save(), 'primary')
dl.disabled = true
let img = null
const save = async () => {
if (!canvas.width) return
const blob = await canvasToBlob(canvas, fmtSel.value, fmtSel.value === 'image/jpeg' ? 0.92 : undefined)
if (blob) download('watermarked.' + (fmtSel.value === 'image/jpeg' ? 'jpg' : 'png'), blob)
}
const draw = () => {
if (!img) return
const w = img.w, h = img.h
canvas.width = w; canvas.height = h
const g = canvas.getContext('2d')
if (fmtSel.value === 'image/jpeg') { g.fillStyle = '#fff'; g.fillRect(0, 0, w, h) }
g.drawImage(img.src, 0, 0, w, h)
const size = Math.max(10, Math.round(Math.min(w, h) * (Number(sizeIn.value) / 100)))
g.font = `600 ${size}px system-ui, "PingFang SC", "Microsoft YaHei", sans-serif`
g.fillStyle = colorIn.value
g.globalAlpha = Number(opIn.value)
g.textBaseline = 'alphabetic'
if (shadowIn.checked) { g.shadowColor = 'rgba(0,0,0,.45)'; g.shadowBlur = Math.max(4, size * 0.25); g.shadowOffsetY = Math.max(2, size * 0.06) }
const pad = Math.round(size * 0.7)
const tw = g.measureText(textIn.value).width
if (posSel.value === 'tile') {
g.save()
g.globalAlpha = Number(opIn.value) * 0.75
g.translate(w / 2, h / 2); g.rotate(-Math.PI / 7); g.translate(-w / 2, -h / 2)
const stepX = tw + pad * 3, stepY = size * 5
for (let y = -h; y < h * 2; y += stepY) for (let x = -w; x < w * 2; x += stepX) g.fillText(textIn.value, x, y)
g.restore()
} else {
let x = pad, y = h - pad
if (posSel.value === 'br') x = w - tw - pad
else if (posSel.value === 'tr') { x = w - tw - pad; y = pad + size }
else if (posSel.value === 'tl') { x = pad; y = pad + size }
else if (posSel.value === 'center') { x = (w - tw) / 2; y = h / 2 + size / 3 }
if (posSel.value === 'bl') x = pad
g.fillText(textIn.value, x, y)
}
g.globalAlpha = 1
dl.disabled = false
empty.hidden = true
}
const open = async (file) => {
try {
const loaded = await loadImage(file)
img = { src: loaded.bmp || loaded.img, w: loaded.w, h: loaded.h }
draw()
toast(`已载入 ${w}×${h}`)
} catch (e) { toast('这不是能识别的图片', true) }
}
drop.addEventListener('click', () => fileInput.click())
fileInput.addEventListener('change', () => { if (fileInput.files[0]) open(fileInput.files[0]) })
drop.addEventListener('dragover', (e) => { e.preventDefault(); drop.classList.add('over') })
drop.addEventListener('dragleave', () => drop.classList.remove('over'))
drop.addEventListener('drop', (e) => { e.preventDefault(); drop.classList.remove('over'); if (e.dataTransfer.files[0]) open(e.dataTransfer.files[0]) })
for (const c of [textIn, posSel, sizeIn, opIn, colorIn, shadowIn, fmtSel]) {
c.addEventListener('input', () => {
sizeLabel.textContent = sizeIn.value + '%'
opLabel.textContent = Math.round(Number(opIn.value) * 100) + '%'
draw()
})
c.addEventListener('change', () => { sizeLabel.textContent = sizeIn.value + '%'; opLabel.textContent = Math.round(Number(opIn.value) * 100) + '%'; draw() })
}
const p1 = pane('图片')
p1.append(drop, fileInput)
const p2 = pane('水印设置')
p2.append(
el('div', { class: 'grid2' },
field('水印文字', textIn),
field('位置', posSel),
el('div', { class: 'row', style: { alignItems: 'center' } },
el('label', { class: 'field', style: { flex: '1' } }, el('span', { text: '大小' }), sizeIn),
sizeLabel),
el('div', { class: 'row', style: { alignItems: 'center' } },
el('label', { class: 'field', style: { flex: '1' } }, el('span', { text: '透明度' }), opIn),
opLabel),
el('div', { class: 'row', style: { alignItems: 'flex-end', gap: '10px' } },
el('label', { class: 'field', style: { flex: '0 0 90px' } }, el('span', { text: '颜色' }), colorIn),
el('label', { class: 'check', style: { paddingBottom: '10px' } }, shadowIn, el('span', { text: '描边阴影' })),
el('label', { class: 'field', style: { flex: '1' } }, el('span', { text: '导出格式' }), fmtSel))))
const p3 = pane('预览', dl)
p3.append(empty, canvas)
root.append(p1, p2, p3)
},
})
/* ================= cURL 转代码 ================= */
DB.tool({
id: 'curl',
name: 'cURL 转代码',
group: 'web',
icon: 'terminal',
desc: '把浏览器复制出来的 cURL 命令转成 fetch / axios / Python requests,请求头和方法都能认',
keywords: ['curl', 'fetch', 'axios', 'requests', 'http', '请求', '转换'],
mount(root) {
const input = area('粘贴 cURL,例如:curl https://api.example.com/v1/items -H "Authorization: Bearer xxx"', 8)
input.value = `curl 'https://api.github.com/repos/syc65535/devbox' \\
-H 'Accept: application/vnd.github+json' \\
-H 'Authorization: Bearer ghp_xxx'`
const out = output()
const err = el('div', { class: 'err' })
const tabsHost = el('div', { class: 'row' })
const LANGS = ['fetch', 'axios', 'python']
let lang = 'fetch'
const tabBtns = {}
for (const l of LANGS) {
const b = el('button', { class: 'btn tiny' + (l === lang ? ' primary' : ''), text: l, onclick: () => { lang = l; for (const k of LANGS) tabBtns[k].classList.toggle('primary', k === l); run() } })
tabBtns[l] = b
tabsHost.append(b)
}
const parseCurl = (raw) => {
const s = raw.replace(/\\\r?\n/g, ' ').trim()
if (!/^curl\b/.test(s)) throw new Error('这行不是 curl 命令')
const tokens = []
const re = /"([^"]*)"|'([^']*)'|(\S+)/g
let m
while ((m = re.exec(s))) tokens.push(m[1] ?? m[2] ?? m[3])
const req = { url: '', method: '', headers: {}, body: '' }
for (let i = 1; i < tokens.length; i++) {
const t = tokens[i]
if (t === '-H' || t === '--header') { const h = tokens[++i] || ''; const k = h.indexOf(':'); if (k > 0) req.headers[h.slice(0, k).trim()] = h.slice(k + 1).trim() }
else if (t === '-X' || t === '--request') req.method = (tokens[++i] || '').toUpperCase()
else if (t === '-d' || t === '--data' || t === '--data-raw' || t === '--data-binary') { req.body = tokens[++i] || ''; if (!req.method) req.method = 'POST' }
else if (t === '-u' || t === '--user') { const u = tokens[++i] || ''; req.headers.Authorization = 'Basic ' + btoa(u) }
else if (t === '--compressed' || t === '-s' || t === '-i' || t === '-L' || t === '-k' || t === '--insecure') continue
else if (!t.startsWith('-')) req.url = t
}
if (!req.url) throw new Error('没找到 URL')
if (!req.method) req.method = req.body ? 'POST' : 'GET'
return req
}
const q = (s) => JSON.stringify(s)
const gen = (req) => {
const hs = Object.entries(req.headers)
if (lang === 'fetch') {
const lines = [`const res = await fetch(${q(req.url)}, {`, ` method: ${q(req.method)},`]
if (hs.length) lines.push(' headers: {', ...hs.map(([k, v]) => ` ${q(k)}: ${q(v)},`), ' },')
if (req.body) lines.push(` body: ${q(req.body)},`)
lines.push('})', 'if (!res.ok) throw new Error(`HTTP ${res.status}`)', 'const data = await res.json()', 'console.log(data)')
return lines.join('\n')
}
if (lang === 'axios') {
const lines = [`import axios from 'axios'`, '', `const { data } = await axios.request({`, ` url: ${q(req.url)},`, ` method: ${q(req.method.toLowerCase())},`]
if (hs.length) lines.push(' headers: {', ...hs.map(([k, v]) => ` ${q(k)}: ${q(v)},`), ' },')
if (req.body) {
let parsed = null
try { parsed = JSON.parse(req.body) } catch {}
lines.push(` data: ${parsed ? JSON.stringify(parsed, null, 2).replace(/\n/g, '\n ') + ',' : q(req.body) + ','}`)
}
lines.push('})', 'console.log(data)')
return lines.join('\n')
}
const lines = ['import requests', '', `res = requests.request(${q(req.method)}, ${q(req.url)},`]
if (hs.length) lines.push(' headers={', ...hs.map(([k, v]) => ` ${q(k)}: ${q(v)},`), ' },')
if (req.body) lines.push(` data=${q(req.body)},`)
lines.push(' timeout=30,', ')', 'res.raise_for_status()', 'print(res.json())')
return lines.join('\n')
}
const run = () => {
err.textContent = ''
if (!input.value.trim()) { out.set(''); return }
try { out.set(gen(parseCurl(input.value))) } catch (e) { out.set(''); err.textContent = e.message }
}
onInput(input, run, 220)
input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) run() })
const p1 = pane('cURL 命令')
p1.append(input, el('div', { class: 'hint', text: '从浏览器开发者工具里「Copy as cURL」直接粘进来即可;支持 -H / -X / -d / -u 和换行续行。' }))
const p2 = pane('生成的代码', tabsHost)
p2.append(err, out.node)
root.append(p1, p2)
run()
},
})
})()