@uvalib/web-components 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.
Files changed (200) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +849 -47
  3. package/dist/analytics.d.ts +10 -0
  4. package/dist/analytics.js +9 -0
  5. package/dist/analytics.js.map +1 -0
  6. package/dist/base/UvalibElement.js +8 -5
  7. package/dist/base/UvalibElement.js.map +1 -1
  8. package/dist/base/analytics-state.d.ts +7 -0
  9. package/dist/base/analytics-state.js.map +1 -1
  10. package/dist/base/light-dom-styles.d.ts +13 -0
  11. package/dist/base/light-dom-styles.js +26 -0
  12. package/dist/base/light-dom-styles.js.map +1 -1
  13. package/dist/base/search-tracker.d.ts +57 -0
  14. package/dist/base/search-tracker.js +51 -0
  15. package/dist/base/search-tracker.js.map +1 -0
  16. package/dist/base.css +286 -14
  17. package/dist/base.d.ts +2 -0
  18. package/dist/base.js +1 -0
  19. package/dist/base.js.map +1 -1
  20. package/dist/components/site-analytics/SiteAnalytics.d.ts +20 -1
  21. package/dist/components/site-analytics/SiteAnalytics.js +93 -12
  22. package/dist/components/site-analytics/SiteAnalytics.js.map +1 -1
  23. package/dist/components/site-page/SitePage.d.ts +23 -0
  24. package/dist/components/site-page/SitePage.js +77 -0
  25. package/dist/components/site-page/SitePage.js.map +1 -1
  26. package/dist/components/uvalib-back-to-top/UvalibBackToTop.d.ts +58 -0
  27. package/dist/components/uvalib-back-to-top/UvalibBackToTop.js +250 -0
  28. package/dist/components/uvalib-back-to-top/UvalibBackToTop.js.map +1 -0
  29. package/dist/components/uvalib-back-to-top/uvalib-back-to-top.d.ts +1 -0
  30. package/dist/components/uvalib-back-to-top/uvalib-back-to-top.js +4 -0
  31. package/dist/components/uvalib-back-to-top/uvalib-back-to-top.js.map +1 -0
  32. package/dist/components/uvalib-breadcrumbs/UvalibBreadcrumbs.d.ts +14 -0
  33. package/dist/components/uvalib-breadcrumbs/UvalibBreadcrumbs.js +56 -4
  34. package/dist/components/uvalib-breadcrumbs/UvalibBreadcrumbs.js.map +1 -1
  35. package/dist/components/uvalib-chip-group/UvalibChipGroup.d.ts +25 -3
  36. package/dist/components/uvalib-chip-group/UvalibChipGroup.js +80 -10
  37. package/dist/components/uvalib-chip-group/UvalibChipGroup.js.map +1 -1
  38. package/dist/components/uvalib-combobox/UvalibCombobox.d.ts +212 -0
  39. package/dist/components/uvalib-combobox/UvalibCombobox.js +1088 -0
  40. package/dist/components/uvalib-combobox/UvalibCombobox.js.map +1 -0
  41. package/dist/components/uvalib-combobox/uvalib-combobox.d.ts +1 -0
  42. package/dist/components/uvalib-combobox/uvalib-combobox.js +4 -0
  43. package/dist/components/uvalib-combobox/uvalib-combobox.js.map +1 -0
  44. package/dist/components/uvalib-contents/UvalibContents.d.ts +53 -0
  45. package/dist/components/uvalib-contents/UvalibContents.js +202 -3
  46. package/dist/components/uvalib-contents/UvalibContents.js.map +1 -1
  47. package/dist/components/uvalib-date-histogram/UvalibDateHistogram.d.ts +56 -17
  48. package/dist/components/uvalib-date-histogram/UvalibDateHistogram.js +285 -81
  49. package/dist/components/uvalib-date-histogram/UvalibDateHistogram.js.map +1 -1
  50. package/dist/components/uvalib-date-range/UvalibDateRange.d.ts +6 -0
  51. package/dist/components/uvalib-date-range/UvalibDateRange.js +23 -0
  52. package/dist/components/uvalib-date-range/UvalibDateRange.js.map +1 -1
  53. package/dist/components/uvalib-filter-drawer/UvalibFilterDrawer.d.ts +113 -0
  54. package/dist/components/uvalib-filter-drawer/UvalibFilterDrawer.js +589 -0
  55. package/dist/components/uvalib-filter-drawer/UvalibFilterDrawer.js.map +1 -0
  56. package/dist/components/uvalib-filter-drawer/uvalib-filter-drawer.d.ts +1 -0
  57. package/dist/components/uvalib-filter-drawer/uvalib-filter-drawer.js +4 -0
  58. package/dist/components/uvalib-filter-drawer/uvalib-filter-drawer.js.map +1 -0
  59. package/dist/components/uvalib-image-regions/UvalibImageRegions.d.ts +138 -0
  60. package/dist/components/uvalib-image-regions/UvalibImageRegions.js +689 -0
  61. package/dist/components/uvalib-image-regions/UvalibImageRegions.js.map +1 -0
  62. package/dist/components/uvalib-image-regions/regions.d.ts +57 -0
  63. package/dist/components/uvalib-image-regions/regions.js +117 -0
  64. package/dist/components/uvalib-image-regions/regions.js.map +1 -0
  65. package/dist/components/uvalib-image-regions/uvalib-image-regions.d.ts +1 -0
  66. package/dist/components/uvalib-image-regions/uvalib-image-regions.js +4 -0
  67. package/dist/components/uvalib-image-regions/uvalib-image-regions.js.map +1 -0
  68. package/dist/components/uvalib-lightbox/UvalibLightbox.d.ts +79 -0
  69. package/dist/components/uvalib-lightbox/UvalibLightbox.js +295 -16
  70. package/dist/components/uvalib-lightbox/UvalibLightbox.js.map +1 -1
  71. package/dist/components/uvalib-map/UvalibMap.d.ts +251 -0
  72. package/dist/components/uvalib-map/UvalibMap.js +1395 -0
  73. package/dist/components/uvalib-map/UvalibMap.js.map +1 -0
  74. package/dist/components/uvalib-map/uvalib-map.d.ts +1 -0
  75. package/dist/components/uvalib-map/uvalib-map.js +4 -0
  76. package/dist/components/uvalib-map/uvalib-map.js.map +1 -0
  77. package/dist/components/uvalib-metadata/UvalibMetadata.d.ts +39 -2
  78. package/dist/components/uvalib-metadata/UvalibMetadata.js +214 -8
  79. package/dist/components/uvalib-metadata/UvalibMetadata.js.map +1 -1
  80. package/dist/components/uvalib-pager/UvalibPager.d.ts +22 -3
  81. package/dist/components/uvalib-pager/UvalibPager.js +42 -4
  82. package/dist/components/uvalib-pager/UvalibPager.js.map +1 -1
  83. package/dist/custom-elements.json +9641 -3131
  84. package/dist/index.d.ts +8 -0
  85. package/dist/index.js +5 -0
  86. package/dist/index.js.map +1 -1
  87. package/dist/pagefind.css +4 -0
  88. package/dist/styles/base.js +119 -0
  89. package/dist/styles/base.js.map +1 -1
  90. package/dist/styles/color-scheme.js +5 -0
  91. package/dist/styles/color-scheme.js.map +1 -1
  92. package/dist/styles/controls.js +6 -0
  93. package/dist/styles/controls.js.map +1 -1
  94. package/dist/styles/hidden.d.ts +2 -0
  95. package/dist/styles/hidden.js +51 -0
  96. package/dist/styles/hidden.js.map +1 -0
  97. package/dist/styles/message.d.ts +1 -0
  98. package/dist/styles/message.js +82 -0
  99. package/dist/styles/message.js.map +1 -0
  100. package/dist/styles/pagefind.js +4 -0
  101. package/dist/styles/pagefind.js.map +1 -1
  102. package/dist/styles/result-list.d.ts +1 -0
  103. package/dist/styles/result-list.js +111 -0
  104. package/dist/styles/result-list.js.map +1 -0
  105. package/dist/styles/results.js +0 -15
  106. package/dist/styles/results.js.map +1 -1
  107. package/dist/testing/index.d.ts +110 -0
  108. package/dist/testing/index.js +100 -0
  109. package/dist/testing/index.js.map +1 -0
  110. package/dist/testing/lighthouse-rules.d.ts +10 -0
  111. package/dist/testing/lighthouse-rules.js +44 -0
  112. package/dist/testing/lighthouse-rules.js.map +1 -0
  113. package/dist/tokens.css +5 -0
  114. package/dist-cdn/analytics.js +32 -0
  115. package/dist-cdn/analytics.js.map +1 -0
  116. package/dist-cdn/base.css +286 -14
  117. package/dist-cdn/bento-box.js +3 -3
  118. package/dist-cdn/chunks/{SiteAnalytics-Cm-FyhYS.js → SiteAnalytics-B9gu5aGO.js} +59 -30
  119. package/dist-cdn/chunks/SiteAnalytics-B9gu5aGO.js.map +1 -0
  120. package/dist-cdn/chunks/{UvalibElement-BnI-eRRR.js → UvalibElement-pGONDAwB.js} +108 -101
  121. package/dist-cdn/chunks/UvalibElement-pGONDAwB.js.map +1 -0
  122. package/dist-cdn/chunks/{accessible-GqhVn5_H.js → accessible-DJv7YOtS.js} +2 -2
  123. package/dist-cdn/chunks/{accessible-GqhVn5_H.js.map → accessible-DJv7YOtS.js.map} +1 -1
  124. package/dist-cdn/chunks/analytics-state-Ce8DKe4F.js.map +1 -1
  125. package/dist-cdn/chunks/{base-p5pk0vb2.js → base-BI8h0Gf3.js} +121 -2
  126. package/dist-cdn/chunks/base-BI8h0Gf3.js.map +1 -0
  127. package/dist-cdn/chunks/{library-weekly-hours-COE7Vv6V.js → library-weekly-hours-CrV3TlP5.js} +3 -3
  128. package/dist-cdn/chunks/{library-weekly-hours-COE7Vv6V.js.map → library-weekly-hours-CrV3TlP5.js.map} +1 -1
  129. package/dist-cdn/chunks/regions-B8ExwUGP.js +86 -0
  130. package/dist-cdn/chunks/regions-B8ExwUGP.js.map +1 -0
  131. package/dist-cdn/chunks/{repeat-CIFUYkyh.js → repeat-m5Zd_QeP.js} +2 -2
  132. package/dist-cdn/chunks/{repeat-CIFUYkyh.js.map → repeat-m5Zd_QeP.js.map} +1 -1
  133. package/dist-cdn/chunks/{site-header-BlOYvQg1.js → site-header-DYRMpdBj.js} +9 -4
  134. package/dist-cdn/chunks/{site-header-BlOYvQg1.js.map → site-header-DYRMpdBj.js.map} +1 -1
  135. package/dist-cdn/chunks/{site-main-nav-AaxZ9rQf.js → site-main-nav-DURrQMal.js} +3 -3
  136. package/dist-cdn/chunks/{site-main-nav-AaxZ9rQf.js.map → site-main-nav-DURrQMal.js.map} +1 -1
  137. package/dist-cdn/chunks/{static-html-1mTAG6nS.js → static-html-C1rhtCHu.js} +2 -2
  138. package/dist-cdn/chunks/{static-html-1mTAG6nS.js.map → static-html-C1rhtCHu.js.map} +1 -1
  139. package/dist-cdn/custom-elements.json +9641 -3131
  140. package/dist-cdn/events-section.js +3 -3
  141. package/dist-cdn/library-hours-setup.js +2 -2
  142. package/dist-cdn/library-weekly-hours.js +1 -1
  143. package/dist-cdn/manifest.json +10 -2
  144. package/dist-cdn/pagefind.css +4 -0
  145. package/dist-cdn/site-alerts.js +4 -4
  146. package/dist-cdn/site-analytics.js +2 -2
  147. package/dist-cdn/site-footer.js +2 -2
  148. package/dist-cdn/site-header.js +1 -1
  149. package/dist-cdn/site-hours-section.js +4 -4
  150. package/dist-cdn/site-main-nav.js +1 -1
  151. package/dist-cdn/site-page.js +56 -11
  152. package/dist-cdn/site-page.js.map +1 -1
  153. package/dist-cdn/site-style.js +2 -2
  154. package/dist-cdn/skills/uvalib-web-components/SKILL.md +98 -13
  155. package/dist-cdn/skills/uvalib-web-components/reference/accessibility-testing.md +34 -2
  156. package/dist-cdn/skills/uvalib-web-components/reference/components.md +302 -14
  157. package/dist-cdn/skills/uvalib-web-components/reference/snippets.md +1 -1
  158. package/dist-cdn/tokens.css +5 -0
  159. package/dist-cdn/uvalib-analytics.js +2 -2
  160. package/dist-cdn/uvalib-back-to-top.js +156 -0
  161. package/dist-cdn/uvalib-back-to-top.js.map +1 -0
  162. package/dist-cdn/uvalib-breadcrumbs.js +31 -11
  163. package/dist-cdn/uvalib-breadcrumbs.js.map +1 -1
  164. package/dist-cdn/uvalib-card-grid.js +1 -1
  165. package/dist-cdn/uvalib-card.js +3 -3
  166. package/dist-cdn/uvalib-chip-group.js +53 -14
  167. package/dist-cdn/uvalib-chip-group.js.map +1 -1
  168. package/dist-cdn/uvalib-combobox.js +667 -0
  169. package/dist-cdn/uvalib-combobox.js.map +1 -0
  170. package/dist-cdn/uvalib-contents.js +100 -22
  171. package/dist-cdn/uvalib-contents.js.map +1 -1
  172. package/dist-cdn/uvalib-date-histogram.js +237 -127
  173. package/dist-cdn/uvalib-date-histogram.js.map +1 -1
  174. package/dist-cdn/uvalib-date-range.js +14 -2
  175. package/dist-cdn/uvalib-date-range.js.map +1 -1
  176. package/dist-cdn/uvalib-filter-drawer.js +355 -0
  177. package/dist-cdn/uvalib-filter-drawer.js.map +1 -0
  178. package/dist-cdn/uvalib-filter.js +3 -3
  179. package/dist-cdn/uvalib-image-regions.js +460 -0
  180. package/dist-cdn/uvalib-image-regions.js.map +1 -0
  181. package/dist-cdn/uvalib-lightbox.js +214 -59
  182. package/dist-cdn/uvalib-lightbox.js.map +1 -1
  183. package/dist-cdn/uvalib-map.js +667 -0
  184. package/dist-cdn/uvalib-map.js.map +1 -0
  185. package/dist-cdn/uvalib-metadata.js +150 -24
  186. package/dist-cdn/uvalib-metadata.js.map +1 -1
  187. package/dist-cdn/uvalib-pager.js +29 -17
  188. package/dist-cdn/uvalib-pager.js.map +1 -1
  189. package/dist-cdn/uvalib-photo-grid.js +2 -2
  190. package/dist-cdn/uvalib-results-count.js +2 -2
  191. package/dist-cdn/uvalib-tabs.js +2 -2
  192. package/dist-cdn/uvalib-tag-list.js +2 -2
  193. package/package.json +43 -1
  194. package/skills/uvalib-web-components/SKILL.md +98 -13
  195. package/skills/uvalib-web-components/reference/accessibility-testing.md +34 -2
  196. package/skills/uvalib-web-components/reference/components.md +302 -14
  197. package/skills/uvalib-web-components/reference/snippets.md +1 -1
  198. package/dist-cdn/chunks/SiteAnalytics-Cm-FyhYS.js.map +0 -1
  199. package/dist-cdn/chunks/UvalibElement-BnI-eRRR.js.map +0 -1
  200. package/dist-cdn/chunks/base-p5pk0vb2.js.map +0 -1
