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
430 lines (393 loc) · 16.9 KB
/
Copy pathPromptEditor.tsx
File metadata and controls
430 lines (393 loc) · 16.9 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import {
type ContextItem,
type SerializedContextItem,
type SerializedPromptEditorState,
type SerializedPromptEditorValue,
getMentionOperations,
serializeContextItem,
toSerializedPromptEditorValue,
} from '@sourcegraph/cody-shared'
import { clsx } from 'clsx'
import {
$createTextNode,
$getRoot,
$getSelection,
$insertNodes,
$setSelection,
type LexicalEditor,
} from 'lexical'
import type { EditorState, SerializedEditorState, SerializedLexicalNode } from 'lexical'
import isEqual from 'lodash/isEqual'
import { type FunctionComponent, memo, useCallback, useEffect, useImperativeHandle, useRef } from 'react'
import { BaseEditor } from './BaseEditor'
import styles from './PromptEditor.module.css'
import { useSetGlobalPromptEditorConfig } from './config'
import { isEditorContentOnlyInitialContext, lexicalNodesForContextItems } from './initialContext'
import {
$insertMentions,
$selectEnd,
getContextItemsForEditor,
getWhitespace,
update,
walkContextItemMentionNodes,
} from './lexicalUtils'
import { $createContextItemMentionNode } from './nodes/ContextItemMentionNode'
import type { KeyboardEventPluginProps } from './plugins/keyboardEvent'
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
}
export 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>
}
/**
* 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,
}) => {
const editorRef = useRef<LexicalEditor>(null)
const hasSetInitialContext = useRef(false)
useImperativeHandle(
ref,
(): PromptEditorRefAPI => ({
setEditorState(state: SerializedPromptEditorState): void {
const editor = editorRef.current
if (editor) {
editor.setEditorState(editor.parseEditorState(state.lexicalEditorState))
}
},
getSerializedValue(): SerializedPromptEditorValue {
if (!editorRef.current) {
throw new Error('PromptEditor has no Lexical editor ref')
}
return toSerializedPromptEditorValue(editorRef.current)
},
setFocus(focus, { moveCursorToEnd } = {}): Promise<void> {
if (!editorRef.current) {
return Promise.resolve()
}
return setFocus(editorRef.current, { focus, moveCursorToEnd })
},
appendText(text: string): Promise<void> {
if (!editorRef.current) {
return Promise.resolve()
}
return appendText(editorRef.current, text)
},
openAtMentionMenu() {
const editor = editorRef.current
if (!editor) {
return Promise.resolve()
}
if (toSerializedPromptEditorValue(editor).text.trim().endsWith('@')) {
return setFocus(editor, { focus: true, moveCursorToEnd: true })
}
return appendText(editorRef.current, '@')
},
filterMentions(filter: (item: SerializedContextItem) => boolean): Promise<void> {
if (!editorRef.current) {
return Promise.resolve()
}
return update(editorRef.current, () => {
let updated = false
walkContextItemMentionNodes($getRoot(), node => {
if (!filter(node.contextItem)) {
node.remove()
updated = true
}
})
return updated
})
},
async addMentions(
items: ContextItem[],
position: 'before' | 'after' = 'after',
sep = ' '
): Promise<void> {
const editor = editorRef.current
if (!editor) {
return
}
const newContextItems = items.map(serializeContextItem)
const existingMentions = getContextItemsForEditor(editor)
const ops = getMentionOperations(existingMentions, newContextItems)
await update(editor, () => {
if (ops.modify.size + ops.delete.size === 0) {
return false
}
walkContextItemMentionNodes($getRoot(), existing => {
const update = ops.modify.get(existing.contextItem)
if (update) {
// replace the existing mention inline with the new one
existing.replace($createContextItemMentionNode(update))
}
if (ops.delete.has(existing.contextItem)) {
existing.remove()
}
})
return true
})
return update(editor, () => {
if (ops.create.length === 0) {
return false
}
$insertMentions(ops.create, position, sep)
$selectEnd()
return true
})
},
async upsertMentions(
items,
position = 'after',
sep = ' ',
focusEditor = true
): Promise<void> {
const editor = editorRef.current
if (!editor) {
return
}
const existingMentions = new Set(
getContextItemsForEditor(editor).map(getKeyForContextItem)
)
const toUpdate = new Map<string, ContextItem>()
for (const item of items) {
const key = getKeyForContextItem(item)
if (existingMentions.has(key)) {
toUpdate.set(key, item)
}
}
await update(editor, () => {
if (toUpdate.size === 0) {
return false
}
walkContextItemMentionNodes($getRoot(), existing => {
const update = toUpdate.get(getKeyForContextItem(existing.contextItem))
if (update) {
// replace the existing mention inline with the new one
existing.replace($createContextItemMentionNode(update))
}
})
if (focusEditor) {
$selectEnd()
} else {
// Workaround for preventing the editor from stealing focus
// (https://github.com/facebook/lexical/issues/2636#issuecomment-1184418601)
// We need this until we can use the new 'skip-dom-selection' tag as
// explained in https://lexical.dev/docs/concepts/selection#focus, introduced
// by https://github.com/facebook/lexical/pull/6894
$setSelection(null)
}
return true
})
return update(editor, () => {
if (items.length === toUpdate.size) {
return false
}
$insertMentions(
items.filter(item => !toUpdate.has(getKeyForContextItem(item))),
position,
sep
)
if (focusEditor) {
$selectEnd()
} else {
// Workaround for preventing the editor from stealing focus
// (https://github.com/facebook/lexical/issues/2636#issuecomment-1184418601)
// We need this until we can use the new 'skip-dom-selection' tag as
// explained in https://lexical.dev/docs/concepts/selection#focus, introduced
// by https://github.com/facebook/lexical/pull/6894
$setSelection(null)
}
return true
})
},
setInitialContextMentions(items: ContextItem[]): Promise<void> {
const editor = editorRef.current
if (!editor) {
return Promise.resolve()
}
return update(editor, () => {
let updated = false
if (!hasSetInitialContext.current || isEditorContentOnlyInitialContext(editor)) {
if (isEditorContentOnlyInitialContext(editor)) {
// Only clear in this case so that we don't clobber any text that was
// inserted before initial context was received.
$getRoot().clear()
updated = true
}
const nodesToInsert = lexicalNodesForContextItems(items, {
isFromInitialContext: true,
})
// Add whitespace after initial context items chips
if (items.length > 0) {
nodesToInsert.push($createTextNode(' '))
updated = true
}
$setSelection($getRoot().selectStart()) // insert at start
$insertNodes(nodesToInsert)
$selectEnd()
hasSetInitialContext.current = true
}
return updated
})
},
}),
[]
)
useSetGlobalPromptEditorConfig()
const onBaseEditorChange = useCallback(
(_editorState: EditorState, editor: LexicalEditor): void => {
if (onChange) {
onChange(toSerializedPromptEditorValue(editor))
}
},
[onChange]
)
useEffect(() => {
if (initialEditorState) {
const editor = editorRef.current
if (editor) {
const currentEditorState = normalizeEditorStateJSON(editor.getEditorState().toJSON())
const newEditorState = initialEditorState.lexicalEditorState
if (!isEqual(currentEditorState, newEditorState)) {
editor.setEditorState(editor.parseEditorState(newEditorState))
}
}
}
}, [initialEditorState])
return (
<BaseEditor
className={clsx(styles.editor, editorClassName, {
[styles.disabled]: disabled,
[styles.seamless]: seamless,
})}
contentEditableClassName={contentEditableClassName}
initialEditorState={initialEditorState?.lexicalEditorState ?? null}
onChange={onBaseEditorChange}
onFocusChange={onFocusChange}
contextWindowSizeInTokens={contextWindowSizeInTokens}
editorRef={editorRef}
placeholder={placeholder}
disabled={disabled}
aria-label="Chat message"
onEnterKey={onEnterKey}
openExternalLink={openExternalLink}
/>
)
},
isEqual
)
function appendText(editor: LexicalEditor, text: string): Promise<void> {
return update(editor, () => {
const root = $getRoot()
root.selectEnd()
$insertNodes([$createTextNode(`${getWhitespace(root)}${text}`)])
root.selectEnd()
return true
})
}
function setFocus(
editor: LexicalEditor,
{ focus, moveCursorToEnd }: { focus?: boolean; moveCursorToEnd?: boolean }
): Promise<void> {
return new Promise(resolve => {
if (focus) {
editor.update(
() => {
const selection = $getSelection()
const root = $getRoot()
// Copied from LexicalEditor#focus, but we need to set the
// `skip-scroll-into-view` tag so that we don't always autoscroll.
if (selection !== null) {
selection.dirty = true
} else if (root.getChildrenSize() !== 0) {
root.selectEnd()
}
if (moveCursorToEnd) {
root.selectEnd()
}
// Ensure element is focused in case the editor is empty. Copied
// from LexicalAutoFocusPlugin.
const doFocus = () => editor.getRootElement()?.focus({ preventScroll: false })
doFocus()
// HACK(sqs): Needed in VS Code webviews to actually get it to focus
// on initial load, for some reason.
setTimeout(doFocus)
},
{ tag: 'skip-scroll-into-view', onUpdate: resolve }
)
} else {
editor.blur()
resolve?.()
}
})
}
/**
* 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))
}
/**
* Computes a unique key for a context item that can be used in e.g. a Map.
*
* The URI is not sufficient to uniquely identify a context item because the same URI can be used
* for different types of context items or, in case of openctx, different provider URIs.
*/
function getKeyForContextItem(item: SerializedContextItem | ContextItem): string {
let key = `${item.uri.toString()}|${item.type}`
if (item.type === 'openctx') {
key += `|${item.providerUri}`
}
return key
}