@aitrien/motifspec 1.26.0 → 1.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/codex.js CHANGED
@@ -1,9 +1,12 @@
1
1
  // MotifSpec behaviour: theme toggle, the backdrop header's scroll state, tooltip dismissal, code copy buttons,
2
- // TOC docking and active section, alert dismissal and toasts.
2
+ // TOC docking and active section, alert dismissal, toasts, date pickers and dialogs.
3
3
  // Shipped as dist/codex.js (@aitrien/motifspec/codex.js).
4
4
  // Enhancement only. Without this script: themes follow the system, code is selectable, the TOC is a plain open list,
5
5
  // and every control that needs script stays hidden. Load it with `defer`; it also works inline at the end of <body>.
6
6
  // Pair it with dist/theme-init.js inline in <head>, which applies a stored theme before first paint.
7
+ // Pages that change without a reload (Turbo in Rails, or anything that fires turbo:load): listeners on the document
8
+ // are set once, and each page's elements are set up again after every visit, frame load and morph. An element is
9
+ // never set up twice, and anything left open is closed before Turbo caches the page.
7
10
  (function () {
8
11
  'use strict';
9
12
  var root = document.documentElement;
@@ -31,18 +34,373 @@
31
34
  function ms(name) {
32
35
  var v = getComputedStyle(root).getPropertyValue(name).trim();
33
36
  return v.endsWith('ms') ? parseFloat(v) : parseFloat(v) * 1000;
37
+ } // A length token in pixels, measured by the browser, so rem, clamp() and calc() values all resolve.
38
+ function px(name) {
39
+ var probe = document.createElement('div');
40
+ probe.style.cssText = 'position:absolute;visibility:hidden;pointer-events:none;inline-size:var(' + name + ')';
41
+ (document.body || document.documentElement).appendChild(probe);
42
+ var w = probe.getBoundingClientRect().width;
43
+ probe.remove();
44
+ return w;
34
45
  }
35
46
 
47
+
36
48
  var theme = read();
37
49
  apply(theme);
38
50
  if (system && system.addEventListener) system.addEventListener('change', function () { apply(theme); });
39
51
 
52
+ // Set-up bookkeeping, so it can run on every page a Turbo visit brings in. fresh() is true the first time an
53
+ // element is set up for a job (an element restored from Turbo's cache is a new element, so it's set up again).
54
+ // watch() and observe() tie a window listener or an observer to an element, and drop it once that element leaves
55
+ // the page, so visits don't pile them up.
56
+ var done = new WeakMap();
57
+ function fresh(el, job) {
58
+ var jobs = done.get(el);
59
+ if (!jobs) { jobs = {}; done.set(el, jobs); }
60
+ if (jobs[job]) return false;
61
+ jobs[job] = true; return true;
62
+ }
63
+ function each(selector, fn) { Array.prototype.forEach.call(document.querySelectorAll(selector), fn); }
64
+ var watchers = { resize: [], scroll: [] };
65
+ function watch(type, el, fn) { watchers[type].push({ el: el, fn: fn }); }
66
+ function run(type) {
67
+ watchers[type] = watchers[type].filter(function (w) { return w.el.isConnected; });
68
+ watchers[type].forEach(function (w) { w.fn(); });
69
+ }
70
+ window.addEventListener('resize', function () { run('resize'); });
71
+ window.addEventListener('scroll', function () { run('scroll'); }, { passive: true });
72
+ var observers = [];
73
+ function observe(el, observer, target) {
74
+ if (target !== undefined) observer.observe(target);
75
+ else if (observer.observe && !(observer instanceof IntersectionObserver)) observer.observe(el);
76
+ observers.push({ el: el, observer: observer });
77
+ return observer;
78
+ }
79
+ function sweep() {
80
+ observers = observers.filter(function (o) { if (o.el.isConnected) return true; o.observer.disconnect(); return false; });
81
+ }
82
+ var openers = new WeakMap();
83
+
40
84
  function ready(fn) { if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn); else fn(); }
41
85
 
42
- ready(function () {
86
+ // ------------------------------------------------------------ once: listeners on the document
87
+ // Escape hides any open tooltip without moving the pointer or focus (WCAG 1.4.13).
88
+ document.addEventListener('keydown', function (e) {
89
+ if (e.key !== 'Escape') return;
90
+ document.querySelectorAll('.cx-tooltip').forEach(function (t) { t.parentElement.classList.add('is-tooltip-dismissed'); });
91
+ });
92
+
93
+ // The docs header's panels close on Escape and on a click outside them, whichever page they're on.
94
+ var headerPanels = function () { return Array.prototype.slice.call(document.querySelectorAll('.cx-header__toc, .cx-header__menu')); };
95
+ document.addEventListener('keydown', function (e) {
96
+ if (e.key !== 'Escape') return;
97
+ headerPanels().forEach(function (d) { if (d.open) { d.open = false; d.querySelector('summary').focus(); } });
98
+ });
99
+ document.addEventListener('click', function (e) { headerPanels().forEach(function (d) { if (d.open && !d.contains(e.target)) d.open = false; }); });
100
+
101
+ // Inside a component preview, links don't navigate.
102
+ document.addEventListener('click', function (e) {
103
+ if (document.body && document.body.classList.contains('cx-preview-body') && e.target.closest && e.target.closest('a[href]')) e.preventDefault();
104
+ });
105
+
106
+ // Search's shortcut: Ctrl+K or Cmd+K, or "/" outside a text field, opens the page's search.
107
+ document.addEventListener('keydown', function (e) {
108
+ var dialog = document.querySelector('.cx-search[data-search]'), open = dialog && openers.get(dialog);
109
+ if (!open) return;
110
+ var typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName) || document.activeElement.isContentEditable;
111
+ if (((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') || (e.key === '/' && !typing && !e.ctrlKey && !e.metaKey && !e.altKey)) {
112
+ e.preventDefault(); open();
113
+ }
114
+ });
115
+
116
+ // Alert dismissal (alert.md): pressing the button hides its alert, and with a key keeps it hidden on later pages.
117
+ // Focus moves to the main column, since the button it was on has gone. One listener on the document, so an alert
118
+ // on any page, or added later, works the same way.
119
+ var dismissed = function (key) { try { return Boolean(key) && localStorage.getItem('cx-alert:' + key) === 'dismissed'; } catch (e) { return false; } };
120
+ document.addEventListener('click', function (e) {
121
+ var btn = e.target.closest && e.target.closest('.cx-alert [data-alert-dismiss]');
122
+ if (!btn) return;
123
+ var key = btn.dataset.alertDismiss;
124
+ btn.closest('.cx-alert').hidden = true;
125
+ if (key) { try { localStorage.setItem('cx-alert:' + key, 'dismissed'); } catch (err) { /* storage blocked: hidden for this view only */ } }
126
+ var main = document.getElementById('main');
127
+ if (main) main.focus({ preventScroll: true });
128
+ });
129
+
130
+
131
+ // Toasts (toast.md): document.dispatchEvent(new CustomEvent('cx-toast', { detail: { text: 'Saved', kind: 'success' } })).
132
+ // One polite live region per page, made here if the page has none, holds up to three; each goes after
133
+ // motion.duration.toast, a time that starts again while the pointer or focus is on it. Escape inside one, or its
134
+ // button, closes it. The text is set as text, never as HTML.
135
+ var toastRegion = function () {
136
+ var region = document.querySelector('.cx-toasts');
137
+ if (!region) {
138
+ region = document.createElement('div'); region.className = 'cx-toasts'; region.setAttribute('role', 'status');
139
+ document.body.appendChild(region);
140
+ }
141
+ return region;
142
+ };
143
+ var toastIcon = function (id, cls) {
144
+ var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
145
+ svg.setAttribute('class', 'cx-icon cx-icon--sm' + (cls ? ' ' + cls : '')); svg.setAttribute('aria-hidden', 'true'); svg.setAttribute('focusable', 'false');
146
+ var use = document.createElementNS('http://www.w3.org/2000/svg', 'use'); use.setAttribute('href', '#cx-icon-' + id);
147
+ svg.appendChild(use); return svg;
148
+ };
149
+ var closeToast = function (toast) {
150
+ if (toast.classList.contains('is-leaving')) return;
151
+ clearTimeout(toast._cxTimer);
152
+ var hadFocus = toast.contains(document.activeElement);
153
+ toast.classList.add('is-leaving'); toast.classList.remove('is-shown');
154
+ setTimeout(function () { toast.remove(); }, ms('--cx-motion-duration-base'));
155
+ if (hadFocus) { var main = document.getElementById('main'); if (main) main.focus({ preventScroll: true }); }
156
+ };
157
+ document.addEventListener('cx-toast', function (e) {
158
+ var d = e.detail || {};
159
+ if (!d.text) return;
160
+ var toast = document.createElement('div'); toast.className = 'cx-toast';
161
+ if (d.kind === 'success') toast.appendChild(toastIcon('check'));
162
+ var p = document.createElement('p'); p.className = 'cx-toast__text'; p.textContent = d.text; toast.appendChild(p);
163
+ var btn = document.createElement('button'); btn.type = 'button'; btn.className = 'cx-toast__dismiss'; btn.setAttribute('aria-label', 'Dismiss');
164
+ btn.appendChild(toastIcon('close')); btn.addEventListener('click', function () { closeToast(toast); }); toast.appendChild(btn);
165
+ var wait = function () { clearTimeout(toast._cxTimer); toast._cxTimer = setTimeout(function () { closeToast(toast); }, ms('--cx-motion-duration-toast')); };
166
+ var hold = function () { clearTimeout(toast._cxTimer); };
167
+ toast.addEventListener('mouseenter', hold); toast.addEventListener('focusin', hold);
168
+ toast.addEventListener('mouseleave', function () { if (!toast.contains(document.activeElement)) wait(); });
169
+ toast.addEventListener('focusout', function (ev) { if (!toast.contains(ev.relatedTarget) && !toast.matches(':hover')) wait(); });
170
+ toast.addEventListener('keydown', function (ev) { if (ev.key === 'Escape') { ev.stopPropagation(); closeToast(toast); } });
171
+ var region = toastRegion();
172
+ var live = region.querySelectorAll('.cx-toast:not(.is-leaving)');
173
+ if (live.length >= 3) closeToast(live[0]);
174
+ region.appendChild(toast);
175
+ window.requestAnimationFrame(function () { window.requestAnimationFrame(function () { toast.classList.add('is-shown'); }); });
176
+ wait();
177
+ });
178
+
179
+ // Dialogs (dialog.md): [data-dialog-open="id"] opens a .cx-dialog with showModal(), which moves focus in, closes on
180
+ // Escape and returns focus when closed. [data-dialog-close] inside one closes it, and so does a click on the
181
+ // backdrop, unless the dialog has data-dialog-keep (a form, whose typing a stray click would lose).
182
+ document.addEventListener('click', function (e) {
183
+ var t = e.target.closest ? e.target : null;
184
+ if (!t) return;
185
+ var opener = t.closest('[data-dialog-open]');
186
+ if (opener) {
187
+ var d = document.getElementById(opener.dataset.dialogOpen);
188
+ if (d && d.showModal && !d.open) d.showModal();
189
+ return;
190
+ }
191
+ var dialog = t.closest('dialog.cx-dialog');
192
+ if (!dialog) return;
193
+ if (t.closest('[data-dialog-close]')) { dialog.close(); return; }
194
+ if (t === dialog && !dialog.hasAttribute('data-dialog-keep')) {
195
+ var r = dialog.getBoundingClientRect();
196
+ if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) dialog.close();
197
+ }
198
+ });
199
+
200
+ // Date pickers (date-picker.md): each [data-date-picker] box gets its calendar button, and the page gets one
201
+ // calendar, made the first time it's opened. Dates are day first (DD/MM/YYYY) and weeks start on Monday. The
202
+ // calendar sits under its field, or above it when there's more room there, in page coordinates so it scrolls
203
+ // with the field. Days, months and years are each a grid with one tab stop, moved by the arrow keys.
204
+ var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
205
+ var DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
206
+ var PAGE = 20;
207
+ var placing = false, cal = null, calBody, calDays, calList, calTitle, monthBtn, yearBtn, navs;
208
+ var field = null, opener = null, selected = null, focusDay = null, view = 'days';
209
+ var today = function () { var n = new Date(); return new Date(n.getFullYear(), n.getMonth(), n.getDate()); };
210
+ var same = function (a, b) { return a && b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate(); };
211
+ var pad = function (n) { return String(n).padStart(2, '0'); };
212
+ var parse = function (v) {
213
+ var m = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(v.trim());
214
+ if (!m) return null;
215
+ var d = new Date(+m[3], +m[2] - 1, +m[1]);
216
+ return d.getMonth() === +m[2] - 1 ? d : null;
217
+ };
218
+ var clampDay = function (y, m, d) { return new Date(y, m, Math.min(d, new Date(y, m + 1, 0).getDate())); };
219
+ var icon = function (id) {
220
+ var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
221
+ svg.setAttribute('class', 'cx-icon'); svg.setAttribute('aria-hidden', 'true'); svg.setAttribute('focusable', 'false');
222
+ var use = document.createElementNS('http://www.w3.org/2000/svg', 'use'); use.setAttribute('href', '#cx-icon-' + id);
223
+ svg.appendChild(use); return svg;
224
+ };
225
+ var el = function (tag, cls, attrs) {
226
+ var n = document.createElement(tag); if (cls) n.className = cls;
227
+ Object.keys(attrs || {}).forEach(function (k) { n.setAttribute(k, attrs[k]); });
228
+ return n;
229
+ };
230
+ var build = function () {
231
+ // a page restored from Turbo's cache can bring a copy of the last calendar with it
232
+ each('.cx-calendar', function (old) { old.remove(); });
233
+ cal = el('div', 'cx-calendar', { popover: '', role: 'dialog', 'aria-label': 'Choose a date' });
234
+ var head = el('div', 'cx-calendar__head');
235
+ var prev = el('button', 'cx-calendar__nav', { type: 'button', 'data-step': '-1' }); prev.appendChild(icon('arrow-back'));
236
+ var next = el('button', 'cx-calendar__nav', { type: 'button', 'data-step': '1' }); next.appendChild(icon('arrow-forward'));
237
+ var pick = el('div', 'cx-calendar__pickers');
238
+ monthBtn = el('button', 'cx-calendar__pick', { type: 'button', 'aria-expanded': 'false' });
239
+ yearBtn = el('button', 'cx-calendar__pick', { type: 'button', 'aria-expanded': 'false' });
240
+ [monthBtn, yearBtn].forEach(function (b) { b.appendChild(document.createElement('span')); b.appendChild(icon('expand')); pick.appendChild(b); });
241
+ head.appendChild(prev); head.appendChild(pick); head.appendChild(next);
242
+ calTitle = el('p', 'cx-visually-hidden', { 'aria-live': 'polite' });
243
+ calDays = el('table', 'cx-calendar__grid', { role: 'grid' });
244
+ var thead = el('thead'), tr = el('tr');
245
+ [1, 2, 3, 4, 5, 6, 0].forEach(function (i) { var th = el('th', '', { scope: 'col', abbr: DAYS[i] }); th.textContent = DAYS[i].slice(0, 2); tr.appendChild(th); });
246
+ thead.appendChild(tr); calDays.appendChild(thead); calBody = el('tbody'); calDays.appendChild(calBody);
247
+ calList = el('div', 'cx-calendar__list'); calList.hidden = true;
248
+ var foot = el('div', 'cx-calendar__foot');
249
+ var todayBtn = el('button', '', { type: 'button' }); todayBtn.textContent = 'Today';
250
+ var closeBtn = el('button', '', { type: 'button' }); closeBtn.textContent = 'Close';
251
+ foot.appendChild(todayBtn); foot.appendChild(closeBtn);
252
+ [head, calTitle, calDays, calList, foot].forEach(function (n) { cal.appendChild(n); });
253
+ document.body.appendChild(cal);
254
+ navs = [prev, next];
255
+ var labelId = 'cx-calendar-title'; calTitle.id = labelId; calDays.setAttribute('aria-labelledby', labelId);
256
+ monthBtn.setAttribute('aria-controls', 'cx-calendar-list'); yearBtn.setAttribute('aria-controls', 'cx-calendar-list'); calList.id = 'cx-calendar-list';
257
+
258
+ calBody.addEventListener('click', function (e) {
259
+ var b = e.target.closest('.cx-calendar__day'); if (!b) return;
260
+ var v = b.dataset.value.split('-'); choose(new Date(+v[0], +v[1], +v[2]));
261
+ });
262
+ calList.addEventListener('click', function (e) {
263
+ var b = e.target.closest('.cx-calendar__cell'); if (!b) return;
264
+ var v = +b.dataset.value;
265
+ if (view === 'years') { focusDay = clampDay(v, focusDay.getMonth(), focusDay.getDate()); setView('months'); }
266
+ else { focusDay = clampDay(focusDay.getFullYear(), v, focusDay.getDate()); setView('days'); }
267
+ });
268
+ monthBtn.addEventListener('click', function () { setView(view === 'months' ? 'days' : 'months'); });
269
+ yearBtn.addEventListener('click', function () { setView(view === 'years' ? 'days' : 'years'); });
270
+ navs.forEach(function (n) {
271
+ n.addEventListener('click', function () {
272
+ var st = +n.dataset.step, y = focusDay.getFullYear(), m = focusDay.getMonth(), d = focusDay.getDate();
273
+ focusDay = view === 'days' ? clampDay(y, m + st, d) : view === 'months' ? clampDay(y + st, m, d) : clampDay(y + st * PAGE, m, d);
274
+ render(false);
275
+ });
276
+ });
277
+ todayBtn.addEventListener('click', function () { view = 'days'; focusDay = today(); render(true); });
278
+ closeBtn.addEventListener('click', close);
279
+ cal.addEventListener('toggle', function (e) { if (e.newState !== 'open') view = 'days'; });
280
+ calBody.addEventListener('keydown', function (e) {
281
+ var d = new Date(focusDay), k = e.key;
282
+ if (k === 'ArrowLeft') d.setDate(d.getDate() - 1);
283
+ else if (k === 'ArrowRight') d.setDate(d.getDate() + 1);
284
+ else if (k === 'ArrowUp') d.setDate(d.getDate() - 7);
285
+ else if (k === 'ArrowDown') d.setDate(d.getDate() + 7);
286
+ else if (k === 'PageUp') d = clampDay(d.getFullYear(), d.getMonth() - 1, d.getDate());
287
+ else if (k === 'PageDown') d = clampDay(d.getFullYear(), d.getMonth() + 1, d.getDate());
288
+ else if (k === 'Home') d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
289
+ else if (k === 'End') d.setDate(d.getDate() + (6 - (d.getDay() + 6) % 7));
290
+ else return;
291
+ e.preventDefault(); focusDay = d; render(true);
292
+ });
293
+ calList.addEventListener('keydown', function (e) {
294
+ var cols = view === 'years' ? 4 : 3, k = e.key, y = focusDay.getFullYear(), m = focusDay.getMonth(), dd = focusDay.getDate(), delta = 0;
295
+ if (k === 'ArrowLeft') delta = -1; else if (k === 'ArrowRight') delta = 1;
296
+ else if (k === 'ArrowUp') delta = -cols; else if (k === 'ArrowDown') delta = cols;
297
+ else if (k === 'PageUp') delta = view === 'years' ? -PAGE : -12; else if (k === 'PageDown') delta = view === 'years' ? PAGE : 12;
298
+ else return;
299
+ e.preventDefault();
300
+ if (view === 'months' && Math.abs(delta) < 12) { if (m + delta < 0 || m + delta > 11) return; focusDay = clampDay(y, m + delta, dd); }
301
+ else focusDay = view === 'years' ? clampDay(y + delta, m, dd) : clampDay(y + delta / 12, m, dd);
302
+ render(true);
303
+ });
304
+ if (!placing) { placing = true; window.addEventListener('resize', place); document.addEventListener('scroll', place, true); }
305
+ };
306
+ var cell = function (cls, text, label, o) {
307
+ var b = el('button', cls, { type: 'button', 'aria-label': label, 'aria-pressed': o.pressed ? 'true' : 'false' });
308
+ if (o.current) b.setAttribute('aria-current', 'date');
309
+ b.textContent = text; b.tabIndex = o.focus ? 0 : -1; b.dataset.value = o.value;
310
+ return b;
311
+ };
312
+ var render = function (moveFocus) {
313
+ var y = focusDay.getFullYear(), m = focusDay.getMonth(), now = today();
314
+ monthBtn.firstChild.textContent = MONTHS[m]; yearBtn.firstChild.textContent = y;
315
+ monthBtn.setAttribute('aria-expanded', String(view === 'months')); yearBtn.setAttribute('aria-expanded', String(view === 'years'));
316
+ monthBtn.setAttribute('aria-label', 'Choose the month, ' + MONTHS[m]); yearBtn.setAttribute('aria-label', 'Choose the year, ' + y);
317
+ calDays.hidden = view !== 'days'; calList.hidden = view === 'days';
318
+ var labels = { days: ['Previous month', 'Next month'], months: ['Previous year', 'Next year'], years: ['Previous ' + PAGE + ' years', 'Next ' + PAGE + ' years'] }[view];
319
+ navs[0].setAttribute('aria-label', labels[0]); navs[1].setAttribute('aria-label', labels[1]);
320
+ if (view === 'days') {
321
+ calTitle.textContent = MONTHS[m] + ' ' + y;
322
+ var first = new Date(y, m, 1), start = new Date(y, m, 1 - ((first.getDay() + 6) % 7));
323
+ calBody.textContent = '';
324
+ for (var w = 0; w < 6; w++) {
325
+ var row = el('tr');
326
+ for (var i = 0; i < 7; i++) {
327
+ var d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + w * 7 + i), td = el('td');
328
+ td.appendChild(cell('cx-calendar__day' + (d.getMonth() !== m ? ' is-other' : ''), d.getDate(),
329
+ DAYS[d.getDay()] + ' ' + d.getDate() + ' ' + MONTHS[d.getMonth()] + ' ' + d.getFullYear(),
330
+ { pressed: same(d, selected), current: same(d, now), focus: same(d, focusDay), value: d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate() }));
331
+ row.appendChild(td);
332
+ }
333
+ calBody.appendChild(row);
334
+ }
335
+ } else if (view === 'months') {
336
+ calTitle.textContent = 'Months of ' + y; calList.className = 'cx-calendar__list cx-calendar__list--months'; calList.textContent = '';
337
+ MONTHS.forEach(function (name, i) {
338
+ calList.appendChild(cell('cx-calendar__cell', name.slice(0, 3), name + ' ' + y,
339
+ { pressed: selected && selected.getFullYear() === y && selected.getMonth() === i, current: now.getFullYear() === y && now.getMonth() === i, focus: i === m, value: i }));
340
+ });
341
+ } else {
342
+ var from = Math.floor(y / PAGE) * PAGE;
343
+ calTitle.textContent = from + ' to ' + (from + PAGE - 1); calList.className = 'cx-calendar__list cx-calendar__list--years'; calList.textContent = '';
344
+ for (var k = from; k < from + PAGE; k++) {
345
+ calList.appendChild(cell('cx-calendar__cell', k, String(k), { pressed: selected && selected.getFullYear() === k, current: now.getFullYear() === k, focus: k === y, value: k }));
346
+ }
347
+ }
348
+ place();
349
+ if (moveFocus) { var f = (view === 'days' ? calBody : calList).querySelector('[tabindex="0"]'); if (f) f.focus(); }
350
+ };
351
+ var setView = function (v) { view = v; render(true); };
352
+ var place = function () {
353
+ if (!cal || !field || !cal.matches(':popover-open')) return;
354
+ var r = field.getBoundingClientRect(), vw = document.documentElement.clientWidth, h = cal.offsetHeight, w = cal.offsetWidth, gap = px('--cx-space-inline-xs'), edge = px('--cx-space-inline-sm');
355
+ var below = window.innerHeight - r.bottom - gap, above = r.top - gap;
356
+ var top = (below < h && above > below) ? r.top - h - gap : r.bottom + gap;
357
+ cal.style.top = (top + window.scrollY) + 'px';
358
+ cal.style.left = (Math.max(edge, Math.min(r.left, vw - w - edge)) + window.scrollX) + 'px';
359
+ };
360
+ var close = function () { cal.hidePopover(); if (opener) opener.focus(); };
361
+ var choose = function (d) {
362
+ selected = d;
363
+ var input = field.querySelector('.cx-field__control');
364
+ input.value = pad(d.getDate()) + '/' + pad(d.getMonth() + 1) + '/' + d.getFullYear();
365
+ input.dispatchEvent(new Event('input', { bubbles: true })); input.dispatchEvent(new Event('change', { bubbles: true }));
366
+ close();
367
+ };
368
+ var setUpPicker = function (box) {
369
+ var btn = box.querySelector('.cx-date__button');
370
+ if (!btn || !HTMLElement.prototype.hasOwnProperty('popover')) return;
371
+ btn.hidden = false;
372
+ if (!fresh(btn, 'date')) return;
373
+ btn.addEventListener('click', function () {
374
+ if (!cal || !cal.isConnected) build();
375
+ if (cal.matches(':popover-open') && opener === btn) { cal.hidePopover(); return; }
376
+ if (cal.matches(':popover-open')) cal.hidePopover();
377
+ opener = btn; field = box;
378
+ selected = parse(box.querySelector('.cx-field__control').value);
379
+ focusDay = new Date(selected || today()); view = 'days';
380
+ cal.setAttribute('aria-label', btn.getAttribute('aria-label') || 'Choose a date');
381
+ cal.showPopover(); render(true);
382
+ });
383
+ };
384
+
385
+ // Before Turbo caches a page for the back button, close what's open on it, so it isn't restored open.
386
+ document.addEventListener('turbo:before-cache', function () {
387
+ each('.cx-calendar', function (c) { if (c.matches(':popover-open')) c.hidePopover(); });
388
+ each('dialog[open]', function (dlg) { dlg.close(); });
389
+ each('.cx-toast', function (t) { t.remove(); });
390
+ each('.cx-header__toc[open], .cx-header__menu[open]', function (dt) { dt.open = false; });
391
+ });
392
+
393
+ // The first page now, and each page Turbo brings in after it.
394
+ ready(page);
395
+ ['turbo:load', 'turbo:frame-load', 'turbo:morph'].forEach(function (type) { document.addEventListener(type, page); });
396
+
397
+ // ------------------------------------------------------------ each page: its elements
398
+ function page() {
399
+ sweep();
43
400
  apply(theme);
44
- document.querySelectorAll('[data-theme-toggle]').forEach(function (b) {
401
+ each('[data-theme-toggle]', function (b) {
45
402
  b.hidden = false;
403
+ if (!fresh(b, 'theme')) return;
46
404
  b.addEventListener('click', function () {
47
405
  var next = shown(theme) === 'dark' ? 'light' : 'dark';
48
406
  theme = next === sys() ? 'auto' : next; // matching the system again means following it again
@@ -50,13 +408,10 @@
50
408
  });
51
409
  });
52
410
 
53
- // Escape hides any open tooltip without moving the pointer or focus (WCAG 1.4.13).
54
- document.addEventListener('keydown', function (e) {
55
- if (e.key !== 'Escape') return;
56
- document.querySelectorAll('.cx-tooltip').forEach(function (t) { t.parentElement.classList.add('is-tooltip-dismissed'); });
57
- });
58
- document.querySelectorAll('.cx-tooltip').forEach(function (t) {
411
+ // Tooltips: a dismissed one comes back once the pointer or focus leaves its host.
412
+ each('.cx-tooltip', function (t) {
59
413
  var host = t.parentElement;
414
+ if (!fresh(host, 'tooltip')) return;
60
415
  var reset = function () { host.classList.remove('is-tooltip-dismissed'); };
61
416
  host.addEventListener('mouseleave', reset);
62
417
  host.addEventListener('focusout', reset);
@@ -64,7 +419,7 @@
64
419
 
65
420
  // The sticky header's height, for scroll-padding-top and the docked TOC: it wraps to two rows on narrow screens.
66
421
  var header = document.querySelector('.cx-header');
67
- if (header) {
422
+ if (header && fresh(header, 'measure')) {
68
423
  var end = header.querySelector('.cx-header__end'), mark = header.querySelector('.cx-wordmark');
69
424
  var measure = function () {
70
425
  root.style.setProperty('--_header-height', header.offsetHeight + 'px');
@@ -73,7 +428,7 @@
73
428
  if (end && mark) header.toggleAttribute('data-wrapped', end.offsetTop > mark.offsetTop + mark.offsetHeight / 2);
74
429
  };
75
430
  measure();
76
- if ('ResizeObserver' in window) new ResizeObserver(measure).observe(header); else window.addEventListener('resize', measure);
431
+ if ('ResizeObserver' in window) observe(header, new ResizeObserver(measure)); else watch('resize', header, measure);
77
432
  }
78
433
 
79
434
  // Backdrop pages: the header starts on the frost and scrolls with the page. Once the script marks it, it sticks,
@@ -81,34 +436,30 @@
81
436
  // Without this script it keeps scrolling away, which is safe: it never sits see-through over the text.
82
437
  // A docs header (cx-header--docs) is marked the same way, so it shows the wordmark in full at the top of the page
83
438
  // and compacts once the page scrolls.
84
- document.querySelectorAll('.cx-backdrop-page .cx-header, .cx-header--docs').forEach(function (header) {
439
+ each('.cx-backdrop-page .cx-header, .cx-header--docs', function (header) {
440
+ if (!fresh(header, 'scrolled')) return;
85
441
  var queued = false;
86
442
  var set = function () { queued = false; header.setAttribute('data-scrolled', window.scrollY > 0 ? 'true' : 'false'); };
87
443
  set();
88
- window.addEventListener('scroll', function () { if (!queued) { queued = true; window.requestAnimationFrame(set); } }, { passive: true });
444
+ watch('scroll', header, function () { if (!queued) { queued = true; window.requestAnimationFrame(set); } });
89
445
  });
90
446
 
91
447
  // The docs header's "On this page" and menu are <details>, so they open and close without script. With it, one
92
448
  // opens at a time, and they close on Escape, on a click outside them, and when a link in them is followed.
93
449
  var panels = Array.prototype.slice.call(document.querySelectorAll('.cx-header__toc, .cx-header__menu'));
94
450
  panels.forEach(function (d) {
451
+ if (!fresh(d, 'panel')) return;
95
452
  d.addEventListener('toggle', function () { if (d.open) panels.forEach(function (o) { if (o !== d) o.open = false; }); });
96
453
  d.addEventListener('click', function (e) { if (e.target.closest('a[href]')) d.open = false; });
97
454
  });
98
- if (panels.length) {
99
- document.addEventListener('keydown', function (e) {
100
- if (e.key !== 'Escape') return;
101
- panels.forEach(function (d) { if (d.open) { d.open = false; d.querySelector('summary').focus(); } });
102
- });
103
- document.addEventListener('click', function (e) { panels.forEach(function (d) { if (d.open && !d.contains(e.target)) d.open = false; }); });
104
- }
105
455
 
106
456
  // Copy buttons on code blocks.
107
- document.querySelectorAll('.cx-code').forEach(function (block) {
457
+ each('.cx-code', function (block) {
108
458
  var btn = block.querySelector('.cx-code__copy');
109
459
  var code = block.querySelector('pre code');
110
460
  if (!btn || !code) return;
111
461
  btn.hidden = false;
462
+ if (!fresh(btn, 'copy')) return;
112
463
  btn.addEventListener('click', function () {
113
464
  var text = Array.prototype.map.call(code.querySelectorAll('.cl'), function (l) { return l.textContent; }).join('') || code.textContent;
114
465
  var label = btn.querySelector('.cx-code__copy-label');
@@ -128,25 +479,46 @@
128
479
  });
129
480
 
130
481
  // Component previews: size each frame to its document's body (the root is never shorter than the frame), and keep
131
- // its theme. Inside a preview, links don't navigate.
132
- document.querySelectorAll('.cx-preview__frame').forEach(function (f) {
482
+ // its theme. An open dialog or popover (a calendar) sits above the body, so while one is open the frame also grows
483
+ // to hold it, and shrinks back when it closes. Inside a preview, links don't navigate.
484
+ each('.cx-preview__frame', function (f) {
485
+ if (!fresh(f, 'preview')) return;
133
486
  var fit = function () {
134
- try { var d = f.contentDocument; if (d && d.body) f.style.setProperty('--_frame-height', d.body.offsetHeight + 'px'); } catch (e) { /* cross-origin: keep the default height */ }
487
+ try {
488
+ var d = f.contentDocument; if (!d || !d.body) return;
489
+ var need = d.body.offsetHeight, room = px('--cx-space-section-sm');
490
+ d.querySelectorAll('dialog[open], [popover]').forEach(function (o) {
491
+ if (o.matches('dialog[open]')) {
492
+ // its parts' full heights, since a dialog with too little room scrolls its body and reports less
493
+ var h = 0;
494
+ o.querySelectorAll(':scope > :not(form), :scope > form > *').forEach(function (c) { h += c.scrollHeight; });
495
+ need = Math.max(need, h + 2 * room);
496
+ }
497
+ else if (o.matches(':popover-open')) need = Math.max(need, o.offsetTop + o.offsetHeight + room);
498
+ });
499
+ f.style.setProperty('--_frame-height', need + 'px');
500
+ } catch (e) { /* cross-origin: keep the default height */ }
135
501
  };
136
502
  var start = function () {
137
503
  apply(theme); fit();
138
- try { if ('ResizeObserver' in window) new ResizeObserver(fit).observe(f.contentDocument.body); } catch (e) { /* keep the measured height */ }
504
+ try { if ('ResizeObserver' in window) observe(f, new ResizeObserver(fit), f.contentDocument.body); } catch (e) { /* keep the measured height */ }
505
+ try {
506
+ var d = f.contentDocument, later = function () { window.requestAnimationFrame(fit); };
507
+ d.addEventListener('toggle', later, true);
508
+ d.addEventListener('close', later, true);
509
+ if ('MutationObserver' in window) new MutationObserver(later).observe(d.body, { subtree: true, attributes: true, attributeFilter: ['open'] });
510
+ } catch (e) { /* keep the measured height */ }
139
511
  };
140
512
  f.addEventListener('load', start);
141
513
  try { if (f.contentDocument && f.contentDocument.readyState === 'complete' && f.contentDocument.body && f.contentDocument.body.childNodes.length) start(); } catch (e) { /* wait for load */ }
142
514
  });
143
- if (document.body.classList.contains('cx-preview-body')) {
144
- document.addEventListener('click', function (e) { if (e.target.closest && e.target.closest('a[href]')) e.preventDefault(); });
145
- }
146
515
 
147
516
  // Tabs: turn the labelled panels into a tab list with one panel shown. Sets that share data-tabs stay in step,
148
517
  // and the choice is remembered for the next page (cx-tabs:<name> in localStorage).
149
- document.querySelectorAll('.cx-tabs').forEach(function (set, n) {
518
+ each('.cx-tabs', function (set, n) {
519
+ if (!fresh(set, 'tabs')) return;
520
+ // a page restored from Turbo's cache keeps the tab list it was given, but not its listeners: make it again
521
+ set.querySelectorAll(':scope > .cx-tabs__list').forEach(function (old) { old.remove(); });
150
522
  var panels = Array.prototype.slice.call(set.querySelectorAll(':scope > .cx-tabs__panel'));
151
523
  if (panels.length < 2) return;
152
524
  var list = document.createElement('div'); list.className = 'cx-tabs__list'; list.setAttribute('role', 'tablist');
@@ -190,7 +562,8 @@
190
562
 
191
563
  // Search: a dialog over a Pagefind index. The trigger is shown once this script runs; Pagefind's script loads on the
192
564
  // first open. Ctrl+K or Cmd+K, or "/" outside a text field, opens it; Escape closes it (native to <dialog>).
193
- document.querySelectorAll('.cx-search[data-search]').forEach(function (dialog) {
565
+ each('.cx-search[data-search]', function (dialog) {
566
+ if (!fresh(dialog, 'search')) return;
194
567
  var input = dialog.querySelector('.cx-search__input');
195
568
  var list = dialog.querySelector('.cx-search__results');
196
569
  var status = dialog.querySelector('.cx-search__status');
@@ -250,17 +623,13 @@
250
623
  e.preventDefault();
251
624
  if (next < 0) input.focus(); else links[next].focus();
252
625
  });
253
- document.addEventListener('keydown', function (e) {
254
- var typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName) || document.activeElement.isContentEditable;
255
- if (((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') || (e.key === '/' && !typing && !e.ctrlKey && !e.metaKey && !e.altKey)) {
256
- e.preventDefault(); open();
257
- }
258
- });
626
+ openers.set(dialog, open);
259
627
  });
260
628
 
261
629
  // Copy page: copies the page's Markdown (its index.md) as plain text. ClipboardItem takes a promise, so the copy
262
630
  // still counts as part of the click while the file loads; without it, the text is fetched first.
263
- document.querySelectorAll('[data-copy-page]').forEach(function (btn) {
631
+ each('[data-copy-page]', function (btn) {
632
+ if (!fresh(btn, 'copy-page')) return;
264
633
  var label = btn.querySelector('.cx-page-actions__label');
265
634
  var icon = btn.querySelector('use');
266
635
  var set = function (state, text, iconId) {
@@ -282,99 +651,48 @@
282
651
  });
283
652
  });
284
653
 
285
- // Alerts (alert.md): show each dismiss button, and hide its alert when pressed. With a key, data-alert-dismiss="x",
286
- // the alert stays hidden on later pages too (localStorage "cx-alert:x"). Focus moves to the main column, since the
287
- // button it was on has gone. One listener on the document, so an alert an app adds later works the same way.
288
- var dismissed = function (key) { try { return Boolean(key) && localStorage.getItem('cx-alert:' + key) === 'dismissed'; } catch (e) { return false; } };
289
- document.querySelectorAll('.cx-alert [data-alert-dismiss]').forEach(function (btn) {
654
+ // Alerts (alert.md): show each dismiss button, or keep its alert hidden if its key was dismissed on an earlier
655
+ // page (localStorage "cx-alert:x" for data-alert-dismiss="x"). The click is handled once, on the document.
656
+ each('.cx-alert [data-alert-dismiss]', function (btn) {
290
657
  var alert = btn.closest('.cx-alert');
291
658
  if (dismissed(btn.dataset.alertDismiss)) alert.hidden = true; else btn.hidden = false;
292
659
  });
293
- document.addEventListener('click', function (e) {
294
- var btn = e.target.closest && e.target.closest('.cx-alert [data-alert-dismiss]');
295
- if (!btn) return;
296
- var key = btn.dataset.alertDismiss;
297
- btn.closest('.cx-alert').hidden = true;
298
- if (key) { try { localStorage.setItem('cx-alert:' + key, 'dismissed'); } catch (err) { /* storage blocked: hidden for this view only */ } }
299
- var main = document.getElementById('main');
300
- if (main) main.focus({ preventScroll: true });
301
- });
660
+ // The toast region is made with the page, so it's already there when a toast is announced.
661
+ toastRegion();
302
662
 
303
- // Toasts (toast.md): document.dispatchEvent(new CustomEvent('cx-toast', { detail: { text: 'Saved', kind: 'success' } })).
304
- // One polite live region per page, made here if the page has none, holds up to three; each goes after
305
- // motion.duration.toast, a time that starts again while the pointer or focus is on it. Escape inside one, or its
306
- // button, closes it. The text is set as text, never as HTML.
307
- var region = document.querySelector('.cx-toasts');
308
- if (!region) {
309
- region = document.createElement('div'); region.className = 'cx-toasts'; region.setAttribute('role', 'status');
310
- document.body.appendChild(region);
311
- }
312
- var toastIcon = function (id, cls) {
313
- var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
314
- svg.setAttribute('class', 'cx-icon cx-icon--sm' + (cls ? ' ' + cls : '')); svg.setAttribute('aria-hidden', 'true'); svg.setAttribute('focusable', 'false');
315
- var use = document.createElementNS('http://www.w3.org/2000/svg', 'use'); use.setAttribute('href', '#cx-icon-' + id);
316
- svg.appendChild(use); return svg;
317
- };
318
- var closeToast = function (toast) {
319
- if (toast.classList.contains('is-leaving')) return;
320
- clearTimeout(toast._cxTimer);
321
- var hadFocus = toast.contains(document.activeElement);
322
- toast.classList.add('is-leaving'); toast.classList.remove('is-shown');
323
- setTimeout(function () { toast.remove(); }, ms('--cx-motion-duration-base'));
324
- if (hadFocus) { var main = document.getElementById('main'); if (main) main.focus({ preventScroll: true }); }
325
- };
326
- document.addEventListener('cx-toast', function (e) {
327
- var d = e.detail || {};
328
- if (!d.text) return;
329
- var toast = document.createElement('div'); toast.className = 'cx-toast';
330
- if (d.kind === 'success') toast.appendChild(toastIcon('check'));
331
- var p = document.createElement('p'); p.className = 'cx-toast__text'; p.textContent = d.text; toast.appendChild(p);
332
- var btn = document.createElement('button'); btn.type = 'button'; btn.className = 'cx-toast__dismiss'; btn.setAttribute('aria-label', 'Dismiss');
333
- btn.appendChild(toastIcon('close')); btn.addEventListener('click', function () { closeToast(toast); }); toast.appendChild(btn);
334
- var wait = function () { clearTimeout(toast._cxTimer); toast._cxTimer = setTimeout(function () { closeToast(toast); }, ms('--cx-motion-duration-toast')); };
335
- var hold = function () { clearTimeout(toast._cxTimer); };
336
- toast.addEventListener('mouseenter', hold); toast.addEventListener('focusin', hold);
337
- toast.addEventListener('mouseleave', function () { if (!toast.contains(document.activeElement)) wait(); });
338
- toast.addEventListener('focusout', function (ev) { if (!toast.contains(ev.relatedTarget) && !toast.matches(':hover')) wait(); });
339
- toast.addEventListener('keydown', function (ev) { if (ev.key === 'Escape') { ev.stopPropagation(); closeToast(toast); } });
340
- var live = region.querySelectorAll('.cx-toast:not(.is-leaving)');
341
- if (live.length >= 3) closeToast(live[0]);
342
- region.appendChild(toast);
343
- window.requestAnimationFrame(function () { window.requestAnimationFrame(function () { toast.classList.add('is-shown'); }); });
344
- wait();
345
- });
663
+ each('[data-date-picker]', setUpPicker);
346
664
 
347
665
  // Docs navigation: dock it (sticky, scrolling on its own) while it sits beside the main column, as the TOC does.
348
- document.querySelectorAll('.cx-docs').forEach(function (docs) {
666
+ each('.cx-docs', function (docs) {
349
667
  var nav = docs.querySelector('.cx-docs-nav');
350
668
  var main = docs.querySelector('.cx-docs__main');
351
- if (!nav || !main) return;
669
+ if (!nav || !main || !fresh(docs, 'dock')) return;
352
670
  var dock = function () {
353
671
  root.style.setProperty('--_viewport-height', window.innerHeight + 'px');
354
672
  nav.classList.toggle('is-docked', Math.abs(nav.offsetTop - main.offsetTop) < 1);
355
673
  };
356
- dock(); window.addEventListener('resize', dock);
674
+ dock(); watch('resize', docs, dock);
357
675
  // Bring the current page into view inside the docked navigation.
358
676
  var current = nav.querySelector('[aria-current="page"]');
359
677
  if (current && nav.classList.contains('is-docked') && current.offsetTop > nav.clientHeight / 2) nav.scrollTop = current.offsetTop - nav.clientHeight / 2;
360
678
  });
361
679
 
362
680
  // Table of contents: dock beside the article when there is room, and mark the current section.
363
- document.querySelectorAll('.cx-article').forEach(function (article) {
681
+ each('.cx-article', function (article) {
364
682
  var toc = article.querySelector('.cx-toc');
365
683
  var main = article.querySelector('.cx-article__main');
366
- if (!toc || !main) return;
684
+ if (!toc || !main || !fresh(article, 'toc')) return;
367
685
  var dock = function () { toc.classList.toggle('is-docked', Math.abs(toc.offsetTop - main.offsetTop) < 1); };
368
- dock(); window.addEventListener('resize', dock);
686
+ dock(); watch('resize', article, dock);
369
687
  // The docs header's "On this page" (site-header.md) lists the same sections, so it is marked too.
370
688
  var links = Array.prototype.slice.call(document.querySelectorAll('.cx-article .cx-toc a[href^="#"], .cx-header__toc li a[href^="#"]'));
371
689
  if (!('IntersectionObserver' in window)) return;
372
- var io = new IntersectionObserver(function (entries) {
690
+ var io = observe(article, new IntersectionObserver(function (entries) {
373
691
  entries.forEach(function (e) {
374
692
  if (!e.isIntersecting) return;
375
693
  links.forEach(function (a) { a.setAttribute('aria-current', a.getAttribute('href') === '#' + e.target.id ? 'true' : 'false'); });
376
694
  });
377
- }, { rootMargin: '0px 0px -70% 0px' });
695
+ }, { rootMargin: '0px 0px -70% 0px' }));
378
696
  links.forEach(function (a) { var t = document.getElementById(a.getAttribute('href').slice(1)); if (t) io.observe(t); });
379
697
  });
380
698
 
@@ -383,7 +701,8 @@
383
701
  // scripted drawing listens for the "cx-plate-pause" event. Under reduced motion nothing plays and the control
384
702
  // stays hidden. The contour survey (data-plate-seed) is run by dist/plate.js instead.
385
703
  var still = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
386
- document.querySelectorAll('.cx-plate[data-plate-motion]').forEach(function (plate) {
704
+ each('.cx-plate[data-plate-motion]', function (plate) {
705
+ if (!fresh(plate, 'plate')) return;
387
706
  var frame = plate.closest('.cx-plate-frame') || plate.parentElement;
388
707
  var toggle = frame.querySelector('.cx-plate__pause');
389
708
  var input = toggle && toggle.querySelector('input');
@@ -398,5 +717,5 @@
398
717
  if (input) input.addEventListener('change', function () { set(input.checked); });
399
718
  set(Boolean(input && input.checked));
400
719
  });
401
- });
720
+ }
402
721
  })();