2023-02-28 16:33:33 +00:00
|
|
|
import { deepSignal } from 'deepsignal';
|
|
|
|
|
|
|
|
const isObject = ( item ) =>
|
|
|
|
item && typeof item === 'object' && ! Array.isArray( item );
|
|
|
|
|
|
|
|
export const deepMerge = ( target, source ) => {
|
|
|
|
if ( isObject( target ) && isObject( source ) ) {
|
|
|
|
for ( const key in source ) {
|
|
|
|
if ( isObject( source[ key ] ) ) {
|
|
|
|
if ( ! target[ key ] ) Object.assign( target, { [ key ]: {} } );
|
|
|
|
deepMerge( target[ key ], source[ key ] );
|
|
|
|
} else {
|
|
|
|
Object.assign( target, { [ key ]: source[ key ] } );
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const getSerializedState = () => {
|
|
|
|
const storeTag = document.querySelector(
|
2023-06-27 10:22:12 +00:00
|
|
|
`script[type="application/json"]#wc-interactivity-store-data`
|
2023-02-28 16:33:33 +00:00
|
|
|
);
|
|
|
|
if ( ! storeTag ) return {};
|
|
|
|
try {
|
|
|
|
const { state } = JSON.parse( storeTag.textContent );
|
|
|
|
if ( isObject( state ) ) return state;
|
|
|
|
throw Error( 'Parsed state is not an object' );
|
|
|
|
} catch ( e ) {
|
2023-06-27 10:22:12 +00:00
|
|
|
// eslint-disable-next-line no-console
|
2023-02-28 16:33:33 +00:00
|
|
|
console.log( e );
|
|
|
|
}
|
|
|
|
return {};
|
|
|
|
};
|
|
|
|
|
|
|
|
const rawState = getSerializedState();
|
|
|
|
export const rawStore = { state: deepSignal( rawState ) };
|
|
|
|
|
|
|
|
if ( typeof window !== 'undefined' ) window.store = rawStore;
|
|
|
|
|
|
|
|
export const store = ( { state, ...block } ) => {
|
|
|
|
deepMerge( rawStore, block );
|
|
|
|
deepMerge( rawState, state );
|
|
|
|
};
|