Skip to content

fix: update combobox to handle duplicate items#5950

Open
preethialuru wants to merge 3 commits intomainfrom
aluru/update-combobox
Open

fix: update combobox to handle duplicate items#5950
preethialuru wants to merge 3 commits intomainfrom
aluru/update-combobox

Conversation

@preethialuru
Copy link
Collaborator

Description

This PR fixes an issue in Combobox component where duplicate itemText values would cause incorrect behavior. When multiple options had the same display text but different underlying values, selecting one would always resolve to the first match.

Motivation and context

When there is a list of items, which has itemText and value. Currently, the combobox only supports the itemText to be sent to change event. So any handling needs to be done using itemText.

But is the list of items has duplicate items with same itemText and different value (uniqueId, in our case its projectId). In this case, we would need both itemText and value to be sent to the change event. So the handling can be done based on both the itemText and value, even if the itemText is same, we can use value as differentiator.

So the request here is to, expose an explicit selectedValue property would eliminate reliance on itemText uniqueness and provide a more reliable contract for downstream consumers.

#5910

Related issue(s)

  • fixes [5910]

Screenshots (if appropriate)

Screen.Recording.2025-12-16.at.10.54.40.PM.mov

Author's checklist

  • I have read the CONTRIBUTING and PULL_REQUESTS documents.
  • I have reviewed at the Accessibility Practices for this feature, see: Aria Practices
  • I have added automated tests to cover my changes.
  • I have included a well-written changeset if my change needs to be published.
  • I have included updated documentation if my change required it.

Reviewer's checklist

  • Includes a Github Issue with appropriate flag or Jira ticket number without a link
  • Includes thoughtfully written changeset if changes suggested include patch, minor, or major features
  • Automated tests cover all use cases and follow best practices for writing
  • Validated on all supported browsers
  • All VRTs are approved before the author can update Golden Hash

Manual review test cases

  • Descriptive Test Statement

    1. Go here
    2. Do this action
    3. Expect this result
  • Descriptive Test Statement

    1. Go here
    2. Do this action
    3. Expect this result

Device review

  • Did it pass in Desktop?
  • Did it pass in (emulated) Mobile?
  • Did it pass in (emulated) iPad?

@preethialuru preethialuru requested a review from a team as a code owner January 5, 2026 06:07
@changeset-bot
Copy link

changeset-bot bot commented Jan 5, 2026

🦋 Changeset detected

