You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

global-public-context.tsx 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use client'
  2. import { create } from 'zustand'
  3. import { useQuery } from '@tanstack/react-query'
  4. import type { FC, PropsWithChildren } from 'react'
  5. import { useEffect } from 'react'
  6. import type { SystemFeatures } from '@/types/feature'
  7. import { defaultSystemFeatures } from '@/types/feature'
  8. import { getSystemFeatures } from '@/service/common'
  9. import Loading from '@/app/components/base/loading'
  10. import { AccessMode } from '@/models/access-control'
  11. type GlobalPublicStore = {
  12. isGlobalPending: boolean
  13. setIsGlobalPending: (isPending: boolean) => void
  14. systemFeatures: SystemFeatures
  15. setSystemFeatures: (systemFeatures: SystemFeatures) => void
  16. webAppAccessMode: AccessMode,
  17. setWebAppAccessMode: (webAppAccessMode: AccessMode) => void
  18. }
  19. export const useGlobalPublicStore = create<GlobalPublicStore>(set => ({
  20. isGlobalPending: true,
  21. setIsGlobalPending: (isPending: boolean) => set(() => ({ isGlobalPending: isPending })),
  22. systemFeatures: defaultSystemFeatures,
  23. setSystemFeatures: (systemFeatures: SystemFeatures) => set(() => ({ systemFeatures })),
  24. webAppAccessMode: AccessMode.PUBLIC,
  25. setWebAppAccessMode: (webAppAccessMode: AccessMode) => set(() => ({ webAppAccessMode })),
  26. }))
  27. const GlobalPublicStoreProvider: FC<PropsWithChildren> = ({
  28. children,
  29. }) => {
  30. const { isPending, data } = useQuery({
  31. queryKey: ['systemFeatures'],
  32. queryFn: getSystemFeatures,
  33. })
  34. const { setSystemFeatures, setIsGlobalPending: setIsPending } = useGlobalPublicStore()
  35. useEffect(() => {
  36. if (data)
  37. setSystemFeatures({ ...defaultSystemFeatures, ...data })
  38. }, [data, setSystemFeatures])
  39. useEffect(() => {
  40. setIsPending(isPending)
  41. }, [isPending, setIsPending])
  42. if (isPending)
  43. return <div className='flex h-screen w-screen items-center justify-center'><Loading /></div>
  44. return <>{children}</>
  45. }
  46. export default GlobalPublicStoreProvider