tablefilter 0.7.13 → 0.7.15

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.
@@ -0,0 +1,415 @@
1
+ /**
2
+ * `<tf-popup-filter>`: accessible column filter popup with an open shadow
3
+ * root. The `trigger` slot holds consumer icons; the element renders its own
4
+ * button when it is empty. The default slot projects filter content into a
5
+ * non-modal `role="dialog"` popup.
6
+ *
7
+ * Attributes: `trigger-text`, `accessible-label`, `accessible-popup-label`,
8
+ * `open`, `disabled`. Methods: `setText()`, `setLabel()`, `setPopupLabel()`,
9
+ * `setOpen()`. State changes emit composed `open-change` with
10
+ * `detail: {open}`.
11
+ *
12
+ * Opening focuses the first focusable filter control or the popup. `Escape`
13
+ * and outside pointer presses close it; focus returns to the trigger.
14
+ * Popup state is mirrored onto a slotted trigger. Styling uses `::part()`;
15
+ * importing this module registers the element.
16
+ */
17
+
18
+ const TRIGGER_ID = 'trigger';
19
+ const POPUP_ID = 'popup';
20
+
21
+ // Controls that take focus, used for the projected filter content and for
22
+ // picking the focus target inside slotted trigger markup. Matches
23
+ // FOCUSABLE_TRIGGER in modules/help.js.
24
+ const FOCUSABLE = 'button:not([disabled]), a[href], ' +
25
+ 'input:not([disabled]), select:not([disabled]), ' +
26
+ 'textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
27
+
28
+ // Cloned into every instance's shadow root. Structure and `part` hooks
29
+ // only: no class or presentational style is baked in.
30
+ const TEMPLATE = document.createElement('template');
31
+ TEMPLATE.innerHTML = `
32
+ <slot name="trigger" part="trigger-slot"></slot>
33
+ <button type="button" part="trigger" id="${TRIGGER_ID}"
34
+ aria-haspopup="dialog" aria-expanded="false"
35
+ aria-controls="${POPUP_ID}">
36
+ <span part="trigger-text"></span>
37
+ </button>
38
+ <div part="popup" id="${POPUP_ID}" role="dialog"
39
+ aria-labelledby="${TRIGGER_ID}" tabindex="-1" hidden>
40
+ <slot part="content-slot"></slot>
41
+ </div>
42
+ `;
43
+
44
+ export class TfPopupFilterElement extends HTMLElement {
45
+ constructor() {
46
+ super();
47
+ this.attachShadow({ mode: 'open' });
48
+ this.shadowRoot.appendChild(TEMPLATE.content.cloneNode(true));
49
+ this._triggerSlot =
50
+ this.shadowRoot.querySelector('slot[name="trigger"]');
51
+ this._trigger = this.shadowRoot.querySelector('[part="trigger"]');
52
+ this._triggerText =
53
+ this.shadowRoot.querySelector('[part="trigger-text"]');
54
+ this._popup = this.shadowRoot.querySelector('[part="popup"]');
55
+ this._contentSlot =
56
+ this.shadowRoot.querySelector('slot[part="content-slot"]');
57
+ this._reportedOpen = false;
58
+ // Assigned trigger attributes before this element applied popup
59
+ // state, keyed by element.
60
+ this._triggerState = new Map();
61
+ this._onOutsidePointerDown = (event) => {
62
+ this._handleOutsidePointerDown(event);
63
+ };
64
+
65
+ this._trigger.addEventListener('click', () => this._toggle());
66
+ this._triggerSlot.addEventListener('click', () => this._toggle());
67
+ this._triggerSlot.addEventListener(
68
+ 'slotchange', () => this._syncLayout());
69
+ this.addEventListener('keydown', (event) => this._onKeydown(event));
70
+ }
71
+
72
+ static get observedAttributes() {
73
+ return ['trigger-text', 'accessible-label',
74
+ 'accessible-popup-label', 'open', 'disabled'];
75
+ }
76
+
77
+ connectedCallback() {
78
+ this._update();
79
+ this._reportedOpen = this.hasAttribute('open');
80
+ this._applyOpen(false);
81
+ this.ownerDocument.addEventListener(
82
+ 'pointerdown', this._onOutsidePointerDown, true);
83
+ }
84
+
85
+ disconnectedCallback() {
86
+ this.ownerDocument.removeEventListener(
87
+ 'pointerdown', this._onOutsidePointerDown, true);
88
+ }
89
+
90
+ attributeChangedCallback(name) {
91
+ this._update();
92
+ if (name === 'open') {
93
+ this._applyOpen(true);
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Set the trigger's visible text.
99
+ * @param {*} text Trigger text
100
+ */
101
+ setText(text) {
102
+ this.setAttribute('trigger-text', text == null ? '' : String(text));
103
+ }
104
+
105
+ /**
106
+ * Set the trigger's accessible name, rendered as `aria-label`.
107
+ * @param {*} label Accessible name
108
+ */
109
+ setLabel(label) {
110
+ this.setAttribute('accessible-label',
111
+ label == null ? '' : String(label));
112
+ }
113
+
114
+ /**
115
+ * Set the popup's accessible name.
116
+ * @param {*} label Accessible name
117
+ */
118
+ setPopupLabel(label) {
119
+ this.setAttribute('accessible-popup-label',
120
+ label == null ? '' : String(label));
121
+ }
122
+
123
+ /**
124
+ * Open or close the popup. Opening moves focus into the popup; closing
125
+ * restores focus to the trigger when focus is inside the popup.
126
+ * @param {Boolean} open Whether the popup is open
127
+ */
128
+ setOpen(open) {
129
+ if (open) {
130
+ this.setAttribute('open', '');
131
+ } else {
132
+ this.removeAttribute('open');
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Apply the open attribute to the popup, report the state and move
138
+ * focus into or out of the popup.
139
+ * @param {Boolean} moveFocus Whether opening moves focus into the popup
140
+ */
141
+ _applyOpen(moveFocus) {
142
+ if (!this.isConnected) {
143
+ return;
144
+ }
145
+ const open = this.hasAttribute('open');
146
+ const hadFocus = !open && this._containsFocus();
147
+ this._popup.hidden = !open;
148
+ this._syncExpanded();
149
+ this._reportOpen(open);
150
+ if (open && moveFocus && this.hasAttribute('open')) {
151
+ this._focusContent();
152
+ } else if (hadFocus) {
153
+ this._focusTrigger();
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Render attributes into the shadow parts.
159
+ */
160
+ _update() {
161
+ // The constructor installs the shadow parts before attribute
162
+ // callbacks run, so the parts exist on every call.
163
+ const label = this.getAttribute('accessible-label') || '';
164
+ if (label) {
165
+ this._trigger.setAttribute('aria-label', label);
166
+ } else {
167
+ this._trigger.removeAttribute('aria-label');
168
+ }
169
+ this._triggerText.textContent =
170
+ this.getAttribute('trigger-text') || '';
171
+
172
+ if (this.hasAttribute('disabled')) {
173
+ this._trigger.setAttribute('disabled', '');
174
+ } else {
175
+ this._trigger.removeAttribute('disabled');
176
+ }
177
+
178
+ this._syncLayout();
179
+ }
180
+
181
+ /**
182
+ * Name the popup from its own attribute, from an assigned trigger
183
+ * control, or from the element button.
184
+ * @param {Array<Element>} assigned Assigned trigger elements
185
+ */
186
+ _setPopupName(assigned) {
187
+ const label = this.getAttribute('accessible-popup-label') || '';
188
+ const triggerName = label || this._assignedTriggerName(assigned);
189
+ if (triggerName) {
190
+ this._popup.setAttribute('aria-label', triggerName);
191
+ this._popup.removeAttribute('aria-labelledby');
192
+ } else {
193
+ this._popup.removeAttribute('aria-label');
194
+ this._popup.setAttribute('aria-labelledby', TRIGGER_ID);
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Read the accessible name of the first assigned trigger control.
200
+ * @param {Array<Element>} assigned Assigned trigger elements
201
+ * @returns {String} Trigger name, or an empty string
202
+ */
203
+ _assignedTriggerName(assigned) {
204
+ for (const el of assigned) {
205
+ const label = (el.getAttribute('aria-label') || '').trim();
206
+ if (label) {
207
+ return label;
208
+ }
209
+ const text = (el.textContent || '').trim();
210
+ if (text) {
211
+ return text;
212
+ }
213
+ const image = el.querySelector('img[alt]');
214
+ const alt = image ? (image.getAttribute('alt') || '').trim() : '';
215
+ if (alt) {
216
+ return alt;
217
+ }
218
+ }
219
+ return '';
220
+ }
221
+
222
+ /**
223
+ * Show the element-rendered button only when the trigger slot has no
224
+ * assigned nodes, and mirror the popup state onto slotted triggers.
225
+ */
226
+ _syncLayout() {
227
+ const assigned = this._triggerSlot
228
+ .assignedNodes({ flatten: true })
229
+ .filter((node) => node.nodeType === Node.ELEMENT_NODE);
230
+ this._trigger.hidden = this._triggerSlot
231
+ .assignedNodes({ flatten: true }).length > 0;
232
+ this._syncSlottedTrigger(assigned);
233
+ this._setPopupName(assigned);
234
+ this._syncExpanded();
235
+ }
236
+
237
+ /**
238
+ * Apply `aria-haspopup` to the assigned trigger controls and restore
239
+ * their previous value when the slot no longer carries them.
240
+ * @param {Array<Element>} assigned Assigned trigger elements
241
+ */
242
+ _syncSlottedTrigger(assigned) {
243
+ const current = new Set(assigned);
244
+ this._triggerState.forEach((previous, el) => {
245
+ if (current.has(el)) {
246
+ return;
247
+ }
248
+ this._restoreAttribute(el, 'aria-haspopup', previous.hasPopup);
249
+ this._restoreAttribute(el, 'aria-expanded', previous.expanded);
250
+ this._triggerState.delete(el);
251
+ });
252
+ assigned.forEach((el) => {
253
+ if (!this._triggerState.has(el)) {
254
+ this._triggerState.set(el, {
255
+ hasPopup: el.getAttribute('aria-haspopup'),
256
+ expanded: el.getAttribute('aria-expanded')
257
+ });
258
+ }
259
+ el.setAttribute('aria-haspopup', 'dialog');
260
+ });
261
+ }
262
+
263
+ /**
264
+ * Restore an attribute to its previous value, or remove it.
265
+ * @param {Element} el Element to update
266
+ * @param {String} name Attribute name
267
+ * @param {String|null} value Previous value
268
+ */
269
+ _restoreAttribute(el, name, value) {
270
+ if (value === null) {
271
+ el.removeAttribute(name);
272
+ } else {
273
+ el.setAttribute(name, value);
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Keep `aria-expanded` in sync with the open attribute on the element
279
+ * button and on assigned trigger controls.
280
+ */
281
+ _syncExpanded() {
282
+ const expanded = String(this.hasAttribute('open'));
283
+ this._trigger.setAttribute('aria-expanded', expanded);
284
+ this._triggerState.forEach((previous, el) => {
285
+ el.setAttribute('aria-expanded', expanded);
286
+ });
287
+ }
288
+
289
+ /**
290
+ * Toggle the popup from either trigger control.
291
+ */
292
+ _toggle() {
293
+ if (this.hasAttribute('disabled')) {
294
+ return;
295
+ }
296
+ if (this.hasAttribute('open')) {
297
+ this._close();
298
+ } else {
299
+ this.setOpen(true);
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Close the popup.
305
+ */
306
+ _close() {
307
+ this.removeAttribute('open');
308
+ }
309
+
310
+ /**
311
+ * Close on `Escape` and return focus to the trigger.
312
+ * @param {KeyboardEvent} event Keydown event
313
+ */
314
+ _onKeydown(event) {
315
+ if (event.key !== 'Escape' || !this.hasAttribute('open')) {
316
+ return;
317
+ }
318
+ event.preventDefault();
319
+ this._close();
320
+ }
321
+
322
+ /**
323
+ * Close when a pointer press lands outside the host and its slots.
324
+ * @param {PointerEvent} event Pointerdown event
325
+ */
326
+ _handleOutsidePointerDown(event) {
327
+ if (!this.hasAttribute('open')) {
328
+ return;
329
+ }
330
+ if (event.composedPath().indexOf(this) !== -1) {
331
+ return;
332
+ }
333
+ this._close();
334
+ }
335
+
336
+ /**
337
+ * Whether focus is inside the projected content or the popup itself.
338
+ * @returns {Boolean} True when a descendant owns focus
339
+ */
340
+ _containsFocus() {
341
+ const active = this.ownerDocument.activeElement;
342
+ if (active && this.contains(active)) {
343
+ return true;
344
+ }
345
+ return this.shadowRoot.activeElement === this._popup;
346
+ }
347
+
348
+ /**
349
+ * Focus the first focusable projected filter control, or the popup.
350
+ */
351
+ _focusContent() {
352
+ const assigned = this._contentSlot.assignedNodes({ flatten: true });
353
+ for (const node of assigned) {
354
+ if (node.nodeType !== Node.ELEMENT_NODE) {
355
+ continue;
356
+ }
357
+ const target = node.matches(FOCUSABLE) ?
358
+ node : node.querySelector(FOCUSABLE);
359
+ if (target) {
360
+ target.focus();
361
+ if (this._containsFocus()) {
362
+ return;
363
+ }
364
+ }
365
+ }
366
+ this._popup.focus();
367
+ }
368
+
369
+ /**
370
+ * Return focus to the slotted trigger control, the element button, or
371
+ * the host when slotted markup hides the button.
372
+ */
373
+ _focusTrigger() {
374
+ const assigned = this._triggerSlot
375
+ .assignedNodes({ flatten: true })
376
+ .filter((node) => node.nodeType === Node.ELEMENT_NODE);
377
+ const slotted = assigned
378
+ .map((el) => el.matches(FOCUSABLE) ? el
379
+ : el.querySelector(FOCUSABLE))
380
+ .find(Boolean);
381
+ if (slotted) {
382
+ slotted.focus();
383
+ return;
384
+ }
385
+ if (!this._trigger.hidden) {
386
+ this._trigger.focus();
387
+ return;
388
+ }
389
+ this.tabIndex = -1;
390
+ this.focus();
391
+ }
392
+
393
+ /**
394
+ * Dispatch `open-change` when the popup state changes.
395
+ * @param {Boolean} open Current popup state
396
+ */
397
+ _reportOpen(open) {
398
+ if (open === this._reportedOpen) {
399
+ return;
400
+ }
401
+ this._reportedOpen = open;
402
+ this.dispatchEvent(new CustomEvent('open-change', {
403
+ detail: { open },
404
+ bubbles: true,
405
+ composed: true
406
+ }));
407
+ }
408
+ }
409
+
410
+ // Register once: loading this module twice, or on a page that already
411
+ // defined the element, keeps the existing definition.
412
+ if (typeof customElements !== 'undefined' &&
413
+ !customElements.get('tf-popup-filter')) {
414
+ customElements.define('tf-popup-filter', TfPopupFilterElement);
415
+ }
@@ -1,8 +1,11 @@
1
1
  import {Feature} from '../feature';
2
2
  import {createElm, elm, removeElm} from '../dom';
3
- import {isEmpty, EMPTY_FN} from '../types';
3
+ import {EMPTY_FN} from '../types';
4
4
  import {NONE} from '../const';
5
5
  import {defaultsStr, defaultsFn} from '../settings';
6
+ import {sanitizeHtml} from '../sanitize';
7
+
8
+ const TOGGLE_EVENTS = ['initialized', 'after-filtering'];
6
9
 
7
10
  /**
8
11
  * UI when filtering yields no matches
@@ -32,7 +35,9 @@ export class NoResults extends Feature {
32
35
  * Custom container DOM element
33
36
  * @type {DOMElement}
34
37
  */
35
- this.customContainer = defaultsStr(f.custom_container, null);
38
+ this.customContainer = f.custom_container &&
39
+ typeof f.custom_container.appendChild === 'function' ?
40
+ f.custom_container : null;
36
41
 
37
42
  /**
38
43
  * ID of custom container element
@@ -41,12 +46,12 @@ export class NoResults extends Feature {
41
46
  this.customContainerId = defaultsStr(f.custom_container_id, null);
42
47
 
43
48
  /**
44
- * Indicates if UI is contained in a external element
49
+ * True when a container element is present or a container id is set
45
50
  * @type {Boolean}
46
51
  * @private
47
52
  */
48
- this.isExternal = !isEmpty(this.customContainer) ||
49
- !isEmpty(this.customContainerId);
53
+ this.isExternal = Boolean(this.customContainer) ||
54
+ Boolean(this.customContainerId);
50
55
 
51
56
  /**
52
57
  * Css class assigned to container element
@@ -83,6 +88,13 @@ export class NoResults extends Feature {
83
88
  * @type {Function}
84
89
  */
85
90
  this.onAfterHide = defaultsFn(f.on_after_hide_msg, EMPTY_FN);
91
+
92
+ /**
93
+ * Subscribed toggle handler
94
+ * @type {Function|null}
95
+ * @private
96
+ */
97
+ this.boundToggle = null;
86
98
  }
87
99
 
88
100
  /**
@@ -92,11 +104,66 @@ export class NoResults extends Feature {
92
104
  if (this.initialized) {
93
105
  return;
94
106
  }
95
- let tf = this.tf;
96
- let target = this.customContainer || elm(this.customContainerId) ||
97
- tf.dom();
107
+ let targetEl = this.isExternal ?
108
+ this.customContainer || elm(this.customContainerId) : null;
109
+
110
+ // TODO(#965): remove once the legacy webpack pipeline is retired.
111
+ if (this.canUseCE(targetEl)) {
112
+ this.initCE(targetEl);
113
+ } else {
114
+ this.initLegacy(targetEl);
115
+ }
116
+
117
+ this.boundToggle = () => this.toggle();
118
+ this.emitter.on(TOGGLE_EVENTS, this.boundToggle);
119
+
120
+ /** @inherited */
121
+ this.initialized = true;
122
+ }
123
+
124
+ /**
125
+ * Whether the feature renders through `<tf-no-results>`.
126
+ * @param {DOMElement} targetEl Resolved external container, if any
127
+ * @returns {Boolean} True when the registered element exposes `setText`
128
+ * and no external container is configured, or the container resolves
129
+ * @private
130
+ */
131
+ canUseCE(targetEl) {
132
+ const NoResultsElement = typeof customElements === 'undefined' ?
133
+ null : customElements.get('tf-no-results');
134
+ return Boolean(NoResultsElement) &&
135
+ typeof NoResultsElement.prototype.setText === 'function' &&
136
+ (!this.isExternal || Boolean(targetEl &&
137
+ typeof targetEl.appendChild === 'function'));
138
+ }
98
139
 
99
- //container
140
+ /**
141
+ * Initialize using the <tf-no-results> custom element
142
+ * @param {DOMElement} targetEl External container element
143
+ * @private
144
+ */
145
+ initCE(targetEl) {
146
+ const host = document.createElement('tf-no-results');
147
+ host.className = this.cssClass;
148
+ host.setText('');
149
+ host.innerHTML = sanitizeHtml(this.content);
150
+
151
+ if (this.isExternal) {
152
+ targetEl.appendChild(host);
153
+ } else {
154
+ const dom = this.tf.dom();
155
+ dom.parentNode.insertBefore(host, dom.nextSibling);
156
+ }
157
+ this.cont = host;
158
+ }
159
+
160
+ /**
161
+ * Initialize using the legacy div container
162
+ * @param {DOMElement} targetEl External container element
163
+ * @private
164
+ */
165
+ initLegacy(targetEl) {
166
+ let target = targetEl || this.tf.dom();
100
167
  let cont = createElm('div');
101
168
  cont.className = this.cssClass;
102
169
  cont.innerHTML = this.content;
@@ -108,15 +175,6 @@ export class NoResults extends Feature {
108
175
  }
109
176
 
110
177
  this.cont = cont;
111
-
112
- // subscribe to after-filtering event
113
- this.emitter.on(
114
- ['initialized', 'after-filtering'],
115
- () => this.toggle()
116
- );
117
-
118
- /** @inherited */
119
- this.initialized = true;
120
178
  }
121
179
 
122
180
  /**
@@ -183,10 +241,14 @@ export class NoResults extends Feature {
183
241
  if (!this.initialized) {
184
242
  return;
185
243
  }
186
- removeElm(this.cont);
244
+ if (this.cont && this.cont.parentNode) {
245
+ removeElm(this.cont);
246
+ }
187
247
  this.cont = null;
188
- // unsubscribe to after-filtering event
189
- this.emitter.off(['after-filtering'], () => this.toggle());
248
+ if (this.boundToggle) {
249
+ this.emitter.off(TOGGLE_EVENTS, this.boundToggle);
250
+ this.boundToggle = null;
251
+ }
190
252
 
191
253
  this.initialized = false;
192
254
  }