67 lines
1.5 KiB
TypeScript
67 lines
1.5 KiB
TypeScript
"use client";
|
|
|
|
import {
|
|
createContext,
|
|
ReactNode,
|
|
useCallback,
|
|
useContext,
|
|
useMemo,
|
|
useState,
|
|
} from "react";
|
|
|
|
interface BackgroundState {
|
|
imageUrl: string | null;
|
|
opacity: number;
|
|
key: string;
|
|
}
|
|
|
|
interface BackgroundContextValue {
|
|
backgroundState: BackgroundState;
|
|
setBackground: (
|
|
imageUrl: string | null,
|
|
opacity: number,
|
|
key?: string,
|
|
) => void;
|
|
}
|
|
|
|
const BackgroundContext = createContext<BackgroundContextValue | undefined>(
|
|
undefined,
|
|
);
|
|
|
|
export const BackgroundProvider = ({ children }: { children: ReactNode }) => {
|
|
const [backgroundState, setBackgroundState] = useState<BackgroundState>({
|
|
imageUrl: null,
|
|
opacity: 0,
|
|
key: "initial",
|
|
});
|
|
|
|
const setBackground = useCallback(
|
|
(imageUrl: string | null, opacity: number, key?: string) => {
|
|
setBackgroundState({
|
|
imageUrl,
|
|
opacity: imageUrl ? Math.max(0, Math.min(opacity, 1)) : 0, // Ensure opacity is 0 if no image
|
|
key: key || imageUrl || `bg-${Date.now()}`,
|
|
});
|
|
},
|
|
[],
|
|
);
|
|
|
|
const contextValue = useMemo(
|
|
() => ({ backgroundState, setBackground }),
|
|
[backgroundState, setBackground],
|
|
);
|
|
|
|
return (
|
|
<BackgroundContext.Provider value={contextValue}>
|
|
{children}
|
|
</BackgroundContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useBackground = (): BackgroundContextValue => {
|
|
const context = useContext(BackgroundContext);
|
|
if (context === undefined) {
|
|
throw new Error("useBackground must be used within a BackgroundProvide x");
|
|
}
|
|
return context;
|
|
};
|