Skip to content

Commit

Permalink
Update useSyntheticChange to only call execCommand if input is fo…
Browse files Browse the repository at this point in the history
…cused (#3562)

* Update `useSyntheticChange` to only call `execCommand` if input is focused

* Create tame-foxes-tan.md
  • Loading branch information
iansan5653 authored Jul 26, 2023
1 parent 7ef802e commit 5379184
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/tame-foxes-tan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@primer/react": patch
---

Fix `MarkdownEditor` file uploads inserting the URL into the wrong input when an overlay is open
6 changes: 5 additions & 1 deletion src/drafts/hooks/useSyntheticChange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export const useSyntheticChange = ({inputRef, fallbackEventHandler}: UseSyntheti
const input = inputRef.current
if (!input) return

input.focus() // the input must be focused to execute execCommand
input.focus()

const replaceRange = replaceRange_ ?? [
input.selectionStart ?? input.value.length,
Expand All @@ -113,6 +113,10 @@ export const useSyntheticChange = ({inputRef, fallbackEventHandler}: UseSyntheti
// but it's a deprecated API and there's no alternative. It also doesn't work in test environments
let execCommandResult = false
try {
// There is no guarantee the input is focused even after calling `focus()` on it. For example, the focus could
// be trapped by an overlay. In that case we must prevent the change from happening in some unexpected target.
if (document.activeElement !== input) throw new Error('Input must be focused to use execCommand')

// expand selection to the whole range and replace it with the new value
input.setSelectionRange(replaceRange[0], replaceRange[1])
execCommandResult =
Expand Down

0 comments on commit 5379184

Please sign in to comment.