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 {};
|
|
|
|
};
|
|
|
|
|
2023-08-10 14:02:33 +00:00
|
|
|
export const afterLoads = new Set();
|
|
|
|
|
2023-02-28 16:33:33 +00:00
|
|
|
const rawState = getSerializedState();
|
|
|
|
export const rawStore = { state: deepSignal( rawState ) };
|
|
|
|
|
|
|
|
if ( typeof window !== 'undefined' ) window.store = rawStore;
|
|
|
|
|
2023-08-10 14:02:33 +00:00
|
|
|
export const store = ( { state, ...block }, { afterLoad } = {} ) => {
|
2023-02-28 16:33:33 +00:00
|
|
|
deepMerge( rawStore, block );
|
|
|
|
deepMerge( rawState, state );
|
2023-08-10 14:02:33 +00:00
|
|
|
if ( afterLoad ) afterLoads.add( afterLoad );
|
2023-02-28 16:33:33 +00:00
|
|
|
};
|