Back

16.66% Statements 8/48
10% Branches 2/20
12.5% Functions 2/16
16.66% Lines 8/48

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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224                                                                          1x                                                                     1x                                   1x                                                                                                                                                   108x 108x                                                                                   108x 108x                 1x            
/*
 * External dependencies
 */
import { GeneratorModal } from '@automattic/jetpack-ai-client';
import { BlockControls } from '@wordpress/block-editor';
import { getBlockType } from '@wordpress/blocks';
import { createHigherOrderComponent } from '@wordpress/compose';
import { useDispatch, useSelect, select } from '@wordpress/data';
import { useCallback, useEffect, useState } from '@wordpress/element';
import { addFilter } from '@wordpress/hooks';
/*
 * Internal dependencies
 */
import { getFeatureAvailability } from '../../blocks/ai-assistant/lib/utils/get-feature-availability';
import AiToolbarButton from './components/ai-toolbar-button.tsx';
import { SITE_LOGO_BLOCK_AI_EXTENSION, TOOL_PLACEMENT, PLACEMENT_CONTEXT } from './constants.ts';
 
/**
 * Mininal type definition for the core select function.
 */
type CoreSelect = {
	getEntityRecord: (
		kind: string,
		name: string
	) => {
		url: string;
		title: string;
		description: string;
		site_logo: number;
	};
};
 
/**
 * Hook to set the site logo on the local state, affecting the logo block.
 *
 * @return {object} An object with the setLogo function.
 */
const useSetLogo = () => {
	const editEntityRecord = useDispatch( 'core' ).editEntityRecord;
	const saveLogo = useCallback(
		( mediaId: number ) => {
			editEntityRecord( 'root', 'site', undefined, {
				site_logo: mediaId,
			} );
		},
		[ editEntityRecord ]
	);
 
	const saveIcon = useCallback(
		( mediaId: number ) => {
			editEntityRecord( 'root', 'site', undefined, {
				site_icon: mediaId,
			} );
		},
		[ editEntityRecord ]
	);
 
	const setLogo = useCallback(
		( mediaId: number, updateIcon: boolean ) => {
			saveLogo( mediaId );
			if ( updateIcon ) {
				saveIcon( mediaId );
			}
		},
		[ saveLogo, saveIcon ]
	);
 
	return {
		setLogo,
	};
};
 
const useSiteDetails = () => {
	const siteSettings = useSelect( selectData => {
		return ( selectData( 'core' ) as CoreSelect ).getEntityRecord( 'root', 'site' );
	}, [] );
 
	return {
		ID: parseInt( window?.Jetpack_Editor_Initial_State?.wpcomBlogId ),
		URL: siteSettings?.url,
		domain: window?.Jetpack_Editor_Initial_State?.siteFragment,
		name: siteSettings?.title,
		description: siteSettings?.description,
		siteLogo: siteSettings?.site_logo || 0,
	};
};
 
/**
 * HOC to add the AI button on the Site Logo toolbar.
 */
const siteLogoEditWithAiComponents = createHigherOrderComponent( BlockEdit => {
	return props => {
		const [ isLogoGeneratorModalVisible, setIsLogoGeneratorModalVisible ] = useState( false );
		const { setLogo } = useSetLogo();
		const shouldSyncIcon = props?.attributes?.shouldSyncIcon || false;
 
		const showModal = useCallback( () => {
			setIsLogoGeneratorModalVisible( true );
		}, [] );
 
		const closeModal = useCallback( () => {
			setIsLogoGeneratorModalVisible( false );
		}, [] );
 
		// const reloadModal = useCallback( () => {
		// 	closeModal();
		// 	showModal();
		// }, [ closeModal, showModal ] );
 
		const applyLogoHandler = useCallback(
			( mediaId: number ) => {
				if ( mediaId ) {
					setLogo( mediaId, shouldSyncIcon );
				}
			},
			[ setLogo, shouldSyncIcon ]
		);
 
		useEffect( () => {
			return () => {
				// close modal if open when the component unmounts
				closeModal();
			};
		}, [ closeModal ] );
 
		const siteDetails = useSiteDetails();
 
		return (
			<>
				<BlockEdit { ...props } />
				<BlockControls group="block">
					<AiToolbarButton showButtonText={ ! siteDetails?.siteLogo } clickHandler={ showModal } />
				</BlockControls>
				<GeneratorModal
					isOpen={ isLogoGeneratorModalVisible }
					onClose={ closeModal }
					onApplyLogo={ applyLogoHandler }
					// reload is not working right and can end up showing a non functional modal
					// onReload={ reloadModal }
					context={ PLACEMENT_CONTEXT }
					placement={ TOOL_PLACEMENT }
					siteDetails={ siteDetails }
				/>
			</>
		);
	};
}, 'SiteLogoEditWithAiComponents' );
 
/**
 * Function to check if the feature is available depending on the site ID.
 *
 * @return {boolean} True if the feature is available.
 */
function isFeatureAvailable() {
	return getFeatureAvailability( SITE_LOGO_BLOCK_AI_EXTENSION );
}
 
/**
 * Function to check if the block can be extended.
 *
 * @param {string} name - The block name.
 * @return {boolean} True if the block can be extended.
 */
function canExtendBlock( name: string ): boolean {
	Eif ( name !== 'core/site-logo' ) {
		return false;
	}
 
	// Check if the AI Assistant block is registered. If not, we understand that Jetpack AI is not active.
	const isAIAssistantBlockRegistered = getBlockType( 'jetpack/ai-assistant' );
 
	if ( ! isAIAssistantBlockRegistered ) {
		return false;
	}
 
	// Disable if the feature is not available.
	if ( ! isFeatureAvailable() ) {
		return false;
	}
 
	/*
	 * Do not extend if the AI Assistant block is hidden,
	 * as a way for the user to hide the extension.
	 * Note: `select( 'core/edit-post' )` returns null on P2 sites (no post editor),
	 * so we fall back to an empty array, which allows the extension to load.
	 */
	const hiddenBlocks =
		(
			select( 'core/edit-post' ) as null | { getHiddenBlockTypes?: () => string[] }
		 )?.getHiddenBlockTypes?.() ?? [];
 
	if ( hiddenBlocks.includes( 'jetpack/ai-assistant' ) ) {
		return false;
	}
 
	return true;
}
 
/**
 * Function to override the core Site Logo block edit settings.
 * Will create a HOC to use as the edit implementation.
 *
 * @param {object} settings - The block settings.
 * @param {string} name     - The block name.
 * @return {object} The new block settings.
 */
function jetpackSiteLogoWithAiSupport( settings, name: string ) {
	Eif ( ! canExtendBlock( name ) ) {
		return settings;
	}
 
	return {
		...settings,
		edit: siteLogoEditWithAiComponents( settings.edit ),
	};
}
 
addFilter(
	'blocks.registerBlockType',
	'jetpack/site-logo-with-ai-support',
	jetpackSiteLogoWithAiSupport,
	100
);