@@ -0,0 +1,1088 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { css, html, nothing, svg, unsafeCSS } from 'lit';
8
+ import { property, state } from 'lit/decorators.js';
9
+ import { trackError, trackEvent } from '../../base/analytics.js';
10
+ import { UvalibElement } from '../../base/UvalibElement.js';
11
+ import { installLightDomStyles } from '../../base/light-dom-styles.js';
12
+ import { normalize, SourceChildren } from '../../base/source-children.js';
13
+ import { accessible } from '../../styles/accessible.js';
14
+ /**
15
+ * `debounce`: milliseconds after the last keystroke before `src` is fetched. `announce`:
16
+ * milliseconds the suggestion count must stay put before it is announced. Tests may shorten them.
17
+ */
18
+ export const comboboxTiming = { debounce: 250, announce: 500 };
19
+ const TAG = 'uvalib-combobox';
20
+ /** How long an announcement stays in the live region before it is cleared. */
21
+ const CLEAR_MS = 5000;
22
+ /** Responses kept per `src`, so Backspace does not fetch again. */
23
+ const CACHE_SIZE = 30;
24
+ let uid = 0;
25
+ const MARKS = /\p{M}/gu;
26
+ /** Case- and accent-insensitive form: “Ébène” and “ebene” match. */
27
+ export const fold = (s) => s.normalize('NFD').replace(MARKS, '').toLowerCase();
28
+ /** `label` folded, with the index in `label` that each folded character came from. */
29
+ function foldMap(label) {
30
+ let text = '';
31
+ const map = [];
32
+ let i = 0;
33
+ for (const ch of label) {
34
+ const f = fold(ch);
35
+ for (let k = 0; k < f.length; k++)
36
+ map.push(i);
37
+ text += f;
38
+ i += ch.length;
39
+ }
40
+ map.push(i);
41
+ return { text, map };
42
+ }
43
+ const WORD = /[\p{L}\p{N}]/u;
44
+ function toEntry(raw) {
45
+ if (typeof raw === 'string' || typeof raw === 'number') {
46
+ const s = normalize(raw);
47
+ return s
48
+ ? { value: s, label: s, disabled: false, fold: fold(s), raw: { value: s, label: s } }
49
+ : null;
50
+ }
51
+ if (!raw || typeof raw !== 'object')
52
+ return null;
53
+ const r = raw;
54
+ const label = normalize(r.label ?? r.value);
55
+ if (!label)
56
+ return null;
57
+ const e = {
58
+ value: String(r.value ?? label),
59
+ label,
60
+ disabled: !!r.disabled,
61
+ fold: fold(label),
62
+ raw: r,
63
+ };
64
+ const d = normalize(r.description);
65
+ if (d)
66
+ e.description = d;
67
+ return e;
68
+ }
69
+ const toEntries = (list) => Array.isArray(list) ? list.map(toEntry).filter((e) => e !== null) : [];
70
+ const count = (n) => n.toLocaleString('en-US');
71
+ /**
72
+ * Kept with `no-style`: the popup under the field, 44px options and clear button, and the
73
+ * hidden live region. `host` is `:host` or the tag.
74
+ */
75
+ const structuralRules = (host) => `
76
+ ${host} { display: block; max-width: 100%; line-height: 1.5; }
77
+ ${host} .label { display: block; margin-block-end: 0.25rem; }
78
+ ${host} .field { position: relative; }
79
+ ${host} .input {
80
+ display: block;
81
+ box-sizing: border-box;
82
+ inline-size: 100%;
83
+ min-block-size: 44px;
84
+ margin: 0;
85
+ padding-inline-end: 44px;
86
+ font: inherit;
87
+ line-height: 1.2;
88
+ }
89
+ ${host} .clear {
90
+ position: absolute;
91
+ inset-block-start: 0;
92
+ inset-inline-end: 0;
93
+ display: inline-flex;
94
+ align-items: center;
95
+ justify-content: center;
96
+ box-sizing: border-box;
97
+ inline-size: 44px;
98
+ block-size: 44px;
99
+ margin: 0;
100
+ padding: 0;
101
+ cursor: pointer;
102
+ }
103
+ ${host} .popup {
104
+ position: absolute;
105
+ inset-inline: 0;
106
+ inset-block-start: calc(100% + 2px);
107
+ z-index: 20;
108
+ box-sizing: border-box;
109
+ max-block-size: min(18rem, 60vh);
110
+ margin: 0;
111
+ overflow-y: auto;
112
+ overscroll-behavior: contain;
113
+ }
114
+ ${host} .listbox { margin: 0; padding: 0; list-style: none; }
115
+ ${host} .option {
116
+ display: flex;
117
+ flex-direction: column;
118
+ justify-content: center;
119
+ box-sizing: border-box;
120
+ min-block-size: 44px;
121
+ overflow-wrap: anywhere;
122
+ cursor: pointer;
123
+ }
124
+ ${host} .option[aria-disabled='true'] { cursor: not-allowed; }
125
+ ${host} .message { box-sizing: border-box; min-block-size: 44px; margin: 0; }
126
+ ${host} .description { margin: 0.25rem 0 0; }
127
+ ${host} .visually-hidden {
128
+ position: absolute;
129
+ width: 1px;
130
+ height: 1px;
131
+ margin: -1px;
132
+ padding: 0;
133
+ overflow: hidden;
134
+ clip: rect(0, 0, 0, 0);
135
+ white-space: nowrap;
136
+ border: 0;
137
+ }
138
+ ${host}[hidden], ${host} [hidden] { display: none !important; }
139
+ `;
140
+ const shadowStructure = unsafeCSS(structuralRules(':host'));
141
+ const BORDER = unsafeCSS('var(--uva-color-control-border, var(--uva-grey, #808080))');
142
+ const ACCENT = unsafeCSS('var(--uva-color-accent-bg, var(--uva-brand-blue, #232d4b))');
143
+ const MUTED = unsafeCSS('var(--uva-color-text-muted, var(--uva-grey-A, #4f4f4f))');
144
+ const TEXT = unsafeCSS('var(--uva-color-input-text, var(--uva-grey-darkest, #2b2b2b))');
145
+ const RAISED = unsafeCSS('var(--uva-color-surface-raised, #ffffff)');
146
+ const CLEAR_ICON = svg `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" focusable="false"><path d="M4 4l8 8M12 4l-8 8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>`;
147
+ /**
148
+ * An editable text field that suggests values as you type, from a local list or a URL: a
149
+ * person, place or subject picker. It follows the WAI-ARIA APG “Editable Combobox With List
150
+ * Autocomplete”: a real `<input role="combobox">` and a `role="listbox"` popup under it.
151
+ *
152
+ * Suggestions come from the `items` property (`{ value, label?, description?, disabled? }`
153
+ * objects, or strings), from `<option>` children (directly or inside a `<datalist>`; the
154
+ * `label` attribute or text is the label, `data-description` the second line), or from `src`,
155
+ * a URL template with `{q}` (fetched 250 ms after the last keystroke once the text has
156
+ * `min-length` characters, default 1; a newer keystroke aborts the older request; the
157
+ * response is a JSON array of the same shape, or anything `transform(data, query)` turns
158
+ * into one). `items` wins over the children while set. Local suggestions match anywhere in
159
+ * the label, ignoring case and accents, those starting with the text first, then those with
160
+ * a word starting with it; at most `max-results` (default 50, 0 for all) are shown, which
161
+ * keeps a list of 16,000 people fast. The matched text is bold and underlined in a `<mark>`.
162
+ *
163
+ * Keys: Down opens the list on the first suggestion and moves (wrapping), Up opens on the
164
+ * last, Alt+Down opens without moving, Alt+Up closes, Enter chooses the active suggestion
165
+ * (and then does not submit the form; with none active, Enter submits as in any field),
166
+ * Escape closes the list and a second Escape clears the field, Home, End, Left and Right move
167
+ * the caret, and Tab leaves without choosing. A real clear button (“Clear <label>”, 44px,
168
+ * shown only with text) empties the field and returns focus to it.
169
+ *
170
+ * Free text is allowed: `value` is whatever is in the field, and `selected` the chosen
171
+ * suggestion (or null); typing after choosing clears it, and leaving the field with text that
172
+ * is exactly one suggestion's label chooses it. `must-choose` makes any other text invalid
173
+ * (“Choose one of the suggestions.”). The element is form-associated: with `name` it submits
174
+ * the chosen suggestion's value, or else the text, and a form reset restores the `value`
175
+ * attribute. `required` and `disabled` (also from a disabled fieldset) work as on an input.
176
+ *
177
+ * A polite status says “5 suggestions”, “50 of 1,234 suggestions”, “No suggestions”,
178
+ * “Loading suggestions” or “Couldn't load suggestions” half a second after the list settles
179
+ * (never on the first render); the popup shows the same notes visibly. A failed load never
180
+ * throws.
181
+ *
182
+ * Before it upgrades, `base.css` shows the label (from the attribute) and holds the field's
183
+ * height. A fallback `<input list>` child works as a plain field meanwhile; on upgrade its
184
+ * text, `name` and `placeholder` carry over, and it is disabled so it does not submit twice.
185
+ *
186
+ * @tagname uvalib-combobox
187
+ * @fires input - The text changed by typing (the native event of the field, composed). Not fired when an option is chosen.
188
+ * @fires select - A suggestion was chosen (click or Enter). `detail` is `{ item }`, the object given. Bubbles and is composed.
189
+ * @fires change - The value was committed: a suggestion chosen, the field cleared, or the field left with changed text. `detail` is `{ value, item }` (`item` is the chosen suggestion or null). Not fired when the app sets `value` or `selected`. Bubbles and is composed.
190
+ * @fires uvalib-analytics-event - For `<site-analytics>`: `['uvalib-combobox', 'select', '<label>', <position from 1>]` when a suggestion is chosen, `['uvalib-combobox', 'clear', '<label>']` when the clear button or Escape empties the field, and `['uvalib-combobox', 'error', 'load']` once when `src` fails. Never the typed text or a suggestion's text or value. Bubbles and is composed.
191
+ * @csspart label - The visible label.
192
+ * @csspart input - The text field.
193
+ * @csspart clear - The clear button.
194
+ * @csspart popup - The popup under the field.
195
+ * @csspart option - Each suggestion.
196
+ * @csspart description - The hint under the field.
197
+ * @cssprop --uva-color-surface-raised - Dark-mode role token: field and popup background (else #fff).
198
+ * @cssprop --uva-color-control-border - Dark-mode role token: field and popup border (else `--uva-grey`, #808080).
199
+ * @cssprop --uva-color-input-text - Dark-mode role token: field and suggestion text (else #2b2b2b).
200
+ * @cssprop --uva-color-text-muted - Dark-mode role token: descriptions, notes and the clear icon (else #4f4f4f).
201
+ * @cssprop --uva-color-surface-hover - Dark-mode role token: active suggestion background (else #dadada).
202
+ * @cssprop --uva-color-track - Dark-mode role token: hovered suggestion background (else #f1f1f1).
203
+ * @cssprop --uva-color-accent-bg - Dark-mode role token: the active suggestion's bar and outline (else `--uva-brand-blue`).
204
+ * @cssprop --uva-color-focus - Dark-mode role token: focus ring (else `--uva-brand-orange`).
205
+ * @cssprop --uva-color-shadow - Dark-mode role token: popup shadow.
206
+ */
207
+ export class UvalibCombobox extends UvalibElement {
208
+ static { this.formAssociated = true; }
209
+ static { this.shadowRootOptions = {
210
+ ...UvalibElement.shadowRootOptions,
211
+ delegatesFocus: true,
212
+ }; }
213
+ static { this.styles = [
214
+ accessible,
215
+ shadowStructure,
216
+ css `
217
+ .label {
218
+ font-weight: 600;
219
+ }
220
+ .input {
221
+ padding-block: 0.5rem;
222
+ padding-inline-start: 0.75rem;
223
+ border: 1px solid ${BORDER};
224
+ border-radius: 5px;
225
+ background: ${RAISED};
226
+ color: ${TEXT};
227
+ }
228
+ .input::placeholder {
229
+ color: ${MUTED};
230
+ opacity: 1;
231
+ }
232
+ .input:disabled {
233
+ background: var(--uva-color-track, var(--uva-grey-200, #f1f1f1));
234
+ color: ${MUTED};
235
+ cursor: not-allowed;
236
+ }
237
+ .input[aria-invalid='true'] {
238
+ border-width: 2px;
239
+ }
240
+ .clear {
241
+ border: 0;
242
+ border-radius: 5px;
243
+ background: none;
244
+ color: ${MUTED};
245
+ }
246
+ .clear:hover {
247
+ color: ${TEXT};
248
+ }
249
+ .clear:focus-visible {
250
+ outline-offset: -4px;
251
+ }
252
+ .popup {
253
+ padding-block: 0.25rem;
254
+ border: 1px solid ${BORDER};
255
+ border-radius: 5px;
256
+ background: ${RAISED};
257
+ color: ${TEXT};
258
+ box-shadow: 0 4px 12px var(--uva-color-shadow, rgba(0, 0, 0, 0.2));
259
+ }
260
+ .option {
261
+ padding: 0.375rem 0.75rem;
262
+ border-inline-start: 4px solid transparent;
263
+ }
264
+ .option:hover {
265
+ background: var(--uva-color-track, var(--uva-grey-200, #f1f1f1));
266
+ }
267
+ /* The active suggestion: a fill, a bar at the start and an outline, never colour alone. */
268
+ .option[aria-selected='true'] {
269
+ border-inline-start-color: ${ACCENT};
270
+ background: var(--uva-color-surface-hover, var(--uva-grey-100, #dadada));
271
+ outline: 2px solid ${ACCENT};
272
+ outline-offset: -2px;
273
+ }
274
+ .option[aria-disabled='true'] {
275
+ color: ${MUTED};
276
+ font-style: italic;
277
+ }
278
+ .option-description {
279
+ color: ${MUTED};
280
+ font-size: 0.875em;
281
+ }
282
+ mark {
283
+ background: none;
284
+ color: inherit;
285
+ font-weight: 700;
286
+ text-decoration: underline;
287
+ text-underline-offset: 0.15em;
288
+ }
289
+ .message {
290
+ padding: 0.625rem 0.75rem;
291
+ color: ${MUTED};
292
+ }
293
+ .description {
294
+ color: ${MUTED};
295
+ }
296
+ @media (forced-colors: active) {
297
+ .input,
298
+ .popup {
299
+ border-color: CanvasText;
300
+ }
301
+ .clear {
302
+ color: ButtonText;
303
+ }
304
+ .option[aria-selected='true'] {
305
+ forced-color-adjust: none;
306
+ border-inline-start-color: HighlightText;
307
+ background: Highlight;
308
+ color: HighlightText;
309
+ outline-color: HighlightText;
310
+ }
311
+ .option[aria-selected='true'] .option-description {
312
+ color: HighlightText;
313
+ }
314
+ .option[aria-disabled='true'] {
315
+ color: GrayText;
316
+ }
317
+ }
318
+ `,
319
+ ]; }
320
+ constructor() {
321
+ super();
322
+ /** The field's visible label (required); also the analytics name. */
323
+ this.label = '';
324
+ /** A hint under the field, read with it (aria-describedby). */
325
+ this.description = '';
326
+ this.placeholder = '';
327
+ /** The form field name. */
328
+ this.name = '';
329
+ /**
330
+ * The text in the field. The attribute is the starting text, and what a form reset
331
+ * restores. Setting it does not fire `change`.
332
+ */
333
+ this.value = '';
334
+ /**
335
+ * The chosen suggestion, or null. Set it (an item or a string) to show a choice: the field
336
+ * shows its label. Setting it does not fire `change`.
337
+ */
338
+ this.selected = null;
339
+ /** A URL template with `{q}` (the trimmed text, URL-encoded) that returns suggestions as JSON. */
340
+ this.src = '';
341
+ /** Characters typed before suggestions appear (and `src` is fetched). */
342
+ this.minLength = 1;
343
+ /** The most suggestions shown at once; 0 for all. */
344
+ this.maxResults = 50;
345
+ /** Text that is not one of the suggestions is invalid. */
346
+ this.mustChoose = false;
347
+ this.required = false;
348
+ this.disabled = false;
349
+ this.open = false;
350
+ this.active = -1;
351
+ this.shown = [];
352
+ this.total = 0;
353
+ this.loading = 'idle';
354
+ this.announcement = '';
355
+ this.formDisabled = false;
356
+ this.invalidShown = false;
357
+ this.childEntries = [];
358
+ this.uid = `${TAG}-${++uid}`;
359
+ this.warned = new Set();
360
+ /** The last committed state: `change` fires when it differs. */
361
+ this.committed = { value: '', item: null };
362
+ this.remote = [];
363
+ this.cache = new Map();
364
+ this.lastAnnounced = '';
365
+ this.adopted = new WeakSet();
366
+ this.started = false;
367
+ this.internals = this.attachInternals();
368
+ new SourceChildren(this, () => this.lightDom, (nodes) => this.read(nodes));
369
+ }
370
+ createRenderRoot() {
371
+ const root = super.createRenderRoot();
372
+ if (root instanceof ShadowRoot && this.noStyle) {
373
+ const sheet = shadowStructure.styleSheet;
374
+ if (sheet)
375
+ root.adoptedStyleSheets = [sheet];
376
+ }
377
+ return root;
378
+ }
379
+ connectedCallback() {
380
+ super.connectedCallback();
381
+ if (this.lightDom && this.noStyle) {
382
+ const node = this.getRootNode();
383
+ installLightDomStyles(`${this.localName}::structure`, unsafeCSS(structuralRules(this.localName)), {
384
+ root: node instanceof ShadowRoot || node instanceof Document ? node : undefined,
385
+ scope: false,
386
+ });
387
+ }
388
+ }
389
+ disconnectedCallback() {
390
+ super.disconnectedCallback();
391
+ this.cancelFetch();
392
+ clearTimeout(this.announceTimer);
393
+ clearTimeout(this.clearTimer);
394
+ this.open = false;
395
+ }
396
+ /* ---------- form association ---------- */
397
+ get form() {
398
+ return this.internals.form;
399
+ }
400
+ get validity() {
401
+ return this.internals.validity;
402
+ }
403
+ get validationMessage() {
404
+ return this.internals.validationMessage;
405
+ }
406
+ get willValidate() {
407
+ return this.internals.willValidate;
408
+ }
409
+ checkValidity() {
410
+ return this.internals.checkValidity();
411
+ }
412
+ reportValidity() {
413
+ return this.internals.reportValidity();
414
+ }
415
+ formResetCallback() {
416
+ this.cancelFetch();
417
+ this.open = false;
418
+ this.active = -1;
419
+ this.invalidShown = false;
420
+ this.setOwn(this.getAttribute('value') ?? '', null);
421
+ this.committed = { value: this.value, item: null };
422
+ }
423
+ formDisabledCallback(disabled) {
424
+ this.formDisabled = disabled;
425
+ }
426
+ formStateRestoreCallback(state) {
427
+ if (typeof state === 'string') {
428
+ this.setOwn(state, null);
429
+ this.committed = { value: state, item: null };
430
+ }
431
+ }
432
+ get input() {
433
+ return this.renderRoot.querySelector(`#${this.uid}-input`);
434
+ }
435
+ focus(options) {
436
+ const input = this.input;
437
+ if (input)
438
+ input.focus(options);
439
+ else
440
+ super.focus(options);
441
+ }
442
+ updateForm() {
443
+ const v = this.selected ? String(this.selected.value) : this.value;
444
+ this.internals.setFormValue(v, this.value);
445
+ const input = this.input ?? undefined;
446
+ if (this.required && !this.value.trim())
447
+ this.internals.setValidity({ valueMissing: true }, 'Fill in this field.', input);
448
+ else if (this.mustChoose && this.value.trim() && !this.selected)
449
+ this.internals.setValidity({ customError: true }, 'Choose one of the suggestions.', input);
450
+ else
451
+ this.internals.setValidity({});
452
+ }
453
+ /* ---------- data ---------- */
454
+ warnOnce(kind, message) {
455
+ if (this.warned.has(kind))
456
+ return;
457
+ this.warned.add(kind);
458
+ console.warn(`${this.localName}: ${message}`);
459
+ }
460
+ /** Read `<option>`s (direct or in a `<datalist>`) and adopt a fallback `<input>`. */
461
+ read(nodes) {
462
+ const options = [];
463
+ for (const n of nodes) {
464
+ if (n instanceof HTMLOptionElement)
465
+ options.push(n);
466
+ else if (n instanceof HTMLDataListElement)
467
+ options.push(...n.options);
468
+ else if (n instanceof HTMLInputElement) {
469
+ this.adopt(n);
470
+ if (n.list && !nodes.includes(n.list))
471
+ options.push(...n.list.options);
472
+ }
473
+ }
474
+ const entries = toEntries(options.map((o) => {
475
+ const label = normalize(o.getAttribute('label') ?? o.textContent) || o.value;
476
+ const item = { value: o.value || label, label };
477
+ const d = o.getAttribute('data-description');
478
+ if (d)
479
+ item.description = d;
480
+ if (o.disabled)
481
+ item.disabled = true;
482
+ return item;
483
+ }));
484
+ const key = (list) => list
485
+ .map((e) => `${e.value}\u0001${e.label}\u0001${e.description ?? ''}\u0001${+e.disabled}`)
486
+ .join('\u0000');
487
+ if (key(entries) !== key(this.childEntries))
488
+ this.childEntries = entries;
489
+ }
490
+ /** The no-JavaScript field: its text, name and placeholder carry over, then it is disabled. */
491
+ adopt(input) {
492
+ if (this.adopted.has(input))
493
+ return;
494
+ this.adopted.add(input);
495
+ if (!this.name && input.name)
496
+ this.name = input.name;
497
+ if (!this.placeholder && input.placeholder)
498
+ this.placeholder = input.placeholder;
499
+ if (!this.value && input.value)
500
+ this.setOwn(input.value, null);
501
+ input.disabled = true;
502
+ }
503
+ /** Local suggestions: `items` while set, else the children. */
504
+ get local() {
505
+ if (this.items) {
506
+ if (this.items !== this.itemsSource) {
507
+ this.itemsSource = this.items;
508
+ this.itemEntries = toEntries(this.items);
509
+ }
510
+ return this.itemEntries;
511
+ }
512
+ return this.childEntries;
513
+ }
514
+ /** The trimmed text, and folded for matching. */
515
+ get query() {
516
+ const text = normalize(this.value);
517
+ return { text, folded: fold(text) };
518
+ }
519
+ get max() {
520
+ const m = Math.trunc(Number(this.maxResults));
521
+ return Number.isFinite(m) && m > 0 ? m : Infinity;
522
+ }
523
+ /** Prefix matches, then word-start matches, then the rest, each in the given order. */
524
+ filter(q) {
525
+ const all = this.local;
526
+ const max = this.max;
527
+ if (!q) {
528
+ this.shown = all.slice(0, max);
529
+ this.total = all.length;
530
+ return;
531
+ }
532
+ const buckets = [[], [], []];
533
+ let total = 0;
534
+ for (const e of all) {
535
+ const i = e.fold.indexOf(q);
536
+ if (i < 0)
537
+ continue;
538
+ total++;
539
+ const b = i === 0 ? 0 : WORD.test(e.fold[i - 1]) ? 2 : 1;
540
+ if (buckets[b].length < max)
541
+ buckets[b].push(e);
542
+ }
543
+ this.shown = buckets.flat().slice(0, max);
544
+ this.total = total;
545
+ }
546
+ cancelFetch() {
547
+ clearTimeout(this.fetchTimer);
548
+ this.fetchTimer = undefined;
549
+ this.abort?.abort();
550
+ this.abort = undefined;
551
+ }
552
+ showRemote(q, entries) {
553
+ this.remote = entries;
554
+ this.remoteQuery = q;
555
+ this.loading = 'idle';
556
+ this.shown = entries.slice(0, this.max);
557
+ this.total = entries.length;
558
+ }
559
+ /** `src`: the cached response, or a fetch once typing pauses. */
560
+ request(q) {
561
+ this.cancelFetch();
562
+ const cached = this.cache.get(q);
563
+ if (cached) {
564
+ this.showRemote(q, cached);
565
+ return;
566
+ }
567
+ this.loading = 'loading';
568
+ this.fetchTimer = setTimeout(() => void this.load(q), comboboxTiming.debounce);
569
+ }
570
+ async load(q) {
571
+ const ctrl = new AbortController();
572
+ this.abort = ctrl;
573
+ const url = this.src.replaceAll('{q}', encodeURIComponent(q));
574
+ try {
575
+ const res = await fetch(new URL(url, this.ownerDocument.baseURI), {
576
+ signal: ctrl.signal,
577
+ headers: { Accept: 'application/json' },
578
+ });
579
+ if (!res.ok)
580
+ throw new Error(`HTTP ${res.status}`);
581
+ const data = await res.json();
582
+ const list = this.transform ? this.transform(data, q) : data;
583
+ if (!Array.isArray(list))
584
+ throw new Error('the response is not an array');
585
+ if (ctrl.signal.aborted)
586
+ return;
587
+ const entries = toEntries(list);
588
+ this.cache.set(q, entries);
589
+ if (this.cache.size > CACHE_SIZE)
590
+ this.cache.delete(this.cache.keys().next().value);
591
+ if (this.query.text !== q)
592
+ return;
593
+ this.showRemote(q, entries);
594
+ this.active = -1;
595
+ }
596
+ catch (err) {
597
+ if (ctrl.signal.aborted)
598
+ return;
599
+ this.loading = 'error';
600
+ this.shown = [];
601
+ this.total = 0;
602
+ this.remoteQuery = undefined;
603
+ this.warnOnce('load', `couldn't load suggestions (${err.message}).`);
604
+ trackError(this, TAG, 'load');
605
+ }
606
+ finally {
607
+ if (this.abort === ctrl)
608
+ this.abort = undefined;
609
+ }
610
+ }
611
+ /** Recompute the suggestions for the current text. */
612
+ refresh() {
613
+ const q = this.query;
614
+ if (this.src) {
615
+ if (q.text.length < this.minLength) {
616
+ this.cancelFetch();
617
+ this.loading = 'idle';
618
+ this.shown = [];
619
+ this.total = 0;
620
+ return;
621
+ }
622
+ if (q.text === this.remoteQuery && this.loading !== 'error') {
623
+ this.shown = this.remote.slice(0, this.max);
624
+ this.total = this.remote.length;
625
+ return;
626
+ }
627
+ this.request(q.text);
628
+ return;
629
+ }
630
+ this.filter(q.folded);
631
+ }
632
+ /* ---------- state changes ---------- */
633
+ setOwn(value, item) {
634
+ this.value = this.ownValue = value;
635
+ this.selected = this.ownSelected = item;
636
+ }
637
+ emit(type, detail) {
638
+ this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));
639
+ }
640
+ /** The suggestion whose label is exactly the text (ignoring case and accents), if one. */
641
+ exact() {
642
+ const q = this.query.folded;
643
+ if (!q)
644
+ return undefined;
645
+ const pool = this.src ? this.remote : this.local;
646
+ const hits = pool.filter((e) => !e.disabled && e.fold === q);
647
+ return hits.length === 1 ? hits[0] : undefined;
648
+ }
649
+ commit() {
650
+ if (!this.selected) {
651
+ const m = this.exact();
652
+ if (m)
653
+ this.setOwn(m.label, m.raw);
654
+ }
655
+ const { value, selected } = this;
656
+ this.invalidShown = this.mustChoose && !!value.trim() && !selected;
657
+ if (value === this.committed.value && selected === this.committed.item)
658
+ return;
659
+ this.committed = { value, item: selected };
660
+ this.emit('change', { value, item: selected });
661
+ }
662
+ close() {
663
+ this.open = false;
664
+ this.active = -1;
665
+ }
666
+ openList(at) {
667
+ if (this.src && this.query.text.length < this.minLength)
668
+ return;
669
+ this.refresh();
670
+ this.open = true;
671
+ this.active =
672
+ at === 'none'
673
+ ? -1
674
+ : this.step(at === 'first' ? -1 : this.shown.length, at === 'first' ? 1 : -1);
675
+ }
676
+ /** The next choosable index from `from` in `dir`, wrapping; -1 when there is none. */
677
+ step(from, dir) {
678
+ const n = this.shown.length;
679
+ for (let k = 1; k <= n; k++) {
680
+ const i = (((from + dir * k) % n) + n) % n;
681
+ if (!this.shown[i].disabled)
682
+ return i;
683
+ }
684
+ return -1;
685
+ }
686
+ choose(index) {
687
+ const e = this.shown[index];
688
+ if (!e || e.disabled)
689
+ return;
690
+ this.cancelFetch();
691
+ this.setOwn(e.label, e.raw);
692
+ this.close();
693
+ this.invalidShown = false;
694
+ this.emit('select', { item: e.raw });
695
+ trackEvent(this, [TAG, 'select', this.label.trim(), index + 1]);
696
+ this.commit();
697
+ }
698
+ clear() {
699
+ this.cancelFetch();
700
+ this.loading = 'idle';
701
+ this.setOwn('', null);
702
+ this.close();
703
+ trackEvent(this, [TAG, 'clear', this.label.trim()]);
704
+ this.commit();
705
+ this.focus();
706
+ }
707
+ /* ---------- handlers ---------- */
708
+ onInput(e) {
709
+ const text = e.target.value;
710
+ const keep = this.selected && text === normalize(this.selected.label ?? this.selected.value);
711
+ this.setOwn(text, keep ? this.selected : null);
712
+ this.invalidShown = false;
713
+ this.active = -1;
714
+ if (this.query.text.length < this.minLength) {
715
+ this.cancelFetch();
716
+ this.loading = 'idle';
717
+ this.close();
718
+ return;
719
+ }
720
+ this.refresh();
721
+ this.open = true;
722
+ }
723
+ onKeydown(e) {
724
+ if (e.isComposing)
725
+ return;
726
+ switch (e.key) {
727
+ case 'ArrowDown':
728
+ e.preventDefault();
729
+ if (e.altKey) {
730
+ if (!this.open)
731
+ this.openList('none');
732
+ }
733
+ else if (!this.open)
734
+ this.openList('first');
735
+ else
736
+ this.active = this.step(this.active, 1);
737
+ return;
738
+ case 'ArrowUp':
739
+ e.preventDefault();
740
+ if (e.altKey)
741
+ this.close();
742
+ else if (!this.open)
743
+ this.openList('last');
744
+ else
745
+ this.active = this.step(this.active < 0 ? this.shown.length : this.active, -1);
746
+ return;
747
+ case 'Enter':
748
+ if (this.open && this.active >= 0) {
749
+ e.preventDefault();
750
+ this.choose(this.active);
751
+ return;
752
+ }
753
+ this.close();
754
+ this.commit();
755
+ this.updateForm();
756
+ if (!this.lightDom && this.form) {
757
+ // A shadow field is not the form's own: submit as a native field would.
758
+ e.preventDefault();
759
+ this.submit(this.form);
760
+ }
761
+ return;
762
+ case 'Escape':
763
+ if (this.open) {
764
+ e.preventDefault();
765
+ e.stopPropagation();
766
+ this.cancelFetch();
767
+ if (this.loading === 'loading')
768
+ this.loading = 'idle';
769
+ this.close();
770
+ }
771
+ else if (this.value) {
772
+ e.preventDefault();
773
+ e.stopPropagation();
774
+ this.clear();
775
+ }
776
+ return;
777
+ case 'Home':
778
+ case 'End':
779
+ case 'ArrowLeft':
780
+ case 'ArrowRight':
781
+ this.active = -1;
782
+ return;
783
+ }
784
+ }
785
+ /** Implicit submission: click the default button, or submit when there is none. */
786
+ submit(form) {
787
+ const button = [...form.elements].find((el) => (el instanceof HTMLButtonElement || el instanceof HTMLInputElement) &&
788
+ (el.type === 'submit' || el.type === 'image'));
789
+ if (button) {
790
+ if (!button.disabled)
791
+ button.click();
792
+ return;
793
+ }
794
+ form.requestSubmit();
795
+ }
796
+ onBlur() {
797
+ this.cancelFetch();
798
+ if (this.loading === 'loading')
799
+ this.loading = 'idle';
800
+ this.close();
801
+ this.commit();
802
+ }
803
+ onOptionClick(e) {
804
+ const li = e.target.closest('[role="option"]');
805
+ if (!li)
806
+ return;
807
+ this.choose(Number(li.dataset.index));
808
+ }
809
+ /* ---------- status ---------- */
810
+ /** The visible note in the popup, and what the live region says. */
811
+ get note() {
812
+ if (this.loading === 'loading' && !this.shown.length)
813
+ return { visible: 'Loading suggestions…', spoken: 'Loading suggestions' };
814
+ if (this.loading === 'error')
815
+ return { visible: "Couldn't load suggestions", spoken: "Couldn't load suggestions" };
816
+ const n = this.shown.length;
817
+ if (!n)
818
+ return { visible: 'No suggestions', spoken: 'No suggestions' };
819
+ if (this.total > n)
820
+ return {
821
+ visible: `Showing ${count(n)} of ${count(this.total)}. Type more to narrow them.`,
822
+ spoken: `${count(n)} of ${count(this.total)} suggestions`,
823
+ };
824
+ return { visible: '', spoken: `${count(n)} suggestion${n === 1 ? '' : 's'}` };
825
+ }
826
+ scheduleAnnouncement() {
827
+ clearTimeout(this.announceTimer);
828
+ const text = this.open ? this.note.spoken : '';
829
+ if (!text) {
830
+ this.lastAnnounced = '';
831
+ return;
832
+ }
833
+ if (text === this.lastAnnounced)
834
+ return;
835
+ this.announceTimer = setTimeout(() => {
836
+ const now = this.open ? this.note.spoken : '';
837
+ if (!now || now === this.lastAnnounced)
838
+ return;
839
+ this.lastAnnounced = now;
840
+ this.announcement = now;
841
+ clearTimeout(this.clearTimer);
842
+ this.clearTimer = setTimeout(() => (this.announcement = ''), CLEAR_MS);
843
+ }, comboboxTiming.announce);
844
+ }
845
+ /* ---------- lifecycle ---------- */
846
+ willUpdate(changed) {
847
+ if (!this.label.trim())
848
+ this.warnOnce('label', 'set label: the field needs a visible label.');
849
+ if (changed.has('selected') && this.selected !== this.ownSelected) {
850
+ // Set by the app: show it.
851
+ const s = this.selected;
852
+ const e = s === null || s === undefined ? null : toEntry(s);
853
+ this.selected = this.ownSelected = e ? e.raw : null;
854
+ if (e)
855
+ this.value = this.ownValue = e.label;
856
+ this.committed = { value: this.value, item: this.selected };
857
+ }
858
+ else if (changed.has('value') && this.value !== this.ownValue) {
859
+ this.value = this.ownValue = String(this.value ?? '');
860
+ if (this.selected && this.value !== normalize(this.selected.label ?? this.selected.value))
861
+ this.selected = this.ownSelected = null;
862
+ this.committed = { value: this.value, item: this.selected };
863
+ }
864
+ if (changed.has('src') || changed.has('transform')) {
865
+ this.cache.clear();
866
+ this.remoteQuery = undefined;
867
+ }
868
+ if (this.open &&
869
+ (changed.has('items') || changed.has('childEntries') || changed.has('maxResults')))
870
+ this.refresh();
871
+ if (this.open && this.active >= this.shown.length)
872
+ this.active = -1;
873
+ }
874
+ updated(changed) {
875
+ super.updated(changed);
876
+ // The field may hold typed text the last render did not know about.
877
+ const field = this.input;
878
+ if (field && field.value !== this.value)
879
+ field.value = this.value;
880
+ if (!this.started) {
881
+ this.started = true;
882
+ this.updateForm();
883
+ return;
884
+ }
885
+ if (changed.has('value') ||
886
+ changed.has('selected') ||
887
+ changed.has('required') ||
888
+ changed.has('mustChoose'))
889
+ this.updateForm();
890
+ if (changed.has('open') ||
891
+ changed.has('shown') ||
892
+ changed.has('total') ||
893
+ changed.has('loading'))
894
+ this.scheduleAnnouncement();
895
+ if (changed.has('active') && this.active >= 0)
896
+ this.reveal();
897
+ }
898
+ /** Scroll the active suggestion into view inside the popup (not the page). */
899
+ reveal() {
900
+ const popup = this.renderRoot.querySelector('.popup');
901
+ const opt = this.renderRoot.querySelector(`#${this.uid}-opt-${this.active}`);
902
+ if (!popup || !opt)
903
+ return;
904
+ const top = opt.offsetTop;
905
+ const bottom = top + opt.offsetHeight;
906
+ if (top < popup.scrollTop)
907
+ popup.scrollTop = top;
908
+ else if (bottom > popup.scrollTop + popup.clientHeight)
909
+ popup.scrollTop = bottom - popup.clientHeight;
910
+ }
911
+ /* ---------- render ---------- */
912
+ marked(label, q) {
913
+ if (!q)
914
+ return label;
915
+ const { text, map } = foldMap(label);
916
+ const parts = [];
917
+ let last = 0;
918
+ let from = 0;
919
+ for (let i = text.indexOf(q); i !== -1; i = text.indexOf(q, from)) {
920
+ const s = map[i];
921
+ const end = map[i + q.length];
922
+ if (s > last)
923
+ parts.push(label.slice(last, s));
924
+ parts.push(html `<mark>${label.slice(s, end)}</mark>`);
925
+ last = end;
926
+ from = i + q.length;
927
+ }
928
+ parts.push(label.slice(last));
929
+ return parts;
930
+ }
931
+ render() {
932
+ const id = this.uid;
933
+ const label = this.label.trim();
934
+ const off = this.disabled || this.formDisabled;
935
+ const expanded = this.open && this.shown.length > 0;
936
+ const note = this.open ? this.note.visible : '';
937
+ const q = this.query.folded;
938
+ return html `<label class="label" part="label" id="${id}-label" for="${id}-input"
939
+ >${label}</label
940
+ >
941
+ <div class="field">
942
+ <input
943
+ id="${id}-input"
944
+ class="input"
945
+ part="input"
946
+ type="text"
947
+ role="combobox"
948
+ aria-autocomplete="list"
949
+ aria-expanded=${expanded ? 'true' : 'false'}
950
+ aria-controls="${id}-listbox"
951
+ aria-activedescendant=${expanded && this.active >= 0 ? `${id}-opt-${this.active}` : nothing}
952
+ aria-describedby=${this.description ? `${id}-description` : nothing}
953
+ aria-required=${this.required ? 'true' : nothing}
954
+ aria-invalid=${this.invalidShown ? 'true' : nothing}
955
+ autocomplete="off"
956
+ autocapitalize="off"
957
+ spellcheck="false"
958
+ placeholder=${this.placeholder || nothing}
959
+ .value=${this.value}
960
+ ?disabled=${off}
961
+ @input=${this.onInput}
962
+ @keydown=${this.onKeydown}
963
+ @blur=${this.onBlur}
964
+ @change=${(e) => e.stopPropagation()}
965
+ @select=${(e) => e.stopPropagation()}
966
+ /><button
967
+ type="button"
968
+ class="clear"
969
+ part="clear"
970
+ aria-label="Clear ${label}"
971
+ ?hidden=${!this.value || off}
972
+ @mousedown=${(e) => e.preventDefault()}
973
+ @click=${this.clear}
974
+ >
975
+ ${CLEAR_ICON}
976
+ </button>
977
+ <div
978
+ class="popup"
979
+ part="popup"
980
+ ?hidden=${!this.open || (!this.shown.length && !note)}
981
+ @mousedown=${(e) => e.preventDefault()}
982
+ >
983
+ <ul
984
+ id="${id}-listbox"
985
+ class="listbox"
986
+ role="listbox"
987
+ aria-labelledby="${id}-label"
988
+ tabindex="-1"
989
+ ?hidden=${!expanded}
990
+ @click=${this.onOptionClick}
991
+ >
992
+ ${expanded
993
+ ? this.shown.map((e, i) => html `<li
994
+ id="${id}-opt-${i}"
995
+ class="option"
996
+ part="option"
997
+ role="option"
998
+ data-index=${i}
999
+ aria-selected=${i === this.active ? 'true' : 'false'}
1000
+ aria-disabled=${e.disabled ? 'true' : nothing}
1001
+ >
1002
+ <span class="option-label">${this.marked(e.label, q)}</span>${e.description
1003
+ ? html `<span class="option-description">${e.description}</span>`
1004
+ : nothing}
1005
+ </li>`)
1006
+ : nothing}
1007
+ </ul>
1008
+ <p class="message" ?hidden=${!note}>${note}</p>
1009
+ </div>
1010
+ </div>
1011
+ <p class="description" part="description" id="${id}-description" ?hidden=${!this.description}>
1012
+ ${this.description}
1013
+ </p>
1014
+ <span class="visually-hidden" role="status" aria-live="polite" aria-atomic="true"
1015
+ >${this.announcement}</span
1016
+ >`;
1017
+ }
1018
+ }
1019
+ __decorate([
1020
+ property({ type: String })
1021
+ ], UvalibCombobox.prototype, "label", void 0);
1022
+ __decorate([
1023
+ property({ type: String })
1024
+ ], UvalibCombobox.prototype, "description", void 0);
1025
+ __decorate([
1026
+ property({ type: String })
1027
+ ], UvalibCombobox.prototype, "placeholder", void 0);
1028
+ __decorate([
1029
+ property({ type: String, reflect: true })
1030
+ ], UvalibCombobox.prototype, "name", void 0);
1031
+ __decorate([
1032
+ property({ type: String })
1033
+ ], UvalibCombobox.prototype, "value", void 0);
1034
+ __decorate([
1035
+ property({ attribute: false })
1036
+ ], UvalibCombobox.prototype, "selected", void 0);
1037
+ __decorate([
1038
+ property({ attribute: false })
1039
+ ], UvalibCombobox.prototype, "items", void 0);
1040
+ __decorate([
1041
+ property({ type: String })
1042
+ ], UvalibCombobox.prototype, "src", void 0);
1043
+ __decorate([
1044
+ property({ attribute: false })
1045
+ ], UvalibCombobox.prototype, "transform", void 0);
1046
+ __decorate([
1047
+ property({ type: Number, attribute: 'min-length' })
1048
+ ], UvalibCombobox.prototype, "minLength", void 0);
1049
+ __decorate([
1050
+ property({ type: Number, attribute: 'max-results' })
1051
+ ], UvalibCombobox.prototype, "maxResults", void 0);
1052
+ __decorate([
1053
+ property({ type: Boolean, attribute: 'must-choose' })
1054
+ ], UvalibCombobox.prototype, "mustChoose", void 0);
1055
+ __decorate([
1056
+ property({ type: Boolean, reflect: true })
1057
+ ], UvalibCombobox.prototype, "required", void 0);
1058
+ __decorate([
1059
+ property({ type: Boolean, reflect: true })
1060
+ ], UvalibCombobox.prototype, "disabled", void 0);
1061
+ __decorate([
1062
+ state()
1063
+ ], UvalibCombobox.prototype, "open", void 0);
1064
+ __decorate([
1065
+ state()
1066
+ ], UvalibCombobox.prototype, "active", void 0);
1067
+ __decorate([
1068
+ state()
1069
+ ], UvalibCombobox.prototype, "shown", void 0);
1070
+ __decorate([
1071
+ state()
1072
+ ], UvalibCombobox.prototype, "total", void 0);
1073
+ __decorate([
1074
+ state()
1075
+ ], UvalibCombobox.prototype, "loading", void 0);
1076
+ __decorate([
1077
+ state()
1078
+ ], UvalibCombobox.prototype, "announcement", void 0);
1079
+ __decorate([
1080
+ state()
1081
+ ], UvalibCombobox.prototype, "formDisabled", void 0);
1082
+ __decorate([
1083
+ state()
1084
+ ], UvalibCombobox.prototype, "invalidShown", void 0);
1085
+ __decorate([
1086
+ state()
1087
+ ], UvalibCombobox.prototype, "childEntries", void 0);
1088
+ //# sourceMappingURL=UvalibCombobox.js.map