useTouchScreen.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. 'use client'
  2. import { useEffect, useState } from 'react'
  3. /**
  4. * Phones and tablets: a finger as the main pointer, or a screen narrower than
  5. * a laptop's. A touchscreen laptop keeps the button, its main pointer is a mouse.
  6. */
  7. export const TOUCH_SCREEN_QUERY = '(pointer: coarse), (max-width: 1023px)'
  8. /**
  9. * Whether this is a phone or tablet, where the floating support button is not
  10. * drawn. `null` until the browser has been asked, so a caller can hold back
  11. * what it would otherwise have to pull away a frame later.
  12. */
  13. export function useTouchScreen(): boolean | null {
  14. const [touchScreen, setTouchScreen] = useState<boolean | null>(null)
  15. useEffect(() => {
  16. const query = window.matchMedia?.(TOUCH_SCREEN_QUERY)
  17. if (!query) {
  18. setTouchScreen(false)
  19. return
  20. }
  21. const sync = () => setTouchScreen(query.matches)
  22. sync()
  23. // Rotating a small tablet or resizing a window moves it across the line.
  24. query.addEventListener('change', sync)
  25. return () => query.removeEventListener('change', sync)
  26. }, [])
  27. return touchScreen
  28. }