Skip to content

Commit 44009f6

Browse files
committed
Refactor ghost text logic to correctly check for whitespace or end-of-input after the caret before suggesting completions
1 parent f02a3ae commit 44009f6

1 file changed

Lines changed: 26 additions & 19 deletions

File tree

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

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -65,25 +65,32 @@ export const use_ghost_text = ({
6565
if (selection && selection.rangeCount > 0) {
6666
const range = selection.getRangeAt(0)
6767
if (range.collapsed) {
68-
const pre_caret_range = range.cloneRange()
69-
pre_caret_range.selectNodeContents(input_ref.current)
70-
pre_caret_range.setEnd(range.startContainer, range.startOffset)
71-
const text_before_cursor = pre_caret_range.toString()
72-
const last_word_match = text_before_cursor.match(/[\S]+$/)
73-
74-
if (last_word_match) {
75-
const last_word_with_prefix = last_word_match[0]
76-
const word_start_match =
77-
last_word_with_prefix.match(/[a-zA-Z_]/)
78-
if (word_start_match) {
79-
const last_word = last_word_with_prefix.substring(
80-
word_start_match.index ?? 0
81-
)
82-
if (last_word.length >= 2) {
83-
for (const id of identifiers) {
84-
if (id.startsWith(last_word) && id !== last_word) {
85-
potential_ghost_text = id.substring(last_word.length)
86-
break
68+
const post_caret_range = range.cloneRange()
69+
post_caret_range.selectNodeContents(input_ref.current)
70+
post_caret_range.setStart(range.endContainer, range.endOffset)
71+
const text_after_cursor = post_caret_range.toString()
72+
73+
if (text_after_cursor === '' || /^\s/.test(text_after_cursor)) {
74+
const pre_caret_range = range.cloneRange()
75+
pre_caret_range.selectNodeContents(input_ref.current)
76+
pre_caret_range.setEnd(range.startContainer, range.startOffset)
77+
const text_before_cursor = pre_caret_range.toString()
78+
const last_word_match = text_before_cursor.match(/[\S]+$/)
79+
80+
if (last_word_match) {
81+
const last_word_with_prefix = last_word_match[0]
82+
const word_start_match =
83+
last_word_with_prefix.match(/[a-zA-Z_]/)
84+
if (word_start_match) {
85+
const last_word = last_word_with_prefix.substring(
86+
word_start_match.index ?? 0
87+
)
88+
if (last_word.length >= 2) {
89+
for (const id of identifiers) {
90+
if (id.startsWith(last_word) && id !== last_word) {
91+
potential_ghost_text = id.substring(last_word.length)
92+
break
93+
}
8794
}
8895
}
8996
}

0 commit comments

Comments
 (0)