import { Context } from "almin" ; import * as React from "react" ; export type ProviderProps < T > = { initialState ? : T ; children : React . ReactNode ; } ; export type ConsumerProps < T > = { children : ( props : T ) => React . ReactNode ; } ; export function createReactContext < T > ( alminContext ) { const initialState = alminContext . getState ( ) ; const StateContext = React . createContext ( initialState ) ; class Provider extends React . PureComponent < ProviderProps < T > > { private releaseHandler : ( ) => void ; constructor ( props ) { super ( props ) ; this . state = props . initialState || initialState ; this . releaseHandler = alminContext . onChange ( this . onChange ) ; } private onChange = ( ) => { this . setState ( alminContext . getState ( ) ) ; } ; componentWillUnmount ( ) { this . releaseHandler ( ) ; } render ( ) { if ( StateContext === null ) { return null ; } return < StateContext . Provider value = { this . state } > { this . props . children } < /StateContext.Provider>; } } class Consumer extends React . PureComponent < ConsumerProps < T > > { render ( ) { if ( StateContext === null ) { throw new Error ( "You must wrap your <Consumer> components with a <Provider> component.\n" + "You can get <Provider> component via `createContext()` API." ) ; } return ( < StateContext . Consumer > { ( value ) => { return this . props . children ( value ) ; } } < /StateContext.Consumer>); } } return { Provider , Consumer , } ; }