Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(radio-button-group): no longer focus first radio button on label click and adds setFocus method. #7050

Merged
Merged
Show file tree
Hide file tree
Changes from 16 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
@@ -1,6 +1,7 @@
import { newE2EPage } from "@stencil/core/testing";
import { accessible, defaults, hidden, reflects, renders } from "../../tests/commonTests";
import { accessible, defaults, focusable, hidden, reflects, renders } from "../../tests/commonTests";
import { html } from "../../../support/formatting";
import { getFocusedElementProp } from "../../tests/utils";

describe("calcite-radio-button-group", () => {
describe("renders", () => {
Expand All @@ -20,6 +21,22 @@ describe("calcite-radio-button-group", () => {
]);
});

describe("is focusable", () => {
focusable(
html`<calcite-radio-button-group name="Options" layout="vertical">
<calcite-label layout="inline">
<calcite-radio-button value="flowers" disabled></calcite-radio-button>
Flowers
</calcite-label>
<calcite-label layout="inline">
<calcite-radio-button value="trees"></calcite-radio-button>
Trees
</calcite-label>
</calcite-radio-button-group>`,
{ focusTargetSelector: "calcite-radio-button" }
);
});

describe("honors hidden attribute", () => {
hidden("calcite-radio-button");

Expand Down Expand Up @@ -452,4 +469,52 @@ describe("calcite-radio-button-group", () => {
expect(changeEvent).toHaveReceivedEventTimes(3);
expect(await getSelectedItemValue()).toBe("three");
});

it("should focus the checked radio-button on setFocus()", async () => {
const page = await newE2EPage();
await page.setContent(html`
<calcite-radio-button-group name="Options" layout="vertical">
<calcite-label layout="inline">
<calcite-radio-button value="trees" disabled id="trees"></calcite-radio-button>
Trees
</calcite-label>
<calcite-label layout="inline">
<calcite-radio-button value="shrubs" id="shrubs"></calcite-radio-button>
Shrubs
</calcite-label>
<calcite-label layout="inline">
<calcite-radio-button value="flowers" id="flowers" checked></calcite-radio-button>
Flowers
</calcite-label>
</calcite-radio-button-group>
`);
const group = await page.find("calcite-radio-button-group");
await group.callMethod("setFocus");
await page.waitForChanges();
expect(await getFocusedElementProp(page, "id")).toBe("flowers");
});

it("should focus the first focusable radio-button on setFocus()", async () => {
const page = await newE2EPage();
await page.setContent(html`
<calcite-radio-button-group name="Options" layout="vertical">
<calcite-label layout="inline">
<calcite-radio-button value="trees" disabled id="trees"></calcite-radio-button>
Trees
</calcite-label>
<calcite-label layout="inline">
<calcite-radio-button value="shrubs" id="shrubs"></calcite-radio-button>
Shrubs
</calcite-label>
<calcite-label layout="inline">
<calcite-radio-button value="flowers" id="flowers"></calcite-radio-button>
Flowers
</calcite-label>
</calcite-radio-button-group>
`);
const group = await page.find("calcite-radio-button-group");
await group.callMethod("setFocus");
await page.waitForChanges();
expect(await getFocusedElementProp(page, "id")).toBe("shrubs");
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,30 @@ import {
h,
Host,
Listen,
Method,
Prop,
State,
VNode,
Watch
} from "@stencil/core";
import { createObserver } from "../../utils/observers";
import { Layout, Scale } from "../interfaces";
import {
componentLoaded,
LoadableComponent,
setComponentLoaded,
setUpLoadableComponent
} from "../../utils/loadable";

/**
* @slot - A slot for adding `calcite-radio-button`s.
*/
@Component({
tag: "calcite-radio-button-group",
styleUrl: "radio-button-group.scss",
shadow: {
delegatesFocus: true
driskull marked this conversation as resolved.
Show resolved Hide resolved
}
shadow: true
})
export class RadioButtonGroup {
export class RadioButtonGroup implements LoadableComponent {
//--------------------------------------------------------------------------
//
// Element
Expand Down Expand Up @@ -91,6 +97,8 @@ export class RadioButtonGroup {

mutationObserver = createObserver("mutation", () => this.passPropsToRadioButtons());

@State() radioButtons: HTMLCalciteRadioButtonElement[] = [];

//--------------------------------------------------------------------------
//
// Lifecycle
Expand All @@ -102,6 +110,14 @@ export class RadioButtonGroup {
this.mutationObserver?.observe(this.el, { childList: true, subtree: true });
}

componentWillLoad(): void {
setUpLoadableComponent(this);
}

componentDidLoad(): void {
setComponentLoaded(this);
}

disconnectedCallback(): void {
this.mutationObserver?.disconnect();
}
Expand All @@ -113,10 +129,11 @@ export class RadioButtonGroup {
//--------------------------------------------------------------------------

private passPropsToRadioButtons = (): void => {
const radioButtons = this.el.querySelectorAll("calcite-radio-button");
this.selectedItem = Array.from(radioButtons).find((radioButton) => radioButton.checked) || null;
if (radioButtons.length > 0) {
radioButtons.forEach((radioButton) => {
this.radioButtons = Array.from(this.el.querySelectorAll("calcite-radio-button"));
this.selectedItem =
Array.from(this.radioButtons).find((radioButton) => radioButton.checked) || null;
if (this.radioButtons.length > 0) {
this.radioButtons.forEach((radioButton) => {
radioButton.disabled = this.disabled || radioButton.disabled;
radioButton.hidden = this.hidden;
radioButton.name = this.name;
Expand All @@ -126,6 +143,11 @@ export class RadioButtonGroup {
}
};

private getFocusableRadioButton(): HTMLCalciteRadioButtonElement | null {
Copy link
Member

Choose a reason for hiding this comment

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

Can you use array.find instead of the while loop?

return this.radioButtons.find((radioButton) => !radioButton.disabled);

Copy link
Member

Choose a reason for hiding this comment

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

The other option would to be to use the tabbable dependency to just get the first tabbable element and focus it.

const index = this.radioButtons.findIndex((radiobutton) => !radiobutton.disabled);
return index >= 0 ? this.radioButtons[index] : null;
Copy link
Member

Choose a reason for hiding this comment

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

@anveshmekala if you're returning the button, why not just use .find() instead of .findIndex?

return this.radioButtons.find((radioButton) => !radiobutton.disabled) ?? null;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

my bad, i checked in the wrong commit. .find( ) is the optimal choice here.

}

//--------------------------------------------------------------------------
//
// Events
Expand All @@ -137,6 +159,25 @@ export class RadioButtonGroup {
*/
@Event({ cancelable: false }) calciteRadioButtonGroupChange: EventEmitter<void>;

//--------------------------------------------------------------------------
//
// Public Method
//
//--------------------------------------------------------------------------

/** Sets focus on the fist focusable `calcite-radio-button` element in the component. */
@Method()
async setFocus(): Promise<void> {
await componentLoaded(this);
if (this.selectedItem && !this.selectedItem.disabled) {
this.selectedItem.setFocus();
return;
}
if (this.radioButtons.length > 0) {
this.getFocusableRadioButton()?.setFocus();
}
}

//--------------------------------------------------------------------------
//
// Event Listeners
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,12 @@ export class RadioButton
) as HTMLCalciteRadioButtonElement[];
};

isDefaultSelectable = (): boolean => {
isFocusable = (): boolean => {
const radioButtons = this.queryButtons();
return !radioButtons.some((radioButton) => radioButton.checked) && radioButtons[0] === this.el;
return (
!radioButtons.some((radioButton) => radioButton.checked) &&
(radioButtons[0] === this.el || radioButtons[0]?.disabled)
);
};

check = (): void => {
Expand Down Expand Up @@ -275,7 +278,7 @@ export class RadioButton
if (this.disabled) {
return undefined;
}
return this.checked || this.isDefaultSelectable() ? 0 : -1;
return this.checked || this.isFocusable() ? 0 : -1;
Copy link
Member

Choose a reason for hiding this comment

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

If a radio-button is added as the first radio-button after all the other radio buttons have already been added to the DOM my guess is that there will be two focusable radio buttons.

We may want to consider creating a registry of radio buttons that are keyed by the name property so that we can ensure only one is ever focusable. @anveshmekala what do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

While testing the above edge case found out an issue with the focusable logic. tabIndex=0 is being assigned to all the tabbable radio-buttons if the first radio button is disabled due to async execution of isFocusable method in each radio-button component.

Regarding the addition of new radio-button after the initial component load, once the above is fixed it wouldn't let two radio-buttons having tabIndex=0 but the first focusable radio-button wont be updated. Using registry may not help since it is specific to each radio-button and any updates (Ex: tabIndex) to the siblings wont trigger updates to the registry.

Copy link
Member

Choose a reason for hiding this comment

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

Since radio button's don't always belong to a group we can't rely on a mutation observer of a parent group so we likely need some kind of map/registry to maintain the active focusable radio button for a specific name property. This logic would make sure only one radio button with the same name value can be focusable. It should be set/updated anytime a radio-button connectedCallback/disconnectedCallback occurs.

Copy link
Member

Choose a reason for hiding this comment

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

Probably something like...

type RootNode = Document | ShadowRoot;
type ActiveRadioButtonLookup = WeakMap<RootNode, Map<string, HTMLCalciteRadioButtonElement>>;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

There is a method queryButtons in radio-button component which queries all the radio-buttons with a similar name for a given radio-button. This will ensure any mutations to the tabIndex attribute of radio-button will be in the same group.

I tried addressing edge cases with the existing setup but it is breaking other features. Will probably split this PR tomorrow in to individual PR's since the issue we have is related to#7113 and prototype with WeakMap.

}

//--------------------------------------------------------------------------
Expand Down