36 lines
939 B
TypeScript
36 lines
939 B
TypeScript
|
|
import * as React from "react"
|
||
|
|
|
||
|
|
import type { MediaAdapter, MediaNotice } from "./types"
|
||
|
|
|
||
|
|
interface MediaContextValue {
|
||
|
|
adapter: MediaAdapter
|
||
|
|
notify?: (notice: MediaNotice) => void
|
||
|
|
}
|
||
|
|
|
||
|
|
const MediaContext = React.createContext<MediaContextValue | null>(null)
|
||
|
|
|
||
|
|
export interface MediaProviderProps {
|
||
|
|
adapter: MediaAdapter
|
||
|
|
children: React.ReactNode
|
||
|
|
notify?: (notice: MediaNotice) => void
|
||
|
|
}
|
||
|
|
|
||
|
|
/** Supplies all persistence and transport dependencies for the media blocks. */
|
||
|
|
export function MediaProvider({
|
||
|
|
adapter,
|
||
|
|
children,
|
||
|
|
notify,
|
||
|
|
}: MediaProviderProps) {
|
||
|
|
const value = React.useMemo(() => ({ adapter, notify }), [adapter, notify])
|
||
|
|
|
||
|
|
return <MediaContext.Provider value={value}>{children}</MediaContext.Provider>
|
||
|
|
}
|
||
|
|
|
||
|
|
export function useMedia(): MediaContextValue {
|
||
|
|
const value = React.useContext(MediaContext)
|
||
|
|
if (!value) {
|
||
|
|
throw new Error("Media blocks must be rendered inside a MediaProvider.")
|
||
|
|
}
|
||
|
|
return value
|
||
|
|
}
|