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

feat(RovingFocus): add support for up/down arrows and home/end buttons #2206

Merged
merged 11 commits into from
Aug 12, 2024
8 changes: 8 additions & 0 deletions .changeset/bright-knives-remain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@digdir/designsystemet-react": patch
---

RovingIndex: add support for up/down arrows and home/end buttons
mimarz marked this conversation as resolved.
Show resolved Hide resolved
- Affects `ToggleGroup`, where up and down arrows can now be used
- Affects `ToggleGroup`, where home and end can now be used
- Affects `Tabs`, where home and end can now be used
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,12 @@ export const ToggleGroupRoot = forwardRef<HTMLDivElement, ToggleGroupProps>(
value={value}
/>
)}
<RovingFocusRoot asChild activeValue={value}>
<RovingFocusRoot
asChild
activeValue={value}
verticalArrows={true}
horizontalArrows={true}
>
<div className='ds-togglegroup__content' role='radiogroup'>
{children}
</div>
Expand Down
41 changes: 34 additions & 7 deletions packages/react/src/utilities/RovingFocus/RovingFocusItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,50 @@ export const RovingFocusItem = forwardRef<HTMLElement, RovingFocusItemProps>(
const focusValue =
value ?? (typeof rest.children == 'string' ? rest.children : '');

const { getOrderedItems, getRovingProps } = useRovingFocus(focusValue);
const {
getOrderedItems,
getRovingProps,
horizontalArrows,
verticalArrows,
} = useRovingFocus(focusValue);

const rovingProps = getRovingProps<HTMLElement>({
onKeyDown: (e) => {
rest?.onKeyDown?.(e);
const items = getOrderedItems();
let nextItem: RovingFocusElement | undefined;

if (e.key === 'ArrowRight') {
nextItem = getNextFocusableValue(items, focusValue);
switch (e.key) {
case 'ArrowRight':
case 'ArrowDown':
if (
(horizontalArrows && e.key === 'ArrowRight') ||
(verticalArrows && e.key === 'ArrowDown')
) {
nextItem = getNextFocusableValue(items, focusValue);
}
break;
case 'ArrowLeft':
case 'ArrowUp':
if (
(horizontalArrows && e.key === 'ArrowLeft') ||
(verticalArrows && e.key === 'ArrowUp')
) {
nextItem = getPrevFocusableValue(items, focusValue);
}
break;
case 'Home':
nextItem = items[0];
break;
case 'End':
nextItem = items[items.length - 1];
break;
}

if (e.key === 'ArrowLeft') {
nextItem = getPrevFocusableValue(items, focusValue);
if (nextItem) {
e.preventDefault();
nextItem.element.focus();
}

nextItem?.element.focus();
},
});

Expand Down
152 changes: 92 additions & 60 deletions packages/react/src/utilities/RovingFocus/RovingFocusRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ type RovingFocusRootBaseProps = {
* @default false
*/
asChild?: boolean;
/**
* If `true`, the `RovingFocusItem` will be focusable with the left and right arrow keys.
*
* @default false
*/
verticalArrows?: boolean;
/**
* If `true`, the `RovingFocusItem` will be focusable with the up and down arrow keys.
*
* @default true
*/
horizontalArrows?: boolean;
Barsnes marked this conversation as resolved.
Show resolved Hide resolved
} & HTMLAttributes<HTMLElement>;

export type RovingFocusElement = {
Expand All @@ -34,6 +46,8 @@ export type RovingFocusProps = {
setFocusableValue: (value: string) => void;
focusableValue: string | null;
onShiftTab: () => void;
horizontalArrows: boolean;
verticalArrows: boolean;
};

export const RovingFocusContext = createContext<RovingFocusProps>({
Expand All @@ -46,76 +60,94 @@ export const RovingFocusContext = createContext<RovingFocusProps>({
/* intentionally empty */
},
focusableValue: null,
horizontalArrows: true,
verticalArrows: false,
});

export const RovingFocusRoot = forwardRef<
HTMLElement,
RovingFocusRootBaseProps
>(({ activeValue, asChild, onBlur, onFocus, ...rest }, ref) => {
const Component = asChild ? Slot : 'div';
>(
(
{
activeValue,
asChild,
verticalArrows = false,
horizontalArrows = true,
onBlur,
onFocus,
...rest
},
ref,
) => {
const Component = asChild ? Slot : 'div';

const [focusableValue, setFocusableValue] = useState<string | null>(null);
const [isShiftTabbing, setIsShiftTabbing] = useState(false);
const elements = useRef(new Map<string, HTMLElement>());
const myRef = useRef<HTMLElement>();
const [focusableValue, setFocusableValue] = useState<string | null>(null);
const [isShiftTabbing, setIsShiftTabbing] = useState(false);
const elements = useRef(new Map<string, HTMLElement>());
const myRef = useRef<HTMLElement>();

const refs = useMergeRefs([ref, myRef]);
const refs = useMergeRefs([ref, myRef]);

const getOrderedItems = (): RovingFocusElement[] => {
if (!myRef.current) return [];
const elementsFromDOM = Array.from(
myRef.current.querySelectorAll<HTMLElement>(
'[data-roving-tabindex-item]',
),
);
const getOrderedItems = (): RovingFocusElement[] => {
if (!myRef.current) return [];
const elementsFromDOM = Array.from(
myRef.current.querySelectorAll<HTMLElement>(
'[data-roving-tabindex-item]',
),
);

return Array.from(elements.current)
.sort(
(a, b) => elementsFromDOM.indexOf(a[1]) - elementsFromDOM.indexOf(b[1]),
)
.map(([value, element]) => ({ value, element }));
};
return Array.from(elements.current)
.sort(
(a, b) =>
elementsFromDOM.indexOf(a[1]) - elementsFromDOM.indexOf(b[1]),
)
.map(([value, element]) => ({ value, element }));
};

useEffect(() => {
setFocusableValue(activeValue ?? null);
}, [activeValue]);
useEffect(() => {
setFocusableValue(activeValue ?? null);
}, [activeValue]);

return (
<RovingFocusContext.Provider
value={{
elements,
getOrderedItems,
focusableValue,
setFocusableValue,
onShiftTab: () => {
setIsShiftTabbing(true);
},
}}
>
<Component
{...rest}
tabIndex={isShiftTabbing ? -1 : 0}
onBlur={(e: FocusEvent<HTMLElement>) => {
onBlur?.(e);
setIsShiftTabbing(false);
setFocusableValue(activeValue ?? null);
return (
<RovingFocusContext.Provider
value={{
elements,
getOrderedItems,
focusableValue,
setFocusableValue,
onShiftTab: () => {
setIsShiftTabbing(true);
},
horizontalArrows,
verticalArrows,
}}
onFocus={(e: FocusEvent<HTMLElement>) => {
onFocus?.(e);
if (e.target !== e.currentTarget) return;
const orderedItems = getOrderedItems();
if (orderedItems.length === 0) return;
>
<Component
{...rest}
tabIndex={isShiftTabbing ? -1 : 0}
onBlur={(e: FocusEvent<HTMLElement>) => {
onBlur?.(e);
setIsShiftTabbing(false);
setFocusableValue(activeValue ?? null);
}}
onFocus={(e: FocusEvent<HTMLElement>) => {
onFocus?.(e);
if (e.target !== e.currentTarget) return;
const orderedItems = getOrderedItems();
if (orderedItems.length === 0) return;

if (focusableValue != null) {
elements.current.get(focusableValue)?.focus();
} else if (activeValue != null) {
elements.current.get(activeValue)?.focus();
} else {
orderedItems.at(0)?.element.focus();
}
}}
ref={refs}
/>
</RovingFocusContext.Provider>
);
});
if (focusableValue != null) {
elements.current.get(focusableValue)?.focus();
} else if (activeValue != null) {
elements.current.get(activeValue)?.focus();
} else {
orderedItems.at(0)?.element.focus();
}
}}
ref={refs}
/>
</RovingFocusContext.Provider>
);
},
);
4 changes: 4 additions & 0 deletions packages/react/src/utilities/RovingFocus/useRovingFocus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,15 @@ export const useRovingFocus = (value: string) => {
setFocusableValue,
focusableValue,
onShiftTab,
horizontalArrows,
verticalArrows,
} = useContext(RovingFocusContext);

return {
getOrderedItems,
isFocusable: focusableValue === value,
horizontalArrows,
verticalArrows,
getRovingProps: <T extends HTMLElement>(props: HTMLAttributes<T>) => ({
...props,
ref: (element: HTMLElement | null) => {
Expand Down
Loading