Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | /**
* External dependencies
*/
import './copy-code-row.scss';
import { Button, Popover } from '@wordpress/components';
import { useRef, useCallback } from '@wordpress/element';
import { __, isRTL, sprintf } from '@wordpress/i18n';
import { copySmall, check } from '@wordpress/icons';
import useCopyConfirmation from '../../hooks/use-copy-confirmation';
type CopyCodeRowProps = {
text: string;
label: string;
};
/**
* A row displaying a code snippet with a copy button.
*
* @param {CopyCodeRowProps} props - The component props.
* @return {JSX.Element} The copy code row component.
*/
export const CopyCodeRow = ( { text, label }: CopyCodeRowProps ) => {
const textRef = useRef< HTMLSpanElement >( null );
const { ref, copied: showCopyConfirmation } = useCopyConfirmation( text, 2000 );
const handleTextClick = useCallback( () => {
if ( ! textRef.current ) {
return;
}
const selection = textRef.current.ownerDocument.defaultView?.getSelection();
if ( selection ) {
const range = textRef.current.ownerDocument.createRange();
range.selectNodeContents( textRef.current );
selection.removeAllRanges();
selection.addRange( range );
}
}, [] );
const handleKeyDown = useCallback(
( event: React.KeyboardEvent ) => {
if ( event.key === 'Enter' || event.key === ' ' ) {
event.preventDefault();
event.stopPropagation();
handleTextClick();
}
},
[ handleTextClick ]
);
return (
<div className="jetpack-form-embed-code__row">
<span className="jetpack-form-embed-code__label">{ label }</span>
<div className="jetpack-form-embed-code__container">
<span
ref={ textRef }
className="jetpack-form-embed-code__text"
onClick={ handleTextClick }
role="textbox"
aria-readonly="true"
tabIndex={ 0 }
onKeyDown={ handleKeyDown }
>
{ text }
</span>
{ showCopyConfirmation ? (
<Button
ref={ ref }
icon={ check }
size="compact"
label={ __( 'Copied!', 'jetpack-forms' ) }
>
<Popover
placement={ isRTL() ? 'top-start' : 'top-end' }
noArrow={ false }
focusOnMount={ false }
className="jetpack-form-embed-code__popover"
>
{ __( 'Copied!', 'jetpack-forms' ) }
</Popover>
</Button>
) : (
<Button
ref={ ref }
icon={ copySmall }
size="compact"
label={ sprintf(
/* translators: %s: label for the code row (e.g. "Embed code", "Shortcode") */
__( 'Copy %s', 'jetpack-forms' ),
label.toLowerCase()
) }
/>
) }
</div>
</div>
);
};
|