import React, { useCallback, useEffect, useRef } from "react" import { getMatchingSlashCommands, SlashCommand } from "@/utils/slash-commands" interface SlashCommandMenuProps { onSelect: (command: SlashCommand) => void selectedIndex: number setSelectedIndex: (index: number) => void onMouseDown: () => void query: string localWorkflowToggles?: Record globalWorkflowToggles?: Record remoteWorkflowToggles?: Record remoteWorkflows?: any[] } const SlashCommandMenu: React.FC = ({ onSelect, selectedIndex, setSelectedIndex, onMouseDown, query, localWorkflowToggles = {}, globalWorkflowToggles = {}, remoteWorkflowToggles, remoteWorkflows, }) => { const menuRef = useRef(null) const handleClick = useCallback( (command: SlashCommand) => { onSelect(command) }, [onSelect], ) useEffect(() => { if (menuRef.current) { const selectedElement = menuRef.current.querySelector(`#slash-command-menu-item-${selectedIndex}`) as HTMLElement if (selectedElement) { const menuRect = menuRef.current.getBoundingClientRect() const selectedRect = selectedElement.getBoundingClientRect() if (selectedRect.bottom > menuRect.bottom) { menuRef.current.scrollTop += selectedRect.bottom - menuRect.bottom } else if (selectedRect.top < menuRect.top) { menuRef.current.scrollTop -= menuRect.top - selectedRect.top } } } }, [selectedIndex]) // Filter commands based on query const filteredCommands = getMatchingSlashCommands( query, localWorkflowToggles, globalWorkflowToggles, remoteWorkflowToggles, remoteWorkflows, ) const defaultCommands = filteredCommands.filter((cmd) => cmd.section === "default" || !cmd.section) const workflowCommands = filteredCommands.filter((cmd) => cmd.section === "custom") // Create a reusable function for rendering a command section const renderCommandSection = (commands: SlashCommand[], title: string, indexOffset: number, showDescriptions: boolean) => { if (commands.length === 0) { return null } return ( <>
{title}
{commands.map((command, index) => { const itemIndex = index + indexOffset return (
handleClick(command)} onMouseEnter={() => setSelectedIndex(itemIndex)}>
/{command.name}
{showDescriptions && command.description && (
{command.description}
)}
) })} ) } return (
{filteredCommands.length > 0 ? ( <> {renderCommandSection(defaultCommands, "Default Commands", 0, true)} {renderCommandSection(workflowCommands, "Workflow Commands", defaultCommands.length, false)} ) : (
No matching commands found
)}
) } export default SlashCommandMenu