Back

93.33% Statements 14/15
100% Branches 4/4
75% Functions 6/8
100% Lines 12/12

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                  1x                   1x 1x                       2x 2x   2x   2x 1x     1x 1x 1x         2x                    
/**
 * Button that copies a link to one tool on an MCP view.
 */
 
import { Button } from '@wordpress/components';
import { useCallback, useEffect, useRef, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { check, link } from '@wordpress/icons';
 
const COPIED_RESET_MS = 2000;
 
/**
 * Build the shareable URL. The hash is the router, so the anchor goes in the path.
 *
 * @param {string} view   - View path, e.g. `mcp/read`.
 * @param {string} anchor - Tool anchor.
 * @return {string} Absolute URL.
 */
function buildAnchorUrl( view, anchor ) {
	const { origin, pathname, search } = window.location;
	return `${ origin }${ pathname }${ search }#/${ view }/${ anchor }`;
}
 
/**
 * Copy-link button with a transient "Copied" state.
 *
 * @param {object} props        - Component props.
 * @param {string} props.view   - View path, e.g. `mcp/read`.
 * @param {string} props.anchor - Tool anchor to link to.
 * @return {object} Component markup.
 */
export default function AnchorCopyButton( { view, anchor } ) {
	const [ copied, setCopied ] = useState( false );
	const timeout = useRef();
 
	useEffect( () => () => clearTimeout( timeout.current ), [] );
 
	const handleClick = useCallback( () => {
		window.navigator.clipboard
			?.writeText( buildAnchorUrl( view, anchor ) )
			.then( () => {
				setCopied( true );
				clearTimeout( timeout.current );
				timeout.current = setTimeout( () => setCopied( false ), COPIED_RESET_MS );
			} )
			.catch( () => {} );
	}, [ view, anchor ] );
 
	return (
		<Button
			size="small"
			icon={ copied ? check : link }
			label={ copied ? __( 'Copied', 'jetpack' ) : __( 'Copy link to this tool', 'jetpack' ) }
			showTooltip
			onClick={ handleClick }
		/>
	);
}