-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathrh-accordion.ts
399 lines (327 loc) · 11 KB
/
rh-accordion.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import { LitElement, html, type TemplateResult } from 'lit';
import { classMap } from 'lit/directives/class-map.js';
import { customElement } from 'lit/decorators/custom-element.js';
import { property } from 'lit/decorators/property.js';
import { observed } from '@patternfly/pfe-core/decorators/observed.js';
import { provide } from '@lit/context';
import { RovingTabindexController } from '@patternfly/pfe-core/controllers/roving-tabindex-controller.js';
import { colorContextConsumer, type ColorTheme } from '../../lib/context/color/consumer.js';
import { colorContextProvider, type ColorPalette } from '../../lib/context/color/provider.js';
import { NumberListConverter, ComposedEvent } from '@patternfly/pfe-core';
import { Logger } from '@patternfly/pfe-core/controllers/logger.js';
import { RhAccordionHeader, AccordionHeaderChangeEvent } from './rh-accordion-header.js';
import { RhAccordionPanel } from './rh-accordion-panel.js';
import { context, type RhAccordionContext } from './context.js';
import styles from './rh-accordion.css';
export class AccordionExpandEvent extends ComposedEvent {
constructor(
public toggle: RhAccordionHeader,
public panel: RhAccordionPanel,
) {
super('expand');
}
}
export class AccordionCollapseEvent extends ComposedEvent {
constructor(
public toggle: RhAccordionHeader,
public panel: RhAccordionPanel,
) {
super('collapse');
}
}
/**
* An accordion is a stacked list of panels which allows users to expand or collapse information when selected. They feature panels that consist of a section text label and a caret icon that collapses or expands to reveal more information.
*
* @summary Expands or collapses a stacked list of panels
*
* @fires {AccordionExpandEvent} expand - when a panel expands
* @fires {AccordionCollapseEvent} collapse - when a panel collapses
*
*
* @slot
* Place the `rh-accordion-header` and `rh-accordion-panel` elements here.
*
* @attr accents
* Position accents in the header either inline or bottom
* {@default inline}
*
*/
@customElement('rh-accordion')
export class RhAccordion extends LitElement {
static readonly version = '{{version}}';
static readonly styles = [styles];
static isAccordion(target: EventTarget | null): target is RhAccordion {
return target instanceof RhAccordion;
}
static isHeader(target: EventTarget | null): target is RhAccordionHeader {
return target instanceof RhAccordionHeader;
}
static isPanel(target: EventTarget | null): target is RhAccordionPanel {
return target instanceof RhAccordionPanel;
}
static isAccordionChangeEvent(event: Event): event is AccordionHeaderChangeEvent {
return event instanceof AccordionHeaderChangeEvent;
}
/**
* Sets accordion header's accents position to inline or bottom
*/
@property({
attribute: true,
reflect: true,
}) accents?: 'inline' | 'bottom';
/**
* Sets and reflects the currently expanded accordion 0-based indexes.
* Use commas to separate multiple indexes.
* ```html
* <pf-accordion expanded-index="1,2">
* ...
* </pf-accordion>
* ```
*/
@property({
attribute: 'expanded-index',
converter: NumberListConverter,
})
get expandedIndex() {
return this.#expandedIndex;
}
set expandedIndex(value) {
const old = this.#expandedIndex;
this.#expandedIndex = value;
if (JSON.stringify(old) !== JSON.stringify(value)) {
this.requestUpdate('expandedIndex', old);
this.collapseAll().then(async () => {
for (const i of this.expandedIndex) {
await this.expand(i, this);
}
});
}
}
get #ctx(): RhAccordionContext {
const accents = this.accents ? this.accents : 'inline';
return { accents };
}
@observed(function largeChanged(this: RhAccordion) {
[...this.headers, ...this.panels].forEach(el => el.toggleAttribute('large', this.large));
})
@property({ reflect: true, type: Boolean }) large = false;
@property({ reflect: true, type: Boolean }) bordered = true;
@colorContextProvider()
@property({ reflect: true, attribute: 'color-palette' }) colorPalette?: ColorPalette;
@colorContextConsumer() private on?: ColorTheme;
protected expandedSets = new Set<number>();
#expandedIndex: number[] = [];
#headerIndex = new RovingTabindexController<RhAccordionHeader>(this);
// actually is read in #init, by the `||=` operator
// eslint-disable-next-line no-unused-private-class-members
#initialized = false;
#logger = new Logger(this);
#mo = new MutationObserver(() => this.#init());
@provide({ context }) private ctx = this.#ctx;
connectedCallback() {
super.connectedCallback();
this.addEventListener('change', this.#onChange as EventListener);
this.#mo.observe(this, { childList: true });
this.#init();
}
override render(): TemplateResult {
const { on = '' } = this;
return html`
<div id="container" class="${classMap({ [on]: !!on })}"><slot></slot></div>
`;
}
async firstUpdated() {
const { headers } = this;
headers.forEach((header, index) => {
if (header.expanded) {
this.#expandHeader(header, index);
const panel = this.#panelForHeader(header);
if (panel) {
this.#expandPanel(panel);
}
}
});
this.ctx = this.#ctx;
}
/**
* Initialize the accordion by connecting headers and panels
* with aria controls and labels; set up the default disclosure
* state if not set by the author; and check the URL for default
* open
*/
async #init() {
this.#initialized ||= !!await this.updateComplete;
this.#headerIndex.initItems(this.headers);
// Event listener to the accordion header after the accordion has been initialized to add the roving tabindex
this.addEventListener('focusin', this.#updateActiveHeader);
this.updateAccessibility();
}
protected override async getUpdateComplete(): Promise<boolean> {
const c = await super.getUpdateComplete();
const results = await Promise.all([
...this.#allHeaders().map(x => x.updateComplete),
...this.#allPanels().map(x => x.updateComplete),
]);
return c && results.every(Boolean);
}
get #activeHeader() {
const { headers } = this;
const index = headers.findIndex(header => header.matches(':focus,:focus-within'));
return index > -1 ? headers.at(index) : undefined;
}
#updateActiveHeader() {
if (this.#activeHeader) {
this.#headerIndex.setActiveItem(this.#activeHeader);
}
}
#panelForHeader(header: RhAccordionHeader) {
const next = header.nextElementSibling;
if (!RhAccordion.isPanel(next)) {
return void this.#logger.error('Sibling element to a header needs to be a panel');
} else {
return next;
}
}
#expandHeader(header: RhAccordionHeader, index = this.#getIndex(header)) {
// If this index is not already listed in the expandedSets array, add it
this.expandedSets.add(index);
this.#expandedIndex = [...this.expandedSets as Set<number>];
header.expanded = true;
}
#expandPanel(panel: RhAccordionPanel) {
panel.expanded = true;
panel.hidden = false;
}
async #collapseHeader(header: RhAccordionHeader, index = this.#getIndex(header)) {
if (!this.expandedSets) {
await this.updateComplete;
}
this.expandedSets.delete(index);
header.expanded = false;
await header.updateComplete;
}
async #collapsePanel(panel: RhAccordionPanel) {
await panel.updateComplete;
if (!panel.expanded) {
return;
}
panel.expanded = false;
panel.hidden = true;
}
#onChange(event: AccordionHeaderChangeEvent) {
if (RhAccordion.isAccordionChangeEvent(event)) {
const index = this.#getIndex(event.target);
if (event.expanded) {
this.expand(index, event.accordion);
} else {
this.collapse(index);
}
}
}
#allHeaders(accordion: RhAccordion = this): RhAccordionHeader[] {
return Array.from(accordion.children).filter((x): x is RhAccordionHeader =>
x instanceof RhAccordionHeader
);
}
#allPanels(accordion: RhAccordion = this): RhAccordionPanel[] {
return Array.from(accordion.children).filter((x =>
RhAccordion.isPanel(x)) as typeof RhAccordion.isPanel
);
}
#getIndex(el: Element | null) {
if (RhAccordion.isHeader(el)) {
return this.headers.findIndex(header => header.id === el.id);
}
if (RhAccordion.isPanel(el)) {
return this.panels.findIndex(panel => panel.id === el.id);
}
this.#logger.warn('The #getIndex method expects to receive a header or panel element.');
return -1;
}
get headers() {
return this.#allHeaders();
}
get panels() {
return this.#allPanels();
}
public updateAccessibility() {
const { headers } = this;
// For each header in the accordion, attach the aria connections
headers.forEach(header => {
const panel = this.#panelForHeader(header);
if (panel) {
header.setAttribute('aria-controls', panel.id);
panel.setAttribute('aria-labelledby', header.id);
panel.hidden = !panel.expanded;
}
});
}
/**
* Accepts a 0-based index value (integer) for the set of accordion items to expand or collapse.
*/
public async toggle(index: number) {
const { headers } = this;
const header = headers[index];
if (!header.expanded) {
await this.expand(index);
} else {
await this.collapse(index);
}
}
/**
* Accepts a 0-based index value (integer) for the set of accordion items to expand.
* Accepts an optional parent accordion to search for headers and panels.
*/
public async expand(index: number, parentAccordion?: RhAccordion) {
const allHeaders: RhAccordionHeader[] = this.#allHeaders(parentAccordion);
const header = allHeaders[index];
if (!header) {
return;
}
const panel = this.#panelForHeader(header);
if (!panel) {
return;
}
// If the header and panel exist, open both
this.#expandHeader(header, index),
this.#expandPanel(panel),
header.focus();
this.dispatchEvent(new AccordionExpandEvent(header, panel));
await this.updateComplete;
}
/**
* Expands all accordion items.
*/
public async expandAll() {
this.headers.forEach(header => this.#expandHeader(header));
this.panels.forEach(panel => this.#expandPanel(panel));
await this.updateComplete;
}
/**
* Accepts a 0-based index value (integer) for the set of accordion items to collapse.
*/
public async collapse(index: number) {
const header = this.headers.at(index);
const panel = this.panels.at(index);
if (!header || !panel) {
return;
}
this.#collapseHeader(header);
this.#collapsePanel(panel);
this.dispatchEvent(new AccordionCollapseEvent(header, panel));
await this.updateComplete;
}
/**
* Collapses all accordion items.
*/
public async collapseAll() {
this.headers.forEach(header => this.#collapseHeader(header));
this.panels.forEach(panel => this.#collapsePanel(panel));
await this.updateComplete;
}
}
declare global {
interface HTMLElementTagNameMap {
'rh-accordion': RhAccordion;
}
}