-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathflowplayer.tsx
More file actions
59 lines (48 loc) · 1.57 KB
/
flowplayer.tsx
File metadata and controls
59 lines (48 loc) · 1.57 KB
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
import type { ForwardedRef } from "react";
import type { Config } from "@flowplayer/player";
import React, { useEffect, forwardRef, useRef, useImperativeHandle } from "react";
import flowplayer from "@flowplayer/player";
import { trackBehaviorUsage } from "./usage";
type KeyValue = Record<string, any>;
// - Types
type Props = {
token: Config["token"],
src: Config["src"],
// allow custom plugin config
opts?: Omit<Config, "token" | "src"> & KeyValue
}
// - Components
const Flowplayer = (props: Props, receivedRef: ForwardedRef<HTMLDivElement>) => {
const { token, src, opts } = props;
const ref = useRef<HTMLDivElement | null>(null);
const playerApi = () => (ref?.current ? flowplayer(ref.current) : null);
useImperativeHandle(receivedRef, () => ref?.current as any);
// Init Flowplayer on mount
useEffect(() => {
if (typeof ref === "function") return;
if (!ref) return;
if (!ref.current) return;
if (!token) return;
const api = flowplayer(ref?.current, { token, ...opts });
trackBehaviorUsage(api, "flowplayer-component-mounted");
return () => {
api.destroy();
if (ref?.current) ref.current.innerHTML = "";
};
}, [token, ref]);
useEffect(() => {
if (!opts) return;
const api = playerApi();
api?.setOpts(opts);
}, [opts]);
useEffect(() => {
if (!src) return;
const api = playerApi();
api?.setSrc(src);
}, [src]);
return <div ref={ref} />;
};
// - Exports
Flowplayer.displayName = "Flowplayer";
export type FlowplayerProps = Props;
export default forwardRef<HTMLDivElement, Props>(Flowplayer);