// Components of the style sheet (appendix B, mockup 13) as functions: dialogs, menus, short notices, switches, // check boxes, avatars. Keyboard first: every control is a real button or input, focus is always visible. import { h, icon, uid } from './dom.js'; import { t } from './text.js'; // ------------------------------------------------------------------------------------------------- short notices let toasts; /** A short notice at the bottom («Impostazioni salvate.»); errors stay longer. */ export function toast(message, kind = '') { if (!toasts) { toasts = h('div.brevi', { role: 'status', 'aria-live': 'polite' }); document.body.append(toasts); } const item = h(`div.breve${kind ? '.' + kind : ''}`, kind === 'errore' ? icon('octagon-alert', 's') : icon('circle-check', 's'), h('span', message)); toasts.append(item); setTimeout(() => item.remove(), kind === 'errore' ? 8000 : 4000); } /** Shows the message of an error (ApiError or anything else). */ export function showError(error) { if (error && error.name === 'AbortError') return; toast(error && error.message ? error.message : t('comune.errore'), 'errore'); } // ------------------------------------------------------------------------------------------------- dialogs const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])'; /** * Opens a modal dialog over the whole window. build(close) returns { header?, body, footer? } or a node; close(value) * resolves the returned promise. Esc and the veil close with undefined. Focus is trapped and restored. * build may also return onEscape (called first on Esc: returning true means the dialog handled it, say by closing a * list of suggestions, and stays open) and onClose (called once, however the dialog closes). */ export function dialog({ title, className = '', build, labelledBy, dismissable = true }) { return new Promise((resolve) => { const opener = document.activeElement; const titleId = labelledBy || uid('dlg'); let closed = false; const close = (value) => { if (closed) return; closed = true; veil.remove(); document.removeEventListener('keydown', onKey, true); if (parts && typeof parts.onClose === 'function') { try { parts.onClose(); } catch (error) { console.error(error); } } if (opener && opener.focus && document.contains(opener)) opener.focus(); resolve(value); }; const parts = build(close); const box = h(`div.dialogo${className ? '.' + className : ''}`, { role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': titleId }); if (title) { box.append(h('header', h('h2', { id: titleId }, title), dismissable ? h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('comune.chiudi'), onclick: () => close(undefined) }, icon('x')) : null)); } if (parts instanceof Node) box.append(parts); else { if (parts.body) box.append(parts.body); if (parts.footer) box.append(parts.footer); } const veil = h('div.velo.finestra', box); veil.addEventListener('mousedown', (e) => { if (e.target === veil && dismissable) close(undefined); }); const onKey = (e) => { if (e.key === 'Escape' && parts && typeof parts.onEscape === 'function' && parts.onEscape()) { e.stopPropagation(); e.preventDefault(); } else if (e.key === 'Escape' && dismissable) { e.stopPropagation(); close(undefined); } else if (e.key === 'Tab') { const items = [...box.querySelectorAll(FOCUSABLE)].filter((el) => el.offsetParent !== null); if (!items.length) return; const first = items[0], last = items[items.length - 1]; if (e.shiftKey && document.activeElement === first) { last.focus(); e.preventDefault(); } else if (!e.shiftKey && document.activeElement === last) { first.focus(); e.preventDefault(); } } }; document.addEventListener('keydown', onKey, true); document.body.append(veil); const autofocus = box.querySelector('[autofocus]') || box.querySelector('.contenuto ' + FOCUSABLE) || box.querySelector(FOCUSABLE); if (autofocus) autofocus.focus(); }); } /** * A confirmation with explicit buttons that say what happens (spec §10.4). Returns the value of the chosen button, * or undefined when dismissed. buttons: [{ label, value, kind: 'primo'|'pericolo'|'' }]. */ export function confirmDialog({ title, text, extra, buttons }) { return dialog({ title, className: 'piccolo', build: (close) => ({ body: h('div.contenuto', text ? h('p', text) : null, extra || null), footer: h('footer', h('div.destra', buttons.map((b) => h(`button.btn${b.kind ? '.' + b.kind : ''}`, { type: 'button', onclick: () => close(b.value), autofocus: b.autofocus || null }, b.label)))), }), }); } // ------------------------------------------------------------------------------------------------- menus let openMenu = null; /** Closes the open menu, if any. */ export function closeMenu() { if (openMenu) openMenu(); } /** * Opens a menu under an anchor. items: [{ label, icon, value, checked, danger, disabled }] or nodes (a search field, * a separator 'hr'). onPick(value) is called with the chosen value. Arrows move, Esc closes, focus returns to the anchor. */ export function menu(anchor, items, onPick, { role = 'menu', align = 'left', width } = {}) { closeMenu(); const box = h('div.menu', { role, style: width ? { width: `${width}px` } : null }); const entries = []; for (const item of items) { if (item === 'hr') { box.append(h('hr')); continue; } if (item instanceof Node) { box.append(item); continue; } const itemRole = item.checked === undefined ? 'menuitem' : item.radio ? 'menuitemradio' : 'menuitemcheckbox'; const button = h(`button${item.danger ? '.pericolo' : ''}`, { type: 'button', role: itemRole, disabled: item.disabled || null, 'aria-checked': item.checked === undefined ? null : String(Boolean(item.checked)), onclick: () => { if (!item.keepOpen) close(); onPick(item.value, button); }, }, item.icon ? icon(item.icon, 's') : null, h('span', item.label), item.checked === undefined ? null : icon('check', 's segno')); entries.push(button); box.append(button); } document.body.append(box); const rect = anchor.getBoundingClientRect(); const boxWidth = box.offsetWidth; let left = align === 'right' ? rect.right - boxWidth : rect.left; left = Math.max(8, Math.min(left, window.innerWidth - boxWidth - 8)); let top = rect.bottom + 6; if (top + box.offsetHeight > window.innerHeight - 8) top = Math.max(8, rect.top - box.offsetHeight - 6); box.style.left = `${left}px`; box.style.top = `${top}px`; anchor.setAttribute('aria-expanded', 'true'); const onDown = (e) => { if (!box.contains(e.target) && !anchor.contains(e.target)) close(); }; const onKey = (e) => { const focusables = [...box.querySelectorAll('button:not([disabled]),input')]; const index = focusables.indexOf(document.activeElement); if (e.key === 'Escape') { e.stopPropagation(); close(); anchor.focus(); } else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); const next = e.key === 'ArrowDown' ? index + 1 : index - 1; const target = focusables[(next + focusables.length) % focusables.length]; if (target) target.focus(); } else if (e.key === 'Tab') { close(); } }; const onScroll = (e) => { if (!box.contains(e.target)) close(); }; function close() { if (!box.isConnected) return; box.remove(); anchor.setAttribute('aria-expanded', 'false'); document.removeEventListener('mousedown', onDown, true); document.removeEventListener('keydown', onKey, true); document.removeEventListener('scroll', onScroll, true); window.removeEventListener('resize', close); if (openMenu === close) openMenu = null; } setTimeout(() => { document.addEventListener('mousedown', onDown, true); document.addEventListener('scroll', onScroll, true); }); document.addEventListener('keydown', onKey, true); window.addEventListener('resize', close); openMenu = close; const first = box.querySelector('input') || box.querySelector('[aria-checked=true]') || entries[0]; if (first) first.focus(); return { box, close }; } // ------------------------------------------------------------------------------------------------- form controls /** A switch («interruttore»): a real checkbox with role switch, styled as .int. */ export function toggle({ checked, label, hiddenLabel = false, disabled = false, onchange }) { const input = h('input.vh', { type: 'checkbox', role: 'switch', checked, disabled, 'aria-label': hiddenLabel ? label : null }); if (onchange) input.addEventListener('change', () => onchange(input.checked, input)); const el = h('label.leva', input, h('span.int', { 'aria-hidden': 'true' }), hiddenLabel ? null : h('span', label)); el.input = input; return el; } /** A check box («spunta»). */ export function checkbox({ checked, label, disabled = false, onchange, labelNode }) { const input = h('input.vh', { type: 'checkbox', checked, disabled }); if (onchange) input.addEventListener('change', () => onchange(input.checked, input)); const el = h('label.voce', input, h('span.spunta', { 'aria-hidden': 'true' }, icon('check')), labelNode || (label ? h('span', label) : null)); el.input = input; return el; } /** A radio button («tondo»). */ export function radio({ name, value, checked, label, labelNode, onchange }) { const input = h('input.vh', { type: 'radio', name, value, checked }); if (onchange) input.addEventListener('change', () => input.checked && onchange(value, input)); const el = h('label.voce', input, h('span.tondo', { 'aria-hidden': 'true' }), labelNode || (label ? h('span', label) : null)); el.input = input; return el; } /** A segmented control («gruppo»): [{ value, label, icon }]. */ export function segmented({ options, value, label, onchange }) { const group = h('div.gruppo', { role: 'radiogroup', 'aria-label': label }); const buttons = options.map((o) => { const b = h('button', { type: 'button', role: 'radio', 'aria-checked': String(o.value === value), class: o.value === value ? 'qui' : null, tabindex: o.value === value ? '0' : '-1', onclick: () => select(o.value, true), }, o.icon ? icon(o.icon, 's') : null, o.label); b.dataset.value = o.value; return b; }); function select(v, notify) { for (const b of buttons) { const on = b.dataset.value === v; b.classList.toggle('qui', on); b.setAttribute('aria-checked', String(on)); b.tabIndex = on ? 0 : -1; if (on && notify) b.focus(); } if (notify && onchange) onchange(v); } group.addEventListener('keydown', (e) => { if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return; const index = buttons.findIndex((b) => b.classList.contains('qui')); const next = buttons[(index + (e.key === 'ArrowRight' ? 1 : -1) + buttons.length) % buttons.length]; select(next.dataset.value, true); e.preventDefault(); }); group.append(...buttons); group.select = (v) => select(v, false); return group; } // ------------------------------------------------------------------------------------------------- avatars and labels const AVATAR_COLORS = ['#2F6B45', '#2E5E78', '#7A5426', '#8A2E4B', '#5A4699', '#3D6B1F', '#7B3F8C', '#1F6670', '#8C4A2F', '#4B5A8C']; /** «MD» for marta.demo, «LV» for luca.viaggi.demo, «E2» for estate.2019.demo. */ export function initials(username) { const parts = String(username || '?').replace(/^@/, '').split(/[._]/).filter(Boolean); if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase(); return (parts[0] || '?').slice(0, 2).toUpperCase(); } function colorOf(username) { let hash = 0; for (const c of String(username)) hash = (hash * 31 + c.charCodeAt(0)) >>> 0; return AVATAR_COLORS[hash % AVATAR_COLORS.length]; } /** An avatar: the latest profile picture when there is one, otherwise initials on a colour from the name. */ export function avatar(username, size = '', thumb = null) { const el = h(`span.av${size ? '.' + size : ''}`, { 'aria-hidden': 'true', style: { background: colorOf(username) } }); if (thumb) el.append(h('img', { src: `/api/thumbnails/${thumb}`, alt: '', loading: 'lazy' })); else el.textContent = initials(username); return el; } /** A label («etichetta»): et(text, 'accento', 'lock'). */ export function label(text, kind = '', iconName = null) { return h(`span.et${kind ? '.' + kind : ''}`, iconName ? icon(iconName) : null, text); }