Skip to content

Commit

Permalink
fix(accordion): ensure item toggle events can be prevented from the o…
Browse files Browse the repository at this point in the history
…utside
  • Loading branch information
Westbrook committed Oct 4, 2021
1 parent c439eb3 commit 30dbfc8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
23 changes: 15 additions & 8 deletions packages/accordion/src/Accordion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,20 +116,27 @@ export class Accordion extends Focusable {
nextItem.focus();
}

private onToggle(event: Event): void {
private async onToggle(event: Event): Promise<void> {
// Let the event pass through the DOM so that it can be
// prevented from the outside if a user so desires.
await 0;
if (this.allowMultiple || event.defaultPrevented) {
// No toggling when `allowMultiple` or the user prevents it.
return;
}
const target = event.target as AccordionItem;
const items = [...this.items] as AccordionItem[];
/* c8 ignore next 3 */
if (items && !items.length) {
// no toggling when there aren't items.
return;
}
if (!this.allowMultiple && !event.defaultPrevented) {
items.forEach((item) => {
if (item.open && item !== target) {
item.open = false;
}
});
}
items.forEach((item) => {
if (item !== target) {
// Close all the items that didn't dispatch the event.
item.open = false;
}
});
}

protected render(): TemplateResult {
Expand Down
8 changes: 4 additions & 4 deletions packages/accordion/test/accordion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,17 +133,17 @@ describe('Accordion', () => {

firstButton.click();
await elementUpdated(el);
expect(firstItem.open);
expect(!secondItem.open);
expect(firstItem.open).to.be.true;
expect(secondItem.open).to.be.false;

el.addEventListener('sp-accordion-item-toggle', (event: Event) =>
event.preventDefault()
);

secondButton.click();
await elementUpdated(el);
expect(firstItem.open);
expect(!secondItem.open);
expect(firstItem.open).to.be.true;
expect(secondItem.open).to.be.false;
});
it('allows more than one open item when `[allow-multiple]`', async () => {
const el = await fixture<Accordion>(Default());
Expand Down

0 comments on commit 30dbfc8

Please sign in to comment.