Skip to content

Update useSyntheticChange to only call execCommand if input is focused #3562

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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