Single FastAPI container with a registry-driven single-page front end, so new tools are one module plus one registry entry. Runs as one container behind a reverse proxy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
159 lines
5.5 KiB
JavaScript
159 lines
5.5 KiB
JavaScript
// 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);
|
|
});
|
|
}
|