Latest commit: 6a27163

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 84 packages
Name Type
@spectrum-web-components/combobox Minor
@spectrum-web-components/bundle Minor
documentation Patch
@spectrum-web-components/accordion Minor
@spectrum-web-components/action-bar Minor
@spectrum-web-components/action-button Minor
@spectrum-web-components/action-group Minor
@spectrum-web-components/action-menu Minor
@spectrum-web-components/alert-banner Minor
@spectrum-web-components/alert-dialog Minor
@spectrum-web-components/asset Minor
@spectrum-web-components/avatar Minor
@spectrum-web-components/badge Minor
@spectrum-web-components/breadcrumbs Minor
@spectrum-web-components/button-group Minor
@spectrum-web-components/button Minor
@spectrum-web-components/card Minor
@spectrum-web-components/checkbox Minor
@spectrum-web-components/clear-button Minor
@spectrum-web-components/close-button Minor
@spectrum-web-components/coachmark Minor
@spectrum-web-components/color-area Minor
@spectrum-web-components/color-field Minor
@spectrum-web-components/color-handle Minor
@spectrum-web-components/color-loupe Minor
@spectrum-web-components/color-slider Minor
@spectrum-web-components/color-wheel Minor
@spectrum-web-components/contextual-help Minor
@spectrum-web-components/dialog Minor
@spectrum-web-components/divider Minor
@spectrum-web-components/dropzone Minor
@spectrum-web-components/field-group Minor
@spectrum-web-components/field-label Minor
@spectrum-web-components/help-text Minor
@spectrum-web-components/icon Minor
@spectrum-web-components/icons-ui Minor
@spectrum-web-components/icons-workflow Minor
@spectrum-web-components/icons Minor
@spectrum-web-components/iconset Minor
@spectrum-web-components/illustrated-message Minor
@spectrum-web-components/infield-button Minor
@spectrum-web-components/link Minor
@spectrum-web-components/menu Minor
@spectrum-web-components/meter Minor
@spectrum-web-components/modal Minor
@spectrum-web-components/number-field Minor
@spectrum-web-components/overlay Minor
@spectrum-web-components/picker-button Minor
@spectrum-web-components/picker Minor
@spectrum-web-components/popover Minor
@spectrum-web-components/progress-bar Minor
@spectrum-web-components/progress-circle Minor
@spectrum-web-components/radio Minor
@spectrum-web-components/search Minor
@spectrum-web-components/sidenav Minor
@spectrum-web-components/slider Minor
@spectrum-web-components/split-view Minor
@spectrum-web-components/status-light Minor
@spectrum-web-components/swatch Minor
@spectrum-web-components/switch Minor
@spectrum-web-components/table Minor
@spectrum-web-components/tabs Minor
@spectrum-web-components/tags Minor
@spectrum-web-components/textfield Minor
@spectrum-web-components/thumbnail Minor
@spectrum-web-components/toast Minor
@spectrum-web-components/tooltip Minor
@spectrum-web-components/top-nav Minor
@spectrum-web-components/tray Minor
@spectrum-web-components/underlay Minor
@spectrum-web-components/custom-vars-viewer Minor
@spectrum-web-components/story-decorator Minor
@spectrum-web-components/vrt-compare Minor
@spectrum-web-components/base Minor
@spectrum-web-components/grid Minor
@spectrum-web-components/opacity-checkerboard Minor
@spectrum-web-components/reactive-controllers Minor
@spectrum-web-components/shared Minor
@spectrum-web-components/styles Minor
@spectrum-web-components/theme Minor
@spectrum-web-components/truncated Minor
@spectrum-web-components/eslint-plugin Minor
example-project-rollup Patch
example-project-webpack Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@preethialuru preethialuru reopened this Jan 5, 2026
@github-actions
Copy link
Contributor

github-actions bot commented Jan 5, 2026

📚 Branch Preview Links

🔍 First Generation Visual Regression Test Results

When a visual regression test fails (or has previously failed while working on this branch), its results can be found in the following URLs:

Deployed to Azure Blob Storage: pr-5950

If the changes are expected, update the current_golden_images_cache hash in the circleci config to accept the new images. Instructions are included in that file.
If the changes are unexpected, you can investigate the cause of the differences and update the code accordingly.

@caseyisonit
Copy link
Contributor

The issue described is an accessibility pattern violation. each item should have a unique value AND label for the drop down. There should never be an instance where two items render the same label with different underlying values.

Copy link
Contributor

@nikkimk nikkimk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have concerns about the accessibility and usability of items with identical text. Can you provide an example where this is necessary and is accessible.

