### Implement MainLayout Component for React Application Shell (TypeScript/React)
Source: https://context7.com/pro-robotech/openapi-ui/llms.txt
This React component, written in TypeScript, serves as the main layout for the application. It manages theme settings (including automatic dark/light mode detection), fetches the cluster list using a custom hook, and integrates with Redux for state management. It also displays an alert if there's an error fetching the cluster list. Dependencies include `antd` for UI elements and `@prorobotech/openapi-k8s-toolkit` for cluster list fetching.
```typescript
import { Layout, theme as antdtheme, Alert } from 'antd'
import { useClusterList } from '@prorobotech/openapi-k8s-toolkit'
import { useSelector, useDispatch } from 'react-redux'
import { setTheme } from 'store/theme/theme/theme'
import { setClusterList } from 'store/clusterList/clusterList/clusterList'
export const MainLayout: FC<{ forcedTheme?: 'dark' | 'light' }> = ({ forcedTheme }) => {
const { cluster } = useParams()
const { token } = antdtheme.useToken()
const dispatch = useDispatch()
const clusterListQuery = useClusterList({ refetchInterval: false })
// Initialize theme from localStorage or system preference
useEffect(() => {
if (forcedTheme) return
const localStorageTheme = localStorage.getItem('theme')
if (localStorageTheme === 'dark' || localStorageTheme === 'light') {
dispatch(setTheme(localStorageTheme))
} else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
dispatch(setTheme('dark'))
}
}, [dispatch, forcedTheme])
// Sync cluster list to Redux store
useEffect(() => {
if (clusterListQuery.data) {
dispatch(setClusterList(clusterListQuery.data))
}
}, [clusterListQuery, dispatch])
return (
{clusterListQuery.error && }
)
}
```
--------------------------------
### BlackholeForm Component: Kubernetes Resource Form Management (React/TypeScript)
Source: https://context7.com/pro-robotech/openapi-ui/llms.txt
The BlackholeForm component facilitates the creation and editing of Kubernetes resources. It offers customization options and responsive height calculation, leveraging the BlackholeFormProvider from '@prorobotech/openapi-k8s-toolkit'. It integrates with react-router-dom for URL parameter handling.
```tsx
import { BlackholeFormProvider, TJSON } from '@prorobotech/openapi-k8s-toolkit'
import { useParams } from 'react-router-dom'
type TBlackholeFormProps = {
data: {
type: 'builtin' | 'apis'
apiGroup?: string
apiVersion?: string
plural: string
prefillValuesSchema?: TJSON
}
customizationId: string
isCreate?: boolean
backlink?: string | null
}
export const BlackholeForm: FC = ({ data, customizationId, isCreate, backlink }) => {
const theme = useSelector((state: RootState) => state.openapiTheme.theme)
const cluster = useSelector((state: RootState) => state.cluster.cluster)
const params = useParams()
const urlParams = {
cluster: params.cluster,
namespace: params.namespace,
syntheticProject: params.syntheticProject,
name: params.name,
}
return (
)
}
```
--------------------------------
### React Router Configuration for OpenAPI UI Application
Source: https://context7.com/pro-robotech/openapi-ui/llms.txt
Defines the main routing structure for the OpenAPI UI application using React Router. It sets up routes for main pages, cluster-scoped views, and various resource management interfaces like tables, forms, and factories. Dependencies include react-router-dom, @tanstack/react-query, and antd.
```tsx
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ConfigProvider } from 'antd'
const queryClient = new QueryClient()
export const App = ({ isFederation, forcedTheme }) => {
const basePrefix = getBasePrefix(isFederation)
return (
}>
{/* Main pages */}
} />
} />
{/* Cluster-scoped routes with AppShell */}
}>
} />
} />
} />
} />
} />
} />
} />
)
}
```
--------------------------------
### Search Component: Kubernetes Resource Search (React/TypeScript)
Source: https://context7.com/pro-robotech/openapi-ui/llms.txt
The Search component enables searching across Kubernetes resources by kind, name, labels, and field selectors. It synchronizes search state with URL parameters using react-router-dom's useSearchParams and debouncing. It utilizes the PackageSearch component from '@prorobotech/openapi-k8s-toolkit' and Ant Design for UI elements.
```tsx
import { Search as PackageSearch, useKinds, LookingGlassIcon } from '@prorobotech/openapi-k8s-toolkit'
import { Form, Spin, Alert } from 'antd'
import { useSearchParams } from 'react-router-dom'
export const Search: FC = () => {
const [searchParams, setSearchParams] = useSearchParams()
const cluster = useSelector((state: RootState) => state.cluster.cluster)
const theme = useSelector((state: RootState) => state.openapiTheme.theme)
const [form] = Form.useForm()
// Fetch available kinds from the cluster
const { data: kindsData, isLoading, error } = useKinds({ cluster })
const watchedKinds = Form.useWatch('kinds', form)
const watchedName = Form.useWatch('name', form)
const watchedLabels = Form.useWatch('labels', form)
const watchedFields = Form.useWatch('fields', form)
// Sync form state to URL params with debouncing
const debouncedPushKinds = useDebouncedCallback((values: string[]) => {
const next = setArrayParam(searchParams, 'kinds', values)
setSearchParams(next, { replace: true })
}, 250)
if (isLoading) return
if (error) return
return (
<>
{watchedKinds?.map(kind => (
))}
>
)
}
```
--------------------------------
### Configure Express Server for API Proxying and Environment Injection (TypeScript)
Source: https://context7.com/pro-robotech/openapi-ui/llms.txt
This TypeScript code configures an Express server to handle API proxying to different services, inject dynamic environment variables into the frontend, and serve health check and metrics endpoints. It uses libraries like `express`, `http-proxy-middleware`, and `dotenv`. The server dynamically sets up proxies for local development and provides a JavaScript file with environment configurations for the React application.
```typescript
import express from 'express'
import http from 'http'
import { createProxyMiddleware } from 'http-proxy-middleware'
import dotenv from 'dotenv'
dotenv.config()
const app = express()
const basePrefix = process.env.BASEPREFIX
// Health check and metrics endpoints
app.use(`${basePrefix}/healthcheck`, healthcheck())
app.use(promBundle({ includeMethod: true, metricsPath: `${basePrefix}/metrics` }))
// API proxies for local development
if (process.env.LOCAL === 'true') {
app.use('/api/clusters/:clusterId/k8s', createProxyMiddleware({
target: `${KUBE_API_URL}/api/clusters`,
changeOrigin: true,
secure: false,
ws: true,
pathRewrite: (path) => path.replace(/^/api/clusters//, '/'),
}))
app.use('/clusterlist', createProxyMiddleware({
target: `${KUBE_API_URL}/clusterlist`,
changeOrigin: true,
}))
app.use('/openapi-bff', createProxyMiddleware({
target: BFF_URL,
changeOrigin: true,
}))
}
// Dynamic environment variables endpoint
app.get(`${basePrefix}/env.js`, (_, res) => {
res.set('Content-Type', 'text/javascript')
res.send(
`
window._env_ = {
BASEPREFIX: "${basePrefix}",
TITLE_TEXT: ${JSON.stringify(TITLE_TEXT)},
KUBE_API_URL: ${JSON.stringify(KUBE_API_URL)},
CUSTOMIZATION_API_GROUP: ${JSON.stringify(CUSTOMIZATION_API_GROUP)},
CUSTOMIZATION_API_VERSION: ${JSON.stringify(CUSTOMIZATION_API_VERSION)},
USE_NAMESPACE_NAV: ${JSON.stringify(USE_NAMESPACE_NAV)},
// ... additional configuration
}
`
)
})
const server = http.createServer(app)
server.listen(port, () => console.log(`Server running at port: ${port}`))
```
--------------------------------
### Redux Store Configuration for OpenAPI UI
Source: https://context7.com/pro-robotech/openapi-ui/llms.txt
Configures the Redux store using Redux Toolkit for centralized state management in the OpenAPI UI application. It defines reducers for theme, federation, base prefix, and cluster information. Includes type definitions for RootState and AppDispatch. Dependencies include @reduxjs/toolkit.
```typescript
import { configureStore } from '@reduxjs/toolkit'
import { themeSlice } from './theme/theme/theme'
import { federationSlice } from './federation/federation/federation'
import { baseprefixSlice } from './federation/federation/baseprefix'
import { clusterListSlice } from './clusterList/clusterList/clusterList'
import { clusterSlice } from './cluster/cluster/cluster'
export const store = configureStore({
reducer: {
openapiTheme: themeSlice.reducer,
federation: federationSlice.reducer,
baseprefix: baseprefixSlice.reducer,
clusterList: clusterListSlice.reducer,
cluster: clusterSlice.reducer,
},
})
export type RootState = ReturnType
export type AppDispatch = typeof store.dispatch
// Theme slice example
export const themeSlice = createSlice({
name: 'theme',
initialState: { theme: 'light' },
reducers: {
setTheme: (state, action: PayloadAction<'light' | 'dark'>) => {
state.theme = action.payload
},
},
})
```
--------------------------------
### useNavSelector Hook for Kubernetes Navigation Data
Source: https://context7.com/pro-robotech/openapi-ui/llms.txt
The useNavSelector hook fetches navigation data for Kubernetes clusters, projects, and instances. It utilizes the useK8sSmartResource hook from '@prorobotech/openapi-k8s-toolkit' to interact with the Kubernetes API. Dependencies include react-redux for state management. It returns mapped cluster and project data for sidebar navigation.
```typescript
import { useK8sSmartResource, TNavigationResource, TSingleResource } from '@prorobotech/openapi-k8s-toolkit'
import { useSelector } from 'react-redux'
import { RootState } from 'store/store'
export const useNavSelector = (cluster?: string, projectName?: string) => {
const clusterList = useSelector((state: RootState) => state.clusterList.clusterList)
// Fetch navigation configuration
const { data: navigationDataArr } = useK8sSmartResource<{ items: TNavigationResource[] }>({
cluster: cluster || '',
apiGroup: BASE_API_GROUP,
apiVersion: BASE_API_VERSION,
plural: BASE_CUSTOMIZATION_NAVIGATION_RESOURCE_PLURAL,
fieldSelector: `metadata.name=${BASE_CUSTOMIZATION_NAVIGATION_RESOURCE_NAME}`,
isEnabled: cluster !== undefined,
})
// Fetch projects
const { data: projects } = useK8sSmartResource<{ items: TSingleResource[] }>({
cluster: cluster || '',
apiGroup: BASE_PROJECTS_API_GROUP,
apiVersion: BASE_PROJECTS_API_VERSION,
plural: BASE_PROJECTS_PLURAL,
isEnabled: cluster !== undefined,
})
// Fetch instances
const { data: instances, isLoading, isError } = useK8sSmartResource<{ items: TSingleResource[] }>({
cluster: cluster || '',
apiGroup: BASE_INSTANCES_API_GROUP,
apiVersion: BASE_INSTANCES_API_VERSION,
plural: BASE_INSTANCES_PLURAL,
isEnabled: cluster !== undefined,
})
// Map to sidebar options
const clustersInSidebar = clusterList?.map(({ name }) => ({ value: name, label: name })) || []
const projectsInSidebar = projects?.items.map(item => ({
value: item.metadata.name,
label: item.metadata.name
})) || []
return { clustersInSidebar, projectsInSidebar, instancesInSidebar, allInstancesLoadingSuccess }
}
```
--------------------------------
### AppShell Component for Application Chrome - React (TypeScript)
Source: https://context7.com/pro-robotech/openapi-ui/llms.txt
The AppShell component provides the main application chrome, including sidebar, breadcrumbs, and context for child routes. It utilizes React Router DOM for navigation and hooks from '@prorobotech/openapi-k8s-toolkit' for pre-fetching Kubernetes kinds.
```tsx
import { useKinds } from '@prorobotech/openapi-k8s-toolkit'
import { Outlet, useParams } from 'react-router-dom'
import { ManageableSidebar, ManageableBreadcrumbs, BackLink } from 'components'
export type TChromeCtx = {
setCurrentTags: (tags?: string[]) => void
setSidebarSuffix: (suffix?: string) => void
setBreadcrumbsSuffix: (suffix?: string) => void
setBacklinkTo: (backlinkTo?: string) => void
setBacklinkTitle: (backlinkTitle?: string) => void
}
export const AppShell: FC<{ inside?: boolean }> = ({ inside }) => {
const { cluster, namespace, syntheticProject } = useParams()
const [currentTags, setCurrentTags] = useState()
const [sidebarSuffix, setSidebarSuffix] = useState()
const [backlinkTo, setBacklinkTo] = useState()
// Pre-fetch kinds for the cluster
const { data: kindsData } = useKinds({
cluster: cluster || '',
isEnabled: !!cluster,
refetchInterval: false,
})
const sidebarId = `${getSidebarIdPrefix({ instance: !!syntheticProject, project: !!namespace })}${sidebarSuffix ?? 'app-shell'}`
const ctx: TChromeCtx = {
setCurrentTags,
setSidebarSuffix,
setBreadcrumbsSuffix: setBreadcrumbsSuffix,
setBacklinkTo,
setBacklinkTitle,
}
return (
}>
{backlinkTo && }
)
}
```
--------------------------------
### TableApiBuiltin Component for Kubernetes Resource Table
Source: https://context7.com/pro-robotech/openapi-ui/llms.txt
The TableApiBuiltin component renders an enriched table for Kubernetes resources, supporting CRUD operations, permissions checking, and bulk delete. It uses '@prorobotech/openapi-k8s-toolkit' for table functionality and Ant Design components for UI elements. It fetches resource data and integrates with Redux for cluster and theme information.
```tsx
import { EnrichedTableProvider, usePermissions, DeleteModal, useK8sSmartResource } from '@prorobotech/openapi-k8s-toolkit'
import { Button, Flex } from 'antd'
import { PlusOutlined, MinusOutlined } from '@ant-design/icons'
export const TableApiBuiltin: FC = ({
namespace,
resourceType,
apiGroup,
apiVersion,
plural,
customizationIdPrefix,
}) => {
const cluster = useSelector((state: RootState) => state.cluster.cluster)
const theme = useSelector((state: RootState) => state.openapiTheme.theme)
const [selectedRowKeys, setSelectedRowKeys] = useState([])
// Check create permissions
const createPermission = usePermissions({
apiGroup: apiGroup || undefined,
plural,
namespace: params.namespace,
cluster,
verb: 'create',
refetchInterval: false,
})
// Fetch resource data
const { data: dataItems, isLoading, error } = useK8sSmartResource<{ items: TSingleResource[] }>({
cluster,
namespace,
apiGroup,
apiVersion: apiVersion || '',
plural,
})
return (
<>
{
setSelectedRowKeys(keys)
setSelectedRowsData(rows)
},
}}
/>
>
)
}
```
--------------------------------
### Factory Component: Dynamic UI Rendering from Kubernetes CRDs (React/TypeScript)
Source: https://context7.com/pro-robotech/openapi-ui/llms.txt
The Factory component dynamically renders UI components based on Kubernetes Factory CRD definitions. It supports configurable layouts and data fetching, utilizing hooks from '@prorobotech/openapi-k8s-toolkit' and Ant Design for UI elements. It fetches factory configurations and renders them using DynamicRendererWithProviders.
```tsx
import { DynamicRendererWithProviders, DynamicComponents, useK8sSmartResource, TFactoryResponse } from '@prorobotech/openapi-k8s-toolkit'
import { Result } from 'antd'
export const Factory: FC = ({ setSidebarTags }) => {
const theme = useSelector((state: RootState) => state.openapiTheme.theme)
const cluster = useSelector((state: RootState) => state.cluster.cluster)
const { key } = useParams()
// Fetch factory configuration from CRD
const { data: factoryData, isLoading } = useK8sSmartResource({
cluster,
apiGroup: BASE_API_GROUP,
apiVersion: BASE_API_VERSION,
plural: 'factories',
})
const { spec } = factoryData?.items.find(({ spec }) => spec.key === key) ?? { spec: undefined }
useEffect(() => {
setSidebarTags(spec?.sidebarTags || [])
}, [spec?.sidebarTags, setSidebarTags])
if (!spec) {
return
}
return (
)
}
```
--------------------------------
### useAuth Hook for Authentication in OpenAPI UI
Source: https://context7.com/pro-robotech/openapi-ui/llms.txt
A custom React hook that handles user authentication by calling the login API endpoint and processing the response. It manages loading states and errors, and extracts user information like full name and requester details. Dependencies include useState, useEffect from React, the login function from api/auth, and constants for field names.
```typescript
import { useState, useEffect } from 'react'
import { login } from 'api/auth'
import { LOGIN_USERNAME_FIELD } from 'constants/customizationApiGroupAndVersion'
export const useAuth = () => {
const [fullName, setFullName] = useState()
const [requester, setRequester] = useState<{ name: string; email: string }>()
const [loadingAuth, setLoadingAuth] = useState(false)
const [error, setError] = useState()
useEffect(() => {
setLoadingAuth(true)
login()
.then(data => {
if (data) {
const userNameFieldKey = LOGIN_USERNAME_FIELD as keyof typeof data
const username = userNameFieldKey in data ? data[userNameFieldKey].toString() : 'No field'
setFullName(username)
setRequester({ name: username, email: data.email })
}
})
.catch(err => setError(err instanceof Error ? err.message : 'Unknown error'))
.finally(() => setLoadingAuth(false))
}, [])
return { fullName, requester, loadingAuth, error }
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.