Bin
2025-12-17 d616898802dfe7e5dd648bcf53c6d1f86b6d3642
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
import { useEffect, useRef } from "react";
 
const enterFullscreen = (el: HTMLElement) => {
  if ("webkitRequestFullscreen" in el) {
    (el as any).webkitRequestFullscreen();
  } else {
    el.requestFullscreen();
  }
};
 
const exitFullscreen = () => {
  if ("webkitCancelFullScreen" in document) {
    (document as any).webkitCancelFullScreen();
  } else {
    document.exitFullscreen();
  }
};
 
const getElement = (): HTMLElement => {
  return (document as any).webkitCurrentFullScreenElement ?? document.fullscreenElement;
};
 
export interface FullscreenProps {
  onEnterFullscreen?: () => void;
  onExitFullscreen?: () => void;
}
 
export interface FullscreenHook {
  enter: typeof enterFullscreen;
  exit: typeof exitFullscreen;
  getElement: typeof getElement;
  setHandlers: (options?: FullscreenProps) => void;
}
 
export const useFullscreen = (options: FullscreenProps = {}, deps: any[]): FullscreenHook => {
  const handlers = useRef(options);
 
  useEffect(() => {
    handlers.current = options;
  }, [options, ...(deps ?? [])]);
 
  useEffect(() => {
    const onChangeFullscreen = () => {
      const fullscreenElement = getElement();
 
      if (!fullscreenElement) {
        handlers.current.onExitFullscreen?.();
      } else {
        handlers.current.onEnterFullscreen?.();
      }
    };
 
    const evt = "onwebkitfullscreenchange" in document ? "webkitfullscreenchange" : "fullscreenchange";
 
    document.addEventListener(evt, onChangeFullscreen);
 
    return () => {
      document.removeEventListener(evt, onChangeFullscreen);
    };
  }, []);
 
  return {
    getElement,
    enter: enterFullscreen,
    exit: exitFullscreen,
    setHandlers(options: FullscreenProps = {}) {
      handlers.current = options;
    },
  };
};