{"version":3,"sources":["createStore.ts"],"sourcesContent":["import { useState, useEffect } from \"react\"\nimport { Data, useObserveData } from \"framer\"\n\nexport function createStore<T>(state: T) {\n    // Use Data so that a Preview reload resets the state\n    const dataStore = Data({\n        state: Object.freeze({\n            ...state,\n        }),\n    })\n    // Create a set function that updates the state\n    const setDataStore = (\n        newState: Partial<T> | ((newState: T) => Partial<T>)\n    ) => {\n        // If the state is an object, make sure we copy it\n        if (typeof newState === \"function\") {\n            newState = newState(dataStore.state)\n        }\n        dataStore.state = Object.freeze({\n            ...dataStore.state,\n            ...newState,\n        })\n    }\n\n    // Store the initial state, copy the object if it's an object\n    let storeState: T =\n        typeof state === \"object\" ? Object.freeze({ ...state }) : state\n\n    // Keep a list of all the listeners, in the form of React hook setters\n    const storeSetters = new Set<Function>()\n\n    // Create a set function that updates all the listeners / setters\n    const setStoreState = (\n        newState: Partial<T> | ((newState: T) => Partial<T>)\n    ) => {\n        // If the state is an object, make sure we copy it\n        if (typeof newState === \"function\") {\n            newState = newState(storeState)\n        }\n        storeState =\n            typeof newState === \"object\"\n                ? Object.freeze({ ...storeState, ...newState })\n                : newState\n        // Update all the listeners / setters with the new value\n        storeSetters.forEach((setter) => setter(storeState))\n    }\n\n    // Create the actual hook based on everything above\n    function useStore() {\n        // Create the hook we are going to use as a listener\n        const [state, setState] = useState(storeState)\n        // If we unmount the component using this hook, we need to remove the listener\n        // @ts-ignore\n        useEffect(() => {\n            // But right now, we need to add the listener\n            storeSetters.add(setState)\n            return () => storeSetters.delete(setState)\n        }, [])\n\n        // If Data context exists, use Data, otherwise use vanilla React state\n        if (useObserveData() === true) {\n            useObserveData()\n            return [dataStore.state, setDataStore] as const\n        } else {\n            // Return the state and a function to update the central store\n            return [state, setStoreState] as const\n        }\n    }\n    return useStore\n}\n"],"names":[],"mappings":"AAAA,MAAM,CAAG,QAAQ,CAAE,SAAS,KAAQ,CAAO,OAC3C,MAAM,CAAG,IAAI,CAAE,cAAc,KAAQ,CAAQ,QAE7C,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