Skip to content

Commit 5379184

Browse files
authored
Update useSyntheticChange to only call execCommand if input is focused (#3562)
* Update `useSyntheticChange` to only call `execCommand` if input is focused * Create tame-foxes-tan.md
1 parent 7ef802e commit 5379184

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

.changeset/tame-foxes-tan.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@primer/react": patch
3+
---
4+
5+
Fix `MarkdownEditor` file uploads inserting the URL into the wrong input when an overlay is open

src/drafts/hooks/useSyntheticChange.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ export const useSyntheticChange = ({inputRef, fallbackEventHandler}: UseSyntheti
9494
const input = inputRef.current
9595
if (!input) return
9696

97-
input.focus() // the input must be focused to execute execCommand
97+
input.focus()
9898

9999
const replaceRange = replaceRange_ ?? [
100100
input.selectionStart ?? input.value.length,
@@ -113,6 +113,10 @@ export const useSyntheticChange = ({inputRef, fallbackEventHandler}: UseSyntheti
113113
// but it's a deprecated API and there's no alternative. It also doesn't work in test environments
114114
let execCommandResult = false
115115
try {
116+
// There is no guarantee the input is focused even after calling `focus()` on it. For example, the focus could
117+
// be trapped by an overlay. In that case we must prevent the change from happening in some unexpected target.
118+
if (document.activeElement !== input) throw new Error('Input must be focused to use execCommand')
119+
116120
// expand selection to the whole range and replace it with the new value
117121
input.setSelectionRange(replaceRange[0], replaceRange[1])
118122
execCommandResult =

0 commit comments

Comments
 (0)