import React, { useContext, createContext, useState, ReactNode, useEffect, } from "react"; import { Box, Text } from "./Ink"; type Shortcut = | "upArrow" | "rightArrow" | "downArrow" | "leftArrow" | "return" | "space"; type KeyboardShortcut = { name: string; key: Shortcut; }; export const KeyboardShortcutsContext = createContext<{ shortcuts: Array; setShortcuts: (shortcuts: Array) => void; }>({ shortcuts: [], setShortcuts: () => {} }); const shortcutToCharacter = (shortcut: Shortcut): string => { switch (shortcut) { case "upArrow": return "↑"; case "rightArrow": return "→"; case "downArrow": return "↓"; case "leftArrow": return "←"; case "return": return "↲"; case "space": return "␣"; } }; export const useKeyboardShortcuts = ( shortcuts: Partial>, ) => { const { setShortcuts } = useContext(KeyboardShortcutsContext); useEffect(() => { setShortcuts( (Object.entries(shortcuts) as Array<[Shortcut, { name: string }]>).map( ([key, { name }]) => ({ key, name }), ), ); }, [JSON.stringify(shortcuts)]); }; export const KeyboardShortcuts = () => { const { shortcuts } = useContext(KeyboardShortcutsContext); return ( {shortcuts.map(({ name, key }) => ( {shortcutToCharacter(key)} {name} ))} ); }; export const KeyboardShortcutsProvider = ({ children, }: { children: ReactNode; }) => { const [shortcuts, setShortcuts] = useState>([]); return ( {children} ); };