Skip to content

Commit 1eeb0b8

Browse files
committed
Refactor paste handling for precise text insertion using raw positions
1 parent dad5603 commit 1eeb0b8

3 files changed

Lines changed: 93 additions & 64 deletions

File tree

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

Lines changed: 1 addition & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ export const PromptField: React.FC<PromptFieldProps> = (props) => {
104104
handle_key_down,
105105
is_history_enabled,
106106
handle_copy,
107+
handle_paste,
107108
handle_input_click
108109
} = use_handlers(props, input_ref, ghost_text, handle_accept_ghost_text)
109110
const { handle_drag_start, handle_drag_over, handle_drop, handle_drag_end } =
@@ -144,49 +145,6 @@ export const PromptField: React.FC<PromptFieldProps> = (props) => {
144145
[]
145146
)
146147

147-
// Prevents pasting html or images
148-
const handle_paste = useCallback(
149-
(e: React.ClipboardEvent<HTMLDivElement>) => {
150-
e.preventDefault()
151-
const text = e.clipboardData.getData('text/plain')
152-
const selection = window.getSelection()
153-
if (!selection || !selection.rangeCount) return
154-
const range = selection.getRangeAt(0)
155-
156-
let text_to_insert = text
157-
if (
158-
props.current_selection &&
159-
text === props.current_selection &&
160-
props.currently_open_file_path
161-
) {
162-
text_to_insert = `<fragment path="${props.currently_open_file_path}">\n${text}\n</fragment>`
163-
let has_space_after = false
164-
if (range.endContainer.nodeType === Node.TEXT_NODE) {
165-
const content = range.endContainer.textContent || ''
166-
if (
167-
range.endOffset < content.length &&
168-
/\s/.test(content[range.endOffset])
169-
) {
170-
has_space_after = true
171-
}
172-
}
173-
if (!has_space_after) {
174-
text_to_insert += ' '
175-
}
176-
}
177-
178-
range.deleteContents()
179-
const text_node = document.createTextNode(text_to_insert)
180-
range.insertNode(text_node)
181-
range.setStartAfter(text_node)
182-
range.setEndAfter(text_node)
183-
selection.removeAllRanges()
184-
selection.addRange(range)
185-
input_ref.current?.dispatchEvent(new Event('input', { bubbles: true }))
186-
},
187-
[props.current_selection, props.currently_open_file_path]
188-
)
189-
190148
const is_mac = use_is_mac()
191149

