update option label on change; fixes #1971 (#2236)

This commit is contained in:
Cory LaViska
2024-10-28 13:02:57 -04:00
committed by GitHub
parent 2e73b3d6c5
commit aca0f3d64a
4 changed files with 11 additions and 28 deletions

View File

@@ -31,7 +31,6 @@ export default class SlOption extends ShoelaceElement {
static styles: CSSResultGroup = [componentStyles, styles];
static dependencies = { 'sl-icon': SlIcon };
private cachedTextLabel: string;
// @ts-expect-error - Controller is currently unused
private readonly localize = new LocalizeController(this);
@@ -58,19 +57,13 @@ export default class SlOption extends ShoelaceElement {
}
private handleDefaultSlotChange() {
const textLabel = this.getTextLabel();
// Ignore the first time the label is set
if (typeof this.cachedTextLabel === 'undefined') {
this.cachedTextLabel = textLabel;
return;
}
// When the label changes, emit a slotchange event so parent controls see it
if (textLabel !== this.cachedTextLabel) {
this.cachedTextLabel = textLabel;
this.emit('slotchange', { bubbles: true, composed: false, cancelable: false });
}
// When the label changes, tell the controller to update
customElements.whenDefined('sl-select').then(() => {
const controller = this.closest('sl-select');
if (controller) {
controller.handleDefaultSlotChange();
}
});
}
private handleMouseEnter() {

View File

@@ -1,6 +1,5 @@
import '../../../dist/shoelace.js';
import { aTimeout, expect, fixture, html, waitUntil } from '@open-wc/testing';
import sinon from 'sinon';
import { aTimeout, expect, fixture, html } from '@open-wc/testing';
import type SlOption from './option.js';
describe('<sl-option>', () => {
@@ -32,17 +31,6 @@ describe('<sl-option>', () => {
expect(el.getAttribute('aria-disabled')).to.equal('true');
});
it('emits the slotchange event when the label changes', async () => {
const el = await fixture<SlOption>(html` <sl-option>Text</sl-option> `);
const slotChangeHandler = sinon.spy();
el.addEventListener('slotchange', slotChangeHandler);
el.textContent = 'New Text';
await waitUntil(() => slotChangeHandler.calledOnce);
expect(slotChangeHandler).to.have.been.calledOnce;
});
it('should convert non-string values to string', async () => {
const el = await fixture<SlOption>(html` <sl-option>Text</sl-option> `);

View File

@@ -501,7 +501,8 @@ export default class SlSelect extends ShoelaceElement implements ShoelaceFormCon
}
}
private handleDefaultSlotChange() {
/* @internal - used by options to update labels */
public handleDefaultSlotChange() {
if (!customElements.get('wa-option')) {
customElements.whenDefined('wa-option').then(() => this.handleDefaultSlotChange());
}