@apliteni/apliteni-ui 0.142.0 → 0.142.3

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.
Files changed (46) hide show
  1. package/README.md +24 -36
  2. package/guidelines/state-set.md +4 -4
  3. package/package.json +3 -3
  4. package/react/dist/index.css +2 -2
  5. package/react/dist/index.js +12 -5
  6. package/src/index.d.ts +13 -96
  7. package/src/index.js +17 -30
  8. package/src/logic/account-nav.js +9 -0
  9. package/src/logic/code.js +75 -0
  10. package/src/logic/dropdown-placement.js +671 -0
  11. package/src/logic/feedback.js +16 -0
  12. package/src/logic/theme.js +5 -0
  13. package/src/styles/command-palette.css +9 -5
  14. package/src/styles/drawer.css +8 -0
  15. package/src/styles/dropdown.css +30 -8
  16. package/src/styles/feedback.css +1 -1
  17. package/src/styles/filter-bar.css +5 -2
  18. package/src/styles/input.css +14 -15
  19. package/src/styles/layout.css +5 -2
  20. package/src/styles/table.css +28 -2
  21. package/src/styles/topbar.css +8 -6
  22. package/src/components/account-nav.js +0 -44
  23. package/src/components/avatar.js +0 -53
  24. package/src/components/back.js +0 -57
  25. package/src/components/button-busy.js +0 -69
  26. package/src/components/command-palette.js +0 -471
  27. package/src/components/confirm.js +0 -131
  28. package/src/components/drawer.js +0 -169
  29. package/src/components/dropdown.js +0 -1713
  30. package/src/components/feedback.js +0 -182
  31. package/src/components/filter-bar.js +0 -86
  32. package/src/components/footer.js +0 -102
  33. package/src/components/index.js +0 -424
  34. package/src/components/loading.js +0 -127
  35. package/src/components/nav.js +0 -220
  36. package/src/components/overlay.js +0 -263
  37. package/src/components/pagination.js +0 -323
  38. package/src/components/segmented.js +0 -33
  39. package/src/components/shell.js +0 -511
  40. package/src/components/stat.js +0 -82
  41. package/src/components/success.js +0 -131
  42. package/src/components/table-values.js +0 -32
  43. package/src/components/tabs.js +0 -82
  44. package/src/components/toasts.js +0 -118
  45. package/src/components/tooltip.js +0 -347
  46. package/src/components/topbar.js +0 -269
