Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { type DetailedHTMLProps, forwardRef, useCallback, useEffect, useRef, type VideoHTMLAttributes } from "react";
import InfoModal from "../../components/Infomodal/Infomodal";
import { patchPlayPauseMethods } from "../../utils/patchPlayPauseMethods";
 
type VirtualVideoProps = DetailedHTMLProps<VideoHTMLAttributes<HTMLVideoElement>, HTMLVideoElement> & {
  canPlayType?: (supported: boolean) => void;
  speed?: number;
};
 
const DEBUG_MODE = false;
 
// Just a mapping of file types to mime types, so we can check if the browser can play the file
// before having to fall back to using a fetch request.
const mimeTypeMapping = {
  // Supported
  mp4: "video/mp4",
  mp4v: "video/mp4",
  mpg4: "video/mp4",
 
  ogg: "video/ogg",
  ogv: "video/ogg",
  ogm: "video/ogg",
  ogx: "video/ogg",
 
  // Partially supported
  webm: "video/webm",
 
  // Unsupported
  avi: "video/avi",
  mov: "video/quicktime",
  qt: "video/quicktime",
};
 
const isBinary = (mimeType: string | null | undefined) => {
  if (!mimeType) {
    return false;
  }
 
  return mimeType.includes("octet-stream");
};
 
export const canPlayUrl = async (url: string) => {
  const video = document.createElement("video");
 
  const pathName = new URL(url, /^https?/.exec(url) ? undefined : window.location.href).pathname;
 
  const fileType = (pathName.split(".").pop() ?? "") as keyof typeof mimeTypeMapping;
 
  let fileMimeType: string | null | undefined = mimeTypeMapping[fileType];
 
  if (!fileMimeType) {
    const fileMeta = await fetch(url, {
      method: "GET",
      headers: {
        Range: "bytes=0-0",
      },
    });
 
    fileMimeType = fileMeta.headers.get("content-type");
  }
 
  // If the file is binary, we can't check if the browser can play it, so we just assume it can.
  const supported = isBinary(fileMimeType) || (!!fileMimeType && video.canPlayType(fileMimeType) !== "");
  const modalExists = document.querySelector(".ant-modal");
 
  if (!supported && !modalExists)
    InfoModal.error("There has been an error rendering your video, please check the format is supported");
  return supported;
};
 
export const VirtualVideo = forwardRef<HTMLVideoElement, VirtualVideoProps>((props, ref) => {
  const video = useRef<HTMLVideoElement | null>(null);
  const source = useRef<HTMLSourceElement | null>(null);
  const attachedEvents = useRef<[string, any][]>([]);
 
  const canPlayType = useCallback(
    async (url: string) => {
      let supported = false;
 
      if (url) {
        supported = await canPlayUrl(url);
      }
 
      if (props.canPlayType) {
        props.canPlayType(supported);
      }
      return supported;
    },
    [props.canPlayType],
  );
 
  const createVideoElement = useCallback(() => {
    const videoEl = document.createElement("video");
 
    videoEl.muted = !!props.muted;
    videoEl.controls = false;
    videoEl.preload = "auto";
    videoEl.playbackRate = props.speed ?? 1;
 
    videoEl.crossOrigin = "anonymous";
 
    Object.assign(videoEl.style, {
      top: "-9999px",
      width: 0,
      height: 0,
      position: "absolute",
    });
 
    if (DEBUG_MODE) {
      Object.assign(videoEl.style, {
        top: 0,
        zIndex: 10000,
        width: "200px",
        height: "200px",
        position: "absolute",
      });
    }
 
    video.current = videoEl;
  }, []);
 
  const attachRef = useCallback((video: HTMLVideoElement | null) => {
    if (video) video = patchPlayPauseMethods(video);
    if (ref instanceof Function) {
      ref(video);
    } else if (ref) {
      ref.current = video;
    }
  }, []);
 
  const attachEventListeners = () => {
    const eventHandlers = Object.entries(props)
      .filter(([key]) => key.startsWith("on"))
      .map(([evt, handler]) => [evt.toLowerCase(), handler]);
 
    const attached: [string, any][] = [];
 
    eventHandlers.forEach(([evt, handler]) => {
      const evtName = evt.replace(/^on/, "");
 
      video.current?.addEventListener(evtName, handler);
      attached.push([evtName, handler]);
    });
 
    attachedEvents.current = attached;
  };
 
  const detachEventListeners = () => {
    if (!video.current) return;
 
    (attachedEvents.current ?? []).forEach(([evt, handler]) => {
      video.current?.removeEventListener(evt, handler);
    });
 
    attachedEvents.current = [];
  };
 
  const unloadSource = () => {
    if (source && video) {
      video.current?.pause();
      source.current?.setAttribute("src", "");
      video.current?.load();
    }
  };
 
  const attachSource = useCallback(() => {
    if (!video.current) return;
 
    video.current?.pause();
 
    if (source.current) unloadSource();
 
    const sourceEl = document.createElement("source");
 
    sourceEl.setAttribute("src", props.src ?? "");
    video.current?.appendChild(sourceEl);
 
    source.current = sourceEl;
  }, [props.src]);
 
  useEffect(() => {
    detachEventListeners();
    attachEventListeners();
  });
 
  // Create a video tag
  useEffect(() => {
    createVideoElement();
    attachEventListeners();
    canPlayType(props.src ?? "").then((canPlay) => {
      if (canPlay && video.current) {
        attachSource();
        attachRef(video.current);
 
        document.body.append(video.current!);
      }
    });
 
    return () => {
      // Handle video cleanup
      detachEventListeners();
      unloadSource();
      attachRef(null);
      video.current?.remove();
      video.current = null;
    };
  }, []);
 
  useEffect(() => {
    if (video.current && props.muted !== undefined) {
      video.current.muted = props.muted;
    }
  }, [props.muted]);
 
  return null;
});