Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -552,3 +552,39 @@ describe("ic-radio-group", () => {
expect(fieldset?.hasAttribute("aria-label")).toBe(false);
});
});

describe("ic-radio-group option ids", () => {
it("keeps label targets unique across repeated radio groups", async () => {
const page = await newSpecPage({
components: [RadioGroup, RadioOption],
html: `<div>
<ic-radio-group label="Test" name="test-0">
<ic-radio-option label="Option A" value="a"></ic-radio-option>
<ic-radio-option label="Option B" value="b"></ic-radio-option>
</ic-radio-group>
<ic-radio-group label="Test" name="test-1">
<ic-radio-option label="Option A" value="a"></ic-radio-option>
<ic-radio-option label="Option B" value="b"></ic-radio-option>
</ic-radio-group>
</div>`,
});

await page.waitForChanges();

const radioOptions = Array.from(
page.doc.querySelectorAll("ic-radio-option")
);
const inputs = radioOptions.map((option) =>
option.querySelector<HTMLInputElement>('input[type="radio"]')
);
const labels = radioOptions.map((option) =>
option.querySelector<HTMLLabelElement>("label")
);
const ids = inputs.map((input) => input?.id);

expect(new Set(ids).size).toBe(ids.length);
labels.forEach((label, index) => {
expect(label?.getAttribute("htmlfor")).toBe(inputs[index]?.id);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -247,13 +247,29 @@ export class RadioOption {
this.selected = this.initiallySelected;
};

private getRadioOptionId = (): string => {
const radioGroups = Array.from(
this.el.ownerDocument.querySelectorAll("ic-radio-group")
) as HTMLIcRadioGroupElement[];
const matchingGroupLabels = radioGroups.filter(
(radioGroup) => radioGroup.label === this.groupLabel
).length;
const groupIdentifier =
matchingGroupLabels > 1 && this.name
? `${this.groupLabel}-${this.name}`
: this.groupLabel;

return `ic-radio-option-${
isPropDefined(this.label) || this.value
}-${groupIdentifier}`;
};

render() {
const {
additionalFieldDisplay,
disabled,
dynamicText,
form,
groupLabel,
handleClick,
handleKeyDown,
hasAdditionalField,
Expand All @@ -264,7 +280,7 @@ export class RadioOption {
theme,
} = this;

const id = `ic-radio-option-${isPropDefined(label) || value}-${groupLabel}`;
const id = this.getRadioOptionId();

return (
<Host
Expand Down