Skip to content

Refactor/toggle #71

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

Merged
merged 3 commits into from
Mar 14, 2024
Merged
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
11 changes: 10 additions & 1 deletion lib/Checkbox/Checkbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,13 +140,22 @@ const CheckboxBase = (props: Props, ref: React.Ref<HTMLButtonElement>) => {
);
}

const rootRef = React.useRef<HTMLButtonElement>(null);

const checkBase = useCheckBase({
value,
autoFocus,
disabled,
checked: checkedProp,
groupCtx: checkGroupCtx,
defaultChecked,
selectMode: "multiple",
togglable: true,
getGroupElement: () => rootRef.current?.closest("[role='group']") ?? null,
getGroupItems: group =>
Array.from(
group.querySelectorAll<HTMLElement>(`[data-slot='${Slots.Root}']`),
),
onChange,
onBlur,
onFocus,
Expand All @@ -157,7 +166,7 @@ const CheckboxBase = (props: Props, ref: React.Ref<HTMLButtonElement>) => {
const id = useDeterministicId(idProp, "styleless-ui__checkbox");
const visibleLabelId = id ? `${id}__label` : undefined;

const handleRef = useForkedRefs(ref, checkBase.handleControllerRef);
const handleRef = useForkedRefs(ref, rootRef, checkBase.handleControllerRef);

const labelProps = getLabelInfo(label, "Checkbox");

Expand Down
3 changes: 2 additions & 1 deletion lib/Expandable/components/Content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,14 @@ const ContentBase = (props: Props, ref: React.Ref<HTMLDivElement>) => {

if (!parent) return;

const trigger = parent.querySelector<HTMLDivElement>(
const trigger = parent.querySelector<HTMLElement>(
`[data-slot="${TriggerRootSlot}"]`,
);

if (!trigger) return;

node.setAttribute("aria-labelledby", trigger.id);
trigger.setAttribute("aria-controls", id);
};

return (
Expand Down
6 changes: 5 additions & 1 deletion lib/Expandable/components/Trigger.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,21 @@ const TriggerBase = <E extends React.ElementType, R extends HTMLElement>(

const refCallback = (node: R | null) => {
setRef(ref, node);

if (!node) return;

const parent = node.closest(`[data-slot="${RootSlot}"]`);

if (!parent) return;

const content = parent.querySelector<R>(`[data-slot="${ContentRootSlot}"]`);
const content = parent.querySelector<HTMLDivElement>(
`[data-slot="${ContentRootSlot}"]`,
);

if (!content) return;

node.setAttribute("aria-controls", content.id);
content.setAttribute("aria-labelledby", id);
};

return (
Expand Down
13 changes: 10 additions & 3 deletions lib/Radio/Radio.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,23 @@ const RadioBase = (props: Props, ref: React.Ref<HTMLButtonElement>) => {
);
}

const rootRef = React.useRef<HTMLButtonElement>(null);

const checkBase = useCheckBase({
value,
groupCtx: radioGroupCtx,
checked: checkedProp,
strategy: "radio-control",
autoFocus,
disabled,
defaultChecked,
selectMode: "single",
togglable: false,
getGroupElement: () =>
rootRef.current?.closest("[role='radiogroup']") ?? null,
getGroupItems: group =>
Array.from(
group.querySelectorAll<HTMLElement>(`[data-slot='${Slots.Root}']`),
),
onChange,
onBlur,
onFocus,
Expand All @@ -147,8 +156,6 @@ const RadioBase = (props: Props, ref: React.Ref<HTMLButtonElement>) => {
const id = useDeterministicId(idProp, "styleless-ui__radio");
const visibleLabelId = id ? `${id}__label` : undefined;

const rootRef = React.useRef<HTMLButtonElement>(null);

const handleRef = useForkedRefs(ref, rootRef, checkBase.handleControllerRef);

const labelProps = getLabelInfo(label, "Radio");
Expand Down
4 changes: 4 additions & 0 deletions lib/Switch/Switch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,10 @@ const SwitchBase = (props: Props, ref: React.Ref<HTMLButtonElement>) => {
disabled,
checked: checkedProp,
defaultChecked,
selectMode: "multiple",
togglable: true,
getGroupElement: () => null,
getGroupItems: () => [],
onChange,
onBlur,
onFocus,
Expand Down
35 changes: 27 additions & 8 deletions lib/Toggle/Toggle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,29 +96,34 @@ const ToggleBase = (props: Props, ref: React.Ref<HTMLButtonElement>) => {
? {
value: toggleGroupCtx.value,
onChange: toggleGroupCtx.onChange,
items: toggleGroupCtx.toggles,
}
: null;

const rootRef = React.useRef<HTMLButtonElement>(null);

const checkBase = useCheckBase({
value,
autoFocus,
disabled,
checked: active,
toggle: true,
togglable: true,
keyboardActivationBehavior: toggleGroupCtx?.keyboardActivationBehavior,
strategy: toggleGroupCtx?.multiple ? "check-control" : "radio-control",
selectMode: toggleGroupCtx?.multiple ? "multiple" : "single",
defaultChecked: defaultActive,
enterKeyFunctionality: "check",
groupCtx,
getGroupElement: () => rootRef.current?.closest("[role='group']") ?? null,
getGroupItems: group =>
Array.from(
group.querySelectorAll<HTMLElement>(`[data-slot='${Slots.Root}']`),
),
onChange: onActiveChange,
onBlur,
onFocus,
onKeyDown,
onKeyUp,
});

const rootRef = React.useRef<HTMLButtonElement>(null);
const handleRef = useForkedRefs(ref, rootRef, checkBase.handleControllerRef);

const renderProps: RenderProps = {
Expand All @@ -144,10 +149,6 @@ const ToggleBase = (props: Props, ref: React.Ref<HTMLButtonElement>) => {

if (!node) return;

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
toggleGroupCtx?.registerToggle(value!, rootRef);
if (!toggleGroupCtx) node.tabIndex = disabled ? -1 : 0;

const accessibleName = computeAccessibleName(node);

if (!accessibleName) {
Expand All @@ -167,17 +168,35 @@ const ToggleBase = (props: Props, ref: React.Ref<HTMLButtonElement>) => {
}
};

const calcTabIndex = () => {
if (disabled) return -1;
if (!toggleGroupCtx) return 0;
if (toggleGroupCtx.multiple) return 0;

const forcedTabableItem = toggleGroupCtx.forcedTabability;

if (forcedTabableItem && forcedTabableItem === value) return 0;

const isSelected = toggleGroupCtx.value === value;

if (!isSelected) return -1;

return 0;
};

const dataAttrs = {
"data-slot": Slots.Root,
"data-active": renderProps.active ? "" : undefined,
"data-disable": renderProps.disabled ? "" : undefined,
"data-entityname": value,
"data-focus-visible": renderProps.focusedVisible ? "" : undefined,
};

return (
<button
{...otherProps}
className={className}
tabIndex={calcTabIndex()}
type="button"
ref={refCallback}
disabled={disabled}
Expand Down
8 changes: 6 additions & 2 deletions lib/ToggleGroup/ToggleGroup.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import ToggleGroup from "./ToggleGroup";

const labelText = "Label";

describe("CheckGroup", () => {
describe("ToggleGroup", () => {
afterEach(jest.clearAllMocks);

itShouldMount(ToggleGroup, { label: labelText });
Expand Down Expand Up @@ -269,10 +269,14 @@ describe("CheckGroup", () => {
expect(handleChange.mock.calls[0]?.join()).toBe("1");

await userEvent.keyboard("[ArrowRight]");
expect(toggles[2]).toHaveFocus();

expect(toggles[2]).not.toHaveFocus();
expect(toggles[1]).toHaveFocus();

await userEvent.tab();
await userEvent.keyboard("[Space]");

expect(toggles[2]).toHaveFocus();
expect(toggles[2]).toHaveAttribute("data-active");
expect(handleChange.mock.calls.length).toBe(2);
expect(handleChange.mock.calls[1]?.join()).toBe("1,2");
Expand Down
54 changes: 24 additions & 30 deletions lib/ToggleGroup/ToggleGroup.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as React from "react";
import { Root as ToggleRootSlot } from "../Toggle/slots";
import { SystemError, getLabelInfo } from "../internals";
import type { Classes, MergeElementProps } from "../types";
import {
Expand Down Expand Up @@ -94,6 +95,10 @@ const ToggleGroupBase = (props: Props, ref: React.Ref<HTMLDivElement>) => {
multiple ? [] : "",
);

const [forcedTabability, setForcedTabability] = React.useState<string | null>(
null,
);

if (multiple && !Array.isArray(value)) {
throw new SystemError(
"The `value` and `defaultValue` " +
Expand Down Expand Up @@ -123,43 +128,33 @@ const ToggleGroupBase = (props: Props, ref: React.Ref<HTMLDivElement>) => {
onChange?.(newValue);
};

const toggles: [string, React.RefObject<HTMLButtonElement>][] = [];

const registerToggle = (
toggleValue: (typeof toggles)[number][0],
toggleRef: (typeof toggles)[number][1],
) => {
if (!toggles.some(r => r[0] === toggleValue))
toggles.push([toggleValue, toggleRef]);
};

React.useEffect(() => {
if (!rootRef.current) return;

toggles.forEach(([v, tRef]) => {
if (!tRef.current) return;
if (value.length > 0) {
setForcedTabability(prev => (prev ? null : prev));

const isSelected = Array.isArray(value) ? value.includes(v) : value === v;
const isDisabled = tRef.current.hasAttribute("disabled");
return;
}

tRef.current.tabIndex = isDisabled ? -1 : isSelected ? 0 : -1;
});

const notTabable = toggles.filter(
([_, tRef]) => tRef.current?.getAttribute("tabindex") !== "0",
const toggles = Array.from(
rootRef.current.querySelectorAll<HTMLElement>(
`[data-slot='${ToggleRootSlot}']`,
),
);

if (notTabable.length !== toggles.length) return;

const toggle =
toggles.find(([_, tRef]) => !tRef.current?.hasAttribute("disabled")) ??
null;
const validToggles = toggles.filter(toggle => {
const isDisabled =
toggle.hasAttribute("disabled") ||
toggle.getAttribute("aria-disabled") === "true";

if (!toggle) return;
const [_, tRef] = toggle;
return !isDisabled;
});

tRef.current?.setAttribute("tabindex", "0");
});
setForcedTabability(
validToggles?.[0]?.getAttribute("data-entityname") ?? null,
);
}, [value]);

const renderLabel = () => {
if (!labelProps.visibleLabel) return null;
Expand Down Expand Up @@ -187,10 +182,9 @@ const ToggleGroupBase = (props: Props, ref: React.Ref<HTMLDivElement>) => {
value={{
multiple,
value,
toggles,
forcedTabability,
keyboardActivationBehavior: keyboardActivationBehavior ?? "manual",
onChange: handleChange,
registerToggle,
}}
>
{renderLabel()}
Expand Down
6 changes: 1 addition & 5 deletions lib/ToggleGroup/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,13 @@ import { type Props } from "./ToggleGroup";

type ContextValue = {
multiple: boolean;
forcedTabability: string | null;
keyboardActivationBehavior: Exclude<
Props["keyboardActivationBehavior"],
undefined
>;
value: Exclude<Props["value"], undefined>;
toggles: [string, React.RefObject<HTMLButtonElement>][];
onChange: (newActiveState: boolean, toggleValue: string) => void;
registerToggle: (
value: string,
ref: React.RefObject<HTMLButtonElement>,
) => void;
};

const Context = React.createContext<ContextValue | null>(null);
Expand Down
Loading