@commmerce/ui 1.6.0 → 1.7.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.
@@ -1,23 +1,43 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
1
6
  var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
7
  if (kind === "m") throw new TypeError("Private method is not writable");
3
8
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
10
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
11
  };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _CmToast_instances, _CmToast_primeTimer, _CmToast_timer, _CmToast_remaining, _CmToast_startedAt, _CmToast_hovered, _CmToast_focused, _CmToast_paused_get, _CmToast_resume, _CmToast_pause, _CmToast_onEnter, _CmToast_onLeave, _CmToast_onFocusIn, _CmToast_onFocusOut, _CmToast_action, _CmToastRegion_ownLabel, _CmToastRegion_onDismiss;
12
+ var _CmToast_instances, _CmToast_primeTimer, _CmToast_timer, _CmToast_remaining, _CmToast_startedAt, _CmToast_hovered, _CmToast_focused, _CmToast_closed, _CmToast_settle, _CmToast_reason, _CmToast_finish, _CmToast_paused_get, _CmToast_resume, _CmToast_pause, _CmToast_onEnter, _CmToast_onLeave, _CmToast_onFocusIn, _CmToast_onFocusOut, _CmToast_action, _CmToastRegion_instances, _CmToastRegion_returnTo, _CmToastRegion_ownLabel, _CmToastRegion_onDismiss, _CmToastRegion_onFocusIn, _CmToastRegion_onKeyDown, _CmToastRegion_onDocKeyDown, _CmToastRegion_giveFocusBack;
13
13
  import { html, css, nothing } from 'lit';
14
14
  import { base, define } from '../base.js';
15
- import { CmLocalizedElement, defineStrings } from '../localize.js';
15
+ import { CmLocalizedElement, defineStrings, translate } from '../localize.js';
16
16
  import './icon.js';
17
17
  const regionStrings = defineStrings('toastRegion', {
18
18
  /** Accessible name of the toast region (a live region). */
19
19
  label: 'Notifications',
20
20
  });
21
+ const toastStrings = defineStrings('toast', {
22
+ /** Label of the action that `undoable()` adds. */
23
+ undo: 'Undo',
24
+ /** Read after a toast that has an action, in a toast region: how to reach it from the keyboard. Empty: not read. */
25
+ shortcut: 'Press F6 to reach it.',
26
+ });
27
+ /** The focused element, looking inside shadow roots. */
28
+ const deepActive = () => {
29
+ let a = document.activeElement;
30
+ while (a?.shadowRoot?.activeElement)
31
+ a = a.shadowRoot.activeElement;
32
+ return a && a !== document.body ? a : null;
33
+ };
34
+ /** Whether `node` is `host` or inside it, crossing shadow roots. */
35
+ const within = (host, node) => {
36
+ for (let n = node; n; n = n.parentNode ?? n.host ?? null)
37
+ if (n === host)
38
+ return true;
39
+ return false;
40
+ };
21
41
  const MIN = 2000;
22
42
  const MAX = 10000;
23
43
  /** How long a new live region gets before its first message, so screen readers register it (ms). */
@@ -25,7 +45,8 @@ const LIVE_REGION_DELAY = 150;
25
45
  /**
26
46
  * A short confirmation that appears at the bottom of the screen and goes away on its own ("Product saved").
27
47
  * Usually shown with `showToast()`, which puts it in the page's toast region so screen readers announce it.
28
- * Hovering or focusing it pauses the timer.
48
+ * Hovering or focusing it pauses the timer. In a toast region, F6 moves focus to the newest toast's action and back.
49
+ * `closed` resolves with how it closed, so code can wait for an Undo (or for the toast to go).
29
50
  * @element cm-toast
30
51
  * @slot - The message, if not given with `message`.
31
52
  * @fires cm-action - The action button was pressed (cancelable; by default the toast then closes).
@@ -53,6 +74,9 @@ export class CmToast extends CmLocalizedElement {
53
74
  _CmToast_startedAt.set(this, 0);
54
75
  _CmToast_hovered.set(this, false);
55
76
  _CmToast_focused.set(this, false);
77
+ _CmToast_closed.set(this, void 0);
78
+ _CmToast_settle.set(this, void 0);
79
+ _CmToast_reason.set(this, void 0);
56
80
  _CmToast_onEnter.set(this, () => { __classPrivateFieldSet(this, _CmToast_hovered, true, "f"); __classPrivateFieldGet(this, _CmToast_instances, "m", _CmToast_pause).call(this); });
57
81
  _CmToast_onLeave.set(this, () => { __classPrivateFieldSet(this, _CmToast_hovered, false, "f"); __classPrivateFieldGet(this, _CmToast_instances, "m", _CmToast_resume).call(this); });
58
82
  _CmToast_onFocusIn.set(this, () => { __classPrivateFieldSet(this, _CmToast_focused, true, "f"); __classPrivateFieldGet(this, _CmToast_instances, "m", _CmToast_pause).call(this); });
@@ -65,6 +89,18 @@ export class CmToast extends CmLocalizedElement {
65
89
  __classPrivateFieldGet(this, _CmToast_instances, "m", _CmToast_resume).call(this);
66
90
  });
67
91
  }
92
+ /**
93
+ * Resolves when the toast closes (this time it is shown), with the reason: `action` (its action was pressed),
94
+ * `close` (Dismiss, Esc or `open = false`), `timeout`, or `removed` (taken off the page while open, e.g. pushed out by newer toasts).
95
+ */
96
+ get closed() {
97
+ if (!__classPrivateFieldGet(this, _CmToast_closed, "f")) {
98
+ if (!this.open && __classPrivateFieldGet(this, _CmToast_reason, "f"))
99
+ return Promise.resolve(__classPrivateFieldGet(this, _CmToast_reason, "f"));
100
+ __classPrivateFieldSet(this, _CmToast_closed, new Promise((resolve) => { __classPrivateFieldSet(this, _CmToast_settle, resolve, "f"); }), "f");
101
+ }
102
+ return __classPrivateFieldGet(this, _CmToast_closed, "f");
103
+ }
68
104
  /** The time the toast stays, clamped to 2000–10000 ms. */
