Skip to content

Commit

Permalink
Fix: Add fallback for clipboard.writeText (#7314)
Browse files Browse the repository at this point in the history
  • Loading branch information
sc0ttkclark authored Aug 27, 2024
2 parents fea6f2d + 371a07b commit b4f492c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
24 changes: 22 additions & 2 deletions ui/js/dfv/src/components/copy-button.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,34 @@ import { __ } from '@wordpress/i18n';

import './copy-button.scss';

const copyToClipboard = async ( text ) => {
try {
// @link https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText
// clipboard.writeText only works in secure context (https).
await navigator.clipboard.writeText( text );
} catch {
// Fallback for older browsers, or in unsecure contexts (http).
const input = document.createElement( 'input' );
input.style.position = 'fixed';
input.style.left = '-9999px';
input.style.top = '-9999px';
document.body.appendChild( input );
input.value = text;
input.select();
document.execCommand( 'copy' );
document.body.removeChild( input );
Promise.resolve();
}
};

// https://lucide.dev/icons/copy
const CopyButton = ( { label, textToCopy, onClick } ) => {
const [ copied, setCopied ] = useState( false );
const handleClick = async () => {
if ( onClick ) {
onClick();
} else {
await navigator.clipboard.writeText( textToCopy );
await copyToClipboard( textToCopy );
}
setCopied( true );
const timeout = setTimeout( () => {
Expand All @@ -27,7 +47,7 @@ const CopyButton = ( { label, textToCopy, onClick } ) => {
>
{ copied ? (
<span>
({ __( 'Copied name', 'pods' ) })
({ __( 'Copied', 'pods' ) })
</span>
) : (
<svg
Expand Down
6 changes: 4 additions & 2 deletions ui/js/dfv/src/components/copy-button.scss
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
.pods-field_copy-button {
opacity: 0;
padding: 1px;
display: inline-flex;

svg {
width: 12px;
height: 12px;
width: 12px;
height: 12px;
}

@media screen and (max-width: 850px) {
Expand Down

0 comments on commit b4f492c

Please sign in to comment.