Skip to content

Commit f1c2fa6

Browse files
committed
Implement code completion ghost text functionality in the PromptField by adding logic for identifier matching and handling Tab key acceptance
1 parent 3664599 commit f1c2fa6

11 files changed

Lines changed: 277 additions & 76 deletions

File tree

‎packages/ui/src/components/editor/panel/PromptField/PromptField.module.scss‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,16 +111,17 @@
111111
}
112112
}
113113

114-
.input-with-tab-hint {
114+
.input-with-file-match-hint {
115115
&::after {
116-
content: 'TAB';
116+
content: '\\';
117117
display: inline-flex;
118118
align-items: center;
119119
justify-content: center;
120120
color: var(--cwc-text-color);
121121
font-size: 10px;
122122
padding: 0 3px;
123123
margin-left: 2px;
124+
transform: translateY(-1px);
124125
font-weight: 500;
125126
border: 1px solid var(--cwc-border-color);
126127
border-radius: 5px;

‎packages/ui/src/components/editor/panel/PromptField/PromptField.tsx‎

Lines changed: 122 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ export type PromptFieldProps = {
5858
on_caret_position_change: (caret_position: number) => void
5959
is_web_mode: boolean
6060
on_search_click: () => void
61-
on_at_sign_click: (search_value?: string) => void
61+
on_at_sign_click: () => void
6262
on_hash_sign_click: () => void
6363
on_curly_braces_click: () => void
6464
caret_position_to_set?: number
@@ -71,13 +71,15 @@ export type PromptFieldProps = {
7171
on_edit_format_change?: (format: EditFormat) => void
7272
edit_format_instructions?: Record<EditFormat, string>
7373
context_file_paths?: string[]
74+
currently_open_file_text?: string
7475
on_go_to_file?: (file_path: string) => void
7576
}
7677

7778
export const PromptField: React.FC<PromptFieldProps> = (props) => {
7879
const input_ref = useRef<HTMLDivElement>(null)
7980
const container_ref = useRef<HTMLDivElement>(null)
8081
const [caret_position, set_caret_position] = useState(0)
82+
const [ghost_text, set_ghost_text] = useState('')
8183
const [show_at_sign_tooltip, set_show_at_sign_tooltip] = useState(false)
8284
const [show_submit_tooltip, set_show_submit_tooltip] = useState(false)
8385
const [is_text_selecting, set_is_text_selecting] = useState(false)
@@ -97,7 +99,7 @@ export const PromptField: React.FC<PromptFieldProps> = (props) => {
9799
is_history_enabled,
98100
handle_copy,
99101
handle_input_click
100-
} = use_handlers(props, input_ref)
102+
} = use_handlers(props, input_ref, ghost_text, handle_accept_ghost_text)
101103
const { handle_drag_start, handle_drag_over, handle_drop, handle_drag_end } =
102104
use_drag_drop({
103105
input_ref,
@@ -108,6 +110,31 @@ export const PromptField: React.FC<PromptFieldProps> = (props) => {
108110

109111
const mouse_down_pos_ref = useRef<{ x: number; y: number } | null>(null)
110112

113+
function handle_accept_ghost_text() {
114+
if (!ghost_text || !input_ref.current) return
115+
116+
const ghost_node = input_ref.current.querySelector(
117+
'span[data-type="ghost-text"]'
118+
)
119+
if (ghost_node) {
120+
const text_node = document.createTextNode(ghost_node.textContent || '')
121+
ghost_node.parentNode?.replaceChild(text_node, ghost_node)
122+
123+
const selection = window.getSelection()
124+
if (selection) {
125+
const range = document.createRange()
126+
range.setStartAfter(text_node)
127+
range.collapse(true)
128+
selection.removeAllRanges()
129+
selection.addRange(range)
130+
}
131+
132+
input_ref.current.dispatchEvent(
133+
new Event('input', { bubbles: true, cancelable: true })
134+
)
135+
}
136+
}
137+
111138
const handle_mouse_down = useCallback(
112139
(e: React.MouseEvent<HTMLDivElement>) => {
113140
mouse_down_pos_ref.current = { x: e.clientX, y: e.clientY }
@@ -142,7 +169,7 @@ export const PromptField: React.FC<PromptFieldProps> = (props) => {
142169
return get_display_text(props.value, props.context_file_paths ?? [])
143170
}, [props.value, props.context_file_paths])
144171

145-
const show_tab_hint = useMemo(() => {
172+
const show_file_match_hint = useMemo(() => {
146173
const value = display_text
147174
if (
148175
!value ||
@@ -197,6 +224,66 @@ export const PromptField: React.FC<PromptFieldProps> = (props) => {
197224
props.context_file_paths
198225
])
199226

227+
const identifiers = useMemo(() => {
228+
if (!props.currently_open_file_text) return new Set<string>()
229+
const matches =
230+
props.currently_open_file_text.match(/[a-zA-Z_][a-zA-Z0-9_]*/g)
231+
if (!matches) return new Set<string>()
232+
return new Set(matches.filter((id) => id.length >= 3))
233+
}, [props.currently_open_file_text])
234+
235+
useEffect(() => {
236+
if (!input_ref.current) {
237+
set_ghost_text('')
238+
return
239+
}
240+
241+
const selection = window.getSelection()
242+
if (!selection || selection.rangeCount === 0) {
243+
set_ghost_text('')
244+
return
245+
}
246+
247+
const range = selection.getRangeAt(0)
248+
if (!range.collapsed) {
249+
set_ghost_text('')
250+
return
251+
}
252+
253+
const pre_caret_range = range.cloneRange()
254+
pre_caret_range.selectNodeContents(input_ref.current)
255+
pre_caret_range.setEnd(range.startContainer, range.startOffset)
256+
const text_before_cursor = pre_caret_range.toString()
257+
258+
const last_word_match = text_before_cursor.match(/[\S]+$/)
259+
if (!last_word_match) {
260+
set_ghost_text('')
261+
return
262+
}
263+
264+
const last_word_with_prefix = last_word_match[0]
265+
const word_start_match = last_word_with_prefix.match(/[a-zA-Z_]/)
266+
if (!word_start_match) {
267+
set_ghost_text('')
268+
return
269+
}
270+
const last_word = last_word_with_prefix.substring(word_start_match.index ?? 0)
271+
272+
if (last_word.length < 2) {
273+
set_ghost_text('')
274+
return
275+
}
276+
277+
for (const id of identifiers) {
278+
if (id.startsWith(last_word) && id !== last_word) {
279+
set_ghost_text(id.substring(last_word.length))
280+
return
281+
}
282+
}
283+
284+
set_ghost_text('')
285+
}, [props.value, caret_position, identifiers])
286+
200287
useEffect(() => {
201288
const input_element = input_ref.current
202289
if (input_element && input_element.innerHTML !== highlighted_html) {
@@ -273,6 +360,37 @@ export const PromptField: React.FC<PromptFieldProps> = (props) => {
273360
document.removeEventListener('selectionchange', on_selection_change)
274361
}, [props.on_caret_position_change, props.value, props.context_file_paths])
275362

363+
useEffect(() => {
364+
const input = input_ref.current
365+
if (!input) return
366+
367+
const existing_ghost = input.querySelector('span[data-type="ghost-text"]')
368+
if (existing_ghost) {
369+
const parent = existing_ghost.parentNode
370+
if (parent) {
371+
parent.removeChild(existing_ghost)
372+
parent.normalize()
373+
}
374+
}
375+
376+
if (ghost_text) {
377+
const selection = window.getSelection()
378+
if (selection && selection.rangeCount > 0) {
379+
const range = selection.getRangeAt(0)
380+
if (range.collapsed) {
381+
const span = document.createElement('span')
382+
span.dataset.type = 'ghost-text'
383+
span.textContent = ghost_text
384+
span.style.color = 'var(--vscode-editorGhostText-foreground, #888)'
385+
span.style.pointerEvents = 'none'
386+
387+
range.insertNode(span)
388+
selection.collapse(range.startContainer, range.startOffset)
389+
}
390+
}
391+
}
392+
}, [ghost_text])
393+
276394
const placeholder = useMemo(() => {
277395
const active_history = props.chat_history
278396

@@ -361,7 +479,7 @@ export const PromptField: React.FC<PromptFieldProps> = (props) => {
361479
onDragOver={handle_drag_over}
362480
onDragEnd={handle_drag_end}
363481
className={cn(styles.input, {
364-
[styles['input-with-tab-hint']]: show_tab_hint,
482+
[styles['input-with-file-match-hint']]: show_file_match_hint,
365483
[styles['input--empty']]: !props.value
366484
})}
367485
data-placeholder={placeholder}

‎packages/ui/src/components/editor/panel/PromptField/hooks/use-handlers.ts‎

Lines changed: 105 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,62 @@ import {
88
map_display_pos_to_raw_pos,
99
map_raw_pos_to_display_pos
1010
} from '../utils/position-mapping'
11+
import { search_paths } from '@shared/utils/search-paths'
1112

1213
type HistoryEntry = {
1314
value: string
1415
raw_caret_pos: number
1516
}
1617

18+
const should_show_file_match_hint = (
19+
value: string,
20+
caret_position: number,
21+
context_file_paths: string[] | undefined
22+
): boolean => {
23+
if (
24+
!value ||
25+
caret_position !== value.length ||
26+
value.endsWith(' ') ||
27+
value.endsWith('\n') ||
28+
!context_file_paths
29+
) {
30+
return false
31+
}
32+
33+
// Check if cursor is at the end of a shortened filename
34+
const text_before_cursor = value.substring(0, caret_position)
35+
const filename_match = text_before_cursor.match(
36+
/([^\s,;:!?`]*\.[^\s,;:!?`]+)$/
37+
)
38+
39+
if (filename_match) {
40+
const filename = filename_match[1]
41+
const is_shortened_filename = context_file_paths.some(
42+
(path) => path.endsWith('/' + filename) || path === filename
43+
)
44+
if (is_shortened_filename) {
45+
return false
46+
}
47+
}
48+
49+
const last_word = value.trim().split(/\s+/).pop()
50+
51+
if (last_word && last_word.length >= 3) {
52+
const matching_paths = search_paths({
53+
paths: context_file_paths,
54+
search_value: last_word
55+
})
56+
return matching_paths.length === 1
57+
}
58+
59+
return false
60+
}
61+
1762
const reconstruct_raw_value_from_node = (node: Node): string => {
18-
if (node.nodeType === Node.TEXT_NODE) {
63+
if (node.nodeType == Node.TEXT_NODE) {
1964
return node.textContent || ''
65+
} else if ((node as HTMLElement).dataset?.type == 'ghost-text') {
66+
return ''
2067
}
2168

2269
if (node.nodeType === Node.ELEMENT_NODE) {
@@ -112,7 +159,9 @@ const set_caret_position_after_change = (
112159

113160
export const use_handlers = (
114161
props: PromptFieldProps,
115-
input_ref: RefObject<HTMLDivElement>
162+
input_ref: RefObject<HTMLDivElement>,
163+
ghost_text: string,
164+
on_accept_ghost_text: () => void
116165
) => {
117166
const [history_index, set_history_index] = useState(-1)
118167
const [is_history_enabled, set_is_history_enabled] = useState(!props.value)
@@ -333,23 +382,65 @@ export const use_handlers = (
333382

334383
const handle_input_change = (e: React.FormEvent<HTMLDivElement>) => {
335384
const currentTarget = e.currentTarget
336-
const new_value = reconstruct_raw_value_from_node(currentTarget)
385+
const new_raw_value = reconstruct_raw_value_from_node(currentTarget)
337386

338-
if (new_value === props.value) {
387+
if (new_raw_value === props.value) {
339388
return
340389
}
341-
update_value(new_value)
342-
set_history_index(-1)
343390

344391
const new_display_value = currentTarget.textContent ?? ''
345392
const caret_position = get_caret_position_from_div(currentTarget)
346393
const char_before_caret = new_display_value.charAt(caret_position - 1)
347394

348-
if (char_before_caret === '@') {
395+
if (char_before_caret == '\\') {
396+
const display_value_before_backslash = new_display_value.substring(
397+
0,
398+
caret_position - 1
399+
)
400+
const show_hint = should_show_file_match_hint(
401+
display_value_before_backslash,
402+
caret_position - 1,
403+
props.context_file_paths
404+
)
405+
406+
if (show_hint) {
407+
const last_word = display_value_before_backslash.trim().split(/\s+/).pop()
408+
if (last_word) {
409+
const matching_paths = search_paths({
410+
paths: props.context_file_paths ?? [],
411+
search_value: last_word
412+
})
413+
if (matching_paths.length === 1) {
414+
const matched_path = matching_paths[0]
415+
const old_raw_value = props.value
416+
417+
const last_word_in_raw_index = old_raw_value.lastIndexOf(last_word)
418+
if (
419+
last_word_in_raw_index !== -1 &&
420+
old_raw_value.endsWith(last_word)
421+
) {
422+
const value_before = old_raw_value.substring(
423+
0,
424+
last_word_in_raw_index
425+
)
426+
const final_new_value = `${value_before}\`${matched_path}\` `
427+
update_value(final_new_value, final_new_value.length)
428+
set_history_index(-1)
429+
return
430+
}
431+
}
432+
}
433+
}
434+
}
435+
436+
update_value(new_raw_value)
437+
set_history_index(-1)
438+
439+
if (char_before_caret == '@') {
349440
setTimeout(() => {
350441
props.on_at_sign_click()
351442
}, 150)
352-
} else if (char_before_caret === '#') {
443+
} else if (char_before_caret == '#') {
353444
setTimeout(() => {
354445
props.on_hash_sign_click()
355446
}, 150)
@@ -519,22 +610,8 @@ export const use_handlers = (
519610

520611
const handle_tab_key = (e: React.KeyboardEvent<HTMLDivElement>) => {
521612
if (!input_ref.current) return
522-
523-
const value = e.currentTarget.textContent ?? ''
524-
const selection_start = get_caret_position_from_div(input_ref.current)
525-
const text_before_cursor = value.substring(0, selection_start)
526-
527-
if (selection_start === 0 || /\s$/.test(text_before_cursor)) {
528-
e.preventDefault()
529-
props.on_at_sign_click()
530-
return
531-
}
532-
533613
e.preventDefault()
534-
const match = text_before_cursor.match(/(\S+)$/)
535-
if (match) {
536-
props.on_at_sign_click(match[1])
537-
}
614+
props.on_at_sign_click()
538615
}
539616

540617
const handle_backspace_key = (e: React.KeyboardEvent<HTMLDivElement>) => {
@@ -684,6 +761,11 @@ export const use_handlers = (
684761
return
685762
}
686763
if (key == 'Tab' && !shiftKey) {
764+
if (ghost_text) {
765+
e.preventDefault()
766+
on_accept_ghost_text()
767+
return
768+
}
687769
handle_tab_key(e)
688770
return
689771
}

0 commit comments

Comments
 (0)