/** * WordPress dependencies */ import { dispatch, select, subscribe } from '@safe-wordpress/data'; /** * Internal dependencies */ import { store as NC_SETTINGS } from './store'; import type { Value as PostTypeValue } from './fields/post-type-setting/config'; // ========= // ANALYTICS // ========= onFieldChange( 'nelio-content_settings[analytics_post_types]', ( value ) => toggleAnalytics( value as PostTypeValue, true ), [ 'nelio-content_settings[google_analytics_data]' ] ); function toggleAnalytics( value: PostTypeValue, refreshDisabled: boolean ) { const { setAttributes } = dispatch( NC_SETTINGS ); void setAttributes( 'nelio-content_settings[google_analytics_data]', { disabled: ! value.length, refreshDisabled, } ); } // toggleAnalytics() // === // EFI // === onFieldChange( 'nelio-content_settings[efi_post_types]', ( value ) => toggleEfi( value as PostTypeValue ) ); function toggleEfi( value: PostTypeValue ) { type MaybeSelect = HTMLSelectElement | null; const disabled = ! value.length; const efiMode = document.getElementById( 'efi-mode' ) as MaybeSelect; if ( efiMode ) { efiMode.disabled = disabled; } const autoFeatImg = document.getElementById( 'auto-feat-image' ) as MaybeSelect; if ( autoFeatImg ) { autoFeatImg.disabled = disabled; } } // ======= // HELPERS // ======= function onFieldChange( field: string, callback: ( currentValue: unknown ) => void, requiredFields: string[] = [] ) { const allFields = [ field, ...requiredFields ]; let hadBeenInitialized = allFields.every( ( f ) => select( NC_SETTINGS ).hasBeenInitialized( f ) ); let previousValue: unknown = select( NC_SETTINGS ).getValue( field ); subscribe( () => { const haveBeenInitialized = allFields.every( ( f ) => select( NC_SETTINGS ).hasBeenInitialized( f ) ); if ( ! haveBeenInitialized ) { return; } const currentValue = select( NC_SETTINGS ).getValue( field ); if ( ! hadBeenInitialized ) { hadBeenInitialized = haveBeenInitialized; previousValue = currentValue; return; } if ( previousValue === currentValue ) { return; } previousValue = currentValue; callback( currentValue ); } ); if ( hadBeenInitialized ) { callback( previousValue ); } }