All files / hooks/use-on-click-outside/src useOnClickOutside.ts

97.82% Statements 45/46
94.59% Branches 35/37
100% Functions 7/7
97.82% Lines 45/46

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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349                                                                                                                                                                                                    1x               42x                       46x     46x 3x       43x 4x       39x 7x 5x         34x 36x 8x       26x                                                                                                                                                                                                               61x     61x     61x     61x     61x       61x     61x 61x 61x 61x   61x   55x         55x 7x       48x     55x     39x       1x         38x               23x         55x     2x   2x               2x         55x   55x 46x       48x 48x   48x 46x              
import { useEffect, useRef } from "react";
 
/**
 * Event types for click outside detection (mouse + touch)
 */
export type ClickOutsideEvent = MouseEvent | TouchEvent;
 
/**
 * Handler function type for click outside events
 */
export type OnClickOutsideHandler = (event: ClickOutsideEvent) => void;
 
/**
 * Mouse event type options
 */
export type MouseEventType =
  | "mousedown"
  | "mouseup"
  | "click"
  | "pointerdown"
  | "pointerup";
 
/**
 * Touch event type options
 */
export type TouchEventType = "touchstart" | "touchend";
 
/**
 * Ref target type - supports single ref or array of refs
 * Array accepts mixed element types (e.g., [buttonRef, divRef])
 */
export type RefTarget<T extends HTMLElement = HTMLElement> =
  | React.RefObject<T | null>
  | Array<React.RefObject<HTMLElement | null>>;
 
/**
 * Options for useOnClickOutside hook
 */
export interface UseOnClickOutsideOptions {
  /**
   * Whether the event listener is enabled
   * @default true
   */
  enabled?: boolean;
 
  /**
   * Whether to use event capture phase.
   * When true, the handler is called before the event reaches the target element,
   * making it immune to stopPropagation calls.
   * @default true
   */
  capture?: boolean;
 
  /**
   * Mouse event type to listen for
   * @default 'mousedown'
   */
  eventType?: MouseEventType;
 
  /**
   * Touch event type to listen for
   * @default 'touchstart'
   */
  touchEventType?: TouchEventType;
 
  /**
   * Whether to detect touch events (for mobile support)
   * @default true
   */
  detectTouch?: boolean;
 
  /**
   * Array of refs to exclude from outside click detection.
   * Clicks on these elements will not trigger the handler.
   */
  excludeRefs?: Array<React.RefObject<HTMLElement | null>>;
 
  /**
   * Custom function to determine if a target should be excluded.
   * Return true to ignore clicks on the target element.
   * @param target - The clicked element
   * @returns Whether to exclude this element from triggering the handler
   */
  shouldExclude?: (target: Node) => boolean;
 
  /**
   * The event target to attach listeners to
   * @default document
   */
  eventTarget?: Document | HTMLElement | Window | null;
}
 
/**
 * Time window (ms) during which an emulated mouse event that trails a touch
 * interaction is suppressed. Touch devices synthesize `mousedown`/`click`
 * events after `touchstart`/`touchend`, which would otherwise fire the handler
 * a second time for the same tap.
 */
const TOUCH_MOUSE_DEDUPE_WINDOW_MS = 700;
 
/**
 * Normalizes ref input to always return an array of refs
 */
export function normalizeRefs<T extends HTMLElement>(
  ref: RefTarget<T>
): Array<React.RefObject<HTMLElement | null>> {
  return Array.isArray(ref) ? ref : [ref];
}
 
/**
 * Checks if a click event occurred outside of all specified elements
 */
export function isClickOutside(
  event: ClickOutsideEvent,
  refs: Array<React.RefObject<HTMLElement | null>>,
  excludeRefs: Array<React.RefObject<HTMLElement | null>>,
  shouldExclude?: (target: Node) => boolean
): boolean {
  const target = event.target as Node;
 
  // Check if target exists in DOM
  if (!target || !target.isConnected) {
    return false;
  }
 
  // Check custom exclude function
  if (shouldExclude?.(target)) {
    return false;
  }
 
  // Check exclude refs
  for (const excludeRef of excludeRefs) {
    if (excludeRef.current?.contains(target)) {
      return false;
    }
  }
 
  // Check target refs - if clicked inside any of them, it's not an outside click
  for (const ref of refs) {
    if (ref.current?.contains(target)) {
      return false;
    }
  }
 
  return true;
}
 
