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 | 1x 1x 1x 1x 1x 1x 1x 1x | /**
* External dependencies
*/
import './copy-code-row.scss';
import { ClipboardIconButton } from '@automattic/jetpack-components';
import { useInstanceId } from '@wordpress/compose';
import { useRef, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import type { JSX } from 'react';
type CopyCodeRowProps = {
text: string;
label: string;
help?: 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, help }: CopyCodeRowProps ) => {
const textRef = useRef< HTMLSpanElement >( null );
const instanceId = useInstanceId( CopyCodeRow );
const labelId = `jetpack-form-embed-code__label-${ instanceId }`;
const helpId = `jetpack-form-embed-code__help-${ instanceId }`;
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 id={ labelId } 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"
aria-labelledby={ labelId }
aria-describedby={ help ? helpId : undefined }
tabIndex={ 0 }
onKeyDown={ handleKeyDown }
>
{ text }
</span>
<ClipboardIconButton
text={ text }
label={ sprintf(
/* translators: %s: label for the code row (e.g. "Embed code", "Shortcode") */
__( 'Copy %s', 'jetpack-forms' ),
label.toLowerCase()
) }
/>
</div>
{ help && (
<p id={ helpId } className="jetpack-form-embed-code__help">
{ help }
</p>
) }
</div>
);
};
|