@commmerce/ui 1.2.0 → 1.3.0

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.
@@ -3,7 +3,13 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
3
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
4
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
5
  };
6
- var _CmNestedItem_instances, _a, _CmNestedItem_internals, _CmNestedItem_onHandleKey, _CmNestedItem_onDragStart, _CmNestedItem_onDragOver, _CmNestedItem_clearDrop, _CmNestedItem_onDrop, _CmNestedList_instances, _CmNestedList_id, _CmNestedList_toggle, _CmNestedList_syncSortable;
6
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7
+ if (kind === "m") throw new TypeError("Private method is not writable");
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
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");
10
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
11
+ };
12
+ var _CmNestedItem_instances, _a, _CmNestedItem_internals, _CmNestedItem_peerLists_get, _CmNestedItem_refocus, _CmNestedItem_onHandleKey, _CmNestedItem_onDragStart, _CmNestedItem_pointerDrag, _CmNestedItem_onPointerDown, _CmNestedItem_targetAt, _CmNestedItem_onDragOver, _CmNestedItem_clearDrop, _CmNestedItem_onDrop, _CmNestedList_instances, _CmNestedList_id, _CmNestedList_toggle, _CmNestedList_syncSortable, _CmNestedList_accepts, _CmNestedList_onDragOver, _CmNestedList_onDrop;
7
13
  import { html, css, nothing } from 'lit';
8
14
  import { base, define, nextId } from '../base.js';
9
15
  import { CmLocalizedElement, defineStrings } from '../localize.js';
@@ -12,8 +18,12 @@ const itemStrings = defineStrings('nestedItem', {
12
18
  /** Accessible name of the drag handle, and the keyboard hint read with it. */
13
19
  reorder: 'Reorder {label}',
14
20
  hint: 'Press up or down arrow to move.',
21
+ /** The keyboard hint in a list with a `group`: the arrows also cross into the list before or after. */
22
+ hintGroup: 'Press up or down arrow to move. At either end of the list, the arrow moves it into the list before or after.',
15
23
  /** Announced after a move. */
16
24
  moved: '{label} moved to position {position} of {total}.',
25
+ /** Announced after a move into another list (`group`). */
26
+ movedTo: '{label} moved to {list}, position {position} of {total}.',
17
27
  });
