Tools site: Markdown editor, JSON editor, 24-hour pastebin

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>
This commit is contained in:
neil 2026-11-01 23:32:22 -08:00
commit 9d910eb147
26 changed files with 2591 additions and 0 deletions

210
app/static/js/app.js Normal file
View file

@ -0,0 +1,210 @@
// App shell: navigation, routing, theme. Tools themselves live in js/tools/*.js.
//
// A tool module exports mount(el, ctx) and may return a cleanup function.
// ctx = {
// rest, // path after the tool's own path, e.g. "abc123" for /paste/abc123
// query, // URLSearchParams of the current URL
// navigate, // navigate('/paste/abc') — client-side navigation
// setTitle, // setTitle('abc123') — extra text in the top bar and tab title
// }
import { TOOLS, CATEGORY_ORDER } from './registry.js';
import { el, store } from './ui.js';
const view = document.getElementById('view');
const navList = document.getElementById('nav-list');
const navFilter = document.getElementById('nav-filter');
const titleEl = document.getElementById('topbar-title');
let cleanup = null;
let routeSeq = 0;
// ---------- theme ----------
const THEMES = ['auto', 'light', 'dark'];
const svg = (d) => `<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${d}</svg>`;
const THEME_ICON = {
auto: svg('<circle cx="12" cy="12" r="9"/><path d="M12 3v18" /><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor"/>'),
light: svg('<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>'),
dark: svg('<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/>'),
};
const themeBtn = document.getElementById('theme-btn');
function applyTheme(t) {
if (t === 'auto') delete document.documentElement.dataset.theme;
else document.documentElement.dataset.theme = t;
themeBtn.innerHTML = THEME_ICON[t];
themeBtn.title = `Theme: ${t}`;
}
let theme = store.get('theme', 'auto');
applyTheme(theme);
themeBtn.addEventListener('click', () => {
theme = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length];
store.set('theme', theme);
applyTheme(theme);
});
// ---------- navigation ----------
function grouped(tools) {
const groups = new Map();
for (const t of tools) {
if (!groups.has(t.category)) groups.set(t.category, []);
groups.get(t.category).push(t);
}
const rank = (c) => (CATEGORY_ORDER.includes(c) ? CATEGORY_ORDER.indexOf(c) : 999);
return [...groups].sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b));
}
function matches(t, q) {
q = q.trim().toLowerCase();
return !q || `${t.name} ${t.description} ${t.category}`.toLowerCase().includes(q);
}
function renderNav() {
const q = navFilter.value;
navList.replaceChildren(
el('a.nav-item.nav-home', { href: '/', dataset: { path: '/' } }, el('span.nav-icon', {}, '⌂'), 'All tools'),
...grouped(TOOLS.filter((t) => matches(t, q))).map(([cat, tools]) =>
el('div.nav-group', {},
el('div.nav-heading', {}, cat),
tools.map((t) => el('a.nav-item', { href: t.path, dataset: { path: t.path } }, el('span.nav-icon', {}, t.icon), t.name)),
),
),
);
markActive();
}
function markActive() {
const tool = findTool(location.pathname);
for (const a of navList.querySelectorAll('.nav-item')) {
const on = tool ? a.dataset.path === tool.path : a.dataset.path === '/';
a.classList.toggle('active', on);
if (on) a.setAttribute('aria-current', 'page');
else a.removeAttribute('aria-current');
}
}
navFilter.addEventListener('input', renderNav);
navFilter.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
const first = TOOLS.find((t) => matches(t, navFilter.value));
if (first) {
navFilter.value = '';
renderNav();
navigate(first.path);
}
} else if (e.key === 'Escape') {
navFilter.value = '';
renderNav();
navFilter.blur();
}
});
document.addEventListener('keydown', (e) => {
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName) || document.activeElement?.isContentEditable;
if (e.key === '/' && !typing) {
e.preventDefault();
setDrawer(true);
navFilter.focus();
}
});
// Mobile drawer
const menuBtn = document.getElementById('menu-btn');
function setDrawer(open) {
document.body.classList.toggle('drawer-open', open);
menuBtn.setAttribute('aria-expanded', String(open));
}
menuBtn.addEventListener('click', () => setDrawer(!document.body.classList.contains('drawer-open')));
document.getElementById('scrim').addEventListener('click', () => setDrawer(false));
// ---------- routing ----------
function findTool(pathname) {
return TOOLS.find((t) => pathname === t.path || pathname.startsWith(`${t.path}/`));
}
export function navigate(path, { replace = false } = {}) {
if (path === location.pathname + location.search) return;
history[replace ? 'replaceState' : 'pushState']({}, '', path);
route();
}
document.addEventListener('click', (e) => {
const a = e.target.closest('a[href]');
if (!a || a.target || a.hasAttribute('download') || e.defaultPrevented) return;
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const url = new URL(a.href, location.href);
if (url.origin !== location.origin || url.pathname.startsWith('/raw/') || url.pathname.startsWith('/api/')) return;
e.preventDefault();
setDrawer(false);
navigate(url.pathname + url.search);
});
window.addEventListener('popstate', route);
function setTitle(tool, extra) {
titleEl.textContent = tool ? [tool.name, extra].filter(Boolean).join(' · ') : '';
document.title = tool ? `${[extra, tool.name].filter(Boolean).join(' · ')} — tools` : 'tools';
}
async function route() {
const seq = ++routeSeq;
if (cleanup) {
try { cleanup(); } catch (err) { console.error(err); }
cleanup = null;
}
markActive();
const tool = findTool(location.pathname);
document.body.dataset.tool = tool ? tool.id : 'home';
if (!tool) {
if (location.pathname !== '/') history.replaceState({}, '', '/');
setTitle(null);
renderHome();
return;
}
setTitle(tool);
view.replaceChildren(el('div.loading', {}, 'Loading…'));
try {
const mod = await tool.load();
if (seq !== routeSeq) return; // navigated away while loading
view.replaceChildren();
const ctx = {
rest: location.pathname.slice(tool.path.length).replace(/^\//, ''),
query: new URLSearchParams(location.search),
navigate,
setTitle: (extra) => setTitle(tool, extra),
};
cleanup = (await mod.mount(view, ctx)) || null;
} catch (err) {
console.error(err);
if (seq === routeSeq) view.replaceChildren(el('div.empty', {}, `Couldn't load ${tool.name}: ${err.message}`));
}
}
function renderHome() {
const filter = el('input.home-filter', { type: 'search', placeholder: 'Find a tool…', 'aria-label': 'Find a tool' });
const grid = el('div.card-grid');
const draw = () =>
grid.replaceChildren(
...TOOLS.filter((t) => matches(t, filter.value)).map((t) =>
el('a.tool-card', { href: t.path },
el('div.tool-card-icon', {}, t.icon),
el('div', {}, el('div.tool-card-name', {}, t.name), el('div.tool-card-desc', {}, t.description)),
),
),
);
filter.addEventListener('input', draw);
filter.addEventListener('keydown', (e) => {
const first = e.key === 'Enter' && grid.querySelector('a');
if (first) navigate(new URL(first.href).pathname);
});
draw();
view.replaceChildren(
el('div.home', {},
el('h1', {}, 'Tools'),
el('p.muted', {}, 'Small utilities that run in your browser. Only pastes are stored on the server, and only for 24 hours.'),
filter,
grid,
),
);
}
renderNav();
route();

37
app/static/js/registry.js Normal file
View file

@ -0,0 +1,37 @@
// The list of tools. The sidebar, the home page and the router are all built from it.
//
// To add a tool: create js/tools/<id>.js exporting mount(el, ctx) (see app.js for ctx),
// then add an entry here. A tool owns every path under its `path`, so /paste/abc123
// goes to the paste tool with ctx.rest = "abc123".
export const TOOLS = [
{
id: 'markdown',
name: 'Markdown',
path: '/markdown',
category: 'Text',
icon: 'M↓',
description: 'Write Markdown with a live preview: side by side, editor only or full-page preview.',
load: () => import('./tools/markdown.js'),
},
{
id: 'json',
name: 'JSON editor',
path: '/json',
category: 'Data',
icon: '{ }',
description: 'Validate, prettify and compact JSON, with a live tree view you can edit.',
load: () => import('./tools/json.js'),
},
{
id: 'paste',
name: 'Pastebin',
path: '/paste',
category: 'Sharing',
icon: '⎘',
description: 'Share text with a short link. Pastes are deleted after 24 hours.',
load: () => import('./tools/paste.js'),
},
];
// Sidebar groups appear in this order; unknown categories go last, alphabetically.
export const CATEGORY_ORDER = ['Text', 'Data', 'Sharing'];

View file

@ -0,0 +1,234 @@
// JSON parser and printer that work on source tokens rather than JS values, so
// formatting never changes the data: numbers keep their exact digits (no precision
// loss on big integers), strings keep their original escapes, duplicate keys survive.
//
// Node shapes (start/end are offsets into the source text):
// {type:'object', entries:[{key, keyRaw, keyStart, keyEnd, value}], start, end}
// {type:'array', items:[node], start, end}
// {type:'string', value, raw, start, end}
// {type:'number', raw, start, end}
// {type:'boolean', value, start, end} / {type:'null', start, end}
export class JsonSyntaxError extends Error {
constructor(message, pos, text) {
const { line, col } = lineCol(text, pos);
super(message);
this.pos = pos;
this.line = line;
this.col = col;
}
}
export function lineCol(text, pos) {
let line = 1;
let last = -1;
for (let i = text.indexOf('\n'); i !== -1 && i < pos; i = text.indexOf('\n', i + 1)) {
line++;
last = i;
}
return { line, col: pos - last };
}
const STRING_RE = /"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/y;
const NUMBER_RE = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y;
export function parse(text) {
let i = text.charCodeAt(0) === 0xfeff ? 1 : 0;
const fail = (msg, at = i) => {
throw new JsonSyntaxError(msg, at, text);
};
const describe = (at) => {
if (at >= text.length) return 'end of input';
const ch = text[at];
return ch === '\n' ? 'line break' : `'${ch}'`;
};
function ws() {
for (;;) {
const c = text.charCodeAt(i);
if (c === 32 || c === 10 || c === 13 || c === 9) i++;
else if (c === 47 && (text[i + 1] === '/' || text[i + 1] === '*')) fail("Comments aren't allowed in JSON");
else return;
}
}
function string() {
STRING_RE.lastIndex = i;
const m = STRING_RE.exec(text);
if (!m) {
// Find the exact problem for a useful message.
for (let j = i + 1; j < text.length; j++) {
const c = text.charCodeAt(j);
if (c === 34) break;
if (c === 10) fail('Unterminated string (strings cannot span lines; use \\n)', j);
if (c < 32) fail('Control character in string; escape it', j);
if (c === 92) {
const e = text[j + 1];
if (e === 'u') {
if (!/^[0-9a-fA-F]{4}$/.test(text.slice(j + 2, j + 6))) fail('Invalid \\u escape: needs four hex digits', j);
j += 5;
} else if ('"\\/bfnrt'.includes(e) && e !== undefined) j++;
else fail(`Invalid escape '\\${e ?? ''}'`, j);
}
}
fail('Unterminated string');
}
const start = i;
i += m[0].length;
return { type: 'string', raw: m[0], value: JSON.parse(m[0]), start, end: i };
}
function value(depth) {
if (depth > 2000) fail('Nested too deeply (more than 2000 levels)');
ws();
const start = i;
const c = text[i];
if (c === '{') {
i++;
const entries = [];
ws();
if (text[i] === '}') return { type: 'object', entries, start, end: ++i };
for (;;) {
ws();
if (text[i] !== '"') {
if (text[i] === '}' && entries.length) fail('Trailing comma before }', i);
if (text[i] === "'") fail('Strings must use double quotes');
fail(i >= text.length ? 'Unexpected end of input: object is not closed' : `Expected a "quoted" key, found ${describe(i)}`);
}
const k = string();
ws();
if (text[i] !== ':') fail(`Expected ':' after key, found ${describe(i)}`);
i++;
const v = value(depth + 1);
entries.push({ key: k.value, keyRaw: k.raw, keyStart: k.start, keyEnd: k.end, value: v });
ws();
if (text[i] === ',') { i++; continue; }
if (text[i] === '}') return { type: 'object', entries, start, end: ++i };
fail(i >= text.length ? 'Unexpected end of input: object is not closed' : `Expected ',' or '}', found ${describe(i)}`);
}
}
if (c === '[') {
i++;
const items = [];
ws();
if (text[i] === ']') return { type: 'array', items, start, end: ++i };
for (;;) {
ws();
if (text[i] === ']' && items.length) fail('Trailing comma before ]', i);
items.push(value(depth + 1));
ws();
if (text[i] === ',') { i++; continue; }
if (text[i] === ']') return { type: 'array', items, start, end: ++i };
fail(i >= text.length ? 'Unexpected end of input: array is not closed' : `Expected ',' or ']', found ${describe(i)}`);
}
}
if (c === '"') return string();
if (c === "'") fail('Strings must use double quotes');
if (c === '-' || (c >= '0' && c <= '9')) {
NUMBER_RE.lastIndex = i;
const m = NUMBER_RE.exec(text);
if (!m) fail('Invalid number');
i += m[0].length;
if (/[0-9.eE]/.test(text[i] || '')) fail('Invalid number (leading zeros and trailing dots are not allowed)', start);
return { type: 'number', raw: m[0], start, end: i };
}
for (const [word, node] of [['true', { type: 'boolean', value: true }], ['false', { type: 'boolean', value: false }], ['null', { type: 'null' }]]) {
if (text.startsWith(word, i)) {
i += word.length;
return { ...node, start, end: i };
}
}
if (i >= text.length) fail('Unexpected end of input: expected a value');
const word = /^[A-Za-z_$][\w$]*/.exec(text.slice(i, i + 40));
if (word) fail(`Unexpected '${word[0]}': ${['undefined', 'NaN', 'Infinity', 'True', 'False', 'None'].includes(word[0]) ? "not valid in JSON" : 'strings must be "quoted"'}`);
fail(`Unexpected ${describe(i)}`);
}
ws();
if (i >= text.length) fail('Empty document');
let root;
try {
root = value(0);
} catch (err) {
if (err instanceof RangeError) throw new JsonSyntaxError('Nested too deeply', i, text);
throw err;
}
ws();
if (i < text.length) fail(`Unexpected ${describe(i)} after the end of the JSON value`);
return root;
}
/** Prints a node. indent '' = compact (no whitespace at all), else e.g. ' ', ' ', '\t'. */
export function stringify(node, indent = ' ') {
const out = [];
const sep = indent ? ': ' : ':';
function walk(n, pad) {
switch (n.type) {
case 'object': {
if (!n.entries.length) return out.push('{}');
const inner = pad + indent;
out.push('{');
n.entries.forEach((e, idx) => {
if (idx) out.push(',');
if (indent) out.push('\n', inner);
out.push(e.keyRaw, sep);
walk(e.value, inner);
});
if (indent) out.push('\n', pad);
return out.push('}');
}
case 'array': {
if (!n.items.length) return out.push('[]');
const inner = pad + indent;
out.push('[');
n.items.forEach((item, idx) => {
if (idx) out.push(',');
if (indent) out.push('\n', inner);
walk(item, inner);
});
if (indent) out.push('\n', pad);
return out.push(']');
}
case 'string':
case 'number':
return out.push(n.raw);
case 'boolean':
return out.push(String(n.value));
case 'null':
return out.push('null');
}
}
walk(node, '');
return out.join('');
}
/** A copy with object keys sorted (by code point), recursively. */
export function sortKeys(node) {
if (node.type === 'object') {
const entries = node.entries
.map((e) => ({ ...e, value: sortKeys(e.value) }))
.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
return { ...node, entries };
}
if (node.type === 'array') return { ...node, items: node.items.map(sortKeys) };
return node;
}
/** Turns text typed into the tree editor into a node: valid JSON as-is, anything else as a string. */
export function nodeFromInput(text) {
try {
return parse(text);
} catch {
return stringNode(text);
}
}
export function stringNode(value) {
return { type: 'string', value, raw: JSON.stringify(value) };
}
/** JavaScript-style path for display, e.g. $.users[0]["first name"] */
export function pathToString(path) {
return '$' + path.map((p) => (typeof p === 'number' ? `[${p}]` : /^[A-Za-z_$][\w$]*$/.test(p) ? `.${p}` : `[${JSON.stringify(p)}]`)).join('');
}

460
app/static/js/tools/json.js Normal file
View file

@ -0,0 +1,460 @@
// JSON editor: a text pane and a live tree pane that stay in sync.
// Text edits re-render the tree as you type; tree edits rewrite the text (undoable).
import { parse, stringify, sortKeys, nodeFromInput, stringNode, pathToString, JsonSyntaxError } from './json-core.js';
import { el, segmented, store, copyText, downloadText, openTextFile, debounce, formatBytes, tabIndent, toast, onLeave } from '../ui.js';
const SAMPLE = `{
"name": "tools",
"version": 1,
"bigNumber": 12345678901234567890,
"tags": ["markdown", "json", "paste"],
"nested": { "ok": true, "nothing": null, "items": [{ "id": 1 }, { "id": 2 }] }
}
`;
const INDENTS = { '2': ' ', '4': ' ', tab: '\t' };
const PAGE = 200; // children shown per expanded node before "show more"
const TREE_LIVE_LIMIT = 5_000_000; // bytes; above this the tree updates on pause, not per keystroke
export async function mount(root, ctx) {
let mode = store.get('json:mode', window.innerWidth < 800 ? 'text' : 'split');
let indentKey = store.get('json:indent', '2');
let ast = null;
let error = null;
let selectedPath = null;
// Open/closed overrides by path key; without one, the root and its children start open.
let opened = new Set();
let closed = new Set();
const shown = new Map(); // path key -> how many children are visible
// ---------- layout ----------
const editor = el('textarea.json-input.mono', { spellcheck: false, wrap: 'off', 'aria-label': 'JSON text', placeholder: 'Paste or type JSON…' });
tabIndent(editor);
const gutter = el('div.gutter.mono', { 'aria-hidden': 'true' });
const gutterNums = el('div.gutter-nums');
const errorMark = el('div.gutter-error');
gutter.append(gutterNums, errorMark);
const tree = el('div.json-tree.mono', { role: 'tree', 'aria-label': 'JSON tree' });
const status = el('div.statusbar');
const modes = segmented([['text', 'Text'], ['split', 'Split'], ['tree', 'Tree']], mode, setMode, 'View mode');
const indentSel = el('select.select', { title: 'Indentation for Format', 'aria-label': 'Indentation', onchange: () => {
indentKey = indentSel.value;
store.set('json:indent', indentKey);
} },
el('option', { value: '2' }, '2 spaces'), el('option', { value: '4' }, '4 spaces'), el('option', { value: 'tab' }, 'Tabs'));
indentSel.value = indentKey;
const toolbar = el('div.toolbar', {},
modes,
el('span.divider'),
el('button.btn.primary', { onclick: format, title: 'Prettify (Ctrl+Shift+F)' }, 'Format'),
indentSel,
el('button.btn', { onclick: compact, title: 'Remove all whitespace outside keys and values (Ctrl+Shift+M)' }, 'Compact'),
el('button.btn', { onclick: sort, title: 'Sort object keys A→Z, recursively' }, 'Sort keys'),
el('span.spacer'),
el('button.btn', { onclick: openFile }, 'Open'),
el('button.btn', { onclick: () => downloadText(editor.value, 'data.json', 'application/json') }, 'Download'),
el('button.btn', { onclick: () => copyText(editor.value) }, 'Copy'),
el('button.btn', { onclick: () => replaceText(''), title: 'Clear (undo with Ctrl+Z)' }, 'Clear'),
);
const treeBar = el('div.tree-bar', {},
el('button.btn.small', { onclick: () => expandAll(true) }, 'Expand all'),
el('button.btn.small', { onclick: () => expandAll(false) }, 'Collapse all'),
el('span.spacer'),
);
const pathBox = el('button.path-chip.mono', { title: 'Copy path', hidden: true, onclick: () => copyText(pathBox.textContent, 'Path copied') });
treeBar.append(pathBox);
const workspace = el('div.json-workspace', {},
el('div.pane.json-text-pane', {}, el('div.editor-wrap', {}, gutter, editor)),
el('div.pane.json-tree-pane', {}, treeBar, tree),
);
root.append(el('div.tool.json-tool', {}, toolbar, workspace, status));
// ---------- text pane ----------
let lineCount = 0;
function updateGutter() {
let n = 1;
for (let i = editor.value.indexOf('\n'); i !== -1; i = editor.value.indexOf('\n', i + 1)) n++;
if (n !== lineCount) {
lineCount = n;
gutterNums.textContent = Array.from({ length: n }, (_, k) => k + 1).join('\n');
}
syncGutter();
}
function syncGutter() {
gutter.scrollTop = editor.scrollTop;
}
editor.addEventListener('scroll', syncGutter);
// When the text shrinks the browser clamps the editor's scroll without always firing
// 'scroll', so re-sync after layout too.
editor.addEventListener('input', () => requestAnimationFrame(syncGutter));
/** Replaces the whole text in a way the browser's undo (Ctrl+Z) can reverse. */
function replaceText(text) {
editor.focus({ preventScroll: true });
editor.select();
// execCommand types into whatever has focus; when the text pane is hidden (Tree
// mode) the editor can't take focus, so set the value directly (not undoable).
if (document.activeElement !== editor || !document.execCommand('insertText', false, text)) {
editor.value = text;
editor.dispatchEvent(new Event('input'));
}
editor.setSelectionRange(0, 0);
editor.scrollTop = 0;
}
function lineHeight() {
return parseFloat(getComputedStyle(editor).lineHeight) || 20;
}
function selectRange(start, end) {
if (mode === 'tree') return;
const before = editor.value.slice(0, start);
const line = before.split('\n').length;
editor.focus({ preventScroll: true });
editor.setSelectionRange(start, end);
editor.scrollTop = Math.max(0, (line - 1) * lineHeight() - editor.clientHeight / 3);
}
// ---------- parsing & status ----------
function reparse() {
const text = editor.value;
try {
ast = text.trim() ? parse(text) : null;
error = null;
} catch (err) {
if (!(err instanceof JsonSyntaxError)) throw err;
error = err;
// Keep showing the last good tree (dimmed) so it doesn't flicker while typing.
}
renderStatus();
renderTree();
updateGutter();
}
function renderStatus() {
const size = formatBytes(new Blob([editor.value]).size);
errorMark.hidden = !error;
if (error) {
errorMark.style.top = `${(error.line - 1) * lineHeight()}px`;
status.className = 'statusbar error';
status.replaceChildren(
el('button.linklike', { onclick: () => selectRange(error.pos, Math.min(error.pos + 1, editor.value.length)), title: 'Go to the error' },
`Line ${error.line}, column ${error.col}`),
`: ${error.message}`,
el('span.spacer'),
el('span.muted', {}, size),
);
} else if (!ast) {
status.className = 'statusbar';
status.replaceChildren(el('span.muted', {}, 'Empty'));
} else {
status.className = 'statusbar ok';
status.replaceChildren('✓ Valid JSON', el('span.muted', {}, ` · ${summary(ast)}`), el('span.spacer'), el('span.muted', {}, size));
}
}
function summary(n) {
if (n.type === 'object') return `object, ${n.entries.length} key${n.entries.length === 1 ? '' : 's'}`;
if (n.type === 'array') return `array, ${n.items.length} item${n.items.length === 1 ? '' : 's'}`;
return n.type;
}
// ---------- toolbar actions ----------
function current() {
if (error) {
toast(`Fix the error first: line ${error.line}, column ${error.col}`, 'error');
selectRange(error.pos, error.pos + 1);
return null;
}
return ast;
}
function format() {
const a = current();
if (a) replaceText(stringify(a, INDENTS[indentKey]) + '\n');
}
function compact() {
const a = current();
if (a) replaceText(stringify(a, ''));
}
function sort() {
const a = current();
if (a) replaceText(stringify(sortKeys(a), INDENTS[indentKey]) + '\n');
}
async function openFile() {
const f = await openTextFile('.json,application/json,text/plain');
if (f) replaceText(f.text);
}
// ---------- tree ----------
const key = (path) => path.map((p) => '/' + String(p).replace(/~/g, '~0').replace(/\//g, '~1')).join('');
const isOpen = (path) => {
const k = key(path);
return closed.has(k) ? false : opened.has(k) || path.length <= 1;
};
function setOpen(path, open) {
const k = key(path);
(open ? opened : closed).add(k);
(open ? closed : opened).delete(k);
}
function renderTree() {
if (mode === 'text') return;
tree.classList.toggle('stale', !!error);
if (!ast) {
tree.replaceChildren(el('div.empty', {}, error ? 'Fix the JSON to see the tree.' : 'Nothing to show yet.'));
return;
}
const scroll = tree.scrollTop;
tree.replaceChildren(renderNode(ast, [], null, null));
tree.scrollTop = scroll;
}
function renderNode(node, path, label, parent) {
const isContainer = node.type === 'object' || node.type === 'array';
const row = el('div.tree-row', { role: 'treeitem', tabIndex: -1 });
const pk = key(path);
if (selectedPath === pk) row.classList.add('selected');
row.style.setProperty('--depth', path.length);
const open = isContainer && isOpen(path);
if (isContainer) {
row.setAttribute('aria-expanded', String(open));
row.append(el('button.twisty', { tabIndex: -1, 'aria-label': open ? 'Collapse' : 'Expand', onclick: (e) => {
e.stopPropagation();
setOpen(path, !open);
renderTree();
} }, open ? '▾' : '▸'));
} else row.append(el('span.twisty-space'));
if (label != null) {
if (typeof label === 'number') row.append(el('span.t-index', {}, String(label)), el('span.t-punct', {}, ': '));
else row.append(editable(el('span.t-key', { title: 'Double-click to rename' }, label), label, (v) => renameKey(parent, path, v)), el('span.t-punct', {}, ': '));
}
if (isContainer) {
const n = node.type === 'object' ? node.entries.length : node.items.length;
row.append(el('span.t-punct', {}, node.type === 'object' ? '{' : '['),
el('span.t-count', {}, open ? '' : ` ${n} ${node.type === 'object' ? (n === 1 ? 'key' : 'keys') : n === 1 ? 'item' : 'items'} `),
el('span.t-punct', {}, open ? '' : node.type === 'object' ? '}' : ']'));
} else {
const shownText = node.type === 'string' ? node.value : node.type === 'number' ? node.raw : String(node.value ?? 'null');
const display = node.type === 'string' ? JSON.stringify(shownText.length > 2000 ? shownText.slice(0, 2000) + '…' : shownText) : shownText;
row.append(editable(el(`span.t-val.t-${node.type}`, { title: 'Double-click to edit' }, display), shownText, (v) => editValue(path, node, v)));
}
const actions = el('span.row-actions');
if (isContainer) actions.append(el('button.mini', { title: node.type === 'object' ? 'Add a key' : 'Add an item', onclick: (e) => { e.stopPropagation(); addChild(path, node); } }, '+'));
if (path.length) actions.append(el('button.mini', { title: 'Delete', onclick: (e) => { e.stopPropagation(); removeAt(path); } }, '×'));
row.append(actions);
row.addEventListener('click', () => {
selectedPath = pk;
tree.querySelectorAll('.tree-row.selected').forEach((r) => r.classList.remove('selected'));
row.classList.add('selected');
pathBox.hidden = false;
pathBox.textContent = pathToString(path);
if (!error && node.start != null) selectRange(node.start, node.end);
});
if (!open) return row;
const children = node.type === 'object' ? node.entries.map((e) => [e.key, e.value]) : node.items.map((v, i) => [i, v]);
const limit = shown.get(pk) || PAGE;
const box = el('div.tree-children', { role: 'group' });
for (const [k, v] of children.slice(0, limit)) box.append(renderNode(v, [...path, k], k, node));
if (children.length > limit) {
box.append(el('button.btn.small.more', { style: `--depth:${path.length + 1}`, onclick: () => { shown.set(pk, limit + PAGE * 5); renderTree(); } },
`Show more (${children.length - limit} hidden)`));
}
const close = el('div.tree-row.closing', {}, el('span.twisty-space'), el('span.t-punct', {}, node.type === 'object' ? '}' : ']'));
close.style.setProperty('--depth', path.length);
return el('div', {}, row, box, close);
}
/** Double-click (or Enter on the focused row) turns a span into an inline input. */
function editable(span, initial, commit) {
span.addEventListener('dblclick', (e) => {
e.stopPropagation();
const input = el('input.inline-edit.mono', { value: initial, size: Math.max(4, Math.min(60, initial.length + 2)) });
let done = false;
const finish = (save) => {
if (done) return;
done = true;
if (save && input.value !== initial) commit(input.value);
else input.replaceWith(span);
};
input.addEventListener('keydown', (ev) => {
ev.stopPropagation();
// preventDefault: committing focuses the text pane, and the Enter must not land there.
if (ev.key === 'Enter') { ev.preventDefault(); finish(true); }
if (ev.key === 'Escape') { ev.preventDefault(); finish(false); }
});
input.addEventListener('blur', () => finish(true));
span.replaceWith(input);
input.focus();
input.select();
});
return span;
}
// Tree edits: change the AST, then rewrite the text formatted with the current indent.
function getAt(path) {
let n = ast;
for (const p of path) n = n.type === 'object' ? n.entries.find((e) => e.key === p)?.value : n.items[p];
return n;
}
function parentAndIndex(path) {
const parent = getAt(path.slice(0, -1));
const last = path[path.length - 1];
const idx = parent.type === 'object' ? parent.entries.findIndex((e) => e.key === last) : last;
return [parent, idx];
}
function commitAst() {
replaceText(stringify(ast, INDENTS[indentKey]) + '\n');
}
function guard() {
if (error) {
toast('Fix the JSON text before editing the tree', 'error');
renderTree();
return false;
}
return true;
}
function editValue(path, node, text) {
if (!guard()) return;
// Strings stay strings; other values are re-read as JSON (so "12" → 12, "abc" → "abc").
const next = node.type === 'string' ? stringNode(text) : nodeFromInput(text.trim());
if (!path.length) ast = next;
else {
const [parent, idx] = parentAndIndex(path);
if (parent.type === 'object') parent.entries[idx].value = next;
else parent.items[idx] = next;
}
commitAst();
}
function renameKey(parent, path, newKey) {
if (!guard()) return;
const [obj, idx] = parentAndIndex(path);
if (obj.entries.some((e, i) => i !== idx && e.key === newKey)) return toast(`Key "${newKey}" already exists`, 'error'), renderTree();
obj.entries[idx].key = newKey;
obj.entries[idx].keyRaw = JSON.stringify(newKey);
remapExpanded(path, [...path.slice(0, -1), newKey]);
commitAst();
}
function remapExpanded(from, to) {
const a = key(from), b = key(to);
const move = (set) => new Set([...set].map((k) => (k === a || k.startsWith(a + '/') ? b + k.slice(a.length) : k)));
opened = move(opened);
closed = move(closed);
}
function addChild(path, node) {
if (!guard()) return;
const target = getAt(path);
if (target.type === 'object') {
let k = 'key', i = 1;
while (target.entries.some((e) => e.key === k)) k = `key${++i}`;
target.entries.push({ key: k, keyRaw: JSON.stringify(k), value: { type: 'null' } });
} else target.items.push({ type: 'null' });
setOpen(path, true);
commitAst();
}
function removeAt(path) {
if (!guard()) return;
const [parent, idx] = parentAndIndex(path);
if (parent.type === 'object') parent.entries.splice(idx, 1);
else parent.items.splice(idx, 1);
selectedPath = null;
pathBox.hidden = true;
commitAst();
}
function expandAll(open) {
if (!ast) return;
opened = new Set();
closed = new Set();
shown.clear();
let count = 0;
(function walk(n, path) {
if (count > 5000 || (n.type !== 'object' && n.type !== 'array')) return;
count++;
if (open) opened.add(key(path));
else if (path.length) closed.add(key(path));
if (n.type === 'object') n.entries.forEach((e) => walk(e.value, [...path, e.key]));
else n.items.forEach((v, i) => walk(v, [...path, i]));
})(ast, []);
if (open && count > 5000) toast('Large document: expanded the first 5000 nodes');
renderTree();
}
// ---------- modes, input, shortcuts ----------
function setMode(m) {
mode = m;
workspace.dataset.mode = m;
modes.set(m);
store.set('json:mode', m);
renderTree();
}
// A paste opened via ?paste= is never written over this browser's own draft.
let fromPaste = false;
const save = debounce(() => {
if (!fromPaste && editor.value.length < 2_000_000) store.set('json:text', editor.value);
}, 500);
const slowParse = debounce(reparse, 400);
editor.addEventListener('input', () => {
updateGutter();
if (editor.value.length > TREE_LIVE_LIMIT) slowParse();
else reparse();
save();
});
function onKey(e) {
if (!(e.ctrlKey || e.metaKey) || !e.shiftKey) return;
const k = e.key.toLowerCase();
if (k === 'f') { e.preventDefault(); format(); }
if (k === 'm') { e.preventDefault(); compact(); }
}
document.addEventListener('keydown', onKey);
// Pasting a whole document into an empty editor formats it straight away.
editor.addEventListener('paste', (e) => {
if (editor.value.trim()) return;
const text = e.clipboardData?.getData('text/plain');
if (!text) return;
try {
const a = parse(text);
e.preventDefault();
document.execCommand('insertText', false, stringify(a, INDENTS[indentKey]) + '\n');
} catch {}
});
editor.value = store.get('json:text', SAMPLE);
const pasteId = ctx.query.get('paste');
if (pasteId) {
try {
const r = await fetch(`/api/paste/${encodeURIComponent(pasteId)}`);
const body = await r.json();
if (!r.ok) throw new Error(body.detail);
editor.value = body.content;
fromPaste = true;
ctx.setTitle(`paste ${pasteId}`);
toast('Opened a shared paste; edits here are not saved');
} catch (err) {
toast(`Couldn't load paste: ${err.message}`, 'error');
}
}
setMode(mode);
reparse();
const off = onLeave(save.flush);
return () => {
save.flush();
off();
document.removeEventListener('keydown', onKey);
};
}

View file

@ -0,0 +1,159 @@
// Markdown editor with live preview. Modes: edit only, side by side, full-page preview.
import { marked } from '../../vendor/marked.esm.js';
import DOMPurify from '../../vendor/purify.es.mjs';
import { el, segmented, store, copyText, downloadText, openTextFile, debounce, tabIndent, toast, onLeave } from '../ui.js';
import { createPaste } from './paste.js';
const SAMPLE = `# Markdown
Type on the left, see it rendered on the right. Switch to **Preview** for a full-page view.
## Formatting
*Italic*, **bold**, ~~strikethrough~~, \`inline code\` and [links](https://example.com).
> Blockquotes look like this.
- [x] Task lists
- [ ] Nested lists
1. one
2. two
| Column | Another | Right |
| ------ | :-----: | ----: |
| tables | aligned | 42 |
\`\`\`js
function hello(name) {
return \`Hello, \${name}!\`;
}
\`\`\`
---
Your text is saved in this browser as you type.
`;
marked.use({ gfm: true });
DOMPurify.addHook('afterSanitizeAttributes', (node) => {
if (node.tagName === 'A' && node.getAttribute('href') && !node.getAttribute('href').startsWith('#')) {
node.setAttribute('target', '_blank');
node.setAttribute('rel', 'noopener noreferrer');
}
});
export function render(md) {
return DOMPurify.sanitize(marked.parse(md));
}
export async function mount(root, ctx) {
let mode = store.get('md:mode', window.innerWidth < 800 ? 'edit' : 'split');
const editor = el('textarea.md-input.mono', {
spellcheck: true,
'aria-label': 'Markdown',
placeholder: 'Write Markdown here…',
});
tabIndent(editor);
const preview = el('article.md-preview.prose', { 'aria-label': 'Preview' });
const stats = el('span.muted.small');
const modes = segmented(
[['edit', 'Edit', 'Editor only'], ['split', 'Split', 'Editor and preview side by side'], ['preview', 'Preview', 'Full-page preview']],
mode,
setMode,
'View mode',
);
const workspace = el('div.md-workspace', {},
el('div.pane.md-edit-pane', {}, editor),
el('div.pane.md-preview-pane', {}, preview),
);
const toolbar = el('div.toolbar', {},
modes,
el('span.spacer'),
stats,
el('button.btn', { onclick: openFile, title: 'Open a .md file' }, 'Open'),
el('button.btn', { onclick: () => downloadText(editor.value, 'document.md', 'text/markdown'), title: 'Download as .md' }, 'Download'),
el('button.btn', { onclick: () => copyText(render(editor.value), 'HTML copied'), title: 'Copy the rendered HTML' }, 'Copy HTML'),
el('button.btn', { onclick: share, title: 'Create a 24-hour paste and copy its link' }, 'Share'),
);
root.append(el('div.tool.md-tool', {}, toolbar, workspace));
function update() {
preview.innerHTML = render(editor.value);
const words = (editor.value.match(/\S+/g) || []).length;
stats.textContent = `${words} word${words === 1 ? '' : 's'}`;
}
// A shared paste opened via ?paste= is never written over this browser's own draft.
let fromPaste = false;
const save = debounce(() => !fromPaste && store.set('md:text', editor.value), 400);
const live = debounce(update, 60);
editor.addEventListener('input', () => {
live();
save();
});
function setMode(m) {
mode = m;
workspace.dataset.mode = m;
modes.set(m);
if (!fromPaste) store.set('md:mode', m);
if (m !== 'edit') update();
if (m !== 'preview') editor.focus({ preventScroll: true });
}
// Keep the preview roughly in step with the editor while scrolling side by side.
let syncing = null;
const sync = (from, to) => () => {
if (mode !== 'split' || (syncing && syncing !== from)) return;
syncing = from;
const max = from.scrollHeight - from.clientHeight;
to.scrollTop = max > 0 ? (from.scrollTop / max) * (to.scrollHeight - to.clientHeight) : 0;
clearTimeout(sync.t);
sync.t = setTimeout(() => (syncing = null), 80);
};
const previewPane = workspace.querySelector('.md-preview-pane');
editor.addEventListener('scroll', sync(editor, previewPane));
previewPane.addEventListener('scroll', sync(previewPane, editor));
async function openFile() {
const f = await openTextFile('.md,.markdown,.txt,text/markdown,text/plain');
if (!f) return;
editor.value = f.text;
update();
save();
}
async function share() {
if (!editor.value.trim()) return toast('Nothing to share', 'error');
const p = await createPaste(editor.value);
if (p) copyText(`${location.origin}/markdown?paste=${p.id}`, 'Link copied (expires in 24 h)');
}
// Load: ?paste=<id> opens a paste here; otherwise the saved draft, otherwise the sample.
const pasteId = ctx.query.get('paste');
editor.value = store.get('md:text', SAMPLE);
if (pasteId) {
try {
const r = await fetch(`/api/paste/${encodeURIComponent(pasteId)}`);
if (!r.ok) throw new Error((await r.json()).detail);
editor.value = (await r.json()).content;
ctx.setTitle(`paste ${pasteId}`);
fromPaste = true;
mode = 'preview';
toast('Opened a shared paste; edits here are not saved', 'info');
} catch (err) {
toast(`Couldn't load paste: ${err.message}`, 'error');
}
}
setMode(mode);
update();
const off = onLeave(save.flush);
return () => {
save.flush();
off();
};
}

View file

@ -0,0 +1,165 @@
// Pastebin: /paste to create, /paste/<id> to view. Pastes expire 24 h after creation.
// Pastes made in this browser are remembered locally (with their delete tokens).
import { el, store, copyText, downloadText, toast, timeLeft, formatBytes } from '../ui.js';
const MAX_BYTES = 1024 * 1024;
function mine() {
const now = Date.now() / 1000;
return (store.get('paste:mine', []) || []).filter((p) => p.expires_at > now);
}
function remember(p, preview) {
store.set('paste:mine', [{ id: p.id, expires_at: p.expires_at, delete_token: p.delete_token, preview }, ...mine()].slice(0, 50));
}
function forget(id) {
store.set('paste:mine', mine().filter((p) => p.id !== id));
}
/** Creates a paste and remembers it locally. Resolves with {id, expires_at, delete_token} or null. */
export async function createPaste(content) {
try {
const r = await fetch('/api/paste', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content }),
});
const body = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(body.detail || `HTTP ${r.status}`);
remember(body, content.slice(0, 80).replace(/\s+/g, ' '));
return body;
} catch (err) {
toast(`Couldn't create paste: ${err.message}`, 'error');
return null;
}
}
async function deletePaste(id, token) {
const r = await fetch(`/api/paste/${encodeURIComponent(id)}`, { method: 'DELETE', headers: { 'X-Delete-Token': token } });
if (r.ok || r.status === 404) forget(id);
return r.ok;
}
export async function mount(root, ctx) {
const timers = [];
const cleanup = () => timers.forEach(clearInterval);
if (ctx.rest) await renderView(root, ctx, ctx.rest, timers);
else renderCreate(root, ctx, timers);
return cleanup;
}
function renderCreate(root, ctx, timers) {
const ta = el('textarea.paste-input.mono', { placeholder: 'Paste or type text…', spellcheck: false, 'aria-label': 'Paste content' });
ta.value = store.get('paste:draft', '');
const info = el('span.muted.small');
const btn = el('button.btn.primary', { onclick: submit }, 'Create paste');
const updateInfo = () => {
const n = new Blob([ta.value]).size;
info.textContent = `${formatBytes(n)} of 1 MB · expires 24 h after creation`;
info.classList.toggle('error-text', n > MAX_BYTES);
};
ta.addEventListener('input', () => {
updateInfo();
store.set('paste:draft', ta.value);
});
ta.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit();
});
async function submit() {
if (!ta.value.trim()) return toast('Nothing to paste', 'error');
if (new Blob([ta.value]).size > MAX_BYTES) return toast('Paste is larger than 1 MB', 'error');
btn.disabled = true;
const p = await createPaste(ta.value);
btn.disabled = false;
if (!p) return;
store.set('paste:draft', '');
copyText(`${location.origin}/paste/${p.id}`, 'Link copied');
ctx.navigate(`/paste/${p.id}`);
}
const list = el('div.paste-list');
function drawList() {
const items = mine();
list.replaceChildren(
...(items.length
? [el('h2.section-title', {}, 'Your recent pastes'),
...items.map((p) =>
el('div.paste-item', {},
el('a.mono', { href: `/paste/${p.id}` }, p.id),
el('span.paste-preview.muted', {}, p.preview || ''),
el('span.muted.small.nowrap', {}, timeLeft(p.expires_at)),
el('button.btn.small', { title: 'Delete now', onclick: async () => {
if (await deletePaste(p.id, p.delete_token)) toast('Deleted');
drawList();
} }, 'Delete'),
))]
: []),
);
}
drawList();
timers.push(setInterval(drawList, 30000));
updateInfo();
root.append(
el('div.tool.paste-tool', {},
el('div.toolbar', {}, el('strong', {}, 'New paste'), el('span.spacer'), info, btn),
el('div.paste-body', {}, ta, el('div.hint.muted.small', {}, 'Ctrl+Enter to create. Anyone with the link can read it until it expires. Don\'t paste secrets.'), list),
),
);
ta.focus();
}
async function renderView(root, ctx, id, timers) {
ctx.setTitle(id);
let p;
try {
const r = await fetch(`/api/paste/${encodeURIComponent(id)}`);
p = await r.json();
if (!r.ok) throw new Error(p.detail || `HTTP ${r.status}`);
} catch (err) {
forget(id);
root.append(el('div.empty', {}, el('p', {}, err.message), el('a.btn.primary', { href: '/paste' }, 'New paste')));
return;
}
const own = mine().find((m) => m.id === id);
const left = el('span.muted.small', {}, timeLeft(p.expires_at));
timers.push(setInterval(() => (left.textContent = timeLeft(p.expires_at)), 30000));
const lines = p.content.split('\n');
const wrapBtn = el('button.btn', { onclick: () => {
view.classList.toggle('wrap');
store.set('paste:wrap', view.classList.contains('wrap'));
} }, 'Wrap');
const view = el('div.paste-view.mono', {},
el('div.paste-lines', { 'aria-hidden': 'true' }, lines.map((_, i) => i + 1).join('\n')),
el('pre.paste-text', {}, p.content),
);
if (store.get('paste:wrap', false)) view.classList.add('wrap');
root.append(
el('div.tool.paste-tool', {},
el('div.toolbar', {},
el('span.mono.strong', {}, id),
el('span.muted.small', {}, `${formatBytes(p.size)} · ${lines.length} line${lines.length === 1 ? '' : 's'}`),
left,
el('span.spacer'),
el('button.btn', { onclick: () => copyText(`${location.origin}/paste/${id}`, 'Link copied') }, 'Copy link'),
el('button.btn', { onclick: () => copyText(p.content) }, 'Copy text'),
el('a.btn', { href: `/raw/${id}`, target: '_blank', rel: 'noopener' }, 'Raw'),
el('button.btn', { onclick: () => downloadText(p.content, `${id}.txt`) }, 'Download'),
el('a.btn', { href: `/markdown?paste=${id}`, title: 'Render this paste as Markdown' }, 'As Markdown'),
el('a.btn', { href: `/json?paste=${id}`, title: 'Open this paste in the JSON editor' }, 'As JSON'),
wrapBtn,
own && el('button.btn.danger', { onclick: async () => {
if (!confirm('Delete this paste now?')) return;
if (await deletePaste(id, own.delete_token)) {
toast('Deleted');
ctx.navigate('/paste');
} else toast("Couldn't delete", 'error');
} }, 'Delete'),
el('a.btn.primary', { href: '/paste' }, 'New'),
),
view,
),
);
}

159
app/static/js/ui.js Normal file
View file

@ -0,0 +1,159 @@
// 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);
});
}