69
105
  get effectiveDuration() {
70
106
  const d = this.duration ?? (this.actionLabel ? MAX : 5000);
@@ -82,6 +118,10 @@ export class CmToast extends CmLocalizedElement {
82
118
  }
83
119
  disconnectedCallback() {
84
120
  super.disconnectedCallback();
121
+ // Taken off the page while showing (not just moved): whoever waits on `closed` hears about it.
122
+ if (this.open && __classPrivateFieldGet(this, _CmToast_settle, "f"))
123
+ queueMicrotask(() => { if (!this.isConnected && this.open)
124
+ __classPrivateFieldGet(this, _CmToast_instances, "m", _CmToast_finish).call(this, 'removed'); });
85
125
  clearTimeout(__classPrivateFieldGet(this, _CmToast_timer, "f"));
86
126
  clearTimeout(__classPrivateFieldGet(this, _CmToast_primeTimer, "f"));
87
127
  this.removeEventListener('pointerenter', __classPrivateFieldGet(this, _CmToast_onEnter, "f"));
@@ -90,6 +130,12 @@ export class CmToast extends CmLocalizedElement {
90
130
  this.removeEventListener('focusout', __classPrivateFieldGet(this, _CmToast_onFocusOut, "f"));
91
131
  }
92
132
  updated(changed) {
133
+ if (changed.has('open') && changed.get('open') !== undefined) {
134
+ if (this.open)
135
+ __classPrivateFieldSet(this, _CmToast_reason, undefined, "f");
136
+ else if (__classPrivateFieldGet(this, _CmToast_settle, "f"))
137
+ __classPrivateFieldGet(this, _CmToast_instances, "m", _CmToast_finish).call(this, 'close');
138
+ }
93
139
  if (changed.has('open') || changed.has('duration') || changed.has('actionLabel') || changed.has('_primed') || changed.has('_inRegion')) {
94
140
  clearTimeout(__classPrivateFieldGet(this, _CmToast_timer, "f"));
95
141
  // The time on screen starts when the message is shown.
@@ -118,22 +164,29 @@ export class CmToast extends CmLocalizedElement {
118
164
  }
119
165
  clearTimeout(__classPrivateFieldGet(this, _CmToast_timer, "f"));
120
166
  this.open = false;
167
+ __classPrivateFieldGet(this, _CmToast_instances, "m", _CmToast_finish).call(this, reason);
121
168
  return true;
122
169
  }
123
170
  render() {
124
171
  const body = html `<div class="toast" part="toast">
125
172
  ${this.tone === 'critical' ? html `<cm-icon class="icon" name="alert" size="20"></cm-icon>` : nothing}
126
173
  <div class="message" part="message">${this.message}<slot></slot></div>
127
- ${this.actionLabel ? html `<button class="action" part="action" @click=${__classPrivateFieldGet(this, _CmToast_instances, "m", _CmToast_action)}>${this.actionLabel}</button>` : nothing}
174
+ ${this.actionLabel ? html `<button class="action" part="action" aria-keyshortcuts=${this._inRegion ? 'F6' : nothing} @click=${__classPrivateFieldGet(this, _CmToast_instances, "m", _CmToast_action)}>${this.actionLabel}</button>` : nothing}
128
175
  <button class="close" part="close" aria-label=${this.t('dismiss')} @click=${() => this.dismiss('close')}>
129
176
  <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="m4 4 8 8M12 4l-8 8" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>
130
177
  </button>
178
+ ${this.actionLabel && this._inRegion && this.t('shortcut') ? html `<span class="hint">${this.t('shortcut')}</span>` : nothing}
131
179
  </div>`;
132
180
  // Inside a toast region the region is the live region; alone, the toast carries its own.
133
181
  return this._inRegion ? body : html `<div role="status" aria-live="polite" aria-atomic="false">${this.open && this._primed ? body : nothing}</div>`;
134
182
  }
135
183
  }
136
- _CmToast_primeTimer = new WeakMap(), _CmToast_timer = new WeakMap(), _CmToast_remaining = new WeakMap(), _CmToast_startedAt = new WeakMap(), _CmToast_hovered = new WeakMap(), _CmToast_focused = new WeakMap(), _CmToast_onEnter = new WeakMap(), _CmToast_onLeave = new WeakMap(), _CmToast_onFocusIn = new WeakMap(), _CmToast_onFocusOut = new WeakMap(), _CmToast_instances = new WeakSet(), _CmToast_paused_get = function _CmToast_paused_get() { return __classPrivateFieldGet(this, _CmToast_hovered, "f") || __classPrivateFieldGet(this, _CmToast_focused, "f"); }, _CmToast_resume = function _CmToast_resume() {
184
+ _CmToast_primeTimer = new WeakMap(), _CmToast_timer = new WeakMap(), _CmToast_remaining = new WeakMap(), _CmToast_startedAt = new WeakMap(), _CmToast_hovered = new WeakMap(), _CmToast_focused = new WeakMap(), _CmToast_closed = new WeakMap(), _CmToast_settle = new WeakMap(), _CmToast_reason = new WeakMap(), _CmToast_onEnter = new WeakMap(), _CmToast_onLeave = new WeakMap(), _CmToast_onFocusIn = new WeakMap(), _CmToast_onFocusOut = new WeakMap(), _CmToast_instances = new WeakSet(), _CmToast_finish = function _CmToast_finish(reason) {
185
+ __classPrivateFieldSet(this, _CmToast_reason, reason, "f");
186
+ const settle = __classPrivateFieldGet(this, _CmToast_settle, "f");
187
+ __classPrivateFieldSet(this, _CmToast_closed, __classPrivateFieldSet(this, _CmToast_settle, undefined, "f"), "f");
188
+ settle?.(reason);
189
+ }, _CmToast_paused_get = function _CmToast_paused_get() { return __classPrivateFieldGet(this, _CmToast_hovered, "f") || __classPrivateFieldGet(this, _CmToast_focused, "f"); }, _CmToast_resume = function _CmToast_resume() {
137
190
  clearTimeout(__classPrivateFieldGet(this, _CmToast_timer, "f"));
138
191
  if (!this.open || __classPrivateFieldGet(this, _CmToast_instances, "a", _CmToast_paused_get))
139
192
  return;
@@ -182,6 +235,13 @@ CmToast.styles = [
182
235
  }
183
236
  .action { text-decoration: underline; text-underline-offset: 3px; }
184
237
  .close { inline-size: 32px; padding: 0; }
238
+ /* Slim (32) inside the toast; on touch screens drawn 40 with a 44px hit area (owner standard 1.6). */
239
+ @media (pointer: coarse) {
240
+ button { position: relative; min-block-size: var(--cm-control-height-lg, 40px); }
241
+ .close { inline-size: var(--cm-control-height-lg, 40px); }
242
+ button::after { content: ''; position: absolute; inset: -2px; }
243
+ }
244
+ .hint { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
185
245
  button:hover { background: color-mix(in srgb, var(--cm-text-on-dark) 14%, transparent); }
186
246
  :host([tone='critical']) button:hover { background: var(--cm-bg-hover); }
187
247
  button:focus-visible { outline: 2px solid var(--cm-text-on-dark); outline-offset: 1px; }
@@ -192,21 +252,53 @@ define('cm-toast', CmToast);
192
252
  /**
193
253
  * The page's toast area: bottom centre, above everything, a polite live region so new toasts are announced.
194
254
  * `showToast()` creates one when needed; add it yourself only to change where toasts appear.
255
+ * Keyboard: F6 (or Shift+F6) moves focus to the newest toast with an action (else the newest toast) and, pressed
256
+ * again, back to where it was; Esc closes the focused toast. When a focused toast closes, focus goes back too.
195
257
  * @element cm-toast-region
196
258
  * @slot - `cm-toast` elements. Closed toasts are removed.
197
259
  */
198
260
  export class CmToastRegion extends CmLocalizedElement {
199
261
  constructor() {
200
262
  super(...arguments);
263
+ _CmToastRegion_instances.add(this);
201
264
  /** Most toasts shown at once. When a new one would exceed it, the oldest is removed. Default 3. */
202
265
  this.max = 3;
266
+ /** Where focus was before it moved into a toast, to go back to. */
267
+ _CmToastRegion_returnTo.set(this, null);
203
268
  /** The region names itself (unless the page set `aria-label`): keep that name in the current language. */
204
269
  _CmToastRegion_ownLabel.set(this, false);
205
270
  _CmToastRegion_onDismiss.set(this, (e) => {
206
271
  const t = e.target;
207
272
  // Remove after the toast has handled the event (and only if nobody cancelled it).
208
- queueMicrotask(() => { if (t.localName === 'cm-toast' && !t.open)
209
- t.remove(); });
273
+ queueMicrotask(() => {
274
+ if (t.localName !== 'cm-toast' || t.open)
275
+ return;
276
+ const hadFocus = t.matches(':focus-within');
277
+ t.remove();
278
+ if (hadFocus)
279
+ __classPrivateFieldGet(this, _CmToastRegion_instances, "m", _CmToastRegion_giveFocusBack).call(this);
280
+ });
281
+ });
282
+ _CmToastRegion_onFocusIn.set(this, (e) => {
283
+ const from = e.relatedTarget;
284
+ if (from && !within(this, from))
285
+ __classPrivateFieldSet(this, _CmToastRegion_returnTo, from, "f");
286
+ });
287
+ _CmToastRegion_onKeyDown.set(this, (e) => {
288
+ if (e.key !== 'Escape' || e.defaultPrevented)
289
+ return;
290
+ const t = e.composedPath().find((n) => n.localName === 'cm-toast');
291
+ if (t && t.parentElement === this) {
292
+ e.preventDefault();
293
+ t.dismiss('close');
294
+ }
295
+ });
296
+ _CmToastRegion_onDocKeyDown.set(this, (e) => {
297
+ if (e.key !== 'F6' || e.altKey || e.ctrlKey || e.metaKey || e.defaultPrevented)
298
+ return;
299
+ const moved = this.matches(':focus-within') ? __classPrivateFieldGet(this, _CmToastRegion_instances, "m", _CmToastRegion_giveFocusBack).call(this) : this.focusToast();
300
+ if (moved)
301
+ e.preventDefault();
210
302
  });
211
303
  }
212
304
  connectedCallback() {
@@ -220,20 +312,59 @@ export class CmToastRegion extends CmLocalizedElement {
220
312
  __classPrivateFieldSet(this, _CmToastRegion_ownLabel, true, "f");
221
313
  }
222
314
  this.addEventListener('cm-dismiss', __classPrivateFieldGet(this, _CmToastRegion_onDismiss, "f"));
315
+ this.addEventListener('focusin', __classPrivateFieldGet(this, _CmToastRegion_onFocusIn, "f"));
316
+ this.addEventListener('keydown', __classPrivateFieldGet(this, _CmToastRegion_onKeyDown, "f"));
317
+ document.addEventListener('keydown', __classPrivateFieldGet(this, _CmToastRegion_onDocKeyDown, "f"));
318
+ }
319
+ disconnectedCallback() {
320
+ super.disconnectedCallback();
321
+ this.removeEventListener('cm-dismiss', __classPrivateFieldGet(this, _CmToastRegion_onDismiss, "f"));
322
+ this.removeEventListener('focusin', __classPrivateFieldGet(this, _CmToastRegion_onFocusIn, "f"));
323
+ this.removeEventListener('keydown', __classPrivateFieldGet(this, _CmToastRegion_onKeyDown, "f"));
324
+ document.removeEventListener('keydown', __classPrivateFieldGet(this, _CmToastRegion_onDocKeyDown, "f"));
223
325
  }
224
- disconnectedCallback() { super.disconnectedCallback(); this.removeEventListener('cm-dismiss', __classPrivateFieldGet(this, _CmToastRegion_onDismiss, "f")); }
225
326
  updated() { if (__classPrivateFieldGet(this, _CmToastRegion_ownLabel, "f"))
226
327
  this.setAttribute('aria-label', this.t('label')); }
328
+ /**
329
+ * Moves focus to the newest open toast with an action (else the newest toast): its action, or its Dismiss button.
330
+ * F6 does this; call it to offer another shortcut. Returns false when there is no toast to focus.
331
+ */
332
+ focusToast() {
333
+ const open = [...this.querySelectorAll(':scope > cm-toast[open]')].reverse();
334
+ const t = open.find((x) => x.actionLabel) ?? open[0];
335
+ const target = t?.shadowRoot?.querySelector('.action') ?? t?.shadowRoot?.querySelector('.close');
336
+ if (!target)
337
+ return false;
338
+ const from = deepActive();
339
+ if (from && !within(this, from))
340
+ __classPrivateFieldSet(this, _CmToastRegion_returnTo, from, "f");
341
+ target.focus();
342
+ return true;
343
+ }
227
344
  /** Adds a toast, removing the oldest ones above `max`. */
228
345
  add(toast) {
229
346
  this.append(toast);
230
347
  const all = [...this.querySelectorAll(':scope > cm-toast')];
231
- all.slice(0, Math.max(0, all.length - Math.max(1, this.max))).forEach((t) => t.remove());
348
+ const gone = all.slice(0, Math.max(0, all.length - Math.max(1, this.max)));
349
+ const hadFocus = gone.some((t) => t.matches(':focus-within'));
350
+ gone.forEach((t) => t.remove());
351
+ if (hadFocus)
352
+ __classPrivateFieldGet(this, _CmToastRegion_instances, "m", _CmToastRegion_giveFocusBack).call(this);
232
353
  return toast;
233
354
  }
234
355
  render() { return html `<slot></slot>`; }
235
356
  }
236
- _CmToastRegion_ownLabel = new WeakMap(), _CmToastRegion_onDismiss = new WeakMap();
357
+ _CmToastRegion_returnTo = new WeakMap(), _CmToastRegion_ownLabel = new WeakMap(), _CmToastRegion_onDismiss = new WeakMap(), _CmToastRegion_onFocusIn = new WeakMap(), _CmToastRegion_onKeyDown = new WeakMap(), _CmToastRegion_onDocKeyDown = new WeakMap(), _CmToastRegion_instances = new WeakSet(), _CmToastRegion_giveFocusBack = function _CmToastRegion_giveFocusBack() {
358
+ const to = __classPrivateFieldGet(this, _CmToastRegion_returnTo, "f");
359
+ __classPrivateFieldSet(this, _CmToastRegion_returnTo, null, "f");
360
+ if (!to?.isConnected)
361
+ return false;
362
+ to.focus();
363
+ // A component host that doesn't pass focus on: focus the first focusable thing inside it.
364
+ if (!within(to, deepActive()))
365
+ to.shadowRoot?.querySelector('button, a[href], input, select, textarea, [tabindex]')?.focus();
366
+ return true;
367
+ };
237
368
  CmToastRegion.properties = { max: { type: Number } };
238
369
  CmToastRegion.styles = [
239
370
  base,
@@ -248,6 +379,8 @@ CmToastRegion.styles = [
248
379
  define('cm-toast-region', CmToastRegion);
249
380
  /**
250
381
  * Shows a toast in the page's toast region (created on first use) and returns it. The message is text, never HTML.
382
+ * The returned toast is the handle: `toast.dismiss()` closes it, and `await toast.closed` gives how it closed
383
+ * (`action`, `timeout`, `close` or `removed`).
251
384
  * @example showToast('Product saved'); showToast('Order archived', { action: { label: 'Undo', onAction: undo } });
252
385
  */
253
386
  export function showToast(message, options = {}) {
@@ -277,3 +410,18 @@ export function showToast(message, options = {}) {
277
410
  }
278
411
  return region.add(toast);
279
412
  }
413
+ /**
414
+ * Undo instead of confirm: runs `doIt` at once, then shows `message` in a toast with Undo, and runs `undoIt` if Undo
415
+ * is pressed. Resolves with how the toast closed once that is known (`action` only after `undoIt` has finished), so
416
+ * a caller can, say, really delete a record only on `timeout`. If `doIt` throws, no toast is shown and the promise rejects.
417
+ * @example await undoable(() => api.archive(lead), () => api.unarchive(lead), { message: 'Lead archived' });
418
+ */
419
+ export async function undoable(doIt, undoIt, options) {
420
+ await doIt();
421
+ const { message, undoLabel, ...rest } = options;
422
+ const label = undoLabel ?? translate('toast', 'undo', undefined, rest.root ?? document.body);
423
+ const reason = await showToast(message, { ...rest, action: { label, onAction: () => { } } }).closed;
424
+ if (reason === 'action')
425
+ await undoIt();
426
+ return reason;
427
+ }