Back

100% Statements 17/17
91.66% Branches 11/12
100% Functions 7/7
100% Lines 17/17

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     18x 165x         24x   108x 108x 24x   84x                     84x             60x     24x             18x 18x 18x       16x 16x    
import { parseWithAttributeSchema } from '@wordpress/blocks';
import { addFilter, removeFilter } from '@wordpress/hooks';
 
const FILTER_NAMESPACE = 'jetpack/videopress-native-video-html-sources';
 
// Registering these sources would drop comment-backed VideoPress values.
let htmlSourcedAttributes = {};
 
function htmlSourcedAttributeSchemas( attributes = {} ) {
	return Object.fromEntries(
		Object.entries( attributes ).filter( ( [ , schema ] ) => schema?.source )
	);
}
 
function readHtmlSourcedAttributes( innerHTML ) {
	return Object.fromEntries(
		Object.entries( htmlSourcedAttributes ).map( ( [ key, schema ] ) => {
			const value = parseWithAttributeSchema( innerHTML, schema );
			if ( value === undefined && Object.prototype.hasOwnProperty.call( schema, 'default' ) ) {
				return [ key, schema.default ];
			}
			return [ key, value ];
		} )
	);
}
 
export function applyNativeVideoHtmlSources(
	blockAttributes,
	blockType,
	innerHTML,
	commentAttributes
) {
	if (
		blockType?.name !== 'core/video' ||
		commentAttributes?.guid ||
		blockAttributes?.guid ||
		typeof innerHTML !== 'string' ||
		! innerHTML.includes( '<video' )
	) {
		return blockAttributes;
	}
 
	return {
		...blockAttributes,
		...readHtmlSourcedAttributes( innerHTML ),
	};
}
 
export function registerNativeVideoHtmlSources( attributes ) {
	htmlSourcedAttributes = htmlSourcedAttributeSchemas( attributes );
	removeFilter( 'blocks.getBlockAttributes', FILTER_NAMESPACE );
	addFilter( 'blocks.getBlockAttributes', FILTER_NAMESPACE, applyNativeVideoHtmlSources );
}
 
export function unregisterNativeVideoHtmlSources() {
	htmlSourcedAttributes = {};
	removeFilter( 'blocks.getBlockAttributes', FILTER_NAMESPACE );
}