// Small helpers shared by every tool. /** el('button.primary', {onclick}, 'Save') — tag with optional .classes, props/attrs, children. */ export function el(spec, props = {}, ...children) { const [tag, ...classes] = spec.split('.'); const node = document.createElement(tag || 'div'); if (classes.length) node.className = classes.join(' '); for (const [k, v] of Object.entries(props || {})) { if (v == null || v === false) continue; if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v); else if (k === 'dataset') Object.assign(node.dataset, v); else if (k in node && typeof v !== 'string') node[k] = v; else node.setAttribute(k, v === true ? '' : v); } for (const c of children.flat()) if (c != null && c !== false) node.append(c); return node; } export function toast(message, kind = 'info') { const box = document.getElementById('toasts'); const t = el(`div.toast.${kind}`, { role: kind === 'error' ? 'alert' : 'status' }, message); box.append(t); setTimeout(() => t.classList.add('out'), kind === 'error' ? 5000 : 2200); setTimeout(() => t.remove(), kind === 'error' ? 5400 : 2600); } export async function copyText(text, what = 'Copied') { try { await navigator.clipboard.writeText(text); } catch { const ta = el('textarea', { value: text, style: 'position:fixed;opacity:0' }); document.body.append(ta); ta.select(); document.execCommand('copy'); ta.remove(); } toast(what); } export function downloadText(text, filename, type = 'text/plain') { const url = URL.createObjectURL(new Blob([text], { type: `${type};charset=utf-8` })); const a = el('a', { href: url, download: filename }); document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); } /** Opens a file picker and resolves with {name, text}, or null if cancelled. */ export function openTextFile(accept = '') { return new Promise((resolve) => { const input = el('input', { type: 'file', accept }); input.addEventListener('change', async () => { const f = input.files[0]; resolve(f ? { name: f.name, text: await f.text() } : null); }); input.addEventListener('cancel', () => resolve(null)); input.click(); }); } // localStorage can be missing or throw (private windows, blocked storage); never let that break a tool. export const store = { get(key, fallback = null) { try { const v = localStorage.getItem(`tools:${key}`); return v == null ? fallback : JSON.parse(v); } catch { return fallback; } }, set(key, value) { try { localStorage.setItem(`tools:${key}`, JSON.stringify(value)); } catch {} }, }; export function formatBytes(n) { if (n < 1024) return `${n} B`; if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`; return `${(n / 1024 / 1024).toFixed(2)} MB`; } export function timeLeft(expiresAtSec) { const s = Math.max(0, Math.round(expiresAtSec - Date.now() / 1000)); if (s <= 0) return 'expired'; if (s < 60) return `${s}s left`; if (s < 3600) return `${Math.floor(s / 60)}m left`; return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m left`; } /** Debounced fn; .flush() runs a pending call now (e.g. before the page unloads). */ export function debounce(fn, ms) { let t, pending; const d = (...args) => { clearTimeout(t); pending = args; t = setTimeout(d.flush, ms); }; d.flush = () => { clearTimeout(t); if (pending) { const args = pending; pending = null; fn(...args); } }; return d; } /** Runs fn when the page is hidden/unloaded; returns a function that removes the listener. */ export function onLeave(fn) { window.addEventListener('pagehide', fn); return () => window.removeEventListener('pagehide', fn); } /** A segmented control: segmented([['edit','Edit'],...], current, onChange). */ export function segmented(options, current, onChange, label = '') { const wrap = el('div.segmented', { role: 'radiogroup', 'aria-label': label }); const buttons = options.map(([value, text, title]) => el('button', { type: 'button', role: 'radio', title: title || text, 'aria-checked': String(value === current), onclick: () => set(value, true), }, text), ); function set(value, fire) { options.forEach(([v], i) => buttons[i].setAttribute('aria-checked', String(v === value))); if (fire) onChange(value); } wrap.append(...buttons); wrap.set = (v) => set(v, false); return wrap; } /** Makes Tab / Shift+Tab indent and outdent in a textarea instead of moving focus. */ export function tabIndent(ta, unit = ' ') { ta.addEventListener('keydown', (e) => { if (e.key !== 'Tab' || e.ctrlKey || e.metaKey || e.altKey) return; e.preventDefault(); const { selectionStart: s, selectionEnd: end, value } = ta; const lineStart = value.lastIndexOf('\n', s - 1) + 1; if (s === end && !e.shiftKey) { document.execCommand('insertText', false, unit) || ta.setRangeText(unit, s, end, 'end'); return; } const block = value.slice(lineStart, end); const lines = block.split('\n'); const out = e.shiftKey ? lines.map((l) => (l.startsWith(unit) ? l.slice(unit.length) : l.replace(/^\t| {1,2}/, ''))) : lines.map((l) => unit + l); ta.setSelectionRange(lineStart, end); document.execCommand('insertText', false, out.join('\n')) || ta.setRangeText(out.join('\n'), lineStart, end, 'select'); ta.setSelectionRange(lineStart, lineStart + out.join('\n').length); }); } /** A modal dialog. Returns the ; it removes itself when closed. */ export function modal(title, body, { wide = false } = {}) { const dlg = el(`dialog.modal${wide ? '.wide' : ''}`, { 'aria-label': title }, el('div.modal-head', {}, el('h2', {}, title), el('button.icon-btn', { 'aria-label': 'Close', onclick: () => dlg.close() }, '✕'), ), el('div.modal-body', {}, body), ); dlg.addEventListener('click', (e) => { if (e.target === dlg) dlg.close(); // click on the backdrop }); dlg.addEventListener('close', () => dlg.remove()); document.body.append(dlg); dlg.showModal(); return dlg; } /** A button that opens a menu: dropdown('Open in', [{label, icon?, onSelect}]). */ export function dropdown(label, items) { const menu = el('div.menu', { role: 'menu', hidden: true }); const btn = el('button.btn', { 'aria-haspopup': 'menu', 'aria-expanded': 'false', onclick: (e) => { e.stopPropagation(); toggle(menu.hidden); } }, label, el('span.caret', { 'aria-hidden': 'true' }, '▾')); for (const it of items) { menu.append(el('button.menu-item', { role: 'menuitem', onclick: () => { toggle(false); it.onSelect(); } }, it.icon ? el('span.nav-icon', {}, it.icon) : null, it.label)); } const outside = (e) => { if (!wrap.contains(e.target)) toggle(false); }; const onKey = (e) => { if (e.key === 'Escape') { toggle(false); btn.focus(); } }; function toggle(open) { menu.hidden = !open; btn.setAttribute('aria-expanded', String(open)); if (open) { document.addEventListener('click', outside); document.addEventListener('keydown', onKey); menu.querySelector('button')?.focus(); } else { document.removeEventListener('click', outside); document.removeEventListener('keydown', onKey); } } const wrap = el('div.dropdown', {}, btn, menu); return wrap; } /** Copies HTML as rich text (with a plain-text alternative) for pasting into docs and chat apps. */ export async function copyRich(html, text, what = 'Copied') { try { if (!window.ClipboardItem || !navigator.clipboard?.write) throw new Error('no async clipboard'); await navigator.clipboard.write([new ClipboardItem({ 'text/html': new Blob([html], { type: 'text/html' }), 'text/plain': new Blob([text], { type: 'text/plain' }), })]); } catch { // Older browsers / insecure origins: select a rendered copy and use the legacy copy command. const holder = el('div', { contenteditable: 'true', style: 'position:fixed;left:-9999px;top:0' }); holder.innerHTML = html; document.body.append(holder); const range = document.createRange(); range.selectNodeContents(holder); const sel = getSelection(); sel.removeAllRanges(); sel.addRange(range); document.execCommand('copy'); sel.removeAllRanges(); holder.remove(); } toast(what); }