@commmerce/ui 1.0.0-rc.3 → 1.0.0-rc.5

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 (101) hide show
  1. package/README.md +1 -1
  2. package/dist/base.d.ts +5 -0
  3. package/dist/base.js +10 -0
  4. package/dist/calendar.d.ts +95 -0
  5. package/dist/calendar.js +280 -0
  6. package/dist/cdn.js +721 -477
  7. package/dist/components/accordion.js +2 -2
  8. package/dist/components/action-bar.d.ts +12 -2
  9. package/dist/components/action-bar.js +10 -5
  10. package/dist/components/action-menu.d.ts +17 -4
  11. package/dist/components/action-menu.js +8 -5
  12. package/dist/components/app-card.d.ts +24 -2
  13. package/dist/components/app-card.js +25 -10
  14. package/dist/components/banner.d.ts +2 -2
  15. package/dist/components/banner.js +4 -3
  16. package/dist/components/bottom-navigation.d.ts +16 -4
  17. package/dist/components/bottom-navigation.js +10 -7
  18. package/dist/components/bottom-sheet.d.ts +4 -1
  19. package/dist/components/bottom-sheet.js +2 -2
  20. package/dist/components/checkbox.d.ts +12 -2
  21. package/dist/components/checkbox.js +7 -2
  22. package/dist/components/combobox.d.ts +186 -0
  23. package/dist/components/combobox.js +521 -0
  24. package/dist/components/comment.d.ts +27 -9
  25. package/dist/components/comment.js +14 -13
  26. package/dist/components/data-table.d.ts +14 -2
  27. package/dist/components/data-table.js +31 -10
  28. package/dist/components/date-picker.d.ts +179 -0
  29. package/dist/components/date-picker.js +336 -0
  30. package/dist/components/date-range-picker.d.ts +251 -0
  31. package/dist/components/date-range-picker.js +484 -0
  32. package/dist/components/file-upload.d.ts +30 -4
  33. package/dist/components/file-upload.js +37 -17
  34. package/dist/components/filter-panel.d.ts +29 -6
  35. package/dist/components/filter-panel.js +16 -14
  36. package/dist/components/flash-offer-bar.d.ts +18 -4
  37. package/dist/components/flash-offer-bar.js +13 -8
  38. package/dist/components/header-bar.d.ts +20 -4
  39. package/dist/components/header-bar.js +20 -13
  40. package/dist/components/icon.d.ts +7 -0
  41. package/dist/components/icon.js +9 -1
  42. package/dist/components/link-tabs.d.ts +16 -4
  43. package/dist/components/link-tabs.js +10 -7
  44. package/dist/components/mobile-menu.d.ts +19 -4
  45. package/dist/components/mobile-menu.js +16 -10
  46. package/dist/components/modal.d.ts +4 -1
  47. package/dist/components/nested-list.d.ts +22 -3
  48. package/dist/components/nested-list.js +25 -12
  49. package/dist/components/notification-panel.d.ts +26 -5
  50. package/dist/components/notification-panel.js +17 -11
  51. package/dist/components/option-group.d.ts +12 -2
  52. package/dist/components/option-group.js +13 -7
  53. package/dist/components/page-header.d.ts +18 -2
  54. package/dist/components/page-header.js +23 -10
  55. package/dist/components/pagination.d.ts +27 -4
  56. package/dist/components/pagination.js +28 -16
  57. package/dist/components/progress-bar.d.ts +12 -2
  58. package/dist/components/progress-bar.js +9 -4
  59. package/dist/components/radio.d.ts +12 -1
  60. package/dist/components/radio.js +12 -6
  61. package/dist/components/report-tile.d.ts +12 -1
  62. package/dist/components/report-tile.js +9 -4
  63. package/dist/components/resource-list.d.ts +36 -5
  64. package/dist/components/resource-list.js +50 -23
  65. package/dist/components/save-bar.d.ts +23 -6
  66. package/dist/components/save-bar.js +14 -12
  67. package/dist/components/search.d.ts +28 -7
  68. package/dist/components/search.js +18 -13
  69. package/dist/components/select.d.ts +12 -2
  70. package/dist/components/select.js +9 -4
  71. package/dist/components/side-navigation.d.ts +16 -4
  72. package/dist/components/side-navigation.js +16 -12
  73. package/dist/components/side-panel.d.ts +5 -2
  74. package/dist/components/side-panel.js +5 -3
  75. package/dist/components/skeleton-display.d.ts +6 -4
  76. package/dist/components/skeleton-display.js +4 -5
  77. package/dist/components/smart-tip.d.ts +25 -6
  78. package/dist/components/smart-tip.js +18 -12
  79. package/dist/components/spinner.d.ts +4 -3
  80. package/dist/components/spinner.js +5 -6
  81. package/dist/components/status-tabs.d.ts +12 -2
  82. package/dist/components/status-tabs.js +14 -8
  83. package/dist/components/table-header.d.ts +15 -2
  84. package/dist/components/table-header.js +13 -5
  85. package/dist/components/tag.d.ts +12 -2
  86. package/dist/components/tag.js +9 -4
  87. package/dist/components/text-field.d.ts +12 -2
  88. package/dist/components/text-field.js +9 -4
  89. package/dist/components/thumbnail.d.ts +12 -2
  90. package/dist/components/thumbnail.js +8 -3
  91. package/dist/components/toast.d.ts +14 -3
  92. package/dist/components/toast.js +20 -9
  93. package/dist/components/toggle.js +2 -0
  94. package/dist/custom-elements.json +16477 -6434
  95. package/dist/index.d.ts +7 -1
  96. package/dist/index.js +5 -1
  97. package/dist/localize.d.ts +130 -0
  98. package/dist/localize.js +232 -0
  99. package/dist/overlay.d.ts +8 -4
  100. package/dist/overlay.js +9 -12
  101. package/package.json +4 -4
