This repository was archived by the owner on Aug 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 488
Expand file tree
/
Copy pathPromptEditor.tsx
More file actions
409 lines (374 loc) · 15.4 KB
/
Copy pathPromptEditor.tsx
File metadata and controls
409 lines (374 loc) · 15.4 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import {
type ContextItem,
ContextItemSource,
type ContextMentionProviderMetadata,
FILE_CONTEXT_MENTION_PROVIDER,
FILE_RANGE_TOOLTIP_LABEL,
NO_SYMBOL_MATCHES_HELP_LABEL,
REMOTE_DIRECTORY_PROVIDER_URI,
REMOTE_FILE_PROVIDER_URI,
SYMBOL_CONTEXT_MENTION_PROVIDER,
type SerializedContextItem,
type SerializedPromptEditorState,
type SerializedPromptEditorValue,
combineLatest,
parseMentionQuery,
} from '@sourcegraph/cody-shared'
import { clsx } from 'clsx'
import type { SerializedEditorState, SerializedLexicalNode } from 'lexical'
import isEqual from 'lodash/isEqual'
import {
type FunctionComponent,
memo,
useCallback,
useContext,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
} from 'react'
import { ChatMentionContext } from '../plugins/atMentions/useChatContextItems'
import type { KeyboardEventPluginProps } from '../plugins/keyboardEvent'
import { useExtensionAPI } from '../useExtensionAPI'
import styles from './PromptEditor.module.css'
import { fromSerializedPromptEditorState, toSerializedPromptEditorValue } from './lexical-interop'
import { schema } from './promptInput'
import 'prosemirror-view/style/prosemirror.css'
import { map } from 'observable-fns'
import {
MentionMenuContextItemContent,
MentionMenuProviderItemContent,
} from '../mentions/mentionMenu/MentionMenuItem'
import { useDefaultContextForChat } from '../useInitialContext'
import { MentionsMenu } from './MentionsMenu'
import { useMentionsMenu, usePromptInput } from './promptInput-react'
interface Props extends KeyboardEventPluginProps {
editorClassName?: string
contentEditableClassName?: string
seamless?: boolean
placeholder?: string
initialEditorState?: SerializedPromptEditorState
onChange?: (value: SerializedPromptEditorValue) => void
onFocusChange?: (focused: boolean) => void
contextWindowSizeInTokens?: number
disabled?: boolean
editorRef?: React.RefObject<PromptEditorRefAPI>
openExternalLink: (uri: string) => void
}
interface PromptEditorRefAPI {
getSerializedValue(): SerializedPromptEditorValue
setFocus(focus: boolean, options?: { moveCursorToEnd?: boolean }): Promise<void>
appendText(text: string): Promise<void>
addMentions(items: ContextItem[], position?: 'before' | 'after', sep?: string): Promise<void>
/**
* Similar to `addMentions`, but unlike `addMentions` it doesn't merge mentions with overlapping
* ranges. Instead it updates the meta data of existing mentions with the same uri.
*
* @param items The context items to add or update.
* @param position Where to insert the mentions, before or after the current input. Defaults to 'after'.
* @param sep The separator to use between mentions. Defaults to a space.
* @param focusEditor Whether to focus the editor after updating the mentions. Defaults to true.
*/
upsertMentions(
items: ContextItem[],
position?: 'before' | 'after',
sep?: string,
focusEditor?: boolean
): Promise<void>
filterMentions(filter: (item: SerializedContextItem) => boolean): Promise<void>
setInitialContextMentions(items: ContextItem[]): Promise<void>
setEditorState(state: SerializedPromptEditorState): void
/**
* Triggers opening the at-mention menu at the end of the current input value.
*/
openAtMentionMenu(): Promise<void>
}
const SUGGESTION_LIST_LENGTH_LIMIT = 20
// These providers are hidden from the UI but still needed for functionality
// like remote file and directoryaccess
const hiddenProviders = [REMOTE_FILE_PROVIDER_URI, REMOTE_DIRECTORY_PROVIDER_URI]
/**
* The component for composing and editing prompts.
*/
export const PromptEditor: FunctionComponent<Props> = memo(
({
editorClassName,
contentEditableClassName,
seamless,
placeholder,
initialEditorState,
onChange,
onFocusChange,
contextWindowSizeInTokens,
disabled,
editorRef: ref,
onEnterKey,
openExternalLink,
}) => {
// We use the interaction ID to differentiate between different
// invocations of the mention-menu. That way upstream we don't trigger
// duplicate telemetry events for the same view
const interactionID = useRef(0)
const convertedInitialEditorState = useMemo(() => {
return initialEditorState
? schema.nodeFromJSON(fromSerializedPromptEditorState(initialEditorState))
: undefined
}, [initialEditorState])
const defaultContext = useDefaultContextForChat()
const extensionAPI = useExtensionAPI()
const mentionMenuData = extensionAPI.mentionMenuData
const mentionSettings = useContext(ChatMentionContext)
const fetchMenuData = useCallback(
({ query, provider }: { query: string; provider?: ContextMentionProviderMetadata }) => {
const initialContext = [
...defaultContext.initialContext,
...defaultContext.corpusContext,
]
const queryLower = query.toLowerCase().trim()
const filteredInitialContextItems = provider
? []
: queryLower
? initialContext.filter(item => item.title?.toLowerCase().startsWith(queryLower))
: initialContext
// NOTE: It's important to only emit after we receive new mentions menu data.
// This ensures that we display the 'old' menu items until new have arrived
// and prevents the menu from 'flickering'.
return combineLatest(
mentionMenuData({
...parseMentionQuery(query, provider ?? null),
interactionID: interactionID.current,
contextRemoteRepositoriesNames: mentionSettings.remoteRepositoriesNames,
}),
extensionAPI.frequentlyUsedContextItems()
).pipe(
map(([menuData, frequentlyUsedItems]) => {
// Get user-provided context items, limited to max suggestions and marked as user source
const items =
menuData.items
?.slice(0, SUGGESTION_LIST_LENGTH_LIMIT)
.map((item: ContextItem) => ({
...item,
source: ContextItemSource.User,
})) ?? []
// Return early with just the items if a specific provider is selected
if (provider) {
return items
}
// Filter out any hidden context providers
const providers = menuData.providers.filter(
(provider: ContextMentionProviderMetadata) =>
!hiddenProviders.includes(provider.id)
)
// With a query, show only matching items
if (query) {
return [...filteredInitialContextItems, ...providers, ...items]
}
// Filter out any frequently used items that are already in filteredInitialContextItems
const uniqueFrequentlyUsedItems = frequentlyUsedItems
.filter(
frequentItem =>
!filteredInitialContextItems.some(
initialItem =>
initialItem.uri.toString() === frequentItem.uri.toString()
)
)
.slice(0, 3)
// Without a query, include filtered frequently used items
return [
...filteredInitialContextItems,
...uniqueFrequentlyUsedItems,
...providers,
...items,
]
})
)
},
[mentionMenuData, mentionSettings, defaultContext, extensionAPI.frequentlyUsedContextItems]
)
const [input, api] = usePromptInput({
placeholder,
initialDocument: convertedInitialEditorState,
disabled,
contextWindowSizeInTokens,
onChange: doc => {
onChange?.(toSerializedPromptEditorValue(doc))
},
onFocusChange,
onEnterKey,
fetchMenuData,
openExternalLink,
})
const {
show,
items,
selectedIndex,
query,
position: menuPosition,
parent,
} = useMentionsMenu(input)
useLayoutEffect(() => {
// We increment the interaction ID when the menu is hidden because `fetchMenuData` can be
// called before the menu is shown, which would result in a different interaction ID for the
// first fetch.
if (!show) {
interactionID.current++
}
}, [show])
useImperativeHandle(
ref,
(): PromptEditorRefAPI => ({
setEditorState(state: SerializedPromptEditorState): void {
api.setDocument(schema.nodeFromJSON(fromSerializedPromptEditorState(state)))
},
getSerializedValue(): SerializedPromptEditorValue {
return toSerializedPromptEditorValue(api.getEditorState().doc)
},
async setFocus(focus, { moveCursorToEnd } = {}): Promise<void> {
api.setFocus(focus, { moveCursorToEnd })
},
async appendText(text: string): Promise<void> {
api.appendText(text)
},
async filterMentions(filter: (item: SerializedContextItem) => boolean): Promise<void> {
api.filterMentions(filter)
},
async addMentions(
items: ContextItem[],
position: 'before' | 'after' = 'after',
sep = ' '
): Promise<void> {
api.addMentions(items, position, sep)
},
async upsertMentions(
items: ContextItem[],
position: 'before' | 'after' = 'after',
sep = ' ',
focusEditor = true
): Promise<void> {
api.upsertMentions(items, position, sep, focusEditor)
},
async setInitialContextMentions(items: ContextItem[]): Promise<void> {
api.setInitialContextMentions(items)
},
async openAtMentionMenu() {
api.openAtMentionMenu()
api.setFocus(true)
},
}),
[api]
)
useEffect(() => {
if (initialEditorState) {
const currentEditorState = normalizeEditorStateJSON(api.getEditorState().doc.toJSON())
const newEditorState = fromSerializedPromptEditorState(initialEditorState)
if (!isEqual(currentEditorState, newEditorState)) {
api.setDocument(schema.nodeFromJSON(newEditorState))
}
}
}, [initialEditorState, api])
const renderItem = useCallback(
(item: ContextItem | ContextMentionProviderMetadata) => {
if ('id' in item) {
return <MentionMenuProviderItemContent provider={item} />
}
// TODO: Support item.badge
return (
<MentionMenuContextItemContent
item={item}
query={parseMentionQuery(query, parent)}
/>
)
},
[query, parent]
)
return (
<div
className={clsx(styles.editor, editorClassName, {
[styles.disabled]: disabled,
[styles.seamless]: seamless,
})}
//For compatibility with the CSS rules that target this attribute
data-lexical-editor="true"
>
<div className={clsx(styles.input, contentEditableClassName)} ref={api.ref} />
{show && (
<MentionsMenu
items={items}
selectedIndex={selectedIndex}
menuPosition={menuPosition}
getHeader={() => getItemsHeading(parent, query)}
getEmptyLabel={() => getEmptyLabel(parent, query)}
onSelect={index => api.applySuggestion(index)}
renderItem={renderItem}
/>
)}
</div>
)
},
isEqual
)
function getItemsHeading(
parentItem: ContextMentionProviderMetadata | null,
query: string
): React.ReactNode {
const mentionQuery = parseMentionQuery(query, parentItem)
if (
(!parentItem || parentItem.id === FILE_CONTEXT_MENTION_PROVIDER.id) &&
mentionQuery.maybeHasRangeSuffix
) {
return FILE_RANGE_TOOLTIP_LABEL
}
if (!parentItem) {
return ''
}
if (
parentItem.id === SYMBOL_CONTEXT_MENTION_PROVIDER.id ||
parentItem.id === FILE_CONTEXT_MENTION_PROVIDER.id
) {
// Don't show heading for these common types because it's just noisy.
return ''
}
if (parentItem.id === REMOTE_DIRECTORY_PROVIDER_URI) {
return (
<div className="tw-flex tw-flex-gap-2 tw-items-center tw-justify-between">
<div>
{mentionQuery.text.includes(':')
? 'Directory - Select or search for a directory*'
: 'Directory - Select a repository*'}
</div>
<div
className={clsx(
'tw-text-xs tw-rounded tw-px-2 tw-text-foreground',
styles.experimental
)}
>
Experimental
</div>
</div>
)
}
return parentItem.title ?? parentItem.id
}
function getEmptyLabel(parentItem: ContextMentionProviderMetadata | null, query: string): string {
const mentionQuery = parseMentionQuery(query, parentItem)
if (!mentionQuery.text) {
return parentItem?.queryLabel ?? 'Search...'
}
if (!parentItem) {
return FILE_CONTEXT_MENTION_PROVIDER.emptyLabel!
}
if (parentItem.id === SYMBOL_CONTEXT_MENTION_PROVIDER.id && mentionQuery.text.length < 3) {
return SYMBOL_CONTEXT_MENTION_PROVIDER.emptyLabel! + NO_SYMBOL_MATCHES_HELP_LABEL
}
return parentItem.emptyLabel ?? 'No results'
}
/**
* Remove properties whose value is undefined, so that this value is the same (for deep-equality) in
* JavaScript if it is JSON.stringify'd and re-JSON.parse'd.
*/
function normalizeEditorStateJSON(
value: SerializedEditorState<SerializedLexicalNode>
): SerializedEditorState<SerializedLexicalNode> {
return JSON.parse(JSON.stringify(value))
}