All files / hooks/use-signal/src useSignal.ts

100% Statements 52/52
100% Branches 21/21
100% Functions 17/17
100% Lines 52/52

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 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282                                                                                                                                                                                                                                                                                                              128x     128x 128x     128x 128x     128x 128x 66x   3x     20x     3x     10x     15x           128x   71x 5x   66x           128x 530x 15x   515x       128x 1x       128x             128x   151x 151x           128x   128x     128x 70x 63x     7x   12x   12x 6x   12x 4x 4x 4x                 128x 69x 69x 2x 2x 2x                 128x 128x 69x 5x 5x       128x            
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.
 *
 * @remarks
 * `info` is a stable object whose fields are backed by getters that read the
 * store **on access**. The values are therefore render-time snapshots, not
 * reactive state — reading `info.subscriberCount` (or any other field) does
 * **not** subscribe the component to changes in that value. A field only
 * reflects new data on renders that happen for another reason (e.g. after the
 * `signal` version changes). Do not bind UI that must update live (such as a
 * subscriber count badge) to these fields expecting them to re-render on their
 * own; drive such UI from the `signal` version instead.
 */
export interface SignalInfo<T = unknown> {
  /** Signal subscription name */
  readonly name: string;
  /** Current number of active subscribers (read-on-access, not reactive) */
  readonly subscriberCount: number;
  /** Timestamp of last emit (Date.now()) */
  readonly timestamp: number;
  /** Total number of times this signal has been emitted */
  readonly emitCount: number;
  /** Data passed with the last emit */
  readonly 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]);
 
  // Cancel any pending debounced emit when the timing or the target channel
  // changes (and on unmount). Keying on [name, debounce] ensures a timer
  // scheduled for a previous `name` never fires against the new channel — it is
  // cleared before the debounced `emit` closure is recreated for the new name.
  useEffect(() => {
    return () => {
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
        debounceTimerRef.current = null;
        pendingDataRef.current = undefined;
      }
    };
  }, [name, debounce]);
 
  // Emit on mount if option is set.
  // Guarded by a ref so React 18/19 StrictMode's mount → unmount → remount
  // double-invoke fires the mount emit exactly once (the ref persists across
  // the remount of the same component instance).
  const didEmitOnMountRef = useRef(false);
  useEffect(() => {
    if (emitOnMount && !didEmitOnMountRef.current) {
      didEmitOnMountRef.current = true;
      baseEmit();
    }
  }, [emitOnMount, baseEmit]);
 
  return {
    signal,
    emit,
    info: infoRef.current!,
  };
}