@uvalib/web-components 1.9.0 → 1.10.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 (48) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +235 -14
  3. package/bin/install-skill.mjs +174 -54
  4. package/dist/base.css +115 -2
  5. package/dist/components/uvalib-list-filter/UvalibListFilter.d.ts +162 -0
  6. package/dist/components/uvalib-list-filter/UvalibListFilter.js +685 -0
  7. package/dist/components/uvalib-list-filter/UvalibListFilter.js.map +1 -0
  8. package/dist/components/uvalib-list-filter/uvalib-list-filter.d.ts +1 -0
  9. package/dist/components/uvalib-list-filter/uvalib-list-filter.js +4 -0
  10. package/dist/components/uvalib-list-filter/uvalib-list-filter.js.map +1 -0
  11. package/dist/components/uvalib-pagefind-search/UvalibPagefindSearch.d.ts +28 -1
  12. package/dist/components/uvalib-pagefind-search/UvalibPagefindSearch.js +139 -3
  13. package/dist/components/uvalib-pagefind-search/UvalibPagefindSearch.js.map +1 -1
  14. package/dist/custom-elements.json +7502 -6348
  15. package/dist/edition.css +758 -0
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.js +1 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/styles/base.js +72 -1
  20. package/dist/styles/base.js.map +1 -1
  21. package/dist/styles/controls.js +2 -0
  22. package/dist/styles/controls.js.map +1 -1
  23. package/dist/styles/edition.d.ts +1 -0
  24. package/dist/styles/edition.js +747 -0
  25. package/dist/styles/edition.js.map +1 -0
  26. package/dist/styles/hidden.js +2 -0
  27. package/dist/styles/hidden.js.map +1 -1
  28. package/dist/styles/layout.d.ts +1 -0
  29. package/dist/styles/layout.js +92 -0
  30. package/dist/styles/layout.js.map +1 -0
  31. package/dist-cdn/base.css +115 -2
  32. package/dist-cdn/chunks/{base-CHMHBPeI.js → base-DXkGlSgH.js} +73 -2
  33. package/dist-cdn/chunks/base-DXkGlSgH.js.map +1 -0
  34. package/dist-cdn/custom-elements.json +7502 -6348
  35. package/dist-cdn/edition.css +758 -0
  36. package/dist-cdn/manifest.json +5 -3
  37. package/dist-cdn/site-page.js +1 -1
  38. package/dist-cdn/site-style.js +1 -1
  39. package/dist-cdn/skills/uvalib-web-components/SKILL.md +29 -8
  40. package/dist-cdn/skills/uvalib-web-components/reference/components.md +53 -1
  41. package/dist-cdn/uvalib-list-filter.js +451 -0
  42. package/dist-cdn/uvalib-list-filter.js.map +1 -0
  43. package/dist-cdn/uvalib-pagefind-search.js +118 -48
  44. package/dist-cdn/uvalib-pagefind-search.js.map +1 -1
  45. package/package.json +6 -1
  46. package/skills/uvalib-web-components/SKILL.md +29 -8
  47. package/skills/uvalib-web-components/reference/components.md +53 -1
  48. package/dist-cdn/chunks/base-CHMHBPeI.js.map +0 -1
