import { useContext , useEffect , useRef , useMemo } from 'react' ; import { appContext } from './AppContext' ; import type { IServiceConstructor , IInitializableController , IDestructibleController , ExtractInitArgs } from './IApp' ; export function useController < T extends IInitializableController > ( ctor , ... args ) ; export function useController < T > ( ctor ) ; export function useController < T > ( ctor , ... args ) { const app = useContext ( appContext ) ; const controllerRef = useRef < T > ( ) ; useMemo ( ( ) => { if ( controllerRef . current && isDestructibleController ( controllerRef . current ) ) { controllerRef . current . destruct ( ) ; } const controller = app . resolveServiceByClass ( ctor ) ; if ( isInitializableController ( controller ) ) { controller . init ( ... args ) ; } controllerRef . current = controller ; } , [ ... args , args . length ] ) ; useEffect ( ( ) => ( ) => { if ( isDestructibleController ( controllerRef . current ) ) { controllerRef . current . destruct ( ) ; } } , [ ] ) ; return controllerRef . current ! ; } function isDestructibleController ( obj ) { return obj && typeof obj . destruct === 'function' ; } function isInitializableController ( obj ) { return obj && typeof obj . init === 'function' ; }