@@ -1,347 +0,0 @@
1
- // Tooltip — the readout that shows a value while a pointer rests on the mark
2
- // holding it. An overlay in every state: one element, rendered once inside its
3
- // host and absolutely placed there, so showing it moves nothing on the page.
4
- //
5
- // <div class="ui-tip-host" data-tip-host>
6
- // <svg>… <rect data-tip-label="Mar 2026" data-tip-value="€48,210" …/> …</svg>
7
- // ${tooltip()}
8
- // </div>
9
- // wireTooltip(container);
10
- //
11
- // A mark carries `data-tip-value`, with `data-tip-label` and `data-tip-detail`;
12
- // a `[data-tip-anchor]` inside it is where the readout opens. Under a finger
13
- // there is no hover, so a tap is the switch: see Pointer kinds below.
14
- // why: docs/components.md#the-hover-readout
15
- import { esc } from './index.js';
16
-
17
- const cx = (...a) => a.filter(Boolean).join(' ');
18
- /* classes: ui-tip__label ui-tip__value ui-tip__detail — built from `k` below, so
19
- a sweep reading class names off the source cannot see them.
20
- */
21
- const PARTS = ['label', 'value', 'detail'];
22
- const px = (n) => (typeof n === 'number' && Number.isFinite(n) ? `${n}px` : null);
23
- let seq = 0;
24
-
25
- /**
26
- * The readout. Render it once inside a `[data-tip-host]`; wireTooltip() fills it.
27
- *
28
- * @param {object} [o]
29
- * @param {string} [o.label] which point — a date, a category, a series
30
- * @param {string} [o.value] the number, already formatted
31
- * @param {string} [o.detail] at most one comparison, such as "+4.2% on February"
32
- * @param {string} [o.placement] 'top' (default) | 'bottom' — the side it prefers; the wiring flips it when clipped
33
- * @param {boolean} [o.open] render it shown, as a picture; its host leaves off `data-tip-host` so no wiring takes it down
34
- * @param {number} [o.x] with `open`: the mark's centre, px from the host's left
35
- * @param {number} [o.y] with `open`: the mark's top edge (its bottom for 'bottom'), px from the host's top
36
- * @param {string} [o.id]
37
- * @returns {string} html
38
- */
39
- export function tooltip({
40
- label = '', value = '', detail = '', placement = 'top', open = false, x, y, id,
41
- } = {}) {
42
- const text = { label, value, detail };
43
- const named = value != null && String(value) !== '';
44
- const pos =[['--ui-tip-x', px(x)], ['--ui-tip-y', px(y)]]
45
- .filter(([, v]) => v).map(([k, v]) => `${k}:${v}`).join(';');
46
- // A tooltip with nothing in it has no name, so an empty readout — the one a
47
- // chart renders before any mark is hovered — takes the role with its first value.
48
- const attrs = [
49
- `class="${cx('ui-tip', placement === 'bottom' && 'is-below', open && 'is-open')}"`,
50
- named ? 'role="tooltip"' : '',
51
- 'data-tip',
52
- id ? `id="${esc(id)}"` : '',
53
- pos ? `style="${pos}"` : '',
54
- ].filter(Boolean).join(' ');
55
- const spans = PARTS.map((k) => {
56
- const t = text[k] == null ? '' : String(text[k]);
57
- return `<span class="ui-tip__${k}"${t ? '' : ' hidden'}>${esc(t)}</span>`;
58
- }).join('');
59
- return `<div ${attrs}>${spans}</div>`;
60
- }
61
-
62
- // ---- Placement -----------------------------------------------------------
63
-
64
- // The mark-to-readout distance is --ui-tip-gap in src/styles/tooltip.css. This is
65
- // the fallback for a document that has not loaded the sheet;
66
- // src/components/tooltip.test.js pins the two to each other.
67
- const TIP_GAP = 8;
68
-
69
- function tipGap(tip) {
70
- const declared = parseFloat(getComputedStyle(tip).getPropertyValue('--ui-tip-gap'));
71
- return Number.isFinite(declared) ? declared : TIP_GAP;
72
- }
73
-
74
- // Hosts nest. A mark or a readout belongs to the nearest [data-tip-host] above it,
75
- // so one mark opens one readout, and an outer host is never handed an inner one's.
76
- function holds(host, el) {
77
- const nearest = el.parentElement?.closest('[data-tip-host]') ?? null;
78
- return host.contains(el) && (nearest === host || !host.contains(nearest));
79
- }
80
-
81
- const tipOf = (host) => [...host.querySelectorAll('[data-tip]')].find((tip) => holds(host, tip)) ?? null;
82
- const clips = (cs) => [cs.overflow, cs.overflowX, cs.overflowY].some((v) => v && v !== 'visible');
83
-
84
- // What the readout has to stay inside: the viewport less its scrollbars, cut
85
- // down by the host and every ancestor whose overflow clips. <body> is left out —
86
- // its overflow is the viewport's, and its box can be shorter than the page.
87
- function clipBox(host) {
88
- const view = host.ownerDocument.documentElement;
89
- const box = { top: 0, left: 0, right: view.clientWidth, bottom: view.clientHeight };
90
- for (let el = host; el && el !== document.body && el !== document.documentElement; el = el.parentElement) {
91
- if (!clips(getComputedStyle(el))) continue;
92
- const r = el.getBoundingClientRect();
93
- box.top = Math.max(box.top, r.top);
94
- box.left = Math.max(box.left, r.left);
95
- box.right = Math.min(box.right, r.right);
96
- box.bottom = Math.min(box.bottom, r.bottom);
97
- }
98
- return box;
99
- }
100
-
101
- // Flip only when the preferred side is too tight AND the other side is roomier,
102
- // so a readout that fits on neither side opens on the roomier one. Then slide
103
- // it along the mark's edge, no further than it takes to stay inside the box.
104
- function place(host, tip, mark) {
105
- const m = (mark.querySelector('[data-tip-anchor]') || mark).getBoundingClientRect();
106
- const h = host.getBoundingClientRect();
107
- const clip = clipBox(host);
108
- const need = tip.offsetHeight + tipGap(tip);
109
- const above = m.top - clip.top;
110
- const below = clip.bottom - m.bottom;
111
- const prefersBelow = tip.__tipPrefersBelow;
112
- const flip = prefersBelow ? below < need && above > below : above < need && below > above;
113
- const isBelow = prefersBelow !== flip;
114
- tip.classList.toggle('is-below', isBelow);
115
-
116
- const centre = m.left + m.width / 2;
117
- const ideal = centre - tip.offsetWidth / 2;
118
- const left = Math.max(clip.left, Math.min(ideal, clip.right - tip.offsetWidth));
119
- // An absolute box is measured from the host's padding edge and rides its scroll.
120
- const s = tip.style;
121
- s.setProperty('--ui-tip-x', `${centre - h.left - host.clientLeft + host.scrollLeft}px`);
122
- s.setProperty('--ui-tip-y', `${(isBelow ? m.bottom : m.top) - h.top - host.clientTop + host.scrollTop}px`);
123
- s.setProperty('--ui-tip-shift', `${left - ideal}px`);
124
- }
125
-
126
- function fill(tip, mark) {
127
- tip.setAttribute('role', 'tooltip');
128
- for (const k of PARTS) {
129
- const el = tip.querySelector(`.ui-tip__${k}`);
130
- if (!el) continue;
131
- const t = mark.getAttribute(`data-tip-${k}`) || '';
132
- el.textContent = t;
133
- el.hidden = !t;
134
- }
135
- }
136
-
137
- // ---- Behaviour -----------------------------------------------------------
138
-
139
- /**
140
- * Show the host's readout for one mark, until hideTooltip() or Escape. For a chart that does its own
141
- * hit-testing; its host needs `.ui-tip-host`. After Escape it shows nothing for the dismissed mark
142
- * until another mark shows or hideTooltip() is called, so a chart may call it on every pointer sample.
143
- */
144
- export function showTooltip(host, mark) {
145
- const tip = tipOf(host);
146
- if (!tip || !mark || mark === host.__tipDismissed) return;
147
- if (tip.__tipPrefersBelow == null) tip.__tipPrefersBelow = tip.classList.contains('is-below');
148
- if (!tip.id) tip.id = `ui-tip-${++seq}`;
149
- releaseMark(host);
150
- fill(tip, mark);
151
- place(host, tip, mark);
152
- // Described only while shown, and only a mark that carried no description of its own.
153
- if (!mark.hasAttribute('aria-describedby')) {
154
- mark.setAttribute('aria-describedby', tip.id);
155
- mark.__tipDescribed = true;
156
- }
157
- host.__tipMark = mark;
158
- host.__tipDismissed = null;
159
- tip.__tipHost = host;
160
- tip.classList.add('is-open');
161
- wireDocument(host.ownerDocument);
162
- }
163
-
164
- function releaseMark(host) {
165
- const mark = host.__tipMark;
166
- if (mark?.__tipDescribed) { mark.removeAttribute('aria-describedby'); mark.__tipDescribed = false; }
167
- host.__tipMark = null;
168
- }
169
-
170
- function close(host) {
171
- releaseMark(host);
172
- tipOf(host)?.classList.remove('is-open');
173
- }
174
-
175
- /** Hide the host's readout: the pointer has left, so the mark Escape dismissed may show again. */
176
- export function hideTooltip(host) {
177
- close(host);
178
- host.__tipDismissed = null;
179
- }
180
-
181
- // A tap that closes a readout dismisses that mark the way Escape does, so a
182
- // chart sampling its own marks does not bring it straight back. Which is true
183
- // of the tap that lands on the mark and of the tap that lands on the host's
184
- // ground beside it: both are the reader putting the readout away.
185
- function dismiss(host) {
186
- const mark = host.__tipMark;
187
- close(host);
188
- host.__tipDismissed = mark;
189
- }
190
-
191
- // ---- Pointer kinds -------------------------------------------------------
192
-
193
- // A finger has no hover. It arrives already pressing, so the pointerover under
194
- // a tap is the tap itself: a readout opened on it would open on the way to
195
- // whatever the mark does when pressed, and go again the moment the finger
196
- // lifts. Under a coarse pointer the tap is the switch instead — one tap opens
197
- // the readout, the next closes it, and a tap anywhere else closes it too.
198
-
199
- /** Whether the device reports no fine pointer at all: a phone, a tablet. */
200
- function coarse(doc) {
201
- try {
202
- return doc.defaultView?.matchMedia?.('(pointer: coarse)')?.matches === true;
203
- } catch { return false; }
204
- }
205
-
206
- // A pointer event says which kind of pointer it is; a click and a focus do not,
207
- // so the last kind seen is remembered for them. A keystroke clears it, because
208
- // a keyboard on a tablet is a third way in and focus has to open the readout
209
- // again after a tap. Before any of that, the media query answers.
210
- //
211
- // A pen is on the tap's side of that line with the finger. It presses a screen
212
- // rather than resting over one, the tablets it comes with report `(pointer:
213
- // coarse)`, and a hover a pen does offer is a few millimetres of one nothing
214
- // here is placed against — so a stylus that fell to the hover path would get
215
- // the flash this component exists to remove. A mouse is the fine pointer.
216
- function touching(doc, e) {
217
- if (e?.pointerType) doc.__tipTouch = e.pointerType === 'touch' || e.pointerType === 'pen';
218
- return doc.__tipTouch ?? coarse(doc);
219
- }
220
-
221
- // Escape dismisses every readout the kit is showing without the pointer having
222
- // to move — the reader it covers something for. One rendered open and never
223
- // shown is a picture, and stays. The dismissed mark is remembered until another
224
- // mark shows or the pointer leaves, so crossing the gap between marks and coming
225
- // back does not return the readout to the mark it was dismissed from.
226
- //
227
- // The same document is where the kind of pointer in play is tracked, and where
228
- // a tap that lands outside a readout's host takes that readout down.
229
- function wireDocument(doc) {
230
- if (doc.__tipDocWired) return;
231
- doc.__tipDocWired = true;
232
- doc.addEventListener('keydown', (e) => {
233
- doc.__tipTouch = false;
234
- doc.__tipTapping = false;
235
- if (e.key !== 'Escape') return;
236
- doc.querySelectorAll('[data-tip].is-open').forEach((tip) => {
237
- const host = tip.__tipHost;
238
- if (!host) return;
239
- const mark = host.__tipMark;
240
- close(host);
241
- host.__tipDismissed = mark;
242
- });
243
- });
244
- // A tap lands focus on the mark on its way to the click that decides, so the
245
- // focus between a pointerdown and its click is the tap's own. Focus that no
246
- // tap brought is not, and opens the readout under a coarse pointer as it
247
- // always did — a reader swiping through the marks with a screen reader gets
248
- // the value and the `aria-describedby` that announces it.
249
- doc.addEventListener('pointerdown', (e) => { touching(doc, e); doc.__tipTapping = true; }, true);
250
- doc.addEventListener('pointercancel', () => { doc.__tipTapping = false; }, true);
251
- // Captured, so a host the tap lands in has already lost every other host's
252
- // readout by the time it opens its own.
253
- doc.addEventListener('click', (e) => {
254
- if (e.__tipDismissal) return;
255
- doc.__tipTapping = false;
256
- if (!touching(doc)) return;
257
- doc.querySelectorAll('[data-tip].is-open').forEach((tip) => {
258
- const host = tip.__tipHost;
259
- if (host && !host.contains(e.target)) hideTooltip(host);
260
- });
261
- }, true);
262
- }
263
-
264
- // An opening tap is stopped on its way to the mark, and stopping it takes it
265
- // away from the document as well — where other overlays keep the click listener
266
- // that dismisses them, so a dropdown panel would stand open behind the readout
267
- // the tap just opened. The tap is handed to the document itself instead. Its
268
- // target is the root element, which every dismissal listener hears and no
269
- // delegated trigger matches, since no trigger's attribute is on the root.
270
- function dismissOverlays(doc) {
271
- const view = doc.defaultView;
272
- if (!view || !doc.documentElement) return;
273
- const passed = new view.MouseEvent('click', { bubbles: true, cancelable: true });
274
- passed.__tipDismissal = true;
275
- doc.documentElement.dispatchEvent(passed);
276
- }
277
-
278
- // The readout is placed in px from its host, so the host has to be the box it is
279
- // positioned against. .ui-tip-host makes it one; a host without it is given the same.
280
- // A host outside the document has no computed style to read, so it waits until it is in one.
281
- function anchorHost(host) {
282
- if (host.__tipAnchored || !host.isConnected) return;
283
- host.__tipAnchored = true;
284
- if (getComputedStyle(host).position === 'static') host.style.position = 'relative';
285
- }
286
-
287
- /**
288
- * Wire every `[data-tip-host]` under root: a pointer resting on a mark, or focus
289
- * landing on one, shows the readout; leaving the marks hides it. Under a coarse
290
- * pointer nothing rests, so a tap on a mark opens the readout and a second tap —
291
- * or a tap anywhere else — closes it. A host with no readout of its own is given
292
- * one here, once, never on hover. Safe to call again.
293
- */
294
- export function wireTooltip(root = document) {
295
- const hosts = [...root.querySelectorAll('[data-tip-host]')];
296
- if (root.matches?.('[data-tip-host]')) hosts.unshift(root);
297
- hosts.forEach((host) => {
298
- if (host.__tipWired) return;
299
- host.__tipWired = true;
300
- const doc = host.ownerDocument;
301
- wireDocument(doc);
302
- anchorHost(host);
303
- if (!tipOf(host)) host.insertAdjacentHTML('beforeend', tooltip());
304
- const markOf = (t) => {
305
- const mark = t?.closest?.('[data-tip-value]');
306
- return mark && holds(host, mark) ? mark : null;
307
- };
308
- host.addEventListener('pointerover', (e) => {
309
- anchorHost(host);
310
- if (touching(doc, e)) return;
311
- const mark = markOf(e.target);
312
- if (!mark) close(host);
313
- else if (mark !== host.__tipMark) showTooltip(host, mark);
314
- });
315
- host.addEventListener('pointerleave', (e) => { if (!touching(doc, e)) hideTooltip(host); });
316
- host.addEventListener('focusin', (e) => {
317
- anchorHost(host);
318
- // A tap lands focus on its way to the click that decides, so under a
319
- // finger the readout waits for that tap rather than opening twice. Focus
320
- // arriving on its own under the same pointer is a reader reaching the
321
- // mark another way, and opens it.
322
- if (touching(doc) && doc.__tipTapping) return;
323
- const mark = markOf(e.target);
324
- if (mark) showTooltip(host, mark);
325
- });
326
- host.addEventListener('focusout', (e) => { if (!markOf(e.relatedTarget)) hideTooltip(host); });
327
- // The tap. Captured, so the tap that opens the readout is spent opening it
328
- // and never reaches the mark's own click — a chart drilling down on a bar
329
- // does not drill down on the tap that asked what the bar says. The tap that
330
- // closes the readout is let through, so the drill-down is one tap further.
331
- // What the opening tap is stopped from reaching, it is handed to: see
332
- // dismissOverlays(), so an open overlay closes under it as under any tap.
333
- host.addEventListener('click', (e) => {
334
- if (!touching(doc)) return;
335
- anchorHost(host);
336
- const mark = markOf(e.target);
337
- if (!mark || mark === host.__tipMark) { dismiss(host); return; }
338
- e.preventDefault();
339
- e.stopPropagation();
340
- dismissOverlays(doc);
341
- // A tap is deliberate, so it ends a dismissal rather than being refused by
342
- // one. What a dismissal stops is the readout coming back on its own.
343
- host.__tipDismissed = null;
344
- showTooltip(host, mark);
345
- }, true);
346
- });
347
- }
@@ -1,269 +0,0 @@
1
- // Topbar factory + client behaviours. Composes the canonical strategy topbar
2
- // (brand, Deck/Text, theme toggle, version switcher, account menu).
3
- import { brand } from '../assets/brand.js';
4
- import { icon, sun, moon } from '../assets/icons.js';
5
- import { esc } from './index.js';
6
- import { wireDropdown } from './dropdown.js';
7
- import { avatar } from './avatar.js';
8
- import { accountMenuNav, initials, toMenuTuple } from './account-nav.js';
9
- import { trustedAttr, trustedUrl } from '../html.js';
10
- const THEME_KEY = 'apliteni-strategy-theme';
11
-
12
- // The icon and name show the saved choice, including automatic mode.
13
- export const themeIcon = (t) => t === 'auto' ? icon('monitor') : t === 'light' ? sun : moon;
14
- export const themeName = (t) => t === 'auto' ? 'Theme: Auto. Switch to dark.' :
15
- t === 'light' ? 'Theme: Light. Switch to auto.' : 'Theme: Dark. Switch to light.';
16
-
17
- export function themeToggle(theme = 'dark') {
18
- // Single icon-only switch. Icon and name are pre-filled for `theme` so the
19
- // first paint is already truthful; applyTheme() keeps them so afterwards.
20
- const name = esc(themeName(theme));
21
- return `<button class="toggle" data-theme-toggle aria-label="${name}" title="${name}"><span class="ic" data-theme-icon>${themeIcon(theme)}</span></button>`;
22
- }
23
-
24
- export function deckTextSwitch(active = 'deck') {
25
- return `<div class="dtsw on" role="group" aria-label="View">` +
26
- `<a${active === 'deck' ? ' class="cur" aria-current="page"' : ''} href="#deck">Deck</a>` +
27
- `<a${active === 'text' ? ' class="cur" aria-current="page"' : ''} href="#text">Text</a></div>`;
28
- }
29
-
30
- // Thin consumer of the shared dropdown wiring (wireDropdown): keeps its own
31
- // bespoke .vsw/.vopt classes for a pixel-identical look, but emits the generic
32
- // [data-dropdown] hooks so there's ONE open/close/keyboard implementation.
33
- // `badge` is a tone key and the kit writes the word for it; the stylesheet used
34
- // to uppercase the key itself. why: docs/foundations.md#labels-and-titles
35
- const VBADGE = { live: 'Live', archive: 'Archive' };
36
- export function versionSwitcher(versions = [], activeIdx = 0) {
37
- const cur = versions[activeIdx]?.label || '';
38
- const opts = versions.map((v, i) => {
39
- const key = String(v.badge || 'archive').toLowerCase();
40
- return `<div class="vopt" role="option" data-dd-item tabindex="-1" aria-selected="${i === activeIdx}" data-active="${i === activeIdx ? '1' : '0'}">` +
41
- `<span class="vname">${v.label}</span>` +
42
- `<span class="vbadge ${key === 'live' ? 'live' : 'arch'}">${Object.hasOwn(VBADGE, key) ? VBADGE[key] : v.badge}</span><span class="vtick" aria-hidden="true">${icon('check')}</span></div>`;
43
- }).join('');
44
- return `<div class="vsw" data-dropdown><button type="button" class="vsw__btn" data-dropdown-trigger aria-haspopup="listbox" aria-expanded="false" aria-label="Version — ${esc(cur)}">` +
45
- `<span class="cur">${cur}</span><span class="car"></span></button>` +
46
- `<div class="vsw__menu" data-dropdown-panel role="listbox" aria-label="Version">${opts}</div></div>`;
47
- }
48
-
49
- // `nav` mirrors the account sidebar, DERIVED from the one ACCOUNT_NAV definition
50
- // rather than restated: a second literal agreed with it by hand about the icon
51
- // and disagreed about the encoding, which is the drift #127 was filed about.
52
- // Body slots below are trusted HTML; attribute copies retain encoded entities.
53
- //
54
- // `initials` is the avatar. A derived value has to be derived BEFORE the
55
- // escaping — `<Ada>` and `&lt;Ada&gt;` do not begin with the same character — so
56
- // shell.js computes the mark from the caller's own strings and passes it down
57
- // beside them. Left out, it is computed here from `name` and `email`.
58
- export function accountMenu({
59
- name = 'Ada Lovelace', email = 'ada@apliteni.com', active = 'prefs', nav, initials: mark, key,
60
- } = {}) {
61
- // initials() is shared with the rail's avatar — the two are the same reader
62
- // on the /account preset, and they used to disagree about who that was.
63
- const ini = mark == null ? initials(name, email) : mark;
64
- // ACCOUNT_NAV is published, and it is a list of item objects — so the shape a
65
- // consumer most naturally hands this option is the one that used to throw here.
66
- // Read either; toMenuTuple() escapes an object on the way, which a tuple that
67
- // arrives already escaped does not need.
68
- //
69
- // A list that is empty is an answer and stays empty, which is what the rail
70
- // does with the same value. Falling back on `.length` meant a caller who asked
71
- // for no entries got none in the rail and the kit's two in the menu — one nav,
72
- // two answers, which is the drift #127 exists to close.
73
- const items = (Array.isArray(nav) ? nav : accountMenuNav())
74
- .map((n) => (Array.isArray(n) ? n : toMenuTuple(n)));
75
- const it = ([id, ic, label, href, target]) =>
76
- `<a href="${trustedUrl(href || '#' + id)}"${target ? ` target="${trustedAttr(target)}"` : ''} data-dd-item tabindex="-1"${active === id ? ' class="cur"' : ''} role="menuitem">${icon(ic)}${label}</a>`;
77
- // `on` so the menu is visible in Storybook / standalone use (no /auth/me gate).
78
- // Consumes the shared dropdown wiring via the generic [data-dropdown] hooks.
79
- return `<div class="acct on" data-dropdown>` +
80
- `<button class="avatar" data-dropdown-trigger aria-haspopup="menu" aria-expanded="false" aria-label="Account">${avatar({ key: key ?? (email || name), initials: ini, size: 32 })}</button>` +
81
- `<div class="amenu" data-dropdown-panel role="menu">` +
82
- `<div class="ahead">${avatar({ key: key ?? (email || name), initials: ini, size: 32 })}<span class="aw"><span class="anm">${name}</span><span class="aem" title="${trustedAttr(email)}">${email}</span></span></div>` +
83
- items.map(it).join('') +
84
- `<div class="asep"></div><a class="aout" href="#logout" data-dd-item tabindex="-1" role="menuitem">${icon('logout')}Sign out</a>` +
85
- `</div></div>`;
86
- }
87
-
88
- // Full topbar. Pass which pieces to include.
89
- export function topbar({
90
- word = 'Strategy', view = 'deck', versions, versionIdx = 0,
91
- account, theme = true, showSwitch = true,
92
- } = {}) {
93
- return `<header class="topbar"><div class="topbar__in">` +
94
- brand({ word }) +
95
- (showSwitch ? deckTextSwitch(view) : '') +
96
- `<span class="spacer"></span>` +
97
- (versions ? versionSwitcher(versions, versionIdx) : '') +
98
- (theme ? themeToggle() : '') +
99
- (account ? accountMenu(account) : '') +
100
- `</div></header>`;
101
- }
102
-
103
- // ---- Behaviours (call once after markup mounts) --------------------------
104
- export function applyTheme(t, root = document.documentElement) {
105
- const media = root.ownerDocument.defaultView.matchMedia?.('(prefers-color-scheme: light)');
106
- root.setAttribute('data-theme-choice', t);
107
- root.setAttribute('data-theme', t === 'auto' ? (media?.matches ? 'light' : 'dark') : t);
108
- const name = themeName(t);
109
- root.querySelectorAll('[data-theme-toggle]').forEach((btn) => {
110
- const ic = btn.querySelector('[data-theme-icon]');
111
- if (ic) ic.innerHTML = themeIcon(t);
112
- // The announced name is the point of the control, so it moves with the
113
- // theme like the glyph does.
114
- btn.setAttribute('aria-label', name);
115
- btn.setAttribute('title', name);
116
- });
117
- try { localStorage.setItem(THEME_KEY, t); } catch (e) { /* no-op */ }
118
- const view = root.ownerDocument.defaultView;
119
- view.dispatchEvent(new view.Event('apliteni-theme-choice'));
120
- }
121
-
122
- const ACCENT_KEY = 'apliteni-strategy-accent';
123
- // One list for the pickers, this wiring and the React component.
124
- export { ACCENTS } from '../logic/accents.js';
125
-
126
- export function applyAccent(name, root = document.documentElement) {
127
- if (!name || name === 'default') root.removeAttribute('data-accent');
128
- else root.setAttribute('data-accent', name);
129
- try { localStorage.setItem(ACCENT_KEY, name || 'default'); } catch (e) { /* no-op */ }
130
- }
131
-
132
- const themeListeners = new WeakMap();
133
-
134
- export function wireTopbar(root = document) {
135
- const html = document.documentElement;
136
- const buttons = root.querySelectorAll('[data-theme-toggle]');
137
- if (buttons.length) {
138
- let choice = html.getAttribute('data-theme-choice') || 'auto';
139
- try { choice = localStorage.getItem(THEME_KEY) || choice; } catch { /* Use the page choice. */ }
140
- if (!['dark', 'light', 'auto'].includes(choice)) choice = 'auto';
141
- applyTheme(choice, html);
142
- const media = html.ownerDocument.defaultView.matchMedia?.('(prefers-color-scheme: light)');
143
- themeListeners.get(html)?.();
144
- const onSystem = () => {
145
- if (html.getAttribute('data-theme-choice') === 'auto') {
146
- html.setAttribute('data-theme', media?.matches ? 'light' : 'dark');
147
- }
148
- };
149
- media?.addEventListener('change', onSystem);
150
- const updateButtons = () => {
151
- const choice = html.getAttribute('data-theme-choice') || 'auto';
152
- html.querySelectorAll('[data-theme-toggle]').forEach((btn) => {
153
- btn.setAttribute('aria-label', themeName(choice));
154
- btn.setAttribute('title', themeName(choice));
155
- const glyph = btn.querySelector('[data-theme-icon]');
156
- if (glyph) glyph.innerHTML = themeIcon(choice);
157
- });
158
- };
159
- const observer = new html.ownerDocument.defaultView.MutationObserver(updateButtons);
160
- observer.observe(html, { attributes: true, attributeFilter: ['data-theme-choice'] });
161
- const view = html.ownerDocument.defaultView;
162
- const onStorage = (event) => {
163
- if (event.key !== null && event.key !== THEME_KEY) return;
164
- let saved;
165
- try { saved = localStorage.getItem(THEME_KEY); } catch { return; }
166
- applyTheme(saved === 'dark' || saved === 'light' ? saved : 'auto', html);
167
- };
168
- view.addEventListener('storage', onStorage);
169
- themeListeners.set(html, () => {
170
- media?.removeEventListener('change', onSystem);
171
- view.removeEventListener('storage', onStorage);
172
- observer.disconnect();
173
- });
174
- buttons.forEach((btn) => {
175
- btn.onclick = () => {
176
- const current = html.getAttribute('data-theme-choice');
177
- applyTheme(current === 'dark' ? 'light' : current === 'light' ? 'auto' : 'dark', html);
178
- };
179
- });
180
- }
181
- // Deck/Text view switch (.dtsw) — switch the active pill on click
182
- root.querySelectorAll('.dtsw').forEach((sw) => {
183
- sw.addEventListener('click', (e) => {
184
- const a = e.target.closest('a');
185
- if (!a || !sw.contains(a)) return;
186
- e.preventDefault();
187
- sw.querySelectorAll('a').forEach((x) => { x.classList.remove('cur'); x.removeAttribute('aria-current'); });
188
- a.classList.add('cur');
189
- a.setAttribute('aria-current', 'page');
190
- });
191
- });
192
- // Segmented controls (.ui-seg) — a toolbar of toggle buttons (see segmented()
193
- // in components/index.js). Click selects; ArrowLeft/ArrowRight move and wrap,
194
- // Home/End jump to the ends. The strip keeps ONE Tab stop: selecting an option
195
- // hands it the tabindex and takes it off the rest, so a page with three of
196
- // these costs three Tab presses, not nine.
197
- root.querySelectorAll('.ui-seg').forEach((seg) => {
198
- const btns = () => Array.prototype.slice.call(seg.querySelectorAll('button'));
199
- const select = (b, focus) => {
200
- btns().forEach((x) => {
201
- const on = x === b;
202
- x.classList.toggle('is-active', on);
203
- // Older hand-written .ui-seg markup carries aria-selected; segmented()
204
- // now emits aria-pressed. Keep whichever the button actually declares in
205
- // step, and never invent the other one.
206
- if (x.hasAttribute('aria-pressed')) x.setAttribute('aria-pressed', on ? 'true' : 'false');
207
- if (x.hasAttribute('aria-selected')) x.setAttribute('aria-selected', on ? 'true' : 'false');
208
- x.tabIndex = on ? 0 : -1;
209
- });
210
- if (focus) b.focus();
211
- };
212
- seg.addEventListener('click', (e) => {
213
- const b = e.target.closest('button');
214
- if (!b || !seg.contains(b)) return;
215
- select(b);
216
- });
217
- seg.addEventListener('keydown', (e) => {
218
- const b = e.target.closest('button');
219
- if (!b || !seg.contains(b)) return;
220
- const all = btns();
221
- const i = all.indexOf(b);
222
- let n = null;
223
- if (e.key === 'ArrowRight') n = (i + 1) % all.length;
224
- else if (e.key === 'ArrowLeft') n = (i - 1 + all.length) % all.length;
225
- else if (e.key === 'Home') n = 0;
226
- else if (e.key === 'End') n = all.length - 1;
227
- if (n === null) return;
228
- e.preventDefault();
229
- select(all[n], true);
230
- });
231
- });
232
- // Version switcher + account menu — the shared dropdown wiring (open/close +
233
- // click-outside + Esc + keyboard nav). One implementation for the whole kit.
234
- wireDropdown(root);
235
- // Accent pickers
236
- root.querySelectorAll('[data-accent-pick]').forEach((chip) => {
237
- chip.addEventListener('click', () => {
238
- applyAccent(chip.getAttribute('data-accent-pick'), document.documentElement);
239
- const group = chip.closest('[data-accent-group]') || root;
240
- group.querySelectorAll('[data-accent-pick]').forEach((c) => {
241
- c.classList.toggle('is-active', c === chip);
242
- // Keep the announced state in step with the visual one.
243
- if (c.hasAttribute('aria-pressed')) c.setAttribute('aria-pressed', c === chip ? 'true' : 'false');
244
- });
245
- });
246
- });
247
- // Copy buttons. The confirmation is a glyph swap plus a word in the live region
248
- // beside the button, so the control holds its 24px box and a reader who cannot
249
- // see the check still hears it. Writing the word into the button would do
250
- // neither: the box jumps, and the permanent aria-label outranks the contents, so
251
- // the announced name would never move. The restore reads the markup the button
252
- // started with — putting `data-orig` back wrote the label as words and dropped
253
- // the glyph, which only looked harmless while a word sat beside it. #474
254
- root.querySelectorAll('.ui-snippet__copy').forEach((btn) => {
255
- const resting = btn.innerHTML;
256
- const status = btn.parentElement?.querySelector('.ui-snippet__status');
257
- btn.addEventListener('click', () => {
258
- const pre = btn.closest('.ui-snippet')?.querySelector('pre');
259
- if (!pre) return;
260
- navigator.clipboard?.writeText(pre.innerText);
261
- btn.innerHTML = icon('check');
262
- if (status) status.textContent = 'Copied';
263
- setTimeout(() => {
264
- btn.innerHTML = resting;
265
- if (status) status.textContent = '';
266
- }, 1400);
267
- });
268
- });
269
- }