/**
 * Detects clicks outside of specified element(s) and calls the provided handler.
 * Useful for closing modals, dropdowns, popovers, and similar UI components.
 *
 * @param ref - Single ref or array of refs to detect outside clicks for
 * @param handler - Callback function called when a click outside is detected
 * @param options - Configuration options for the event listener
 *
 * @example
 * ```tsx
 * // Basic usage - close modal on outside click
 * function Modal({ isOpen, onClose }) {
 *   const modalRef = useRef<HTMLDivElement>(null);
 *
 *   useOnClickOutside(modalRef, () => onClose(), { enabled: isOpen });
 *
 *   if (!isOpen) return null;
 *
 *   return (
 *     <div className="overlay">
 *       <div ref={modalRef} className="modal">
 *         Modal content
 *       </div>
 *     </div>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Multiple refs - button and dropdown menu
 * function Dropdown() {
 *   const [isOpen, setIsOpen] = useState(false);
 *   const buttonRef = useRef<HTMLButtonElement>(null);
 *   const menuRef = useRef<HTMLDivElement>(null);
 *
 *   useOnClickOutside(
 *     [buttonRef, menuRef],
 *     () => setIsOpen(false),
 *     { enabled: isOpen }
 *   );
 *
 *   return (
 *     <>
 *       <button ref={buttonRef} onClick={() => setIsOpen(!isOpen)}>
 *         Toggle
 *       </button>
 *       {isOpen && (
 *         <div ref={menuRef}>Dropdown content</div>
 *       )}
 *     </>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // With exclude refs - ignore specific elements
 * function ModalWithPortal({ isOpen, onClose }) {
 *   const modalRef = useRef<HTMLDivElement>(null);
 *   const toastRef = useRef<HTMLDivElement>(null);
 *
 *   useOnClickOutside(modalRef, onClose, {
 *     enabled: isOpen,
 *     excludeRefs: [toastRef], // Clicks on toast won't close modal
 *   });
 *
 *   return (
 *     <>
 *       {isOpen && <div ref={modalRef}>Modal</div>}
 *       <div ref={toastRef}>Toast notification</div>
 *     </>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // With custom exclude function
 * useOnClickOutside(ref, handleClose, {
 *   shouldExclude: (target) => {
 *     // Ignore clicks on elements with specific class
 *     return (target as Element).closest?.('.ignore-outside-click') !== null;
 *   },
 * });
 * ```
 */
export function useOnClickOutside<T extends HTMLElement = HTMLElement>(
  ref: RefTarget<T>,
  handler: OnClickOutsideHandler,
  options: UseOnClickOutsideOptions = {}
): void {
  const {
    enabled = true,
    capture = true,
    eventType = "mousedown",
    touchEventType = "touchstart",
    detectTouch = true,
    excludeRefs = [],
    shouldExclude,
    eventTarget,
  } = options;
 
  // Store handler in ref to avoid re-registering event listeners
  const handlerRef = useRef<OnClickOutsideHandler>(handler);
 
  // Store shouldExclude in ref to avoid re-registering event listeners
  const shouldExcludeRef = useRef(shouldExclude);
 
  // Store excludeRefs in ref to avoid re-registering event listeners
  const excludeRefsRef = useRef(excludeRefs);
 
  // Store ref in a ref to avoid re-registering when array is passed inline
  const refRef = useRef(ref);
 
  // Timestamp of the most recent touch interaction, used to suppress the
  // emulated mouse events that touch devices dispatch after a tap.
  const lastTouchTimeRef = useRef(0);
 
  // Update refs when values change
  handlerRef.current = handler;
  shouldExcludeRef.current = shouldExclude;
  excludeRefsRef.current = excludeRefs;
  refRef.current = ref;
 
  useEffect(() => {
    // SSR check
    Iif (typeof document === "undefined") {
      return;
    }
 
    // Don't add listener if disabled
    if (!enabled) {
      return;
    }
 
    // Get the event target (default to document)
    const target = eventTarget ?? document;
 
    // Internal handler for mouse events
    const handleMouseEvent = (event: Event) => {
      // Suppress the emulated mouse event that trails a touch tap so the
      // handler fires once per interaction, not twice, on touch devices.
      if (
        detectTouch &&
        Date.now() - lastTouchTimeRef.current < TOUCH_MOUSE_DEDUPE_WINDOW_MS
      ) {
        return;
      }
 
      // Normalize refs at event time so the latest ref target(s) are used
      // even when the ref identity changes without re-subscribing.
      if (
        isClickOutside(
          event as MouseEvent,
          normalizeRefs(refRef.current),
          excludeRefsRef.current,
          shouldExcludeRef.current
        )
      ) {
        handlerRef.current(event as MouseEvent);
      }
    };
 
    // Internal handler for touch events
    const handleTouchEvent = (event: Event) => {
      // Record the interaction time first so the trailing mouse event is
      // suppressed regardless of whether this tap was an outside click.
      lastTouchTimeRef.current = Date.now();
 
      Eif (
        isClickOutside(
          event as TouchEvent,
          normalizeRefs(refRef.current),
          excludeRefsRef.current,
          shouldExcludeRef.current
        )
      ) {
        handlerRef.current(event as TouchEvent);
      }
    };
 
    // Add event listeners
    target.addEventListener(eventType, handleMouseEvent, { capture });
 
    if (detectTouch) {
      target.addEventListener(touchEventType, handleTouchEvent, { capture });
    }
 
    // Cleanup
    return () => {
      target.removeEventListener(eventType, handleMouseEvent, { capture });
 
      if (detectTouch) {
        target.removeEventListener(touchEventType, handleTouchEvent, {
          capture,
        });
      }
    };
  }, [enabled, capture, eventType, touchEventType, detectTouch, eventTarget]);
}