192150
const highlighted_html = useMemo(() => {

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

Lines changed: 86 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ const reconstruct_raw_value_from_node = (node: Node): string => {
5858
if (!path) return ''
5959
const filename = path.split('/').pop() || path
6060
const index = inner_content.indexOf(filename)
61-
if (index !== -1) {
61+
if (index != -1) {
6262
const prefix = inner_content.substring(0, index)
6363
const suffix = inner_content.substring(index + filename.length)
6464
return `${prefix}\`${path}\`${suffix}`
@@ -68,7 +68,7 @@ const reconstruct_raw_value_from_node = (node: Node): string => {
6868
if (!branchName) return ''
6969
const expected_text = `Diff with ${branchName}`
7070
const index = inner_content.indexOf(expected_text)
71-
if (index !== -1) {
71+
if (index != -1) {
7272
const prefix = inner_content.substring(0, index)
7373
const suffix = inner_content.substring(index + expected_text.length)
7474
return `${prefix}#Changes:${branchName}${suffix}`
@@ -79,15 +79,15 @@ const reconstruct_raw_value_from_node = (node: Node): string => {
7979
if (!contextType || !contextName) return ''
8080
const expected_text = `Context "${contextName}"`
8181
const index = inner_content.indexOf(expected_text)
82-
if (index !== -1) {
82+
if (index != -1) {
8383
const prefix = inner_content.substring(0, index)
8484
const suffix = inner_content.substring(index + expected_text.length)
8585
return `${prefix}#SavedContext:${contextType} "${contextName}"${suffix}`
8686
}
8787
} else if (el.dataset.type == 'selection-keyword') {
8888
const expected_text = 'Selection'
8989
const index = inner_content.indexOf(expected_text)
90-
if (index !== -1) {
90+
if (index != -1) {
9191
const prefix = inner_content.substring(0, index)
9292
const suffix = inner_content.substring(index + expected_text.length)
9393
return `${prefix}#Selection${suffix}`
@@ -101,7 +101,7 @@ const reconstruct_raw_value_from_node = (node: Node): string => {
101101
}
102102
const short_hash = commit_hash.substring(0, 7)
103103
const index = inner_content.indexOf(short_hash)
104-
if (index !== -1) {
104+
if (index != -1) {
105105
const prefix = inner_content.substring(0, index)
106106
const suffix = inner_content.substring(index + short_hash.length)
107107
return `${prefix}#Commit:${repo_name}:${commit_hash} "${commit_message.replace(
@@ -357,6 +357,71 @@ export const use_handlers = (
357357
e.clipboardData.setData('text/plain', raw_text_slice)
358358
}
359359

360+
const handle_paste = (e: React.ClipboardEvent<HTMLDivElement>) => {
361+
e.preventDefault()
362+
const text = e.clipboardData.getData('text/plain')
363+
const selection = window.getSelection()
364+
if (!selection || !selection.rangeCount || !input_ref.current) return
365+
const range = selection.getRangeAt(0)
366+
const input_element = input_ref.current
367+
368+
if (!input_element.contains(range.startContainer)) return
369+
370+
const pre_selection_range = document.createRange()
371+
pre_selection_range.selectNodeContents(input_element)
372+
pre_selection_range.setEnd(range.startContainer, range.startOffset)
373+
const display_start = pre_selection_range.toString().length
374+
375+
pre_selection_range.setEnd(range.endContainer, range.endOffset)
376+
const display_end = pre_selection_range.toString().length
377+
378+
const raw_start = map_display_pos_to_raw_pos(
379+
display_start,
380+
props.value,
381+
props.context_file_paths ?? []
382+
)
383+
const raw_end = map_display_pos_to_raw_pos(
384+
display_end,
385+
props.value,
386+
props.context_file_paths ?? []
387+
)
388+
389+
let text_to_insert = text
390+
let caret_offset_adjustment = 0
391+
392+
if (
393+
props.current_selection &&
394+
text === props.current_selection &&
395+
props.currently_open_file_path
396+
) {
397+
text_to_insert = `<fragment path="${props.currently_open_file_path}">\n${text}\n</fragment>`
398+
399+
let has_space_after = false
400+
if (raw_end < props.value.length) {
401+
const char_after = props.value[raw_end]
402+
if (/\s/.test(char_after)) {
403+
has_space_after = true
404+
}
405+
}
406+
407+
if (!has_space_after) {
408+
text_to_insert += ' '
409+
} else {
410+
caret_offset_adjustment = 1
411+
}
412+
}
413+
414+
const new_value =
415+
props.value.substring(0, raw_start) +
416+
text_to_insert +
417+
props.value.substring(raw_end)
418+
const new_caret_pos =
419+
raw_start + text_to_insert.length + caret_offset_adjustment
420+
421+
has_modified_current_entry_ref.current = true
422+
update_value(new_value, new_caret_pos)
423+
}
424+
360425
const handle_input_click = (e: React.MouseEvent<HTMLDivElement>) => {
361426
const target = e.target as HTMLElement
362427
const icon_element = target.closest('[data-role="keyword-icon"]')
@@ -567,17 +632,22 @@ export const use_handlers = (
567632
return false
568633
}
569634

570-
const handle_pasted_lines_keyword_deletion = (
571-
raw_pos: number,
572-
context_file_paths: string[]
573-
): boolean => {
635+
const handle_pasted_lines_keyword_deletion = (raw_pos: number): boolean => {
574636
const text_before_cursor = props.value.substring(0, raw_pos)
575-
const match = text_before_cursor.match(
576-
/<fragment path="[^"]+">\n[\s\S]*?\n<\/fragment>$/
577-
)
578637

579-
if (match) {
580-
const start_of_match = raw_pos - match[0].length
638+
const regex = /<fragment path="[^"]+">\n[\s\S]*?\n<\/fragment>/g
639+
let match
640+
let last_match: RegExpExecArray | null = null
641+
642+
while ((match = regex.exec(text_before_cursor)) !== null) {
643+
last_match = match
644+
}
645+
646+
if (
647+
last_match &&
648+
last_match.index + last_match[0].length === text_before_cursor.length
649+
) {
650+
const start_of_match = last_match.index
581651
const new_value =
582652
props.value.substring(0, start_of_match) +
583653
props.value.substring(raw_pos)
@@ -623,7 +693,7 @@ export const use_handlers = (
623693
}
624694

625695
if (el.dataset.type == 'pasted-lines-keyword') {
626-
return handle_pasted_lines_keyword_deletion(raw_pos, context_file_paths)
696+
return handle_pasted_lines_keyword_deletion(raw_pos)
627697
}
628698

629699
return false
@@ -982,6 +1052,7 @@ export const use_handlers = (
9821052
is_history_enabled,
9831053
handle_clear,
9841054
handle_copy,
1055+
handle_paste,
9851056
handle_input_click
9861057
}
9871058
}

‎packages/ui/src/components/editor/panel/PromptField/utils/get-highlighted-text.tsx‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const process_text_part_for_files = (
2828
return `<span class="${cn(
2929
styles['keyword'],
3030
styles['keyword--file']
31-
)}" contentEditable="false" data-type="file-keyword" data-path="${escape_html(
31+
)}" data-type="file-keyword" data-path="${escape_html(
3232
file_path
3333
)}" title="${escape_html(file_path)}"><span class="${
3434
styles['keyword__icon']
@@ -78,7 +78,7 @@ export const get_highlighted_text = (params: {
7878
return `<span class="${cn(
7979
styles['keyword'],
8080
styles['keyword--pasted-lines']
81-
)}" contentEditable="false" data-type="pasted-lines-keyword" data-path="${escape_html(
81+
)}" data-type="pasted-lines-keyword" data-path="${escape_html(
8282
path
8383
)}" data-content="${escape_html(content)}"><span class="${
8484
styles['keyword__icon']
@@ -96,14 +96,14 @@ export const get_highlighted_text = (params: {
9696
: `Selection: ${params.current_selection
9797
.substring(0, 100)
9898
.replace(/\n/g, ' ')}...`
99-
return `<span class="${className}" contentEditable="false" data-type="selection-keyword" title="${escape_html(title)}"><span class="${styles['keyword__icon']}" data-role="keyword-icon"></span><span class="${styles['keyword__text']}" data-role="keyword-text">Selection</span></span>`
99+
return `<span class="${className}" data-type="selection-keyword" title="${escape_html(title)}"><span class="${styles['keyword__icon']}" data-role="keyword-icon"></span><span class="${styles['keyword__text']}" data-role="keyword-text">Selection</span></span>`
100100
}
101101
if (part && /^#Changes:[^\s,;:!?]+$/.test(part)) {
102102
const branch_name = part.substring('#Changes:'.length)
103103
return `<span class="${cn(
104104
styles['keyword'],
105105
styles['keyword--changes']
106-
)}" contentEditable="false" data-type="changes-keyword" data-branch-name="${escape_html(
106+
)}" data-type="changes-keyword" data-branch-name="${escape_html(
107107
branch_name
108108
)}"><span class="${
109109
styles['keyword__icon']
@@ -122,7 +122,7 @@ export const get_highlighted_text = (params: {
122122
return `<span class="${cn(
123123
styles['keyword'],
124124
styles['keyword--saved-context']
125-
)}" contentEditable="false" data-type="saved-context-keyword" data-context-type="${context_type}" data-context-name="${escape_html(
125+
)}" data-type="saved-context-keyword" data-context-type="${context_type}" data-context-name="${escape_html(
126126
context_name
127127
)}"><span class="${
128128
styles['keyword__icon']
@@ -144,7 +144,7 @@ export const get_highlighted_text = (params: {
144144
return `<span class="${cn(
145145
styles['keyword'],
146146
styles[`keyword--${symbol.toLowerCase()}`]
147-
)}" contentEditable="false" data-type="${symbol.toLowerCase()}-keyword" data-repo-name="${escape_html(
147+
)}" data-type="${symbol.toLowerCase()}-keyword" data-repo-name="${escape_html(
148148
repo_name
149149
)}" data-commit-hash="${escape_html(
150150
commit_hash

0 commit comments

Comments
 (0)