-
Notifications
You must be signed in to change notification settings - Fork 251
Expand file tree
/
Copy pathAutocompletePrompt.tsx
More file actions
188 lines (172 loc) · 6 KB
/
AutocompletePrompt.tsx
File metadata and controls
188 lines (172 loc) · 6 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import {SelectInput, SelectInputProps, Item as SelectItem} from './SelectInput.js'
import {InfoTableProps} from './Prompts/InfoTable.js'
import {TextInput} from './TextInput.js'
import {InfoMessageProps} from './Prompts/InfoMessage.js'
import {Message, PromptLayout} from './Prompts/PromptLayout.js'
import {throttle} from '../../../../public/common/function.js'
import {AbortSignal} from '../../../../public/node/abort.js'
import useDeferredUnmount from '../hooks/use-deferred-unmount.js'
import usePrompt, {PromptState} from '../hooks/use-prompt.js'
import React, {ReactElement, useCallback, useEffect, useRef, useState} from 'react'
import {Box} from 'ink'
export interface SearchResults<T> {
data: SelectItem<T>[]
meta?: {
hasNextPage: boolean
}
}
export interface AutocompletePromptProps<T> {
message: Message
choices: SelectInputProps<T>['items']
onSubmit: (value: T) => void
infoTable?: InfoTableProps['table']
hasMorePages?: boolean
search: (term: string) => Promise<SearchResults<T>>
abortSignal?: AbortSignal
infoMessage?: InfoMessageProps['message']
groupOrder?: string[]
}
const MIN_NUMBER_OF_ITEMS_FOR_SEARCH = 5
function AutocompletePrompt<T>({
message,
choices,
infoTable,
onSubmit,
search,
hasMorePages: initialHasMorePages = false,
abortSignal,
infoMessage,
groupOrder,
}: React.PropsWithChildren<AutocompletePromptProps<T>>): ReactElement | null {
const unmountInk = useDeferredUnmount()
const [searchTerm, setSearchTerm] = useState('')
const [searchResults, setSearchResults] = useState<SelectItem<T>[]>(choices)
const canSearch = choices.length > MIN_NUMBER_OF_ITEMS_FOR_SEARCH
const [hasMorePages, setHasMorePages] = useState(initialHasMorePages)
const {promptState, setPromptState, answer, setAnswer} = usePrompt<SelectItem<T> | undefined>({
initialAnswer: undefined,
})
const paginatedSearch = useCallback(
async (term: string) => {
const results = await search(term)
return results
},
[search],
)
const submitAnswer = useCallback(
(answer: SelectItem<T>) => {
if (promptState === PromptState.Idle) {
setAnswer(answer)
setPromptState(PromptState.Submitted)
}
},
[promptState, setAnswer, setPromptState],
)
useEffect(() => {
if (promptState === PromptState.Submitted && answer) {
setSearchTerm('')
onSubmit(answer.value)
unmountInk()
}
}, [answer, onSubmit, promptState, unmountInk])
const setLoadingWhenSlow = useRef<NodeJS.Timeout>()
// we want to set it each time so that searchTermRef always tracks searchTerm,
// this is NOT the same as writing useRef(searchTerm)
const searchTermRef = useRef('')
searchTermRef.current = searchTerm
// Keep current values in refs to avoid stale closures
const choicesRef = useRef(choices)
choicesRef.current = choices
const initialHasPagesRef = useRef(initialHasMorePages)
initialHasPagesRef.current = initialHasMorePages
// useMemo ensures debounceSearch is not recreated on every render
const debounceSearch = React.useMemo(
() =>
throttle(
(term: string) => {
setLoadingWhenSlow.current = setTimeout(() => {
setPromptState(PromptState.Loading)
}, 100)
paginatedSearch(term)
.then((result) => {
// while we were waiting for the promise to resolve, the user
// has emptied the search term, so we want to show the default
// choices instead
if (searchTermRef.current.length === 0) {
setSearchResults(choicesRef.current)
setHasMorePages(initialHasPagesRef.current)
} else {
setSearchResults(result.data)
setHasMorePages(result.meta?.hasNextPage ?? false)
}
setPromptState(PromptState.Idle)
})
.catch(() => {
setPromptState(PromptState.Error)
})
.finally(() => {
clearTimeout(setLoadingWhenSlow.current)
})
},
400,
{leading: true, trailing: true},
),
[paginatedSearch, setPromptState],
)
return (
<PromptLayout
message={message}
state={promptState}
infoTable={infoTable}
infoMessage={infoMessage}
abortSignal={abortSignal}
header={
promptState !== PromptState.Submitted && canSearch ? (
<Box marginLeft={3}>
<TextInput
value={searchTerm}
onChange={(term) => {
setSearchTerm(term)
// Update ref immediately so that the debounceSearch's .then()
// callback sees the current term. With React 19's automatic
// batching, the render (which normally updates the ref) is
// deferred, so without this the ref would be stale when the
// search Promise resolves.
searchTermRef.current = term
if (term.length > 0) {
debounceSearch(term)
} else {
debounceSearch.cancel()
setPromptState(PromptState.Idle)
setSearchResults(choices)
}
}}
placeholder="Type to search..."
/>
</Box>
) : null
}
submittedAnswerLabel={answer?.label}
input={
<SelectInput
items={searchResults}
initialItems={choices}
enableShortcuts={false}
emptyMessage="No results found."
highlightedTerm={searchTerm}
loading={promptState === PromptState.Loading}
errorMessage={
promptState === PromptState.Error
? 'There has been an error while searching. Please try again later.'
: undefined
}
hasMorePages={hasMorePages}
morePagesMessage="Find what you're looking for by typing its name."
onSubmit={submitAnswer}
groupOrder={groupOrder}
/>
}
/>
)
}
export {AutocompletePrompt}