Skip to content
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

Fix: Add fallback for clipboard.writeText #7314

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
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
Loading