import type { PropsWithChildren } from 'react' ; import React , { useEffect , useMemo , useState } from 'react' ; import type { ApplicationStart , DocLinksStart , NotificationsStart } from 'src/core/public' ; import type { GetAllSpacesPurpose } from '../../common' ; import type { SpacesManager } from '../spaces_manager' ; import type { SpacesData , SpacesDataEntry } from '../types' ; import { createSpacesReactContext } from './context' ; import type { InternalProps , SpacesContextProps , SpacesReactContext } from './types' ; interface Services { application : ApplicationStart ; docLinks : DocLinksStart ; notifications : NotificationsStart ; } async function getSpacesData ( spacesManager , feature ? ) { const spaces = await spacesManager . getSpaces ( { includeAuthorizedPurposes : true } ) ; const activeSpace = await spacesManager . getActiveSpace ( ) ; const spacesMap = spaces . map < SpacesDataEntry > ( ( { authorizedPurposes , disabledFeatures , ... space } ) => { const isActiveSpace = space . id === activeSpace . id ; const isFeatureDisabled = feature !== undefined && disabledFeatures . includes ( feature ) ; return { ... space , ... ( isActiveSpace && { isActiveSpace } ) , ... ( isFeatureDisabled && { isFeatureDisabled } ) , isAuthorizedForPurpose : ( purpose ) => authorizedPurposes ? authorizedPurposes [ purpose ] === true : true , } ; } ) . reduce ( ( acc , cur ) => acc . set ( cur . id , cur ) , new Map < string , SpacesDataEntry > ( ) ) ; return { spacesMap , activeSpaceId : activeSpace . id , } ; } export const SpacesContextWrapperInternal = ( props ) => { const { spacesManager , getStartServices , feature , children } = props ; const [ context , setContext ] = useState < SpacesReactContext < Services > | undefined > ( ) ; const spacesDataPromise = useMemo ( ( ) => getSpacesData ( spacesManager , feature ) , [ spacesManager , feature ] ) ; useEffect ( ( ) => { getStartServices ( ) . then ( ( [ coreStart ] ) => { const { application , docLinks , notifications } = coreStart ; const services = { application , docLinks , notifications } ; setContext ( createSpacesReactContext ( services , spacesManager , spacesDataPromise ) ) ; } ) ; } , [ getStartServices , spacesDataPromise , spacesManager ] ) ; if ( ! context ) { return null ; } return < context . Provider > { children } < /context.Provider>; } ;