/** * WordPress dependencies */ import { subscribe, select, dispatch } from '@wordpress/data'; /** * External dependencies */ import once from 'lodash/once'; /** * Internal dependencies */ import { store as NAB_CHECKER } from './store'; import type { State } from './store/types'; const LOCAL_KEY = 'nabChecker'; export const initLocalStorageSyncher = once( () => { const data = getLocalStorageValue(); let prevTab = data.tab; let prevPosition = data.position; void dispatch( NAB_CHECKER ).setTab( prevTab ); void dispatch( NAB_CHECKER ).setPosition( prevPosition ); subscribe( () => { const tab = select( NAB_CHECKER ).getTab(); const position = select( NAB_CHECKER ).getPosition(); if ( tab === prevTab && position === prevPosition ) { return; } prevTab = tab; prevPosition = position; localStorage.setItem( LOCAL_KEY, JSON.stringify( { tab, position } ) ); }, NAB_CHECKER ); } ); // ======= // HELPERS // ======= const DEFAULT_VALUE: { readonly tab: State[ 'tab' ]; readonly position: State[ 'position' ]; } = { tab: 'status', position: 'top-right', }; function getLocalStorageValue(): typeof DEFAULT_VALUE { try { const raw: unknown = JSON.parse( localStorage.getItem( LOCAL_KEY ) ?? '' ); if ( ! raw || 'object' !== typeof raw ) { return DEFAULT_VALUE; } const tab = 'tab' in raw ? raw.tab : ''; const position = 'position' in raw ? raw.position : ''; return { tab: 'status' === tab || 'experiments' === tab || 'events' === tab || 'heatmap-clicks' === tab ? tab : DEFAULT_VALUE.tab, position: 'top-left' === position || 'top-right' === position || 'bottom-left' === position || 'bottom-right' === position ? position : DEFAULT_VALUE.position, }; } catch ( _ ) { return DEFAULT_VALUE; } }