/** * WordPress dependencies */ import type { select as Select, subscribe as Subscribe, } from '@safe-wordpress/data'; /** * External dependencies */ import { domReady } from '../../../../../../../assets/src/public/utils/helpers/dom-ready'; import type { CssEditorState } from '@nab/types'; /* eslint-disable */ const parent = window.parent as any; const select = parent.wp.data.select as typeof Select; const subscribe = parent.wp.data.subscribe as typeof Subscribe; /* eslint-enable */ // NOTE. No @nab packages in front. import type { store as dataStore } from '@nab/data'; const NAB_DATA = 'nab/data' as unknown as typeof dataStore; // NOTE. No @nab packages in front. import type { store as editorStore } from '@nab/editor'; const NAB_EDITOR = 'nab/editor' as unknown as typeof editorStore; type State = { readonly mode: CssEditorState[ 'mode' ]; readonly css: string; }; export function onCssChanged( callback: ( state: State ) => void ): void { let prevState: State | undefined; const run = () => { if ( ! areChangesActive() ) { return; } const mode = getMode(); if ( ! mode ) { return; } const css = getCss(); const state = { mode, css }; if ( prevState && state.css === prevState.css ) { return; } prevState = state; callback( state ); }; subscribe( run, NAB_EDITOR ); domReady( run ); } // ======= // HELPERS // ======= const areChangesActive = () => select( NAB_DATA ).getPageAttribute( 'css-editor/cssEditorState' ) ?.areChangesActive; const getMode = () => select( NAB_DATA ).getPageAttribute( 'css-editor/cssEditorState' )?.mode; const getCss = (): string => { const alternativeId = select( NAB_DATA ).getPageAttribute( 'css-editor/cssEditorState' )?.alternativeId; if ( ! alternativeId ) { return ''; } const alternative = select( NAB_EDITOR ).getAlternative< { css: string } >( alternativeId ); return alternative?.attributes.css ?? ''; };