MCPcopy Create free account
hub / github.com/streamich/react-use / createHTMLMediaHook

Function createHTMLMediaHook

src/factory/createHTMLMediaHook.ts:33–242  ·  view source on GitHub ↗
(
  tag: 'audio' | 'video'
)

Source from the content-addressed store, hash-verified

31type MediaPropsWithRef<T> = HTMLMediaProps & { ref?: React.MutableRefObject<T | null> };
32
33export default function createHTMLMediaHook<T extends HTMLAudioElement | HTMLVideoElement>(
34 tag: 'audio' | 'video'
35) {
36 return (elOrProps: HTMLMediaProps | React.ReactElement<HTMLMediaProps>) => {
37 let element: React.ReactElement<MediaPropsWithRef<T>> | undefined;
38 let props: MediaPropsWithRef<T>;
39
40 if (React.isValidElement(elOrProps)) {
41 element = elOrProps;
42 props = element.props;
43 } else {
44 props = elOrProps;
45 }
46
47 const [state, setState] = useSetState<HTMLMediaState>({
48 buffered: [],
49 time: 0,
50 duration: 0,
51 paused: true,
52 muted: false,
53 volume: 1,
54 playing: false,
55 });
56 const ref = useRef<T | null>(null);
57
58 const wrapEvent = (userEvent, proxyEvent?) => {
59 return (event) => {
60 try {
61 proxyEvent && proxyEvent(event);
62 } finally {
63 userEvent && userEvent(event);
64 }
65 };
66 };
67
68 const onPlay = () => setState({ paused: false });
69 const onPlaying = () => setState({ playing: true });
70 const onWaiting = () => setState({ playing: false });
71 const onPause = () => setState({ paused: true, playing: false });
72 const onVolumeChange = () => {
73 const el = ref.current;
74 if (!el) {
75 return;
76 }
77 setState({
78 muted: el.muted,
79 volume: el.volume,
80 });
81 };
82 const onDurationChange = () => {
83 const el = ref.current;
84 if (!el) {
85 return;
86 }
87 const { duration, buffered } = el;
88 setState({
89 duration,
90 buffered: parseTimeRanges(buffered),

Callers 2

useAudio.tsFile · 0.85
useVideo.tsFile · 0.85

Calls 3

useSetStateFunction · 0.85
wrapEventFunction · 0.85
setStateFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…