From 2318f6d8eac2fe8d06f4f2bb99fe49e111efab5e Mon Sep 17 00:00:00 2001 From: Andrew Noblet Date: Thu, 9 Feb 2023 09:12:58 -0500 Subject: [PATCH] feat(cxl-ui): [cxl-vaadin-accordion] update accordion behavior when on mobile --- .../src/components/cxl-vaadin-accordion.js | 57 ++++++++++++++++++- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/packages/cxl-ui/src/components/cxl-vaadin-accordion.js b/packages/cxl-ui/src/components/cxl-vaadin-accordion.js index a374c6422..f0a4a62ce 100644 --- a/packages/cxl-ui/src/components/cxl-vaadin-accordion.js +++ b/packages/cxl-ui/src/components/cxl-vaadin-accordion.js @@ -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. */ @@ -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. @@ -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; }