All files / use-signal/src useSignal.ts

97.91% Statements 47/48
100% Branches 19/19
94.11% Functions 16/17
97.91% Lines 47/48

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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262                                                                                                                                                                                                                                                                                          96x     96x 96x     96x 96x     96x 96x 53x   3x     14x     3x     8x     15x           96x   54x 3x   51x           96x 429x 9x   420x       96x         96x             96x   140x 140x           96x   96x     96x 54x 49x     5x   11x   11x 6x   11x 4x 4x 4x           96x 53x 53x 1x           96x 54x 4x       96x            
import {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useSyncExternalStore,
} from "react";
import {
  subscribe,
  getSnapshot as getStoreSnapshot,
  emit as storeEmit,
  getSubscriberCount,
  getEmitCount,
  getTimestamp,
  getData,
} from "./store";
 
/**
 * Signal metadata object for debugging and monitoring
 */
export interface SignalInfo<T = unknown> {
  /** Signal subscription name */
  name: string;
  /** Current number of active subscribers */
  subscriberCount: number;
  /** Timestamp of last emit (Date.now()) */
  timestamp: number;
  /** Total number of times this signal has been emitted */
  emitCount: number;
  /** Data passed with the last emit */
  data: T | undefined;
}
 
/**
 * Options for useSignal hook
 */
export interface SignalOptions {
  /** Automatically emit when component mounts */
  emitOnMount?: boolean;
  /** Callback executed when emit is called */
  onEmit?: () => void;
  /** Conditionally enable/disable subscription (default: true) */
  enabled?: boolean;
  /** Debounce emit calls in milliseconds */
  debounce?: number;
}
 
/**
 * Return type for useSignal hook
 */
export interface UseSignalReturn<T = unknown> {
  /** Current signal version number - use in dependency arrays */
  signal: number;
  /** Function to emit the signal and notify all subscribers, optionally with data */
  emit: (data?: T) => void;
  /** Stable metadata object for debugging and monitoring */
  info: SignalInfo<T>;
}
 
/**
 * A hook for event-driven communication between components without prop drilling.
 * Components subscribe to a shared signal by name. When any component emits,
 * all subscribers receive a new version number.
 *
 * @param name - Unique identifier string for the signal channel
 * @param options - Configuration options
 * @returns Object containing signal value, emit function, and info metadata
 *
 * @example
 * ```tsx
 * // Parent Component - emits signal
 * function ParentComponent() {
 *   const { emit } = useSignal("Dashboard Refresh");
 *
 *   return <button onClick={emit}>Refresh All</button>;
 * }
 *
 * // Child Component - subscribes to signal
 * function DataTable() {
 *   const { signal } = useSignal("Dashboard Refresh");
 *
 *   useEffect(() => {
 *     fetchTableData();
 *   }, [signal]);
 *
 *   return <table>...</table>;
 * }
 * ```
 *
 * @example
 * ```tsx
 * // With debugging info
 * function MonitoredComponent() {
 *   const { signal, emit, info } = useSignal("API Sync", {
 *     onEmit: () => console.log("Syncing...")
 *   });
 *
 *   useEffect(() => {
 *     syncData();
 *     console.log(`Sync #${info.emitCount} with ${info.subscriberCount} listeners`);
 *   }, [signal]);
 *
 *   return <button onClick={emit}>Sync</button>;
 * }
 * ```
 *
 * @example
 * ```tsx
 * // With data payload
 * function DataEmitter() {
 *   const { emit } = useSignal<{ userId: string }>("user-action");
 *
 *   const handleClick = (userId: string) => {
 *     emit({ userId });
 *   };
 *
 *   return <button onClick={() => handleClick("123")}>Action</button>;
 * }
 *
 * function DataReceiver() {
 *   const { signal, info } = useSignal<{ userId: string }>("user-action");
 *
 *   useEffect(() => {
 *     if (info.data) {
 *       console.log("User action for:", info.data.userId);
 *     }
 *   }, [signal]);
 *
 *   return <div>Listening...</div>;
 * }
 * ```
 */
export function useSignal<T = unknown>(
  name: string,
  options: SignalOptions = {}
): UseSignalReturn<T> {
  const {
    emitOnMount = false,
    onEmit,
    enabled = true,
    debounce,
  } = options;
 
  // Store options in refs for stable references
  const onEmitRef = useRef(onEmit);
  onEmitRef.current = onEmit;
 
  // Stable name ref for info object
  const nameRef = useRef(name);
  nameRef.current = name;
 
  // Info object with stable reference using getters for live data
  const infoRef = useRef<SignalInfo<T> | null>(null);
  if (!infoRef.current) {
    infoRef.current = {
      get name() {
        return nameRef.current;
      },
      get subscriberCount() {
        return getSubscriberCount(nameRef.current);
      },
      get timestamp() {
        return getTimestamp(nameRef.current);
      },
      get emitCount() {
        return getEmitCount(nameRef.current);
      },
      get data() {
        return getData(nameRef.current) as T | undefined;
      },
    } as SignalInfo<T>;
  }
 
  // Subscribe function for useSyncExternalStore
  const subscribeToStore = useCallback(
    (onStoreChange: () => void) => {
      if (!enabled) {
        return () => {};
      }
      return subscribe(name, onStoreChange);
    },
    [name, enabled]
  );
 
  // Get snapshot function
  const getSnapshot = useCallback((): number => {
    if (!enabled) {
      return 0;
    }
    return getStoreSnapshot(name);
  }, [name, enabled]);
 
  // Server snapshot (always 0 for SSR)
  const getServerSnapshot = useCallback((): number => {
    return 0;
  }, []);
 
  // Use useSyncExternalStore for synchronized state
  const signal = useSyncExternalStore(
    subscribeToStore,
    getSnapshot,
    getServerSnapshot
  );
 
  // Base emit function
  const baseEmit = useCallback(
    (data?: T) => {
      storeEmit(name, data);
      onEmitRef.current?.();
    },
    [name]
  );
 
  // Debounce timer ref
  const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  // Store the latest data for debounced emit
  const pendingDataRef = useRef<T | undefined>(undefined);
 
  // Debounced or regular emit
  const emit = useMemo(() => {
    if (!debounce || debounce <= 0) {
      return baseEmit;
    }
 
    return (data?: T) => {
      // Store the latest data
      pendingDataRef.current = data;
 
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }
      debounceTimerRef.current = setTimeout(() => {
        baseEmit(pendingDataRef.current);
        pendingDataRef.current = undefined;
        debounceTimerRef.current = null;
      }, debounce);
    };
  }, [baseEmit, debounce]);
 
  // Cleanup debounce timer on unmount
  useEffect(() => {
    return () => {
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }
    };
  }, []);
 
  // Emit on mount if option is set
  useEffect(() => {
    if (emitOnMount) {
      baseEmit();
    }
  }, [emitOnMount, baseEmit]);
 
  return {
    signal,
    emit,
    info: infoRef.current!,
  };
}