|
| 1 | +/** @jsxImportSource react */ |
| 2 | +import { useState, useEffect, useRef } from "react" |
| 3 | +import { Box, Text, useInput, useStdin } from "ink" |
| 4 | +import { theme } from "../theme" |
| 5 | + |
| 6 | +interface SelectOption { |
| 7 | + label: string |
| 8 | + value: string |
| 9 | +} |
| 10 | + |
| 11 | +interface SelectMenuProps { |
| 12 | + options: SelectOption[] |
| 13 | + onSelect: (value: string) => void |
| 14 | + onCancel?: () => void |
| 15 | + title?: string |
| 16 | + isActive?: boolean |
| 17 | +} |
| 18 | + |
| 19 | +export const SelectMenu = ({ options, onSelect, onCancel, title, isActive = true }: SelectMenuProps) => { |
| 20 | + const [selected, setSelected] = useState(0) |
| 21 | + const optionsRef = useRef(options) |
| 22 | + const isMounted = useRef(true) |
| 23 | + const { stdin, setRawMode, isRawModeSupported } = useStdin() |
| 24 | + |
| 25 | + optionsRef.current = options |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + isMounted.current = true |
| 29 | + return () => { |
| 30 | + isMounted.current = false |
| 31 | + } |
| 32 | + }, []) |
| 33 | + |
| 34 | + useEffect(() => { |
| 35 | + setSelected(0) |
| 36 | + }, [options.length]) |
| 37 | + |
| 38 | + useEffect(() => { |
| 39 | + if (!isRawModeSupported || !isActive) return |
| 40 | + |
| 41 | + setRawMode(true) |
| 42 | + |
| 43 | + return () => { |
| 44 | + setRawMode(false) |
| 45 | + } |
| 46 | + }, [isRawModeSupported, isActive, setRawMode]) |
| 47 | + |
| 48 | + useInput( |
| 49 | + (input, key) => { |
| 50 | + if (!isMounted.current) return |
| 51 | + |
| 52 | + const currentOptions = optionsRef.current |
| 53 | + if (!currentOptions || currentOptions.length === 0) return |
| 54 | + |
| 55 | + if (key.upArrow) { |
| 56 | + setSelected((prev) => (prev > 0 ? prev - 1 : currentOptions.length - 1)) |
| 57 | + } |
| 58 | + |
| 59 | + if (key.downArrow) { |
| 60 | + setSelected((prev) => (prev < currentOptions.length - 1 ? prev + 1 : 0)) |
| 61 | + } |
| 62 | + |
| 63 | + if (key.return) { |
| 64 | + const option = currentOptions[selected] |
| 65 | + if (option && isMounted.current) onSelect(option.value) |
| 66 | + } |
| 67 | + |
| 68 | + if (key.escape && onCancel && isMounted.current) { |
| 69 | + onCancel() |
| 70 | + } |
| 71 | + }, |
| 72 | + { isActive }, |
| 73 | + ) |
| 74 | + |
| 75 | + if (!options || options.length === 0) { |
| 76 | + return null |
| 77 | + } |
| 78 | + |
| 79 | + return ( |
| 80 | + <Box flexDirection="column"> |
| 81 | + {title && <Text color={theme.colors.primary}>{title}</Text>} |
| 82 | + {options.map((option, index) => ( |
| 83 | + <Box key={`${option.value}-${index}`}> |
| 84 | + <Text color={index === selected ? theme.colors.primary : undefined}> |
| 85 | + {index === selected ? "❯ " : " "} |
| 86 | + {option.label} |
| 87 | + </Text> |
| 88 | + </Box> |
| 89 | + ))} |
| 90 | + </Box> |
| 91 | + ) |
| 92 | +} |
0 commit comments