Comment on lines 292 to 297
export const duplicateItemText = (): TemplateResult => {
const optionsWithDuplicates: ComboboxOption[] = [
{ value: 'val1', itemText: 'Same Display Text' },
{ value: 'val2', itemText: 'Same Display Text' },
{ value: 'val3', itemText: 'Unique Text' },
];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This example would not be accessible as there is no way to differentiate options to the user. Is there an accessible use case you can provide for this PR instead?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated the example to be more accessible.

Comment on lines +328 to +340
protected override handleChange(): void {
this.dispatchEvent(
new CustomEvent('change', {
bubbles: true,
composed: true,
detail: {
value: this.itemValue,
itemText: this.value,
},
})
);
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The combobox documentation should be updated to reflect this.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overriding handleChange will suppress base class behaviour too. Do we want this?
This is risky. The base class is doing important housekeeping (state updates, validation, other events). My approach would be to use super.handleChange() unless you intentionally want to replace that logic.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Texfield is already dispatching change event at @change handler. This is duplicate semantics.
Check here:

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to dispatch change event with detail like text and value, which is not added in Textfield. These details are needed for the user to handle UI on their side.

Suppose, we have a requirement to store the itemText selected in the text box and pass it to API on a CTA click.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The combobox documentation should be updated to reflect this.

Can you please let me know where do we need to update the docs?

Copy link
Contributor

@nikkimk nikkimk Feb 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The combobox documentation should be updated to reflect this.

Can you please let me know where do we need to update the docs?

@preethialuru 1st-gen/packages/combobox/README.md

Add a section just above the accessibility section, something like this:

### Behaviors

#### Change Event

When the selection changes, a `change` event is fired. The event detail contains `value` and `itemText` of the selected option.

```html demo
<sp-combobox id="employee" label="Employee">
    <sp-menu-item value="emp-1042">Alex Johnson (Engineering)</sp-menu-item>
    <sp-menu-item value="emp-2187">Alex Johnson (Marketing)</sp-menu-item>
    <sp-menu-item value="emp-3301">Sam Chen (Design)</sp-menu-item>
    <sp-menu-item value="emp-4455">Jordan Lee (Sales)</sp-menu-item>
</sp-combobox>
<script>
    document.getElementById('employee').addEventListener('change', (event) => {
        alert(`${event.detail.value}: ${event.detail.itemText}`);
    });
</script>
```

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@preethialuru Your use case is valid but I see ther eis big problem changing the event contract. It effects all change events not just menu selection. If you need itemValue we can expose it as a public reactive property rather than changing the event contract. You can add a public @Property for the selected option's value:

@property({ type: String, attribute: 'selected-value' })
public selectedValue = '';

Then you can capture it on your app side by

combobox.addEventListener('change', () => {
    const itemText = combobox.value;           // display text
    const value = combobox.selectedValue;      // underlying ID
    api.save({ id: value, name: itemText });
});

This would be non-breaking and will work for all scenarios.

@nikkimk
Copy link
Contributor

nikkimk commented Jan 7, 2026

We also need to make sure this PR includes a changeset.

Comment on lines +328 to +340
protected override handleChange(): void {
this.dispatchEvent(
new CustomEvent('change', {
bubbles: true,
composed: true,
detail: {
value: this.itemValue,
itemText: this.value,
},
})
);
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overriding handleChange will suppress base class behaviour too. Do we want this?
This is risky. The base class is doing important housekeeping (state updates, validation, other events). My approach would be to use super.handleChange() unless you intentionally want to replace that logic.

Comment on lines 319 to 321
this.updateComplete.then(() => {
this._menuSelectedValue = '';
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are setting _menuSelectedValue when selecting a menu item and clear it both in shouldUpdate (synchronously) and via this.updateComplete.then(() => { this._menuSelectedValue = ''; }).
This is redundant and can mask timing issues. Remove updateComplete.then(...) cleanup and keep clearing in shouldUpdate right after you use it. Much clearer and ties it to the render/update cycle

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed updateComplete.then(...)

Comment on lines +328 to +340
protected override handleChange(): void {
this.dispatchEvent(
new CustomEvent('change', {
bubbles: true,
composed: true,
detail: {
value: this.itemValue,
itemText: this.value,
},
})
);
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Texfield is already dispatching change event at @change handler. This is duplicate semantics.
Check here:

this._menuSelectedValue = '';
} else {
this.itemValue =
this.availableOptions.find(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If availableOptions is stale or lazily updated, you might pick a wrong match. Please ensure filterAvailableOptions() is deterministic and up-to-date before shouldUpdate runs.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated PR to use all the options instead of availableOptions.

@Rajdeepc Rajdeepc added the Contribution PRs from contributors label Jan 13, 2026
@preethialuru
Copy link
Collaborator Author

I have concerns about the accessibility and usability of items with identical text. Can you provide an example where this is necessary and is accessible.

Hi @nikkimk, we've a requirement where itemText can be duplicate. We cannot rely on just the itemText to handle change event. Please refer to this requirement thread in SWC channel https://cclight.slack.com/archives/CESK60MQD/p1764083843191409

@pfulton pfulton added the Status:Ready for re-review PR has had its feedback addressed and is once again ready for review. label Feb 10, 2026
Copy link
Contributor

@Rajdeepc Rajdeepc left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good thinking here but I want to be careful in how to expose if safely. Kindly go through my suggestions and let me know what you think.
Once these are addressed we can revisit the changeset and JSDoc which also needs to be updated.

this.itemValue = selected?.value || '';
this._menuSelectedValue = selected?.value || '';
this.value = selected?.itemText || '';
this.handleChange();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sp-menu fires its own change event with bubbles: true, composed: true. That event propagates up through the shadow DOM and reaches consumers listening on <sp-combobox>. event.preventDefault() does not stop propagation -- it only prevents the browser's default action.
Then this.handleChange() dispatches a second CustomEvent('change', ...). Consumers will receive two change events per selection: the menu's original plain Event (no detail) and the new CustomEvent (with detail).
Please call event.stopPropagation() to prevent the menu's change from leaking out.

Comment on lines +328 to +340
protected override handleChange(): void {
this.dispatchEvent(
new CustomEvent('change', {
bubbles: true,
composed: true,
detail: {
value: this.itemValue,
itemText: this.value,
},
})
);
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@preethialuru Your use case is valid but I see ther eis big problem changing the event contract. It effects all change events not just menu selection. If you need itemValue we can expose it as a public reactive property rather than changing the event contract. You can add a public @Property for the selected option's value:

@property({ type: String, attribute: 'selected-value' })
public selectedValue = '';

Then you can capture it on your app side by

combobox.addEventListener('change', () => {
    const itemText = combobox.value;           // display text
    const value = combobox.selectedValue;      // underlying ID
    api.save({ id: value, name: itemText });
});

This would be non-breaking and will work for all scenarios.

* This ensures we preserve the exact selected value even when multiple
* options have the same itemText.
*/
private _menuSelectedValue: string = '';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You dont' need this. You can replace this with a boolean. You are already setting this.itemValue in line 313.. Instead add a flag here

private _valueSetByMenu = false;

(item) => item.value === target?.value
);
this.itemValue = selected?.value || '';
this._menuSelectedValue = selected?.value || '';
Copy link
Contributor

@Rajdeepc Rajdeepc Feb 17, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need of creating a shadow copy here. Raise the guard so shouldUpdate doesn't overwrite it via itemText lookup.

this.itemValue = selected?.value || '';
this._valueSetByMenu = true;

Comment on lines +366 to +374
if (this._menuSelectedValue) {
this.itemValue = this._menuSelectedValue;
this._menuSelectedValue = '';
} else {
const allOptions = this.options || this.optionEls;
this.itemValue =
allOptions.find((option) => option.itemText === this.value)
?.value ?? '';
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check the boolean guard instead of reading a shadow copy of the value

if (this._valueSetByMenu) {
            // itemValue was already set by handleMenuChange; just lower the guard.
            this._valueSetByMenu = false;
        } else {
            // Value changed from typing or programmatic set -- resolve itemValue
            // by looking up the matching option.
            const allOptions = this.options || this.optionEls;
            this.itemValue =
                allOptions.find((option) => option.itemText === this.value)
                    ?.value ?? '';
        }

@Rajdeepc
Copy link
Contributor

Hi @preethialuru , Just to let you know that this PR has been moved to a feature request rather than a bug fix. I have added some feedback on the implementation. Once you go through it let me know we can discuss and after talking to the a11y team this is where we stand.

I think we could approve the PR under these three conditions:

  1. The examples in docs and storybook  leverage the description slot to differentiate the duplicates.
  2. We add guidance under the accessibility documentation to ensure that if they are duplicates, that there is a unique description added.
  3. We verify that the screen reader reads them as as different item

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Contribution PRs from contributors Status:Ready for re-review PR has had its feedback addressed and is once again ready for review.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants