@commmerce/ui 1.2.0 → 1.4.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.
@@ -9,14 +9,17 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
9
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
10
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
11
11
  };
12
- var _CmSelect_instances, _CmSelect_internals, _CmSelect_id, _CmSelect_defaultValue, _CmSelect_typed, _CmSelect_typedAt, _CmSelect_observer, _CmSelect_readChildren, _CmSelect_enabledIndexes, _CmSelect_show, _CmSelect_hide, _CmSelect_commit, _CmSelect_move, _CmSelect_typeahead, _CmSelect_onKeyDown, _CmSelect_onOutside, _CmSelect_onBoxClick, _CmSelect_focusBox;
12
+ var _CmSelect_instances, _CmSelect_internals, _CmSelect_id, _CmSelect_defaultValue, _CmSelect_typed, _CmSelect_typedAt, _CmSelect_observer, _CmSelect_readChildren, _CmSelect_enabledIndexes, _CmSelect_show, _CmSelect_hide, _CmSelect_commit, _CmSelect_move, _CmSelect_typeahead, _CmSelect_onKeyDown, _CmSelect_onOutside, _CmSelect_onBoxClick, _CmSelect_display, _CmSelect_focusBox;
13
13
  import { LitElement, html, css, nothing } from 'lit';
14
14
  import { base, define, nextId } from '../base.js';
15
15
  import { CmLocalizedElement, defineStrings } from '../localize.js';
16
+ import { groupStyles, sortByGroup, groupRuns } from '../popover.js';
16
17
  import './icon.js';
17
18
  const strings = defineStrings('select', {
18
19
  /** Validation message when `required` and nothing is chosen. */
19
20
  required: 'Please select an item in the list.',
21
+ /** The chosen option in the box with `show-group`: "Lead: Company". */
22
+ grouped: '{group}: {label}',
20
23
  });
21
24
  /**
22
25
  * Dropdown field: a labelled box that opens a list of options and shows the chosen one.
@@ -24,8 +27,9 @@ const strings = defineStrings('select', {
24
27
  * design; it keeps native-select keyboard behaviour. Participates in native forms.
25
28
  *
26
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).
27
31
  * @element cm-select
28
- * @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.
29
33
  * @fires change - When the merchant picks a different option.
30
34
  * @fires input - Same moment as `change`.
31
35
  */
