Skip to content
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
4 changes: 4 additions & 0 deletions packages/compose/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Bug Fixes

- `useCopyToClipboard`: Call the `onSuccess` callback even when the trigger node unmounts before the copy resolves ([#78387](https://github.com/WordPress/gutenberg/pull/78387)).

## 7.46.0 (2026-05-14)

## 7.45.0 (2026-04-29)
Expand Down
4 changes: 2 additions & 2 deletions packages/compose/src/hooks/use-copy-on-click/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { RefObject } from 'react';
/**
* Internal dependencies
*/
import { clearSelection, copyToClipboard } from '../use-copy-to-clipboard';
import { restoreFocus, copyToClipboard } from '../use-copy-to-clipboard';

/**
* Copies the text to the clipboard when the element is clicked.
Expand Down Expand Up @@ -73,7 +73,7 @@ export default function useCopyOnClick(
return;
}
if ( success ) {
clearSelection( trigger );
restoreFocus( trigger );
if ( timeout ) {
setHasCopied( true );
clearTimeout( timeoutId );
Expand Down
16 changes: 8 additions & 8 deletions packages/compose/src/hooks/use-copy-to-clipboard/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,14 @@ export async function copyToClipboard(
}

/**
* Clears the current selection and restores focus to the trigger element.
* Restores focus to the trigger element.
*
* @param trigger The element that triggered the copy.
*/
export function clearSelection( trigger: Element ): void {
export function restoreFocus( trigger: Element ): void {
if ( 'focus' in trigger && typeof trigger.focus === 'function' ) {
trigger.focus();
}
trigger.ownerDocument?.defaultView?.getSelection()?.removeAllRanges();
}

/**
Expand Down Expand Up @@ -93,19 +92,20 @@ export default function useCopyToClipboard< T extends HTMLElement >(
const textRef = useUpdatedRef( text );
const onSuccessRef = useUpdatedRef( onSuccess );
return useRefEffect( ( node ) => {
// Flag to prevent callbacks after unmount when the Promise resolves.
// Tracks whether the node is still mounted when the Promise resolves.
let isActive = true;
const handleClick = async () => {
const textToCopy =
typeof textRef.current === 'function'
? textRef.current()
: textRef.current || '';
const success = await copyToClipboard( textToCopy, node );
if ( ! isActive ) {
return;
}
if ( success ) {
clearSelection( node );
// Restoring focus only matters while the node is mounted.
if ( isActive ) {
restoreFocus( node );
}
// Always run, even after unmount, to allow updating other UI.
if ( onSuccessRef.current ) {
onSuccessRef.current();
}
Expand Down
38 changes: 33 additions & 5 deletions packages/compose/src/hooks/use-copy-to-clipboard/test/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import userEvent from '@testing-library/user-event';
/**
* Internal dependencies
*/
import useCopyToClipboard, { copyToClipboard, clearSelection } from '../';
import useCopyToClipboard, { copyToClipboard, restoreFocus } from '../';

interface TestComponentProps {
text: string | ( () => string );
Expand Down Expand Up @@ -68,7 +68,7 @@ describe( 'useCopyToClipboard', () => {
expect( onSuccess ).not.toHaveBeenCalled();
} );

it( 'should not call onSuccess after unmount', async () => {
it( 'should call onSuccess after the node unmounts', async () => {
let resolvePromise: () => void;
const delayedPromise = new Promise< void >( ( resolve ) => {
resolvePromise = resolve;
Expand All @@ -91,7 +91,35 @@ describe( 'useCopyToClipboard', () => {
await new Promise( ( resolve ) => setTimeout( resolve, 0 ) );
} );

expect( onSuccess ).not.toHaveBeenCalled();
expect( onSuccess ).toHaveBeenCalledTimes( 1 );
} );

it( 'should not restore focus after the node unmounts', async () => {
let resolvePromise: () => void;
const delayedPromise = new Promise< void >( ( resolve ) => {
resolvePromise = resolve;
} );
jest.spyOn( navigator.clipboard, 'writeText' ).mockReturnValue(
delayedPromise
);

const user = userEvent.setup();
const { unmount } = render( <TestComponent text="test" /> );

const button = screen.getByRole( 'button' );
const focusSpy = jest.spyOn( button, 'focus' );

await user.click( button );
unmount();
// Discard focus calls from the initial click; we only care about post-unmount calls.
focusSpy.mockClear();
Comment thread
t-hamano marked this conversation as resolved.
Resolved

await act( async () => {
resolvePromise();
await new Promise( ( resolve ) => setTimeout( resolve, 0 ) );
} );

expect( focusSpy ).not.toHaveBeenCalled();
} );
} );

Expand Down Expand Up @@ -129,13 +157,13 @@ describe( 'copyToClipboard', () => {
} );
} );

describe( 'clearSelection', () => {
describe( 'restoreFocus', () => {
it( 'should focus the trigger element', () => {
const trigger = document.createElement( 'button' );
document.body.appendChild( trigger );
const focusMock = jest.spyOn( trigger, 'focus' );

clearSelection( trigger );
restoreFocus( trigger );

expect( focusMock ).toHaveBeenCalledTimes( 1 );

Expand Down
Loading