Files
devbox/js/tools-web.js
T
2026-11-17 14:51:40 +08:00

358 lines
21 KiB
JavaScript
Raw Permalink 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 · Web 与系统:颜色 / HTTP / 权限 / CIDR */
(function () {
'use strict'
const { el, panelTitle, copy, toast, 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 clamp = (v, a, b) => Math.min(b, Math.max(a, v))
function hslToRgb(h, s, l) {
h = ((h % 360) + 360) % 360; s /= 100; l /= 100
const c = (1 - Math.abs(2 * l - 1)) * s
const x = c * (1 - Math.abs((h / 60) % 2 - 1))
const m = l - c / 2
let rgb
if (h < 60) rgb = [c, x, 0]; else if (h < 120) rgb = [x, c, 0]
else if (h < 180) rgb = [0, c, x]; else if (h < 240) rgb = [0, x, c]
else if (h < 300) rgb = [x, 0, c]; else rgb = [c, 0, x]
return rgb.map((v) => Math.round((v + m) * 255))
}
function rgbToHsl(r, g, b) {
r /= 255; g /= 255; b /= 255
const max = Math.max(r, g, b), min = Math.min(r, g, b)
const l = (max + min) / 2
let h = 0, s = 0
if (max !== min) {
const d = max - min
s = l > .5 ? d / (2 - max - min) : d / (max + min)
if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) * 60
else if (max === g) h = ((b - r) / d + 2) * 60
else h = ((r - g) / d + 4) * 60
}
return [Math.round(h), Math.round(s * 100), Math.round(l * 100)]
}
const lum = (r, g, b) => {
const f = (v) => { v /= 255; return v <= .03928 ? v / 12.92 : Math.pow((v + .055) / 1.055, 2.4) }
return .2126 * f(r) + .7152 * f(g) + .0722 * f(b)
}
const contrast = (a, b) => { const l1 = Math.max(a, b), l2 = Math.min(a, b); return (l1 + .05) / (l2 + .05) }
const hex2 = (n) => n.toString(16).padStart(2, '0')
const toHex = (r, g, b) => '#' + hex2(r) + hex2(g) + hex2(b)
DB.tool({
id: 'color',
name: '颜色工具',
group: 'web',
icon: 'palette',
desc: 'HEX / RGB / HSL 实时互转,对比度检查与明暗色阶',
keywords: ['color', 'hex', 'rgb', 'hsl', 'contrast', 'wcag', '颜色', '配色', '对比度'],
mount(root) {
const state = { r: 91, g: 140, b: 255 }
const picker = el('input', { type: 'color', class: 'color-input', value: '#5b8cff' })
const heroTitle = el('b', { text: '#5B8CFF' })
const heroSub = el('span', { text: 'rgb(91, 140, 255)' })
const hero = el('div', { class: 'color-hero' }, el('div', { class: 'color-hero-in' }, heroTitle, heroSub), picker)
const hexIn = el('input', { type: 'text', value: '#5b8cff', style: { fontFamily: 'var(--mono)' } })
const inp = {}
for (const k of ['r', 'g', 'b']) inp[k] = el('input', { type: 'number', min: 0, max: 255, value: state[k] })
const hslIn = {}
for (const k of ['h', 's', 'l']) hslIn[k] = el('input', { type: 'number', min: 0, max: k === 'h' ? 360 : 100, value: 0 })
const formats = el('div', { class: 'fmt-grid' })
const shades = el('div', { class: 'swatches' })
const cc = el('div', { class: 'stack' })
const paint = () => {
const { r, g, b } = state
const [h, s, l] = rgbToHsl(r, g, b)
const hexv = toHex(r, g, b)
hero.style.background = hexv
const light = lum(r, g, b) > 0.55
hero.classList.toggle('on-light', light)
heroTitle.textContent = hexv.toUpperCase()
heroSub.textContent = `rgb(${r}, ${g}, ${b}) · hsl(${h} ${s}% ${l}%)`
const fmt = {
HEX: hexv.toUpperCase(),
'HEX 短': /^#(.)\1(.)\2(.)\3$/i.test(hexv) ? '#' + [r, g, b].map((v) => hex2(v)[0]).join('') : '—',
RGB: `rgb(${r}, ${g}, ${b})`,
'RGB %': `rgb(${(r / 255 * 100).toFixed(1)}% ${(g / 255 * 100).toFixed(1)}% ${(b / 255 * 100).toFixed(1)}%)`,
HSL: `hsl(${h} ${s}% ${l}%)`,
'CSS 变量': `--brand: ${hexv};`,
'RGBA 50%': `rgba(${r}, ${g}, ${b}, .5)`,
'Flutter 0xFF': '0xFF' + hex2(r).toUpperCase() + hex2(g).toUpperCase() + hex2(b).toUpperCase(),
}
formats.textContent = ''
for (const [k, v] of Object.entries(fmt)) {
formats.append(el('button', { class: 'fmt-item', title: '点击复制 ' + v, onclick: () => copy(v) },
el('span', { class: 'fmt-k', text: k }),
el('code', { class: 'fmt-v', text: v })))
}
shades.textContent = ''
const steps = [90, 78, 64, 50, 36, 24, 14]
steps.forEach((L) => {
const [rr, gg, bb] = hslToRgb(h, s, L)
const hexs = toHex(rr, gg, bb)
const sw = el('div', { class: 'swatch', style: { background: hexs }, title: hexs + ' · L=' + L })
sw.addEventListener('click', () => copy(hexs))
shades.append(wrapSwatch(sw, hexs))
})
cc.textContent = ''
for (const [label, bg] of [['白底黑字', lum(255, 255, 255)], ['黑底白字', lum(0, 0, 0)]]) {
const ratio = contrast(lum(r, g, b), bg)
const grade = ratio >= 7 ? ['AAA', 'good'] : ratio >= 4.5 ? ['AA', 'good'] : ratio >= 3 ? ['AA 大字', 'warn'] : ['不达标', 'bad']
cc.append(el('div', { class: 'row between' },
el('span', { text: label, style: { fontSize: '13px', color: 'var(--dim)' } }),
el('span', { class: 'chip', html: `<b>${ratio.toFixed(2)}:1</b> <b class="${grade[1]}">${grade[0]}</b>` })))
}
}
const wrapSwatch = (sw, label) => {
const box = el('div', { style: { display: 'flex', flexDirection: 'column', gap: '5px', alignItems: 'center' } })
box.append(sw, el('span', { text: label, style: { font: '10.5px var(--mono)', color: 'var(--dim-2)' } }))
return box
}
const syncFromRgb = () => {
const { r, g, b } = state
picker.value = toHex(r, g, b)
hexIn.value = toHex(r, g, b).toUpperCase()
inp.r.value = r; inp.g.value = g; inp.b.value = b
const [h, s, l] = rgbToHsl(r, g, b)
hslIn.h.value = h; hslIn.s.value = s; hslIn.l.value = l
paint()
}
const setRgb = (r, g, b) => { state.r = clamp(Math.round(r), 0, 255); state.g = clamp(Math.round(g), 0, 255); state.b = clamp(Math.round(b), 0, 255); syncFromRgb() }
picker.addEventListener('input', () => { const v = picker.value; setRgb(parseInt(v.slice(1, 3), 16), parseInt(v.slice(3, 5), 16), parseInt(v.slice(5, 7), 16)) })
hexIn.addEventListener('input', () => {
let v = hexIn.value.trim().replace(/^#/, '')
if (/^[0-9a-f]{3}$/i.test(v)) v = v.split('').map((c) => c + c).join('')
if (/^[0-9a-f]{6}$/i.test(v)) setRgb(parseInt(v.slice(0, 2), 16), parseInt(v.slice(2, 4), 16), parseInt(v.slice(4, 6), 16))
})
for (const k of ['r', 'g', 'b']) inp[k].addEventListener('input', () => setRgb(Number(inp.r.value) || 0, Number(inp.g.value) || 0, Number(inp.b.value) || 0))
for (const k of ['h', 's', 'l']) hslIn[k].addEventListener('input', () => {
const rgb = hslToRgb(Number(hslIn.h.value) || 0, Number(hslIn.s.value) || 0, Number(hslIn.l.value) || 0)
setRgb(...rgb)
})
const p1 = pane('颜色')
p1.append(hero,
el('div', { style: { marginTop: '14px' } }, el('label', { class: 'field' }, el('span', { text: 'HEX' }), hexIn)),
el('div', { class: 'row', style: { marginTop: '12px' } },
el('label', { class: 'field', style: { flex: '1 1 0' } }, el('span', { text: 'R' }), inp.r),
el('label', { class: 'field', style: { flex: '1 1 0' } }, el('span', { text: 'G' }), inp.g),
el('label', { class: 'field', style: { flex: '1 1 0' } }, el('span', { text: 'B' }), inp.b)),
el('div', { class: 'row', style: { marginTop: '12px' } },
el('label', { class: 'field', style: { flex: '1 1 0' } }, el('span', { text: 'H' }), hslIn.h),
el('label', { class: 'field', style: { flex: '1 1 0' } }, el('span', { text: 'S %' }), hslIn.s),
el('label', { class: 'field', style: { flex: '1 1 0' } }, el('span', { text: 'L %' }), hslIn.l)))
const p2 = pane('各种写法(点击复制)')
p2.append(formats)
const p3 = pane('明暗色阶(点击复制)')
p3.append(shades)
const p4 = pane('对比度')
p4.append(cc)
root.append(p1, p2, p3, p4)
syncFromRgb()
},
})
/* ================= HTTP 状态码与 MIME ================= */
const STATUS = [
[100, 'Continue', '继续'], [101, 'Switching Protocols', '切换协议'], [102, 'Processing', '处理中'], [103, 'Early Hints', '早期提示'],
[200, 'OK', '成功'], [201, 'Created', '已创建'], [202, 'Accepted', '已接受(异步处理中)'], [203, 'Non-Authoritative Information', '非权威信息'],
[204, 'No Content', '成功但无内容'], [205, 'Reset Content', '重置内容'], [206, 'Partial Content', '部分内容(断点续传)'],
[300, 'Multiple Choices', '多种选择'], [301, 'Moved Permanently', '永久重定向'], [302, 'Found', '临时重定向'],
[303, 'See Other', '用 GET 去另一个地址看'], [304, 'Not Modified', '资源没变(缓存命中)'], [307, 'Temporary Redirect', '临时重定向(保持方法)'],
[308, 'Permanent Redirect', '永久重定向(保持方法)'],
[400, 'Bad Request', '请求格式不对'], [401, 'Unauthorized', '没认证 / 令牌无效'], [402, 'Payment Required', '需要付费'],
[403, 'Forbidden', '认证了但没权限'], [404, 'Not Found', '资源不存在'], [405, 'Method Not Allowed', '方法不允许'],
[406, 'Not Acceptable', '无法满足 Accept'], [407, 'Proxy Authentication Required', '代理要认证'], [408, 'Request Timeout', '请求超时'],
[409, 'Conflict', '冲突(版本/唯一键)'], [410, 'Gone', '资源已被永久删除'], [411, 'Length Required', '需要 Content-Length'],
[412, 'Precondition Failed', '前置条件失败'], [413, 'Payload Too Large', '请求体太大'], [414, 'URI Too Long', 'URL 太长'],
[415, 'Unsupported Media Type', '不支持的媒体类型'], [416, 'Range Not Satisfiable', '范围不合法'], [418, "I'm a teapot", '彩蛋'],
[422, 'Unprocessable Entity', '参数校验失败'], [425, 'Too Early', '太早了(防重放)'], [426, 'Upgrade Required', '需要升级协议'],
[428, 'Precondition Required', '需要条件请求'], [429, 'Too Many Requests', '限流,稍后再试'], [431, 'Request Header Fields Too Large', '请求头太大'],
[451, 'Unavailable For Legal Reasons', '因法律原因不可用'],
[500, 'Internal Server Error', '服务端内部错误'], [501, 'Not Implemented', '服务端没实现'], [502, 'Bad Gateway', '网关收到错误响应'],
[503, 'Service Unavailable', '服务暂不可用(过载/维护)'], [504, 'Gateway Timeout', '网关超时'], [505, 'HTTP Version Not Supported', 'HTTP 版本不支持'],
[507, 'Insufficient Storage', '存储不足'], [508, 'Loop Detected', '检测到循环'],
]
const MIME = [
['application/json', '.json', 'JSON 数据'], ['application/xml', '.xml', 'XML'], ['application/javascript', '.js', 'JS(官方)'],
['text/javascript', '.js', 'JS(常用)'], ['text/html', '.html', 'HTML'], ['text/css', '.css', 'CSS'], ['text/plain', '.txt', '纯文本'],
['text/csv', '.csv', 'CSV'], ['text/markdown', '.md', 'Markdown'], ['application/pdf', '.pdf', 'PDF'],
['application/zip', '.zip', 'ZIP'], ['application/gzip', '.gz', 'gzip'], ['application/octet-stream', '.bin', '二进制流'],
['application/wasm', '.wasm', 'WebAssembly'], ['application/x-www-form-urlencoded', '—', '表单提交(默认)'],
['multipart/form-data', '—', '表单文件上传'], ['image/png', '.png', 'PNG'], ['image/jpeg', '.jpg', 'JPEG'],
['image/webp', '.webp', 'WebP'], ['image/avif', '.avif', 'AVIF'], ['image/gif', '.gif', 'GIF'], ['image/svg+xml', '.svg', 'SVG'],
['image/x-icon', '.ico', 'favicon'], ['font/woff2', '.woff2', 'WOFF2'], ['font/ttf', '.ttf', 'TrueType'],
['audio/mpeg', '.mp3', 'MP3'], ['audio/ogg', '.ogg', 'OGG 音频'], ['video/mp4', '.mp4', 'MP4'],
['video/webm', '.webm', 'WebM'], ['application/vnd.api+json', '.json', 'JSON:API'],
]
DB.tool({
id: 'http',
name: 'HTTP 状态码 & MIME',
group: 'web',
icon: 'globe',
desc: '常用状态码与 Content-Type 速查,带中英说明,可搜索',
keywords: ['http', 'status', 'code', 'mime', 'content-type', '状态码', '媒体类型'],
mount(root) {
const q = el('input', { type: 'search', placeholder: '搜索:404 / timeout / json / 图片…' })
const statList = el('div', { class: 'files' })
const mimeList = el('div', { class: 'files' })
const paint = () => {
const kw = q.value.trim().toLowerCase()
statList.textContent = ''
mimeList.textContent = ''
const sc = STATUS.filter(([c, en, zh]) => !kw || String(c).includes(kw) || en.toLowerCase().includes(kw) || zh.includes(kw))
const mc = MIME.filter(([m, ext, zh]) => !kw || m.includes(kw) || ext.includes(kw) || zh.includes(kw))
for (const [c, en, zh] of sc) {
const color = c < 200 ? 'var(--dim)' : c < 300 ? 'var(--good)' : c < 400 ? 'var(--accent-2)' : c < 500 ? 'var(--warn)' : 'var(--bad)'
const row = el('div', { class: 'file-row', style: { gridTemplateColumns: 'auto 1fr auto' } },
el('b', { text: String(c), style: { color, fontFamily: 'var(--mono)', fontSize: '14px', minWidth: '38px' } }),
el('div', { class: 'file-meta' }, el('b', { text: zh }), el('span', { text: en })),
el('button', { class: 'btn tiny', text: '复制', onclick: () => copy(`${c} ${en}`) }))
statList.append(row)
}
for (const [m, ext, zh] of mc) {
const row = el('div', { class: 'file-row', style: { gridTemplateColumns: '1fr auto' } },
el('div', { class: 'file-meta' }, el('b', { text: m }), el('span', { text: `${ext} · ${zh}` })),
el('button', { class: 'btn tiny', text: '复制', onclick: () => copy(m) }))
mimeList.append(row)
}
if (!sc.length) statList.append(el('div', { class: 'hint', text: '没有匹配的状态码' }))
if (!mc.length) mimeList.append(el('div', { class: 'hint', text: '没有匹配的 MIME' }))
}
q.addEventListener('input', DB.debounce(paint, 120))
const p1 = pane('查找')
p1.append(q)
const p2 = pane('HTTP 状态码')
p2.append(statList)
const p3 = pane('常见 Content-Type')
p3.append(mimeList)
root.append(p1, p2, p3)
paint()
},
})
/* ================= chmod ================= */
DB.tool({
id: 'chmod',
name: '文件权限 chmod',
group: 'web',
icon: 'terminal',
desc: '勾选框和八进制互转,顺手解释 rwx 与常见权限',
keywords: ['chmod', 'permission', 'rwx', '权限', '755', '644'],
mount(root) {
const state = { u: { r: true, w: true, x: true }, g: { r: true, w: false, x: true }, o: { r: true, w: false, x: true } }
const grid = el('div', {})
const octalIn = el('input', { type: 'text', value: '755', style: { fontFamily: 'var(--mono)', width: '110px' }, maxlength: 4 })
const symOut = el('div', { class: 'out', text: '-rwxr-xr-x' })
const desc = el('div', { class: 'hint' })
const octalOf = () => ['u', 'g', 'o'].map((w) => (state[w].r ? 4 : 0) + (state[w].w ? 2 : 0) + (state[w].x ? 1 : 0)).join('')
const symOf = () => '-' + ['u', 'g', 'o'].map((w) => (state[w].r ? 'r' : '-') + (state[w].w ? 'w' : '-') + (state[w].x ? 'x' : '-')).join('')
const paint = () => {
grid.textContent = ''
;[['u', '所有者'], ['g', '同组'], ['o', '其他人']].forEach(([w, label]) => {
const row = el('div', { class: 'row', style: { gap: '14px', margin: '6px 0' } }, el('span', { text: label, style: { width: '64px', color: 'var(--dim)', fontSize: '13px' } }))
;['r', 'w', 'x'].forEach((bit) => {
const box = el('input', { type: 'checkbox', checked: state[w][bit] })
box.addEventListener('change', () => { state[w][bit] = box.checked; paint() })
row.append(el('label', { class: 'check' }, box, el('span', { text: bit + '(' + ({ r: '读', w: '写', x: '执行' })[bit] + ')' })))
})
grid.append(row)
})
octalIn.value = octalOf()
symOut.textContent = symOf()
const oc = octalOf()
const map = { 777: '所有人可读写执行(危险)', 755: '所有人可读执行,只有主写', 750: '同组可读执行,其他人无权', 700: '只有自己能读写执行', 644: '所有人可读,只有主写', 640: '同组可读,其他人无权', 600: '只有自己可读写', 444: '所有人只读' }
desc.textContent = map[oc] || `八进制 ${oc} · 等价 ${symOf()}`
}
octalIn.addEventListener('input', () => {
const v = octalIn.value.replace(/[^0-7]/g, '')
if (v.length !== 3) return
const [u, g, o] = v.split('').map(Number)
;[['u', u], ['g', g], ['o', o]].forEach(([w, n]) => {
state[w].r = !!(n & 4); state[w].w = !!(n & 2); state[w].x = !!(n & 1)
})
paint()
})
const p1 = pane('勾选权限')
p1.append(grid)
const p2 = pane('结果')
p2.append(el('div', { class: 'row', style: { marginBottom: '10px' } }, el('span', { text: '八进制', style: { color: 'var(--dim)', fontSize: '13px' } }), octalIn, btn('复制 chmod 命令', () => copy('chmod ' + octalOf() + ' 文件名'))))
p2.append(symOut, desc)
root.append(p1, p2)
paint()
},
})
/* ================= IPv4 / CIDR ================= */
DB.tool({
id: 'ipv4',
name: 'IPv4 / CIDR 计算',
group: 'web',
icon: 'globe',
desc: '输入 IP 和掩码,算出网段、广播地址、可用主机范围',
keywords: ['ip', 'cidr', 'subnet', 'netmask', 'ipv4', '网段', '子网', '掩码'],
mount(root) {
const ipIn = el('input', { type: 'text', value: '192.168.1.10', style: { fontFamily: 'var(--mono)' } })
const prefixIn = el('input', { type: 'number', value: 24, min: 0, max: 32, style: { width: '90px' } })
const out = el('div', {})
const err = el('div', { class: 'err' })
const toInt = (ip) => {
const parts = ip.trim().split('.')
if (parts.length !== 4 || parts.some((p) => !/^\d{1,3}$/.test(p) || Number(p) > 255)) throw new Error('IPv4 格式不对')
return parts.reduce((a, p) => ((a << 8) | Number(p)) >>> 0, 0)
}
const toIp = (n) => [(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join('.')
const run = () => {
err.textContent = ''
out.textContent = ''
try {
const ip = toInt(ipIn.value)
const p = clamp(Number(prefixIn.value) || 0, 0, 32)
const mask = p === 0 ? 0 : (0xffffffff << (32 - p)) >>> 0
const net = (ip & mask) >>> 0
const bcast = (net | (~mask >>> 0)) >>> 0
const size = 2 ** (32 - p)
const first = p >= 31 ? net : net + 1
const last = p >= 31 ? bcast : bcast - 1
const priv = (net >>> 24) === 10 || (net >>> 20) === 0xac1 || (net >>> 16) === 0xc0a8 || (net >>> 8) === 0x7f00
const rows = [
['网络地址', toIp(net) + '/' + p],
['子网掩码', toIp(mask) + '(' + p + ' 位)'],
['通配符', toIp((~mask) >>> 0)],
['广播地址', toIp(bcast)],
['可用范围', p >= 31 ? toIp(net) + ' – ' + toIp(bcast) : toIp(first) + ' – ' + toIp(last)],
['可用主机', p >= 31 ? String(size) : String(Math.max(0, size - 2))],
['地址总数', String(size)],
['私有地址', priv ? '是(内网)' : '否'],
['网段写法', toIp(net) + '/' + p],
]
const dl = el('dl', { class: 'kv' })
for (const [k, v] of rows) dl.append(el('dt', { text: k }), el('dd', {}, el('span', { text: v }), el('button', { class: 'btn tiny', style: { marginLeft: '8px' }, text: '复制', onclick: () => copy(v) })))
out.append(dl)
} catch (e) { err.textContent = e.message }
}
onInput(ipIn, run, 200)
prefixIn.addEventListener('input', run)
const p1 = pane('地址')
p1.append(el('div', { class: 'row' }, el('div', { style: { flex: '1 1 200px' } }, ipIn), el('span', { text: '/', style: { color: 'var(--dim)' } }), prefixIn,
btn('常见掩码', null, 'ghost')))
const quick = el('div', { class: 'chip-list', style: { marginTop: '10px' } })
for (const pp of [8, 16, 24, 25, 28, 30, 32]) quick.append(el('button', { text: '/' + pp, onclick: () => { prefixIn.value = pp; run() } }))
p1.append(quick)
const p2 = pane('结果')
p2.append(err, out)
root.append(p1, p2)
run()
},
})
})()