-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathUploadingContext.tsx
More file actions
76 lines (67 loc) · 1.62 KB
/
UploadingContext.tsx
File metadata and controls
76 lines (67 loc) · 1.62 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"use client";
import type React from "react";
import { createContext, useContext, useEffect, useState } from "react";
interface UploadingContextType {
uploadStatus: UploadStatus | undefined;
setUploadStatus: (state: UploadStatus | undefined) => void;
}
export type UploadStatus =
| {
status: "parsing";
}
| {
status: "creating";
}
| {
status: "converting";
capId: string;
progress: number;
}
| {
status: "uploadingThumbnail";
capId: string;
progress: number;
}
| {
status: "uploadingVideo";
capId: string;
progress: number;
thumbnailUrl: string | undefined;
};
const UploadingContext = createContext<UploadingContextType | undefined>(
undefined,
);
export function useUploadingContext() {
const context = useContext(UploadingContext);
if (!context)
throw new Error(
"useUploadingContext must be used within an UploadingProvider",
);
return context;
}
export function UploadingProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState<UploadStatus>();
// Prevent the user closing the tab while uploading
useEffect(() => {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
if (state?.status) {
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = "";
return "";
}
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [state]);
return (
<UploadingContext.Provider
value={{
uploadStatus: state,
setUploadStatus: setState,
}}
>
{children}
</UploadingContext.Provider>
);
}