import { BlockPreview } from '@wordpress/block-editor'; import { rawHandler } from '@wordpress/blocks'; import { Spinner } from '@wordpress/components'; import { useRef, useMemo, useState, useLayoutEffect, useCallback, } from '@wordpress/element'; import { forwardRef } from '@wordpress/element'; import { pageNames } from '@shared/lib/pages'; import classNames from 'classnames'; import { AnimatePresence, motion } from 'framer-motion'; import { usePreviewIframe } from '@launch/hooks/usePreviewIframe'; import { hexTomatrixValues, lowerImageQuality } from '@launch/lib/util'; import themeJSON from '../_data/theme-processed.json'; export const PagePreview = forwardRef(({ style }, ref) => { const previewContainer = useRef(null); const blockRef = useRef(null); const [ready, setReady] = useState(false); const onLoad = useCallback( (frame) => { frame.contentDocument?.getElementById('ext-tj')?.remove(); // Run this 150 times at an interval of 100ms (15s) // This is a brute force check that the styles are there let lastRun = performance.now(); let counter = 0; const checkOnStyles = () => { if (counter >= 150) return; const now = performance.now(); if (now - lastRun < 100) return requestAnimationFrame(checkOnStyles); lastRun = now; frame?.contentDocument?.querySelector('[href*=load-styles]')?.remove(); if (!frame.contentDocument?.getElementById('ext-tj')) { const primaryColor = style?.variation?.settings?.color?.palette?.theme?.find( ({ slug }) => slug === 'primary', )?.color; const [r, g, b] = hexTomatrixValues(primaryColor); frame.contentDocument?.body?.insertAdjacentHTML( 'beforeend', ``, ); } // Look for any frames inside the iframe, like the html block const innerFrames = frame.contentDocument?.querySelectorAll('iframe'); innerFrames?.forEach((inner) => { inner?.contentDocument ?.querySelector('[href*=load-styles]') ?.remove(); inner?.contentDocument ?.querySelector('body') ?.classList.add('editor-styles-wrapper'); if (inner && !inner.contentDocument?.getElementById('ext-tj')) { inner.contentDocument?.body?.insertAdjacentHTML( 'beforeend', ``, ); } }); counter++; requestAnimationFrame(checkOnStyles); // recursive }; checkOnStyles(); }, [style?.variation], ); const { ready: showPreview } = usePreviewIframe({ container: ref.current, ready, onLoad, loadDelay: 400, }); const blocks = useMemo(() => { const links = [ pageNames.about.title, pageNames.blog.title, pageNames.contact.title, ]; const code = [ style?.headerCode, style?.patterns ?.map(({ code }) => code) .flat() .join(''), style?.footerCode, ] .filter(Boolean) .join('') .replace( // //g, `
${links.join(' | ')}
`, ) .replace( // //g, `${links.join(' | ')}
`, ) .replace( //g, '', ); return rawHandler({ HTML: lowerImageQuality(code) }); }, [style]); useLayoutEffect(() => { setReady(false); const timer = setTimeout(() => setReady(true), 0); return () => clearTimeout(timer); }, [blocks]); return ( <>