v3: added localization, use global player for uploaded audio/video files

This commit is contained in:
khannurien
2026-04-03 15:29:33 +00:00
parent 378b3ffa46
commit 0ce80398a4
64 changed files with 4248 additions and 941 deletions

View File

@@ -1,19 +1,43 @@
import { createContext } from "react";
export interface PlayerItem {
embedUrl: string;
title?: string;
type: string;
}
export type PlayerItem =
| { kind: "embed"; embedUrl: string; title?: string; type: string }
| { kind: "file"; fileUrl: string; mimeType: string; title?: string };
export interface PlayerContextValue {
// Playback state — readable by any consumer
current: PlayerItem | null;
playing: boolean;
currentTime: number;
duration: number;
// Control — callable by any consumer
play(item: PlayerItem): void;
stop(): void;
seekTo(time: number): void;
togglePlay(): void;
// Internal: GlobalPlayer registers MediaPlayer's imperative handles here
// so seekTo / togglePlay can reach into the actual media element.
seekRef: { current: ((t: number) => void) | null };
toggleRef: { current: (() => void) | null };
// Internal: GlobalPlayer calls these to push state back into the provider
onPlayStateChange(playing: boolean): void;
onTimeUpdate(time: number, duration: number): void;
}
export const PlayerContext = createContext<PlayerContextValue>({
current: null,
playing: false,
currentTime: 0,
duration: 0,
play: () => {},
stop: () => {},
seekTo: () => {},
togglePlay: () => {},
seekRef: { current: null },
toggleRef: { current: null },
onPlayStateChange: () => {},
onTimeUpdate: () => {},
});

View File

@@ -1,12 +1,80 @@
import { useCallback, useMemo, useState } from "react";
import { useCallback, useMemo, useRef, useState } from "react";
import { PlayerContext, type PlayerItem } from "./PlayerContext.ts";
export function PlayerProvider({ children }: { children: React.ReactNode }) {
const [current, setCurrent] = useState<PlayerItem | null>(null);
const [playing, setPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
const play = setCurrent;
const stop = useCallback(() => setCurrent(null), []);
const value = useMemo(() => ({ current, play, stop }), [current, play, stop]);
// GlobalPlayer registers the active MediaPlayer's imperative handles here
const seekRef = useRef<((t: number) => void) | null>(null);
const toggleRef = useRef<(() => void) | null>(null);
// Suppresses stale timeupdate callbacks that fire between play() and the old
// MediaPlayer's unmount cleanup. Cleared when the new media fires onPlayStateChange(true).
const suppressUpdates = useRef(false);
const play = useCallback((item: PlayerItem) => {
suppressUpdates.current = true;
setCurrent(item);
setCurrentTime(0);
setDuration(0);
setPlaying(false);
}, []);
const stop = useCallback(() => {
setCurrent(null);
setPlaying(false);
setCurrentTime(0);
setDuration(0);
}, []);
const seekTo = useCallback((t: number) => {
seekRef.current?.(t);
setCurrentTime(t); // optimistic — prevents waveform jitter before timeupdate fires
}, []);
const togglePlay = useCallback(() => {
toggleRef.current?.();
}, []);
const onPlayStateChange = useCallback((p: boolean) => {
if (p) suppressUpdates.current = false;
setPlaying(p);
}, []);
const onTimeUpdate = useCallback((t: number, d: number) => {
if (suppressUpdates.current) return;
setCurrentTime(t);
setDuration(d);
}, []);
const value = useMemo(() => ({
current,
playing,
currentTime,
duration,
play,
stop,
seekTo,
togglePlay,
seekRef,
toggleRef,
onPlayStateChange,
onTimeUpdate,
}), [
current,
playing,
currentTime,
duration,
play,
stop,
seekTo,
togglePlay,
onPlayStateChange,
onTimeUpdate,
]);
return (
<PlayerContext.Provider value={value}>

View File

@@ -30,12 +30,11 @@ import {
deserializePlaylist,
deserializePublicUser,
} from "../model.ts";
import { t } from "@lingui/core/macro";
import { useAuth } from "../hooks/useAuth.ts";
interface WSProviderProps {
children: ReactNode;
token: string | null;
userId: string | null;
onForceLogout?: () => void;
}
const MAX_BACKOFF = 30_000;
@@ -61,13 +60,23 @@ function parseWSMessage(data: string): IncomingWSMessage | null {
}
}
export function WSProvider(
{ children, token, userId, onForceLogout }: WSProviderProps,
) {
export function WSProvider({ children }: WSProviderProps) {
const { token, user, logout } = useAuth();
const userId = user?.id ?? null;
const [wsStatus, setWSStatus] = useState<
"connecting" | "connected" | "disconnected"
>("connecting");
const [wsErrorMessage, setWSErrorMessage] = useState<string | null>(null);
// Reset status to "connecting" during render when token changes, rather than
// inside the effect (which would cause a cascading re-render).
const [prevToken, setPrevToken] = useState(token);
if (prevToken !== token) {
setPrevToken(token);
setWSStatus("connecting");
setWSErrorMessage(null);
}
const [onlineUsers, setOnlineUsers] = useState<OnlineUser[]>([]);
const [voteCounts, setVoteCounts] = useState<Record<string, number>>({});
const [myVotes, setMyVotes] = useState<Set<string>>(new Set());
@@ -94,10 +103,14 @@ export function WSProvider(
const voteCountsRef = useRef(voteCounts);
const myVotesRef = useRef(myVotes);
const userIdRef = useRef(userId);
// Stable ref for logout so the effect doesn't reconnect when the function
// reference changes on re-renders.
const onForceLogoutRef = useRef(logout);
useLayoutEffect(() => {
voteCountsRef.current = voteCounts;
myVotesRef.current = myVotes;
userIdRef.current = userId;
onForceLogoutRef.current = logout;
});
const socketRef = useRef<WebSocket | null>(null);
@@ -139,9 +152,6 @@ export function WSProvider(
let connectTimeout: ReturnType<typeof setTimeout> | null = null;
let everConnected = false;
setWSStatus("connecting");
setWSErrorMessage(null);
function connect() {
if (closed) return;
@@ -155,7 +165,7 @@ export function WSProvider(
if (ws.readyState !== WebSocket.CONNECTING) return;
setWSStatus("disconnected");
setWSErrorMessage(
"Can't connect to the live updates server. Upvotes and notifications may not sync until it reconnects.",
t`Can't connect to the live updates server. Upvotes and notifications may not sync until it reconnects.`,
);
ws.close();
}, CONNECT_TIMEOUT);
@@ -327,7 +337,7 @@ export function WSProvider(
}
case "force_logout":
onForceLogout?.();
onForceLogoutRef.current();
break;
case "error":
@@ -346,8 +356,8 @@ export function WSProvider(
setWSStatus("disconnected");
setWSErrorMessage(
everConnected
? "Live updates are temporarily disconnected. Trying to reconnect..."
: "Can't connect to the live updates server. Upvotes and notifications may not sync until it reconnects.",
? t`Live updates are temporarily disconnected. Trying to reconnect…`
: t`Can't connect to the live updates server. Upvotes and notifications may not sync until it reconnects.`,
);
reconnectTimer = setTimeout(() => {
backoff = Math.min(backoff * 2, MAX_BACKOFF);