@@ -0,0 +1,685 @@
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 { trackEvent } from '../../base/analytics.js';
10
+ import { UvalibElement } from '../../base/UvalibElement.js';
11
+ import { installLightDomStyles } from '../../base/light-dom-styles.js';
12
+ import { hrefWithParam, paramFromLocation } from '../../base/url-param.js';
13
+ import { accessible } from '../../styles/accessible.js';
14
+ import { message } from '../../styles/message.js';
15
+ const TAG = 'uvalib-list-filter';
16
+ /**
17
+ * How long (ms) the filter must stay put before it is announced and reported to analytics
18
+ * (as `<uvalib-results-count>` and the date range settle), and before it is written to the
19
+ * URL. Tests may shorten them.
20
+ */
21
+ export const listFilterTiming = { settle: 1000, url: 250 };
22
+ /** How long an announcement stays in the live region before it is cleared. */
23
+ const CLEAR_MS = 5000;
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
+ /** The query's words, folded: every one must appear in an item, in any order. */
29
+ export const queryWords = (q) => fold(q).split(/\s+/).filter(Boolean);
30
+ /** The same words in any case or order are the same query (for analytics). */
31
+ const queryKey = (q) => queryWords(q).toSorted().join(' ');
32
+ const count = (n) => n.toLocaleString('en-US');
33
+ /**
34
+ * Hidden items stay hidden whatever `display` the page gives them: one unlayered sheet per
35
+ * root (document or shadow root). It only reaches the direct children of the item and group
36
+ * parents this element marks, so other `[hidden]` content on the page is left alone.
37
+ */
38
+ const guards = new WeakMap();
39
+ const MARK = 'data-uvalib-list-filter';
40
+ function installGuard(root) {
41
+ let sheet = guards.get(root);
42
+ if (!sheet) {
43
+ const doc = root.ownerDocument ?? root;
44
+ const Ctor = doc.defaultView?.CSSStyleSheet ?? CSSStyleSheet;
45
+ sheet = new Ctor();
46
+ sheet.replaceSync(`:where([${MARK}]) > [hidden] { display: none !important; }`);
47
+ guards.set(root, sheet);
48
+ }
49
+ if (!root.adoptedStyleSheets.includes(sheet))
50
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
51
+ }
52
+ 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>`;
53
+ /**
54
+ * Kept with `no-style`: the label above a 44px field, the 44px clear button inside its end,
55
+ * the visually hidden text, and `[hidden]`. `host` is `:host` or the tag.
56
+ */
57
+ const structuralRules = (host) => `
58
+ ${host} { display: block; max-width: 100%; font-size: 1rem; line-height: 1.5; }
59
+ ${host} .label { display: block; margin-block-end: 0.25rem; }
60
+ ${host} .field { position: relative; }
61
+ ${host} .input {
62
+ display: block;
63
+ box-sizing: border-box;
64
+ inline-size: 100%;
65
+ min-block-size: 44px;
66
+ margin: 0;
67
+ padding-inline-end: 44px;
68
+ font: inherit;
69
+ line-height: 1.2;
70
+ }
71
+ ${host} .input::-webkit-search-cancel-button { -webkit-appearance: none; appearance: none; }
72
+ ${host} .clear {
73
+ position: absolute;
74
+ inset-block-start: 0;
75
+ inset-inline-end: 0;
76
+ display: inline-flex;
77
+ align-items: center;
78
+ justify-content: center;
79
+ box-sizing: border-box;
80
+ inline-size: 44px;
81
+ block-size: 44px;
82
+ margin: 0;
83
+ padding: 0;
84
+ cursor: pointer;
85
+ }
86
+ ${host} .count { margin: 0.25rem 0 0; }
87
+ ${host} .visually-hidden {
88
+ position: absolute;
89
+ width: 1px;
90
+ height: 1px;
91
+ margin: -1px;
92
+ padding: 0;
93
+ overflow: hidden;
94
+ clip: rect(0, 0, 0, 0);
95
+ white-space: nowrap;
96
+ border: 0;
97
+ }
98
+ ${host}[hidden], ${host} [hidden] { display: none !important; }
99
+ `;
100
+ const shadowStructure = unsafeCSS(structuralRules(':host'));
101
+ const BORDER = unsafeCSS('var(--uva-color-control-border, var(--uva-grey, #808080))');
102
+ const MUTED = unsafeCSS('var(--uva-color-text-muted, var(--uva-grey-A, #4f4f4f))');
103
+ const TEXT = unsafeCSS('var(--uva-color-input-text, var(--uva-grey-darkest, #2b2b2b))');
104
+ const RAISED = unsafeCSS('var(--uva-color-surface-raised, #ffffff)');
105
+ /**
106
+ * A text field that filters a long list on the page as you type: a collection's 473 texts, a
107
+ * staff directory, a table of databases. The list is the page's own markup and stays fully
108
+ * visible without the script.
109
+ *
110
+ * `for` is the id of the list: any element whose children are the items (a `<ul>` or `<ol>`,
111
+ * a `<dl>` of `<div>` rows, a grid of cards; for a `<table>`, the rows of its bodies).
112
+ * `selector` picks the items instead (inside `for` when both are set, else in the page).
113
+ * An item matches when every word typed appears in its `data-filter-text`, or else its text,
114
+ * in any order, ignoring case and accents (“eneide” finds “Énéide”). Items that do not match
115
+ * get the `hidden` attribute (kept hidden whatever `display` the page gives them); clearing
116
+ * the field shows them all again. Thousands of items filter at once on every keystroke: the
117
+ * text is read once, and only items whose state changes are touched.
118
+ *
119
+ * Groups: give each group's wrapper `data-filter-group` (a `<section>` with its heading and
120
+ * its list) and point `selector` at the items; a group whose items are all hidden is hidden
121
+ * too, heading and all.
122
+ *
123
+ * The visible `label` (default “Filter”; `hide-label` hides it visually) names the field, and
124
+ * a Clear button (“Clear <label>”, 44px, shown only with text) or Escape empties it, keeping
125
+ * focus in the field. Under the field a count follows at once (“Showing 12 of 473 texts”;
126
+ * `noun`, plural, and `singular` name the items), and a polite status announces it once the
127
+ * typing settles (a second after the last keystroke), never on every key or at load. When
128
+ * nothing matches, a message says “No texts match “…”.” To put the count elsewhere, point
129
+ * `results-count` at a `<uvalib-results-count>` (give it `total` and `noun` in the markup):
130
+ * the element then sets its `shown` and `total` and leaves the count and announcement to it.
131
+ *
132
+ * With `query-param` (bare: `filter`) the filter is read from that URL parameter at start
133
+ * and written back with `history.replaceState` as you type, so a filtered list can be shared
134
+ * and Back returns to it. The list's content is read once; call `refresh()` after changing an
135
+ * item's text in script (added or removed items and `data-filter-text` changes are noticed).
136
+ *
137
+ * Before it upgrades, `base.css` holds the label, field and count's height, so nothing moves.
138
+ *
139
+ * @tagname uvalib-list-filter
140
+ * @fires uvalib-list-filter-change - The filter was applied with a new query (typing, Clear, Escape, `value` set in script, the URL at start, Back and Forward). `detail` is `{ query, shown, total }`. Not fired at load without a query. Bubbles and is composed.
141
+ * @fires uvalib-analytics-event - For `<site-analytics>`, on the visitor's actions only: `['uvalib-list-filter', 'filter', '', <shown>]` once the typing settles on a new query, and `['uvalib-list-filter', 'clear']` when the visitor empties the field. Never the typed text. Bubbles and is composed.
142
+ * @csspart label - The visible label.
143
+ * @csspart field - The box around the field and its clear button.
144
+ * @csspart input - The text field.
145
+ * @csspart clear - The clear button.
146
+ * @csspart count - The visible count under the field.
147
+ * @csspart empty - The “No … match” message.
148
+ * @cssprop --uva-color-surface-raised - Dark-mode role token: field background (else #fff).
149
+ * @cssprop --uva-color-control-border - Dark-mode role token: field border (else `--uva-grey`, #808080).
150
+ * @cssprop --uva-color-input-text - Dark-mode role token: field text (else #2b2b2b).
151
+ * @cssprop --uva-color-text - Dark-mode role token: label text (else #2b2b2b).
152
+ * @cssprop --uva-color-text-muted - Dark-mode role token: placeholder, count and the clear icon (else #4f4f4f).
153
+ * @cssprop --uva-color-alert-info-bg - Dark-mode role token: the no-match message background.
154
+ * @cssprop --uva-color-focus - Dark-mode role token: focus ring (else `--uva-brand-orange`).
155
+ */
156
+ export class UvalibListFilter extends UvalibElement {
157
+ constructor() {
158
+ super(...arguments);
159
+ /** The id of the list whose children are the items (for a table, its body rows). */
160
+ this.htmlFor = '';
161
+ /** A CSS selector for the items, inside `for` when it is set, else in the page. */
162
+ this.selector = '';
163
+ /** The field's visible label and accessible name. */
164
+ this.label = 'Filter';
165
+ /** Hide the label visually (it still names the field), when a heading beside it says it. */
166
+ this.hideLabel = false;
167
+ /** Placeholder text in the empty field, such as “Title or author”. */
168
+ this.placeholder = '';
169
+ /** What the items are, plural: “items” by default. */
170
+ this.noun = 'items';
171
+ /** What one item is. Default: “item” when `noun` is unset, else `noun`. */
172
+ this.singular = '';
173
+ /** The id of a `<uvalib-results-count>` to drive instead of the element's own count. */
174
+ this.resultsCount = '';
175
+ /**
176
+ * The URL parameter to read the filter from and write it to; a bare attribute uses
177
+ * `filter`. Off by default.
178
+ */
179
+ this.queryParam = null;
180
+ /** The text in the field. Setting it filters the list (not reported to analytics). */
181
+ this.value = '';
182
+ this.shownCount = 0;
183
+ this.totalCount = 0;
184
+ /** The query the shown counts belong to. */
185
+ this.appliedQuery = '';
186
+ this.announcement = '';
187
+ this.uid = `${TAG}-${++uid}`;
188
+ this.started = false;
189
+ this.warned = false;
190
+ /** The words of the last query reported to analytics (or restored), joined. */
191
+ this.reported = '';
192
+ this.onInput = (e) => {
193
+ e.stopPropagation();
194
+ this.value = e.target.value;
195
+ this.apply(true);
196
+ };
197
+ this.onKeydown = (e) => {
198
+ if (e.key !== 'Escape' || !this.value)
199
+ return;
200
+ e.preventDefault();
201
+ this.clear();
202
+ };
203
+ this.clear = () => {
204
+ const input = this.input;
205
+ if (input)
206
+ input.value = '';
207
+ this.value = '';
208
+ this.apply(true);
209
+ input?.focus();
210
+ trackEvent(this, [TAG, 'clear']);
211
+ this.reported = '';
212
+ };
213
+ this.flushUrl = () => {
214
+ if (this.urlTimer === undefined)
215
+ return;
216
+ clearTimeout(this.urlTimer);
217
+ this.urlTimer = undefined;
218
+ const name = this.param;
219
+ if (!name)
220
+ return;
221
+ const q = this.value.trim();
222
+ if ((paramFromLocation(location, name) ?? '') === q)
223
+ return;
224
+ try {
225
+ history.replaceState(history.state, '', hrefWithParam(location, name, q || null));
226
+ }
227
+ catch {
228
+ // A document whose URL cannot change (about:srcdoc), or too many changes: skip the URL.
229
+ }
230
+ };
231
+ /** Back and Forward: follow the URL's filter. */
232
+ this.onPopState = () => {
233
+ if (!this.started || !this.param)
234
+ return;
235
+ const q = this.urlQuery() ?? '';
236
+ if (q === this.value)
237
+ return;
238
+ this.value = q;
239
+ this.reported = queryKey(q);
240
+ this.apply();
241
+ };
242
+ }
243
+ static { this.styles = [
244
+ accessible,
245
+ shadowStructure,
246
+ message,
247
+ css `
248
+ :host {
249
+ color: var(--uva-color-text, var(--uva-grey-darkest, #2b2b2b));
250
+ }
251
+ .label {
252
+ font-weight: 600;
253
+ }
254
+ .field {
255
+ max-inline-size: 36rem;
256
+ }
257
+ .input {
258
+ padding-block: 0.5rem;
259
+ padding-inline-start: 0.75rem;
260
+ border: 1px solid ${BORDER};
261
+ border-radius: 5px;
262
+ background: ${RAISED};
263
+ color: ${TEXT};
264
+ }
265
+ .input::placeholder {
266
+ color: ${MUTED};
267
+ opacity: 1;
268
+ }
269
+ .clear {
270
+ border: 0;
271
+ border-radius: 5px;
272
+ background: none;
273
+ color: ${MUTED};
274
+ }
275
+ .clear:hover {
276
+ color: ${TEXT};
277
+ }
278
+ .clear:focus-visible {
279
+ outline-offset: -4px;
280
+ }
281
+ .count {
282
+ color: ${MUTED};
283
+ }
284
+ .uvalib-message {
285
+ margin-block: 0.75rem 0;
286
+ }
287
+ @media (forced-colors: active) {
288
+ .input {
289
+ border-color: CanvasText;
290
+ }
291
+ .clear {
292
+ color: ButtonText;
293
+ }
294
+ }
295
+ `,
296
+ ]; }
297
+ /** How many items match now. */
298
+ get shown() {
299
+ return this.shownCount;
300
+ }
301
+ /** How many items the list has. */
302
+ get total() {
303
+ return this.totalCount;
304
+ }
305
+ createRenderRoot() {
306
+ const root = super.createRenderRoot();
307
+ if (root instanceof ShadowRoot && this.noStyle) {
308
+ const sheet = shadowStructure.styleSheet;
309
+ if (sheet)
310
+ root.adoptedStyleSheets = [sheet];
311
+ }
312
+ return root;
313
+ }
314
+ connectedCallback() {
315
+ super.connectedCallback();
316
+ if (this.lightDom && this.noStyle) {
317
+ const node = this.getRootNode();
318
+ installLightDomStyles(`${this.localName}::structure`, unsafeCSS(structuralRules(this.localName)), {
319
+ root: node instanceof ShadowRoot || node instanceof Document ? node : undefined,
320
+ scope: false,
321
+ });
322
+ }
323
+ window.addEventListener('popstate', this.onPopState);
324
+ window.addEventListener('pagehide', this.flushUrl);
325
+ // Moved in the page: read the list again and filter it as before.
326
+ if (this.started)
327
+ this.reset();
328
+ }
329
+ disconnectedCallback() {
330
+ super.disconnectedCallback();
331
+ window.removeEventListener('popstate', this.onPopState);
332
+ window.removeEventListener('pagehide', this.flushUrl);
333
+ clearTimeout(this.settleTimer);
334
+ clearTimeout(this.clearing);
335
+ this.flushUrl();
336
+ this.observer?.disconnect();
337
+ this.observed = undefined;
338
+ // Without the field there is no way to clear the filter: show the whole list again.
339
+ this.showAll();
340
+ }
341
+ /** The list may come after the element in a page still loading: wait for it then. */
342
+ begin() {
343
+ if (document.readyState === 'loading' && !this.collect())
344
+ document.addEventListener('DOMContentLoaded', () => this.start(), { once: true });
345
+ else
346
+ this.start();
347
+ }
348
+ start() {
349
+ if (this.started || !this.isConnected)
350
+ return;
351
+ this.started = true;
352
+ const fromUrl = this.urlQuery();
353
+ if (fromUrl !== null)
354
+ this.value = fromUrl;
355
+ this.reported = queryKey(this.value);
356
+ this.apply();
357
+ }
358
+ // Filtering in willUpdate: the counts it sets render in the same update.
359
+ willUpdate(changed) {
360
+ if (!this.hasUpdated)
361
+ return this.begin();
362
+ if (!this.started)
363
+ return;
364
+ if (changed.has('htmlFor') || changed.has('selector'))
365
+ this.reset();
366
+ else if (changed.has('value') && this.value !== this.appliedQuery)
367
+ this.apply();
368
+ }
369
+ /** Read the list again (an item's text changed in script) and filter it with the current text. */
370
+ refresh() {
371
+ if (this.started)
372
+ this.reset();
373
+ }
374
+ reset() {
375
+ this.showAll();
376
+ this.index = undefined;
377
+ this.apply();
378
+ }
379
+ // ---- the list
380
+ lookupRoot() {
381
+ const node = this.getRootNode();
382
+ return node instanceof ShadowRoot || node instanceof Document ? node : document;
383
+ }
384
+ /** The `for` element, if any. */
385
+ target() {
386
+ return this.htmlFor ? this.lookupRoot().getElementById(this.htmlFor) : null;
387
+ }
388
+ collect() {
389
+ const scope = this.target();
390
+ if (this.htmlFor && !scope)
391
+ return null;
392
+ let found;
393
+ if (this.selector) {
394
+ try {
395
+ found = [...(scope ?? this.lookupRoot()).querySelectorAll(this.selector)];
396
+ }
397
+ catch {
398
+ return null;
399
+ }
400
+ }
401
+ else if (!scope)
402
+ return null;
403
+ else if (scope instanceof HTMLTableElement)
404
+ found = [...scope.tBodies].flatMap((b) => [...b.rows]);
405
+ else
406
+ found = [...scope.children];
407
+ return found.filter((e) => e instanceof HTMLElement);
408
+ }
409
+ build() {
410
+ const items = this.collect();
411
+ if (!items) {
412
+ if (!this.warned) {
413
+ this.warned = true;
414
+ console.warn(`<${TAG}>: no list found; set "for" to the id of the list, or "selector" to its items.`);
415
+ }
416
+ return undefined;
417
+ }
418
+ const group = items.map((el) => el.parentElement?.closest('[data-filter-group]') ?? null);
419
+ const groups = [...new Set(group.filter((g) => g !== null))];
420
+ const root = items[0]?.getRootNode();
421
+ if (root instanceof Document || root instanceof ShadowRoot)
422
+ installGuard(root);
423
+ for (const parent of new Set([...items, ...groups].map((e) => e.parentElement)))
424
+ parent?.setAttribute(MARK, '');
425
+ this.observe();
426
+ return { items, hidden: items.map((el) => el.hidden), group, groups };
427
+ }
428
+ /** Added or removed items, and data-filter-text changes, read the list again. */
429
+ observe() {
430
+ const scope = this.target();
431
+ if (!scope || scope === this.observed)
432
+ return;
433
+ this.observer?.disconnect();
434
+ this.observer ??= new MutationObserver(() => {
435
+ this.index = undefined;
436
+ this.apply();
437
+ });
438
+ this.observer.observe(scope, {
439
+ childList: true,
440
+ subtree: true,
441
+ attributes: true,
442
+ attributeFilter: ['data-filter-text'],
443
+ });
444
+ this.observed = scope;
445
+ }
446
+ textOf(idx) {
447
+ idx.text ??= idx.items.map((el) => fold(el.dataset.filterText ?? el.textContent ?? ''));
448
+ return idx.text;
449
+ }
450
+ /** Show or hide every item for the current text (`user`: typed, so settle, report and write the URL). */
451
+ apply(user = false) {
452
+ this.index ??= this.build();
453
+ const idx = this.index;
454
+ const query = this.value;
455
+ const prevQuery = this.appliedQuery;
456
+ this.appliedQuery = query;
457
+ if (!idx) {
458
+ this.shownCount = this.totalCount = 0;
459
+ return;
460
+ }
461
+ const words = queryWords(query);
462
+ const text = words.length ? this.textOf(idx) : [];
463
+ const { items, hidden, group } = idx;
464
+ const visible = new Map();
465
+ let shown = 0;
466
+ for (let i = 0; i < items.length; i++) {
467
+ let hide = false;
468
+ if (words.length) {
469
+ const t = text[i];
470
+ for (const w of words) {
471
+ if (!t.includes(w)) {
472
+ hide = true;
473
+ break;
474
+ }
475
+ }
476
+ }
477
+ if (hidden[i] !== hide) {
478
+ hidden[i] = hide;
479
+ items[i].hidden = hide;
480
+ }
481
+ if (!hide) {
482
+ shown++;
483
+ const g = group[i];
484
+ if (g)
485
+ visible.set(g, (visible.get(g) ?? 0) + 1);
486
+ }
487
+ }
488
+ for (const g of idx.groups) {
489
+ const hide = !visible.has(g);
490
+ if (g.hidden !== hide)
491
+ g.hidden = hide;
492
+ }
493
+ const changed = query !== prevQuery || shown !== this.shownCount || items.length !== this.totalCount;
494
+ this.shownCount = shown;
495
+ this.totalCount = items.length;
496
+ this.driveResultsCount();
497
+ if (changed && (query || prevQuery))
498
+ this.dispatchEvent(new CustomEvent('uvalib-list-filter-change', {
499
+ detail: { query, shown, total: items.length },
500
+ bubbles: true,
501
+ composed: true,
502
+ }));
503
+ if (user) {
504
+ clearTimeout(this.settleTimer);
505
+ this.settleTimer = setTimeout(() => this.settle(), listFilterTiming.settle);
506
+ clearTimeout(this.urlTimer);
507
+ this.urlTimer = setTimeout(this.flushUrl, listFilterTiming.url);
508
+ }
509
+ }
510
+ showAll() {
511
+ const idx = this.index;
512
+ if (!idx)
513
+ return;
514
+ idx.items.forEach((el, i) => {
515
+ if (idx.hidden[i])
516
+ el.hidden = idx.hidden[i] = false;
517
+ });
518
+ for (const g of idx.groups)
519
+ g.hidden = false;
520
+ }
521
+ externalCount() {
522
+ return this.resultsCount ? this.lookupRoot().getElementById(this.resultsCount) : null;
523
+ }
524
+ driveResultsCount() {
525
+ const rc = this.externalCount();
526
+ if (!rc)
527
+ return;
528
+ rc.total = this.totalCount;
529
+ rc.shown = this.shownCount;
530
+ }
531
+ // ---- what the visitor sees and hears
532
+ word(n) {
533
+ const plural = this.noun.trim() || 'items';
534
+ if (n !== 1)
535
+ return plural;
536
+ return this.singular.trim() || (plural === 'items' ? 'item' : plural);
537
+ }
538
+ /** The visible count: “Showing 12 of 473 texts”, “Showing all 473 texts”. */
539
+ get countText() {
540
+ const total = this.totalCount;
541
+ const shown = this.shownCount;
542
+ if (!total)
543
+ return this.started && this.index ? `No ${this.word(0)}` : '';
544
+ if (shown < total)
545
+ return `Showing ${count(shown)} of ${count(total)} ${this.word(total)}`;
546
+ if (total === 1)
547
+ return `Showing 1 ${this.word(1)}`;
548
+ return `Showing all ${count(total)} ${this.word(total)}`;
549
+ }
550
+ get emptyText() {
551
+ const q = this.appliedQuery.trim();
552
+ return this.totalCount && !this.shownCount && q ? `No ${this.word(0)} match “${q}”.` : '';
553
+ }
554
+ /** The typing settled: announce the count, and report a new query. */
555
+ settle() {
556
+ if (!this.externalCount())
557
+ this.announce(this.emptyText || this.countText);
558
+ const key = queryKey(this.value);
559
+ if (key === this.reported)
560
+ return;
561
+ if (key)
562
+ trackEvent(this, [TAG, 'filter', '', this.shownCount]);
563
+ else
564
+ trackEvent(this, [TAG, 'clear']);
565
+ this.reported = key;
566
+ }
567
+ announce(text) {
568
+ if (!text)
569
+ return;
570
+ clearTimeout(this.clearing);
571
+ const say = () => {
572
+ this.announcement = text;
573
+ this.clearing = setTimeout(() => (this.announcement = ''), CLEAR_MS);
574
+ };
575
+ // The same words still in the region would not be read again: empty it first.
576
+ if (this.announcement === text) {
577
+ this.announcement = '';
578
+ void this.updateComplete.then(() => requestAnimationFrame(say));
579
+ }
580
+ else
581
+ say();
582
+ }
583
+ get input() {
584
+ return this.renderRoot.querySelector(`#${this.uid}-input`);
585
+ }
586
+ // ---- the URL
587
+ get param() {
588
+ const p = this.queryParam;
589
+ return p === null ? '' : p.trim() || 'filter';
590
+ }
591
+ /** The filter in the URL, or null with `query-param` off or the parameter missing. */
592
+ urlQuery() {
593
+ const name = this.param;
594
+ return name ? paramFromLocation(location, name) : null;
595
+ }
596
+ render() {
597
+ const id = this.uid;
598
+ const label = this.label.trim() || 'Filter';
599
+ const own = !this.resultsCount;
600
+ const empty = this.emptyText;
601
+ return html `<label
602
+ class="label ${this.hideLabel ? 'visually-hidden' : ''}"
603
+ part="label"
604
+ for="${id}-input"
605
+ >${label}</label
606
+ >
607
+ <div class="field" part="field">
608
+ <input
609
+ id="${id}-input"
610
+ class="input"
611
+ part="input"
612
+ type="search"
613
+ autocomplete="off"
614
+ autocapitalize="off"
615
+ spellcheck="false"
616
+ enterkeyhint="search"
617
+ placeholder=${this.placeholder || nothing}
618
+ .value=${this.value}
619
+ @input=${this.onInput}
620
+ @keydown=${this.onKeydown}
621
+ @change=${(e) => e.stopPropagation()}
622
+ /><button
623
+ type="button"
624
+ class="clear"
625
+ part="clear"
626
+ aria-label="Clear ${label}"
627
+ ?hidden=${!this.value}
628
+ @mousedown=${(e) => e.preventDefault()}
629
+ @click=${this.clear}
630
+ >
631
+ ${CLEAR_ICON}
632
+ </button>
633
+ </div>
634
+ ${own ? html `<p class="count" part="count">${this.countText}</p>` : nothing}
635
+ <p class="uvalib-message" part="empty" ?hidden=${!empty}>${empty}</p>
636
+ ${own
637
+ ? html `<span class="visually-hidden" role="status" aria-live="polite" aria-atomic="true"
638
+ >${this.announcement}</span
639
+ >`
640
+ : nothing}`;
641
+ }
642
+ }
643
+ __decorate([
644
+ property({ type: String, attribute: 'for' })
645
+ ], UvalibListFilter.prototype, "htmlFor", void 0);
646
+ __decorate([
647
+ property({ type: String })
648
+ ], UvalibListFilter.prototype, "selector", void 0);
649
+ __decorate([
650
+ property({ type: String })
651
+ ], UvalibListFilter.prototype, "label", void 0);
652
+ __decorate([
653
+ property({ type: Boolean, reflect: true, attribute: 'hide-label' })
654
+ ], UvalibListFilter.prototype, "hideLabel", void 0);
655
+ __decorate([
656
+ property({ type: String })
657
+ ], UvalibListFilter.prototype, "placeholder", void 0);
658
+ __decorate([
659
+ property({ type: String })
660
+ ], UvalibListFilter.prototype, "noun", void 0);
661
+ __decorate([
662
+ property({ type: String })
663
+ ], UvalibListFilter.prototype, "singular", void 0);
664
+ __decorate([
665
+ property({ type: String, attribute: 'results-count' })
666
+ ], UvalibListFilter.prototype, "resultsCount", void 0);
667
+ __decorate([
668
+ property({ type: String, attribute: 'query-param' })
669
+ ], UvalibListFilter.prototype, "queryParam", void 0);
670
+ __decorate([
671
+ property({ type: String })
672
+ ], UvalibListFilter.prototype, "value", void 0);
673
+ __decorate([
674
+ state()
675
+ ], UvalibListFilter.prototype, "shownCount", void 0);
676
+ __decorate([
677
+ state()
678
+ ], UvalibListFilter.prototype, "totalCount", void 0);
679
+ __decorate([
680
+ state()
681
+ ], UvalibListFilter.prototype, "appliedQuery", void 0);
682
+ __decorate([
683
+ state()
684
+ ], UvalibListFilter.prototype, "announcement", void 0);
685
+ //# sourceMappingURL=UvalibListFilter.js.map