46 lines
1.0 KiB
TypeScript
46 lines
1.0 KiB
TypeScript
|
"use client";
|
||
|
import { createContext, useReducer } from "react";
|
||
|
|
||
|
export interface DanmuPayload {
|
||
|
liveName?: string;
|
||
|
liveId?: string;
|
||
|
songId?: string;
|
||
|
songName?: string;
|
||
|
songArtist?: string;
|
||
|
}
|
||
|
|
||
|
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 };
|
||
|
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>
|
||
|
);
|
||
|
}
|