49 lines
1.2 KiB
TypeScript
49 lines
1.2 KiB
TypeScript
"use client";
|
|
import { createContext, useReducer } from "react";
|
|
|
|
export interface DanmuPayload {
|
|
liveName?: string;
|
|
liveId?: string;
|
|
songId?: string;
|
|
songName?: string;
|
|
songArtist?: string;
|
|
listener?: (msg: string) => void;
|
|
}
|
|
|
|
export interface DanmuAction {
|
|
type: string;
|
|
payload: DanmuPayload;
|
|
}
|
|
|
|
export const DanmuContext = createContext<DanmuPayload & { dispatch?: any }>(
|
|
{}
|
|
);
|
|
|
|
const reducer = (state: DanmuPayload, action: DanmuAction): DanmuPayload => {
|
|
const payload = action.payload;
|
|
switch (action.type) {
|
|
case "songs":
|
|
return {
|
|
...state,
|
|
songId: payload.songId,
|
|
songName: payload.songName,
|
|
songArtist: payload.songArtist,
|
|
};
|
|
case "lives":
|
|
return { ...state, liveId: payload.liveId, liveName: payload.liveName };
|
|
case "listener":
|
|
return { ...state, listener: payload.listener };
|
|
default:
|
|
throw new Error("not support action");
|
|
}
|
|
};
|
|
|
|
export default function DanmuProvider(props: any) {
|
|
const [state, dispatch] = useReducer(reducer, {});
|
|
return (
|
|
<DanmuContext.Provider value={{ ...state, dispatch }}>
|
|
{props.children}
|
|
</DanmuContext.Provider>
|
|
);
|
|
}
|