context.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 'use client'
  2. import type { ReactNode } from 'react'
  3. import {
  4. useMemo,
  5. useRef,
  6. useState,
  7. } from 'react'
  8. import {
  9. createContext,
  10. useContextSelector,
  11. } from 'use-context-selector'
  12. import { useSelector as useAppContextSelector } from '@/context/app-context'
  13. import type { FilterState } from './filter-management'
  14. import { useTranslation } from 'react-i18next'
  15. import { useTabSearchParams } from '@/hooks/use-tab-searchparams'
  16. export type PluginPageContextValue = {
  17. containerRef: React.RefObject<HTMLDivElement>
  18. currentPluginID: string | undefined
  19. setCurrentPluginID: (pluginID?: string) => void
  20. filters: FilterState
  21. setFilters: (filter: FilterState) => void
  22. activeTab: string
  23. setActiveTab: (tab: string) => void
  24. options: Array<{ value: string, text: string }>
  25. }
  26. export const PluginPageContext = createContext<PluginPageContextValue>({
  27. containerRef: { current: null },
  28. currentPluginID: undefined,
  29. setCurrentPluginID: () => { },
  30. filters: {
  31. categories: [],
  32. tags: [],
  33. searchQuery: '',
  34. },
  35. setFilters: () => { },
  36. activeTab: '',
  37. setActiveTab: () => { },
  38. options: [],
  39. })
  40. type PluginPageContextProviderProps = {
  41. children: ReactNode
  42. }
  43. export function usePluginPageContext(selector: (value: PluginPageContextValue) => any) {
  44. return useContextSelector(PluginPageContext, selector)
  45. }
  46. export const PluginPageContextProvider = ({
  47. children,
  48. }: PluginPageContextProviderProps) => {
  49. const { t } = useTranslation()
  50. const containerRef = useRef<HTMLDivElement>(null)
  51. const [filters, setFilters] = useState<FilterState>({
  52. categories: [],
  53. tags: [],
  54. searchQuery: '',
  55. })
  56. const [currentPluginID, setCurrentPluginID] = useState<string | undefined>()
  57. const { enable_marketplace } = useAppContextSelector(s => s.systemFeatures)
  58. const options = useMemo(() => {
  59. return [
  60. { value: 'plugins', text: t('common.menus.plugins') },
  61. ...(
  62. enable_marketplace
  63. ? [{ value: 'discover', text: t('common.menus.exploreMarketplace') }]
  64. : []
  65. ),
  66. ]
  67. }, [t, enable_marketplace])
  68. const [activeTab, setActiveTab] = useTabSearchParams({
  69. defaultTab: options[0].value,
  70. })
  71. return (
  72. <PluginPageContext.Provider
  73. value={{
  74. containerRef,
  75. currentPluginID,
  76. setCurrentPluginID,
  77. filters,
  78. setFilters,
  79. activeTab,
  80. setActiveTab,
  81. options,
  82. }}
  83. >
  84. {children}
  85. </PluginPageContext.Provider>
  86. )
  87. }