Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useSettingsSectionNavigation.ts

56 lines2.1 KB

1import { useState, type FocusEvent, type KeyboardEvent } from "react";
2​
3const SECTION = "[data-settings-section]";
4​
5/**
6 * Settings sections share one Tab stop, and arrows move focus without opening a section.
7 * The Tab stop follows the last focused section until the open section changes.
8 */
9export function useSettingsSectionNavigation(currentSection: string) {
10 const [focused, setFocused] = useState<{ section: string; page: string } | null>(null);
11 const tabStop = focused?.page === currentSection ? focused.section : currentSection;
12 const remember = (element: HTMLElement) => {
13 const section = element.dataset.settingsSection;
14 if (section) setFocused({ section, page: currentSection });
15 };
16 const onFocus = (event: FocusEvent<HTMLElement>) => {
17 if (event.target instanceof HTMLElement && event.target.matches(SECTION))
18 remember(event.target);
19 };
20 const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
21 if (
22 event.defaultPrevented ||
23 event.altKey ||
24 event.ctrlKey ||
25 event.metaKey ||
26 !(event.target instanceof HTMLElement) ||
27 !event.target.matches(SECTION)
28 )
29 return;
30 // Every section is a root leaf; Left and Right have no tree action.
31 if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
32 event.preventDefault();
33 return;
34 }
35 const items = Array.from(event.currentTarget.querySelectorAll<HTMLElement>(SECTION));
36 const index = items.indexOf(event.target);
37 const next =
38 event.key === "ArrowDown"
39 ? Math.min(index + 1, items.length - 1)
40 : event.key === "ArrowUp"
41 ? Math.max(index - 1, 0)
42 : event.key === "Home"
43 ? 0
44 : event.key === "End"
45 ? items.length - 1
46 : undefined;
47 const target = next === undefined ? undefined : items[next];
48 if (!target) return;
49 event.preventDefault();
50 remember(target);
51 target.scrollIntoView({ block: "nearest" });
52 target.focus({ preventScroll: true });
53 };
54 const tabIndexFor = (section: string) => (section === tabStop ? 0 : -1);
55 return { containerProps: { onFocus, onKeyDown }, tabIndexFor };