18
28
  const listStrings = defineStrings('nestedList', {
19
29
  /** Accessible name of the show/hide button. */
@@ -27,6 +37,7 @@ const listStrings = defineStrings('nestedList', {
27
37
  * @slot - Child `cm-nested-item`s.
28
38
  * @slot actions - Controls at the end of the row: a badge, a toggle, edit and delete buttons.
29
39
  * @fires cm-reorder - Bubbles from the moved item: `detail: { item, from, to }` (positions among its siblings). Cancelable.
40
+ * @fires cm-move - Bubbles from the item before it moves into another list with the same `group` (since 1.3): `detail: { item, from, to, fromList, toList }`, where `from` is its position in `fromList` and `to` its position in `toList` after the move. Cancelable: the component moves the element unless you call `preventDefault()`.
30
41
  */
31
42
  export class CmNestedItem extends CmLocalizedElement {
32
43
  constructor() {
@@ -40,6 +51,7 @@ export class CmNestedItem extends CmLocalizedElement {
40
51
  this.sortable = false;
41
52
  this._hasChildren = false;
42
53
  _CmNestedItem_internals.set(this, this.attachInternals());
54
+ _CmNestedItem_pointerDrag.set(this, false);
43
55
  __classPrivateFieldGet(this, _CmNestedItem_internals, "f").role = 'listitem';
44
56
  }
45
57
  connectedCallback() {
@@ -48,6 +60,33 @@ export class CmNestedItem extends CmLocalizedElement {
48
60
  if (!this.hasAttribute('role'))
49
61
  this.setAttribute('role', 'listitem');
50
62
  }
63
+ /** The `cm-nested-list` this item is a top-level row of, or null when it is nested in another item. */
64
+ get list() {
65
+ const p = this.parentElement;
66
+ return p?.localName === 'cm-nested-list' ? p : null;
67
+ }
68
+ /**
69
+ * Moves this top-level row into another `cm-nested-list` with the same `group`, at position `to` (default: the
70
+ * end), firing a cancelable `cm-move` first. With its own list it is the same as `moveTo(to)`. Use it for a
71
+ * "Move to…" menu. Returns false if nothing moved. Since 1.3.
72
+ */
73
+ moveToList(list, to) {
74
+ const from = this.list;
75
+ if (!from || !list)
76
+ return false;
77
+ if (list === from)
78
+ return to === undefined ? false : this.moveTo(to);
79
+ if (!from.group || list.group !== from.group)
80
+ return false;
81
+ const targets = list.items;
82
+ const index = Math.max(0, Math.min(targets.length, to ?? targets.length));
83
+ const detail = { item: this, from: from.items.indexOf(this), to: index, fromList: from, toList: list };
84
+ if (!this.dispatchEvent(new CustomEvent('cm-move', { detail, bubbles: true, composed: true, cancelable: true })))
85
+ return false;
86
+ list.insertBefore(this, targets[index] ?? null);
87
+ list.announce(this.t('movedTo', { label: this.label, list: list.heading, position: index + 1, total: targets.length + 1 }));
88
+ return true;
89
+ }
51
90
  /** Sibling `cm-nested-item`s, including this one. */
52
91
  get siblings() {
53
92
  return [...this.parentElement.children].filter((c) => c.localName === 'cm-nested-item');
@@ -76,10 +115,10 @@ export class CmNestedItem extends CmLocalizedElement {
76
115
  ${this.sortable
77
116
  ? html `<button class="handle" type="button" part="handle" draggable="true" aria-label=${this.t('reorder', { label: this.label })}
78
117
  aria-describedby="hint"
79
- @keydown=${__classPrivateFieldGet(this, _CmNestedItem_instances, "m", _CmNestedItem_onHandleKey)} @dragstart=${__classPrivateFieldGet(this, _CmNestedItem_instances, "m", _CmNestedItem_onDragStart)}
80
- @dragend=${() => { this.classList.remove('dragging'); _a.dragged = null; }}><cm-icon name="drag" size="18"></cm-icon></button>`
118
+ @keydown=${__classPrivateFieldGet(this, _CmNestedItem_instances, "m", _CmNestedItem_onHandleKey)} @dragstart=${__classPrivateFieldGet(this, _CmNestedItem_instances, "m", _CmNestedItem_onDragStart)} @pointerdown=${__classPrivateFieldGet(this, _CmNestedItem_instances, "m", _CmNestedItem_onPointerDown)}
119
+ @dragend=${() => { this.classList.remove('dragging'); _a.dragged = null; markDrop(this, null); }}><cm-icon name="drag" size="18"></cm-icon></button>`
81
120
  : nothing}
82
- ${this.sortable ? html `<span class="sr" id="hint">${this.t('hint')}</span>` : nothing}
121
+ ${this.sortable ? html `<span class="sr" id="hint">${this.t(this.list?.group ? 'hintGroup' : 'hint')}</span>` : nothing}
83
122
  <span class="label" part="label">${this.label}</span>
84
123
  <span class="actions" part="actions"><slot name="actions"></slot></span>
85
124
  </div>
@@ -99,8 +138,33 @@ export class CmNestedItem extends CmLocalizedElement {
99
138
  }
100
139
  }
101
140
  }
102
- _a = CmNestedItem, _CmNestedItem_internals = new WeakMap(), _CmNestedItem_instances = new WeakSet(), _CmNestedItem_onHandleKey = function _CmNestedItem_onHandleKey(e) {
141
+ _a = CmNestedItem, _CmNestedItem_internals = new WeakMap(), _CmNestedItem_pointerDrag = new WeakMap(), _CmNestedItem_instances = new WeakSet(), _CmNestedItem_peerLists_get = function _CmNestedItem_peerLists_get() {
142
+ const own = this.list;
143
+ if (!own?.group)
144
+ return [];
145
+ const root = own.getRootNode();
146
+ return [...root.querySelectorAll('cm-nested-list')]
147
+ .filter((l) => l === own || (l.group === own.group && l.sortable && (!l.collapsible || l.open)));
148
+ }, _CmNestedItem_refocus = function _CmNestedItem_refocus() {
149
+ // Moving the row re-inserts it, which drops focus. Restore it at once so a quick second key
150
+ // press (e.g. ↓ then End) still reaches the handle, and again after render as a fallback.
151
+ const refocus = () => this.renderRoot.querySelector('.handle')?.focus();
152
+ refocus();
153
+ requestAnimationFrame(refocus);
154
+ }, _CmNestedItem_onHandleKey = function _CmNestedItem_onHandleKey(e) {
103
155
  const i = this.siblings.indexOf(this);
156
+ // In a list with a `group`, ↑ on the first row and ↓ on the last cross into the list before or after.
157
+ const up = e.key === 'ArrowUp', down = e.key === 'ArrowDown';
158
+ if ((up && i === 0) || (down && i === this.siblings.length - 1)) {
159
+ const lists = __classPrivateFieldGet(this, _CmNestedItem_instances, "a", _CmNestedItem_peerLists_get);
160
+ const next = lists[lists.indexOf(this.list) + (up ? -1 : 1)];
161
+ if (next) {
162
+ e.preventDefault();
163
+ if (this.moveToList(next, up ? next.items.length : 0))
164
+ __classPrivateFieldGet(this, _CmNestedItem_instances, "m", _CmNestedItem_refocus).call(this);
165
+ return;
166
+ }
167
+ }
104
168
  let to;
105
169
  if (e.key === 'ArrowUp')
106
170
  to = i - 1;
@@ -113,20 +177,68 @@ _a = CmNestedItem, _CmNestedItem_internals = new WeakMap(), _CmNestedItem_instan
113
177
  else
114
178
  return;
115
179
  e.preventDefault();
116
- if (this.moveTo(to)) {
117
- // Moving the row re-inserts it, which drops focus. Restore it at once so a quick second key
118
- // press (e.g. ↓ then End) still reaches the handle, and again after render as a fallback.
119
- const refocus = () => this.renderRoot.querySelector('.handle')?.focus();
120
- refocus();
121
- requestAnimationFrame(refocus);
122
- }
180
+ if (this.moveTo(to))
181
+ __classPrivateFieldGet(this, _CmNestedItem_instances, "m", _CmNestedItem_refocus).call(this);
123
182
  }, _CmNestedItem_onDragStart = function _CmNestedItem_onDragStart(e) {
124
183
  e.stopPropagation();
184
+ if (__classPrivateFieldGet(this, _CmNestedItem_pointerDrag, "f")) {
185
+ e.preventDefault();
186
+ return;
187
+ } // a touch drag is already moving the row
125
188
  _a.dragged = this;
126
189
  this.classList.add('dragging');
127
190
  e.dataTransfer?.setData('text/plain', this.label);
128
191
  if (e.dataTransfer)
129
192
  e.dataTransfer.effectAllowed = 'move';
193
+ }, _CmNestedItem_onPointerDown = function _CmNestedItem_onPointerDown(e) {
194
+ if (e.pointerType === 'mouse' || !e.isPrimary)
195
+ return;
196
+ const startY = e.clientY;
197
+ let target = null;
198
+ const move = (ev) => {
199
+ if (ev.pointerId !== e.pointerId)
200
+ return;
201
+ if (!__classPrivateFieldGet(this, _CmNestedItem_pointerDrag, "f")) {
202
+ if (Math.abs(ev.clientY - startY) < 6)
203
+ return;
204
+ __classPrivateFieldSet(this, _CmNestedItem_pointerDrag, true, "f");
205
+ _a.dragged = this;
206
+ this.classList.add('dragging');
207
+ }
208
+ ev.preventDefault();
209
+ target = __classPrivateFieldGet(this, _CmNestedItem_instances, "m", _CmNestedItem_targetAt).call(this, ev.clientX, ev.clientY);
210
+ markDrop(this, target);
211
+ };
212
+ const end = (ev) => {
213
+ if (ev.pointerId !== e.pointerId)
214
+ return;
215
+ document.removeEventListener('pointermove', move, true);
216
+ document.removeEventListener('pointerup', end, true);
217
+ document.removeEventListener('pointercancel', end, true);
218
+ const dragged = __classPrivateFieldGet(this, _CmNestedItem_pointerDrag, "f");
219
+ __classPrivateFieldSet(this, _CmNestedItem_pointerDrag, false, "f");
220
+ _a.dragged = null;
221
+ this.classList.remove('dragging');
222
+ markDrop(this, null);
223
+ if (!dragged || ev.type === 'pointercancel' || !target)
224
+ return;
225
+ if (target.list)
226
+ this.moveToList(target.list, target.index);
227
+ else
228
+ this.moveTo(target.index);
229
+ };
230
+ document.addEventListener('pointermove', move, true);
231
+ document.addEventListener('pointerup', end, true);
232
+ document.addEventListener('pointercancel', end, true);
233
+ }, _CmNestedItem_targetAt = function _CmNestedItem_targetAt(x, y) {
234
+ for (const l of __classPrivateFieldGet(this, _CmNestedItem_instances, "a", _CmNestedItem_peerLists_get)) {
235
+ if (l === this.list)
236
+ continue;
237
+ const r = l.getBoundingClientRect();
238
+ if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom)
239
+ return { list: l, index: indexAt(l.items, this, y) };
240
+ }
241
+ return { index: indexAt(this.siblings, this, y) };
130
242
  }, _CmNestedItem_onDragOver = function _CmNestedItem_onDragOver(e) {
131
243
  const d = _a.dragged;
132
244
  if (!d || d === this || d.parentElement !== this.parentElement)
@@ -177,6 +289,8 @@ CmNestedItem.styles = [
177
289
  color: var(--cm-icon-selected); background: none; border: 0; border-radius: var(--cm-radius-xs); cursor: grab;
178
290
  }
179
291
  .handle:focus-visible { outline: 2px solid var(--cm-border-strong); outline-offset: 2px; }
292
+ /* Touch: a drag that starts on the handle moves the row instead of scrolling the page. */
293
+ .handle { touch-action: none; }
180
294
  .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
181
295
  .children { margin-block: var(--cm-space-10) 0; margin-inline: 50px 0; display: flex; flex-direction: column; gap: var(--cm-space-10); }
182
296
  .children:not(.has) { display: none; }
@@ -189,16 +303,42 @@ CmNestedItem.styles = [
189
303
  ];
190
304
  CmNestedItem.dragged = null;
191
305
  define('cm-nested-item', CmNestedItem);
306
+ /** Position a dragged row would take among `rows` (it is left out) for a pointer at `y`: rows whose middle is above it. */
307
+ function indexAt(rows, dragged, y) {
308
+ return rows.filter((r) => {
309
+ if (r === dragged)
310
+ return false;
311
+ const b = r.getBoundingClientRect();
312
+ return b.top + b.height / 2 < y;
313
+ }).length;
314
+ }
315
+ /** Shows where a dragged row will land (a line before or after a row, or an outline on an empty list); null clears. */
316
+ function markDrop(dragged, target) {
317
+ const root = (dragged.list ?? dragged).getRootNode();
318
+ root.querySelectorAll('cm-nested-item.drop-before, cm-nested-item.drop-after, cm-nested-list.drop-target')
319
+ .forEach((el) => el.classList.remove('drop-before', 'drop-after', 'drop-target'));
320
+ if (!target)
321
+ return;
322
+ const rows = (target.list ? target.list.items : dragged.siblings).filter((r) => r !== dragged);
323
+ if (!rows.length)
324
+ target.list?.classList.add('drop-target');
325
+ else if (target.index < rows.length)
326
+ rows[target.index].classList.add('drop-before');
327
+ else
328
+ rows[rows.length - 1].classList.add('drop-after');
329
+ }
192
330
  /**
193
331
  * A titled group of rows that nest inside each other, such as a navigation menu with links and
194
332
  * sub-links, or categories and sub-categories. The heading sits in a 90px grey bar with its own
195
333
  * actions; rows below are indented one step per level. With `sortable`, each row gets a drag
196
334
  * handle that also works from the keyboard (↑/↓, Home/End). With `collapsible`, the bar gets a
197
- * round button that shows and hides the rows.
335
+ * round button that shows and hides the rows. Give sortable lists the same `group` to let top-level rows move
336
+ * between them, by drag and drop or from the keyboard (since 1.3).
198
337
  * @element cm-nested-list
199
338
  * @slot - `cm-nested-item` rows.
200
339
  * @slot actions - Controls in the heading bar, e.g. an "Add links" button or a toggle.
201
340
  * @fires cm-reorder - When a row is moved. See `cm-nested-item`.
341
+ * @fires cm-move - When a row moves into another list with the same `group`. Fired on the row before it moves, so it bubbles through the list it leaves. See `cm-nested-item`.
202
342
  * @fires cm-toggle - `detail: { open }` when a collapsible list is shown or hidden.
203
343
  */
204
344
  export class CmNestedList extends CmLocalizedElement {
@@ -215,16 +355,33 @@ export class CmNestedList extends CmLocalizedElement {
215
355
  this.collapsible = false;
216
356
  /** Whether the rows are shown when `collapsible`. */
217
357
  this.open = true;
358
+ /**
359
+ * Name shared by sortable lists that accept each other's top-level rows (since 1.3), e.g. every section of a
360
+ * form layout. Rows then move between them by drag and drop (mouse or touch) and from the keyboard: ↑ on the
361
+ * first row or ↓ on the last moves it into the list before or after. The component moves the element and fires
362
+ * a cancelable `cm-move`. An empty list in a group shows a drop area.
363
+ */
364
+ this.group = '';
218
365
  this._msg = '';
366
+ this._empty = false;
219
367
  _CmNestedList_id.set(this, nextId('cm-nl'));
220
368
  }
369
+ /** The top-level `cm-nested-item` rows, in order. */
370
+ get items() {
371
+ return [...this.children].filter((c) => c.localName === 'cm-nested-item');
372
+ }
221
373
  /** Reads a message to screen readers, e.g. after a move. */
222
374
  announce(msg) {
223
375
  this._msg = '';
224
376
  requestAnimationFrame(() => (this._msg = msg));
225
377
  }
378
+ willUpdate() {
379
+ // A list with no rows gets no slotchange, so count them before the first render.
380
+ if (!this.hasUpdated)
381
+ this._empty = !this.items.length;
382
+ }
226
383
  updated(changed) {
227
- if (changed.has('sortable'))
384
+ if (changed.has('sortable') || changed.has('group'))
228
385
  __classPrivateFieldGet(this, _CmNestedList_instances, "m", _CmNestedList_syncSortable).call(this);
229
386
  }
230
387
  render() {
@@ -240,8 +397,9 @@ export class CmNestedList extends CmLocalizedElement {
240
397
  <cm-icon name=${shown ? 'chevron-up' : 'chevron-down'} size="14"></cm-icon></button>`
241
398
  : nothing}
242
399
  </div>
243
- <div class="rows" id="${__classPrivateFieldGet(this, _CmNestedList_id, "f")}-rows" role="list" aria-labelledby="${__classPrivateFieldGet(this, _CmNestedList_id, "f")}-h" ?hidden=${!shown}>
244
- <slot @slotchange=${() => __classPrivateFieldGet(this, _CmNestedList_instances, "m", _CmNestedList_syncSortable).call(this)}></slot>
400
+ <div class="rows ${this.group && this._empty ? 'empty' : ''}" id="${__classPrivateFieldGet(this, _CmNestedList_id, "f")}-rows" role="list" aria-labelledby="${__classPrivateFieldGet(this, _CmNestedList_id, "f")}-h" ?hidden=${!shown}
401
+ @dragover=${__classPrivateFieldGet(this, _CmNestedList_instances, "m", _CmNestedList_onDragOver)} @drop=${__classPrivateFieldGet(this, _CmNestedList_instances, "m", _CmNestedList_onDrop)}>
402
+ <slot @slotchange=${() => { __classPrivateFieldGet(this, _CmNestedList_instances, "m", _CmNestedList_syncSortable).call(this); this._empty = !this.items.length; }}></slot>
245
403
  </div>
246
404
  <span class="sr" role="status">${this._msg}</span>
247
405
  `;
@@ -251,8 +409,25 @@ _CmNestedList_id = new WeakMap(), _CmNestedList_instances = new WeakSet(), _CmNe
251
409
  this.open = !this.open;
252
410
  this.dispatchEvent(new CustomEvent('cm-toggle', { detail: { open: this.open }, bubbles: true, composed: true }));
253
411
  }, _CmNestedList_syncSortable = function _CmNestedList_syncSortable() {
254
- [...this.children].forEach((k) => { if (k.localName === 'cm-nested-item')
255
- k.sortable = this.sortable; });
412
+ const rows = this.items;
413
+ rows.forEach((k) => { k.sortable = this.sortable; k.requestUpdate(); });
414
+ }, _CmNestedList_accepts = function _CmNestedList_accepts(d) {
415
+ const from = d?.list;
416
+ return !!d && !!from && from !== this && !!this.group && from.group === this.group && this.sortable && (!this.collapsible || this.open);
417
+ }, _CmNestedList_onDragOver = function _CmNestedList_onDragOver(e) {
418
+ const d = CmNestedItem.dragged;
419
+ if (!__classPrivateFieldGet(this, _CmNestedList_instances, "m", _CmNestedList_accepts).call(this, d))
420
+ return;
421
+ e.preventDefault();
422
+ markDrop(d, { list: this, index: indexAt(this.items, d, e.clientY) });
423
+ }, _CmNestedList_onDrop = function _CmNestedList_onDrop(e) {
424
+ const d = CmNestedItem.dragged;
425
+ if (!__classPrivateFieldGet(this, _CmNestedList_instances, "m", _CmNestedList_accepts).call(this, d))
426
+ return;
427
+ e.preventDefault();
428
+ const index = indexAt(this.items, d, e.clientY);
429
+ markDrop(d, null);
430
+ d.moveToList(this, index);
256
431
  };
257
432
  CmNestedList.properties = {
258
433
  heading: {},
@@ -260,7 +435,9 @@ CmNestedList.properties = {
260
435
  sortable: { type: Boolean, reflect: true },
261
436
  collapsible: { type: Boolean, reflect: true },
262
437
  open: { type: Boolean, reflect: true },
438
+ group: { reflect: true },
263
439
  _msg: { state: true },
440
+ _empty: { state: true },
264
441
  };
265
442
  CmNestedList.styles = [
266
443
  base,
@@ -280,6 +457,8 @@ CmNestedList.styles = [
280
457
  .toggle:focus-visible { outline: 2px solid var(--cm-border-strong); outline-offset: 2px; }
281
458
  .rows { display: flex; flex-direction: column; gap: var(--cm-space-10); margin-block: var(--cm-space-15) 0; margin-inline: 50px 0; }
282
459
  .rows[hidden] { display: none; }
460
+ .rows.empty { min-height: 60px; border: var(--cm-border-1) dashed var(--cm-border-default); border-radius: var(--cm-radius-md); }
461
+ :host(.drop-target) .rows.empty { border: 2px solid var(--cm-border-strong); }
283
462
  .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
284
463
  @media (max-width: 640px) {
285
464
  .bar { min-height: 60px; padding: 0 var(--cm-space-10); gap: var(--cm-space-10); }
@@ -9,14 +9,23 @@ declare module '../localize.js' {
9
9
  optionGroup: typeof strings;
10
10
  }
11
11
  }
12
+ /** An option of `cm-option-group`. */
13
+ export interface OptionGroupOption extends SelectOption {
14
+ /**
15
+ * Colours the option by the outcome it records, as `cm-button`'s `tone`: `success` (green, "Signed up") or
16
+ * `critical` (red, "Not interested"). The label still carries the meaning. Since 1.3.
17
+ */
18
+ tone?: 'critical' | 'success';
19
+ }
12
20
  /**
13
21
  * A row of outlined buttons where exactly one is selected (black), used to switch a form between
14
22
  * types, such as offer types. Behaves like a native radio group: one tab stop, arrow keys move and
15
23
  * select, and the form receives the selected value.
16
24
  *
17
- * Options come from `<option>` children or the `options` property.
25
+ * Options come from `<option>` children or the `options` property. A `tone` on an option (`<option tone="success">`
26
+ * or `{ tone }`, since 1.3) colours it by the outcome it records: outlined in the tone, filled in it when selected.
18
27
  * @element cm-option-group
19
- * @slot - `<option value="…">Label</option>` elements. `disabled` and `selected` are honoured.
28
+ * @slot - `<option value="…">Label</option>` elements. `disabled`, `selected` and `tone` (`success`, `critical`) are honoured.
20
29
  * @fires change - When the merchant picks a different option.
21
30
  * @fires input - Same moment as `change`.
22
31
  */
@@ -50,13 +59,13 @@ export declare class CmOptionGroup extends CmLocalizedElement {
50
59
  name: string;
51
60
  /** Value of the selected option; empty when nothing is selected. */
52
61
  value: string;
53
- /** Options as strings or `{ value, label, disabled }`. Used instead of `<option>` children when set. */
54
- options: Array<string | SelectOption>;
62
+ /** Options as strings or `{ value, label, disabled, tone }`. Used instead of `<option>` children when set. */
63
+ options: Array<string | OptionGroupOption>;
55
64
  /** The form will not submit until an option is chosen. */
56
65
  required: boolean;
57
66
  /** Blocks every option. Also set by a disabled `<fieldset>`. */
58
67
  disabled: boolean;
59
- _slotted: SelectOption[];
68
+ _slotted: OptionGroupOption[];
60
69
  static styles: import("lit").CSSResult[];
61
70
  connectedCallback(): void;
62
71
  disconnectedCallback(): void;
@@ -71,7 +80,7 @@ export declare class CmOptionGroup extends CmLocalizedElement {
71
80
  /** Focuses the selected option, or the first one. */
72
81
  focus(options?: FocusOptions): void;
73
82
  /** The options in use, normalised. */
74
- get items(): SelectOption[];
83
+ get items(): OptionGroupOption[];
75
84
  firstUpdated(): void;
76
85
  updated(): void;
77
86
  render(): import("lit-html").TemplateResult<1>;
@@ -22,9 +22,10 @@ const strings = defineStrings('optionGroup', {
22
22
  * types, such as offer types. Behaves like a native radio group: one tab stop, arrow keys move and
23
23
  * select, and the form receives the selected value.
24
24
  *
25
- * Options come from `<option>` children or the `options` property.
25
+ * Options come from `<option>` children or the `options` property. A `tone` on an option (`<option tone="success">`
26
+ * or `{ tone }`, since 1.3) colours it by the outcome it records: outlined in the tone, filled in it when selected.
26
27
  * @element cm-option-group
27
- * @slot - `<option value="…">Label</option>` elements. `disabled` and `selected` are honoured.
28
+ * @slot - `<option value="…">Label</option>` elements. `disabled`, `selected` and `tone` (`success`, `critical`) are honoured.
28
29
  * @fires change - When the merchant picks a different option.
29
30
  * @fires input - Same moment as `change`.
30
31
  */
@@ -38,7 +39,7 @@ export class CmOptionGroup extends CmLocalizedElement {
38
39
  this.name = '';
39
40
  /** Value of the selected option; empty when nothing is selected. */
40
41
  this.value = '';
41
- /** Options as strings or `{ value, label, disabled }`. Used instead of `<option>` children when set. */
42
+ /** Options as strings or `{ value, label, disabled, tone }`. Used instead of `<option>` children when set. */
42
43
  this.options = [];
43
44
  /** The form will not submit until an option is chosen. */
44
45
  this.required = false;
@@ -53,7 +54,7 @@ export class CmOptionGroup extends CmLocalizedElement {
53
54
  connectedCallback() {
54
55
  super.connectedCallback();
55
56
  __classPrivateFieldGet(this, _CmOptionGroup_instances, "m", _CmOptionGroup_readChildren).call(this);
56
- __classPrivateFieldGet(this, _CmOptionGroup_observer, "f").observe(this, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['value', 'label', 'disabled', 'selected'] });
57
+ __classPrivateFieldGet(this, _CmOptionGroup_observer, "f").observe(this, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['value', 'label', 'disabled', 'selected', 'tone'] });
57
58
  }
58
59
  disconnectedCallback() {
59
60
  super.disconnectedCallback();
@@ -96,7 +97,7 @@ export class CmOptionGroup extends CmLocalizedElement {
96
97
  <div class="options" part="options" role="radiogroup"
97
98
  aria-labelledby=${this.label ? `${__classPrivateFieldGet(this, _CmOptionGroup_id, "f")}-l` : nothing} aria-label=${!this.label && hostLabel ? hostLabel : nothing}
98
99
  aria-required=${this.required ? 'true' : nothing}>
99
- ${items.map((o, i) => html `<button type="button" role="radio" part="option" aria-checked=${o.value === this.value ? 'true' : 'false'}
100
+ ${items.map((o, i) => html `<button type="button" role="radio" part="option" class=${o.tone === 'critical' || o.tone === 'success' ? `tone-${o.tone}` : nothing} aria-checked=${o.value === this.value ? 'true' : 'false'}
100
101
  tabindex=${i === stop ? '0' : '-1'} ?disabled=${this.disabled || !!o.disabled}
101
102
  @click=${() => __classPrivateFieldGet(this, _CmOptionGroup_instances, "m", _CmOptionGroup_select).call(this, i)} @keydown=${(e) => __classPrivateFieldGet(this, _CmOptionGroup_instances, "m", _CmOptionGroup_onKeyDown).call(this, e, i)}>${o.label}</button>`)}
102
103
  </div>
@@ -106,7 +107,13 @@ export class CmOptionGroup extends CmLocalizedElement {
106
107
  }
107
108
  _CmOptionGroup_internals = new WeakMap(), _CmOptionGroup_id = new WeakMap(), _CmOptionGroup_defaultValue = new WeakMap(), _CmOptionGroup_observer = new WeakMap(), _CmOptionGroup_instances = new WeakSet(), _CmOptionGroup_readChildren = function _CmOptionGroup_readChildren() {
108
109
  const opts = [...this.querySelectorAll('option')];
109
- this._slotted = opts.map((o) => ({ value: o.value, label: o.label || o.textContent.trim(), disabled: o.disabled }));
110
+ this._slotted = opts.map((o) => {
111
+ const opt = { value: o.value, label: o.label || o.textContent.trim(), disabled: o.disabled };
112
+ const tone = o.getAttribute('tone');
113
+ if (tone === 'critical' || tone === 'success')
114
+ opt.tone = tone;
115
+ return opt;
116
+ });
110
117
  if (!this.hasUpdated && !this.value) {
111
118
  this.value = opts.find((o) => o.hasAttribute('selected'))?.value ?? '';
112
119
  __classPrivateFieldSet(this, _CmOptionGroup_defaultValue, this.value, "f");
@@ -167,6 +174,18 @@ CmOptionGroup.styles = [
167
174
  button:focus-visible { outline: 2px solid var(--cm-border-strong); outline-offset: 2px; }
168
175
  button:disabled { background: var(--cm-bg-input-filled); color: var(--cm-text-secondary); border-color: var(--cm-border-default); cursor: not-allowed; }
169
176
  button[aria-checked='true']:disabled { background: var(--cm-action-disabled); color: var(--cm-action-disabled-text); }
177
+ /* Tones (1.3), the same token pairs as cm-button's tones (packages/tokens/scripts/contrast.mjs). Unselected: tone
178
+ text and outline on bg-surface (text-critical on bg-hover is under 4.5:1 in dark), hover tints it. Selected:
179
+ filled with the tone's text colour under action-primary-text; hover darkens it towards text-default. Selected
180
+ and unselected differ by fill, not only hue; disabled options look like any disabled option. */
181
+ button.tone-critical:not(:disabled) { --_tone: var(--cm-text-critical); --_edge: var(--cm-border-critical); --_tint: var(--cm-bg-critical); }
182
+ button.tone-success:not(:disabled) { --_tone: var(--cm-text-success); --_edge: var(--cm-text-success); --_tint: var(--cm-bg-success-soft); }
183
+ button[class^='tone-']:not(:disabled) { background: var(--cm-bg-surface); color: var(--_tone); border-color: var(--_edge); }
184
+ button[class^='tone-']:not(:disabled):hover { background: linear-gradient(var(--_tint), var(--_tint)) var(--cm-bg-surface); }
185
+ button[class^='tone-'][aria-checked='true']:not(:disabled) { background: var(--_tone); border-color: var(--_tone); color: var(--cm-action-primary-text); }
186
+ button[class^='tone-'][aria-checked='true']:not(:disabled):hover {
187
+ background: color-mix(in srgb, var(--_tone) 80%, var(--cm-text-default)); border-color: color-mix(in srgb, var(--_tone) 80%, var(--cm-text-default));
188
+ }
170
189
  slot { display: none; }
171
190
  @media (max-width: 640px) {
172
191
  .label { font-size: var(--cm-type-heading-sm-resp-size); }
@@ -3,6 +3,8 @@ import './icon.js';
3
3
  declare const strings: {
4
4
  /** Validation message when `required` and nothing is chosen. */
5
5
  required: string;
6
+ /** The chosen option in the box with `show-group`: "Lead: Company". */
7
+ grouped: string;
6
8
  };
7
9
  declare module '../localize.js' {
8
10
  interface CmStrings {
@@ -13,6 +15,11 @@ export interface SelectOption {
13
15
  value: string;
14
16
  label: string;
15
17
  disabled?: boolean;
18
+ /**
19
+ * Heading of the group the option belongs to ("Lead"), like a native `<optgroup label>`. Options of the same group
20
+ * are shown together under the heading, in the order the groups first appear. Since 1.3.
21
+ */
22
+ group?: string;
16
23
  }
17
24
  /**
18
25
  * Dropdown field: a labelled box that opens a list of options and shows the chosen one.
@@ -20,8 +27,9 @@ export interface SelectOption {
20
27
  * design; it keeps native-select keyboard behaviour. Participates in native forms.
21
28
  *
22
29
  * Options come from `<option>` children (easy in plain HTML, PHP and EJS) or the `options` property.
30
+ * Group them under headings with `<optgroup label="…">` or a `group` on each option (since 1.3).
23
31
  * @element cm-select
24
- * @slot - `<option value="…">Label</option>` elements. `disabled` and `selected` are honoured.
32
+ * @slot - `<option value="…">Label</option>` elements, optionally inside `<optgroup label="…">`. `disabled` (also on an optgroup) and `selected` are honoured.
25
33
  * @fires change - When the merchant picks a different option.
26
34
  * @fires input - Same moment as `change`.
27
35
  */
@@ -62,6 +70,10 @@ export declare class CmSelect extends CmLocalizedElement {
62
70
  type: BooleanConstructor;
63
71
  reflect: boolean;
64
72
  };
73
+ showGroup: {
74
+ type: BooleanConstructor;
75
+ attribute: string;
76
+ };
65
77
  _active: {
66
78
  state: boolean;
67
79
  };
@@ -81,7 +93,7 @@ export declare class CmSelect extends CmLocalizedElement {
81
93
  value: string;
82
94
  /** Shown while nothing is chosen, e.g. "Select customer". */
83
95
  placeholder: string;
84
- /** Options as strings or `{ value, label, disabled }`. Used instead of `<option>` children when set. */
96
+ /** Options as strings or `{ value, label, disabled, group }`. Used instead of `<option>` children when set. */
85
97
  options: Array<string | SelectOption>;
86
98
  /** The form will not submit until an option is chosen. */
87
99
  required: boolean;
@@ -89,6 +101,11 @@ export declare class CmSelect extends CmLocalizedElement {
89
101
  disabled: boolean;
90
102
  /** Whether the list is showing. */
91
103
  open: boolean;
104
+ /**
105
+ * Shows the chosen option's group before its label in the box ("Lead: Company"), for grouped lists where labels
106
+ * repeat across groups. The list itself always shows the bare label under its group heading. Since 1.3.
107
+ */
108
+ showGroup: boolean;
92
109
  _active: number;
93
110
  _slotted: SelectOption[];
94
111
  static styles: import("lit").CSSResult[];
@@ -102,7 +119,7 @@ export declare class CmSelect extends CmLocalizedElement {
102
119
  formResetCallback(): void;
103
120
  formDisabledCallback(d: boolean): void;
104
121
  formStateRestoreCallback(state: string): void;
105
- /** The options in use, normalised. */
122
+ /** The options in use, normalised, in the order shown (options of a group together). */
106
123
  get items(): SelectOption[];
107
124
  firstUpdated(): void;
108
125
  updated(changed: Map<string, unknown>): void;