@@ -170,22 +170,23 @@ export const PromptField: React.FC<PromptFieldProps> = (props) => {
170170
171171 useEffect ( ( ) => {
172172 if ( input_ref . current && input_ref . current . innerHTML !== highlighted_html ) {
173- let selection_start = 0
174-
175- if ( is_focused ) {
176- selection_start = get_caret_position_from_div ( input_ref . current )
177- } else {
178- selection_start = map_raw_pos_to_display_pos (
179- props . value . length ,
180- props . value ,
181- props . context_file_paths ?? [ ]
182- )
183- }
184-
173+ const selection = window . getSelection ( )
174+ const should_restore_caret =
175+ document . activeElement === input_ref . current &&
176+ selection &&
177+ selection . rangeCount > 0 &&
178+ selection . anchorNode &&
179+ input_ref . current . contains ( selection . anchorNode )
180+
181+ const selection_start = should_restore_caret
182+ ? get_caret_position_from_div ( input_ref . current )
183+ : 0
185184 input_ref . current . innerHTML = highlighted_html
186- set_caret_position_for_div ( input_ref . current , selection_start )
185+ if ( should_restore_caret ) {
186+ set_caret_position_for_div ( input_ref . current , selection_start )
187+ }
187188 }
188- } , [ highlighted_html , is_focused , props . value , props . context_file_paths ] )
189+ } , [ highlighted_html ] )
189190
190191 useEffect ( ( ) => {
191192 if ( input_ref . current ) {
@@ -228,14 +229,6 @@ export const PromptField: React.FC<PromptFieldProps> = (props) => {
228229 }
229230 } , [ props . focus_and_select_key ] )
230231
231- useEffect ( ( ) => {
232- const input_element = input_ref . current
233- if ( input_element ) {
234- const is_focused = document . activeElement === input_element
235- if ( ! is_focused ) input_element . focus ( )
236- }
237- } , [ props . value ] )
238-
239232 useEffect ( ( ) => {
240233 const on_selection_change = ( ) => {
241234 if ( document . activeElement === input_ref . current && input_ref . current ) {
0 commit comments