function reportNativeElementPositionChanges()

in apps-rendering/src/client/nativeCommunication.ts [225:294]


function reportNativeElementPositionChanges(): void {
	let adSlots = getAdSlots();
	let videoSlots = getVideoSlots();

	const targetNode = document.querySelector('html') as Node;
	const config: MutationObserverInit = {
		childList: true,
		subtree: true,
		attributeFilter: ['style'],
	};
	const callback = function (): void {
		try {
			const currentAdSlots = getAdSlots();

			if (positionChanged(currentAdSlots, adSlots)) {
				adSlots = currentAdSlots;
				void commercialClient.updateAdverts(currentAdSlots);
			}
		} catch (ex) {
			logger.error('Exception updating ads');
		}

		try {
			const currentVideoSlots = getVideoSlots();

			if (positionChanged(currentVideoSlots, videoSlots)) {
				videoSlots = currentVideoSlots;
				void videoClient.updateVideos(currentVideoSlots);
			}
		} catch (ex) {
			logger.error('Exception updating videos');
		}
	};

	// After a 3 second wait, attempt to sync up positions again
	// This is to fix bug with Youtube embeds being 50px higher than they should be
	// on first load of page, on Android.
	window.setTimeout(callback, 3000);

	let currentAnimationFrame: number | null = null;
	window.addEventListener(
		'resize',
		() => {
			if (currentAnimationFrame !== null) {
				window.cancelAnimationFrame(currentAnimationFrame);
			}
			currentAnimationFrame = window.requestAnimationFrame(callback);
		},
		false,
	);

	window.addEventListener('load', callback);

	const observer = new MutationObserver(callback);
	observer.observe(targetNode, config);

	try {
		void document.fonts.ready.then(() => {
			void commercialClient.updateAdverts(getAdSlots());
			void videoClient.updateVideos(getVideoSlots());
		});
	} catch (e) {
		logger.error(
			`font loading API not supported: ${errorToString(
				e,
				'unknown reason',
			)}`,
		);
	}
}