@@ -1,6 +1,17 @@
1
- import { LitElement } from 'lit';
1
+ import { CmLocalizedElement } from '../localize.js';
2
2
  import './icon.js';
3
3
  import './skeleton.js';
4
+ declare const strings: {
5
+ /** Shown when there are no rows and no `empty` slot. */
6
+ empty: string;
7
+ /** Announced after a sort. `{direction}` is the common `ascending` or `descending`. */
8
+ sorted: string;
9
+ };
10
+ declare module '../localize.js' {
11
+ interface CmStrings {
12
+ dataTable: typeof strings;
13
+ }
14
+ }
4
15
  /** One column of a data table. */
5
16
  export interface DataTableColumn {
6
17
  /** The property of each row shown in this column, and the key in `cm-sort`. */
@@ -38,7 +49,7 @@ export type SortDirection = 'ascending' | 'descending';
38
49
  * `preventDefault()` to stop the table sorting itself. With `sort-mode="manual"` it never sorts itself.
39
50
  * @cssprop --cm-data-table-max-height - With `sticky-header`, the table scrolls inside this height. Default `none`.
40
51
  */
41
- export declare class CmDataTable extends LitElement {
52
+ export declare class CmDataTable extends CmLocalizedElement {
42
53
  #private;
43
54
  static properties: {
44
55
  columns: {
@@ -130,3 +141,4 @@ declare global {
130
141
  'cm-data-table': CmDataTable;
131
142
  }
132
143
  }
144
+ export {};
@@ -10,10 +10,17 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
10
10
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
11
11
  };
12
12
  var _CmDataTable_instances, _CmDataTable_userSorted, _CmDataTable_observer, _CmDataTable_readLight, _CmDataTable_say, _CmDataTable_enhanceLight, _CmDataTable_lightIcon, _CmDataTable_onLightSort, _CmDataTable_onSort, _CmDataTable_text, _CmDataTable_cls;
13
- import { LitElement, html, css, nothing } from 'lit';
13
+ import { html, css, nothing } from 'lit';
14
14
  import { base, define } from '../base.js';
15
+ import { CmLocalizedElement, defineStrings, formatDate } from '../localize.js';
15
16
  import './icon.js';
16
17
  import './skeleton.js';
18
+ const strings = defineStrings('dataTable', {
19
+ /** Shown when there are no rows and no `empty` slot. */
20
+ empty: 'No data',
21
+ /** Announced after a sort. `{direction}` is the common `ascending` or `descending`. */
22
+ sorted: 'Sorted by {column}, {direction}',
23
+ });
17
24
  let sheetAdded = false;
18
25
  /**
19
26
  * Styles for a server-rendered `<table>` written inside `cm-data-table` (light DOM, so it can't be styled
@@ -61,9 +68,23 @@ function toNumber(v) {
61
68
  return negative ? -n : n;
62
69
  }
63
70
  const toTime = (v) => (v instanceof Date ? v.getTime() : typeof v === 'number' ? v : Date.parse(String(v ?? '')));
64
- const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
71
+ const collators = new Map();
72
+ /** Text sorts by the table's language (`lang`), with numbers inside text compared as numbers. */
73
+ function collator(locale) {
74
+ let c = collators.get(locale ?? '');
75
+ if (!c) {
76
+ try {
77
+ c = new Intl.Collator(locale, { numeric: true, sensitivity: 'base' });
78
+ }
79
+ catch {
80
+ c = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
81
+ }
82
+ collators.set(locale ?? '', c);
83
+ }
84
+ return c;
85
+ }
65
86
  /** Compares two cell values the way a column of `type` should sort. Empty values sort last. */
66
- function compare(a, b, type) {
87
+ function compare(a, b, type, locale) {
67
88
  const empty = (v) => v === null || v === undefined || v === '';
68
89
  if (empty(a) || empty(b))
69
90
  return empty(a) === empty(b) ? 0 : empty(a) ? 1 : -1;
@@ -71,7 +92,7 @@ function compare(a, b, type) {
71
92
  return (toNumber(a) || 0) - (toNumber(b) || 0);
72
93
  if (type === 'date')
73
94
  return (toTime(a) || 0) - (toTime(b) || 0);
74
- return collator.compare(String(a), String(b));
95
+ return collator(locale).compare(String(a), String(b));
75
96
  }
76
97
  /**
77
98
  * A data table for reports and read-only lists: sales by day, stock by location, order lines.
@@ -89,7 +110,7 @@ function compare(a, b, type) {
89
110
  * `preventDefault()` to stop the table sorting itself. With `sort-mode="manual"` it never sorts itself.
90
111
  * @cssprop --cm-data-table-max-height - With `sticky-header`, the table scrolls inside this height. Default `none`.
91
112
  */
92
- export class CmDataTable extends LitElement {
113
+ export class CmDataTable extends CmLocalizedElement {
93
114
  constructor() {
94
115
  super(...arguments);
95
116
  _CmDataTable_instances.add(this);
@@ -145,7 +166,7 @@ export class CmDataTable extends LitElement {
145
166
  const emptyA = av === null || av === undefined || av === '', emptyB = bv === null || bv === undefined || bv === '';
146
167
  if (emptyA || emptyB)
147
168
  return emptyA === emptyB ? i - j : emptyA ? 1 : -1;
148
- return sign * compare(av, bv, col.type) || i - j;
169
+ return sign * compare(av, bv, col.type, this.locale) || i - j;
149
170
  }).map(([r]) => r);
150
171
  }
151
172
  updated(changed) {
@@ -185,7 +206,7 @@ export class CmDataTable extends LitElement {
185
206
  : rows.map((r) => html `<tr part="row">${cols.map((c, i) => i === 0
186
207
  ? html `<th scope="row" class=${__classPrivateFieldGet(this, _CmDataTable_instances, "m", _CmDataTable_cls).call(this, c)} part="cell">${__classPrivateFieldGet(this, _CmDataTable_instances, "m", _CmDataTable_text).call(this, r[c.key])}</th>`
187
208
  : html `<td class=${__classPrivateFieldGet(this, _CmDataTable_instances, "m", _CmDataTable_cls).call(this, c)} part="cell">${__classPrivateFieldGet(this, _CmDataTable_instances, "m", _CmDataTable_text).call(this, r[c.key])}</td>`)}</tr>`)}
188
- ${showEmpty ? html `<tr class="empty"><td colspan=${n}><slot name="empty">No data</slot></td></tr>` : nothing}
209
+ ${showEmpty ? html `<tr class="empty"><td colspan=${n}><slot name="empty">${this.t('empty')}</slot></td></tr>` : nothing}
189
210
  </tbody>
190
211
  ${this.totals && !this.loading && !showEmpty
191
212
  ? html `<tfoot><tr part="totals">${cols.map((c) => html `<td class=${__classPrivateFieldGet(this, _CmDataTable_instances, "m", _CmDataTable_cls).call(this, c)}>${__classPrivateFieldGet(this, _CmDataTable_instances, "m", _CmDataTable_text).call(this, this.totals[c.key])}</td>`)}</tr></tfoot>`
@@ -202,7 +223,7 @@ _CmDataTable_userSorted = new WeakMap(), _CmDataTable_observer = new WeakMap(),
202
223
  __classPrivateFieldGet(this, _CmDataTable_instances, "m", _CmDataTable_enhanceLight).call(this);
203
224
  }
204
225
  }, _CmDataTable_say = function _CmDataTable_say(label, direction) {
205
- this._announce = `Sorted by ${label}, ${direction}`;
226
+ this._announce = this.t('sorted', { column: label, direction: this.t(direction) });
206
227
  }, _CmDataTable_enhanceLight = function _CmDataTable_enhanceLight() {
207
228
  const table = this.querySelector(':scope > table');
208
229
  const cells = table?.tHead?.rows[0]?.cells;
@@ -241,7 +262,7 @@ _CmDataTable_userSorted = new WeakMap(), _CmDataTable_observer = new WeakMap(),
241
262
  const sorted = [...body.rows].map((r, i) => [r, value(r), i]).sort(([, a, i], [, b, j]) => {
242
263
  if (a === '' || b === '')
243
264
  return a === b ? i - j : a === '' ? 1 : -1;
244
- return sign * compare(a, b, type) || i - j;
265
+ return sign * compare(a, b, type, this.locale) || i - j;
245
266
  });
246
267
  body.append(...sorted.map(([r]) => r));
247
268
  }
@@ -266,7 +287,7 @@ _CmDataTable_userSorted = new WeakMap(), _CmDataTable_observer = new WeakMap(),
266
287
  if (v === null || v === undefined)
267
288
  return '';
268
289
  if (v instanceof Date)
269
- return v.toLocaleDateString();
290
+ return formatDate(v, {}, this.locale);
270
291
  return String(v);
271
292
  }, _CmDataTable_cls = function _CmDataTable_cls(c) {
272
293
  return `${isEnd(c) ? 'end' : ''} ${c.type === 'numeric' || c.type === 'money' ? 'num' : ''}`;
@@ -0,0 +1,179 @@
1
+ import { type PropertyValues } from 'lit';
2
+ import { CmLocalizedElement } from '../localize.js';
3
+ import './icon.js';
4
+ declare const strings: {
5
+ /** Calendar button while no date is set. */
6
+ choose: string;
7
+ /** Calendar button while no date is set, when the field has a label. */
8
+ chooseFor: string;
9
+ /** Calendar button once a date is set. `{date}` is the full date. */
10
+ change: string;
11
+ /** Calendar button once a date is set, when the field has a label. */
12
+ changeFor: string;
13
+ /** Accessible name of the calendar popup. */
14
+ dialog: string;
15
+ previousMonth: string;
16
+ nextMonth: string;
17
+ /** Letters for day, month and year in the placeholder pattern, e.g. dd/mm/yyyy. */
18
+ patternDay: string;
19
+ patternMonth: string;
20
+ patternYear: string;
21
+ /** Validation: the text is not a date. `{pattern}` is e.g. dd/mm/yyyy. */
22
+ badInput: string;
23
+ /** Validation: `required` and empty. */
24
+ required: string;
25
+ /** Validation: before `min`. `{date}` is the min date. */
26
+ rangeUnderflow: string;
27
+ /** Validation: after `max`. */
28
+ rangeOverflow: string;
29
+ /** Validation: a date in `disabled-dates` or refused by `isDateDisabled`. */
30
+ unavailable: string;
31
+ };
32
+ declare module '../localize.js' {
33
+ interface CmStrings {
34
+ datePicker: typeof strings;
35
+ }
36
+ }
37
+ /**
38
+ * Date field: type a date or pick one from a calendar. Follows the WAI-ARIA APG "date picker dialog" pattern:
39
+ * the calendar button opens a month grid where arrows move by day and week, Page Up/Down by month, Shift+Page Up/Down
40
+ * by year, Home/End to the start and end of the week, Enter picks and Escape closes. Month and weekday names come
41
+ * from `Intl` in the page's language. Participates in native forms with an ISO `yyyy-mm-dd` value.
42
+ * @element cm-date-picker
43
+ * @fires change - When the date changes: picked in the calendar, or typed and committed with Enter or by leaving the box.
44
+ * @fires input - Same moment as `change`.
45
+ * @csspart box - The bordered box around the text input and calendar button.
46
+ * @csspart input - The text input.
47
+ * @csspart calendar - The month grid.
48
+ */
49
+ export declare class CmDatePicker extends CmLocalizedElement {
50
+ #private;
51
+ static formAssociated: boolean;
52
+ static shadowRootOptions: {
53
+ delegatesFocus: boolean;
54
+ mode: ShadowRootMode;
55
+ serializable?: boolean;
56
+ slotAssignment?: SlotAssignmentMode;
57
+ };
58
+ static properties: {
59
+ label: {};
60
+ helpText: {
61
+ attribute: string;
62
+ };
63
+ error: {
64
+ reflect: boolean;
65
+ };
66
+ name: {
67
+ reflect: boolean;
68
+ };
69
+ value: {};
70
+ min: {};
71
+ max: {};
72
+ placeholder: {};
73
+ locale: {
74
+ noAccessor: boolean;
75
+ };
76
+ firstDayOfWeek: {
77
+ type: NumberConstructor;
78
+ attribute: string;
79
+ };
80
+ disabledDates: {
81
+ attribute: string;
82
+ converter: {
83
+ fromAttribute: (v: string | null) => string[];
84
+ toAttribute: (v: unknown) => unknown;
85
+ };
86
+ };
87
+ isDateDisabled: {
88
+ attribute: boolean;
89
+ };
90
+ required: {
91
+ type: BooleanConstructor;
92
+ reflect: boolean;
93
+ };
94
+ disabled: {
95
+ type: BooleanConstructor;
96
+ reflect: boolean;
97
+ };
98
+ open: {
99
+ type: BooleanConstructor;
100
+ reflect: boolean;
101
+ };
102
+ size: {
103
+ reflect: boolean;
104
+ };
105
+ _text: {
106
+ state: boolean;
107
+ };
108
+ _focus: {
109
+ state: boolean;
110
+ };
111
+ };
112
+ /** Visible label above the box. Required for accessibility unless the element has an aria-label. */
113
+ label: string;
114
+ /** One sentence under the box in text-tertiary. */
115
+ helpText: string;
116
+ /** Error message; turns the border critical and sets aria-invalid. */
117
+ error: string;
118
+ /** Form field name. */
119
+ name: string;
120
+ /** The date as ISO `yyyy-mm-dd`; empty when no date is set. */
121
+ value: string;
122
+ /** Earliest date that can be chosen, ISO `yyyy-mm-dd`. */
123
+ min: string;
124
+ /** Latest date that can be chosen, ISO `yyyy-mm-dd`. */
125
+ max: string;
126
+ /** Shown in the empty box. Defaults to the locale's pattern, e.g. "dd/mm/yyyy". */
127
+ placeholder: string;
128
+ /**
129
+ * BCP 47 language for month and weekday names and the typed date order, e.g. `en-IN`, `hi-IN`. Empty: the same
130
+ * language as every other component (`configure({ locale })`, else the nearest `lang` attribute, else the browser's).
131
+ * Built-in text follows that language too; set it with `strings`, `setStrings()` or `configure()`.
132
+ */
133
+ get locale(): string;
134
+ set locale(v: string);
135
+ /** First column of the calendar: 0 = Sunday, 1 = Monday … 6 = Saturday. Defaults to the locale's custom where the browser knows it, else Sunday. */
136
+ firstDayOfWeek?: number;
137
+ /** Dates that can't be chosen, as ISO strings. In HTML, a comma- or space-separated list. */
138
+ disabledDates: string[];
139
+ /** Function that returns true for dates that can't be chosen, e.g. `(iso) => new Date(iso).getDay() === 0` for Sundays. Property only. */
140
+ isDateDisabled?: (date: string) => boolean;
141
+ /** The form will not submit until a date is set. */
142
+ required: boolean;
143
+ /** Blocks interaction. Also set by a disabled `<fieldset>`. */
144
+ disabled: boolean;
145
+ /** Whether the calendar is showing. */
146
+ open: boolean;
147
+ /** `small`: 12px label, 14px value (filter panels). */
148
+ size: 'default' | 'small';
149
+ _text: string;
150
+ _focus: Date;
151
+ static styles: import("lit").CSSResult[];
152
+ connectedCallback(): void;
153
+ disconnectedCallback(): void;
154
+ get form(): HTMLFormElement | null;
155
+ get validity(): ValidityState;
156
+ get validationMessage(): string;
157
+ /** The value as a local Date, or null. */
158
+ get valueAsDate(): Date | null;
159
+ checkValidity(): boolean;
160
+ reportValidity(): boolean;
161
+ formResetCallback(): void;
162
+ formDisabledCallback(d: boolean): void;
163
+ formStateRestoreCallback(state: string): void;
164
+ /** Opens the calendar. */
165
+ show(): void;
166
+ /** Closes the calendar. */
167
+ close(): void;
168
+ /** True when a date can't be chosen (outside min/max, in `disabledDates` or refused by `isDateDisabled`). */
169
+ isUnavailable(iso: string): boolean;
170
+ willUpdate(changed: PropertyValues): void;
171
+ updated(changed: PropertyValues): void;
172
+ render(): import("lit-html").TemplateResult<1>;
173
+ }
174
+ declare global {
175
+ interface HTMLElementTagNameMap {
176
+ 'cm-date-picker': CmDatePicker;
177
+ }
178
+ }
179
+ export {};
@@ -0,0 +1,336 @@
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
+ };
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 _CmDatePicker_instances, _CmDatePicker_localeProp, _CmDatePicker_internals, _CmDatePicker_id, _CmDatePicker_defaultValue, _CmDatePicker_keepText, _CmDatePicker_focusGrid, _CmDatePicker_locale_get, _CmDatePicker_fmt_get, _CmDatePicker_firstDay_get, _CmDatePicker_pattern_get, _CmDatePicker_format, _CmDatePicker_prepareFocus, _CmDatePicker_setValue, _CmDatePicker_commitText, _CmDatePicker_pick, _CmDatePicker_focusTrigger, _CmDatePicker_toggle, _CmDatePicker_onInputKey, _CmDatePicker_onGridKey, _CmDatePicker_onPopKey, _CmDatePicker_onMonth, _CmDatePicker_onOutside;
13
+ import { LitElement, html, css, nothing } from 'lit';
14
+ import { live } from 'lit/directives/live.js';
15
+ import { base, define, nextId, logicalKey } from '../base.js';
16
+ import { CmLocalizedElement, defineStrings } from '../localize.js';
17
+ import { fromISO, toISO, addMonths, startOfMonth, clamp, trapTab, dateFieldStyles, gridKey, renderGrid, calendarStyles, dateFormat, parseDate, resolveLocale, localeFirstDay, listConverter, asList, datePattern, } from '../calendar.js';
18
+ import './icon.js';
19
+ const strings = defineStrings('datePicker', {
20
+ /** Calendar button while no date is set. */
21
+ choose: 'Choose date',
22
+ /** Calendar button while no date is set, when the field has a label. */
23
+ chooseFor: 'Choose date for {label}',
24
+ /** Calendar button once a date is set. `{date}` is the full date. */
25
+ change: 'Change date, {date}',
26
+ /** Calendar button once a date is set, when the field has a label. */
27
+ changeFor: 'Change date for {label}, {date}',
28
+ /** Accessible name of the calendar popup. */
29
+ dialog: 'Choose date',
30
+ previousMonth: 'Previous month',
31
+ nextMonth: 'Next month',
32
+ /** Letters for day, month and year in the placeholder pattern, e.g. dd/mm/yyyy. */
33
+ patternDay: 'dd',
34
+ patternMonth: 'mm',
35
+ patternYear: 'yyyy',
36
+ /** Validation: the text is not a date. `{pattern}` is e.g. dd/mm/yyyy. */
37
+ badInput: 'Enter a date like {pattern}.',
38
+ /** Validation: `required` and empty. */
39
+ required: 'Enter or choose a date.',
40
+ /** Validation: before `min`. `{date}` is the min date. */
41
+ rangeUnderflow: 'Choose {date} or later.',
42
+ /** Validation: after `max`. */
43
+ rangeOverflow: 'Choose {date} or earlier.',
44
+ /** Validation: a date in `disabled-dates` or refused by `isDateDisabled`. */
45
+ unavailable: 'This date isn\'t available. Choose another date.',
46
+ });
47
+ /**
48
+ * Date field: type a date or pick one from a calendar. Follows the WAI-ARIA APG "date picker dialog" pattern:
49
+ * the calendar button opens a month grid where arrows move by day and week, Page Up/Down by month, Shift+Page Up/Down
50
+ * by year, Home/End to the start and end of the week, Enter picks and Escape closes. Month and weekday names come
51
+ * from `Intl` in the page's language. Participates in native forms with an ISO `yyyy-mm-dd` value.
52
+ * @element cm-date-picker
53
+ * @fires change - When the date changes: picked in the calendar, or typed and committed with Enter or by leaving the box.
54
+ * @fires input - Same moment as `change`.
55
+ * @csspart box - The bordered box around the text input and calendar button.
56
+ * @csspart input - The text input.
57
+ * @csspart calendar - The month grid.
58
+ */
59
+ export class CmDatePicker extends CmLocalizedElement {
60
+ constructor() {
61
+ super(...arguments);
62
+ _CmDatePicker_instances.add(this);
63
+ /** Visible label above the box. Required for accessibility unless the element has an aria-label. */
64
+ this.label = '';
65
+ /** One sentence under the box in text-tertiary. */
66
+ this.helpText = '';
67
+ /** Error message; turns the border critical and sets aria-invalid. */
68
+ this.error = '';
69
+ /** Form field name. */
70
+ this.name = '';
71
+ /** The date as ISO `yyyy-mm-dd`; empty when no date is set. */
72
+ this.value = '';
73
+ /** Earliest date that can be chosen, ISO `yyyy-mm-dd`. */
74
+ this.min = '';
75
+ /** Latest date that can be chosen, ISO `yyyy-mm-dd`. */
76
+ this.max = '';
77
+ /** Shown in the empty box. Defaults to the locale's pattern, e.g. "dd/mm/yyyy". */
78
+ this.placeholder = '';
79
+ _CmDatePicker_localeProp.set(this, '');
80
+ /** Dates that can't be chosen, as ISO strings. In HTML, a comma- or space-separated list. */
81
+ this.disabledDates = [];
82
+ /** The form will not submit until a date is set. */
83
+ this.required = false;
84
+ /** Blocks interaction. Also set by a disabled `<fieldset>`. */
85
+ this.disabled = false;
86
+ /** Whether the calendar is showing. */
87
+ this.open = false;
88
+ /** `small`: 12px label, 14px value (filter panels). */
89
+ this.size = 'default';
90
+ this._text = '';
91
+ this._focus = new Date();
92
+ _CmDatePicker_internals.set(this, this.attachInternals());
93
+ _CmDatePicker_id.set(this, nextId('cm-dp'));
94
+ _CmDatePicker_defaultValue.set(this, null);
95
+ _CmDatePicker_keepText.set(this, false);
96
+ _CmDatePicker_focusGrid.set(this, false);
97
+ _CmDatePicker_toggle.set(this, () => {
98
+ if (this.disabled)
99
+ return;
100
+ if (this.open)
101
+ this.open = false;
102
+ else {
103
+ __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_commitText).call(this);
104
+ this.show();
105
+ }
106
+ });
107
+ _CmDatePicker_onInputKey.set(this, (e) => {
108
+ if (e.key === 'Enter') {
109
+ __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_commitText).call(this);
110
+ }
111
+ else if (e.key === 'ArrowDown' && e.altKey) {
112
+ e.preventDefault();
113
+ __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_commitText).call(this);
114
+ this.show();
115
+ }
116
+ else if (e.key === 'Escape' && this.open) {
117
+ e.preventDefault();
118
+ this.open = false;
119
+ }
120
+ });
121
+ _CmDatePicker_onGridKey.set(this, (e) => {
122
+ const next = gridKey(logicalKey(e, this), e, this._focus, __classPrivateFieldGet(this, _CmDatePicker_instances, "a", _CmDatePicker_firstDay_get));
123
+ if (next) {
124
+ e.preventDefault();
125
+ this._focus = clamp(next, fromISO(this.min), fromISO(this.max));
126
+ __classPrivateFieldSet(this, _CmDatePicker_focusGrid, true, "f");
127
+ return;
128
+ }
129
+ if (e.key === 'Enter' || e.key === ' ') {
130
+ e.preventDefault();
131
+ __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_pick).call(this, this._focus);
132
+ }
133
+ });
134
+ _CmDatePicker_onPopKey.set(this, (e) => {
135
+ if (e.key === 'Escape') {
136
+ e.preventDefault();
137
+ e.stopPropagation();
138
+ this.open = false;
139
+ __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_focusTrigger).call(this);
140
+ return;
141
+ }
142
+ trapTab(e, e.currentTarget);
143
+ });
144
+ _CmDatePicker_onMonth.set(this, (step) => {
145
+ this._focus = clamp(addMonths(this._focus, step), fromISO(this.min), fromISO(this.max));
146
+ });
147
+ _CmDatePicker_onOutside.set(this, (e) => {
148
+ if (this.open && !e.composedPath().includes(this))
149
+ this.open = false;
150
+ });
151
+ }
152
+ /**
153
+ * BCP 47 language for month and weekday names and the typed date order, e.g. `en-IN`, `hi-IN`. Empty: the same
154
+ * language as every other component (`configure({ locale })`, else the nearest `lang` attribute, else the browser's).
155
+ * Built-in text follows that language too; set it with `strings`, `setStrings()` or `configure()`.
156
+ */
157
+ get locale() { return __classPrivateFieldGet(this, _CmDatePicker_localeProp, "f"); }
158
+ set locale(v) { const old = __classPrivateFieldGet(this, _CmDatePicker_localeProp, "f"); __classPrivateFieldSet(this, _CmDatePicker_localeProp, v ?? '', "f"); this.requestUpdate('locale', old); }
159
+ connectedCallback() {
160
+ super.connectedCallback();
161
+ if (__classPrivateFieldGet(this, _CmDatePicker_defaultValue, "f") === null)
162
+ __classPrivateFieldSet(this, _CmDatePicker_defaultValue, this.value, "f");
163
+ document.addEventListener('pointerdown', __classPrivateFieldGet(this, _CmDatePicker_onOutside, "f"), true);
164
+ }
165
+ disconnectedCallback() {
166
+ super.disconnectedCallback();
167
+ document.removeEventListener('pointerdown', __classPrivateFieldGet(this, _CmDatePicker_onOutside, "f"), true);
168
+ }
169
+ get form() { return __classPrivateFieldGet(this, _CmDatePicker_internals, "f").form; }
170
+ get validity() { return __classPrivateFieldGet(this, _CmDatePicker_internals, "f").validity; }
171
+ get validationMessage() { return __classPrivateFieldGet(this, _CmDatePicker_internals, "f").validationMessage; }
172
+ /** The value as a local Date, or null. */
173
+ get valueAsDate() { return fromISO(this.value); }
174
+ checkValidity() { return __classPrivateFieldGet(this, _CmDatePicker_internals, "f").checkValidity(); }
175
+ reportValidity() { return __classPrivateFieldGet(this, _CmDatePicker_internals, "f").reportValidity(); }
176
+ formResetCallback() { this.value = __classPrivateFieldGet(this, _CmDatePicker_defaultValue, "f") ?? ''; this._text = __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_format).call(this, this.value); this.open = false; }
177
+ formDisabledCallback(d) { this.disabled = d; if (d)
178
+ this.open = false; }
179
+ formStateRestoreCallback(state) { this.value = state ?? ''; }
180
+ /** Opens the calendar. */
181
+ show() { if (!this.disabled) {
182
+ __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_prepareFocus).call(this);
183
+ this.open = true;
184
+ } }
185
+ /** Closes the calendar. */
186
+ close() { this.open = false; }
187
+ /** True when a date can't be chosen (outside min/max, in `disabledDates` or refused by `isDateDisabled`). */
188
+ isUnavailable(iso) {
189
+ const d = fromISO(iso);
190
+ if (!d)
191
+ return true;
192
+ const min = fromISO(this.min), max = fromISO(this.max);
193
+ if ((min && d < min) || (max && d > max))
194
+ return true;
195
+ return asList(this.disabledDates).includes(iso) || !!this.isDateDisabled?.(iso);
196
+ }
197
+ willUpdate(changed) {
198
+ if (changed.has('value') && !__classPrivateFieldGet(this, _CmDatePicker_keepText, "f"))
199
+ this._text = __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_format).call(this, this.value);
200
+ else if (changed.has('locale') && fromISO(this.value))
201
+ this._text = __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_format).call(this, this.value);
202
+ __classPrivateFieldSet(this, _CmDatePicker_keepText, false, "f");
203
+ }
204
+ updated(changed) {
205
+ __classPrivateFieldGet(this, _CmDatePicker_internals, "f").setFormValue(this.value || null, this._text);
206
+ const input = this.renderRoot.querySelector('input') ?? undefined;
207
+ const d = fromISO(this.value);
208
+ const fmt = __classPrivateFieldGet(this, _CmDatePicker_instances, "a", _CmDatePicker_fmt_get);
209
+ if (this.error)
210
+ __classPrivateFieldGet(this, _CmDatePicker_internals, "f").setValidity({ customError: true }, this.error, input);
211
+ else if (this._text.trim() && !d)
212
+ __classPrivateFieldGet(this, _CmDatePicker_internals, "f").setValidity({ badInput: true }, this.t('badInput', { pattern: __classPrivateFieldGet(this, _CmDatePicker_instances, "a", _CmDatePicker_pattern_get) }), input);
213
+ else if (this.required && !d)
214
+ __classPrivateFieldGet(this, _CmDatePicker_internals, "f").setValidity({ valueMissing: true }, this.t('required'), input);
215
+ else if (d && fromISO(this.min) && d < fromISO(this.min))
216
+ __classPrivateFieldGet(this, _CmDatePicker_internals, "f").setValidity({ rangeUnderflow: true }, this.t('rangeUnderflow', { date: fmt.medium(fromISO(this.min)) }), input);
217
+ else if (d && fromISO(this.max) && d > fromISO(this.max))
218
+ __classPrivateFieldGet(this, _CmDatePicker_internals, "f").setValidity({ rangeOverflow: true }, this.t('rangeOverflow', { date: fmt.medium(fromISO(this.max)) }), input);
219
+ else if (d && this.isUnavailable(this.value))
220
+ __classPrivateFieldGet(this, _CmDatePicker_internals, "f").setValidity({ customError: true }, this.t('unavailable'), input);
221
+ else
222
+ __classPrivateFieldGet(this, _CmDatePicker_internals, "f").setValidity({});
223
+ if (this.open && __classPrivateFieldGet(this, _CmDatePicker_focusGrid, "f")) {
224
+ __classPrivateFieldSet(this, _CmDatePicker_focusGrid, false, "f");
225
+ this.renderRoot.querySelector('td[tabindex="0"]')?.focus();
226
+ }
227
+ if (changed.has('open') && changed.get('open') === true && !this.open)
228
+ __classPrivateFieldSet(this, _CmDatePicker_focusGrid, false, "f");
229
+ }
230
+ render() {
231
+ const fmt = __classPrivateFieldGet(this, _CmDatePicker_instances, "a", _CmDatePicker_fmt_get);
232
+ const value = fromISO(this.value);
233
+ const described = [this.error && `${__classPrivateFieldGet(this, _CmDatePicker_id, "f")}-err`, this.helpText && `${__classPrivateFieldGet(this, _CmDatePicker_id, "f")}-help`].filter(Boolean).join(' ');
234
+ const hostLabel = this.getAttribute('aria-label');
235
+ const name = this.label || hostLabel || '';
236
+ const month = startOfMonth(this._focus);
237
+ return html `<div class="field">
238
+ ${this.label
239
+ ? html `<label class="label" for="${__classPrivateFieldGet(this, _CmDatePicker_id, "f")}-in" part="label">${this.label}${this.required ? html `<span class="req" aria-hidden="true">*</span>` : nothing}</label>`
240
+ : nothing}
241
+ <div class="wrap">
242
+ <div class="box" part="box">
243
+ <input id="${__classPrivateFieldGet(this, _CmDatePicker_id, "f")}-in" part="input" type="text" autocomplete="off" spellcheck="false"
244
+ .value=${live(this._text)} placeholder=${this.placeholder || __classPrivateFieldGet(this, _CmDatePicker_instances, "a", _CmDatePicker_pattern_get)}
245
+ aria-label=${!this.label && hostLabel ? hostLabel : nothing}
246
+ ?required=${this.required} ?disabled=${this.disabled}
247
+ aria-invalid=${this.error ? 'true' : nothing} aria-describedby=${described || nothing}
248
+ @input=${(e) => { e.stopPropagation(); this._text = e.target.value; }}
249
+ @change=${() => __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_commitText).call(this)} @keydown=${__classPrivateFieldGet(this, _CmDatePicker_onInputKey, "f")} />
250
+ <button type="button" class="trigger" part="trigger" ?disabled=${this.disabled}
251
+ aria-label=${value ? this.t(name ? 'changeFor' : 'change', { label: name, date: fmt.long(value) }) : this.t(name ? 'chooseFor' : 'choose', { label: name })}
252
+ aria-haspopup="dialog" aria-expanded=${this.open ? 'true' : 'false'} aria-controls="${__classPrivateFieldGet(this, _CmDatePicker_id, "f")}-pop"
253
+ @click=${__classPrivateFieldGet(this, _CmDatePicker_toggle, "f")}><cm-icon name="calendar" size="18"></cm-icon></button>
254
+ </div>
255
+ <div class="pop" id="${__classPrivateFieldGet(this, _CmDatePicker_id, "f")}-pop" part="popover" role="dialog" aria-modal="true" aria-label=${this.t('dialog')}
256
+ ?hidden=${!this.open} @keydown=${__classPrivateFieldGet(this, _CmDatePicker_onPopKey, "f")}>
257
+ ${this.open ? html `<div class="cal">${renderGrid({
258
+ id: __classPrivateFieldGet(this, _CmDatePicker_id, "f"), fmt, firstDay: __classPrivateFieldGet(this, _CmDatePicker_instances, "a", _CmDatePicker_firstDay_get), month, focus: this._focus,
259
+ min: fromISO(this.min), max: fromISO(this.max),
260
+ isDisabled: (d) => this.isUnavailable(toISO(d)),
261
+ mark: (d) => (value && toISO(d) === this.value ? 'selected' : ''),
262
+ onPick: (d) => __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_pick).call(this, d), onKey: __classPrivateFieldGet(this, _CmDatePicker_onGridKey, "f"), onMonth: __classPrivateFieldGet(this, _CmDatePicker_onMonth, "f"),
263
+ previousLabel: this.t('previousMonth'), nextLabel: this.t('nextMonth'),
264
+ })}</div>` : nothing}
265
+ </div>
266
+ </div>
267
+ ${this.error ? html `<p class="error" id="${__classPrivateFieldGet(this, _CmDatePicker_id, "f")}-err" role="alert">${this.error}</p>` : nothing}
268
+ ${this.helpText ? html `<p class="help" id="${__classPrivateFieldGet(this, _CmDatePicker_id, "f")}-help">${this.helpText}</p>` : nothing}
269
+ </div>`;
270
+ }
271
+ }
272
+ _CmDatePicker_localeProp = new WeakMap(), _CmDatePicker_internals = new WeakMap(), _CmDatePicker_id = new WeakMap(), _CmDatePicker_defaultValue = new WeakMap(), _CmDatePicker_keepText = new WeakMap(), _CmDatePicker_focusGrid = new WeakMap(), _CmDatePicker_toggle = new WeakMap(), _CmDatePicker_onInputKey = new WeakMap(), _CmDatePicker_onGridKey = new WeakMap(), _CmDatePicker_onPopKey = new WeakMap(), _CmDatePicker_onMonth = new WeakMap(), _CmDatePicker_onOutside = new WeakMap(), _CmDatePicker_instances = new WeakSet(), _CmDatePicker_locale_get = function _CmDatePicker_locale_get() { return resolveLocale(this, this.locale); }, _CmDatePicker_fmt_get = function _CmDatePicker_fmt_get() { return dateFormat(__classPrivateFieldGet(this, _CmDatePicker_instances, "a", _CmDatePicker_locale_get)); }, _CmDatePicker_firstDay_get = function _CmDatePicker_firstDay_get() {
273
+ const n = Number(this.firstDayOfWeek);
274
+ return this.firstDayOfWeek == null || Number.isNaN(n) ? localeFirstDay(__classPrivateFieldGet(this, _CmDatePicker_instances, "a", _CmDatePicker_locale_get)) : ((Math.trunc(n) % 7) + 7) % 7;
275
+ }, _CmDatePicker_pattern_get = function _CmDatePicker_pattern_get() { return datePattern(__classPrivateFieldGet(this, _CmDatePicker_instances, "a", _CmDatePicker_fmt_get), { d: this.t('patternDay'), m: this.t('patternMonth'), y: this.t('patternYear') }); }, _CmDatePicker_format = function _CmDatePicker_format(v) {
276
+ const d = fromISO(v);
277
+ return d ? __classPrivateFieldGet(this, _CmDatePicker_instances, "a", _CmDatePicker_fmt_get).short(d) : v;
278
+ }, _CmDatePicker_prepareFocus = function _CmDatePicker_prepareFocus() {
279
+ const today = new Date();
280
+ const start = fromISO(this.value) ?? new Date(today.getFullYear(), today.getMonth(), today.getDate());
281
+ this._focus = clamp(start, fromISO(this.min), fromISO(this.max));
282
+ __classPrivateFieldSet(this, _CmDatePicker_focusGrid, true, "f");
283
+ }, _CmDatePicker_setValue = function _CmDatePicker_setValue(v) {
284
+ if (v === this.value)
285
+ return;
286
+ this.value = v;
287
+ this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
288
+ this.dispatchEvent(new Event('change', { bubbles: true, composed: true }));
289
+ }, _CmDatePicker_commitText = function _CmDatePicker_commitText() {
290
+ const text = this._text.trim();
291
+ if (!text) {
292
+ __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_setValue).call(this, '');
293
+ return;
294
+ }
295
+ const iso = parseDate(text, __classPrivateFieldGet(this, _CmDatePicker_instances, "a", _CmDatePicker_fmt_get));
296
+ if (iso) {
297
+ __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_setValue).call(this, iso);
298
+ this._text = __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_format).call(this, iso);
299
+ }
300
+ else {
301
+ __classPrivateFieldSet(this, _CmDatePicker_keepText, true, "f");
302
+ __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_setValue).call(this, '');
303
+ }
304
+ }, _CmDatePicker_pick = function _CmDatePicker_pick(d) {
305
+ const iso = toISO(d);
306
+ if (this.isUnavailable(iso))
307
+ return;
308
+ this.open = false;
309
+ __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_setValue).call(this, iso);
310
+ this._text = __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_format).call(this, iso);
311
+ __classPrivateFieldGet(this, _CmDatePicker_instances, "m", _CmDatePicker_focusTrigger).call(this);
312
+ }, _CmDatePicker_focusTrigger = function _CmDatePicker_focusTrigger() { this.renderRoot.querySelector('.trigger')?.focus(); };
313
+ CmDatePicker.formAssociated = true;
314
+ CmDatePicker.shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };
315
+ CmDatePicker.properties = {
316
+ label: {},
317
+ helpText: { attribute: 'help-text' },
318
+ error: { reflect: true },
319
+ name: { reflect: true },
320
+ value: {},
321
+ min: {},
322
+ max: {},
323
+ placeholder: {},
324
+ locale: { noAccessor: true },
325
+ firstDayOfWeek: { type: Number, attribute: 'first-day-of-week' },
326
+ disabledDates: { attribute: 'disabled-dates', converter: listConverter },
327
+ isDateDisabled: { attribute: false },
328
+ required: { type: Boolean, reflect: true },
329
+ disabled: { type: Boolean, reflect: true },
330
+ open: { type: Boolean, reflect: true },
331
+ size: { reflect: true },
332
+ _text: { state: true },
333
+ _focus: { state: true },
334
+ };
335
+ CmDatePicker.styles = [base, dateFieldStyles, calendarStyles, css `.pop { min-width: 0; }`];
336
+ define('cm-date-picker', CmDatePicker);