Back

21.05% Statements 4/19
8.33% Branches 1/12
20% Functions 1/5
21.05% Lines 4/19

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                          1x                                                                                             108x 108x               1x          
import { createBlock } from '@wordpress/blocks';
import { addFilter } from '@wordpress/hooks';
import services from './services';
 
/**
 * The Social Icons widget and Social Links block determine the link source
 * differently. This loops through all current icons and compares the URL against
 * an array of available services in order to populate the new blocks.
 *
 * @param {object} instance - The widget instance returned from the API
 * @param {string} idBase   - The widget name
 * @return {object} The transforms settings
 */
const socialLinksTransform = {
	from: [
		{
			type: 'block',
			isMultiBlock: false,
			blocks: [ 'core/legacy-widget' ],
			isMatch: ( { idBase, instance } ) => {
				if ( ! instance?.raw ) {
					return false;
				}
				return idBase === 'jetpack_widget_social_icons';
			},
			transform: ( { instance } ) => {
				let innerBlocks = [];
				const icons = instance.raw.icons;
 
				icons.forEach( icon => {
					const iconUrl = new URL( icon.url.includes( ':' ) ? icon.url : 'https://' + icon.url );
					const iconHostname = iconUrl.hostname ? iconUrl.hostname : iconUrl.protocol;
					const iconService = services.find( service => {
						return iconHostname.includes( service.url ) || service.url.includes( iconHostname );
					} );
 
					const innerBlock = createBlock( 'core/social-link', {
						service: iconService ? iconService.name : 'chain',
						url: icon.url,
					} );
					innerBlocks = [ ...innerBlocks, innerBlock ];
				} );
				return createBlock( 'core/social-links', {}, innerBlocks );
			},
		},
	],
};
 
/**
 * With the upgrade to block editor in widgets, the Social Icons widget is redundant.
 *
 * Since this feature is built into the Gutenberg core and there is no relevant Jetpack
 * block to place this in, we need to hook into the core block and apply the transform to
 * handle this addition.
 *
 * @param {object} settings - Block settings object.
 * @param {string} name     - The block name
 * @return {object} The settings for the given block with the patched variations.
 */
function addTransformToSocialLinksWidget( settings, name ) {
	Eif ( name !== 'core/social-links' ) {
		return settings;
	}
 
	settings.transforms = socialLinksTransform;
 
	return settings;
}
 
addFilter(
	'blocks.registerBlockType',
	'addTransformToSocialLinksWidget',
	addTransformToSocialLinksWidget
);