/** * WordPress dependencies */ import type { select as Select, subscribe as Subscribe, } from '@safe-wordpress/data'; /** * External dependencies */ import type { CssWorkingContentValue } 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; export function onTogglePreview( callback: ( isActive: boolean, css: string, contentValues: ReadonlyArray< CssWorkingContentValue > ) => void ): void { let prevState: boolean | undefined; subscribe( () => { const isActive = areChangesActive(); if ( isActive === undefined ) { return; } if ( prevState !== undefined && isActive === prevState ) { return; } prevState = isActive; callback( isActive, getCss(), getContentValues() ); }, NAB_DATA ); } // ======= // HELPERS // ======= const areChangesActive = () => select( NAB_DATA ).getPageAttribute( 'css-editor/cssEditorState' ) ?.areChangesActive; 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 ?? ''; }; const NO_CHANGES: ReadonlyArray< CssWorkingContentValue > = []; const getContentValues = () => select( NAB_DATA ).getPageAttribute( 'css-editor/cssEditorState' ) ?.contentValues ?? NO_CHANGES;