dify/web/app/components/plugins/plugin-page/context.tsx

97 lines
2.5 KiB
TypeScript
Raw Normal View History

2024-10-12 11:33:12 +08:00
'use client'
import type { ReactNode } from 'react'
2024-10-12 16:34:02 +08:00
import {
useMemo,
2024-10-12 16:34:02 +08:00
useRef,
2024-10-15 19:20:59 +08:00
useState,
2024-10-12 16:34:02 +08:00
} from 'react'
import {
createContext,
useContextSelector,
} from 'use-context-selector'
import { useSelector as useAppContextSelector } from '@/context/app-context'
2024-11-08 16:11:50 +08:00
import type { PluginDetail } from '../types'
import type { FilterState } from './filter-management'
import { useTranslation } from 'react-i18next'
import { useTabSearchParams } from '@/hooks/use-tab-searchparams'
2024-10-12 11:33:12 +08:00
export type PluginPageContextValue = {
containerRef: React.RefObject<HTMLDivElement>
currentPluginDetail: PluginDetail | undefined
setCurrentPluginDetail: (plugin: PluginDetail) => void
filters: FilterState
setFilters: (filter: FilterState) => void
activeTab: string
setActiveTab: (tab: string) => void
options: Array<{ value: string, text: string }>
2024-10-12 11:33:12 +08:00
}
export const PluginPageContext = createContext<PluginPageContextValue>({
containerRef: { current: null },
2024-11-02 12:49:02 +08:00
currentPluginDetail: undefined,
2024-11-08 16:11:50 +08:00
setCurrentPluginDetail: () => { },
filters: {
categories: [],
tags: [],
searchQuery: '',
},
2024-11-08 16:11:50 +08:00
setFilters: () => { },
activeTab: '',
2024-11-08 16:11:50 +08:00
setActiveTab: () => { },
options: [],
2024-10-12 11:33:12 +08:00
})
type PluginPageContextProviderProps = {
children: ReactNode
}
2024-10-12 16:34:02 +08:00
export function usePluginPageContext(selector: (value: PluginPageContextValue) => any) {
return useContextSelector(PluginPageContext, selector)
}
2024-10-12 11:33:12 +08:00
export const PluginPageContextProvider = ({
children,
}: PluginPageContextProviderProps) => {
const { t } = useTranslation()
2024-10-12 11:33:12 +08:00
const containerRef = useRef<HTMLDivElement>(null)
const [filters, setFilters] = useState<FilterState>({
categories: [],
tags: [],
searchQuery: '',
})
const [currentPluginDetail, setCurrentPluginDetail] = useState<PluginDetail | undefined>()
const { enable_marketplace } = useAppContextSelector(s => s.systemFeatures)
const options = useMemo(() => {
return [
{ value: 'plugins', text: t('common.menus.plugins') },
...(
enable_marketplace
? [{ value: 'discover', text: 'Explore Marketplace' }]
: []
),
]
}, [t, enable_marketplace])
const [activeTab, setActiveTab] = useTabSearchParams({
defaultTab: options[0].value,
})
2024-10-12 16:34:02 +08:00
2024-10-12 11:33:12 +08:00
return (
2024-10-12 16:34:02 +08:00
<PluginPageContext.Provider
value={{
containerRef,
2024-11-02 12:49:02 +08:00
currentPluginDetail,
setCurrentPluginDetail,
filters,
setFilters,
activeTab,
setActiveTab,
options,
2024-10-12 16:34:02 +08:00
}}
>
2024-10-12 11:33:12 +08:00
{children}
</PluginPageContext.Provider>
)
}