| 1 | import { useEffect, useRef } from "react"; |
| 2 | import { topicShortcutIndexFromEvent, useTopicShortcuts, type TopicShortcutEntry } from "../lib/topicShortcuts"; |
| 3 | import type { ShortcutPlatform } from "../lib/keyboardShortcuts"; |
| 4 | import { useCommittedCommand } from "../lib/useCommittedCommand"; |
| 5 | |
| 6 | export function useTopicNavigationShortcuts(input: { |
| 7 | enabled: boolean; |
| 8 | platform: ShortcutPlatform; |
| 9 | onNavigate: (entry: TopicShortcutEntry) => void; |
| 10 | }) { |
| 11 | const topicsRef = useRef<readonly TopicShortcutEntry[]>([]); |
| 12 | const onNavigate = useCommittedCommand(input.onNavigate); |
| 13 | const { showBadges } = useTopicShortcuts(input.enabled, input.platform); |
| 14 | useEffect(() => { |
| 15 | if (!input.enabled) return; |
| 16 | const onKeydown = (event: globalThis.KeyboardEvent) => { |
| 17 | const index = topicShortcutIndexFromEvent(event, input.platform); |
| 18 | if (index === null || index >= topicsRef.current.length) return; |
| 19 | event.preventDefault(); |
| 20 | onNavigate(topicsRef.current[index]); |
| 21 | }; |
| 22 | document.addEventListener("keydown", onKeydown); |
| 23 | return () => document.removeEventListener("keydown", onKeydown); |
| 24 | }, [input.enabled, input.platform, onNavigate]); |
| 25 | return { |
| 26 | showBadges, |
| 27 | setVisibleTopics: useCommittedCommand((topics: TopicShortcutEntry[]) => { topicsRef.current = topics; }), |
| 28 | }; |
| 29 | } |
| 30 |