Skip to content

Commit 105d478

Browse files
committed
Refactor Enter key handling to properly insert newlines in rich text input while preserving raw text positions
1 parent 55fd339 commit 105d478

1 file changed

Lines changed: 41 additions & 23 deletions

File tree

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

Lines changed: 41 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1350,31 +1350,49 @@ export const use_handlers = (
13501350
}
13511351

13521352
if (key == 'Enter') {
1353-
if (props.send_with_shift_enter) {
1354-
if (shiftKey) {
1355-
e.preventDefault()
1356-
handle_submit(e)
1357-
} else {
1358-
e.preventDefault()
1359-
const selection = window.getSelection()
1360-
if (!selection || !selection.rangeCount || !params.input_ref.current)
1361-
return
1362-
1363-
const range = selection.getRangeAt(0)
1364-
range.deleteContents()
1365-
const text_node = document.createTextNode('\n')
1366-
range.insertNode(text_node)
1367-
range.setStartAfter(text_node)
1368-
range.setEndAfter(text_node)
1369-
selection.removeAllRanges()
1370-
selection.addRange(range)
1371-
params.input_ref.current.dispatchEvent(
1372-
new Event('input', { bubbles: true })
1373-
)
1374-
}
1375-
} else if (!shiftKey) {
1353+
if (props.send_with_shift_enter && shiftKey) {
13761354
e.preventDefault()
13771355
handle_submit(e)
1356+
} else if (!props.send_with_shift_enter && !shiftKey) {
1357+
e.preventDefault()
1358+
handle_submit(e)
1359+
} else {
1360+
e.preventDefault()
1361+
const selection = window.getSelection()
1362+
if (!selection || !selection.rangeCount || !params.input_ref.current)
1363+
return
1364+
1365+
const range = selection.getRangeAt(0)
1366+
const input_element = params.input_ref.current
1367+
1368+
if (!input_element.contains(range.startContainer)) return
1369+
1370+
const pre_selection_range = document.createRange()
1371+
pre_selection_range.selectNodeContents(input_element)
1372+
pre_selection_range.setEnd(range.startContainer, range.startOffset)
1373+
const display_start = pre_selection_range.toString().length
1374+
1375+
pre_selection_range.setEnd(range.endContainer, range.endOffset)
1376+
const display_end = pre_selection_range.toString().length
1377+
1378+
const raw_start = map_display_pos_to_raw_pos({
1379+
display_pos: display_start,
1380+
raw_text: props.value,
1381+
context_file_paths: props.context_file_paths ?? []
1382+
})
1383+
const raw_end = map_display_pos_to_raw_pos({
1384+
display_pos: display_end,
1385+
raw_text: props.value,
1386+
context_file_paths: props.context_file_paths ?? []
1387+
})
1388+
1389+
const new_value =
1390+
props.value.substring(0, raw_start) +
1391+
'\n' +
1392+
props.value.substring(raw_end)
1393+
1394+
has_modified_current_entry_ref.current = true
1395+
update_value(new_value, raw_start + 1)
13781396
}
13791397
return
13801398
}

0 commit comments

Comments
 (0)