All files / use-local-storage/src store.ts

100% Statements 15/15
75% Branches 6/8
100% Functions 6/6
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                  1x                 62x 53x     62x 62x   62x 62x     62x 53x                         36x 36x 49x                 2x               48x      
/**
 * Internal Store Manager for localStorage synchronization
 * This module manages listeners for same-tab synchronization across components
 * using the same localStorage key.
 *
 * @internal This module is not exported publicly
 */
 
/** Map of key -> Set of listener callbacks */
const listeners = new Map<string, Set<() => void>>();
 
/**
 * Subscribe a listener to changes for a specific key
 * @param key - The localStorage key to subscribe to
 * @param listener - Callback to invoke when the key's value changes
 * @returns Unsubscribe function
 */
export function subscribe(key: string, listener: () => void): () => void {
  if (!listeners.has(key)) {
    listeners.set(key, new Set());
  }
 
  const keyListeners = listeners.get(key)!;
  keyListeners.add(listener);
 
  return () => {
    keyListeners.delete(listener);
 
    // Cleanup: remove the key entry if no more listeners
    if (keyListeners.size === 0) {
      listeners.delete(key);
    }
  };
}
 
/**
 * Notify all listeners subscribed to a specific key
 * This is called when setValue or removeValue is invoked
 * to synchronize all components using the same key in the same tab
 *
 * @param key - The localStorage key that was updated
 */
export function notifyListeners(key: string): void {
  const keyListeners = listeners.get(key);
  Eif (keyListeners) {
    keyListeners.forEach((listener) => listener());
  }
}
 
/**
 * Get the count of listeners for a key (for testing purposes)
 * @internal
 */
export function getListenerCount(key: string): number {
  return listeners.get(key)?.size ?? 0;
}
 
/**
 * Clear all listeners (for testing purposes)
 * @internal
 */
export function clearAllListeners(): void {
  listeners.clear();
}