UNPKG

@zubridge/electron

Version:

A streamlined state management library for Electron applications using Zustand.

48 lines (47 loc) 1.73 kB
import { createZustandAdapter } from '../adapters/zustand.js'; import { createReduxAdapter } from '../adapters/redux.js'; // WeakMap allows stores to be garbage collected when no longer referenced // Use a variable reference so we can replace it in tests let stateManagerRegistry = new WeakMap(); /** * Gets a state manager for the given store, creating one if it doesn't exist * @internal This is used by createDispatch and createCoreBridge */ export function getStateManager(store, options) { // Check if we already have a state manager for this store if (stateManagerRegistry.has(store)) { return stateManagerRegistry.get(store); } // Create a new state manager based on store type let stateManager; if ('setState' in store) { // It's a Zustand store stateManager = createZustandAdapter(store, options); } else if ('dispatch' in store) { // It's a Redux store stateManager = createReduxAdapter(store, options); } else { throw new Error('Unrecognized store type. Must be a Zustand StoreApi or Redux Store.'); } // Cache the state manager stateManagerRegistry.set(store, stateManager); return stateManager; } /** * Removes a state manager from the registry * Useful when cleaning up to prevent memory leaks in long-running applications */ export function removeStateManager(store) { stateManagerRegistry.delete(store); } /** * Clears all state managers from the registry * Mainly useful for testing */ export function clearStateManagers() { // WeakMap doesn't have a clear method, but we can replace it // with a new empty WeakMap to achieve the same effect stateManagerRegistry = new WeakMap(); }