app-context.tsx 6.4 KB

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