All files / src/hooks useResponsiveBreakpoint.ts

94.44% Statements 17/18
83.33% Branches 5/6
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 67 68 69 70 71 72 73 74 75 76 77 78                    9x                       33x 24x 12x                                                             23x   16x 16x     23x   16x 17x 17x       16x     16x     23x    
import { useState, useEffect } from 'react';
 
/**
 * Responsive breakpoint names
 */
export type Breakpoint = 'mobile' | 'tablet' | 'desktop';
 
/**
 * Breakpoint width thresholds in pixels
 */
const BREAKPOINTS = {
  mobile: 640,
  tablet: 1024,
} as const;
 
/**
 * Determines the current breakpoint based on window width
 * 
 * @param width - Window width in pixels
 * @returns Current breakpoint name
 */
function getBreakpoint(width: number): Breakpoint {
  if (width < BREAKPOINTS.mobile) return 'mobile';
  if (width < BREAKPOINTS.tablet) return 'tablet';
  return 'desktop';
}
 
/**
 * Custom hook for detecting current responsive breakpoint
 * 
 * ## Business Perspective
 * 
 * This hook enables widgets to adapt their layout and content based on
 * device size, ensuring optimal user experience for security officers
 * and executives accessing the application from different devices. 📱💻
 * 
 * Responsive design is critical for modern security dashboards that need
 * to be accessible on mobile devices during incident response.
 * 
 * @returns Current breakpoint ('mobile', 'tablet', or 'desktop')
 * 
 * @example
 * ```typescript
 * const breakpoint = useResponsiveBreakpoint();
 * 
 * return (
 *   <div>
 *     {breakpoint === 'mobile' && <MobileLayout />}
 *     {breakpoint === 'tablet' && <TabletLayout />}
 *     {breakpoint === 'desktop' && <DesktopLayout />}
 *   </div>
 * );
 * ```
 */
export function useResponsiveBreakpoint(): Breakpoint {
  const [breakpoint, setBreakpoint] = useState<Breakpoint>(() => {
    // SSR safety: return desktop as default for server-side rendering
    Iif (typeof window === 'undefined') return 'desktop';
    return getBreakpoint(window.innerWidth);
  });
 
  useEffect(() => {
    // Handler for window resize events
    const handleResize = () => {
      const width = window.innerWidth;
      setBreakpoint(getBreakpoint(width));
    };
 
    // Add event listener
    window.addEventListener('resize', handleResize);
 
    // Cleanup: remove event listener on unmount
    return () => window.removeEventListener('resize', handleResize);
  }, []);
 
  return breakpoint;
}