import * as React from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { Bullseye, Button, Spinner } from '@patternfly/react-core'; import { useQuery } from '@tanstack/react-query'; import { APPLICATION_LIST_PATH } from '@routes/paths'; import { RouterParams } from '../../../routes/utils'; import { NamespaceKind } from '../../../types'; import ErrorEmptyState from '../../components/empty-state/ErrorEmptyState'; import { createNamespaceQueryOptions, getLastUsedNamespace, setLastUsedNamespace } from './utils'; export type NamespaceContextData = { namespace: string; namespaceResource: NamespaceKind | undefined; namespacesLoaded: boolean; lastUsedNamespace: string; namespaces: NamespaceKind[]; }; export const NamespaceContext = React.createContext({ namespace: '', namespaceResource: undefined, namespacesLoaded: false, namespaces: [], lastUsedNamespace: getLastUsedNamespace(), }); export const NamespaceProvider: React.FC = ({ children }) => { const { data: namespaces, isLoading: namespaceLoading, error: namespacesError, } = useQuery(createNamespaceQueryOptions()); const params = useParams(); const navigate = useNavigate(); const activeNamespaceName: string = params.workspaceName ?? getLastUsedNamespace(); const homeNamespace = React.useMemo(() => { if (namespaceLoading || namespacesError) return null; const namespacesData = namespaces ?? []; return namespacesData.find((n) => n.metadata.name === activeNamespaceName); }, [namespaces, namespacesError, namespaceLoading, activeNamespaceName]); const { data: namespaceResource, isLoading: activeNamespaceLoading, error, } = useQuery({ ...createNamespaceQueryOptions(activeNamespaceName), retry: false, enabled: !activeNamespaceName, }); React.useEffect(() => { if (!error && getLastUsedNamespace() !== activeNamespaceName) { setLastUsedNamespace(activeNamespaceName); } }, [activeNamespaceName, error]); if (error) { return ( {homeNamespace ? ( ) : null} ); } // If namespaces failed to load but we have an active namespace, use fallback with empty list return ( {!(namespaceLoading || activeNamespaceLoading) ? ( children ) : ( )} ); };