Skip to content

Commit

Permalink
feat(cxl-ui): [cxl-vaadin-accordion] update accordion behavior when o…
Browse files Browse the repository at this point in the history
…n mobile
  • Loading branch information
anoblet committed Feb 9, 2023
1 parent 058e421 commit 2318f6d
Showing 1 changed file with 55 additions and 2 deletions.
57 changes: 55 additions & 2 deletions packages/cxl-ui/src/components/cxl-vaadin-accordion.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ import cxlVaadinAccordionGlobalStyles from '../styles/global/cxl-vaadin-accordio
*/
@customElement('cxl-vaadin-accordion')
export class CXLVaadinAccordionElement extends Accordion {
// Keep track of device width.
_wide = true;

// Device width media query
_wideMediaQuery = '(min-width: 750px)';

/**
* Global styles.
*/
Expand All @@ -20,6 +26,49 @@ export class CXLVaadinAccordionElement extends Accordion {
registerGlobalStyles(cxlVaadinAccordionGlobalStyles, {
moduleId: 'cxl-vaadin-accordion-global',
});

this._registerMediaListener();
}

/**
* Registers a media query listener to keep track of device width.
* If the user is on mobile, open all panels, and disable panel toggling.
*/
_registerMediaListener() {
const observer = window.matchMedia(this._wideMediaQuery);
const matches = (mediaQueryList) => {
// Reset the hasAppliedState flag when the media query changes.
this.hasAppliedState = false;

if (mediaQueryList.matches) {
this._wide = true;

if (this.items) {
for (let i = 0; i < this.items.length; i++) {
this.items[i].disabled = false;
}

this._updateItems(this.items, 0);
}
} else {
this._wide = false;

if (this.items) {
for (let i = 0; i < this.items.length; i++) {
this.items[i].opened = true;
this.items[i].disabled = true;
}
}
}
};

// Items aren't available on first load, so we need to listen for changes.
this.addEventListener('items-changed', () => {
matches(observer);
});

// Listen for changes to the device width.
observer.addEventListener('change', matches);
}

// Keep track of accordion panels state.
Expand All @@ -37,12 +86,16 @@ export class CXLVaadinAccordionElement extends Accordion {
this.opened = null;
}

this._saveAccordionState(this.items, e.detail.value, idx);
// Save accordion panel state if on desktop.
if (this._wide) {
this._saveAccordionState(this.items, e.detail.value, idx);
}
}

// Restore accordion panel state.
_updateItems(items, opened) {
if (!items) {
// Check for items and restore state only on desktop.
if (!items || !this._wide) {
return;
}

Expand Down

0 comments on commit 2318f6d

Please sign in to comment.