- 新增 cat-file / cat-check2 / cat-zip / cat-misc2 / cat-net / cat-final 六个目录文件 - 内置 vendor:qrcode-generator、bcryptjs、marked(均 MIT),server.mjs 放行 /js/vendor/ - 首页加分类磁贴(带数量与说明,点一下筛到该分类),hero 文案区分本地/联网工具 - zip/tar 自写解析与打包,xlsx↔csv/json/html/md,docx/pptx/epub 抽文本,ttf→woff - 屏幕/色觉/散光/视力/摄像头/GPS/传感器/键盘/双击/轮询率等硬件自测 - 二维码 & WiFi 码 & vCard & bcrypt & Markdown 编辑器 - 我的 IP / IP 归属 / DNS(DoH) / 网速 / 响应测试(标注需联网) - README/INSTALL 更新:工具数、依赖说明、第六批清单
368 lines
29 KiB
JavaScript
368 lines
29 KiB
JavaScript
(function () {
|
||
const { el, panelTitle, copy, toast, bytes, download } = DB
|
||
const pane = (t, ...k) => { const p = el('div', { class: 'panel' }); if (t) p.append(panelTitle(t)); p.append(...k.filter(Boolean)); return p }
|
||
const btn = (l, f, c = '') => el('button', { class: 'btn ' + c, text: l, onclick: f })
|
||
const bufOf = (f) => new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = rej; r.readAsArrayBuffer(f) })
|
||
const picker = (multi, cb, accept) => { const i = el('input', { type: 'file', class: 'inp', multiple: !!multi }); if (accept) i.accept = accept; i.addEventListener('change', () => cb([...i.files])); return i }
|
||
const unz = async (u8) => { if (!window.DecompressionStream) throw new Error('浏览器不支持 DecompressionStream'); const ds = new DecompressionStream('deflate-raw'); const s = new Blob([u8]).stream().pipeThrough(ds); return new Uint8Array(await new Response(s).arrayBuffer()) }
|
||
const crcTable = (() => { 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 })()
|
||
const crc32 = (u8) => { let c = 0xffffffff; for (let i = 0; i < u8.length; i++) c = crcTable[(c ^ u8[i]) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0 }
|
||
|
||
/* 读取 ZIP(中央目录 + deflate-raw) */
|
||
async function unzip(u8) {
|
||
const dv = new DataView(u8.buffer, u8.byteOffset, u8.byteLength)
|
||
let eocd = -1
|
||
for (let i = u8.length - 22; i >= Math.max(0, u8.length - 66000); i--) { if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break } }
|
||
if (eocd < 0) throw new Error('不是有效的 ZIP 文件')
|
||
const count = dv.getUint16(eocd + 10, true)
|
||
let p = dv.getUint32(eocd + 16, true)
|
||
const out = []
|
||
for (let i = 0; i < count; i++) {
|
||
if (dv.getUint32(p, true) !== 0x02014b50) break
|
||
const method = dv.getUint16(p + 10, true)
|
||
const csize = dv.getUint32(p + 20, true)
|
||
const usize = dv.getUint32(p + 24, true)
|
||
const nlen = dv.getUint16(p + 28, true), elen = dv.getUint16(p + 30, true), clen = dv.getUint16(p + 32, true)
|
||
const off = dv.getUint32(p + 42, true)
|
||
const name = new TextDecoder().decode(u8.subarray(p + 46, p + 46 + nlen))
|
||
const dataStart = off + 30 + dv.getUint16(off + 26, true) + dv.getUint16(off + 28, true)
|
||
out.push({ name, method, csize, usize, dataStart })
|
||
p += 46 + nlen + elen + clen
|
||
}
|
||
return out
|
||
}
|
||
const entryData = async (u8, e) => { const raw = u8.subarray(e.dataStart, e.dataStart + e.csize); return e.method === 0 ? raw : unz(raw) }
|
||
|
||
/* 打包 ZIP(store,无压缩,兼容性最好) */
|
||
function makeZip(entries) {
|
||
const enc = new TextEncoder(); const parts = []; const central = []; let offset = 0
|
||
for (const { name, data } of entries) {
|
||
const nameU8 = enc.encode(name); const u8 = data instanceof Uint8Array ? data : new Uint8Array(data)
|
||
const crc = crc32(u8)
|
||
const local = new Uint8Array(30 + nameU8.length); const lv = new DataView(local.buffer)
|
||
lv.setUint32(0, 0x04034b50, true); lv.setUint16(4, 20, true); lv.setUint16(6, 0x0800, true); lv.setUint16(8, 0, true)
|
||
lv.setUint32(14, crc, true); lv.setUint32(18, u8.length, true); lv.setUint32(22, u8.length, true); lv.setUint16(26, nameU8.length, true)
|
||
local.set(nameU8, 30)
|
||
parts.push(local, u8)
|
||
const cd = new Uint8Array(46 + nameU8.length); const cv = new DataView(cd.buffer)
|
||
cv.setUint32(0, 0x02014b50, true); cv.setUint16(4, 20, true); cv.setUint16(6, 20, true); cv.setUint16(8, 0x0800, true); cv.setUint16(10, 0, true)
|
||
cv.setUint32(16, crc, true); cv.setUint32(20, u8.length, true); cv.setUint32(24, u8.length, true); cv.setUint16(28, nameU8.length, true)
|
||
cv.setUint32(42, offset, true); cd.set(nameU8, 46)
|
||
central.push(cd)
|
||
offset += local.length + u8.length
|
||
}
|
||
const cdSize = central.reduce((a, c) => a + c.length, 0)
|
||
const end = new Uint8Array(22); const ev = new DataView(end.buffer)
|
||
ev.setUint32(0, 0x06054b50, true); ev.setUint16(8, entries.length, true); ev.setUint16(10, entries.length, true)
|
||
ev.setUint32(12, cdSize, true); ev.setUint32(16, offset, true)
|
||
return new Blob([...parts, ...central, end], { type: 'application/zip' })
|
||
}
|
||
|
||
/* ZIP 预览 */
|
||
DB.tool({ id: 'zip-preview', name: '压缩包预览', group: 'web', icon: 'box', desc: '看 zip/xlsx/docx/epub 里都有什么', keywords: ['zip', '压缩包', '预览'],
|
||
mount(root) {
|
||
const out = el('div', { class: 'kv-out', text: '' })
|
||
const run = async (files) => {
|
||
if (!files[0]) return
|
||
try { const u8 = new Uint8Array(await bufOf(files[0])); const list = await unzip(u8)
|
||
const total = list.reduce((a, e) => a + e.usize, 0)
|
||
out.textContent = `${files[0].name}:${list.length} 个条目,解压后 ${bytes(total)}\n\n` + list.slice(0, 300).map((e) => `${bytes(e.usize).padStart(9)} ${e.name}`).join('\n')
|
||
} catch (e) { out.textContent = '解析失败:' + e.message }
|
||
}
|
||
root.append(pane('压缩包预览'), picker(false, run, '.zip,.xlsx,.docx,.pptx,.epub,.apk'), out)
|
||
} })
|
||
|
||
/* 解压 */
|
||
DB.tool({ id: 'extract-zip', name: '解压 ZIP', group: 'web', icon: 'box', desc: '在浏览器里解压,逐个下载', keywords: ['解压', 'unzip', 'zip'],
|
||
mount(root) {
|
||
const list = el('div', { class: 'kv-out', text: '' }); let cur = null
|
||
const run = async (files) => { if (!files[0]) return; try { cur = { u8: new Uint8Array(await bufOf(files[0])), entries: await unzip(new Uint8Array(await bufOf(files[0]))) }; list.textContent = cur.entries.map((e, i) => `${i + 1}. ${e.name}(${bytes(e.usize)})`).join('\n') } catch (e) { list.textContent = e.message } }
|
||
const all = async () => { if (!cur) return
|
||
for (const e of cur.entries.filter((x) => !x.name.endsWith('/'))) { try { const d = await entryData(cur.u8, e); download(new Blob([d]), e.name.split('/').pop()) } catch (err) {} } }
|
||
const one = async () => { if (!cur) return; const n = +(prompt('第几个文件?') || 0); const e = cur.entries[n - 1]; if (!e) return; download(new Blob([await entryData(cur.u8, e)]), e.name.split('/').pop()) }
|
||
root.append(pane('解压 ZIP'), picker(false, run, '.zip'), list, el('div', { class: 'row' }, btn('全部下载', all), btn('下载指定', one, 'ghost')))
|
||
} })
|
||
|
||
/* 打包 */
|
||
DB.tool({ id: 'create-zip', name: '打包成 ZIP', group: 'web', icon: 'box', desc: '多个文件打成一个 zip(不压缩)', keywords: ['打包', '压缩', 'zip'],
|
||
mount(root) {
|
||
const st = el('div', { class: 'kv-out', text: '' }); let picked = []
|
||
const run = (files) => { picked = files; st.textContent = files.map((f) => `${f.name}(${bytes(f.size)})`).join('\n') || '' }
|
||
const go = async () => { if (!picked.length) return toast('先选文件', true)
|
||
const entries = []
|
||
for (const f of picked) entries.push({ name: f.name, data: new Uint8Array(await bufOf(f)) })
|
||
download(makeZip(entries), 'devbox-' + Date.now() + '.zip') }
|
||
root.append(pane('打包成 ZIP'), picker(true, run), st, btn('打包下载', go))
|
||
} })
|
||
|
||
/* TAR */
|
||
async function untar(u8) {
|
||
const out = []; let off = 0
|
||
while (off + 512 <= u8.length) {
|
||
const block = u8.subarray(off, off + 512)
|
||
if (block.every((b) => b === 0)) break
|
||
const name = new TextDecoder().decode(block.subarray(0, 100)).replace(/\0.*$/, '')
|
||
const sizeStr = new TextDecoder().decode(block.subarray(124, 136)).replace(/\0.*$/, '').trim()
|
||
const size = parseInt(sizeStr, 8) || 0
|
||
const type = String.fromCharCode(block[156] || 48)
|
||
off += 512
|
||
if (type === '0' || type === '\0' || type === '48') out.push({ name, size, data: u8.subarray(off, off + size) })
|
||
off += Math.ceil(size / 512) * 512
|
||
}
|
||
return out
|
||
}
|
||
DB.tool({ id: 'extract-tar', name: '解压 TAR', group: 'web', icon: 'box', desc: '解 .tar 文件(不含 tar.gz)', keywords: ['tar', '解压'],
|
||
mount(root) {
|
||
const out = el('div', { class: 'kv-out', text: '' })
|
||
const run = async (files) => { if (!files[0]) return; const list = await untar(new Uint8Array(await bufOf(files[0])))
|
||
out.textContent = list.map((e) => `${bytes(e.size).padStart(9)} ${e.name}`).join('\n') || '没读到条目(可能是 tar.gz,先用 gzip-crc 解压)' }
|
||
root.append(pane('解压 TAR'), picker(false, run, '.tar'), out)
|
||
} })
|
||
DB.tool({ id: 'create-tar', name: '打包 TAR', group: 'web', icon: 'box', desc: '多文件打成 .tar', keywords: ['tar', '打包'],
|
||
mount(root) {
|
||
let picked = []
|
||
const go = async () => {
|
||
if (!picked.length) return toast('先选文件', true)
|
||
const enc = new TextEncoder(); const parts = []
|
||
for (const f of picked) {
|
||
const data = new Uint8Array(await bufOf(f)); const h = new Uint8Array(512)
|
||
h.set(enc.encode(f.name).subarray(0, 100), 0)
|
||
h.set(enc.encode((0o644).toString(8).padStart(7, '0')), 100)
|
||
h.set(enc.encode(Math.floor(f.lastModified / 1000).toString(8).padStart(11, '0')), 136)
|
||
h.set(enc.encode(data.length.toString(8).padStart(11, '0')), 124)
|
||
h.set(enc.encode('0'), 156)
|
||
let sum = 0; for (const b of h) sum += b
|
||
h.set(enc.encode(sum.toString(8).padStart(6, '0') + '\0 '), 148)
|
||
parts.push(h, data, new Uint8Array((512 - data.length % 512) % 512))
|
||
}
|
||
parts.push(new Uint8Array(1024))
|
||
download(new Blob(parts, { type: 'application/x-tar' }), 'devbox-' + Date.now() + '.tar')
|
||
}
|
||
root.append(pane('打包 TAR'), picker(true, (f) => { picked = f; toast('已选 ' + f.length + ' 个') }), btn('打包下载', go))
|
||
} })
|
||
|
||
/* 7z / rar 识别 */
|
||
function unsupported(id, name, sig, tip) {
|
||
DB.tool({ id, name, group: 'web', icon: 'box', desc: '识别文件头并给出处理建议(浏览器内不解压)', keywords: [name, '解压'], mount(root) {
|
||
const out = el('div', { class: 'kv-out', text: '' })
|
||
root.append(pane(name), picker(false, async (files) => { if (!files[0]) return
|
||
const head = [...new Uint8Array(await bufOf(files[0])).slice(0, 8)].map((b) => b.toString(16).padStart(2, '0')).join(' ')
|
||
out.textContent = `文件:${files[0].name}(${bytes(files[0].size)})\n文件头:${head}\n${head.startsWith(sig) ? '格式识别正确 ✓' : '文件头与预期不符'}\n\n${tip}` }, '*'), out)
|
||
} })
|
||
}
|
||
unsupported('extract-7z', '7Z 识别', '37 7a bc af', '浏览器无法解 7z 的 LZMA 容器,请在电脑上用 7-Zip 解开后再拖进来处理。')
|
||
unsupported('extract-rar', 'RAR 识别', '52 61 72 21', 'RAR 是专有格式,浏览器无法解压;用 WinRAR / 7-Zip 解开。')
|
||
|
||
/* 分卷 */
|
||
DB.tool({ id: 'split-zip', name: '文件分卷', group: 'web', icon: 'box', desc: '把大文件切成若干份', keywords: ['分卷', '切分', 'split'],
|
||
mount(root) {
|
||
const size = el('input', { type: 'number', class: 'inp', value: 10, min: 1 })
|
||
let cur = null; const st = el('div', { class: 'kv-out', text: '' })
|
||
const run = (files) => { cur = files[0]; if (cur) st.textContent = `${cur.name}(${bytes(cur.size)}),每份 ${size.value} MB` }
|
||
const go = async () => { if (!cur) return; const u8 = new Uint8Array(await bufOf(cur)); const step = (+size.value || 10) * 1024 * 1024
|
||
for (let i = 0, n = 0; i < u8.length; i += step, n++) download(new Blob([u8.subarray(i, i + step)]), `${cur.name}.part${String(n + 1).padStart(2, '0')}`) }
|
||
root.append(pane('文件分卷'), picker(false, run), el('div', { class: 'row' }, el('label', { text: '每份 MB' }), size), st, btn('切分并下载', go))
|
||
} })
|
||
|
||
/* XLSX 解析 */
|
||
function parseSheet(xml, shared) {
|
||
const rows = []
|
||
const rowRe = /<row[^>]*>([\s\S]*?)<\/row>/g
|
||
let m
|
||
while ((m = rowRe.exec(xml))) {
|
||
const cells = []
|
||
const cRe = /<c[^>]*?(?:r="([A-Z]+)\d+")?[^>]*?(?:t="(\w+)")?[^>]*?(?:>([\s\S]*?)<\/c>|\/>)/g
|
||
let c
|
||
while ((c = cRe.exec(m[1]))) {
|
||
const col = c[1] ? c[1].charCodeAt(0) - 65 : cells.length
|
||
const type = c[2]
|
||
const inner = c[3] || ''
|
||
const v = (inner.match(/<v>([\s\S]*?)<\/v>/) || [])[1]
|
||
const is = (inner.match(/<is>[\s\S]*?<t[^>]*>([\s\S]*?)<\/t>/) || [])[1]
|
||
let val = ''
|
||
if (type === 's' && v != null) val = shared[+v] ?? ''
|
||
else if (is != null) val = is
|
||
else if (v != null) val = v
|
||
while (cells.length < col) cells.push('')
|
||
cells[col] = val
|
||
}
|
||
rows.push(cells)
|
||
}
|
||
return rows
|
||
}
|
||
async function readXlsx(file) {
|
||
const u8 = new Uint8Array(await bufOf(file)); const entries = await unzip(u8)
|
||
const get = async (name) => { const e = entries.find((x) => x.name === name); return e ? new TextDecoder().decode(await entryData(u8, e)) : '' }
|
||
const sharedXml = await get('xl/sharedStrings.xml')
|
||
const shared = [...sharedXml.matchAll(/<si>[\s\S]*?<t[^>]*>([\s\S]*?)<\/t>[\s\S]*?<\/si>/g)].map((m) => m[1])
|
||
const sheets = entries.filter((e) => /^xl\/worksheets\/sheet\d+\.xml$/.test(e.name))
|
||
const out = []
|
||
for (const s of sheets) out.push({ name: s.name.replace(/.*\//, ''), rows: parseSheet(new TextDecoder().decode(await entryData(u8, s)), shared) })
|
||
return out
|
||
}
|
||
const toCSV = (rows) => rows.map((r) => r.map((c) => (/[",\n]/.test(c) ? '"' + c.replace(/"/g, '""') + '"' : c)).join(',')).join('\n')
|
||
|
||
function xlsTool(id, name, desc, fn, keywords) {
|
||
DB.tool({ id, name, group: 'format', icon: 'table', desc, keywords: keywords || ['excel', 'xlsx'], mount(root) {
|
||
const out = el('div', { class: 'kv-out', text: '' })
|
||
const run = async (files) => { if (!files[0]) return
|
||
try { const sheets = await readXlsx(files[0]); out.textContent = fn(sheets)
|
||
if (fn.download) {} } catch (e) { out.textContent = '解析失败:' + e.message } }
|
||
root.append(pane(name), picker(false, run, '.xlsx'), out, btn('复制结果', () => copy(out.textContent), 'ghost'))
|
||
} })
|
||
}
|
||
xlsTool('excel-to-csv', 'Excel 转 CSV', '每个工作表输出一段 CSV', (sheets) => sheets.map((s) => `# ${s.name}\n` + toCSV(s.rows)).join('\n\n'))
|
||
xlsTool('xlsx-to-json', 'Excel 转 JSON(xlsx)', '第一行当表头,输出对象数组', (sheets) => sheets.map((s) => { const [head, ...rest] = s.rows; const arr = rest.map((r) => Object.fromEntries(head.map((h, i) => [h || '列' + (i + 1), r[i] ?? '']))); return `// ${s.name}\n` + JSON.stringify(arr, null, 2) }).join('\n\n'))
|
||
xlsTool('excel-to-html', 'Excel 转 HTML', '生成可直接粘进网页的表格', (sheets) => sheets.map((s) => `<!-- ${s.name} -->\n<table border="1">\n` + s.rows.map((r, i) => '<tr>' + r.map((c) => (i ? `<td>${c}</td>` : `<th>${c}</th>`)).join('') + '</tr>').join('\n') + '\n</table>').join('\n\n'))
|
||
xlsTool('excel-to-markdown', 'Excel 转 Markdown', '生成 Markdown 表格', (sheets) => sheets.map((s) => { const [h, ...r] = s.rows; if (!h) return ''; return `### ${s.name}\n| ` + h.join(' | ') + ' |\n| ' + h.map(() => '---').join(' | ') + ' |\n' + r.map((row) => '| ' + row.join(' | ') + ' |').join('\n') }).join('\n\n'))
|
||
xlsTool('excel-merge', 'Excel 多表合并', '把多个工作表按行拼起来', (sheets) => { const head = sheets[0]?.rows[0] || []; const rows = sheets.flatMap((s) => s.rows.slice(1)); return toCSV([head, ...rows]) })
|
||
xlsTool('excel-split', 'Excel 拆表', '每个工作表单独输出 CSV', (sheets) => sheets.map((s) => `=== ${s.name} ===\n` + toCSV(s.rows)).join('\n\n'))
|
||
|
||
/* 生成 xlsx */
|
||
DB.tool({ id: 'json-to-excel', name: 'JSON 转 Excel', group: 'format', icon: 'table', desc: '对象数组生成可直接打开的 .xlsx', keywords: ['xlsx', 'excel', '导出'],
|
||
mount(root) {
|
||
const inp = el('textarea', { class: 'ta', rows: 8, placeholder: '[{"名称":"A","数量":1}]' })
|
||
const st = el('div', { class: 'kv-out', text: '' })
|
||
const go = () => {
|
||
let data; try { data = JSON.parse(inp.value) } catch (e) { st.textContent = 'JSON 有问题:' + e.message; return }
|
||
if (!Array.isArray(data)) data = [data]
|
||
const head = [...new Set(data.flatMap((o) => Object.keys(o)))]
|
||
const esc = (s) => String(s ?? '').replace(/&/g, '&').replace(/</g, '<')
|
||
const rows = [head, ...data.map((o) => head.map((h) => o[h]))]
|
||
let body = ''
|
||
rows.forEach((r, ri) => { body += `<row r="${ri + 1}">` + r.map((c, ci) => `<c r="${String.fromCharCode(65 + ci)}${ri + 1}" t="inlineStr"><is><t>${esc(c)}</t></is></c>`).join('') + '</row>' })
|
||
const files = {
|
||
'[Content_Types].xml': `<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>`,
|
||
'_rels/.rels': `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`,
|
||
'xl/workbook.xml': `<?xml version="1.0"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>`,
|
||
'xl/_rels/workbook.xml.rels': `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>`,
|
||
'xl/worksheets/sheet1.xml': `<?xml version="1.0"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${body}</sheetData></worksheet>`,
|
||
}
|
||
const enc = new TextEncoder()
|
||
const blob = makeZip(Object.entries(files).map(([name, text]) => ({ name, data: enc.encode(text) })))
|
||
download(blob, 'data.xlsx'); st.textContent = `已生成 ${data.length} 行 × ${head.length} 列`
|
||
}
|
||
root.append(pane('JSON 转 Excel'), inp, st, btn('生成并下载', go))
|
||
} })
|
||
DB.tool({ id: 'csv-to-excel', name: 'CSV 转 Excel', group: 'format', icon: 'table', desc: '粘贴或选 CSV,导出 .xlsx', keywords: ['csv', 'xlsx'],
|
||
mount(root) {
|
||
const inp = el('textarea', { class: 'ta', rows: 8, placeholder: 'a,b,c\n1,2,3' })
|
||
const st = el('div', { class: 'kv-out', text: '' })
|
||
const go = () => {
|
||
const rows = inp.value.trim().split('\n').map((l) => l.split(','))
|
||
const esc = (s) => String(s ?? '').replace(/&/g, '&').replace(/</g, '<')
|
||
let body = ''
|
||
rows.forEach((r, ri) => { body += `<row r="${ri + 1}">` + r.map((c, ci) => `<c r="${String.fromCharCode(65 + ci)}${ri + 1}" t="inlineStr"><is><t>${esc(c)}</t></is></c>`).join('') + '</row>' })
|
||
const files = {
|
||
'[Content_Types].xml': `<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>`,
|
||
'_rels/.rels': `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`,
|
||
'xl/workbook.xml': `<?xml version="1.0"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>`,
|
||
'xl/worksheets/sheet1.xml': `<?xml version="1.0"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${body}</sheetData></worksheet>`,
|
||
}
|
||
const enc = new TextEncoder()
|
||
download(makeZip(Object.entries(files).map(([name, text]) => ({ name, data: enc.encode(text) }))), 'data.xlsx')
|
||
st.textContent = `已生成 ${rows.length} 行(Excel 可能需要点“是”修复 rels,属正常)`
|
||
}
|
||
root.append(pane('CSV 转 Excel'), inp, st, btn('生成并下载', go))
|
||
} })
|
||
|
||
/* DOCX / PPTX / EPUB 文本抽取 */
|
||
async function docText(u8) {
|
||
const entries = await unzip(u8)
|
||
const pick = async (re) => { const e = entries.find((x) => re.test(x.name)); return e ? new TextDecoder().decode(await entryData(u8, e)) : '' }
|
||
const main = await pick(/^word\/document\.xml$/)
|
||
if (main) return { kind: 'docx', xml: main }
|
||
const slideNames = entries.filter((e) => /^ppt\/slides\/slide\d+\.xml$/.test(e.name)).sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }))
|
||
if (slideNames.length) { let t = ''; for (const s of slideNames) t += `--- ${s.name.replace(/.*\//, '')} ---\n` + new TextDecoder().decode(await entryData(u8, s)) + '\n'; return { kind: 'pptx', xml: t } }
|
||
const chapter = entries.filter((e) => /\.x?html?$/.test(e.name))
|
||
if (chapter.length) { let t = ''; for (const c of chapter) t += new TextDecoder().decode(await entryData(u8, c)) + '\n'; return { kind: 'epub', xml: t } }
|
||
throw new Error('这个包里没找到可读的正文')
|
||
}
|
||
const stripTags = (xml) => xml.replace(/<w:p[^>]*>/g, '\n').replace(/<a:p>/g, '\n').replace(/<[^>]+>/g, '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/\n{3,}/g, '\n\n').trim()
|
||
|
||
function docTool(id, name, desc, mode) {
|
||
DB.tool({ id, name, group: 'format', icon: 'file', desc, keywords: ['docx', 'word', 'pptx', 'epub'], mount(root) {
|
||
const out = el('div', { class: 'kv-out', text: '' })
|
||
const run = async (files) => { if (!files[0]) return
|
||
try { const { kind, xml } = await docText(new Uint8Array(await bufOf(files[0])))
|
||
const text = stripTags(xml)
|
||
if (mode === 'txt') out.textContent = text
|
||
else if (mode === 'html') out.textContent = `<article>\n` + text.split('\n').filter(Boolean).map((l) => `<p>${l}</p>`).join('\n') + '\n</article>'
|
||
else out.textContent = text.split('\n').filter(Boolean).map((l) => (l.length < 20 ? '## ' + l : l)).join('\n\n')
|
||
out.dataset.kind = kind
|
||
} catch (e) { out.textContent = '读取失败:' + e.message } }
|
||
root.append(pane(name), picker(false, run, '.docx,.pptx,.epub'), out, el('div', { class: 'row' }, btn('复制', () => copy(out.textContent), 'ghost'), btn('下载 .txt', () => download(new Blob([out.textContent], { type: 'text/plain' }), 'text.txt'), 'ghost')))
|
||
} })
|
||
}
|
||
docTool('word-to-txt', 'Word 转纯文本', 'docx 里抽出正文(保留段落换行)', 'txt')
|
||
docTool('word-to-html', 'Word 转 HTML', 'docx 段落转 <p> 标签', 'html')
|
||
docTool('pptx-to-txt', 'PPT 转文本', '抽出每页文字', 'txt')
|
||
docTool('epub-to-txt', 'EPUB 转文本', '抽出全部章节文字', 'txt')
|
||
DB.tool({ id: 'epub-reader', name: 'EPUB 阅读', group: 'format', icon: 'book', desc: '在线翻页读 epub 章节', keywords: ['epub', '阅读', '电子书'],
|
||
mount(root) {
|
||
const out = el('div', { class: 'kv-out', text: '' }); const nav = el('div', { class: 'row' })
|
||
let chapters = [], idx = 0
|
||
const paint = () => { out.textContent = chapters[idx] || '' }
|
||
const run = async (files) => { if (!files[0]) return
|
||
try { const u8 = new Uint8Array(await bufOf(files[0])); const entries = await unzip(u8)
|
||
chapters = []
|
||
for (const e of entries.filter((x) => /\.x?html?$/.test(x.name)).sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }))) {
|
||
const t = stripTags(new TextDecoder().decode(await entryData(u8, e)))
|
||
if (t.length > 40) chapters.push(t)
|
||
}
|
||
idx = 0; nav.textContent = ''
|
||
nav.append(el('span', { class: 'hint', text: `共 ${chapters.length} 章` }), btn('上一章', () => { idx = Math.max(0, idx - 1); paint() }, 'ghost'), btn('下一章', () => { idx = Math.min(chapters.length - 1, idx + 1); paint() }, 'ghost'))
|
||
paint()
|
||
} catch (e) { out.textContent = '读取失败:' + e.message } }
|
||
root.append(pane('EPUB 阅读'), picker(false, run, '.epub'), out, nav)
|
||
} })
|
||
|
||
/* 文本转 Word(HTML .doc) */
|
||
DB.tool({ id: 'txt-to-word', name: '文本转 Word', group: 'office', icon: 'file', desc: '生成 .doc,Word/WPS 都能打开', keywords: ['word', 'doc', '导出'],
|
||
mount(root) {
|
||
const inp = el('textarea', { class: 'ta', rows: 8, placeholder: '正文…' })
|
||
const go = () => { const html = `<html xmlns:o="urn:schemas-microsoft-com:office:office"><head><meta charset="utf-8"><title>文档</title></head><body style="font-family:宋体;font-size:12pt">` +
|
||
inp.value.split('\n').map((l) => `<p style="margin:0 0 8pt">${l || ' '}</p>`).join('') + '</body></html>'
|
||
download(new Blob([html], { type: 'application/msword' }), 'document.doc') }
|
||
root.append(pane('文本转 Word'), inp, btn('下载 .doc', go))
|
||
} })
|
||
|
||
/* 字体:TTF → WOFF(zlib 压缩表) */
|
||
DB.tool({ id: 'ttf-to-woff2', name: '字体压缩(TTF→WOFF)', group: 'web', icon: 'box', desc: '浏览器内把 ttf/otf 压成 woff,体积约减半', keywords: ['字体', 'woff', 'ttf'],
|
||
mount(root) {
|
||
const out = el('div', { class: 'kv-out', text: '' })
|
||
const run = async (files) => { if (!files[0]) return
|
||
try {
|
||
const u8 = new Uint8Array(await bufOf(files[0])); const dv = new DataView(u8.buffer)
|
||
const flavor = dv.getUint32(0, false); const numTables = dv.getUint16(4, false)
|
||
const tables = []
|
||
for (let i = 0; i < numTables; i++) { const p = 12 + i * 16
|
||
tables.push({ tag: u8.subarray(p, p + 4), check: dv.getUint32(p + 4, false), offset: dv.getUint32(p + 8, false), length: dv.getUint32(p + 12, false) }) }
|
||
const chunks = [] ; const entries = []
|
||
let off = 44 + numTables * 20
|
||
for (const t of [...tables].sort((a, b) => String.fromCharCode(...a.tag).localeCompare(String.fromCharCode(...b.tag)))) {
|
||
const data = u8.subarray(t.offset, t.offset + t.length)
|
||
let comp = data
|
||
try { const cs = new CompressionStream('deflate'); comp = new Uint8Array(await new Response(new Blob([data]).stream().pipeThrough(cs)).arrayBuffer()) } catch (e) {}
|
||
const h = new Uint8Array(20); const hv = new DataView(h.buffer)
|
||
h.set(t.tag, 0); hv.setUint32(4, off, false); hv.setUint32(8, comp.length, false); hv.setUint32(12, t.length, false); hv.setUint32(16, t.check, false)
|
||
entries.push(h, comp.length === t.length ? new Uint8Array(0) : new Uint8Array(0))
|
||
chunks.push({ h, comp, orig: t.length })
|
||
off += comp.length + ((4 - comp.length % 4) % 4)
|
||
}
|
||
const head = new Uint8Array(44); const hv = new DataView(head.buffer)
|
||
head.set(new TextEncoder().encode('wOFF'), 0); hv.setUint32(4, flavor, false); hv.setUint32(8, off, false)
|
||
hv.setUint16(12, numTables, false); hv.setUint32(16, u8.length, false); hv.setUint32(20, 1, false)
|
||
const parts = [head]
|
||
for (const e of entries) parts.push(e)
|
||
for (const c of chunks) { parts.push(c.comp); const pad = (4 - c.comp.length % 4) % 4; if (pad) parts.push(new Uint8Array(pad)) }
|
||
const blob = new Blob(parts, { type: 'font/woff' })
|
||
download(blob, (files[0].name || 'font').replace(/\.(ttf|otf)$/i, '') + '.woff')
|
||
out.textContent = `已转换:${bytes(files[0].size)} → ${bytes(blob.size)}`
|
||
} catch (e) { out.textContent = '转换失败:' + e.message } }
|
||
root.append(pane('字体压缩'), picker(false, run, '.ttf,.otf'), out, el('p', { class: 'hint', text: '输出 WOFF1,所有现代浏览器都支持;woff2 需要 Brotli,浏览器内做不了。' }))
|
||
} })
|
||
DB.tool({ id: 'font-subset', name: '字体子集提示', group: 'web', icon: 'box', desc: '中文字体按字数裁子集的做法说明', keywords: ['字体', '子集', 'subset'],
|
||
mount(root) { root.append(pane('字体子集'), el('div', { class: 'kv-out', text: '浏览器里做子集需要解析 glyf/CFF 表,太重。\n\n推荐做法:\n1) 本地用 pyftsubset 生成:pyftsubset in.ttf --text-file=chars.txt --flavor=woff2 --output-file=out.woff2\n2) 或用 fontmin / glyphhanger\n\n如果只是想减体积,先用「字体压缩」把 ttf 转成 woff。' })) } })
|
||
})()
|