|
| 1 | +'use strict'; |
| 2 | +const $ = id => document.getElementById(id); |
| 3 | +const codec = window.Base64Codec; |
| 4 | +let mode = 'encode'; |
| 5 | +let source = 'text'; |
| 6 | +let selected = null; |
| 7 | +let result = null; |
| 8 | +let sourceUrl = ''; |
| 9 | +let resultUrl = ''; |
| 10 | +let revision = 0; |
| 11 | +let selectionRevision = 0; |
| 12 | +let timer; |
| 13 | +let toastTimer; |
| 14 | +const drafts = { encode: '', decode: '' }; |
| 15 | + |
| 16 | +function sizeLabel(size) { |
| 17 | + return size < 1024 ? `${size} B` : size < 1024 * 1024 ? `${(size / 1024).toFixed(1)} KB` : `${(size / 1024 / 1024).toFixed(2)} MB`; |
| 18 | +} |
| 19 | +function notify(message) { |
| 20 | + $('status').textContent = message; |
| 21 | + $('status').classList.add('visible'); |
| 22 | + clearTimeout(toastTimer); |
| 23 | + toastTimer = setTimeout(() => $('status').classList.remove('visible'), 3000); |
| 24 | +} |
| 25 | +function revokeResult() { |
| 26 | + if (resultUrl) URL.revokeObjectURL(resultUrl); |
| 27 | + resultUrl = ''; |
| 28 | + $('decoded-preview').removeAttribute('src'); |
| 29 | +} |
| 30 | +function resetResult() { |
| 31 | + revision++; |
| 32 | + clearTimeout(timer); |
| 33 | + result = null; |
| 34 | + revokeResult(); |
| 35 | + $('output').value = ''; |
| 36 | + for (const id of ['output', 'image-result', 'error', 'save']) $(id).hidden = true; |
| 37 | + $('empty-result').hidden = false; |
| 38 | + $('copy').disabled = true; |
| 39 | + $('copy').textContent = '复制结果'; |
| 40 | + $('output-count').textContent = '等待输入'; |
| 41 | + $('result-type').textContent = mode === 'encode' ? 'BASE64' : '自动识别'; |
| 42 | +} |
| 43 | +function renderMode() { |
| 44 | + const encode = mode === 'encode'; |
| 45 | + const image = encode && source === 'image'; |
| 46 | + for (const value of ['encode', 'decode']) { |
| 47 | + $(`${value}-mode`).classList.toggle('active', mode === value); |
| 48 | + $(`${value}-mode`).setAttribute('aria-pressed', String(mode === value)); |
| 49 | + } |
| 50 | + for (const value of ['text', 'image']) { |
| 51 | + $(`${value}-source`).classList.toggle('active', source === value); |
| 52 | + $(`${value}-source`).setAttribute('aria-pressed', String(source === value)); |
| 53 | + } |
| 54 | + $('source-controls').hidden = !encode; |
| 55 | + $('input').hidden = image; |
| 56 | + $('image-input').hidden = !image; |
| 57 | + $('output-options').hidden = !image; |
| 58 | + $('input-title').textContent = encode ? '原始内容' : 'Base64 内容'; |
| 59 | + $('output-title').textContent = encode ? '编码结果' : '解码结果'; |
| 60 | + $('input').placeholder = encode ? '在这里输入或粘贴文本…\n\n支持中文、Emoji 和多行文本。' : '在这里粘贴 Base64…\n\n支持纯 Base64 或 data:image/…;base64,…\n图片将自动显示预览。'; |
| 61 | + $('input-help').textContent = image ? '保留原图格式与质量' : encode ? '文本使用 UTF-8 编码' : '自动忽略空格与换行'; |
| 62 | + $('input-count').textContent = image ? selected ? sizeLabel(selected.bytes.length) : '未选择图片' : `${$('input').value.length.toLocaleString()} 字符`; |
| 63 | + $('pick-image').hidden = !!selected; |
| 64 | + $('selected-image').hidden = !selected; |
| 65 | +} |
| 66 | +function changeMode(next) { |
| 67 | + if (mode !== next) { |
| 68 | + drafts[mode] = $('input').value; |
| 69 | + mode = next; |
| 70 | + $('input').value = drafts[mode]; |
| 71 | + selectionRevision++; |
| 72 | + } |
| 73 | + renderMode(); |
| 74 | + convert(); |
| 75 | +} |
| 76 | +function changeSource(next) { |
| 77 | + source = next; |
| 78 | + selectionRevision++; |
| 79 | + renderMode(); |
| 80 | + convert(); |
| 81 | +} |
| 82 | +function showError(error) { |
| 83 | + $('empty-result').hidden = true; |
| 84 | + $('error').hidden = false; |
| 85 | + $('error').textContent = error.message || '转换失败,请检查输入内容。'; |
| 86 | + $('output-count').textContent = '请检查内容'; |
| 87 | +} |
| 88 | +function convert() { |
| 89 | + resetResult(); |
| 90 | + const current = revision; |
| 91 | + try { |
| 92 | + if (mode === 'encode') { |
| 93 | + if (source === 'image' && !selected || source === 'text' && !$('input').value) return; |
| 94 | + const text = source === 'image' ? ($('data-url').checked ? `data:${selected.mime};base64,` : '') + selected.base64 : codec.encodeText($('input').value); |
| 95 | + result = { kind: 'text', text }; |
| 96 | + $('output').value = text; |
| 97 | + $('output').hidden = false; |
| 98 | + $('output-count').textContent = `${text.length.toLocaleString()} 字符`; |
| 99 | + } else { |
| 100 | + if (!$('input').value.trim()) return; |
| 101 | + result = codec.decode($('input').value); |
| 102 | + if (result.kind === 'image') { |
| 103 | + const imageResult = result; |
| 104 | + $('result-type').textContent = result.extension.toUpperCase(); |
| 105 | + $('image-result').hidden = false; |
| 106 | + $('save').hidden = false; |
| 107 | + $('copy').textContent = '复制 Base64'; |
| 108 | + $('output-count').textContent = sizeLabel(result.bytes.length); |
| 109 | + $('image-meta').textContent = `${result.mime} · 正在加载预览…`; |
| 110 | + const img = $('decoded-preview'); |
| 111 | + img.onload = () => { |
| 112 | + if (current !== revision) return; |
| 113 | + $('image-meta').textContent = `${img.naturalWidth} × ${img.naturalHeight} px · ${imageResult.mime} · ${sizeLabel(imageResult.bytes.length)}`; |
| 114 | + }; |
| 115 | + img.onerror = () => { |
| 116 | + if (current !== revision) return; |
| 117 | + $('image-meta').textContent = '图片数据已识别,但预览失败;可能文件损坏或当前环境不支持此格式。仍可保存原文件。'; |
| 118 | + }; |
| 119 | + resultUrl = URL.createObjectURL(new Blob([result.bytes], { type: result.mime })); |
| 120 | + img.src = resultUrl; |
| 121 | + } else { |
| 122 | + $('result-type').textContent = 'UTF-8'; |
| 123 | + $('output').hidden = false; |
| 124 | + $('output').value = result.text; |
| 125 | + $('output-count').textContent = `${result.text.length.toLocaleString()} 字符 · ${sizeLabel(result.bytes.length)}`; |
| 126 | + } |
| 127 | + } |
| 128 | + $('empty-result').hidden = true; |
| 129 | + $('copy').disabled = false; |
| 130 | + } catch (error) { showError(error); } |
| 131 | +} |
| 132 | +async function selectImage(file) { |
| 133 | + if (!file) return; |
| 134 | + if (mode !== 'encode') changeMode('encode'); |
| 135 | + source = 'image'; |
| 136 | + const current = ++selectionRevision; |
| 137 | + selected = null; |
| 138 | + if (sourceUrl) URL.revokeObjectURL(sourceUrl); |
| 139 | + sourceUrl = ''; |
| 140 | + $('source-preview').removeAttribute('src'); |
| 141 | + resetResult(); |
| 142 | + renderMode(); |
| 143 | + try { |
| 144 | + codec.checkSize(file.size); |
| 145 | + const bytes = new Uint8Array(typeof file.arrayBuffer === 'function' ? await file.arrayBuffer() : file.bytes); |
| 146 | + if (current !== selectionRevision) return; |
| 147 | + const mime = codec.imageMime(bytes); |
| 148 | + if (!mime) throw new Error('无法识别此图片,请选择 PNG、JPG、GIF、WebP、BMP、ICO、AVIF 或 SVG。'); |
| 149 | + selected = { bytes, mime, base64: codec.encodeBytes(bytes) }; |
| 150 | + sourceUrl = URL.createObjectURL(new Blob([bytes], { type: mime })); |
| 151 | + $('source-preview').src = sourceUrl; |
| 152 | + $('source-preview').onerror = () => { if (current === selectionRevision) notify('当前环境无法预览此图片,仍可编码和保存原始数据。'); }; |
| 153 | + $('file-info').textContent = `${file.name || '粘贴的图片'} · ${sizeLabel(bytes.length)}`; |
| 154 | + renderMode(); |
| 155 | + convert(); |
| 156 | + } catch (error) { if (current === selectionRevision) showError(error); } |
| 157 | +} |
| 158 | +$('encode-mode').onclick = () => changeMode('encode'); |
| 159 | +$('decode-mode').onclick = () => changeMode('decode'); |
| 160 | +$('text-source').onclick = () => changeSource('text'); |
| 161 | +$('image-source').onclick = () => changeSource('image'); |
| 162 | +$('data-url').onchange = convert; |
| 163 | +$('input').addEventListener('input', () => { |
| 164 | + drafts[mode] = $('input').value; |
| 165 | + renderMode(); |
| 166 | + resetResult(); |
| 167 | + timer = setTimeout(convert, 250); |
| 168 | +}); |
| 169 | +$('clear').onclick = () => { |
| 170 | + selectionRevision++; |
| 171 | + $('input').value = ''; |
| 172 | + drafts[mode] = ''; |
| 173 | + if (mode === 'encode') { |
| 174 | + selected = null; |
| 175 | + if (sourceUrl) URL.revokeObjectURL(sourceUrl); |
| 176 | + sourceUrl = ''; |
| 177 | + $('source-preview').removeAttribute('src'); |
| 178 | + $('file-input').value = ''; |
| 179 | + } |
| 180 | + resetResult(); |
| 181 | + renderMode(); |
| 182 | +}; |
| 183 | +async function pickImage() { |
| 184 | + // 网页预览使用 HTML file input;ZTools 必须走宿主的防失焦对话框。 |
| 185 | + if (!window.ztools) { |
| 186 | + $('file-input').click(); |
| 187 | + return; |
| 188 | + } |
| 189 | + const current = selectionRevision; |
| 190 | + const buttons = [$('pick-image'), $('replace-image')]; |
| 191 | + buttons.forEach(button => { button.disabled = true; }); |
| 192 | + try { |
| 193 | + if (!window.base64Native?.openImage) throw new Error('选图接口未加载,请重新加载插件后重试。'); |
| 194 | + const image = await window.base64Native.openImage(); |
| 195 | + if (current !== selectionRevision) return; |
| 196 | + if (image.canceled) return; |
| 197 | + await selectImage({ name: image.name, size: image.bytes.length, bytes: image.bytes }); |
| 198 | + } catch (error) { |
| 199 | + if (current === selectionRevision) notify(`选图失败:${error.message}`); |
| 200 | + } finally { |
| 201 | + buttons.forEach(button => { button.disabled = false; }); |
| 202 | + } |
| 203 | +} |
| 204 | +for (const id of ['pick-image', 'replace-image']) $(id).onclick = pickImage; |
| 205 | +$('file-input').onchange = event => { |
| 206 | + selectImage(event.target.files[0]); |
| 207 | + event.target.value = ''; |
| 208 | +}; |
| 209 | +document.addEventListener('keydown', event => { |
| 210 | + if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); convert(); } |
| 211 | +}); |
| 212 | +document.addEventListener('paste', event => { |
| 213 | + if (mode !== 'encode') return; |
| 214 | + const image = [...(event.clipboardData?.items || [])].find(item => item.type.startsWith('image/')); |
| 215 | + if (image) { event.preventDefault(); selectImage(image.getAsFile()); } |
| 216 | +}); |
| 217 | +const inputPanel = document.querySelector('.input-panel'); |
| 218 | +document.addEventListener('dragover', event => { event.preventDefault(); if (mode === 'encode') inputPanel.classList.add('dragging'); }); |
| 219 | +document.addEventListener('dragleave', event => { if (!event.relatedTarget) inputPanel.classList.remove('dragging'); }); |
| 220 | +document.addEventListener('drop', event => { |
| 221 | + event.preventDefault(); |
| 222 | + inputPanel.classList.remove('dragging'); |
| 223 | + if (mode === 'encode' && event.dataTransfer.files.length) selectImage(event.dataTransfer.files[0]); |
| 224 | +}); |
| 225 | +$('copy').onclick = async () => { |
| 226 | + if (!result) return; |
| 227 | + const text = result.kind === 'image' ? `data:${result.mime};base64,${result.base64}` : result.text; |
| 228 | + try { |
| 229 | + if (window.ztools?.copyText) { |
| 230 | + if (await window.ztools.copyText(text) === false) throw new Error('复制失败,请重试。'); |
| 231 | + } else await navigator.clipboard.writeText(text); |
| 232 | + notify('已复制到剪贴板'); |
| 233 | + } catch (error) { notify(error.message || '复制失败,请手动选择结果复制。'); } |
| 234 | +}; |
| 235 | +$('save').onclick = async () => { |
| 236 | + if (result?.kind !== 'image') return; |
| 237 | + const image = result; |
| 238 | + try { |
| 239 | + if (window.base64Native?.saveImage) { |
| 240 | + const saved = await window.base64Native.saveImage(image.base64); |
| 241 | + notify(saved.canceled ? '已取消保存' : '图片已保存'); |
| 242 | + } else { |
| 243 | + const url = URL.createObjectURL(new Blob([image.bytes], { type: image.mime })); |
| 244 | + const link = document.createElement('a'); |
| 245 | + link.href = url; |
| 246 | + link.download = `base64-image.${image.extension}`; |
| 247 | + document.body.append(link); |
| 248 | + link.click(); |
| 249 | + link.remove(); |
| 250 | + setTimeout(() => URL.revokeObjectURL(url), 30000); |
| 251 | + notify('已发起图片下载'); |
| 252 | + } |
| 253 | + } catch (error) { notify(`保存失败:${error.message}`); } |
| 254 | +}; |
| 255 | +if (window.ztools?.onPluginEnter) { |
| 256 | + window.ztools.onPluginEnter(param => { |
| 257 | + if (param.code === 'decode' || param.code === 'encode') changeMode(param.code); |
| 258 | + if ((param.type === 'over' || param.type === 'regex') && typeof param.payload === 'string') { |
| 259 | + source = 'text'; |
| 260 | + $('input').value = param.payload; |
| 261 | + drafts[mode] = param.payload; |
| 262 | + renderMode(); |
| 263 | + convert(); |
| 264 | + } |
| 265 | + if (!$('input').hidden) $('input').focus(); |
| 266 | + }); |
| 267 | +} |
| 268 | +renderMode(); |
| 269 | +resetResult(); |
0 commit comments