Skip to content

Commit

Permalink
next: fix Radio Group keyboard nav (#742)
Browse files Browse the repository at this point in the history
  • Loading branch information
huntabyte authored Oct 6, 2024
1 parent 6a10c28 commit 0cbb0e0
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/tame-ads-heal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"bits-ui": patch
---

Radio Group: allow both arrow up/down and left/right per WAI-ARIA spec
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ class RadioGroupItemState {
};

#onkeydown = (e: KeyboardEvent) => {
this.#root.rovingFocusGroup.handleKeydown(this.#ref.current, e);
this.#root.rovingFocusGroup.handleKeydown(this.#ref.current, e, true);
};

#tabIndex = $derived.by(() => this.#root.rovingFocusGroup.getTabIndex(this.#ref.current));
Expand Down
13 changes: 12 additions & 1 deletion packages/bits-ui/src/lib/internal/use-roving-focus.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,11 @@ export function useRovingFocus(props: UseRovingFocusProps) {
items[0]?.focus();
}

function handleKeydown(node: HTMLElement | null | undefined, e: KeyboardEvent) {
function handleKeydown(
node: HTMLElement | null | undefined,
e: KeyboardEvent,
both: boolean = false
) {
const rootNode = document.getElementById(props.rootNodeId.current);
if (!rootNode || !node) return;

Expand All @@ -94,6 +98,13 @@ export function useRovingFocus(props: UseRovingFocusProps) {
[kbd.END]: items.length - 1,
};

if (both) {
const altNextKey = nextKey === kbd.ARROW_DOWN ? kbd.ARROW_RIGHT : kbd.ARROW_DOWN;
const altPrevKey = prevKey === kbd.ARROW_UP ? kbd.ARROW_LEFT : kbd.ARROW_UP;
keyToIndex[altNextKey] = currentIndex + 1;
keyToIndex[altPrevKey] = currentIndex - 1;
}

let itemIndex = keyToIndex[e.key];
if (itemIndex === undefined) return;
e.preventDefault();
Expand Down

0 comments on commit 0cbb0e0

Please sign in to comment.