network-monitor/app/static/js/ui.js

268 lines
10 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// House UI helpers. Plain ES module, no dependencies; pairs with house.css.
// Copy into the project (e.g. static/js/ui.js) unchanged.
//
// Per-browser storage is namespaced by <html data-app="<slug>"> so projects
// on the same origin don't collide.
const NS = (document.documentElement.dataset.app || 'app') + ':';
/** el('button.primary', {onclick}, 'Save'): tag with optional .classes, props/attrs, children.
* String values become attributes; set innerHTML with Object.assign (and only on sanitized HTML). */
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;
}
/** A short confirmation in the corner: toast('Copied'), toast('Upload failed: too large', 'error').
* While a modal dialog is open the toast goes inside it: everything outside a modal sits under
* its backdrop, which would dim the toast. */
export function toast(message, kind = 'info') {
const host = document.querySelector('dialog[open]') || document.body;
let box = [...host.children].find((c) => c.classList.contains('toasts'));
if (!box) {
box = el('div.toasts', { 'aria-live': 'polite' });
host.append(box);
}
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);
}
/** Copies text and toasts `what`; resolves false (and says so) when the browser refuses.
* navigator.clipboard only exists in secure contexts (https, localhost). On plain http, e.g.
* http://10.9.8.10 or http://host.local, it falls back to a hidden textarea + execCommand. */
export async function copyText(text, what = 'Copied') {
let ok = false;
try {
await navigator.clipboard.writeText(text);
ok = true;
} catch {
// Inside an open modal, anything outside the dialog is inert and can't be selected.
const host = document.querySelector('dialog[open]') || document.body;
const before = document.activeElement;
const ta = el('textarea', { readonly: true, 'aria-hidden': 'true', style: 'position:fixed;top:0;left:0;width:1px;height:1px;opacity:0' });
ta.value = text; // a textarea's value attribute is ignored: set the property
host.append(ta);
ta.focus();
ta.select();
try { ok = document.execCommand('copy'); } catch { ok = false; }
ta.remove();
before?.focus?.();
}
toast(ok ? what : 'Couldn’t copy here: select the text and press Ctrl+C (⌘C on a Mac)', ok ? 'info' : 'error');
return ok;
}
/** 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);
}
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 the page.
export const store = {
prefix: NS,
get(key, fallback = null) {
try {
const v = localStorage.getItem(NS + key);
return v == null ? fallback : JSON.parse(v);
} catch {
return fallback;
}
},
set(key, value) {
try {
localStorage.setItem(NS + key, JSON.stringify(value));
} catch {}
},
remove(key) {
try {
localStorage.removeItem(NS + key);
} 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`;
}
/** 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, 'View'). Has .set(value). */
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 lines = value.slice(lineStart, end).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: modal('Title', body, {wide, footer}). Returns the <dialog>; it removes itself when closed. */
export function modal(title, body, { wide = false, footer = null } = {}) {
const dlg = el(`dialog.modal${wide ? '.wide' : ''}`, { 'aria-label': title },
el('div.modal-head', {},
el('h2', {}, title),
el('button.icon-btn', { type: 'button', 'aria-label': 'Close', onclick: () => dlg.close() }, '✕'),
),
el('div.modal-body', {}, body),
footer ? el('div.modal-foot', {}, footer) : null,
);
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;
}
/** Resolves true/false: await confirmDialog('Delete project?', 'This cannot be undone.', 'Delete project'). */
export function confirmDialog(title, message, confirmLabel = 'Confirm', { danger = true } = {}) {
return new Promise((resolve) => {
let ok = false;
const yes = el(`button.btn.${danger ? 'danger' : 'primary'}`, { type: 'button', onclick: () => { ok = true; dlg.close(); } }, confirmLabel);
const no = el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel');
const dlg = modal(title, el('p', {}, message), { footer: [no, yes] });
dlg.addEventListener('close', () => resolve(ok));
yes.focus();
});
}
/** 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', { type: 'button', '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', { type: 'button', 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;
}