diff --git a/src/Collapsable.ts b/src/Collapsable.ts index 091eaee..559e8c1 100644 --- a/src/Collapsable.ts +++ b/src/Collapsable.ts @@ -151,22 +151,33 @@ export class Collapsable { } } - public handleDefaultExpanded(): void { + public handleDefaultExpanded(media?: MediaQueryList | null): void { this.prepareDefaultExpanded() const { options } = this const collapsableEvent = new CustomEvent('init.collapsable', { bubbles: true }) const force = !options.collapsableAll - this.defaultExpandedItem.forEach((item) => { - item.expand(collapsableEvent, null, force) - }) + // First, close all the items but the default expanded and then expand the default expanded. The order of + // operations is necessary for correct accordion collapsable. this.items - .filter((item) => !this.defaultExpandedItem.includes(item)) + .filter((item) => { + // When media is being handled, skip items without media or items with different media or not matching media. + if (media && (!item.media || item.media.media !== media.media || !media.matches)) { + return false + } + + // For other items, return whether they should be default expanded or not. + return !this.defaultExpandedItem.includes(item) + }) .forEach((item) => { item.collapse(collapsableEvent, null, true) }) + + this.defaultExpandedItem.forEach((item) => { + item.expand(collapsableEvent, null, force) + }) } public getExtLinkById(id?: string): CollapsableExtLink[] { @@ -178,7 +189,7 @@ export class Collapsable { } public getExpanded(): CollapsableItem[] { - return this.items.filter((item) => item.isExpanded) + return this.items.filter((item) => item.isExpanded && (!item.media || (item.media && item.media.matches))) } public expandAll(data?: any): void { diff --git a/src/CollapsableItem.ts b/src/CollapsableItem.ts index a085013..37fae02 100644 --- a/src/CollapsableItem.ts +++ b/src/CollapsableItem.ts @@ -291,9 +291,14 @@ export class CollapsableItem { // This allows us to collapse expanded item even if there might be collapseAll === false option this.collapsable.promiseOpen = true - // If accordion, we have to collapse previously opened item before expanding; if accordion element hasn't - // collapsed, we can't continue - if (options.accordion && expandedItem.length && !expandedItem[0].collapse(collapsableEvent, data, force)) { + // If `accordion`, we have to collapse a previously opened item (if different from the current item) before + // expanding; if the opened item hasn't collapsed, we can't continue + if ( + options.accordion && + expandedItem.length && + this !== expandedItem[0] && + !expandedItem[0].collapse(collapsableEvent, data, force) + ) { this.collapsable.promiseOpen = false return false }