diff --git a/carino-clock.js b/carino-clock.js index 1aa9529..9ba11c8 100644 --- a/carino-clock.js +++ b/carino-clock.js @@ -15,6 +15,11 @@ * .beats = Swatch Internet Time (Biel Mean Time = UTC+1, 1 beat = 86.4s) Change the clock here once; every site picks it up on next load. + + Language: the tooltip and the local city name come from a small + dictionary here (es, pt-BR, ja, ru), picked by CarinoLang.current or + ; a site's window.t wins when it has the string. UTC, + EPOCH, TAI and BEATS are names, not words, and stay as they are. ============================================================ */ (function () { 'use strict'; @@ -24,11 +29,58 @@ function pad(n) { return String(n).padStart(2, '0'); } + var TIP = 'Click to toggle Local / UTC / Epoch / TAI / .beats'; + + // The tooltip, plus the city names of the zones the fleet's visitors are + // most often in. Any other zone shows its IANA city name as it is. + var L10N = { + es: { + 'Click to toggle Local / UTC / Epoch / TAI / .beats': 'Haz clic para alternar Local / UTC / Epoch / TAI / .beats', + 'LOCAL': 'LOCAL', 'Mexico City': 'Ciudad de México', 'New York': 'Nueva York', 'Sao Paulo': 'São Paulo', + 'London': 'Londres', 'Tokyo': 'Tokio', 'Moscow': 'Moscú', 'Bogota': 'Bogotá', + }, + 'pt-BR': { + 'Click to toggle Local / UTC / Epoch / TAI / .beats': 'Clique para alternar Local / UTC / Epoch / TAI / .beats', + 'LOCAL': 'LOCAL', 'Mexico City': 'Cidade do México', 'New York': 'Nova York', 'Sao Paulo': 'São Paulo', + 'London': 'Londres', 'Madrid': 'Madri', 'Tokyo': 'Tóquio', 'Moscow': 'Moscou', 'Bogota': 'Bogotá', + }, + ja: { + 'Click to toggle Local / UTC / Epoch / TAI / .beats': 'クリックで切り替え: ローカル / UTC / Epoch / TAI / .beats', + 'LOCAL': 'ローカル', 'Mexico City': 'メキシコシティ', 'New York': 'ニューヨーク', 'Los Angeles': 'ロサンゼルス', + 'Chicago': 'シカゴ', 'Sao Paulo': 'サンパウロ', 'Bogota': 'ボゴタ', 'Madrid': 'マドリード', + 'London': 'ロンドン', 'Tokyo': '東京', 'Moscow': 'モスクワ', + }, + ru: { + 'Click to toggle Local / UTC / Epoch / TAI / .beats': 'Нажмите, чтобы переключить: местное / UTC / Epoch / TAI / .beats', + 'LOCAL': 'МЕСТНОЕ', 'Mexico City': 'Мехико', 'New York': 'Нью-Йорк', 'Los Angeles': 'Лос-Анджелес', + 'Chicago': 'Чикаго', 'Sao Paulo': 'Сан-Паулу', 'Bogota': 'Богота', 'Madrid': 'Мадрид', + 'London': 'Лондон', 'Tokyo': 'Токио', 'Moscow': 'Москва', + }, + }; + function langNow() { + var l = String((window.CarinoLang && window.CarinoLang.current) || document.documentElement.lang || 'en'); + return /^pt/i.test(l) ? 'pt-BR' : l.slice(0, 2).toLowerCase(); + } + function tr(s) { + if (typeof window.t === 'function') { + try { var v = window.t(s); if (typeof v === 'string' && v && v !== s) return v; } catch (e) { /* not i18n */ } + } + var d = L10N[langNow()]; + return (d && d[s]) || s; + } + var LOCAL_TZ = 'LOCAL'; try { LOCAL_TZ = (Intl.DateTimeFormat().resolvedOptions().timeZone || 'LOCAL') .split('/').pop().replace(/_/g, ' ') || 'LOCAL'; } catch (e) { LOCAL_TZ = 'LOCAL'; } + // Looked up once per language, not on every one-second tick. + var tzLang = null, tzLabel = LOCAL_TZ; + function localTz() { + var l = langNow(); + if (l !== tzLang) { tzLang = l; tzLabel = tr(LOCAL_TZ); } + return tzLabel; + } function beats(d) { // Swatch .beats — UTC+1, 1000 beats/day return '@' + String(Math.floor(((d.getTime() + 3600000) % 86400000) / 86400) % 1000).padStart(3, '0'); @@ -46,7 +98,7 @@ } else if (mode === 4) { time = beats(d); tz = 'BEATS'; } else { - time = pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()); tz = LOCAL_TZ; + time = pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()); tz = localTz(); } return { time: time, tz: tz }; } @@ -75,7 +127,7 @@ // partner, double-tapping the clock to cycle modes selects the digits on // any slightly older iPhone or Mac. box.style.webkitUserSelect = 'none'; - box.setAttribute('title', 'Click to toggle Local / UTC / Epoch / TAI / .beats'); + box.setAttribute('title', tr(TIP)); if (!box.hasAttribute('role')) box.setAttribute('role', 'button'); if (!box.hasAttribute('tabindex')) box.setAttribute('tabindex', '0'); function cycle() { c.mode = (c.mode + 1) % MODES; tickAll(); } @@ -104,6 +156,14 @@ if (!document.hidden) tickAll(); }); window.addEventListener('pageshow', tickAll); + // A tick late, so a site's own langchange handler has switched window.t. + function relabel() { + tzLang = null; + for (var i = 0; i < clocks.length; i++) clocks[i].box.setAttribute('title', tr(TIP)); + tickAll(); + } + window.addEventListener('carino:langchange', function () { setTimeout(relabel, 0); }); + document.addEventListener('DOMContentLoaded', function () { setTimeout(relabel, 0); }); // The shared navbar injects its header shortly after load, so re-scan a // few times to catch a `.header-clock` that appears just after we boot. var tries = 0; diff --git a/carino-lang.js b/carino-lang.js index e4c02e9..f40ddf7 100644 --- a/carino-lang.js +++ b/carino-lang.js @@ -29,7 +29,9 @@ window.CarinoLang.set(code) // programmatic switch window.addEventListener('carino:langchange', (e) => e.detail.lang) An app with no dictionary simply stays English — the choice - still persists for the sites that do translate. + still persists for the sites that do translate. The switcher's + own words (its tooltip, "Auto", the legal shield's tooltip) are + translated here, with a site's window.t winning when it has them. Self-contained: styles are inlined and scoped under #cnLangBtn / #cnLangBox with hard-coded colours, so it is safe on light-themed @@ -199,8 +201,12 @@ updateBtn(); renderRows(); window.dispatchEvent(new CustomEvent('carino:langchange', { detail: { lang: current } })); + // Again a tick later, once the site's own handler has switched window.t. + setTimeout(relabel, 0); } + function relabel() { updateBtn(); renderRows(); } + function label(code) { for (var i = 0; i < LANGS.length; i++) if (LANGS[i][0] === code) return LANGS[i][1]; return 'EN'; @@ -221,9 +227,28 @@ var LEGAL = { en: 'Legal notice & privacy', es: 'Aviso legal y privacidad', 'pt-BR': 'Aviso legal e privacidade', ja: '法的通知とプライバシー', ru: 'Правовая информация и конфиденциальность' }; + var TIP = 'Language — Auto follows your browser'; + var L10N = { + es: { 'Language — Auto follows your browser': 'Idioma: Auto sigue a tu navegador', 'Auto': 'Auto' }, + 'pt-BR': { 'Language — Auto follows your browser': 'Idioma: Auto segue o seu navegador', 'Auto': 'Auto' }, + ja: { 'Language — Auto follows your browser': '言語 — 自動はブラウザーの設定に従います', 'Auto': '自動' }, + ru: { 'Language — Auto follows your browser': 'Язык — «Авто» следует настройкам браузера', 'Auto': 'Авто' }, + }; + function tr(s) { + if (typeof window.t === 'function') { + try { var v = window.t(s); if (typeof v === 'string' && v && v !== s) return v; } catch (e) { /* not i18n */ } + } + var d = L10N[current]; + return (d && d[s]) || s; + } + function updateBtn() { var btn = document.getElementById('cnLangBtn'); - if (btn) btn.innerHTML = ICON + '' + (manual ? label(current) : 'AUTO') + ''; + if (btn) { + btn.innerHTML = ICON + '' + (manual ? label(current) : 'AUTO') + ''; + btn.title = tr(TIP); + btn.setAttribute('aria-label', btn.title); + } var legal = document.getElementById('cnLegal'); if (legal) { legal.title = LEGAL[current] || LEGAL.en; legal.setAttribute('aria-label', legal.title); } } @@ -235,7 +260,7 @@ var auto = document.createElement('button'); auto.type = 'button'; auto.className = manual ? '' : 'active'; - auto.innerHTML = 'Auto' + label(resolve(navigator.language) || 'en') + ''; + auto.innerHTML = '' + tr('Auto') + '' + label(resolve(navigator.language) || 'en') + ''; auto.addEventListener('click', function (e) { e.stopPropagation(); set('auto'); @@ -267,11 +292,14 @@ var btn = document.createElement('button'); btn.id = 'cnLangBtn'; btn.type = 'button'; - btn.title = 'Language — Auto follows your browser'; btn.setAttribute('aria-haspopup', 'true'); if (beforeEl) right.insertBefore(btn, beforeEl); else right.appendChild(btn); updateBtn(); + // window.t (the site's i18n.js) loads after this file, still before + // DOMContentLoaded; adding the listener once that has passed is harmless. + document.addEventListener('DOMContentLoaded', function () { setTimeout(relabel, 0); }); + setTimeout(relabel, 0); var box = document.createElement('div'); box.id = 'cnLangBox'; diff --git a/carino-navbar.js b/carino-navbar.js index f438fdd..e024952 100644 --- a/carino-navbar.js +++ b/carino-navbar.js @@ -70,6 +70,13 @@ needs it only some of the time (Asobi: while a game is open, not on its scrolling chooser) switches it at run time instead: window.CarinoNav.immersive(true | false). + + Language. The bar's own words (tooltips, aria-labels, the greeting, + "More") come from a small dictionary in this file for es, pt-BR, ja + and ru, picked by CarinoLang.current (or ), so a site with + no i18n.js of its own still gets them. A site's window.t wins when it + has the string. They re-render on carino:langchange, one tick late so + the site's own handler has switched its dictionary first. ============================================================ */ (function () { 'use strict'; @@ -146,11 +153,91 @@ var LEGAL_URL = 'https://carino.systems/legal.html'; var LEGAL = 'Legal notice & privacy'; + var L10N = { + es: { + 'Carino Systems — back to hub': 'Carino Systems — volver al hub', + '{app} — reload': '{app} — recargar', + '{repo} on GitHub': '{repo} en GitHub', + 'LinkedIn profile': 'Perfil en LinkedIn', + 'More': 'Más', + 'Ready.': 'Listo.', + 'Late shift.': 'Turno nocturno.', + 'Good morning.': 'Buenos días.', + 'Good afternoon.': 'Buenas tardes.', + 'Good evening.': 'Buenas noches.', + }, + 'pt-BR': { + 'Carino Systems — back to hub': 'Carino Systems — voltar ao hub', + '{app} — reload': '{app} — recarregar', + '{repo} on GitHub': '{repo} no GitHub', + 'LinkedIn profile': 'Perfil no LinkedIn', + 'More': 'Mais', + 'Ready.': 'Pronto.', + 'Late shift.': 'Turno da noite.', + 'Good morning.': 'Bom dia.', + 'Good afternoon.': 'Boa tarde.', + 'Good evening.': 'Boa noite.', + }, + ja: { + 'Carino Systems — back to hub': 'Carino Systems — ハブに戻る', + '{app} — reload': '{app} — 再読み込み', + '{repo} on GitHub': 'GitHub の {repo}', + 'LinkedIn profile': 'LinkedIn プロフィール', + 'More': 'その他', + 'Ready.': '準備完了。', + 'Late shift.': '夜勤お疲れさま。', + 'Good morning.': 'おはようございます。', + 'Good afternoon.': 'こんにちは。', + 'Good evening.': 'こんばんは。', + }, + ru: { + 'Carino Systems — back to hub': 'Carino Systems — вернуться в хаб', + '{app} — reload': '{app} — перезагрузить', + '{repo} on GitHub': '{repo} на GitHub', + 'LinkedIn profile': 'Профиль в LinkedIn', + 'More': 'Ещё', + 'Ready.': 'Готово.', + 'Late shift.': 'Ночная смена.', + 'Good morning.': 'Доброе утро.', + 'Good afternoon.': 'Добрый день.', + 'Good evening.': 'Добрый вечер.', + }, + }; + + function langNow() { + var l = String((window.CarinoLang && window.CarinoLang.current) || document.documentElement.lang || 'en'); + return /^pt/i.test(l) ? 'pt-BR' : l.slice(0, 2).toLowerCase(); + } + // A site's window.t answers first; only a string it does not know (t + // hands the key back) falls to the dictionary above. `literal` is the + // finished English ("Learn — reload"), which is how site dictionaries key + // it; `key` is the template with {name} slots, tried after it. + function tr(key, vars, literal) { + var fill = function (s) { + return String(s).replace(/\{(\w+)\}/g, function (m, k) { return vars && k in vars ? vars[k] : m; }); + }; + var en = literal || fill(key); + if (typeof window.t === 'function') { + try { + var v = window.t(en); + if (typeof v === 'string' && v && v !== en) return v; + if (vars) { v = window.t(key); if (typeof v === 'string' && v && v !== key) return fill(v); } + } catch (e) { /* not an i18n function after all */ } + } + var d = L10N[langNow()]; + return d && d[key] ? fill(d[key]) : en; + } + function label(el, text, aria) { + if (!el) return; + el.title = text; + if (aria) el.setAttribute('aria-label', text); + } + var MARKUP = '' + '
' + '
' + '' - + 'Carino' + + 'Carino' + '' + '' + '
' @@ -161,8 +248,8 @@ + '
' + '' + '
' + '
'; @@ -176,14 +263,33 @@ function greet() { var h = new Date().getHours(); var s = h < 5 ? 'Late shift.' : h < 12 ? 'Good morning.' : h < 18 ? 'Good afternoon.' : 'Good evening.'; - set('cnGreeting', (typeof window.t === 'function') ? window.t(s) : s); + set('cnGreeting', tr(s)); } - window.addEventListener('carino:langchange', greet); - // carino-navbar.js is deferred and executes BEFORE i18n.js, so window.t does - // not exist yet when inject() first calls greet(). Each site's i18n.js adopts - // the fleet locale in its own DOMContentLoaded handler, registered after this - // one — so re-render on a timeout, once every handler has finished. - document.addEventListener('DOMContentLoaded', function () { setTimeout(greet, 0); }); + + // Tooltips and aria-labels. The app tag's visible text is the app's name + // and stays as it is. + function relabel() { + var nav = document.getElementById('carinoNav'); + if (!nav) return; + label(nav.querySelector('.brand-name'), tr('Carino Systems — back to hub')); + if (TAG) label(nav.querySelector('.app-tag'), tr('{app} — reload', { app: TAG })); + label(nav.querySelector('#cnGitHub'), REPO ? tr('{repo} on GitHub', { repo: REPO }) : 'GitHub', true); + label(nav.querySelector('#cnLinkedIn'), tr('LinkedIn profile'), true); + var more = nav.querySelector('.cn-more'); + if (more) label(more, tr('More'), true); + } + + // carino-navbar.js is deferred and executes BEFORE carino-lang.js and the + // site's i18n.js, so neither the language nor window.t exists yet when + // inject() first renders. Each site's i18n.js adopts the fleet locale in its + // own DOMContentLoaded or carino:langchange handler, registered after this + // one, so re-render on a timeout, once every handler has finished; the + // refit waits one tick more, for carino-clock.js to repaint its label too. + function rerender() { + setTimeout(function () { relabel(); greet(); setTimeout(queueFit, 0); }, 0); + } + window.addEventListener('carino:langchange', rerender); + document.addEventListener('DOMContentLoaded', rerender); function loadClockModule() { if (document.querySelector('script[data-carino-clock]')) return; @@ -223,8 +329,6 @@ // that fits wins. var fitting = false, fitQueued = false, fitPending = false, fitObserver = null; - function moreLabel() { return (typeof window.t === 'function') ? window.t('More') : 'More'; } - function ensureMore(nav) { var btn = nav.querySelector('.cn-more'); if (btn) return btn; @@ -248,10 +352,7 @@ right.appendChild(keep); right.appendChild(btn); nav.appendChild(menu); - function label() { var l = moreLabel(); btn.title = l; btn.setAttribute('aria-label', l); } - label(); - window.addEventListener('carino:langchange', label); - document.addEventListener('DOMContentLoaded', function () { setTimeout(label, 0); }); + label(btn, tr('More'), true); function open(on) { menu.hidden = !on; btn.setAttribute('aria-expanded', on ? 'true' : 'false'); @@ -378,7 +479,6 @@ function watchFit(nav) { window.addEventListener('resize', queueFit); - window.addEventListener('carino:langchange', queueFit); // carino-lang.js, carino-diag.js and the app add to the bar after this // runs, and apps show or hide their own controls; refit on any of it. // Only the right cluster and the menu are watched (the clock ticks every @@ -456,12 +556,13 @@ wrap.innerHTML = MARKUP; var nav = wrap.firstElementChild; document.body.insertBefore(nav, document.body.firstChild); - if (TAG) { var t = nav.querySelector('.app-tag'); if (t) { t.textContent = TAG; t.title = TAG + ' — reload'; } } + if (TAG) { var t = nav.querySelector('.app-tag'); if (t) t.textContent = TAG; } // On the legal page itself the shield would only link back to this page. if (/\/legal(\.html)?$/.test(location.pathname)) { var legal = nav.querySelector('#cnLegal'); if (legal) legal.remove(); } + relabel(); relocateActions(nav); watchFit(nav); immersive(nav); diff --git a/carino-ui.css b/carino-ui.css index 524214e..07e2a4c 100644 --- a/carino-ui.css +++ b/carino-ui.css @@ -348,6 +348,8 @@ /* .modal on a native : closed, it stays closed (.modal sets display). */ dialog.modal:not([open]) { display: none; } dialog.modal { padding: 0; color: inherit; } + /* keep the fleet's 16px side gutter on a phone (.modal's width replaces the UA margins) */ + dialog.modal { max-width: min(520px, calc(100% - 32px)); } dialog.modal::backdrop { background: rgba(0,0,0,0.65); -webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px); } .modal { display: flex; flex-direction: column; width: 100%; max-width: 520px; diff --git a/carino-ui.js b/carino-ui.js index 77c4010..bd2e0a7 100644 --- a/carino-ui.js +++ b/carino-ui.js @@ -4,8 +4,8 @@ copies it into each site. Load it deferred, after carino-navbar.js: - Three pieces, all opt-in by markup, so loading the file on a page that - uses none of them does nothing: + Four pieces, all opt-in by markup or call, so loading the file on a + page that uses none of them does nothing: 1. Workspace drawer. Below 900px .ws-rail is an off-canvas drawer. Any [data-ws-toggle] button opens and closes it; the scrim, Esc and @@ -26,6 +26,27 @@ 3. Export menu. Every .cs-menu: its [aria-haspopup] button opens the .cs-menu-panel; choosing an item, clicking away or Esc closes it. Items keep their own handlers; the menu only governs visibility. + + 4. Modal. Works on both markups: a .modal-scrim[hidden] holding a + .modal, or a native . Pass the scrim, the + .modal inside it, the , or an element id. + CarinoUI.modal.open(el, { + returnFocus: btn, // optional: default is what had focus + onDismiss(reason) { … }, // optional: Esc / scrim / [data-close] + onClose(reason) { … }, // optional: after it has closed + }); + CarinoUI.modal.close(el); // also .isOpen(el), .top() + Open moves focus to the first control inside (or the card itself) + and keeps Tab inside (a card holding an iframe gets two hidden + focus edges, so Tab out of the iframe wraps back too). Esc, a click on the scrim or ::backdrop, and + any [data-close] button inside dismiss the topmost modal: without + onDismiss that closes it; with onDismiss the page decides (confirm + unsaved changes, then call close). Close restores focus to the + opener and fires "carino:modalclose" on the scrim or + (detail.reason: "escape", "backdrop", "button" or whatever was + passed to close). A page with its own Esc handler leaves Esc alone + while CarinoUI.modal.top() is set, or calls preventDefault() when it + handles the key itself; this one skips a prevented Esc. ============================================================ */ (function () { 'use strict'; @@ -122,6 +143,159 @@ set(false); } + // ---- 4. Modal ---- + var FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), iframe, [tabindex]:not([tabindex="-1"])'; + var stack = []; // open modals, topmost last: { root, box, opts, back } + + // root = what is shown and hidden (the scrim or the ); box = the card. + function resolve(el) { + if (typeof el === 'string') el = document.getElementById(el); + if (!el) return null; + if (el.tagName === 'DIALOG') return { root: el, box: el }; + var scrim = el.classList.contains('modal-scrim') ? el : el.closest('.modal-scrim'); + if (!scrim) return null; + return { root: scrim, box: scrim.querySelector('.modal') || scrim }; + } + function entryOf(root) { + for (var i = stack.length - 1; i >= 0; i--) if (stack[i].root === root) return stack[i]; + return null; + } + function focusables(box) { + return Array.prototype.filter.call(box.querySelectorAll(FOCUSABLE), function (n) { + return n.getClientRects().length > 0 && !n.hasAttribute('data-modal-sentinel'); + }); + } + // Tab out of a cross-origin iframe never reaches our keydown, so a focusable + // edge at each end of the card catches it and wraps it back inside. + function sentinel(box, edge) { + var s = document.createElement('span'); + s.tabIndex = 0; + s.setAttribute('data-modal-sentinel', edge); + s.setAttribute('aria-hidden', 'true'); + s.style.position = 'fixed'; s.style.top = '0'; s.style.left = '0'; + s.style.width = '1px'; s.style.height = '1px'; s.style.overflow = 'hidden'; + s.style.opacity = '0'; s.style.pointerEvents = 'none'; + if (edge === 'start') box.insertBefore(s, box.firstChild); else box.appendChild(s); + return s; + } + function dismiss(entry, reason) { + if (typeof entry.opts.onDismiss !== 'function') { closeModal(entry.root, reason); return; } + // The page's own close path calls close(el) with no reason; it gets this one. + entry.reason = reason; + try { entry.opts.onDismiss(reason); } finally { entry.reason = null; } + } + function wireModal(m) { + if (m.root.dataset.modalReady) return; + m.root.dataset.modalReady = '1'; + // A scrim click counts only when the press started on the scrim too, so + // selecting text in the card and releasing outside does not close it. + var downOnRoot = false; + m.root.addEventListener('pointerdown', function (e) { downOnRoot = e.target === m.root; }); + m.root.addEventListener('click', function (e) { + var entry = entryOf(m.root); + if (!entry) return; + var x = e.target.closest && e.target.closest('[data-close]'); + if (x && m.root.contains(x)) { dismiss(entry, 'button'); return; } + if (e.target !== m.root || !downOnRoot) return; + if (m.root.tagName === 'DIALOG') { + // The is the card, so only a click outside its box is the backdrop. + var r = m.root.getBoundingClientRect(); + if (e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom) return; + } + dismiss(entry, 'backdrop'); + }); + if (m.root.tagName === 'DIALOG') { + m.root.addEventListener('cancel', function (e) { + e.preventDefault(); + var entry = entryOf(m.root); + if (entry) dismiss(entry, 'escape'); + }); + // dialog.close() or a
closes without us: tidy up. + // The event is queued, so it can arrive after closeModal has already + // run and the page has opened the dialog again; that one is stale. + m.root.addEventListener('close', function () { + if (entryOf(m.root) && !m.root.open) closeModal(m.root, m.root.returnValue || 'native'); + }); + } + } + function openModal(el, opts) { + var m = resolve(el); + if (!m) return null; + opts = opts || {}; + var open = entryOf(m.root); + if (open) { + open.opts = opts; + // Closed natively a moment ago, its 'close' event not yet handled: show it again. + if (m.root.tagName === 'DIALOG' && !m.root.open) m.root.showModal(); + return m.root; + } + wireModal(m); + var prev = document.activeElement; + var back = opts.returnFocus || (prev && prev !== document.body ? prev : null); + var edges = m.box.querySelector('iframe') ? [sentinel(m.box, 'start'), sentinel(m.box, 'end')] : []; + stack.push({ root: m.root, box: m.box, opts: opts, back: back, edges: edges }); + if (m.root.tagName === 'DIALOG') { if (!m.root.open) m.root.showModal(); } + else m.root.hidden = false; + // The page may focus a particular field right after this. + var f = focusables(m.box); + if (f.length) f[0].focus({ preventScroll: true }); + else { + if (!m.box.hasAttribute('tabindex')) m.box.setAttribute('tabindex', '-1'); + m.box.focus({ preventScroll: true }); + } + return m.root; + } + function closeModal(el, reason) { + var m = resolve(el); + var entry = m && entryOf(m.root); + if (!entry) return; + stack.splice(stack.indexOf(entry), 1); + entry.edges.forEach(function (s) { if (s.parentNode) s.parentNode.removeChild(s); }); + var active = document.activeElement; + var hadFocus = !active || active === document.body || m.root.contains(active); + if (m.root.tagName === 'DIALOG') { if (m.root.open) m.root.close(); } + else m.root.hidden = true; + // A modal opened from inside this one returns to this one's opener. + stack.forEach(function (o) { if (o.back && m.root.contains(o.back)) o.back = entry.back; }); + var back = entry.back; + if (hadFocus && back && document.contains(back) && back.focus) back.focus({ preventScroll: true }); + reason = reason || entry.reason || 'close'; + if (typeof entry.opts.onClose === 'function') entry.opts.onClose(reason); + m.root.dispatchEvent(new CustomEvent('carino:modalclose', { bubbles: true, detail: { reason: reason } })); + } + function topModal() { return stack.length ? stack[stack.length - 1].root : null; } + + // Capture phase, so the modal answers Esc before the drawer or a menu does. + window.addEventListener('keydown', function (e) { + var entry = stack[stack.length - 1]; + if (!entry) return; + if (e.key === 'Escape') { + if (e.defaultPrevented) return; + e.preventDefault(); + e.stopPropagation(); + dismiss(entry, 'escape'); + return; + } + if (e.key !== 'Tab') return; + var f = focusables(entry.box); + if (!f.length) { e.preventDefault(); return; } + var first = f[0], last = f[f.length - 1], a = document.activeElement; + if (!entry.box.contains(a)) { e.preventDefault(); first.focus(); } + else if (e.shiftKey && (a === first || a === entry.box)) { e.preventDefault(); last.focus(); } + else if (!e.shiftKey && a === last) { e.preventDefault(); first.focus(); } + }, true); + // Focus that leaves anyway (Tab out of an iframe, a click on the page behind + // a scrim the page made see-through) comes back to the top modal. + document.addEventListener('focusin', function (e) { + var entry = stack[stack.length - 1]; + if (!entry) return; + var edge = e.target.getAttribute && e.target.getAttribute('data-modal-sentinel'); + if (!edge && entry.box.contains(e.target)) return; + var f = focusables(entry.box); + var to = edge === 'start' ? f[f.length - 1] : f[0]; + (to || entry.box).focus({ preventScroll: true }); + }); + function boot() { Array.prototype.forEach.call(document.querySelectorAll('.ws'), initDrawer); Array.prototype.forEach.call(document.querySelectorAll('.cs-menu'), initMenu); @@ -129,5 +303,11 @@ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot(); - window.CarinoUI = { slices: slices, drawer: initDrawer, menu: initMenu, parseHash: parseHash }; + window.CarinoUI = { + slices: slices, drawer: initDrawer, menu: initMenu, parseHash: parseHash, + modal: { + open: openModal, close: closeModal, top: topModal, + isOpen: function (el) { var m = resolve(el); return !!(m && entryOf(m.root)); }, + }, + }; })();