import { jotaiStore } from "@follow/utils/jotai" import { useAtomValue } from "jotai" import { selectAtom } from "jotai/utils" import { useCallback, useMemo } from "react" import { CommandRegistry } from "../registry/registry" import type { FollowCommandId, FollowCommandMap } from "../types" export const getCommand = (id: T) => { const commands = jotaiStore.get(CommandRegistry.atom) as FollowCommandMap return id in commands ? commands[id] : null } export function useCommand(id: T): FollowCommandMap[T] | null { const commands = useAtomValue( useMemo(() => selectAtom(CommandRegistry.atom, (commands) => commands[id]), [id]), ) return commands as FollowCommandMap[T] | null } const noop = () => {} export function useRunCommandFn() { return useCallback( (id: T, args: Parameters) => { const cmd = getCommand(id) if (!cmd) return noop // @ts-expect-error - The type should be discriminated return () => cmd.run(...args) }, [], ) }