import { createTailwindConfig, updateTailwindTheme, updateTailwindPlugins, } from '@tailwind/config'; let subscribePrev = null as string; const init = (wp: any, blockbite: any, tailwind: any) => { if (wp && blockbite) { const store = wp.data.select('biteStore/editor'); wp.data.subscribe(() => { if (!store) { return; } const subscribeCurrent = store.getTailwindConfigChange(); const editorStylesWrapper = getEditorStylesWrapper(); /* Listen for changes and trigger once */ if (subscribePrev !== subscribeCurrent && editorStylesWrapper) { subscribePrev = subscribeCurrent; prefixStylesWrappersParent(editorStylesWrapper); addTailwindConfig(store, blockbite, tailwind); removeSsrStyles(); } }); } }; // scope up the window chain to find the wp object and blockbite object if (window.self !== window.top) { const wp = window.parent.wp; const blockbite = window.parent?.blockbite; init(wp, blockbite, tailwind); } else { init(wp, blockbite, tailwind); } const getEditorStylesWrapper = () => { const stylesWrapper = document.querySelector('.editor-styles-wrapper'); return stylesWrapper; }; const prefixStylesWrappersParent = (editorStylesWrapper: any) => { const parent = editorStylesWrapper.parentElement; parent.setAttribute('id', 'b_'); }; const addTailwindConfig = (store: any, blockbite: any, tailwind: any) => { const utils = store.getUtils(); const theme = store.getTheme(); // init the tailwind config blockbite.tailwindConfig = createTailwindConfig(); const { extendColors, extendFontSize, extendFontFamily } = updateTailwindTheme(store); // add theme extend blockbite.tailwindConfig.theme.extend = { ...blockbite.tailwindConfig.theme.extend, colors: extendColors, fontSize: extendFontSize, fontFamily: extendFontFamily, }; blockbite.tailwindConfig.plugins = updateTailwindPlugins(utils, theme); // create a reference to the scoped blockbite.tailwindConfig const resolvedConfig = tailwind.resolveConfig(blockbite.tailwindConfig); // Push update to the bottom of the event loop to ensure that // other operations (such as device switching) are complete setTimeout(() => { tailwind.config = resolvedConfig; // we need a better fix for this // this is a hack to force the tailwind config to update const tempStyle = document.createElement('style'); document.head.appendChild(tempStyle); document.head.removeChild(tempStyle); }, 0); }; const removeSsrStyles = () => { // Remove server-side rendered styles for the editor. // This was only needed to prevent a FOUC in the editor. const ssrStyles = document.getElementById('blockbite-style-css'); if (ssrStyles) { setTimeout(() => { ssrStyles.remove(); console.log('Removed server-side rendered styles for the editor.'); }, 2000); } };