| 20 | } |
| 21 | |
| 22 | export function useSlashCompletion(props: UseSlashCompletionProps): { |
| 23 | completionStart: number; |
| 24 | completionEnd: number; |
| 25 | } { |
| 26 | const { |
| 27 | enabled, |
| 28 | query, |
| 29 | slashCommands, |
| 30 | commandContext, |
| 31 | setSuggestions, |
| 32 | setIsLoadingSuggestions, |
| 33 | setIsPerfectMatch, |
| 34 | } = props; |
| 35 | const [completionStart, setCompletionStart] = useState(-1); |
| 36 | const [completionEnd, setCompletionEnd] = useState(-1); |
| 37 | |
| 38 | useEffect(() => { |
| 39 | if (!enabled || query === null) { |
| 40 | return; |
| 41 | } |
| 42 | |
| 43 | const fullPath = query?.substring(1) || ''; |
| 44 | const hasTrailingSpace = !!query?.endsWith(' '); |
| 45 | const rawParts = fullPath.split(/\s+/).filter((p) => p); |
| 46 | let commandPathParts = rawParts; |
| 47 | let partial = ''; |
| 48 | |
| 49 | if (!hasTrailingSpace && rawParts.length > 0) { |
| 50 | partial = rawParts[rawParts.length - 1]; |
| 51 | commandPathParts = rawParts.slice(0, -1); |
| 52 | } |
| 53 | |
| 54 | let currentLevel: readonly SlashCommand[] | undefined = slashCommands; |
| 55 | let leafCommand: SlashCommand | null = null; |
| 56 | |
| 57 | for (const part of commandPathParts) { |
| 58 | if (!currentLevel) { |
| 59 | leafCommand = null; |
| 60 | currentLevel = []; |
| 61 | break; |
| 62 | } |
| 63 | const found: SlashCommand | undefined = currentLevel.find( |
| 64 | (cmd) => cmd.name === part || cmd.altNames?.includes(part), |
| 65 | ); |
| 66 | if (found) { |
| 67 | leafCommand = found; |
| 68 | currentLevel = found.subCommands as readonly SlashCommand[] | undefined; |
| 69 | } else { |
| 70 | leafCommand = null; |
| 71 | currentLevel = []; |
| 72 | break; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | let exactMatchAsParent: SlashCommand | undefined; |
| 77 | if (!hasTrailingSpace && currentLevel) { |
| 78 | exactMatchAsParent = currentLevel.find( |
| 79 | (cmd) => |