summaryrefslogtreecommitdiff
path: root/packages/cli/src/ui/hooks/useReverseSearchCompletion.tsx
blob: 3fb9217ed276f7d84400cb896c3e8ff8e8b827e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { useEffect, useCallback } from 'react';
import { useCompletion } from './useCompletion.js';
import { TextBuffer } from '../components/shared/text-buffer.js';
import { Suggestion } from '../components/SuggestionsDisplay.js';

export interface UseReverseSearchCompletionReturn {
  suggestions: Suggestion[];
  activeSuggestionIndex: number;
  visibleStartIndex: number;
  showSuggestions: boolean;
  isLoadingSuggestions: boolean;
  navigateUp: () => void;
  navigateDown: () => void;
  handleAutocomplete: (i: number) => void;
  resetCompletionState: () => void;
}

export function useReverseSearchCompletion(
  buffer: TextBuffer,
  shellHistory: readonly string[],
  reverseSearchActive: boolean,
): UseReverseSearchCompletionReturn {
  const {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    showSuggestions,
    isLoadingSuggestions,

    setSuggestions,
    setShowSuggestions,
    setActiveSuggestionIndex,
    resetCompletionState,
    navigateUp,
    navigateDown,
  } = useCompletion();

  useEffect(() => {
    if (!reverseSearchActive) {
      resetCompletionState();
    }
  }, [reverseSearchActive, resetCompletionState]);

  useEffect(() => {
    if (!reverseSearchActive) {
      return;
    }

    const q = buffer.text.toLowerCase();
    const matches = shellHistory.reduce<Suggestion[]>((acc, cmd) => {
      const idx = cmd.toLowerCase().indexOf(q);
      if (idx !== -1) {
        acc.push({ label: cmd, value: cmd, matchedIndex: idx });
      }
      return acc;
    }, []);

    setSuggestions(matches);
    setShowSuggestions(matches.length > 0);
    setActiveSuggestionIndex(matches.length > 0 ? 0 : -1);
  }, [
    buffer.text,
    shellHistory,
    reverseSearchActive,
    setActiveSuggestionIndex,
    setShowSuggestions,
    setSuggestions,
  ]);

  const handleAutocomplete = useCallback(
    (i: number) => {
      if (i < 0 || i >= suggestions.length) return;
      buffer.setText(suggestions[i].value);
      resetCompletionState();
    },
    [buffer, suggestions, resetCompletionState],
  );

  return {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    showSuggestions,
    isLoadingSuggestions,
    navigateUp,
    navigateDown,
    handleAutocomplete,
    resetCompletionState,
  };
}