diff --git a/README.md b/README.md index 4959a97..a8adbc3 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ ## 特点 -- **23 个工具,6 类**:图片 / 编码 / 加密 / 文本 / 时间 / Web 与系统 +- **26 个工具,6 类**:图片 / 编码 / 加密 / 文本 / 时间 / Web 与系统 - **全部本地算**:哈希、AES、图片转码都走浏览器自带的 Web Crypto 和 Canvas,文件不会离开这台设备 - **零依赖、无构建**:原生 HTML + CSS + JS,没有 npm install,没有打包器;双击 `index.html` 也能跑(`file://` 支持) - **手机能用**:侧栏自动收成抽屉,卡片和表单按竖屏重排 @@ -20,6 +20,7 @@ | 图片 | 图片格式转换 | PNG / JPEG / WebP 互转,可调质量、按宽度缩放、批量处理,显示压缩前后体积 | | 图片 | 图片 ↔ Base64 | 图片转 DataURL 内联进 CSS/HTML;Base64 还原成图片下载 | | 图片 | 图片信息与取色 | 尺寸、比例、体积、格式,抽出主色板,点色块直接复制 | +| 图片 | 图片加水印 | 拖一张图,压文字水印:四角/居中/平铺,大小、透明度、颜色、描边都可调,导出 PNG/JPEG | | 编码 | Base64 编解码 | 中文、emoji 不乱码;支持 URL 安全变体与自动判断方向 | | 编码 | URL 编码 / 解析 | 整段 URL 或单个参数编解码,查询参数拆成表格 | | 编码 | HTML 实体转义 | `< > & " '` 转实体;反向把实体还原成可读文本 | @@ -32,6 +33,7 @@ | 文本 | 文本对比 Diff | 行级 LCS 对比,高亮增删并统计 +/- | | 文本 | 正则测试 | 实时高亮、列出分组、预览替换;`g i m s u` 是开关胶囊 | | 文本 | 文本转换与清理 | 大小写、camel/snake/kebab/CONSTANT、去空行、去重、排序、反转、合并空格、字数统计 | +| 文本 | JSON 转 TypeScript | 递归生成嵌套 `interface`,数组元素合并键、缺失字段标 `?`,类型冲突自动联合 | | 时间 | 时间戳转换 | 秒/毫秒自动识别,同时给出本地、UTC、ISO、相对时间、星期与年内第几天 | | 时间 | 日期计算 | 加减天/周/月/年/工作日;两个日期之间的天数与工作日数 | | 时间 | Cron 表达式 | 5/6 段解析成人话,算出接下来 5 次执行时间,带常用预设 | @@ -39,6 +41,7 @@ | Web | HTTP 状态码 & MIME | 52 个状态码 + 30 个常用 MIME,可搜索 | | Web | 文件权限 chmod | `rwx` 勾选 ↔ 八进制互转,附常见权限解释 | | Web | IPv4 / CIDR 计算 | 网络地址、掩码、通配符、广播、可用范围、主机数、是否私有地址 | +| Web | cURL 转代码 | 粘贴浏览器复制的 cURL,转成 fetch / axios / Python requests,方法、请求头、body 都能带 | | Web | **一键部署脚本** | 填仓库、目录、构建命令,生成服务器上直接能跑的 `deploy.sh` + systemd 单元 + Nginx 配置 | ## 一键部署脚本 @@ -76,6 +79,12 @@ python3 -m http.server 8100 | --- | --- | | ![JSON](preview/json.png) | ![正则](preview/regex.png) | +| JSON → TypeScript | cURL → 代码 | +| --- | --- | +| ![JSON 转 TS](preview/json2ts.png) | ![cURL](preview/curl.png) | + +![图片水印](preview/watermark.png) + ## 技术要点 - **哈希与加密**用浏览器内置 `crypto.subtle`:SHA-1/256/384/512、HMAC、PBKDF2、AES-GCM。不是自造的算法,也没有把密钥发到任何地方。 @@ -99,6 +108,7 @@ devbox/ │ ├── tools-image.js # 图片转换 / Base64 / 取色 │ ├── tools-web.js # 颜色 / HTTP / chmod / CIDR │ ├── tools-deploy.js # 一键部署脚本 +│ ├── tools-extra.js # JSON→TS / 图片水印 / cURL 转代码 │ └── app.js # 路由、搜索、命令面板 ├── preview/ # README 截图 └── README.md diff --git a/css/style.css b/css/style.css index 4ff608c..af5e0d9 100644 --- a/css/style.css +++ b/css/style.css @@ -433,3 +433,8 @@ mark { background: rgba(55, 224, 208, .28); color: #eafffb; border-radius: 3px; } .flag:hover { border-color: rgba(91,140,255,.5); color: var(--txt); } .flag.on { background: rgba(91,140,255,.18); border-color: rgba(91,140,255,.65); color: #cfe0ff; box-shadow: 0 0 0 1px rgba(91,140,255,.25) inset; } + +/* ===== 图片水印 ===== */ +.color-input-mini { width: 90px; height: 38px; padding: 2px; border-radius: 8px; border: 1px solid var(--line-strong); background: rgba(255,255,255,.03); cursor: pointer; } +.wm-canvas { max-width: 100%; border-radius: 10px; border: 1px solid var(--line); display: block; margin-top: 10px; } +.drop.over { border-color: var(--accent); background: rgba(91,140,255,.08); } diff --git a/index.html b/index.html index 39b55f0..f66c388 100644 --- a/index.html +++ b/index.html @@ -106,6 +106,7 @@ + diff --git a/js/tools-crypto.js b/js/tools-crypto.js index df7e2fa..11e1435 100644 --- a/js/tools-crypto.js +++ b/js/tools-crypto.js @@ -221,7 +221,7 @@ if (k === 'exp') tag = v < now ? '(已过期)' : '(' + relTime(v - now) + '后过期)' else if (k === 'nbf') tag = v > now ? '(还没生效)' : '' else if (k === 'iat') tag = '(' + relTime(now - v) + '前签发)' - return el('dt', { text: k }), el('dd', { text: d.toLocaleString('zh-CN') + ' ' + tag }) + return [el('dt', { text: k }), el('dd', { text: d.toLocaleString('zh-CN') + ' ' + tag })] } const relTime = (sec) => { const a = Math.abs(sec) diff --git a/js/tools-extra.js b/js/tools-extra.js new file mode 100644 index 0000000..a102243 --- /dev/null +++ b/js/tools-extra.js @@ -0,0 +1,309 @@ +/* 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() + }, + }) +})() diff --git a/preview/curl.png b/preview/curl.png new file mode 100644 index 0000000..727714a Binary files /dev/null and b/preview/curl.png differ diff --git a/preview/home.png b/preview/home.png index b08d1ac..87ba134 100644 Binary files a/preview/home.png and b/preview/home.png differ diff --git a/preview/json2ts.png b/preview/json2ts.png new file mode 100644 index 0000000..fbb2ac5 Binary files /dev/null and b/preview/json2ts.png differ diff --git a/preview/watermark.png b/preview/watermark.png new file mode 100644 index 0000000..7a5de38 Binary files /dev/null and b/preview/watermark.png differ