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
---

RovingFocus: add `orientation` to support for different arrow directions, and add support home/end buttons
- 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,7 @@ export const ToggleGroupRoot = forwardRef<HTMLDivElement, ToggleGroupProps>(
value={value}
/>
)}
<RovingFocusRoot asChild activeValue={value}>
<RovingFocusRoot asChild activeValue={value} orientation='ambiguous'>
<div className='ds-togglegroup__content' role='radiogroup'>
{children}
</div>
Expand Down
44 changes: 38 additions & 6 deletions packages/react/src/utilities/RovingFocus/RovingFocusItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,55 @@ export const RovingFocusItem = forwardRef<HTMLElement, RovingFocusItemProps>(
const focusValue =
value ?? (typeof rest.children == 'string' ? rest.children : '');

const { getOrderedItems, getRovingProps } = useRovingFocus(focusValue);
const { getOrderedItems, getRovingProps, orientation } =
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 (orientation) {
case 'horizontal':
if (e.key === 'ArrowRight') {
nextItem = getNextFocusableValue(items, focusValue);
}

if (e.key === 'ArrowLeft') {
nextItem = getPrevFocusableValue(items, focusValue);
}
break;
case 'vertical':
if (e.key === 'ArrowDown') {
nextItem = getNextFocusableValue(items, focusValue);
}

if (e.key === 'ArrowUp') {
nextItem = getPrevFocusableValue(items, focusValue);
}
break;
case 'ambiguous':
if (['ArrowRight', 'ArrowDown'].includes(e.key)) {
nextItem = getNextFocusableValue(items, focusValue);
}

if (['ArrowLeft', 'ArrowUp'].includes(e.key)) {
nextItem = getPrevFocusableValue(items, focusValue);
}
}

if (e.key === 'ArrowLeft') {
nextItem = getPrevFocusableValue(items, focusValue);
if (e.key === 'Home') {
nextItem = items[0];
}
if (e.key === 'End') {
nextItem = items[items.length - 1];
}

nextItem?.element.focus();
if (nextItem) {
e.preventDefault();
nextItem.element.focus();
}
},
});

Expand Down
144 changes: 85 additions & 59 deletions packages/react/src/utilities/RovingFocus/RovingFocusRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ type RovingFocusRootBaseProps = {
* @default false
*/
asChild?: boolean;
/**
* Changes what arrow keys are used to navigate the roving focus.
* Sets correct `aria-orientation` attribute, if `vertical` or `horizontal`.
*
* @default 'horizontal'
*/
orientation?: 'vertical' | 'horizontal' | 'ambiguous';
} & HTMLAttributes<HTMLElement>;

export type RovingFocusElement = {
Expand All @@ -34,6 +41,7 @@ export type RovingFocusProps = {
setFocusableValue: (value: string) => void;
focusableValue: string | null;
onShiftTab: () => void;
orientation: 'vertical' | 'horizontal' | 'ambiguous';
};

export const RovingFocusContext = createContext<RovingFocusProps>({
Expand All @@ -46,76 +54,94 @@ export const RovingFocusContext = createContext<RovingFocusProps>({
/* intentionally empty */
},
focusableValue: null,
orientation: 'horizontal',
});

export const RovingFocusRoot = forwardRef<
HTMLElement,
RovingFocusRootBaseProps
>(({ activeValue, asChild, onBlur, onFocus, ...rest }, ref) => {
const Component = asChild ? Slot : 'div';
>(
(
{
activeValue,
asChild,
orientation = 'horizontal',
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);
},
orientation,
}}
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();
if (focusableValue != null) {
elements.current.get(focusableValue)?.focus();
} else if (activeValue != null) {
elements.current.get(activeValue)?.focus();
} else {
orderedItems.at(0)?.element.focus();
}
}}
aria-orientation={
orientation === 'ambiguous' ? undefined : orientation
}
}}
ref={refs}
/>
</RovingFocusContext.Provider>
);
});
ref={refs}
/>
</RovingFocusContext.Provider>
);
},
);
2 changes: 2 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,13 @@ export const useRovingFocus = (value: string) => {
setFocusableValue,
focusableValue,
onShiftTab,
orientation,
} = useContext(RovingFocusContext);

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