-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Replace clipboard.js with native Clipboard API
#37713
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
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
3de064c
Refactor `useCopyToClipboard` hook to use the native `clipboard` APIs
ciampo fceccef
Refactor `useCopyOnClick` hook to use the native `clipboard` APIs
ciampo 2d05d94
Remove unused `clipboard` dependency
ciampo 139a8d6
Add `useCopyToClipboard` unit tests
ciampo 6ab8d53
Add `useCopyOnClick` tests
ciampo eba4157
Remove selection clearance and focus management
ciampo 875e8c8
CHANGELOG
ciampo cfcbec2
Update package-loc.json
ciampo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Original file line | Diff line number | Diff line change |
|---|---|---|---|
| @@ -1,12 +1,7 @@ | |||
| /** | |||
| * External dependencies | |||
| */ | |||
| import Clipboard from 'clipboard'; | |||
|
|
|||
| /** | /** | ||
| * WordPress dependencies | * WordPress dependencies | ||
| */ | */ | ||
| import { useRef, useEffect, useState } from '@wordpress/element'; | import { useEffect, useState } from '@wordpress/element'; | ||
| import deprecated from '@wordpress/deprecated'; | import deprecated from '@wordpress/deprecated'; | ||
|
|
|
||
| /* eslint-disable jsdoc/no-undefined-types */ | /* eslint-disable jsdoc/no-undefined-types */ | ||
|
|
@@ -30,45 +25,60 @@ export default function useCopyOnClick( ref, text, timeout = 4000 ) { | ||
| alternative: 'wp.compose.useCopyToClipboard', | alternative: 'wp.compose.useCopyToClipboard', | ||
| } ); | } ); | ||
|
|
|
||
| /** @type {import('react').MutableRefObject<Clipboard | undefined>} */ | |||
| const clipboard = useRef(); | |||
| const [ hasCopied, setHasCopied ] = useState( false ); | const [ hasCopied, setHasCopied ] = useState( false ); | ||
|
|
|
||
| useEffect( () => { | useEffect( () => { | ||
| /** @type {number | undefined} */ | /** @type {number | undefined} */ | ||
| let timeoutId; | let timeoutId; | ||
| /** @type Array<Element>) */ | |||
noahtallen marked this conversation as resolved.
Show resolved
Hide resolved
|
|||
| let triggers = []; | |||
|
|
|
||
| if ( ! ref.current ) { | if ( ! ref.current ) { | ||
| return; | return; | ||
| } | } | ||
|
|
|
||
| // Clipboard listens to click events. | // `triggers` is always an array, regardless of the value of the `ref` param. | ||
| clipboard.current = new Clipboard( ref.current, { | if ( typeof ref.current === 'string' ) { | ||
| text: () => ( typeof text === 'function' ? text() : text ), | // expect `ref` to be a DOM selector | ||
| } ); | triggers = Array.from( document.querySelectorAll( ref.current ) ); | ||
| } else if ( 'length' in ref.current ) { | |||
| // Expect `ref` to be a `NodeList` | |||
| triggers = Array.from( ref.current ); | |||
| } else { | |||
| // Expect `ref` to be a single `Element` | |||
| triggers = [ ref.current ]; | |||
| } | |||
|
Comment on lines
+40
to
+50
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Previously, the different values for |
|||
|
|
|
||
| clipboard.current.on( 'success', ( { clearSelection, trigger } ) => { | /** | ||
| // Clearing selection will move focus back to the triggering button, | * @param {Event} e | ||
| // ensuring that it is not reset to the body, and further that it is | */ | ||
| // kept within the rendered node. | const copyTextToClipboard = ( e ) => { | ||
| clearSelection(); | const trigger = /** @type {HTMLElement | null} */ ( e.target ); | ||
| const currentWindow = trigger?.ownerDocument.defaultView || window; | |||
| const textToCopy = typeof text === 'function' ? text() : text || ''; | |||
|
|
|
||
| // Handle ClipboardJS focus bug, see https://github.com/zenorocha/clipboard.js/issues/680 | currentWindow?.navigator?.clipboard | ||
| if ( trigger ) { | ?.writeText( textToCopy ) | ||
| /** @type {HTMLElement} */ ( trigger ).focus(); | .then( () => { | ||
| } | if ( timeout ) { | ||
| setHasCopied( true ); | |||
| clearTimeout( timeoutId ); | |||
| timeoutId = setTimeout( | |||
| () => setHasCopied( false ), | |||
| timeout | |||
| ); | |||
| } | |||
| } ); | |||
| }; | |||
|
|
|
||
| if ( timeout ) { | triggers.forEach( ( t ) => | ||
| setHasCopied( true ); | t.addEventListener( 'click', copyTextToClipboard ) | ||
| clearTimeout( timeoutId ); | ); | ||
| timeoutId = setTimeout( () => setHasCopied( false ), timeout ); | |||
| } | |||
| } ); | |||
|
|
|
||
| return () => { | return () => { | ||
| if ( clipboard.current ) { | triggers.forEach( ( t ) => | ||
| clipboard.current.destroy(); | t.removeEventListener( 'click', copyTextToClipboard ) | ||
| } | ); | ||
| clearTimeout( timeoutId ); | clearTimeout( timeoutId ); | ||
| }; | }; | ||
| }, [ text, timeout, setHasCopied ] ); | }, [ text, timeout, setHasCopied ] ); | ||
|
|
|||
71 changes: 71 additions & 0 deletions
71
packages/compose/src/hooks/use-copy-on-click/test/index.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Original file line | Diff line number | Diff line change |
|---|---|---|---|
| @@ -0,0 +1,71 @@ | |||
| /** | |||
| * External dependencies | |||
| */ | |||
| import { render, screen, fireEvent, waitFor } from '@testing-library/react'; | |||
|
|
|||
| /** | |||
| * WordPress dependencies | |||
| */ | |||
| import { useRef } from '@wordpress/element'; | |||
|
|
|||
| /** | |||
| * Internal dependencies | |||
| */ | |||
| import useCopyOnClick from '../'; | |||
|
|
|||
| const ExampleComponent = ( { text, ...props } ) => { | |||
| const ref = useRef(); | |||
|
|
|||
| const hasCopied = useCopyOnClick( ref, text, 1000 ); | |||
|
|
|||
| return ( | |||
| <button ref={ ref } { ...props }> | |||
| { hasCopied ? 'Copied' : 'Click to copy' } | |||
| </button> | |||
| ); | |||
| }; | |||
|
|
|||
| let clipboardValue; | |||
|
|
|||
| const originalClipboard = global.navigator.clipboard; | |||
| const mockClipboard = { | |||
| writeText: jest.fn().mockImplementation( ( text ) => { | |||
| return new Promise( ( resolve ) => { | |||
| clipboardValue = text; | |||
| resolve(); | |||
| } ); | |||
| } ), | |||
| }; | |||
|
|
|||
| global.navigator.clipboard = mockClipboard; | |||
|
|
|||
| describe( 'useCopyOnClick', () => { | |||
| beforeEach( () => { | |||
| clipboardValue = undefined; | |||
| } ); | |||
|
|
|||
| afterAll( () => { | |||
| global.navigator.clipboard = originalClipboard; | |||
| } ); | |||
|
|
|||
| it( 'should copy the text to the clipboard and display a warning notice', async () => { | |||
| const textToBeCopied = 'mango'; | |||
| render( <ExampleComponent text={ textToBeCopied } /> ); | |||
|
|
|||
| expect( console ).toHaveWarned(); | |||
|
|
|||
| const triggerButton = screen.getByText( 'Click to copy' ); | |||
| fireEvent.click( triggerButton ); | |||
|
|
|||
| await waitFor( () => | |||
| expect( clipboardValue ).toEqual( textToBeCopied ) | |||
| ); | |||
|
|
|||
| // Check that the displayed text changes as a way of testing | |||
| // the `hasCopied` logic | |||
| expect( screen.getByText( 'Copied' ) ).toBeInTheDocument(); | |||
| await waitFor( () => | |||
| expect( screen.getByText( 'Click to copy' ) ).toBeInTheDocument() | |||
| ); | |||
| } ); | |||
| } ); | |||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
60 changes: 60 additions & 0 deletions
60
packages/compose/src/hooks/use-copy-to-clipboard/test/index.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Original file line | Diff line number | Diff line change |
|---|---|---|---|
| @@ -0,0 +1,60 @@ | |||
| /** | |||
| * External dependencies | |||
| */ | |||
| import { render, screen, fireEvent, waitFor } from '@testing-library/react'; | |||
|
|
|||
| /** | |||
| * Internal dependencies | |||
| */ | |||
| import useCopyToClipboard from '../'; | |||
|
|
|||
| const ExampleComponent = ( { onSuccess, text, ...props } ) => { | |||
| const ref = useCopyToClipboard( text, onSuccess ); | |||
|
|
|||
| return ( | |||
| <button ref={ ref } { ...props }> | |||
| Click to copy | |||
| </button> | |||
| ); | |||
| }; | |||
|
|
|||
| let clipboardValue; | |||
|
|
|||
| const originalClipboard = global.navigator.clipboard; | |||
| const mockClipboard = { | |||
| writeText: jest.fn().mockImplementation( ( text ) => { | |||
| return new Promise( ( resolve ) => { | |||
| clipboardValue = text; | |||
| resolve(); | |||
| } ); | |||
| } ), | |||
| }; | |||
|
|
|||
| global.navigator.clipboard = mockClipboard; | |||
|
|
|||
| describe( 'useCopyToClipboard', () => { | |||
| beforeEach( () => { | |||
| clipboardValue = undefined; | |||
| } ); | |||
|
|
|||
| afterAll( () => { | |||
| global.navigator.clipboard = originalClipboard; | |||
| } ); | |||
|
|
|||
| it( 'should copy the text to the clipboard', async () => { | |||
| const successCallback = jest.fn(); | |||
| const textToBeCopied = 'mango'; | |||
| render( | |||
| <ExampleComponent | |||
| onSuccess={ successCallback } | |||
| text={ textToBeCopied } | |||
| /> | |||
| ); | |||
|
|
|||
| const triggerButton = screen.getByText( 'Click to copy' ); | |||
| fireEvent.click( triggerButton ); | |||
|
|
|||
| await waitFor( () => expect( successCallback ).toHaveBeenCalled() ); | |||
| expect( clipboardValue ).toEqual( textToBeCopied ); | |||
| } ); | |||
| } ); | |||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
While the changes in this file are pretty convoluted, it is a deprecated hook after all. The changes in the other hook are a lot more palatable. :P I still think it's worth it to remove the dependency.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I had the same train of thoughts, and came to the same conclusion — refactoring this deprecated hook allows us to remove the dependency from the repo :)