@behindthemusictree/app-kit 0.0.0-stage → 24.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/dist/app-error-B8IoFBhD.d.ts +45 -0
- package/dist/app-error-codes-D5eYg7xR.d.ts +49 -0
- package/dist/auth/index.cjs +479 -0
- package/dist/auth/index.cjs.map +1 -0
- package/dist/auth/index.d.ts +83 -0
- package/dist/auth/index.js +36 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/chunk-4MEK3CNF.js +246 -0
- package/dist/chunk-4MEK3CNF.js.map +1 -0
- package/dist/chunk-5NTNMBJP.js +25 -0
- package/dist/chunk-5NTNMBJP.js.map +1 -0
- package/dist/chunk-5YLNSX34.js +211 -0
- package/dist/chunk-5YLNSX34.js.map +1 -0
- package/dist/chunk-7EOS2K24.js +267 -0
- package/dist/chunk-7EOS2K24.js.map +1 -0
- package/dist/chunk-FYOLIMWU.js +25 -0
- package/dist/chunk-FYOLIMWU.js.map +1 -0
- package/dist/chunk-JMFEWI53.js +10 -0
- package/dist/chunk-JMFEWI53.js.map +1 -0
- package/dist/chunk-OGTDTTHJ.js +244 -0
- package/dist/chunk-OGTDTTHJ.js.map +1 -0
- package/dist/chunk-OIZPAN6I.js +356 -0
- package/dist/chunk-OIZPAN6I.js.map +1 -0
- package/dist/chunk-T5D5T52J.js +271 -0
- package/dist/chunk-T5D5T52J.js.map +1 -0
- package/dist/chunk-TCXWV62L.js +1 -0
- package/dist/chunk-TCXWV62L.js.map +1 -0
- package/dist/chunk-Y52MKNHR.js +1461 -0
- package/dist/chunk-Y52MKNHR.js.map +1 -0
- package/dist/genre-tree/index.cjs +2133 -0
- package/dist/genre-tree/index.cjs.map +1 -0
- package/dist/genre-tree/index.d.ts +3031 -0
- package/dist/genre-tree/index.js +179 -0
- package/dist/genre-tree/index.js.map +1 -0
- package/dist/genre-tree/testing.cjs +55 -0
- package/dist/genre-tree/testing.cjs.map +1 -0
- package/dist/genre-tree/testing.d.ts +7 -0
- package/dist/genre-tree/testing.js +27 -0
- package/dist/genre-tree/testing.js.map +1 -0
- package/dist/ids-D8XCErUS.d.ts +8 -0
- package/dist/index.cjs +3194 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +308 -0
- package/dist/index.js.map +1 -0
- package/dist/player/index.cjs +388 -0
- package/dist/player/index.cjs.map +1 -0
- package/dist/player/index.d.ts +108 -0
- package/dist/player/index.js +20 -0
- package/dist/player/index.js.map +1 -0
- package/dist/popup/index.cjs +403 -0
- package/dist/popup/index.cjs.map +1 -0
- package/dist/popup/index.d.ts +80 -0
- package/dist/popup/index.js +16 -0
- package/dist/popup/index.js.map +1 -0
- package/dist/scope-BoMVOHmz.d.ts +4 -0
- package/dist/track-noun/index.cjs +53 -0
- package/dist/track-noun/index.cjs.map +1 -0
- package/dist/track-noun/index.d.ts +15 -0
- package/dist/track-noun/index.js +11 -0
- package/dist/track-noun/index.js.map +1 -0
- package/dist/transport/index.cjs +773 -0
- package/dist/transport/index.cjs.map +1 -0
- package/dist/transport/index.d.ts +203 -0
- package/dist/transport/index.js +69 -0
- package/dist/transport/index.js.map +1 -0
- package/package.json +97 -4
- package/README.md +0 -3
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AuthRequired,
|
|
3
|
+
BackendError,
|
|
4
|
+
BadRequestError,
|
|
5
|
+
ClientError,
|
|
6
|
+
InvalidInputError,
|
|
7
|
+
NetworkError,
|
|
8
|
+
ServiceError,
|
|
9
|
+
useConnectivityError
|
|
10
|
+
} from "./chunk-4MEK3CNF.js";
|
|
11
|
+
|
|
12
|
+
// src/popup/PopupContext.tsx
|
|
13
|
+
import { createContext, useContext, useState, useCallback, useMemo } from "react";
|
|
14
|
+
import { jsx } from "react/jsx-runtime";
|
|
15
|
+
var AUTH_POPUP_TYPE = "auth";
|
|
16
|
+
var PopupContext = createContext(void 0);
|
|
17
|
+
function PopupProvider({ children }) {
|
|
18
|
+
const [state, setState] = useState({ content: null, type: null });
|
|
19
|
+
const activePopup = state.content;
|
|
20
|
+
const showPopup = useCallback((popup, type) => {
|
|
21
|
+
setState({ content: popup, type: type ?? null });
|
|
22
|
+
}, []);
|
|
23
|
+
const hidePopup = useCallback((options) => {
|
|
24
|
+
if (options?.onlyIfType !== void 0) {
|
|
25
|
+
setState((prev) => prev.type === options.onlyIfType ? { content: null, type: null } : prev);
|
|
26
|
+
} else {
|
|
27
|
+
setState({ content: null, type: null });
|
|
28
|
+
}
|
|
29
|
+
}, []);
|
|
30
|
+
const value = useMemo(() => ({ showPopup, hidePopup, activePopup }), [showPopup, hidePopup, activePopup]);
|
|
31
|
+
return /* @__PURE__ */ jsx(PopupContext.Provider, { value, children });
|
|
32
|
+
}
|
|
33
|
+
function usePopup() {
|
|
34
|
+
const context = useContext(PopupContext);
|
|
35
|
+
if (context === void 0) {
|
|
36
|
+
throw new Error("usePopup must be used within a PopupProvider");
|
|
37
|
+
}
|
|
38
|
+
return context;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// src/popup/useConnectivityErrorPopup.ts
|
|
42
|
+
import { useEffect, useRef } from "react";
|
|
43
|
+
var ALWAYS_REDISPLAY_ON_REPEAT = [NetworkError, BackendError, ClientError, ServiceError, InvalidInputError];
|
|
44
|
+
function useConnectivityErrorPopup({
|
|
45
|
+
isAccountPage,
|
|
46
|
+
routeRequiresAuth,
|
|
47
|
+
routeRequiresSpotify,
|
|
48
|
+
renderers
|
|
49
|
+
}) {
|
|
50
|
+
const { showPopup, hidePopup } = usePopup();
|
|
51
|
+
const { connectivityError, clearConnectivityError } = useConnectivityError();
|
|
52
|
+
const currentConnectivityErrorRef = useRef(null);
|
|
53
|
+
const renderersRef = useRef(renderers);
|
|
54
|
+
renderersRef.current = renderers;
|
|
55
|
+
useEffect(() => {
|
|
56
|
+
if (connectivityError === null) {
|
|
57
|
+
if (currentConnectivityErrorRef.current !== null) {
|
|
58
|
+
currentConnectivityErrorRef.current = null;
|
|
59
|
+
hidePopup();
|
|
60
|
+
}
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const error = connectivityError;
|
|
64
|
+
const isSpotifyAllowlistOrAuthError = error instanceof BackendError && ["BAC4012" /* BACKEND_SPOTIFY_USER_NOT_IN_ALLOWLIST */, "BAC4013" /* BACKEND_SPOTIFY_AUTHENTICATION_ERROR */].includes(
|
|
65
|
+
error.code
|
|
66
|
+
);
|
|
67
|
+
if (isSpotifyAllowlistOrAuthError && !routeRequiresSpotify) {
|
|
68
|
+
hidePopup();
|
|
69
|
+
clearConnectivityError();
|
|
70
|
+
currentConnectivityErrorRef.current = null;
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (currentConnectivityErrorRef.current == null || !ALWAYS_REDISPLAY_ON_REPEAT.includes(currentConnectivityErrorRef.current) && !(connectivityError instanceof currentConnectivityErrorRef.current)) {
|
|
74
|
+
const renderer = renderersRef.current;
|
|
75
|
+
let popup = null;
|
|
76
|
+
let popupType = null;
|
|
77
|
+
if (!isAccountPage && routeRequiresAuth && error instanceof AuthRequired) {
|
|
78
|
+
popup = renderer.renderAuthPopup();
|
|
79
|
+
popupType = AUTH_POPUP_TYPE;
|
|
80
|
+
} else if (!isAccountPage && routeRequiresSpotify && error instanceof BackendError && error.code === "BAC4031" /* BACKEND_SPOTIFY_AUTHORIZATION_REQUIRED */) {
|
|
81
|
+
popup = renderer.renderSpotifyOnlyAuthPopup();
|
|
82
|
+
popupType = AUTH_POPUP_TYPE;
|
|
83
|
+
} else if (error instanceof InvalidInputError) {
|
|
84
|
+
console.error("[InvalidInputError]", error.code, error.json);
|
|
85
|
+
popup = renderer.renderInternalErrorPopup(error.code);
|
|
86
|
+
} else if (routeRequiresSpotify && error instanceof BackendError && ["BAC4012" /* BACKEND_SPOTIFY_USER_NOT_IN_ALLOWLIST */, "BAC4013" /* BACKEND_SPOTIFY_AUTHENTICATION_ERROR */].includes(
|
|
87
|
+
error.code
|
|
88
|
+
)) {
|
|
89
|
+
popup = renderer.renderSpotifyAuthErrorPopup({
|
|
90
|
+
message: error.message,
|
|
91
|
+
errorCode: error.code,
|
|
92
|
+
onClose: () => hidePopup()
|
|
93
|
+
});
|
|
94
|
+
} else if (error instanceof BackendError && [
|
|
95
|
+
"BAC4014" /* BACKEND_GOOGLE_AUTHENTICATION_ERROR */,
|
|
96
|
+
"BAC4015" /* BACKEND_GOOGLE_OAUTH_MISCONFIGURED */,
|
|
97
|
+
"BAC4011" /* BACKEND_GOOGLE_OAUTH_CODE_INVALID_OR_EXPIRED */
|
|
98
|
+
].includes(error.code)) {
|
|
99
|
+
popup = renderer.renderGoogleAuthErrorPopup({ message: error.message, onClose: () => hidePopup() });
|
|
100
|
+
} else if (error instanceof BadRequestError || error instanceof BackendError || error instanceof ServiceError || error instanceof AuthRequired) {
|
|
101
|
+
popup = renderer.renderInternalErrorPopup(error.code);
|
|
102
|
+
} else if (error instanceof NetworkError) {
|
|
103
|
+
popup = renderer.renderNetworkErrorPopup();
|
|
104
|
+
}
|
|
105
|
+
if (popup) {
|
|
106
|
+
showPopup(popup, popupType);
|
|
107
|
+
}
|
|
108
|
+
currentConnectivityErrorRef.current = error.constructor;
|
|
109
|
+
}
|
|
110
|
+
}, [
|
|
111
|
+
connectivityError,
|
|
112
|
+
showPopup,
|
|
113
|
+
hidePopup,
|
|
114
|
+
clearConnectivityError,
|
|
115
|
+
isAccountPage,
|
|
116
|
+
routeRequiresAuth,
|
|
117
|
+
routeRequiresSpotify
|
|
118
|
+
]);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// src/popup/useTrackUpload.ts
|
|
122
|
+
import { useState as useState2, useEffect as useEffect2, useCallback as useCallback2, useRef as useRef2 } from "react";
|
|
123
|
+
function useTrackUpload({
|
|
124
|
+
files,
|
|
125
|
+
genre,
|
|
126
|
+
onProcessFile,
|
|
127
|
+
onComplete,
|
|
128
|
+
uploadTimeoutMs
|
|
129
|
+
}) {
|
|
130
|
+
const [items, setItems] = useState2([]);
|
|
131
|
+
const [currentUploadIndex, setCurrentUploadIndex] = useState2(0);
|
|
132
|
+
const [isUploading, setIsUploading] = useState2(false);
|
|
133
|
+
const [allComplete, setAllComplete] = useState2(false);
|
|
134
|
+
const lastFilesKeyRef = useRef2(null);
|
|
135
|
+
const progressIntervalRef = useRef2(null);
|
|
136
|
+
const runRef = useRef2(0);
|
|
137
|
+
const completedRunRef = useRef2(null);
|
|
138
|
+
useEffect2(() => {
|
|
139
|
+
const filesKey = `${files.length}-${files.map((f) => `${f.name}:${f.size}`).join("|")}-${genre ?? ""}`;
|
|
140
|
+
if (lastFilesKeyRef.current === filesKey) return;
|
|
141
|
+
lastFilesKeyRef.current = filesKey;
|
|
142
|
+
runRef.current += 1;
|
|
143
|
+
if (progressIntervalRef.current) {
|
|
144
|
+
clearInterval(progressIntervalRef.current);
|
|
145
|
+
progressIntervalRef.current = null;
|
|
146
|
+
}
|
|
147
|
+
setItems(
|
|
148
|
+
files.map((file, index) => ({
|
|
149
|
+
id: `upload-${index}-${file.name}`,
|
|
150
|
+
file,
|
|
151
|
+
genre: genre ?? null,
|
|
152
|
+
status: "pending",
|
|
153
|
+
progress: 0
|
|
154
|
+
}))
|
|
155
|
+
);
|
|
156
|
+
setCurrentUploadIndex(0);
|
|
157
|
+
setIsUploading(false);
|
|
158
|
+
setAllComplete(false);
|
|
159
|
+
}, [files, genre]);
|
|
160
|
+
const startNextUpload = useCallback2(() => {
|
|
161
|
+
const currentItem = items[currentUploadIndex];
|
|
162
|
+
setIsUploading(true);
|
|
163
|
+
setItems(
|
|
164
|
+
(prev) => prev.map((item, index) => index === currentUploadIndex ? { ...item, status: "uploading", progress: 0 } : item)
|
|
165
|
+
);
|
|
166
|
+
if (progressIntervalRef.current) clearInterval(progressIntervalRef.current);
|
|
167
|
+
progressIntervalRef.current = setInterval(() => {
|
|
168
|
+
setItems(
|
|
169
|
+
(prev) => prev.map(
|
|
170
|
+
(item, index) => index === currentUploadIndex && item.status === "uploading" ? { ...item, progress: Math.min(item.progress + Math.random() * 8, 99) } : item
|
|
171
|
+
)
|
|
172
|
+
);
|
|
173
|
+
}, 800);
|
|
174
|
+
const uploadingIndex = currentUploadIndex;
|
|
175
|
+
const run = runRef.current;
|
|
176
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
177
|
+
setTimeout(() => reject(new Error("Upload timed out. The server took too long to respond.")), uploadTimeoutMs);
|
|
178
|
+
});
|
|
179
|
+
Promise.race([onProcessFile(currentItem.file, currentItem.genre), timeoutPromise]).then((data) => {
|
|
180
|
+
if (run !== runRef.current) return;
|
|
181
|
+
if (progressIntervalRef.current) {
|
|
182
|
+
clearInterval(progressIntervalRef.current);
|
|
183
|
+
progressIntervalRef.current = null;
|
|
184
|
+
}
|
|
185
|
+
setItems(
|
|
186
|
+
(prev) => prev.map(
|
|
187
|
+
(item, index) => index === uploadingIndex ? { ...item, status: "success", progress: 100, uploadedTrack: data } : item
|
|
188
|
+
)
|
|
189
|
+
);
|
|
190
|
+
setIsUploading(false);
|
|
191
|
+
setCurrentUploadIndex((prev) => prev + 1);
|
|
192
|
+
}).catch((error) => {
|
|
193
|
+
if (run !== runRef.current) return;
|
|
194
|
+
if (progressIntervalRef.current) {
|
|
195
|
+
clearInterval(progressIntervalRef.current);
|
|
196
|
+
progressIntervalRef.current = null;
|
|
197
|
+
}
|
|
198
|
+
setItems(
|
|
199
|
+
(prev) => prev.map((item, index) => index === uploadingIndex ? { ...item, status: "error", error } : item)
|
|
200
|
+
);
|
|
201
|
+
setIsUploading(false);
|
|
202
|
+
setCurrentUploadIndex((prev) => prev + 1);
|
|
203
|
+
});
|
|
204
|
+
}, [items, currentUploadIndex, onProcessFile, uploadTimeoutMs]);
|
|
205
|
+
useEffect2(() => {
|
|
206
|
+
return () => {
|
|
207
|
+
if (progressIntervalRef.current) {
|
|
208
|
+
clearInterval(progressIntervalRef.current);
|
|
209
|
+
progressIntervalRef.current = null;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
}, []);
|
|
213
|
+
useEffect2(() => {
|
|
214
|
+
const shouldStart = items.length > 0 && !isUploading && currentUploadIndex < items.length;
|
|
215
|
+
if (shouldStart) {
|
|
216
|
+
startNextUpload();
|
|
217
|
+
}
|
|
218
|
+
}, [items, currentUploadIndex, isUploading, startNextUpload]);
|
|
219
|
+
useEffect2(() => {
|
|
220
|
+
if (items.length > 0 && currentUploadIndex >= items.length && !isUploading) {
|
|
221
|
+
if (completedRunRef.current === runRef.current) return;
|
|
222
|
+
completedRunRef.current = runRef.current;
|
|
223
|
+
setAllComplete(true);
|
|
224
|
+
const successfulTracks = items.filter((item) => item.status === "success" && item.uploadedTrack).map((item) => item.uploadedTrack);
|
|
225
|
+
onComplete?.(successfulTracks);
|
|
226
|
+
}
|
|
227
|
+
}, [items, currentUploadIndex, isUploading, onComplete]);
|
|
228
|
+
return {
|
|
229
|
+
items,
|
|
230
|
+
isUploading,
|
|
231
|
+
allComplete,
|
|
232
|
+
successfulCount: items.filter((item) => item.status === "success").length,
|
|
233
|
+
errorCount: items.filter((item) => item.status === "error").length
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export {
|
|
238
|
+
AUTH_POPUP_TYPE,
|
|
239
|
+
PopupProvider,
|
|
240
|
+
usePopup,
|
|
241
|
+
useConnectivityErrorPopup,
|
|
242
|
+
useTrackUpload
|
|
243
|
+
};
|
|
244
|
+
//# sourceMappingURL=chunk-OGTDTTHJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/popup/PopupContext.tsx","../src/popup/useConnectivityErrorPopup.ts","../src/popup/useTrackUpload.ts"],"sourcesContent":["\"use client\";\n\nimport { createContext, useContext, useState, useCallback, useMemo, ReactNode } from \"react\";\n\nexport const AUTH_POPUP_TYPE = \"auth\";\n\ninterface PopupState {\n content: ReactNode;\n type: string | null;\n}\n\ninterface HidePopupOptions {\n onlyIfType?: string;\n}\n\ninterface PopupContextType {\n showPopup: (popup: ReactNode, type?: string | null) => void;\n hidePopup: (options?: HidePopupOptions) => void;\n activePopup: ReactNode | null;\n}\n\nconst PopupContext = createContext<PopupContextType | undefined>(undefined);\n\ninterface PopupProviderProps {\n children: ReactNode;\n}\n\nexport function PopupProvider({ children }: PopupProviderProps) {\n const [state, setState] = useState<PopupState>({ content: null, type: null });\n const activePopup = state.content;\n\n const showPopup = useCallback((popup: ReactNode, type?: string | null) => {\n setState({ content: popup, type: type ?? null });\n }, []);\n\n const hidePopup = useCallback((options?: HidePopupOptions) => {\n if (options?.onlyIfType !== undefined) {\n setState((prev) => (prev.type === options.onlyIfType ? { content: null, type: null } : prev));\n } else {\n setState({ content: null, type: null });\n }\n }, []);\n\n const value = useMemo(() => ({ showPopup, hidePopup, activePopup }), [showPopup, hidePopup, activePopup]);\n\n return <PopupContext.Provider value={value}>{children}</PopupContext.Provider>;\n}\n\nexport function usePopup() {\n const context = useContext(PopupContext);\n if (context === undefined) {\n throw new Error(\"usePopup must be used within a PopupProvider\");\n }\n return context;\n}\n","\"use client\";\n\nimport { ReactNode, useEffect, useRef } from \"react\";\nimport {\n AuthRequired,\n BackendError,\n BadRequestError,\n ClientError,\n ConnectivityError,\n InvalidInputError,\n NetworkError,\n ServiceError,\n} from \"../transport/app-errors/app-error\";\nimport { ErrorCode } from \"../transport/app-errors/app-error-codes\";\nimport { useConnectivityError } from \"../transport/connectivity-error-context\";\nimport { AUTH_POPUP_TYPE, usePopup } from \"./PopupContext\";\n\nexport interface ConnectivityErrorPopupRenderers {\n renderAuthPopup: () => ReactNode;\n renderSpotifyOnlyAuthPopup: () => ReactNode;\n renderInternalErrorPopup: (errorCode: ErrorCode) => ReactNode;\n renderSpotifyAuthErrorPopup: (params: { message: string; errorCode: ErrorCode; onClose: () => void }) => ReactNode;\n renderGoogleAuthErrorPopup: (params: { message: string; onClose: () => void }) => ReactNode;\n renderNetworkErrorPopup: () => ReactNode;\n}\n\nexport interface UseConnectivityErrorPopupOptions {\n isAccountPage: boolean;\n routeRequiresAuth: boolean;\n routeRequiresSpotify: boolean;\n renderers: ConnectivityErrorPopupRenderers;\n}\n\nconst ALWAYS_REDISPLAY_ON_REPEAT = [NetworkError, BackendError, ClientError, ServiceError, InvalidInputError];\n\n/**\n * Classifies the shared connectivity-error state into the right popup and shows it. Consuming apps\n * supply the actual popup components via `renderers` since those are app-branded; this hook owns\n * only the error -> popup-kind decision, so a fix here (e.g. a route not requiring auth still\n * surfacing an unexpected AuthRequired) applies to every app instead of needing a per-app patch.\n */\nexport function useConnectivityErrorPopup({\n isAccountPage,\n routeRequiresAuth,\n routeRequiresSpotify,\n renderers,\n}: UseConnectivityErrorPopupOptions): void {\n const { showPopup, hidePopup } = usePopup();\n const { connectivityError, clearConnectivityError } = useConnectivityError();\n const currentConnectivityErrorRef = useRef<typeof ConnectivityError | null>(null);\n const renderersRef = useRef(renderers);\n renderersRef.current = renderers;\n\n useEffect(() => {\n if (connectivityError === null) {\n if (currentConnectivityErrorRef.current !== null) {\n currentConnectivityErrorRef.current = null;\n hidePopup();\n }\n return;\n }\n\n const error = connectivityError;\n const isSpotifyAllowlistOrAuthError =\n error instanceof BackendError &&\n [ErrorCode.BACKEND_SPOTIFY_USER_NOT_IN_ALLOWLIST, ErrorCode.BACKEND_SPOTIFY_AUTHENTICATION_ERROR].includes(\n error.code,\n );\n\n if (isSpotifyAllowlistOrAuthError && !routeRequiresSpotify) {\n hidePopup();\n clearConnectivityError();\n currentConnectivityErrorRef.current = null;\n return;\n }\n\n if (\n currentConnectivityErrorRef.current == null ||\n (!ALWAYS_REDISPLAY_ON_REPEAT.includes(currentConnectivityErrorRef.current) &&\n !(connectivityError instanceof currentConnectivityErrorRef.current))\n ) {\n const renderer = renderersRef.current;\n let popup: ReactNode | null = null;\n let popupType: string | null = null;\n\n if (!isAccountPage && routeRequiresAuth && error instanceof AuthRequired) {\n popup = renderer.renderAuthPopup();\n popupType = AUTH_POPUP_TYPE;\n } else if (\n !isAccountPage &&\n routeRequiresSpotify &&\n error instanceof BackendError &&\n error.code === ErrorCode.BACKEND_SPOTIFY_AUTHORIZATION_REQUIRED\n ) {\n popup = renderer.renderSpotifyOnlyAuthPopup();\n popupType = AUTH_POPUP_TYPE;\n } else if (error instanceof InvalidInputError) {\n console.error(\"[InvalidInputError]\", error.code, error.json);\n popup = renderer.renderInternalErrorPopup(error.code);\n } else if (\n routeRequiresSpotify &&\n error instanceof BackendError &&\n [ErrorCode.BACKEND_SPOTIFY_USER_NOT_IN_ALLOWLIST, ErrorCode.BACKEND_SPOTIFY_AUTHENTICATION_ERROR].includes(\n error.code,\n )\n ) {\n popup = renderer.renderSpotifyAuthErrorPopup({\n message: error.message,\n errorCode: error.code,\n onClose: () => hidePopup(),\n });\n } else if (\n error instanceof BackendError &&\n [\n ErrorCode.BACKEND_GOOGLE_AUTHENTICATION_ERROR,\n ErrorCode.BACKEND_GOOGLE_OAUTH_MISCONFIGURED,\n ErrorCode.BACKEND_GOOGLE_OAUTH_CODE_INVALID_OR_EXPIRED,\n ].includes(error.code)\n ) {\n popup = renderer.renderGoogleAuthErrorPopup({ message: error.message, onClose: () => hidePopup() });\n } else if (\n error instanceof BadRequestError ||\n error instanceof BackendError ||\n error instanceof ServiceError ||\n error instanceof AuthRequired\n ) {\n // AuthRequired reaches here when the route doesn't require a session (e.g. a public\n // reference page) or is the account page, so the AuthPopup branch above didn't fire —\n // an unexpected 401 on those routes still needs to surface, not be dropped silently.\n popup = renderer.renderInternalErrorPopup(error.code);\n } else if (error instanceof NetworkError) {\n popup = renderer.renderNetworkErrorPopup();\n }\n\n if (popup) {\n showPopup(popup, popupType);\n }\n\n currentConnectivityErrorRef.current = error.constructor as typeof ConnectivityError;\n }\n }, [\n connectivityError,\n showPopup,\n hidePopup,\n clearConnectivityError,\n isAccountPage,\n routeRequiresAuth,\n routeRequiresSpotify,\n ]);\n}\n","\"use client\";\n\nimport { useState, useEffect, useCallback, useRef } from \"react\";\n\nexport type UploadStatus = \"pending\" | \"uploading\" | \"success\" | \"error\";\n\nexport type TrackUploadItem = {\n id: string;\n file: File;\n genre: string | null;\n status: UploadStatus;\n progress: number;\n error?: Error | null;\n uploadedTrack?: unknown;\n};\n\nexport interface UseTrackUploadOptions {\n files: File[];\n genre?: string | null;\n onProcessFile: (file: File, genre?: string | null) => Promise<unknown>;\n onComplete?: (uploadedTracks: unknown[]) => void;\n /**\n * Timeout (ms) before an in-flight upload is treated as failed. Passed by the consuming app\n * (from whatever env var / config it uses) so this package doesn't assume a specific env var name.\n */\n uploadTimeoutMs: number;\n}\n\nexport interface UseTrackUploadResult {\n items: TrackUploadItem[];\n isUploading: boolean;\n allComplete: boolean;\n successfulCount: number;\n errorCount: number;\n}\n\n/** Uploads `files` one after the other through `onProcessFile`, restarting whenever the file list or genre changes. */\nexport function useTrackUpload({\n files,\n genre,\n onProcessFile,\n onComplete,\n uploadTimeoutMs,\n}: UseTrackUploadOptions): UseTrackUploadResult {\n const [items, setItems] = useState<TrackUploadItem[]>([]);\n const [currentUploadIndex, setCurrentUploadIndex] = useState(0);\n const [isUploading, setIsUploading] = useState(false);\n const [allComplete, setAllComplete] = useState(false);\n\n const lastFilesKeyRef = useRef<string | null>(null);\n const progressIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);\n const runRef = useRef(0);\n const completedRunRef = useRef<number | null>(null);\n\n useEffect(() => {\n const filesKey = `${files.length}-${files.map((f) => `${f.name}:${f.size}`).join(\"|\")}-${genre ?? \"\"}`;\n if (lastFilesKeyRef.current === filesKey) return;\n lastFilesKeyRef.current = filesKey;\n runRef.current += 1;\n if (progressIntervalRef.current) {\n clearInterval(progressIntervalRef.current);\n progressIntervalRef.current = null;\n }\n\n setItems(\n files.map((file, index) => ({\n id: `upload-${index}-${file.name}`,\n file,\n genre: genre ?? null,\n status: \"pending\" as UploadStatus,\n progress: 0,\n })),\n );\n setCurrentUploadIndex(0);\n setIsUploading(false);\n setAllComplete(false);\n }, [files, genre]);\n\n const startNextUpload = useCallback(() => {\n const currentItem = items[currentUploadIndex];\n setIsUploading(true);\n\n setItems((prev) =>\n prev.map((item, index) => (index === currentUploadIndex ? { ...item, status: \"uploading\", progress: 0 } : item)),\n );\n\n if (progressIntervalRef.current) clearInterval(progressIntervalRef.current);\n progressIntervalRef.current = setInterval(() => {\n setItems((prev) =>\n prev.map((item, index) =>\n index === currentUploadIndex && item.status === \"uploading\"\n ? { ...item, progress: Math.min(item.progress + Math.random() * 8, 99) }\n : item,\n ),\n );\n }, 800);\n\n const uploadingIndex = currentUploadIndex;\n const run = runRef.current;\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => reject(new Error(\"Upload timed out. The server took too long to respond.\")), uploadTimeoutMs);\n });\n\n Promise.race([onProcessFile(currentItem.file, currentItem.genre), timeoutPromise])\n .then((data) => {\n if (run !== runRef.current) return;\n if (progressIntervalRef.current) {\n clearInterval(progressIntervalRef.current);\n progressIntervalRef.current = null;\n }\n setItems((prev) =>\n prev.map((item, index) =>\n index === uploadingIndex ? { ...item, status: \"success\", progress: 100, uploadedTrack: data } : item,\n ),\n );\n setIsUploading(false);\n setCurrentUploadIndex((prev) => prev + 1);\n })\n .catch((error) => {\n if (run !== runRef.current) return;\n if (progressIntervalRef.current) {\n clearInterval(progressIntervalRef.current);\n progressIntervalRef.current = null;\n }\n setItems((prev) =>\n prev.map((item, index) => (index === uploadingIndex ? { ...item, status: \"error\", error } : item)),\n );\n setIsUploading(false);\n setCurrentUploadIndex((prev) => prev + 1);\n });\n }, [items, currentUploadIndex, onProcessFile, uploadTimeoutMs]);\n\n useEffect(() => {\n return () => {\n if (progressIntervalRef.current) {\n clearInterval(progressIntervalRef.current);\n progressIntervalRef.current = null;\n }\n };\n }, []);\n\n useEffect(() => {\n const shouldStart = items.length > 0 && !isUploading && currentUploadIndex < items.length;\n if (shouldStart) {\n startNextUpload();\n }\n }, [items, currentUploadIndex, isUploading, startNextUpload]);\n\n useEffect(() => {\n if (items.length > 0 && currentUploadIndex >= items.length && !isUploading) {\n // React may re-run queued updaters, handing back an equal-but-new items after completion\n if (completedRunRef.current === runRef.current) return;\n completedRunRef.current = runRef.current;\n setAllComplete(true);\n const successfulTracks = items\n .filter((item) => item.status === \"success\" && item.uploadedTrack)\n .map((item) => item.uploadedTrack);\n onComplete?.(successfulTracks);\n }\n }, [items, currentUploadIndex, isUploading, onComplete]);\n\n return {\n items,\n isUploading,\n allComplete,\n successfulCount: items.filter((item) => item.status === \"success\").length,\n errorCount: items.filter((item) => item.status === \"error\").length,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAEA,SAAS,eAAe,YAAY,UAAU,aAAa,eAA0B;AA2C5E;AAzCF,IAAM,kBAAkB;AAiB/B,IAAM,eAAe,cAA4C,MAAS;AAMnE,SAAS,cAAc,EAAE,SAAS,GAAuB;AAC9D,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAqB,EAAE,SAAS,MAAM,MAAM,KAAK,CAAC;AAC5E,QAAM,cAAc,MAAM;AAE1B,QAAM,YAAY,YAAY,CAAC,OAAkB,SAAyB;AACxE,aAAS,EAAE,SAAS,OAAO,MAAM,QAAQ,KAAK,CAAC;AAAA,EACjD,GAAG,CAAC,CAAC;AAEL,QAAM,YAAY,YAAY,CAAC,YAA+B;AAC5D,QAAI,SAAS,eAAe,QAAW;AACrC,eAAS,CAAC,SAAU,KAAK,SAAS,QAAQ,aAAa,EAAE,SAAS,MAAM,MAAM,KAAK,IAAI,IAAK;AAAA,IAC9F,OAAO;AACL,eAAS,EAAE,SAAS,MAAM,MAAM,KAAK,CAAC;AAAA,IACxC;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,QAAM,QAAQ,QAAQ,OAAO,EAAE,WAAW,WAAW,YAAY,IAAI,CAAC,WAAW,WAAW,WAAW,CAAC;AAExG,SAAO,oBAAC,aAAa,UAAb,EAAsB,OAAe,UAAS;AACxD;AAEO,SAAS,WAAW;AACzB,QAAM,UAAU,WAAW,YAAY;AACvC,MAAI,YAAY,QAAW;AACzB,U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AM;AACd,UAAM,cAAc,MAAM,SAAS,KAAK,CAAC,eAAe,qBAAqB,MAAM;AACnF,QAAI,aAAa;AACf,sBAAgB;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,OAAO,oBAAoB,aAAa,eAAe,CAAC;AAE5D,EAAAA,WAAU,MAAM;AACd,QAAI,MAAM,SAAS,KAAK,sBAAsB,MAAM,UAAU,CAAC,aAAa;AAE1E,UAAI,gBAAgB,YAAY,OAAO,QAAS;AAChD,sBAAgB,UAAU,OAAO;AACjC,qBAAe,IAAI;AACnB,YAAM,mBAAmB,MACtB,OAAO,CAAC,SAAS,KAAK,WAAW,aAAa,KAAK,aAAa,EAChE,IAAI,CAAC,SAAS,KAAK,aAAa;AACnC,mBAAa,gBAAgB;AAAA,IAC/B;AAAA,EACF,GAAG,CAAC,OAAO,oBAAoB,aAAa,UAAU,CAAC;AAEvD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,iBAAiB,MAAM,OAAO,CAAC,SAAS,KAAK,WAAW,SAAS,EAAE;AAAA,IACnE,YAAY,MAAM,OAAO,CAAC,SAAS,KAAK,WAAW,OAAO,EAAE;AAAA,EAC9D;AACF;","names":["useState","useEffect","useCallback","useRef"]}
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
// src/player/PlayStates.ts
|
|
2
|
+
var PlayStates = /* @__PURE__ */ ((PlayStates2) => {
|
|
3
|
+
PlayStates2["PLAYING"] = "PLAYING";
|
|
4
|
+
PlayStates2["PAUSED"] = "PAUSED";
|
|
5
|
+
PlayStates2["STOPPED"] = "STOPPED";
|
|
6
|
+
PlayStates2["LOADING"] = "LOADING";
|
|
7
|
+
return PlayStates2;
|
|
8
|
+
})(PlayStates || {});
|
|
9
|
+
|
|
10
|
+
// src/player/MediaController.ts
|
|
11
|
+
var AudioMediaController = class {
|
|
12
|
+
constructor(audio) {
|
|
13
|
+
this.audio = audio;
|
|
14
|
+
}
|
|
15
|
+
audio;
|
|
16
|
+
getCurrentTime() {
|
|
17
|
+
return this.audio.currentTime;
|
|
18
|
+
}
|
|
19
|
+
setCurrentTime(time) {
|
|
20
|
+
this.audio.currentTime = time;
|
|
21
|
+
}
|
|
22
|
+
getVolume() {
|
|
23
|
+
return this.audio.volume * 100;
|
|
24
|
+
}
|
|
25
|
+
setVolume(volume) {
|
|
26
|
+
this.audio.volume = volume / 100;
|
|
27
|
+
}
|
|
28
|
+
play() {
|
|
29
|
+
this.audio.play().catch((error) => {
|
|
30
|
+
console.error("Error playing audio:", error);
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
pause() {
|
|
34
|
+
this.audio.pause();
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
var YoutubeMediaController = class {
|
|
38
|
+
constructor(player) {
|
|
39
|
+
this.player = player;
|
|
40
|
+
}
|
|
41
|
+
player;
|
|
42
|
+
getCurrentTime() {
|
|
43
|
+
return this.player.getCurrentTime();
|
|
44
|
+
}
|
|
45
|
+
setCurrentTime(time) {
|
|
46
|
+
this.player.seekTo(time, true);
|
|
47
|
+
}
|
|
48
|
+
getVolume() {
|
|
49
|
+
return this.player.getVolume();
|
|
50
|
+
}
|
|
51
|
+
setVolume(volume) {
|
|
52
|
+
this.player.setVolume(volume);
|
|
53
|
+
}
|
|
54
|
+
play() {
|
|
55
|
+
this.player.playVideo();
|
|
56
|
+
}
|
|
57
|
+
pause() {
|
|
58
|
+
this.player.pauseVideo();
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// src/player/PlayerContext.tsx
|
|
63
|
+
import { createContext, useContext, useState, useRef, useEffect, useCallback, useMemo } from "react";
|
|
64
|
+
|
|
65
|
+
// src/player/youtubeIframeApi.ts
|
|
66
|
+
var apiPromise = null;
|
|
67
|
+
function loadYoutubeIframeApi() {
|
|
68
|
+
if (typeof window === "undefined") {
|
|
69
|
+
return Promise.reject(new Error("YouTube IFrame API can only be loaded in the browser"));
|
|
70
|
+
}
|
|
71
|
+
if (window.YT?.Player) {
|
|
72
|
+
return Promise.resolve(window.YT);
|
|
73
|
+
}
|
|
74
|
+
if (apiPromise) {
|
|
75
|
+
return apiPromise;
|
|
76
|
+
}
|
|
77
|
+
apiPromise = new Promise((resolve) => {
|
|
78
|
+
const previousCallback = window.onYouTubeIframeAPIReady;
|
|
79
|
+
window.onYouTubeIframeAPIReady = () => {
|
|
80
|
+
previousCallback?.();
|
|
81
|
+
resolve(window.YT);
|
|
82
|
+
};
|
|
83
|
+
const script = document.createElement("script");
|
|
84
|
+
script.src = "https://www.youtube.com/iframe_api";
|
|
85
|
+
document.head.appendChild(script);
|
|
86
|
+
});
|
|
87
|
+
return apiPromise;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// src/player/PlayerContext.tsx
|
|
91
|
+
import { jsx } from "react/jsx-runtime";
|
|
92
|
+
var isPlayable = (track) => track.kind !== "youtube" || !track.unplayableReason;
|
|
93
|
+
function youtubeErrorMessage(code) {
|
|
94
|
+
if (code === 100) return "Video not found";
|
|
95
|
+
if (code === 101 || code === 150) return "Embedding disabled by the video owner";
|
|
96
|
+
return `YouTube playback error (code ${code})`;
|
|
97
|
+
}
|
|
98
|
+
var PlayerContext = createContext(void 0);
|
|
99
|
+
function PlayerProvider({ children, loadTrack }) {
|
|
100
|
+
const [playerTrackObject, setPlayerTrackObject] = useState(null);
|
|
101
|
+
const [isPlaying, setIsPlaying] = useState(false);
|
|
102
|
+
const [duration, setDuration] = useState(0);
|
|
103
|
+
const [volume, setVolume] = useState(50);
|
|
104
|
+
const [playState, setPlayState] = useState("STOPPED" /* STOPPED */);
|
|
105
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
106
|
+
const [onTrackEnd, setOnTrackEnd] = useState(null);
|
|
107
|
+
const audioElementRef = useRef(null);
|
|
108
|
+
const youtubePlayerRef = useRef(null);
|
|
109
|
+
const videoContainerRef = useRef(null);
|
|
110
|
+
const currentTimeRef = useRef(0);
|
|
111
|
+
const onTrackEndRef = useRef(onTrackEnd);
|
|
112
|
+
useEffect(() => {
|
|
113
|
+
onTrackEndRef.current = onTrackEnd;
|
|
114
|
+
}, [onTrackEnd]);
|
|
115
|
+
useEffect(() => {
|
|
116
|
+
loadYoutubeIframeApi().catch(() => {
|
|
117
|
+
});
|
|
118
|
+
}, []);
|
|
119
|
+
useEffect(() => {
|
|
120
|
+
const interval = setInterval(() => {
|
|
121
|
+
const player = youtubePlayerRef.current;
|
|
122
|
+
if (player) {
|
|
123
|
+
currentTimeRef.current = player.getCurrentTime();
|
|
124
|
+
setDuration(player.getDuration());
|
|
125
|
+
}
|
|
126
|
+
}, 250);
|
|
127
|
+
return () => clearInterval(interval);
|
|
128
|
+
}, []);
|
|
129
|
+
const handleYoutubeStateChange = useCallback((event) => {
|
|
130
|
+
if (event.data === window.YT.PlayerState.ENDED) {
|
|
131
|
+
setPlayState("STOPPED" /* STOPPED */);
|
|
132
|
+
setIsPlaying(false);
|
|
133
|
+
onTrackEndRef.current?.();
|
|
134
|
+
}
|
|
135
|
+
}, []);
|
|
136
|
+
const loadAudioTrack = useCallback(
|
|
137
|
+
(track) => {
|
|
138
|
+
const audio = new Audio(track.streamUrl);
|
|
139
|
+
audio.volume = volume / 100;
|
|
140
|
+
audioElementRef.current = audio;
|
|
141
|
+
audio.addEventListener("loadedmetadata", () => {
|
|
142
|
+
setDuration(audio.duration);
|
|
143
|
+
});
|
|
144
|
+
audio.addEventListener("timeupdate", () => {
|
|
145
|
+
currentTimeRef.current = audio.currentTime;
|
|
146
|
+
});
|
|
147
|
+
audio.addEventListener("ended", () => {
|
|
148
|
+
setPlayState("STOPPED" /* STOPPED */);
|
|
149
|
+
setIsPlaying(false);
|
|
150
|
+
onTrackEndRef.current?.();
|
|
151
|
+
});
|
|
152
|
+
audio.addEventListener("error", (e) => {
|
|
153
|
+
console.error("Audio error event fired:", e);
|
|
154
|
+
});
|
|
155
|
+
setPlayerTrackObject({ track, mediaController: new AudioMediaController(audio), isReady: true, loadError: void 0 });
|
|
156
|
+
setPlayState("PLAYING" /* PLAYING */);
|
|
157
|
+
setIsPlaying(true);
|
|
158
|
+
audio.play().catch((error) => {
|
|
159
|
+
console.error("Error auto-playing audio:", error);
|
|
160
|
+
});
|
|
161
|
+
},
|
|
162
|
+
[volume]
|
|
163
|
+
);
|
|
164
|
+
const loadYoutubeTrack = useCallback(
|
|
165
|
+
async (track) => {
|
|
166
|
+
if (youtubePlayerRef.current) {
|
|
167
|
+
const player = youtubePlayerRef.current;
|
|
168
|
+
player.loadVideoById(track.youtubeVideoId);
|
|
169
|
+
setPlayerTrackObject({ track, mediaController: new YoutubeMediaController(player), isReady: true, loadError: void 0 });
|
|
170
|
+
setPlayState("PLAYING" /* PLAYING */);
|
|
171
|
+
setIsPlaying(true);
|
|
172
|
+
player.playVideo();
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const container = videoContainerRef.current;
|
|
176
|
+
if (!container) {
|
|
177
|
+
throw new Error("PlayerVideoSurface must be rendered before a YouTube track can be loaded");
|
|
178
|
+
}
|
|
179
|
+
const YT = await loadYoutubeIframeApi();
|
|
180
|
+
await new Promise((resolve) => {
|
|
181
|
+
const player = new YT.Player(container, {
|
|
182
|
+
videoId: track.youtubeVideoId,
|
|
183
|
+
playerVars: { autoplay: 1 },
|
|
184
|
+
events: {
|
|
185
|
+
onReady: () => {
|
|
186
|
+
youtubePlayerRef.current = player;
|
|
187
|
+
setPlayerTrackObject({ track, mediaController: new YoutubeMediaController(player), isReady: true, loadError: void 0 });
|
|
188
|
+
setPlayState("PLAYING" /* PLAYING */);
|
|
189
|
+
setIsPlaying(true);
|
|
190
|
+
player.playVideo();
|
|
191
|
+
resolve();
|
|
192
|
+
},
|
|
193
|
+
onStateChange: handleYoutubeStateChange,
|
|
194
|
+
onError: (event) => {
|
|
195
|
+
const loadError = youtubeErrorMessage(event.data);
|
|
196
|
+
setPlayerTrackObject((prev) => prev ? { ...prev, loadError } : prev);
|
|
197
|
+
setPlayState("STOPPED" /* STOPPED */);
|
|
198
|
+
setIsPlaying(false);
|
|
199
|
+
onTrackEndRef.current?.();
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
},
|
|
205
|
+
[handleYoutubeStateChange]
|
|
206
|
+
);
|
|
207
|
+
const loadTrackForPlayer = useCallback(
|
|
208
|
+
(trackId) => {
|
|
209
|
+
if (audioElementRef.current) {
|
|
210
|
+
audioElementRef.current.pause();
|
|
211
|
+
audioElementRef.current.currentTime = 0;
|
|
212
|
+
audioElementRef.current = null;
|
|
213
|
+
}
|
|
214
|
+
if (youtubePlayerRef.current) {
|
|
215
|
+
youtubePlayerRef.current.pauseVideo();
|
|
216
|
+
}
|
|
217
|
+
setPlayerTrackObject(null);
|
|
218
|
+
setIsLoading(true);
|
|
219
|
+
setPlayState("LOADING" /* LOADING */);
|
|
220
|
+
loadTrack(trackId).then((track) => track.kind === "youtube" ? loadYoutubeTrack(track) : loadAudioTrack(track)).catch((error) => {
|
|
221
|
+
console.error("Error loading track:", error);
|
|
222
|
+
setPlayState("STOPPED" /* STOPPED */);
|
|
223
|
+
setPlayerTrackObject({
|
|
224
|
+
track: { id: trackId, kind: "audio", streamUrl: "", title: "" },
|
|
225
|
+
isReady: false,
|
|
226
|
+
loadError: error?.message ?? "Failed to load track"
|
|
227
|
+
});
|
|
228
|
+
}).finally(() => {
|
|
229
|
+
setIsLoading(false);
|
|
230
|
+
});
|
|
231
|
+
},
|
|
232
|
+
[loadTrack, loadAudioTrack, loadYoutubeTrack]
|
|
233
|
+
);
|
|
234
|
+
const handleNextTrack = useCallback(
|
|
235
|
+
(trackList, currentTrack, onTrackChange) => {
|
|
236
|
+
if (!trackList || !currentTrack) return;
|
|
237
|
+
const currentIndex = trackList.findIndex((track) => track.id === currentTrack.id);
|
|
238
|
+
if (currentIndex === -1) return;
|
|
239
|
+
const nextTrack = trackList.slice(currentIndex + 1).find(isPlayable);
|
|
240
|
+
if (nextTrack) {
|
|
241
|
+
onTrackChange(nextTrack);
|
|
242
|
+
loadTrackForPlayer(nextTrack.id);
|
|
243
|
+
}
|
|
244
|
+
},
|
|
245
|
+
[loadTrackForPlayer]
|
|
246
|
+
);
|
|
247
|
+
const handlePreviousTrack = useCallback(
|
|
248
|
+
(trackList, currentTrack, onTrackChange) => {
|
|
249
|
+
if (!trackList || !currentTrack) return;
|
|
250
|
+
const currentIndex = trackList.findIndex((track) => track.id === currentTrack.id);
|
|
251
|
+
if (currentIndex === -1) return;
|
|
252
|
+
const previousTrack = trackList.slice(0, currentIndex).reverse().find(isPlayable);
|
|
253
|
+
if (previousTrack) {
|
|
254
|
+
onTrackChange(previousTrack);
|
|
255
|
+
loadTrackForPlayer(previousTrack.id);
|
|
256
|
+
}
|
|
257
|
+
},
|
|
258
|
+
[loadTrackForPlayer]
|
|
259
|
+
);
|
|
260
|
+
useEffect(() => {
|
|
261
|
+
return () => {
|
|
262
|
+
if (audioElementRef.current) {
|
|
263
|
+
audioElementRef.current.pause();
|
|
264
|
+
audioElementRef.current = null;
|
|
265
|
+
}
|
|
266
|
+
if (youtubePlayerRef.current) {
|
|
267
|
+
youtubePlayerRef.current.destroy();
|
|
268
|
+
youtubePlayerRef.current = null;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
}, []);
|
|
272
|
+
const handlePlayPauseAction = useCallback(() => {
|
|
273
|
+
if (playState === "LOADING" /* LOADING */) return;
|
|
274
|
+
if (!playerTrackObject?.isReady) return;
|
|
275
|
+
const mediaController = playerTrackObject.mediaController;
|
|
276
|
+
if (!mediaController) return;
|
|
277
|
+
if (playState === "PLAYING" /* PLAYING */) {
|
|
278
|
+
mediaController.pause();
|
|
279
|
+
setPlayState("PAUSED" /* PAUSED */);
|
|
280
|
+
setIsPlaying(false);
|
|
281
|
+
} else {
|
|
282
|
+
mediaController.play();
|
|
283
|
+
setPlayState("PLAYING" /* PLAYING */);
|
|
284
|
+
setIsPlaying(true);
|
|
285
|
+
}
|
|
286
|
+
}, [playerTrackObject?.isReady, playerTrackObject?.mediaController, playState]);
|
|
287
|
+
const contextValue = useMemo(
|
|
288
|
+
() => ({
|
|
289
|
+
playerTrackObject,
|
|
290
|
+
isPlaying,
|
|
291
|
+
setIsPlaying,
|
|
292
|
+
currentTimeRef,
|
|
293
|
+
duration,
|
|
294
|
+
setDuration,
|
|
295
|
+
volume,
|
|
296
|
+
setVolume,
|
|
297
|
+
playState,
|
|
298
|
+
setPlayState,
|
|
299
|
+
handlePlayPauseAction,
|
|
300
|
+
loadTrackForPlayer,
|
|
301
|
+
isLoading,
|
|
302
|
+
handleNextTrack,
|
|
303
|
+
handlePreviousTrack,
|
|
304
|
+
onTrackEnd,
|
|
305
|
+
setOnTrackEnd,
|
|
306
|
+
videoContainerRef
|
|
307
|
+
}),
|
|
308
|
+
[
|
|
309
|
+
playerTrackObject,
|
|
310
|
+
isPlaying,
|
|
311
|
+
duration,
|
|
312
|
+
volume,
|
|
313
|
+
playState,
|
|
314
|
+
isLoading,
|
|
315
|
+
handlePlayPauseAction,
|
|
316
|
+
loadTrackForPlayer,
|
|
317
|
+
handleNextTrack,
|
|
318
|
+
handlePreviousTrack,
|
|
319
|
+
onTrackEnd
|
|
320
|
+
]
|
|
321
|
+
);
|
|
322
|
+
return /* @__PURE__ */ jsx(PlayerContext.Provider, { value: contextValue, children });
|
|
323
|
+
}
|
|
324
|
+
function usePlayer() {
|
|
325
|
+
const context = useContext(PlayerContext);
|
|
326
|
+
if (context === void 0) {
|
|
327
|
+
throw new Error("usePlayer must be used within a PlayerProvider");
|
|
328
|
+
}
|
|
329
|
+
return context;
|
|
330
|
+
}
|
|
331
|
+
function PlayerVideoSurface({ className }) {
|
|
332
|
+
const { videoContainerRef } = usePlayer();
|
|
333
|
+
return /* @__PURE__ */ jsx("div", { ref: videoContainerRef, className });
|
|
334
|
+
}
|
|
335
|
+
function useCurrentTime() {
|
|
336
|
+
const { currentTimeRef } = usePlayer();
|
|
337
|
+
const [currentTime, setCurrentTime] = useState(0);
|
|
338
|
+
useEffect(() => {
|
|
339
|
+
const interval = setInterval(() => {
|
|
340
|
+
setCurrentTime(currentTimeRef.current);
|
|
341
|
+
}, 100);
|
|
342
|
+
return () => clearInterval(interval);
|
|
343
|
+
}, [currentTimeRef]);
|
|
344
|
+
return currentTime;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export {
|
|
348
|
+
PlayStates,
|
|
349
|
+
AudioMediaController,
|
|
350
|
+
YoutubeMediaController,
|
|
351
|
+
PlayerProvider,
|
|
352
|
+
usePlayer,
|
|
353
|
+
PlayerVideoSurface,
|
|
354
|
+
useCurrentTime
|
|
355
|
+
};
|
|
356
|
+
//# sourceMappingURL=chunk-OIZPAN6I.js.map
|