diff --git a/.changeset/mean-plants-rush.md b/.changeset/mean-plants-rush.md new file mode 100644 index 000000000..d9454044d --- /dev/null +++ b/.changeset/mean-plants-rush.md @@ -0,0 +1,5 @@ +--- +'@lion/ui': patch +--- + +lion-switch: checked-changed event is no longer fired on element initialization when checked is set through attribute diff --git a/packages/ui/components/switch/src/LionSwitchButton.js b/packages/ui/components/switch/src/LionSwitchButton.js index a323d9846..610df6cef 100644 --- a/packages/ui/components/switch/src/LionSwitchButton.js +++ b/packages/ui/components/switch/src/LionSwitchButton.js @@ -78,6 +78,7 @@ export class LionSwitchButton extends DisabledWithTabIndexMixin(LitElement) { this.role = 'switch'; this.checked = false; + this.__initialized = false; /** @protected */ this._toggleChecked = this._toggleChecked.bind(this); /** @private */ @@ -158,8 +159,20 @@ export class LionSwitchButton extends DisabledWithTabIndexMixin(LitElement) { */ requestUpdate(name, oldValue, options) { super.requestUpdate(name, oldValue, options); - if (this.isConnected && name === 'checked' && this.checked !== oldValue && !this.disabled) { + if ( + this.__initialized && + this.isConnected && + name === 'checked' && + this.checked !== oldValue && + !this.disabled + ) { this.__checkedStateChange(); } } + + /** @param {import('lit').PropertyValues } changedProperties */ + firstUpdated(changedProperties) { + super.firstUpdated(changedProperties); + this.__initialized = true; + } } diff --git a/packages/ui/components/switch/test/lion-switch-button.test.js b/packages/ui/components/switch/test/lion-switch-button.test.js index 2852c2bff..6921cedb5 100644 --- a/packages/ui/components/switch/test/lion-switch-button.test.js +++ b/packages/ui/components/switch/test/lion-switch-button.test.js @@ -1,4 +1,4 @@ -import { expect, fixture as _fixture } from '@open-wc/testing'; +import { expect, fixture as _fixture, fixtureSync, elementUpdated } from '@open-wc/testing'; import { html } from 'lit/static-html.js'; import sinon from 'sinon'; import '@lion/ui/define/lion-switch-button.js'; @@ -126,6 +126,20 @@ describe('lion-switch-button', () => { expect(handlerSpy.called).to.be.false; }); + it('should not dispatch "checked-changed" event if not initialized on update', async () => { + const handlerSpy = sinon.spy(); + const elSync = /** @type {LionSwitchButton} */ ( + fixtureSync(html``) + ); + expect(elSync.__initialized).to.be.false; + await elementUpdated(elSync); + expect(elSync.__initialized).to.be.true; + expect(handlerSpy.called).to.be.false; + elSync.checked = !elSync.checked; + await elementUpdated(elSync); + expect(handlerSpy.called).to.be.true; + }); + describe('a11y', () => { it('should manage "aria-checked"', async () => { expect(el.hasAttribute('aria-checked')).to.be.true;