-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
useFullscreen.ts
69 lines (59 loc) Β· 1.94 KB
/
useFullscreen.ts
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
import {useLayoutEffect, RefObject, useState} from 'react';
import screenfull from 'screenfull';
export interface FullScreenOptions {
video?: RefObject<HTMLVideoElement>;
onClose?: (error?: Error) => void;
}
const noop = () => {};
const useFullscreen = (ref: RefObject<Element>, on: boolean, options: FullScreenOptions = {}): boolean => {
const {video, onClose = noop} = options;
const [isFullscreen, setIsFullscreen] = useState(on);
useLayoutEffect(() => {
if (!on) return;
if (!ref.current) return;
const onWebkitEndFullscreen = () => {
video!.current!.removeEventListener('webkitendfullscreen', onWebkitEndFullscreen);
onClose();
};
const onChange = () => {
if (screenfull) {
const isFullscreen = screenfull.isFullscreen;
setIsFullscreen(isFullscreen);
if (!isFullscreen) {
onClose();
}
}
};
if (screenfull && screenfull.enabled) {
try {
screenfull.request(ref.current);
setIsFullscreen(true);
} catch (error) {
onClose(error);
setIsFullscreen(false);
}
screenfull.on('change', onChange);
} else if (video && video.current && video.current.webkitEnterFullscreen) {
video.current.webkitEnterFullscreen();
video.current.addEventListener('webkitendfullscreen', onWebkitEndFullscreen);
setIsFullscreen(true);
} else {
onClose();
setIsFullscreen(false);
}
return () => {
setIsFullscreen(false);
if (screenfull && screenfull.enabled) {
try {
screenfull.off('change', onChange);
screenfull.exit();
} catch {}
} else if (video && video.current && video.current.webkitExitFullscreen) {
video.current.removeEventListener('webkitendfullscreen', onWebkitEndFullscreen);
video.current.webkitExitFullscreen();
}
}
}, [ref.current, video, on]);
return isFullscreen;
};
export default useFullscreen;