@@ -45,7 +49,7 @@ export class CmSelect extends CmLocalizedElement {
45
49
  this.value = '';
46
50
  /** Shown while nothing is chosen, e.g. "Select customer". */
47
51
  this.placeholder = '';
48
- /** Options as strings or `{ value, label, disabled }`. Used instead of `<option>` children when set. */
52
+ /** Options as strings or `{ value, label, disabled, group }`. Used instead of `<option>` children when set. */
49
53
  this.options = [];
50
54
  /** The form will not submit until an option is chosen. */
51
55
  this.required = false;
@@ -53,6 +57,11 @@ export class CmSelect extends CmLocalizedElement {
53
57
  this.disabled = false;
54
58
  /** Whether the list is showing. */
55
59
  this.open = false;
60
+ /**
61
+ * Shows the chosen option's group before its label in the box ("Lead: Company"), for grouped lists where labels
62
+ * repeat across groups. The list itself always shows the bare label under its group heading. Since 1.3.
63
+ */
64
+ this.showGroup = false;
56
65
  this._active = -1;
57
66
  this._slotted = [];
58
67
  _CmSelect_internals.set(this, this.attachInternals());
@@ -178,11 +187,11 @@ export class CmSelect extends CmLocalizedElement {
178
187
  formDisabledCallback(d) { this.disabled = d; if (d)
179
188
  this.open = false; }
180
189
  formStateRestoreCallback(state) { this.value = state; }
181
- /** The options in use, normalised. */
190
+ /** The options in use, normalised, in the order shown (options of a group together). */
182
191
  get items() {
183
192
  if (!this.options.length)
184
- return this._slotted;
185
- return this.options.map((o) => (typeof o === 'string' ? { value: o, label: o } : o));
193
+ return sortByGroup(this._slotted);
194
+ return sortByGroup(this.options.map((o) => (typeof o === 'string' ? { value: o, label: o } : o)));
186
195
  }
187
196
  firstUpdated() { __classPrivateFieldSet(this, _CmSelect_defaultValue, __classPrivateFieldGet(this, _CmSelect_defaultValue, "f") || this.value, "f"); }
188
197
  updated(changed) {
@@ -203,6 +212,9 @@ export class CmSelect extends CmLocalizedElement {
203
212
  const current = items.find((o) => o.value === this.value);
204
213
  const described = [this.error && `${__classPrivateFieldGet(this, _CmSelect_id, "f")}-err`, this.helpText && `${__classPrivateFieldGet(this, _CmSelect_id, "f")}-help`].filter(Boolean).join(' ');
205
214
  const hostLabel = this.getAttribute('aria-label');
215
+ const option = (o, i) => html `<li role="option" id="${__classPrivateFieldGet(this, _CmSelect_id, "f")}-o${i}" class=${i === this._active ? 'active' : ''}
216
+ aria-selected=${o.value === this.value ? 'true' : 'false'} aria-disabled=${o.disabled ? 'true' : nothing}
217
+ @pointerenter=${() => !o.disabled && (this._active = i)} @click=${() => __classPrivateFieldGet(this, _CmSelect_instances, "m", _CmSelect_commit).call(this, i)}>${o.label}</li>`;
206
218
  return html `<div class="field">
207
219
  ${this.label
208
220
  ? html `<span class="label" id="${__classPrivateFieldGet(this, _CmSelect_id, "f")}-l" part="label" @click=${__classPrivateFieldGet(this, _CmSelect_focusBox, "f")}>${this.label}${this.required ? html `<span class="req" aria-hidden="true">*</span>` : nothing}</span>`
@@ -216,15 +228,16 @@ export class CmSelect extends CmLocalizedElement {
216
228
  aria-required=${this.required ? 'true' : nothing} aria-invalid=${this.error ? 'true' : nothing}
217
229
  aria-disabled=${this.disabled ? 'true' : nothing} aria-describedby=${described || nothing}
218
230
  @click=${__classPrivateFieldGet(this, _CmSelect_onBoxClick, "f")} @keydown=${__classPrivateFieldGet(this, _CmSelect_onKeyDown, "f")} @blur=${() => __classPrivateFieldGet(this, _CmSelect_instances, "m", _CmSelect_hide).call(this)}>
219
- <span class="text ${current ? '' : 'placeholder'}" id="${__classPrivateFieldGet(this, _CmSelect_id, "f")}-v">${current ? current.label : this.placeholder}</span>
231
+ <span class="text ${current ? '' : 'placeholder'}" id="${__classPrivateFieldGet(this, _CmSelect_id, "f")}-v">${current ? __classPrivateFieldGet(this, _CmSelect_instances, "m", _CmSelect_display).call(this, current) : this.placeholder}</span>
220
232
  <cm-icon class="chev" name="chevron-down" size="16"></cm-icon>
221
233
  </div>
222
234
  <ul role="listbox" id="${__classPrivateFieldGet(this, _CmSelect_id, "f")}-list" part="listbox" tabindex="-1" aria-labelledby=${this.label ? `${__classPrivateFieldGet(this, _CmSelect_id, "f")}-l` : nothing}
223
235
  aria-label=${!this.label && hostLabel ? hostLabel : nothing} ?hidden=${!this.open}
224
236
  @pointerdown=${(e) => e.preventDefault()}>
225
- ${items.map((o, i) => html `<li role="option" id="${__classPrivateFieldGet(this, _CmSelect_id, "f")}-o${i}" class=${i === this._active ? 'active' : ''}
226
- aria-selected=${o.value === this.value ? 'true' : 'false'} aria-disabled=${o.disabled ? 'true' : nothing}
227
- @pointerenter=${() => !o.disabled && (this._active = i)} @click=${() => __classPrivateFieldGet(this, _CmSelect_instances, "m", _CmSelect_commit).call(this, i)}>${o.label}</li>`)}
237
+ ${groupRuns(items).map((run, gi) => run.group
238
+ ? html `<li role="group" aria-labelledby="${__classPrivateFieldGet(this, _CmSelect_id, "f")}-g${gi}"><div role="presentation" class="gh" id="${__classPrivateFieldGet(this, _CmSelect_id, "f")}-g${gi}">${run.group}</div>
239
+ <ul role="none" class="gopts">${run.rows.map(({ row, index }) => option(row, index))}</ul></li>`
240
+ : run.rows.map(({ row, index }) => option(row, index)))}
228
241
  </ul>
229
242
  </div>
230
243
  ${this.error ? html `<p class="error" id="${__classPrivateFieldGet(this, _CmSelect_id, "f")}-err" role="alert">${this.error}</p>` : nothing}
@@ -235,7 +248,13 @@ export class CmSelect extends CmLocalizedElement {
235
248
  }
236
249
  _CmSelect_internals = new WeakMap(), _CmSelect_id = new WeakMap(), _CmSelect_defaultValue = new WeakMap(), _CmSelect_typed = new WeakMap(), _CmSelect_typedAt = new WeakMap(), _CmSelect_observer = new WeakMap(), _CmSelect_onKeyDown = new WeakMap(), _CmSelect_onOutside = new WeakMap(), _CmSelect_onBoxClick = new WeakMap(), _CmSelect_focusBox = new WeakMap(), _CmSelect_instances = new WeakSet(), _CmSelect_readChildren = function _CmSelect_readChildren() {
237
250
  const opts = [...this.querySelectorAll('option')];
238
- this._slotted = opts.map((o) => ({ value: o.value, label: o.label || o.textContent.trim(), disabled: o.disabled }));
251
+ this._slotted = opts.map((o) => {
252
+ const g = o.parentElement?.localName === 'optgroup' ? o.parentElement : null;
253
+ const opt = { value: o.value, label: o.label || o.textContent.trim(), disabled: o.disabled || !!g?.disabled };
254
+ if (g?.label)
255
+ opt.group = g.label;
256
+ return opt;
257
+ });
239
258
  if (!this.hasUpdated && !this.value) {
240
259
  this.value = opts.find((o) => o.hasAttribute('selected'))?.value ?? '';
241
260
  __classPrivateFieldSet(this, _CmSelect_defaultValue, this.value, "f");
@@ -282,6 +301,8 @@ _CmSelect_internals = new WeakMap(), _CmSelect_id = new WeakMap(), _CmSelect_def
282
301
  return i;
283
302
  }
284
303
  return -1;
304
+ }, _CmSelect_display = function _CmSelect_display(o) {
305
+ return this.showGroup && o.group ? this.t('grouped', { group: o.group, label: o.label }) : o.label;
285
306
  };
286
307
  CmSelect.formAssociated = true;
287
308
  CmSelect.shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };
@@ -296,11 +317,13 @@ CmSelect.properties = {
296
317
  required: { type: Boolean, reflect: true },
297
318
  disabled: { type: Boolean, reflect: true },
298
319
  open: { type: Boolean, reflect: true },
320
+ showGroup: { type: Boolean, attribute: 'show-group' },
299
321
  _active: { state: true },
300
322
  _slotted: { state: true },
301
323
  };
302
324
  CmSelect.styles = [
303
325
  base,
326
+ groupStyles,
304
327
  css `
305
328
  :host { display: block; position: relative; }
306
329
  .field { display: flex; flex-direction: column; gap: var(--cm-space-10); }
@@ -333,6 +356,7 @@ CmSelect.styles = [
333
356
  [role='option'][aria-selected='true'] { background: var(--cm-action-primary); color: var(--cm-action-primary-text); }
334
357
  [role='option'][aria-selected='true'].active { background: var(--cm-action-primary-hover); }
335
358
  [role='option'][aria-disabled='true'] { color: var(--cm-text-secondary); cursor: not-allowed; }
359
+ [role='group'] { display: block; }
336
360
  .help, .error { margin: 0; font-size: 12px; color: var(--cm-text-tertiary); }
337
361
  .error { color: var(--cm-text-critical); }
338
362
  slot { display: none; }
@@ -0,0 +1,153 @@
1
+ import { CmLocalizedElement } from '../localize.js';
2
+ declare const strings: {
3
+ /** Name of the Draw / Type tab list when the field has no label. */
4
+ modes: string;
5
+ /** The two tabs. */
6
+ draw: string;
7
+ type: string;
8
+ /** Accessible name of the drawing area, and the same once something is drawn. */
9
+ pad: string;
10
+ padSigned: string;
11
+ /** Read with the drawing area: how to draw, and the keyboard alternative. */
12
+ instructions: string;
13
+ /** Hint above the line while nothing is drawn. */
14
+ signHere: string;
15
+ /** Accessible name and placeholder of the box in Type mode. */
16
+ typeLabel: string;
17
+ typePlaceholder: string;
18
+ /** Undo and Clear buttons: visible text and accessible names. */
19
+ undo: string;
20
+ undoLabel: string;
21
+ clear: string;
22
+ clearLabel: string;
23
+ /** Announced after Clear and Undo. */
24
+ cleared: string;
25
+ undone: string;
26
+ /** Validation message when `required` and nothing is signed. */
27
+ required: string;
28
+ };
29
+ declare module '../localize.js' {
30
+ interface CmStrings {
31
+ signatureField: typeof strings;
32
+ }
33
+ }
34
+ /**
35
+ * Signature field: sign by drawing with a mouse, finger or pen, or by typing a name that is shown in a handwriting
36
+ * font. Gives a PNG of the signature, cropped to the ink, as a data URL (`value`, `toDataURL()`) or a Blob
37
+ * (`toBlob()`). Participates in native forms: submits the data URL under `name`; `required` blocks submission
38
+ * until something is signed. For e-sign screens ("Sign now") and signing pages.
39
+ *
40
+ * Load `@commmerce/tokens/fonts.css` (the hosted build's fonts.css) for the typed signature's font, Dancing Script;
41
+ * without it, typed signatures use the system's cursive font.
42
+ * @element cm-signature-field
43
+ * @fires cm-change - After a stroke is finished, Undo, Clear, a switch between Draw and Type, or typing stops for 400ms. `detail`: `{ value, empty, mode }`. A plain `change` event (no detail) follows it, for code that treats every form field alike.
44
+ * @csspart label - The label.
45
+ * @csspart tabs - The Draw / Type tab list.
46
+ * @csspart pad - The signing area (both modes).
47
+ * @csspart canvas - The drawing canvas.
48
+ * @csspart input - The text box in Type mode.
49
+ * @csspart undo - The Undo button (Draw mode).
50
+ * @csspart clear - The Clear button.
51
+ * @cssprop --cm-signature-font - Font of typed signatures. Default: Dancing Script, then cursive system fonts.
52
+ */
53
+ export declare class CmSignatureField extends CmLocalizedElement {
54
+ #private;
55
+ static formAssociated: boolean;
56
+ static shadowRootOptions: {
57
+ delegatesFocus: boolean;
58
+ mode: ShadowRootMode;
59
+ serializable?: boolean;
60
+ slotAssignment?: SlotAssignmentMode;
61
+ };
62
+ static properties: {
63
+ label: {};
64
+ hint: {};
65
+ helpText: {
66
+ attribute: string;
67
+ };
68
+ error: {
69
+ reflect: boolean;
70
+ };
71
+ name: {
72
+ reflect: boolean;
73
+ };
74
+ value: {};
75
+ mode: {
76
+ reflect: boolean;
77
+ };
78
+ typedName: {
79
+ attribute: string;
80
+ };
81
+ required: {
82
+ type: BooleanConstructor;
83
+ reflect: boolean;
84
+ };
85
+ disabled: {
86
+ type: BooleanConstructor;
87
+ reflect: boolean;
88
+ };
89
+ _announce: {
90
+ state: boolean;
91
+ };
92
+ };
93
+ /** Visible label above the field, e.g. "Your signature". Without one, give the element an `aria-label`. */
94
+ label: string;
95
+ /** Lowercase bracketed note after the label. */
96
+ hint: string;
97
+ /** One sentence under the field in text-tertiary, e.g. what the signer agrees to. */
98
+ helpText: string;
99
+ /** Error message from your own validation; turns the pad's border critical and is announced. */
100
+ error: string;
101
+ /** Form field name. */
102
+ name: string;
103
+ /**
104
+ * The signature as a PNG data URL (`data:image/png;base64,…`), cropped to the ink, or empty when nothing is
105
+ * signed. Updated after every stroke and keystroke. Set it to a PNG or SVG data URL (or any image URL the page
106
+ * may read) to show a saved signature in Draw mode; set it to `''` to clear both modes.
107
+ */
108
+ value: string;
109
+ /** The selected tab: `draw` (pointer, touch, pen) or `type` (keyboard). Each keeps its own signature. */
110
+ mode: 'draw' | 'type';
111
+ /** The name typed in Type mode. Set it to prefill the box with the signer's name. */
112
+ typedName: string;
113
+ /** Shows a red asterisk and blocks form submission until something is signed. */
114
+ required: boolean;
115
+ /** Blocks interaction. Also set by a disabled `<fieldset>`. */
116
+ disabled: boolean;
117
+ /** @internal Text in the polite status region. */
118
+ _announce: string;
119
+ static styles: import("lit").CSSResult[];
120
+ connectedCallback(): void;
121
+ disconnectedCallback(): void;
122
+ get form(): HTMLFormElement | null;
123
+ get validity(): ValidityState;
124
+ get validationMessage(): string;
125
+ checkValidity(): boolean;
126
+ reportValidity(): boolean;
127
+ formResetCallback(): void;
128
+ formDisabledCallback(d: boolean): void;
129
+ formStateRestoreCallback(state: string): void;
130
+ /** True when the current mode has nothing signed: no strokes (or saved image) in Draw, no text in Type. */
131
+ get empty(): boolean;
132
+ /**
133
+ * The signature as a PNG data URL: black ink on transparent at 2x the pad's size, cropped to the ink with 8px
134
+ * (16 image pixels) around it. Empty string when nothing is signed.
135
+ */
136
+ toDataURL(): string;
137
+ /** The same PNG as `toDataURL()` as a Blob, for uploading. `null` when nothing is signed. */
138
+ toBlob(): Promise<Blob | null>;
139
+ /** Removes the current mode's signature (Draw: every stroke and any saved image; Type: the text). */
140
+ clear(): void;
141
+ /** Removes the last stroke in Draw mode (then the saved image, if one was loaded). */
142
+ undo(): void;
143
+ willUpdate(changed: Map<string, unknown>): void;
144
+ firstUpdated(): void;
145
+ updated(changed: Map<string, unknown>): void;
146
+ render(): import("lit-html").TemplateResult<1>;
147
+ }
148
+ declare global {
149
+ interface HTMLElementTagNameMap {
150
+ 'cm-signature-field': CmSignatureField;
151
+ }
152
+ }
153
+ export {};