app-context.tsx 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. 'use client'
  2. import { createRef, useCallback, useEffect, useMemo, useRef, useState } from 'react'
  3. import useSWR from 'swr'
  4. import { createContext, useContext, useContextSelector } from 'use-context-selector'
  5. import type { FC, ReactNode } from 'react'
  6. import { fetchAppList } from '@/service/apps'
  7. import Loading from '@/app/components/base/loading'
  8. import { fetchCurrentWorkspace, fetchLanggeniusVersion, fetchUserProfile, getSystemFeatures } from '@/service/common'
  9. import type { App } from '@/types/app'
  10. import { Theme } from '@/types/app'
  11. import type { ICurrentWorkspace, LangGeniusVersionResponse, UserProfileResponse } from '@/models/common'
  12. import MaintenanceNotice from '@/app/components/header/maintenance-notice'
  13. import type { SystemFeatures } from '@/types/feature'
  14. import { defaultSystemFeatures } from '@/types/feature'
  15. export type AppContextValue = {
  16. theme: Theme
  17. setTheme: (theme: Theme) => void
  18. apps: App[]
  19. systemFeatures: SystemFeatures
  20. mutateApps: VoidFunction
  21. userProfile: UserProfileResponse
  22. mutateUserProfile: VoidFunction
  23. currentWorkspace: ICurrentWorkspace
  24. isCurrentWorkspaceManager: boolean
  25. isCurrentWorkspaceOwner: boolean
  26. isCurrentWorkspaceEditor: boolean
  27. isCurrentWorkspaceDatasetOperator: boolean
  28. mutateCurrentWorkspace: VoidFunction
  29. pageContainerRef: React.RefObject<HTMLDivElement>
  30. langeniusVersionInfo: LangGeniusVersionResponse
  31. useSelector: typeof useSelector
  32. }
  33. const initialLangeniusVersionInfo = {
  34. current_env: '',
  35. current_version: '',
  36. latest_version: '',
  37. release_date: '',
  38. release_notes: '',
  39. version: '',
  40. can_auto_update: false,
  41. }
  42. const initialWorkspaceInfo: ICurrentWorkspace = {
  43. id: '',
  44. name: '',
  45. plan: '',
  46. status: '',
  47. created_at: 0,
  48. role: 'normal',
  49. providers: [],
  50. in_trail: true,
  51. }
  52. const AppContext = createContext<AppContextValue>({
  53. theme: Theme.light,
  54. systemFeatures: defaultSystemFeatures,
  55. setTheme: () => { },
  56. apps: [],
  57. mutateApps: () => { },
  58. userProfile: {
  59. id: '',
  60. name: '',
  61. email: '',
  62. avatar: '',
  63. is_password_set: false,
  64. },
  65. currentWorkspace: initialWorkspaceInfo,
  66. isCurrentWorkspaceManager: false,
  67. isCurrentWorkspaceOwner: false,
  68. isCurrentWorkspaceEditor: false,
  69. isCurrentWorkspaceDatasetOperator: false,
  70. mutateUserProfile: () => { },
  71. mutateCurrentWorkspace: () => { },
  72. pageContainerRef: createRef(),
  73. langeniusVersionInfo: initialLangeniusVersionInfo,
  74. useSelector,
  75. })
  76. export function useSelector<T>(selector: (value: AppContextValue) => T): T {
  77. return useContextSelector(AppContext, selector)
  78. }
  79. export type AppContextProviderProps = {
  80. children: ReactNode
  81. }
  82. export const AppContextProvider: FC<AppContextProviderProps> = ({ children }) => {
  83. const pageContainerRef = useRef<HTMLDivElement>(null)
  84. const { data: appList, mutate: mutateApps } = useSWR({ url: '/apps', params: { page: 1, limit: 30, name: '' } }, fetchAppList)
  85. const { data: userProfileResponse, mutate: mutateUserProfile } = useSWR({ url: '/account/profile', params: {} }, fetchUserProfile)
  86. const { data: currentWorkspaceResponse, mutate: mutateCurrentWorkspace } = useSWR({ url: '/workspaces/current', params: {} }, fetchCurrentWorkspace)
  87. const { data: systemFeatures } = useSWR({ url: '/console/system-features' }, getSystemFeatures, {
  88. fallbackData: defaultSystemFeatures,
  89. })
  90. const [userProfile, setUserProfile] = useState<UserProfileResponse>()
  91. const [langeniusVersionInfo, setLangeniusVersionInfo] = useState<LangGeniusVersionResponse>(initialLangeniusVersionInfo)
  92. const [currentWorkspace, setCurrentWorkspace] = useState<ICurrentWorkspace>(initialWorkspaceInfo)
  93. const isCurrentWorkspaceManager = useMemo(() => ['owner', 'admin'].includes(currentWorkspace.role), [currentWorkspace.role])
  94. const isCurrentWorkspaceOwner = useMemo(() => currentWorkspace.role === 'owner', [currentWorkspace.role])
  95. const isCurrentWorkspaceEditor = useMemo(() => ['owner', 'admin', 'editor'].includes(currentWorkspace.role), [currentWorkspace.role])
  96. const isCurrentWorkspaceDatasetOperator = useMemo(() => currentWorkspace.role === 'dataset_operator', [currentWorkspace.role])
  97. const updateUserProfileAndVersion = useCallback(async () => {
  98. if (userProfileResponse && !userProfileResponse.bodyUsed) {
  99. const result = await userProfileResponse.json()
  100. setUserProfile(result)
  101. const current_version = userProfileResponse.headers.get('x-version')
  102. const current_env = process.env.NODE_ENV === 'development' ? 'DEVELOPMENT' : userProfileResponse.headers.get('x-env')
  103. const versionData = await fetchLanggeniusVersion({ url: '/version', params: { current_version } })
  104. setLangeniusVersionInfo({ ...versionData, current_version, latest_version: versionData.version, current_env })
  105. }
  106. }, [userProfileResponse])
  107. useEffect(() => {
  108. updateUserProfileAndVersion()
  109. }, [updateUserProfileAndVersion, userProfileResponse])
  110. useEffect(() => {
  111. if (currentWorkspaceResponse)
  112. setCurrentWorkspace(currentWorkspaceResponse)
  113. }, [currentWorkspaceResponse])
  114. const [theme, setTheme] = useState<Theme>(Theme.light)
  115. const handleSetTheme = useCallback((theme: Theme) => {
  116. setTheme(theme)
  117. globalThis.document.documentElement.setAttribute('data-theme', theme)
  118. }, [])
  119. useEffect(() => {
  120. globalThis.document.documentElement.setAttribute('data-theme', theme)
  121. // eslint-disable-next-line react-hooks/exhaustive-deps
  122. }, [])
  123. if (!appList || !userProfile)
  124. return <Loading type='app' />
  125. return (
  126. <AppContext.Provider value={{
  127. theme,
  128. setTheme: handleSetTheme,
  129. apps: appList.data,
  130. systemFeatures: { ...defaultSystemFeatures, ...systemFeatures },
  131. mutateApps,
  132. userProfile,
  133. mutateUserProfile,
  134. pageContainerRef,
  135. langeniusVersionInfo,
  136. useSelector,
  137. currentWorkspace,
  138. isCurrentWorkspaceManager,
  139. isCurrentWorkspaceOwner,
  140. isCurrentWorkspaceEditor,
  141. isCurrentWorkspaceDatasetOperator,
  142. mutateCurrentWorkspace,
  143. }}>
  144. <div className='flex flex-col h-full overflow-y-auto'>
  145. {globalThis.document?.body?.getAttribute('data-public-maintenance-notice') && <MaintenanceNotice />}
  146. <div ref={pageContainerRef} className='grow relative flex flex-col overflow-y-auto overflow-x-hidden bg-background-body'>
  147. {children}
  148. </div>
  149. </div>
  150. </AppContext.Provider>
  151. )
  152. }
  153. export const useAppContext = () => useContext(AppContext)
  154. export default AppContext