@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,424 +0,0 @@
1
- import { calloutIcons } from '../logic/callout.js';
2
- import { ACCENTS, accentSwatchStyle } from '../logic/accents.js';
3
- export { calloutIcons } from '../logic/callout.js';
4
- // apliteni-ui component factories — each returns an HTML string, matching the
5
- // viz/ server-render idiom so the portal can adopt them with no framework.
6
- import { icon } from '../assets/icons.js';
7
- import { illo } from '../assets/illustrations.js';
8
- import { successCheck } from './success.js';
9
- import { esc, safeUrl } from '../html.js';
10
- export { esc, safeUrl } from '../html.js';
11
- const cx = (...a) => a.filter(Boolean).join(' ');
12
- // ---- Button --------------------------------------------------------------
13
- // `iconSvg` is a raw leading-icon SVG string (trusted markup, not escaped) for
14
- // branded glyphs the kit's icon set doesn't own — e.g. a Google "G". It takes
15
- // the leading slot; `icon` is the named-icon shorthand for kit glyphs. This is
16
- // what lets third-party buttons go through button() instead of hand-rolled markup.
17
- //
18
- // `iconOnly` drops the visible text, and kit glyphs are aria-hidden — so `label`
19
- // stops being decoration and becomes the control's ONLY accessible name. It is
20
- // mirrored into aria-label + title, and an empty label falls back to the icon
21
- // name rather than shipping a nameless button.
22
- //
23
- // That is the accessibility half, and it is not permission. WHEN a control may
24
- // go wordless is a closed list — `iconOnlyAllowed` in src/assets/icons.js — and
25
- // stories/guidelines/iconography.test.js reviews call sites against it.
26
- export function button({
27
- label = 'Button', variant = 'secondary', size = 'md', icon: ic, iconSvg, iconRight,
28
- block = false, disabled = false, busy = false, type = 'button', href, iconOnly = false,
29
- } = {}) {
30
- const cls = cx(
31
- 'ui-btn',
32
- variant && `ui-btn--${variant}`,
33
- size !== 'md' && `ui-btn--${size}`,
34
- block && 'ui-btn--block',
35
- iconOnly && 'ui-btn--icon',
36
- );
37
- const dots = busy ? '<span class="ui-btn__dots" aria-hidden="true"><i></i><i></i><i></i></span>' : '';
38
- const lead = iconSvg || (ic ? icon(ic) : '');
39
- const inner = `${lead}${iconOnly ? '' : `<span class="ui-btn__label-slot"><span class="ui-btn__label">${esc(label)}</span></span>`}${iconRight ? icon(iconRight) : ''}${dots}`;
40
- // Static busy ⇒ disabled; setButtonBusy wires focus-preserving activation guards.
41
- const name = String(label == null ? '' : label).trim() || ic || 'Button';
42
- const named = iconOnly ? ` aria-label="${esc(name)}" title="${esc(name)}"` : '';
43
- const attrs = `class="${esc(cls)}"${disabled || busy ? ' disabled aria-disabled="true"' : ''}${busy ? ' aria-busy="true"' : ''}${disabled && busy ? ' data-btn-disabled' : ''}${named}`;
44
- const control = href
45
- ? `<a href="${esc(safeUrl(href))}" ${attrs}>${inner}</a>`
46
- : `<button type="${esc(type)}" ${attrs}>${inner}</button>`;
47
- return busy ? `${control}<span class="ui-sr ui-btn__status" role="status" aria-live="polite"></span>` : control;
48
- }
49
-
50
- // ---- Badge / Pill --------------------------------------------------------
51
- // Neutral is written out rather than left implied: a status column reading its tone off the
52
- // class list found nothing on two of four rows, and the tone a chip is in is not a default
53
- // the markup should have to know. The base class carries the same fill either way. #459
54
- export function badge(label, variant = 'neutral') {
55
- return `<span class="${esc(cx('ui-badge', `ui-badge--${variant}`))}">${esc(label)}</span>`;
56
- }
57
- export function pill(label, variant) {
58
- return `<span class="${esc(cx('ui-pill', variant && `ui-pill--${variant}`))}">${esc(label)}</span>`;
59
- }
60
- export function statusDot(live = false) {
61
- return `<span class="${cx('ui-dot', live && 'is-live')}"></span>`;
62
- }
63
-
64
- // ---- Card ----------------------------------------------------------------
65
- // The title is a heading one level under the page's h1 unless `level` says
66
- // otherwise. why: docs/foundations.md#labels-and-titles
67
- export function card({ title, sub, body = '', variant, pad, icon: ic, level = 2 } = {}) {
68
- const cls = cx('ui-card', variant && `ui-card--${variant}`, pad && `ui-card--pad-${pad}`);
69
- const h = [2, 3, 4, 5, 6].includes(Number(level)) ? `h${Number(level)}` : 'h2';
70
- // title/sub are trusted markup (may carry a badge/icon) — not escaped.
71
- const head = title
72
- ? `<${h} class="ui-card__title">${ic ? `<span class="ui-card__icon">${icon(ic)}</span>` : ''}${title}</${h}>${sub ? `<div class="ui-card__sub">${sub}</div>` : ''}`
73
- : '';
74
- return `<div class="${esc(cls)}">${head}${body}</div>`;
75
- }
76
-
77
- // ---- Segmented control ---------------------------------------------------
78
- // A strip of mutually exclusive toggle buttons.
79
- // It is NOT a tablist: it controls no panel, so it must not announce one.
80
- // `role="toolbar"` with a roving tabindex is the honest shape, and wireTopbar()
81
- // ships the keyboard behaviour.
82
- //
83
- // When the pill drives a real change of view, reach for tabs() instead —
84
- // that one owns panels and earns the tab announcement.
85
- //
86
- // `ariaLabel` names the strip. `name` seeds data-seg and is deliberately
87
- // not an accessible name — it is an identifier, not prose, defaulting to
88
- // "Options" so a strip is never left unlabelled.
89
- export function segmented({ options = [], active = 0, size, block, name = 'seg', ariaLabel = 'Options', appearance, disabled = false } = {}) {
90
- const cls = cx('ui-seg', appearance === 'underline' && 'ui-seg--underline', size && `ui-seg--${size}`, block && 'ui-seg--block');
91
- // Exactly one option holds the Tab stop. If `active` points nowhere (nothing
92
- // selected yet) the first option holds it, so the strip is never unreachable.
93
- const rove = active >= 0 && active < options.length && !options[active]?.disabled ? active : options.findIndex(o => !o.disabled);
94
- const btns = options.map((o, i) => {
95
- const label = typeof o === 'string' ? o : o.label;
96
- const val = typeof o === 'string' ? o : (o.value ?? o.label);
97
- const on = i === active;
98
- return `<button type="button"${disabled || o.disabled ? ' disabled' : ''} aria-pressed="${on}" tabindex="${i === rove ? '0' : '-1'}"`
99
- + ` data-value="${esc(val)}"${on ? ' class="is-active"' : ''}>${esc(label)}</button>`;
100
- }).join('');
101
- return `<div class="${esc(cls)}" role="toolbar" aria-label="${esc(ariaLabel)}" data-seg="${esc(name)}">${btns}</div>`;
102
- }
103
-
104
- // ---- Accent picker -------------------------------------------------------
105
- // The accent list and every swatch's paints live in ../logic/accents.js, which
106
- // the React picker reads too, so neither copy can drift from the other.
107
- // Swatches have no text and no glyph at all — the aria-label is the whole
108
- // accessible name, and aria-pressed carries which one is on.
109
- export function accentPicker({ active = 'default', options = ACCENTS } = {}) {
110
- const title = (o) => o.charAt(0).toUpperCase() + o.slice(1);
111
- const style = (o) => Object.entries(accentSwatchStyle(o)).map(([k, v]) => `${k}:${v}`).join(';');
112
- return `<div class="ui-accent-picker" data-accent-group role="group" aria-label="Accent">${options.map((o) =>
113
- `<button type="button" data-accent-pick="${esc(o)}"${o === active ? ' class="is-active"' : ''}`
114
- + ` style="${style(o)}" aria-pressed="${o === active ? 'true' : 'false'}"`
115
- + ` aria-label="${esc(title(o))} accent" title="${esc(title(o))}"></button>`).join('')}</div>`;
116
- }
117
-
118
- // ---- Field / input -------------------------------------------------------
119
- // Auto-generated ids let field() tie its <label for> to the control it wraps.
120
- // A module counter (never Date/random) keeps ids unique within a rendered page.
121
- let _uid = 0;
122
- const nextId = (p = 'ui') => `${p}-${++_uid}`;
123
- // Give the first form control in `html` an id (or reuse one it already carries)
124
- // so a <label> can point at it. Returns { html, id }; id is null if there's no
125
- // form element to name.
126
- function withControlId(html) {
127
- const existing = html.match(/<(?:input|textarea|select)\b[^>]*\bid="([^"]+)"/);
128
- if (existing) return { html, id: existing[1] };
129
- let id = null;
130
- const out = html.replace(/<(input|textarea|select)\b/, (m) => { id = nextId('field'); return `${m} id="${id}"`; });
131
- return { html: out, id };
132
- }
133
- // Same trick, for the attributes that carry state rather than identity:
134
- // aria-describedby, aria-invalid, required. Anything the control already spells
135
- // out for itself wins — a caller who passed `invalid` to input() keeps their own
136
- // aria-invalid. `true` renders a bare boolean attribute.
137
- function withAttrsOn(html, openTag, attrs) {
138
- const pairs = Object.entries(attrs).filter(([, v]) => v != null && v !== false);
139
- if (!pairs.length) return html;
140
- return html.replace(openTag, (m, tag, rest, tail) => {
141
- const add = pairs
142
- .filter(([k]) => !new RegExp(`\\s${k}(?=[\\s=>/]|$)`).test(rest))
143
- .map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${esc(v)}"`))
144
- .join('');
145
- return `<${tag}${rest}${add}${tail}>`;
146
- });
147
- }
148
- const withControlAttrs = (html, attrs) => withAttrsOn(html, /<(input|textarea|select)\b([^>]*?)(\s*\/?)>/, attrs);
149
-
150
- // A dropdown() is not a form element: its id sits on the outer div, which a
151
- // <label for> cannot name, and its one input (the search field) is inside the
152
- // panel. So field() wires the trigger button instead: the label and the value
153
- // name it, and the hint or error describes it. why: docs/components.md#forms
154
- const DD_ROOT = /<(div)\b((?=[^>]*\bdata-dropdown(?=[\s>]))[^>]*?)(\s*\/?)>/;
155
- const DD_TRIGGER = /<(button)\b((?=[^>]*\bdata-dropdown-trigger\b)[^>]*?)(\s*\/?)>/;
156
- const DD_PANEL = /<(div)\b((?=[^>]*\bdata-dropdown-panel\b)[^>]*?)(\s*\/?)>/;
157
- const attrId = (tag) => tag?.match(/\sid="([^"]+)"/)?.[1] || null;
158
- function withDropdownId(html, id) {
159
- const root = html.match(DD_ROOT)[0];
160
- const existing = attrId(root);
161
- if (existing) return { html, id: existing };
162
- const own = id || nextId('field');
163
- return { html: html.replace(DD_ROOT, (m) => m.replace('<div', `<div id="${esc(own)}"`)), id: own };
164
- }
165
- function withDropdownAttrs(html, { rootId, labelId, describedby, invalid }) {
166
- const trigger = html.match(DD_TRIGGER)?.[0] || '';
167
- const triggerId = attrId(trigger) || `${rootId}-trigger`;
168
- // A trigger that carries its own aria-label keeps it: the caller named it.
169
- const named = labelId && !/\saria-label(?:ledby)?=/.test(trigger);
170
- let out = withAttrsOn(html, DD_TRIGGER, {
171
- id: named ? triggerId : null,
172
- 'aria-labelledby': named ? `${labelId} ${triggerId}` : null,
173
- 'aria-describedby': describedby,
174
- 'aria-invalid': invalid,
175
- });
176
- const panel = html.match(DD_PANEL)?.[0] || '';
177
- if (labelId && !/\saria-label(?:ledby)?=/.test(panel)) out = withAttrsOn(out, DD_PANEL, { 'aria-labelledby': labelId });
178
- return out;
179
- }
180
-
181
- // A labelled control with, optionally, a hint or an error under it.
182
- //
183
- // The label half was wired in #119 (withControlId above → a real `for=`). This
184
- // finishes the job for the rest: the hint or error gets an id and the control
185
- // points at it with aria-describedby, so the reason a value was rejected is read
186
- // out with the field instead of sitting beside it as loose text. An errored
187
- // control is marked aria-invalid, and `required` puts the requirement in the
188
- // markup rather than in the label's wording — the asterisk is decoration on top
189
- // of that, so it is hidden from assistive technology.
190
- export function field({ label, hint, error, control = '', id, required = false } = {}) {
191
- let ctl = control;
192
- let forId = id;
193
- const dd = DD_ROOT.test(control);
194
- let ddId = null;
195
- if (label && control) {
196
- const r = dd ? withDropdownId(control, id) : withControlId(control);
197
- ctl = r.html;
198
- forId = id || r.id;
199
- if (dd) ddId = r.id;
200
- }
201
- // Error wins over hint — only one message shows, so only one id is minted.
202
- const msg = error || hint;
203
- const msgId = msg && control ? nextId(error ? 'field-err' : 'field-hint') : null;
204
- ctl = dd
205
- ? withDropdownAttrs(ctl, {
206
- rootId: ddId, labelId: ddId && `${ddId}-label`, describedby: msgId, invalid: error ? 'true' : null,
207
- })
208
- : withControlAttrs(ctl, {
209
- 'aria-describedby': msgId,
210
- 'aria-invalid': error ? 'true' : null,
211
- required: required || null,
212
- });
213
- const lab = label
214
- ? `<label class="ui-field__label"${ddId ? ` id="${esc(ddId)}-label"` : ''}${forId ? ` for="${id ? esc(id) : forId}"` : ''}>${esc(label)}`
215
- + `${required ? '<span class="ui-field__req" aria-hidden="true">*</span>' : ''}</label>`
216
- : '';
217
- const foot = error
218
- ? `<div class="ui-field__error"${msgId ? ` id="${msgId}"` : ''}>${icon('alert')}${esc(error)}</div>`
219
- : hint ? `<div class="ui-field__hint"${msgId ? ` id="${msgId}"` : ''}>${esc(hint)}</div>` : '';
220
- return `<div class="ui-field">${lab}${ctl}${foot}</div>`;
221
- }
222
- // `ariaLabel` gives a standalone control (no wrapping field) an accessible name.
223
- // `invalid` paints the control red AND says so in aria-invalid — the red on its
224
- // own is a state only a sighted user can read.
225
- export function input({ type = 'text', placeholder = '', value = '', icon: ic, invalid, disabled, required, name, id, ariaLabel } = {}) {
226
- const attrs = `${id ? ` id="${esc(id)}"` : ''}${name ? ` name="${esc(name)}"` : ''}${ariaLabel ? ` aria-label="${esc(ariaLabel)}"` : ''}`
227
- + `${invalid ? ' aria-invalid="true"' : ''}${required ? ' required' : ''}${disabled ? ' disabled' : ''}`;
228
- const el = `<input class="${cx('ui-input', invalid && 'is-invalid')}" type="${esc(type)}" placeholder="${esc(placeholder)}" value="${esc(value)}"${attrs}>`;
229
- if (!ic) return el;
230
- return `<div class="ui-input-group"><span class="ui-input-group__icon">${icon(ic)}</span>${el}</div>`;
231
- }
232
- export function textarea({ placeholder = '', value = '', rows = 4, name, id, ariaLabel } = {}) {
233
- return `<textarea class="ui-textarea" rows="${esc(rows)}" placeholder="${esc(placeholder)}"${id ? ` id="${esc(id)}"` : ''}${name ? ` name="${esc(name)}"` : ''}${ariaLabel ? ` aria-label="${esc(ariaLabel)}"` : ''}>${esc(value)}</textarea>`;
234
- }
235
- // Native <select>. Pass a `label` via field() or an `ariaLabel` for a bare one —
236
- // a select with neither has no accessible name.
237
- export function select({ options = [], value, name, id, ariaLabel, disabled } = {}) {
238
- const opts = options.map((o) => {
239
- const label = typeof o === 'string' ? o : o.label;
240
- const val = typeof o === 'string' ? o : (o.value ?? o.label);
241
- const sel = value != null && String(val) === String(value);
242
- return `<option value="${esc(val)}"${sel ? ' selected' : ''}>${esc(label)}</option>`;
243
- }).join('');
244
- return `<select class="ui-select"${id ? ` id="${esc(id)}"` : ''}${name ? ` name="${esc(name)}"` : ''}${ariaLabel ? ` aria-label="${esc(ariaLabel)}"` : ''}${disabled ? ' disabled' : ''}>${opts}</select>`;
245
- }
246
- export function checkbox({ label, checked, type = 'checkbox', name, disabled = false } = {}) {
247
- return `<label class="ui-check"><input type="${esc(type)}"${name ? ` name="${esc(name)}"` : ''}${checked ? ' checked' : ''}${disabled ? ' disabled' : ''}><span>${label}</span></label>`;
248
- }
249
- // `label` becomes the input's accessible name (a bare switch has no visible text,
250
- // so it needs one). Defaults to "Toggle" so a control is never left unlabelled.
251
- export function switchToggle({ checked = false, disabled = false, name, label = 'Toggle' } = {}) {
252
- return `<label class="ui-switch"><input type="checkbox"${name ? ` name="${esc(name)}"` : ''}${checked ? ' checked' : ''}${disabled ? ' disabled' : ''} aria-label="${esc(label)}"><span class="ui-switch__track"></span></label>`;
253
- }
254
-
255
- // ---- Callout / toast / success ------------------------------------------
256
-
257
-
258
- export function callout({ variant, icon: ic = calloutIcons[variant] || 'info', body, actions } = {}) {
259
- return `<div class="${esc(cx('ui-callout', variant && variant !== 'neutral' && `ui-callout--${variant}`))}"><span class="ui-callout__icon">${icon(ic)}</span><div class="ui-callout__body">${body}${actions != null ? `<div class="ui-toolbar ui-callout__actions">${actions}</div>` : ''}</div></div>`;
260
- }
261
- // Default icon per status — overridable with `icon`. The circle family is not
262
- // decoration: a circled glyph is a STATE the system reports, a bare one is an
263
- // ACTION you can take (iconMeanings in src/assets/icons.js).
264
- //
265
- // This used to read `success: 'check', danger: 'x', warn: 'alert'`, which made
266
- // a danger toast render the same bare `x` twice — once as the status, meaning
267
- // "this failed", once as the close button, meaning "make this go away". Status
268
- // took the circle glyphs the kit already shipped and never used, and the bare
269
- // `x` now belongs to the close button alone.
270
- const TOAST_ICON = {
271
- success: 'circleCheck', danger: 'circleX', warn: 'circleAlert', info: 'info', neutral: 'bolt',
272
- };
273
- // A toast carries a status (colour) and a style (surface). Everything visual is
274
- // token-driven: the status modifier sets --toast-accent/-glow/-on, the style
275
- // modifier consumes them. `action` adds a trailing button ("Undo"/"Retry"),
276
- // `timer` adds an auto-dismiss progress bar (true → default 5s, or a number of
277
- // seconds), `compact` drops the body for a single-line toast.
278
- export function toast({
279
- variant = 'success', style = 'soft', title, body, icon: ic,
280
- action, timer = false, compact = false, dismissible = true,
281
- } = {}) {
282
- const cls = cx('ui-toast', `ui-toast--${variant}`, `ui-toast--${style}`, compact && 'ui-toast--compact');
283
- const actLabel = typeof action === 'string' ? action : action && action.label;
284
- const actBtn = actLabel ? `<button class="ui-toast__action" type="button">${esc(actLabel)}</button>` : '';
285
- // Icon-only: the glyph is aria-hidden, so aria-label IS the accessible name.
286
- const closeBtn = dismissible ? `<button type="button" class="ui-toast__close" aria-label="Dismiss">${icon('x')}</button>` : '';
287
- const bodyHtml = compact || !body ? '' : `<div class="ui-toast__text">${esc(body)}</div>`;
288
- const dur = typeof timer === 'number' ? ` style="--toast-dur:${timer}s"` : '';
289
- const timerBar = timer ? '<span class="ui-toast__timer" data-toast-timer></span>' : '';
290
- return `<div class="${esc(cls)}" role="status" aria-live="polite"${dur}>`
291
- + `<span class="ui-toast__icon">${icon(ic || TOAST_ICON[variant] || 'info')}</span>`
292
- + `<div class="ui-toast__body">${title ? `<div class="ui-toast__title">${esc(title)}</div>` : ''}${bodyHtml}</div>`
293
- + `${actBtn}${closeBtn}${timerBar}</div>`;
294
- }
295
- // The inline confirmation. A check, a title and one line of sub, dropped into
296
- // the page the user is already on — under a form that just submitted, or inside
297
- // a card. Two strings, no options; styles are .ui-success in styles/callout.css.
298
- //
299
- // The kit also publishes success() from components/success.js, which is the same
300
- // idea at page size: layouts, follow-up buttons and an auto-redirect countdown.
301
- // Pick by how much of the screen the confirmation owns. The two share the check;
302
- // their layout and content remain independent.
303
- export function successPanel({ title = 'Done', sub = '', check = 'line' } = {}) {
304
- // The circled mark is one status size everywhere, so the box narrows for it.
305
- const box = check === 'circled' ? 'ui-success__check ui-success__check--circled' : 'ui-success__check';
306
- return `<div class="ui-success"><div class="${box}">${successCheck(check)}</div><div class="ui-success__title">${esc(title)}</div>${sub ? `<div class="ui-success__sub">${esc(sub)}</div>` : ''}</div>`;
307
- }
308
-
309
- // ---- Empty state ---------------------------------------------------------
310
- // The placeholder for an empty list/table/page. Pass `art` as an illustration
311
- // name (see illustrations.js) or raw <svg> markup; a legacy line `icon` name is
312
- // also accepted. `actions` is trusted button markup (e.g. button({…})).
313
- export function emptyState({ art, icon: ic, title, sub, actions } = {}) {
314
- const artHtml = art
315
- ? `<div class="ui-empty__art">${/<svg/.test(art) ? art : illo(art)}</div>`
316
- : ic ? `<div class="ui-empty__icon">${icon(ic)}</div>` : '';
317
- return `<div class="ui-empty">${artHtml}`
318
- + `${title ? `<div class="ui-empty__title">${esc(title)}</div>` : ''}`
319
- + `${sub ? `<div class="ui-empty__sub">${esc(sub)}</div>` : ''}`
320
- + `${actions ? `<div class="ui-empty__actions">${actions}</div>` : ''}`
321
- + `</div>`;
322
- }
323
-
324
- // ---- Snippet -------------------------------------------------------------
325
- // The copy button is icon-only: `copy` is on the closed list in
326
- // src/assets/icons.js, the bar is narrow, and the word said nothing the glyph
327
- // does not. `copyLabel` is therefore the accessible name and the tooltip rather
328
- // than visible text, and it should name what is being copied — "Copy command",
329
- // "Copy configuration" — the way every other icon-only control in the kit is
330
- // named (aria-label plus title, as button() and the theme toggle write it).
331
- // The confirmation is a glyph swap, not a word: the button holds its 24px box
332
- // through it, and the word goes to the live region beside it. A permanent
333
- // aria-label outranks an element's contents, so swapping text into the button
334
- // would have changed the pixels and left the announced name frozen — the region
335
- // is what carries "Copied" to a reader who cannot see the check. It ships empty
336
- // and is filled later, because a role="status" inserted together with its text is
337
- // silent on several screen readers. The button's own name stays the action, which
338
- // is still available; wireTopbar() fills the region. `data-orig` records the
339
- // resting label for a caller that wants it.
340
- // `type="button"`: without it a snippet dropped inside a <form> submits the form.
341
- export function snippet({ label = 'shell', code = '', reveal = false, copy = true, copyLabel = 'Copy code' } = {}) {
342
- const copyBtn = copy
343
- ? `<button type="button" class="ui-snippet__copy" aria-label="${esc(copyLabel)}" title="${esc(copyLabel)}" data-orig="${esc(copyLabel)}">${icon('copy')}</button>`
344
- + '<span class="ui-sr ui-snippet__status" role="status" aria-live="polite"></span>'
345
- : '';
346
- return `<div class="${cx('ui-snippet', reveal && 'ui-snippet--reveal')}"><div class="ui-snippet__bar"><span>${esc(label)}</span>${copyBtn}</div><pre>${code}</pre></div>`;
347
- }
348
-
349
- // Tiny highlighters. Each escapes first, then wraps the tokens its language
350
- // shows, using the class names in styles/code.css (.k .f .s .u .c). Shell is
351
- // ported from viz/account.mjs; JSON and TypeScript were added for the snippets
352
- // the kit's own docs show.
353
- //
354
- // Every pattern runs over ESCAPED text, so a quoted string ends at &quot; and a
355
- // shell URL stops at any entity. The group order is the class order beside it.
356
- //
357
- // They are small on purpose — they colour short documentation snippets, not
358
- // arbitrary programs. Known limits: no nested template expressions, no regex
359
- // literals, and in TypeScript a `//` inside a string reads as a comment unless a
360
- // `:` precedes it, which is what keeps a URL in a string whole.
361
- const LANGUAGES = {
362
- shell: {
363
- pattern: /(#[^\n]*)|(&quot;(?:[^&]|&(?!quot;))*&quot;|'[^']*')|(https?:\/\/[^\s"'&]+)|(\B--?[A-Za-z][\w-]*)|(^[a-z][\w.-]*)/gm,
364
- classes: ['c', 's', 'u', 'f', 'k'],
365
- },
366
- // A key is a string followed by a colon, matched by lookahead so the colon
367
- // stays unpainted. Keys, string values and scalars take three different
368
- // classes, because a number that looks exactly like a key is not highlighting.
369
- json: {
370
- pattern: /(&quot;(?:[^&]|&(?!quot;))*&quot;)(?=\s*:)|(&quot;(?:[^&]|&(?!quot;))*&quot;)|(\b(?:true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g,
371
- classes: ['k', 's', 'f'],
372
- },
373
- ts: {
374
- pattern: /(\/\*[\s\S]*?\*\/|(?<![:/])\/\/[^\n]*)|(&quot;(?:[^&]|&(?!quot;))*&quot;|'[^']*'|`[^`]*`)|(\b(?:import|export|from|const|let|var|function|return|async|await|class|extends|implements|interface|type|enum|new|if|else|for|while|of|in|as|default|readonly|void)\b)|(\b(?:true|false|null|undefined)\b|\b\d+(?:\.\d+)?\b)/g,
375
- classes: ['c', 's', 'k', 'f'],
376
- },
377
- };
378
-
379
- /** The languages codeTokens and hlCode understand, so a gate can discover them. */
380
- export const codeLanguages = Object.keys(LANGUAGES);
381
-
382
- const ENTITY = { amp: '&', lt: '<', gt: '>', quot: '"' };
383
- // The exact inverse of esc: every & in escaped text starts one of these four.
384
- const unesc = (text) => text.replace(/&(amp|lt|gt|quot);/g, (_, name) => ENTITY[name]);
385
-
386
- /**
387
- * A language's tokens, as `[{ cls, text }]` with `cls` null between tokens and
388
- * `text` the original unescaped source. Concatenating `text` returns `raw`, so a
389
- * React caller renders the spans from the same string it copies instead of
390
- * keeping a second hand-written copy in step. hlCode joins the same tokens into
391
- * HTML; neither can drift from the other. An unrecognised `lang` is read as
392
- * shell, the way the kit reads every other unknown option name.
393
- *
394
- * No pattern ever matches inside an entity — `#`, `h`, `-`, `/`, `*`, a digit and
395
- * `^[a-z]` do not occur in `&amp;`, `&lt;`, `&gt;` or `&quot;`, no keyword is one
396
- * of `amp`, `lt`, `gt` or `quot`, and every alternative either stops before `&` or
397
- * consumes a whole `&quot;` — so each slice is entity-complete and
398
- * `esc(unesc(slice))` returns the slice unchanged. hlCode's output is therefore
399
- * byte-identical to wrapping the matches in place, which
400
- * src/components/snippet-tokens.test.js holds for every language, against a copy
401
- * of the one-pass implementation hlShell had before #474.
402
- */
403
- export function codeTokens(raw, lang = 'shell') {
404
- const { pattern, classes } = LANGUAGES[lang] || LANGUAGES.shell;
405
- const escaped = esc(raw);
406
- const out = [];
407
- let at = 0;
408
- pattern.lastIndex = 0;
409
- for (const match of escaped.matchAll(pattern)) {
410
- if (match.index > at) out.push({ cls: null, text: unesc(escaped.slice(at, match.index)) });
411
- out.push({ cls: classes[match.slice(1).findIndex(Boolean)], text: unesc(match[0]) });
412
- at = match.index + match[0].length;
413
- }
414
- if (at < escaped.length) out.push({ cls: null, text: unesc(escaped.slice(at)) });
415
- return out;
416
- }
417
-
418
- export const hlCode = (raw, lang = 'shell') =>
419
- codeTokens(raw, lang).map(({ cls, text }) => (cls ? `<span class="${cls}">${esc(text)}</span>` : esc(text))).join('');
420
-
421
- export const hlShell = (raw) => hlCode(raw, 'shell');
422
-
423
- export { icon };
424
- export { illo, illoNames } from '../assets/illustrations.js';
@@ -1,127 +0,0 @@
1
- // The pending and denied states of a SCREEN, not of one control.
2
- //
3
- // busyRegion() is one live region that outlives what it reports on; setBusy()
4
- // swaps its body and writes a line into the sr-only node already inside it.
5
- // Three things land in that body: skeleton() while it fetches, your markup once
6
- // the rows arrive, deniedState() when the answer came back 403.
7
- //
8
- // why: docs/components.md#pending-and-denied-states
9
- import { icon } from '../assets/icons.js';
10
- import { button, esc } from './index.js';
11
- import { playEntrance } from '../motion.js';
12
-
13
- const cx = (...a) => a.filter(Boolean).join(' ');
14
- // ---- Skeleton ------------------------------------------------------------
15
- // The placeholder shape. `lines` is a count, or an array of widths when the
16
- // varied ragged edge of real prose matters (['100%','92%','60%']). `height`
17
- // makes it one solid block instead — a chart, a map, an avatar. The shimmer is
18
- // .m-skeleton from the motion library, so there is one animation to own and it
19
- // is already inside that library's reduced-motion net.
20
- export function skeleton({ lines = 3, width, height, radius, className = '' } = {}) {
21
- const widths = Array.isArray(lines) ? lines : Array.isArray(width) ? width : null;
22
- const n = widths ? widths.length : Math.max(1, lines | 0);
23
- const styleFor = (i) => {
24
- const w = widths ? widths[i] : (typeof width === 'string' ? width : null);
25
- const bits = [w && `width:${w}`, height && `height:${height}`, radius && `border-radius:${radius}`];
26
- const s = bits.filter(Boolean).join(';');
27
- return s ? ` style="${esc(s)}"` : '';
28
- };
29
- const bars = Array.from({ length: n }, (_, i) =>
30
- `<span class="ui-skel__bar m-skeleton"${styleFor(i)}></span>`).join('');
31
- return `<div class="${esc(cx('ui-skel', className))}" aria-hidden="true">${bars}</div>`;
32
- }
33
-
34
- // A table's worth of skeleton — `rows` × `cols` of bar, laid out on a grid so
35
- // the placeholder has the column rhythm the real table will have. Screens that
36
- // load a table are the common case, and hand-rolling this per screen is how
37
- // four slightly different loading tables get shipped.
38
- export function skeletonTable({ rows = 5, cols = 4, head = true } = {}) {
39
- const row = (cls) => `<div class="${esc(cls)}">`
40
- + Array.from({ length: Math.max(1, cols | 0) }, () => '<span class="ui-skel__bar m-skeleton"></span>').join('')
41
- + '</div>';
42
- const body = Array.from({ length: Math.max(1, rows | 0) }, () => row('ui-skel__row')).join('');
43
- return `<div class="ui-skel ui-skel--table" style="--skel-cols:${Math.max(1, cols | 0)}" aria-hidden="true">`
44
- + `${head ? row('ui-skel__row ui-skel__row--head') : ''}${body}</div>`;
45
- }
46
-
47
- // ---- The region ----------------------------------------------------------
48
- // `label` is what is spoken while it works, `readyLabel` the fallback for when
49
- // it finishes without the caller supplying a line. Both are parked on the
50
- // element so setBusy() can find them and the caller never repeats itself.
51
- //
52
- // `body` overrides the default skeleton (pass your own placeholder, or the
53
- // already-loaded content when the region starts ready).
54
- export function busyRegion({
55
- label = 'Loading…', readyLabel = 'Loaded', busy = true,
56
- body, lines = 3, className = '',
57
- } = {}) {
58
- const inner = body != null ? body : skeleton({ lines });
59
- return `<div class="${esc(cx('ui-busy', className))}" data-busy`
60
- + ` data-busy-label="${esc(label)}" data-busy-ready="${esc(readyLabel)}"`
61
- + ` role="status" aria-live="polite" aria-busy="${busy ? 'true' : 'false'}">`
62
- + `<span class="ui-sr" data-busy-msg>${esc(busy ? label : readyLabel)}</span>`
63
- + `<div class="ui-busy__body" data-busy-body>${inner}</div>`
64
- + '</div>';
65
- }
66
-
67
- // Flip a region between busy and ready, and say so. Writing into
68
- // [data-busy-msg] IS the announcement. Callers pass `message` for the specific
69
- // line ("14 invoices", "You don't have access to this report"); the region's
70
- // own labels are the fallback.
71
- //
72
- // Accepts the region, a selector, or any ancestor of it. Returns the region, or
73
- // null when there is nothing to update — safe to call against a torn-down view.
74
- export function setBusy(root, { busy = false, message, body } = {}) {
75
- const el = typeof root === 'string' ? document.querySelector(root) : root;
76
- if (!el || typeof el.querySelector !== 'function') return null;
77
- const region = el.matches && el.matches('[data-busy]') ? el : el.querySelector('[data-busy]');
78
- if (!region) return null;
79
-
80
- region.setAttribute('aria-busy', busy ? 'true' : 'false');
81
- if (body != null) {
82
- const slot = region.querySelector('[data-busy-body]');
83
- // The new body fades in. Only here — the region the page loads with is still.
84
- if (slot) { slot.innerHTML = body; playEntrance(slot); }
85
- }
86
- const msg = region.querySelector('[data-busy-msg]');
87
- if (msg) {
88
- const fallback = busy
89
- ? (region.dataset.busyLabel || 'Loading…')
90
- : (region.dataset.busyReady || 'Loaded');
91
- msg.textContent = message == null ? fallback : String(message);
92
- }
93
- return region;
94
- }
95
-
96
- // ---- Permission denied ---------------------------------------------------
97
- // The 403 screen. Same shape as emptyState() — a mark, a title, a line, some
98
- // actions — because to a reader they are the same event: the thing you came for
99
- // is not here. What separates them is that this one owes an explanation, so
100
- // `need` is a first-class slot rather than something to bury in `sub`.
101
- //
102
- // `need` names the scope or role the reader is missing, verbatim, as code. A
103
- // reader who can act on "you need reports.read" acts on it; "insufficient
104
- // permissions" sends them to open a ticket to find out what to ask for.
105
- //
106
- // No role and no live region here — see the file header. When this lands as the
107
- // answer to a fetch, put it inside a busyRegion() and the region announces it.
108
- export function deniedState({
109
- title = 'You don’t have access',
110
- sub = '',
111
- need = '',
112
- actions = [],
113
- icon: ic = 'lock',
114
- className = '',
115
- } = {}) {
116
- const needEl = need
117
- ? `<div class="ui-denied__need">Needs <code class="ui-code">${esc(need)}</code></div>`
118
- : '';
119
- const actionsEl = actions.length
120
- ? `<div class="ui-denied__actions">${actions.map((a) => button({ size: 'md', ...a })).join('')}</div>`
121
- : '';
122
- return `<div class="${esc(cx('ui-denied', className))}">`
123
- + `<div class="ui-denied__seal" aria-hidden="true">${icon(ic)}</div>`
124
- + `<div class="ui-denied__title">${esc(title)}</div>`
125
- + `${sub ? `<div class="ui-denied__sub">${esc(sub)}</div>` : ''}`
126
- + `${needEl}${actionsEl}</div>`;
127
- }