dify
This commit is contained in:
91
dify/web/app/components/plugins/plugin-page/context.tsx
Normal file
91
dify/web/app/components/plugins/plugin-page/context.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode, RefObject } from 'react'
|
||||
import {
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react'
|
||||
import {
|
||||
createContext,
|
||||
useContextSelector,
|
||||
} from 'use-context-selector'
|
||||
import type { FilterState } from './filter-management'
|
||||
import { useTabSearchParams } from '@/hooks/use-tab-searchparams'
|
||||
import { noop } from 'lodash-es'
|
||||
import { PLUGIN_PAGE_TABS_MAP, usePluginPageTabs } from '../hooks'
|
||||
import { useGlobalPublicStore } from '@/context/global-public-context'
|
||||
|
||||
export type PluginPageContextValue = {
|
||||
containerRef: RefObject<HTMLDivElement | null>
|
||||
currentPluginID: string | undefined
|
||||
setCurrentPluginID: (pluginID?: string) => void
|
||||
filters: FilterState
|
||||
setFilters: (filter: FilterState) => void
|
||||
activeTab: string
|
||||
setActiveTab: (tab: string) => void
|
||||
options: Array<{ value: string, text: string }>
|
||||
}
|
||||
|
||||
const emptyContainerRef: RefObject<HTMLDivElement | null> = { current: null }
|
||||
|
||||
export const PluginPageContext = createContext<PluginPageContextValue>({
|
||||
containerRef: emptyContainerRef,
|
||||
currentPluginID: undefined,
|
||||
setCurrentPluginID: noop,
|
||||
filters: {
|
||||
categories: [],
|
||||
tags: [],
|
||||
searchQuery: '',
|
||||
},
|
||||
setFilters: noop,
|
||||
activeTab: '',
|
||||
setActiveTab: noop,
|
||||
options: [],
|
||||
})
|
||||
|
||||
type PluginPageContextProviderProps = {
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export function usePluginPageContext(selector: (value: PluginPageContextValue) => any) {
|
||||
return useContextSelector(PluginPageContext, selector)
|
||||
}
|
||||
|
||||
export const PluginPageContextProvider = ({
|
||||
children,
|
||||
}: PluginPageContextProviderProps) => {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null)
|
||||
const [filters, setFilters] = useState<FilterState>({
|
||||
categories: [],
|
||||
tags: [],
|
||||
searchQuery: '',
|
||||
})
|
||||
const [currentPluginID, setCurrentPluginID] = useState<string | undefined>()
|
||||
|
||||
const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
|
||||
const tabs = usePluginPageTabs()
|
||||
const options = useMemo(() => {
|
||||
return enable_marketplace ? tabs : tabs.filter(tab => tab.value !== PLUGIN_PAGE_TABS_MAP.marketplace)
|
||||
}, [tabs, enable_marketplace])
|
||||
const [activeTab, setActiveTab] = useTabSearchParams({
|
||||
defaultTab: options[0].value,
|
||||
})
|
||||
|
||||
return (
|
||||
<PluginPageContext.Provider
|
||||
value={{
|
||||
containerRef,
|
||||
currentPluginID,
|
||||
setCurrentPluginID,
|
||||
filters,
|
||||
setFilters,
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
options,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</PluginPageContext.Provider>
|
||||
)
|
||||
}
|
||||
67
dify/web/app/components/plugins/plugin-page/debug-info.tsx
Normal file
67
dify/web/app/components/plugins/plugin-page/debug-info.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import { useContext } from 'use-context-selector'
|
||||
import I18n from '@/context/i18n'
|
||||
import {
|
||||
RiArrowRightUpLine,
|
||||
RiBugLine,
|
||||
} from '@remixicon/react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import KeyValueItem from '../base/key-value-item'
|
||||
import Tooltip from '@/app/components/base/tooltip'
|
||||
import Button from '@/app/components/base/button'
|
||||
import { getDocsUrl } from '@/app/components/plugins/utils'
|
||||
import { useDebugKey } from '@/service/use-plugins'
|
||||
|
||||
const i18nPrefix = 'plugin.debugInfo'
|
||||
|
||||
const DebugInfo: FC = () => {
|
||||
const { t } = useTranslation()
|
||||
const { locale } = useContext(I18n)
|
||||
const { data: info, isLoading } = useDebugKey()
|
||||
|
||||
// info.key likes 4580bdb7-b878-471c-a8a4-bfd760263a53 mask the middle part using *.
|
||||
const maskedKey = info?.key?.replace(/(.{8})(.*)(.{8})/, '$1********$3')
|
||||
|
||||
if (isLoading) return null
|
||||
|
||||
return (
|
||||
<Tooltip
|
||||
triggerMethod='click'
|
||||
disabled={!info}
|
||||
popupContent={
|
||||
<>
|
||||
<div className='flex items-center gap-1 self-stretch'>
|
||||
<span className='system-sm-semibold flex shrink-0 grow basis-0 flex-col items-start justify-center text-text-secondary'>{t(`${i18nPrefix}.title`)}</span>
|
||||
<a href={getDocsUrl(locale, '/plugins/quick-start/debug-plugin')} target='_blank' className='flex cursor-pointer items-center gap-0.5 text-text-accent-light-mode-only'>
|
||||
<span className='system-xs-medium'>{t(`${i18nPrefix}.viewDocs`)}</span>
|
||||
<RiArrowRightUpLine className='h-3 w-3' />
|
||||
</a>
|
||||
</div>
|
||||
<div className='space-y-0.5'>
|
||||
<KeyValueItem
|
||||
label={'URL'}
|
||||
value={`${info?.host}:${info?.port}`}
|
||||
/>
|
||||
<KeyValueItem
|
||||
label={'Key'}
|
||||
value={info?.key || ''}
|
||||
maskedValue={maskedKey}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
popupClassName='flex flex-col items-start w-[256px] px-4 py-3.5 gap-1 border border-components-panel-border
|
||||
rounded-xl bg-components-tooltip-bg shadows-shadow-lg z-50'
|
||||
asChild={false}
|
||||
position='bottom'
|
||||
>
|
||||
<Button className='h-full w-full p-2 text-components-button-secondary-text'>
|
||||
<RiBugLine className='h-4 w-4' />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(DebugInfo)
|
||||
136
dify/web/app/components/plugins/plugin-page/empty/index.tsx
Normal file
136
dify/web/app/components/plugins/plugin-page/empty/index.tsx
Normal file
@@ -0,0 +1,136 @@
|
||||
'use client'
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { MagicBox } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
|
||||
import { FileZip } from '@/app/components/base/icons/src/vender/solid/files'
|
||||
import { Github } from '@/app/components/base/icons/src/vender/solid/general'
|
||||
import InstallFromGitHub from '@/app/components/plugins/install-plugin/install-from-github'
|
||||
import InstallFromLocalPackage from '@/app/components/plugins/install-plugin/install-from-local-package'
|
||||
import { usePluginPageContext } from '../context'
|
||||
import { Group } from '@/app/components/base/icons/src/vender/other'
|
||||
import Line from '../../marketplace/empty/line'
|
||||
import { useInstalledPluginList } from '@/service/use-plugins'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
|
||||
import { noop } from 'lodash-es'
|
||||
import { useGlobalPublicStore } from '@/context/global-public-context'
|
||||
import Button from '@/app/components/base/button'
|
||||
|
||||
type InstallMethod = {
|
||||
icon: React.FC<{ className?: string }>
|
||||
text: string
|
||||
action: string
|
||||
}
|
||||
|
||||
const Empty = () => {
|
||||
const { t } = useTranslation()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [selectedAction, setSelectedAction] = useState<string | null>(null)
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const { enable_marketplace, plugin_installation_permission } = useGlobalPublicStore(s => s.systemFeatures)
|
||||
const setActiveTab = usePluginPageContext(v => v.setActiveTab)
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (file) {
|
||||
setSelectedFile(file)
|
||||
setSelectedAction('local')
|
||||
}
|
||||
}
|
||||
const filters = usePluginPageContext(v => v.filters)
|
||||
const { data: pluginList } = useInstalledPluginList()
|
||||
|
||||
const text = useMemo(() => {
|
||||
if (pluginList?.plugins.length === 0)
|
||||
return t('plugin.list.noInstalled')
|
||||
if (filters.categories.length > 0 || filters.tags.length > 0 || filters.searchQuery)
|
||||
return t('plugin.list.notFound')
|
||||
}, [pluginList?.plugins.length, t, filters.categories.length, filters.tags.length, filters.searchQuery])
|
||||
|
||||
const [installMethods, setInstallMethods] = useState<InstallMethod[]>([])
|
||||
useEffect(() => {
|
||||
const methods = []
|
||||
if (enable_marketplace)
|
||||
methods.push({ icon: MagicBox, text: t('plugin.source.marketplace'), action: 'marketplace' })
|
||||
|
||||
if (plugin_installation_permission.restrict_to_marketplace_only) {
|
||||
setInstallMethods(methods)
|
||||
}
|
||||
else {
|
||||
methods.push({ icon: Github, text: t('plugin.source.github'), action: 'github' })
|
||||
methods.push({ icon: FileZip, text: t('plugin.source.local'), action: 'local' })
|
||||
setInstallMethods(methods)
|
||||
}
|
||||
}, [plugin_installation_permission, enable_marketplace, t])
|
||||
|
||||
return (
|
||||
<div className='relative z-0 w-full grow'>
|
||||
{/* skeleton */}
|
||||
<div className='absolute top-0 z-10 grid h-full w-full grid-cols-2 gap-2 overflow-hidden px-12'>
|
||||
{Array.from({ length: 20 }).fill(0).map((_, i) => (
|
||||
<div key={i} className='h-24 rounded-xl bg-components-card-bg' />
|
||||
))}
|
||||
</div>
|
||||
{/* mask */}
|
||||
<div className='absolute z-20 h-full w-full bg-gradient-to-b from-components-panel-bg-transparent to-components-panel-bg' />
|
||||
<div className='relative z-30 flex h-full items-center justify-center'>
|
||||
<div className='flex flex-col items-center gap-y-3'>
|
||||
<div className='relative -z-10 flex size-14 items-center justify-center rounded-xl
|
||||
border-[1px] border-dashed border-divider-deep bg-components-card-bg shadow-xl shadow-shadow-shadow-5'>
|
||||
<Group className='h-5 w-5 text-text-tertiary' />
|
||||
<Line className='absolute right-[-1px] top-1/2 -translate-y-1/2' />
|
||||
<Line className='absolute left-[-1px] top-1/2 -translate-y-1/2' />
|
||||
<Line className='absolute left-1/2 top-0 -translate-x-1/2 -translate-y-1/2 rotate-90' />
|
||||
<Line className='absolute left-1/2 top-full -translate-x-1/2 -translate-y-1/2 rotate-90' />
|
||||
</div>
|
||||
<div className='system-md-regular text-text-tertiary'>
|
||||
{text}
|
||||
</div>
|
||||
<div className='flex w-[236px] flex-col'>
|
||||
<input
|
||||
type='file'
|
||||
ref={fileInputRef}
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFileChange}
|
||||
accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
|
||||
/>
|
||||
<div className='flex w-full flex-col gap-y-1'>
|
||||
{installMethods.map(({ icon: Icon, text, action }) => (
|
||||
<Button
|
||||
key={action}
|
||||
className='justify-start gap-x-0.5 px-3'
|
||||
onClick={() => {
|
||||
if (action === 'local')
|
||||
fileInputRef.current?.click()
|
||||
else if (action === 'marketplace')
|
||||
setActiveTab('discover')
|
||||
else
|
||||
setSelectedAction(action)
|
||||
}}
|
||||
>
|
||||
<Icon className='size-4' />
|
||||
<span className='px-0.5'>{text}</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{selectedAction === 'github' && <InstallFromGitHub
|
||||
onSuccess={noop}
|
||||
onClose={() => setSelectedAction(null)}
|
||||
/>}
|
||||
{selectedAction === 'local' && selectedFile
|
||||
&& (<InstallFromLocalPackage
|
||||
file={selectedFile}
|
||||
onClose={() => setSelectedAction(null)}
|
||||
onSuccess={noop}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Empty.displayName = 'Empty'
|
||||
|
||||
export default React.memo(Empty)
|
||||
@@ -0,0 +1,127 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
RiArrowDownSLine,
|
||||
RiCloseCircleFill,
|
||||
} from '@remixicon/react'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import Checkbox from '@/app/components/base/checkbox'
|
||||
import cn from '@/utils/classnames'
|
||||
import Input from '@/app/components/base/input'
|
||||
import { useCategories } from '../../hooks'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type CategoriesFilterProps = {
|
||||
value: string[]
|
||||
onChange: (categories: string[]) => void
|
||||
}
|
||||
const CategoriesFilter = ({
|
||||
value,
|
||||
onChange,
|
||||
}: CategoriesFilterProps) => {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const { categories: options, categoriesMap } = useCategories()
|
||||
const filteredOptions = options.filter(option => option.name.toLowerCase().includes(searchText.toLowerCase()))
|
||||
const handleCheck = (id: string) => {
|
||||
if (value.includes(id))
|
||||
onChange(value.filter(tag => tag !== id))
|
||||
else
|
||||
onChange([...value, id])
|
||||
}
|
||||
const selectedTagsLength = value.length
|
||||
|
||||
return (
|
||||
<PortalToFollowElem
|
||||
placement='bottom-start'
|
||||
offset={{
|
||||
mainAxis: 4,
|
||||
}}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
>
|
||||
<PortalToFollowElemTrigger onClick={() => setOpen(v => !v)}>
|
||||
<div className={cn(
|
||||
'flex h-8 cursor-pointer items-center rounded-lg bg-components-input-bg-normal px-2 py-1 text-text-tertiary hover:bg-state-base-hover-alt',
|
||||
selectedTagsLength && 'text-text-secondary',
|
||||
open && 'bg-state-base-hover',
|
||||
)}>
|
||||
<div className={cn(
|
||||
'system-sm-medium flex items-center p-1',
|
||||
)}>
|
||||
{
|
||||
!selectedTagsLength && t('plugin.allCategories')
|
||||
}
|
||||
{
|
||||
!!selectedTagsLength && value.map(val => categoriesMap[val].label).slice(0, 2).join(',')
|
||||
}
|
||||
{
|
||||
selectedTagsLength > 2 && (
|
||||
<div className='system-xs-medium ml-1 text-text-tertiary'>
|
||||
+{selectedTagsLength - 2}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
{
|
||||
!!selectedTagsLength && (
|
||||
<RiCloseCircleFill
|
||||
className='h-4 w-4 cursor-pointer text-text-quaternary'
|
||||
onClick={
|
||||
(e) => {
|
||||
e.stopPropagation()
|
||||
onChange([])
|
||||
}
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
!selectedTagsLength && (
|
||||
<RiArrowDownSLine className='h-4 w-4' />
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</PortalToFollowElemTrigger>
|
||||
<PortalToFollowElemContent className='z-10'>
|
||||
<div className='w-[240px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm'>
|
||||
<div className='p-2 pb-1'>
|
||||
<Input
|
||||
showLeftIcon
|
||||
value={searchText}
|
||||
onChange={e => setSearchText(e.target.value)}
|
||||
placeholder={t('plugin.searchCategories')}
|
||||
/>
|
||||
</div>
|
||||
<div className='max-h-[448px] overflow-y-auto p-1'>
|
||||
{
|
||||
filteredOptions.map(option => (
|
||||
<div
|
||||
key={option.name}
|
||||
className='flex h-7 cursor-pointer items-center rounded-lg px-2 py-1.5 hover:bg-state-base-hover'
|
||||
onClick={() => handleCheck(option.name)}
|
||||
>
|
||||
<Checkbox
|
||||
className='mr-1'
|
||||
checked={value.includes(option.name)}
|
||||
/>
|
||||
<div className='system-sm-medium px-1 text-text-secondary'>
|
||||
{option.label}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</PortalToFollowElemContent>
|
||||
</PortalToFollowElem>
|
||||
)
|
||||
}
|
||||
|
||||
export default CategoriesFilter
|
||||
@@ -0,0 +1,11 @@
|
||||
export type Tag = {
|
||||
id: string
|
||||
name: string
|
||||
type: string
|
||||
binding_count: number
|
||||
}
|
||||
|
||||
export type Category = {
|
||||
name: 'model' | 'tool' | 'extension' | 'bundle'
|
||||
binding_count: number
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import React, { useState } from 'react'
|
||||
import CategoriesFilter from './category-filter'
|
||||
import TagFilter from './tag-filter'
|
||||
import SearchBox from './search-box'
|
||||
import { usePluginPageContext } from '../context'
|
||||
|
||||
export type FilterState = {
|
||||
categories: string[]
|
||||
tags: string[]
|
||||
searchQuery: string
|
||||
}
|
||||
|
||||
type FilterManagementProps = {
|
||||
onFilterChange: (filters: FilterState) => void
|
||||
}
|
||||
|
||||
const FilterManagement: React.FC<FilterManagementProps> = ({ onFilterChange }) => {
|
||||
const initFilters = usePluginPageContext(v => v.filters) as FilterState
|
||||
const [filters, setFilters] = useState<FilterState>(initFilters)
|
||||
|
||||
const updateFilters = (newFilters: Partial<FilterState>) => {
|
||||
const updatedFilters = { ...filters, ...newFilters }
|
||||
setFilters(updatedFilters)
|
||||
onFilterChange(updatedFilters)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='flex items-center gap-2 self-stretch'>
|
||||
<CategoriesFilter
|
||||
value={filters.categories}
|
||||
onChange={categories => updateFilters({ categories })}
|
||||
/>
|
||||
<TagFilter
|
||||
value={filters.tags}
|
||||
onChange={tags => updateFilters({ tags })}
|
||||
/>
|
||||
<SearchBox
|
||||
searchQuery={filters.searchQuery}
|
||||
onChange={searchQuery => updateFilters({ searchQuery })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default FilterManagement
|
||||
@@ -0,0 +1,30 @@
|
||||
'use client'
|
||||
|
||||
import Input from '@/app/components/base/input'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
type SearchBoxProps = {
|
||||
searchQuery: string
|
||||
onChange: (query: string) => void
|
||||
}
|
||||
|
||||
const SearchBox: React.FC<SearchBoxProps> = ({
|
||||
searchQuery,
|
||||
onChange,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<Input
|
||||
wrapperClassName='flex w-[200px] items-center rounded-lg'
|
||||
className='bg-components-input-bg-normal'
|
||||
showLeftIcon
|
||||
value={searchQuery}
|
||||
placeholder={t('plugin.search')}
|
||||
onChange={(e) => {
|
||||
onChange(e.target.value)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default SearchBox
|
||||
@@ -0,0 +1,27 @@
|
||||
import { create } from 'zustand'
|
||||
import type { Category, Tag } from './constant'
|
||||
|
||||
type State = {
|
||||
tagList: Tag[]
|
||||
categoryList: Category[]
|
||||
showTagManagementModal: boolean
|
||||
showCategoryManagementModal: boolean
|
||||
}
|
||||
|
||||
type Action = {
|
||||
setTagList: (tagList?: Tag[]) => void
|
||||
setCategoryList: (categoryList?: Category[]) => void
|
||||
setShowTagManagementModal: (showTagManagementModal: boolean) => void
|
||||
setShowCategoryManagementModal: (showCategoryManagementModal: boolean) => void
|
||||
}
|
||||
|
||||
export const useStore = create<State & Action>(set => ({
|
||||
tagList: [],
|
||||
categoryList: [],
|
||||
setTagList: tagList => set(() => ({ tagList })),
|
||||
setCategoryList: categoryList => set(() => ({ categoryList })),
|
||||
showTagManagementModal: false,
|
||||
showCategoryManagementModal: false,
|
||||
setShowTagManagementModal: showTagManagementModal => set(() => ({ showTagManagementModal })),
|
||||
setShowCategoryManagementModal: showCategoryManagementModal => set(() => ({ showCategoryManagementModal })),
|
||||
}))
|
||||
@@ -0,0 +1,122 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
RiArrowDownSLine,
|
||||
RiCloseCircleFill,
|
||||
} from '@remixicon/react'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import Checkbox from '@/app/components/base/checkbox'
|
||||
import cn from '@/utils/classnames'
|
||||
import Input from '@/app/components/base/input'
|
||||
import { useTags } from '../../hooks'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type TagsFilterProps = {
|
||||
value: string[]
|
||||
onChange: (tags: string[]) => void
|
||||
}
|
||||
const TagsFilter = ({
|
||||
value,
|
||||
onChange,
|
||||
}: TagsFilterProps) => {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const { tags: options, getTagLabel } = useTags()
|
||||
const filteredOptions = options.filter(option => option.name.toLowerCase().includes(searchText.toLowerCase()))
|
||||
const handleCheck = (id: string) => {
|
||||
if (value.includes(id))
|
||||
onChange(value.filter(tag => tag !== id))
|
||||
else
|
||||
onChange([...value, id])
|
||||
}
|
||||
const selectedTagsLength = value.length
|
||||
|
||||
return (
|
||||
<PortalToFollowElem
|
||||
placement='bottom-start'
|
||||
offset={{
|
||||
mainAxis: 4,
|
||||
}}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
>
|
||||
<PortalToFollowElemTrigger onClick={() => setOpen(v => !v)}>
|
||||
<div className={cn(
|
||||
'flex h-8 cursor-pointer select-none items-center rounded-lg bg-components-input-bg-normal px-2 py-1 text-text-tertiary hover:bg-state-base-hover-alt',
|
||||
selectedTagsLength && 'text-text-secondary',
|
||||
open && 'bg-state-base-hover',
|
||||
)}>
|
||||
<div className={cn(
|
||||
'system-sm-medium flex items-center p-1',
|
||||
)}>
|
||||
{
|
||||
!selectedTagsLength && t('pluginTags.allTags')
|
||||
}
|
||||
{
|
||||
!!selectedTagsLength && value.map(val => getTagLabel(val)).slice(0, 2).join(',')
|
||||
}
|
||||
{
|
||||
selectedTagsLength > 2 && (
|
||||
<div className='system-xs-medium ml-1 text-text-tertiary'>
|
||||
+{selectedTagsLength - 2}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
{
|
||||
!!selectedTagsLength && (
|
||||
<RiCloseCircleFill
|
||||
className='h-4 w-4 cursor-pointer text-text-quaternary'
|
||||
onClick={() => onChange([])}
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
!selectedTagsLength && (
|
||||
<RiArrowDownSLine className='h-4 w-4' />
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</PortalToFollowElemTrigger>
|
||||
<PortalToFollowElemContent className='z-10'>
|
||||
<div className='w-[240px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm'>
|
||||
<div className='p-2 pb-1'>
|
||||
<Input
|
||||
showLeftIcon
|
||||
value={searchText}
|
||||
onChange={e => setSearchText(e.target.value)}
|
||||
placeholder={t('pluginTags.searchTags')}
|
||||
/>
|
||||
</div>
|
||||
<div className='max-h-[448px] overflow-y-auto p-1'>
|
||||
{
|
||||
filteredOptions.map(option => (
|
||||
<div
|
||||
key={option.name}
|
||||
className='flex h-7 cursor-pointer select-none items-center rounded-lg px-2 py-1.5 hover:bg-state-base-hover'
|
||||
onClick={() => handleCheck(option.name)}
|
||||
>
|
||||
<Checkbox
|
||||
className='mr-1'
|
||||
checked={value.includes(option.name)}
|
||||
/>
|
||||
<div className='system-sm-medium px-1 text-text-secondary'>
|
||||
{option.label}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</PortalToFollowElemContent>
|
||||
</PortalToFollowElem>
|
||||
)
|
||||
}
|
||||
|
||||
export default TagsFilter
|
||||
313
dify/web/app/components/plugins/plugin-page/index.tsx
Normal file
313
dify/web/app/components/plugins/plugin-page/index.tsx
Normal file
@@ -0,0 +1,313 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useContext } from 'use-context-selector'
|
||||
import Link from 'next/link'
|
||||
import {
|
||||
RiBookOpenLine,
|
||||
RiDragDropLine,
|
||||
RiEqualizer2Line,
|
||||
} from '@remixicon/react'
|
||||
import { useBoolean } from 'ahooks'
|
||||
import InstallFromLocalPackage from '../install-plugin/install-from-local-package'
|
||||
import {
|
||||
PluginPageContextProvider,
|
||||
usePluginPageContext,
|
||||
} from './context'
|
||||
import InstallPluginDropdown from './install-plugin-dropdown'
|
||||
import { useUploader } from './use-uploader'
|
||||
import useReferenceSetting from './use-reference-setting'
|
||||
import DebugInfo from './debug-info'
|
||||
import PluginTasks from './plugin-tasks'
|
||||
import Button from '@/app/components/base/button'
|
||||
import TabSlider from '@/app/components/base/tab-slider'
|
||||
import Tooltip from '@/app/components/base/tooltip'
|
||||
import cn from '@/utils/classnames'
|
||||
import ReferenceSettingModal from '@/app/components/plugins/reference-setting-modal/modal'
|
||||
import InstallFromMarketplace from '../install-plugin/install-from-marketplace'
|
||||
import {
|
||||
useRouter,
|
||||
useSearchParams,
|
||||
} from 'next/navigation'
|
||||
import type { Dependency } from '../types'
|
||||
import type { PluginDeclaration, PluginManifestInMarket } from '../types'
|
||||
import { sleep } from '@/utils'
|
||||
import { getDocsUrl } from '@/app/components/plugins/utils'
|
||||
import { fetchBundleInfoFromMarketPlace, fetchManifestFromMarketPlace } from '@/service/plugins'
|
||||
import { MARKETPLACE_API_PREFIX } from '@/config'
|
||||
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
|
||||
import I18n from '@/context/i18n'
|
||||
import { noop } from 'lodash-es'
|
||||
import { PLUGIN_TYPE_SEARCH_MAP } from '../marketplace/plugin-type-switch'
|
||||
import { PLUGIN_PAGE_TABS_MAP } from '../hooks'
|
||||
import { useGlobalPublicStore } from '@/context/global-public-context'
|
||||
import useDocumentTitle from '@/hooks/use-document-title'
|
||||
|
||||
const PACKAGE_IDS_KEY = 'package-ids'
|
||||
const BUNDLE_INFO_KEY = 'bundle-info'
|
||||
|
||||
export type PluginPageProps = {
|
||||
plugins: React.ReactNode
|
||||
marketplace: React.ReactNode
|
||||
}
|
||||
const PluginPage = ({
|
||||
plugins,
|
||||
marketplace,
|
||||
}: PluginPageProps) => {
|
||||
const { t } = useTranslation()
|
||||
const { locale } = useContext(I18n)
|
||||
const searchParams = useSearchParams()
|
||||
const { replace } = useRouter()
|
||||
useDocumentTitle(t('plugin.metadata.title'))
|
||||
|
||||
// just support install one package now
|
||||
const packageId = useMemo(() => {
|
||||
const idStrings = searchParams.get(PACKAGE_IDS_KEY)
|
||||
try {
|
||||
return idStrings ? JSON.parse(idStrings)[0] : ''
|
||||
}
|
||||
catch {
|
||||
return ''
|
||||
}
|
||||
}, [searchParams])
|
||||
|
||||
const [uniqueIdentifier, setUniqueIdentifier] = useState<string | null>(null)
|
||||
|
||||
const [dependencies, setDependencies] = useState<Dependency[]>([])
|
||||
const bundleInfo = useMemo(() => {
|
||||
const info = searchParams.get(BUNDLE_INFO_KEY)
|
||||
try {
|
||||
return info ? JSON.parse(info) : undefined
|
||||
}
|
||||
catch {
|
||||
return undefined
|
||||
}
|
||||
}, [searchParams])
|
||||
|
||||
const [isShowInstallFromMarketplace, {
|
||||
setTrue: showInstallFromMarketplace,
|
||||
setFalse: doHideInstallFromMarketplace,
|
||||
}] = useBoolean(false)
|
||||
|
||||
const hideInstallFromMarketplace = () => {
|
||||
doHideInstallFromMarketplace()
|
||||
const url = new URL(window.location.href)
|
||||
url.searchParams.delete(PACKAGE_IDS_KEY)
|
||||
url.searchParams.delete(BUNDLE_INFO_KEY)
|
||||
replace(url.toString())
|
||||
}
|
||||
const [manifest, setManifest] = useState<PluginDeclaration | PluginManifestInMarket | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
setUniqueIdentifier(null)
|
||||
await sleep(100)
|
||||
if (packageId) {
|
||||
const { data } = await fetchManifestFromMarketPlace(encodeURIComponent(packageId))
|
||||
const { plugin, version } = data
|
||||
setManifest({
|
||||
...plugin,
|
||||
version: version.version,
|
||||
icon: `${MARKETPLACE_API_PREFIX}/plugins/${plugin.org}/${plugin.name}/icon`,
|
||||
})
|
||||
setUniqueIdentifier(packageId)
|
||||
showInstallFromMarketplace()
|
||||
return
|
||||
}
|
||||
if (bundleInfo) {
|
||||
const { data } = await fetchBundleInfoFromMarketPlace(bundleInfo)
|
||||
setDependencies(data.version.dependencies)
|
||||
showInstallFromMarketplace()
|
||||
}
|
||||
})()
|
||||
}, [packageId, bundleInfo])
|
||||
|
||||
const {
|
||||
referenceSetting,
|
||||
canManagement,
|
||||
canDebugger,
|
||||
canSetPermissions,
|
||||
setReferenceSettings,
|
||||
} = useReferenceSetting()
|
||||
const [showPluginSettingModal, {
|
||||
setTrue: setShowPluginSettingModal,
|
||||
setFalse: setHidePluginSettingModal,
|
||||
}] = useBoolean(false)
|
||||
const [currentFile, setCurrentFile] = useState<File | null>(null)
|
||||
const containerRef = usePluginPageContext(v => v.containerRef)
|
||||
const options = usePluginPageContext(v => v.options)
|
||||
const activeTab = usePluginPageContext(v => v.activeTab)
|
||||
const setActiveTab = usePluginPageContext(v => v.setActiveTab)
|
||||
const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
|
||||
|
||||
const isPluginsTab = useMemo(() => activeTab === PLUGIN_PAGE_TABS_MAP.plugins, [activeTab])
|
||||
const isExploringMarketplace = useMemo(() => {
|
||||
const values = Object.values(PLUGIN_TYPE_SEARCH_MAP)
|
||||
return activeTab === PLUGIN_PAGE_TABS_MAP.marketplace || values.includes(activeTab)
|
||||
}, [activeTab])
|
||||
|
||||
const handleFileChange = (file: File | null) => {
|
||||
if (!file || !file.name.endsWith('.difypkg')) {
|
||||
setCurrentFile(null)
|
||||
return
|
||||
}
|
||||
|
||||
setCurrentFile(file)
|
||||
}
|
||||
const uploaderProps = useUploader({
|
||||
onFileChange: handleFileChange,
|
||||
containerRef,
|
||||
enabled: isPluginsTab && canManagement,
|
||||
})
|
||||
|
||||
const { dragging, fileUploader, fileChangeHandle, removeFile } = uploaderProps
|
||||
return (
|
||||
<div
|
||||
id='marketplace-container'
|
||||
ref={containerRef}
|
||||
style={{ scrollbarGutter: 'stable' }}
|
||||
className={cn('relative flex grow flex-col overflow-y-auto border-t border-divider-subtle', isPluginsTab
|
||||
? 'rounded-t-xl bg-components-panel-bg'
|
||||
: 'bg-background-body',
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'sticky top-0 z-10 flex min-h-[60px] items-center gap-1 self-stretch bg-components-panel-bg px-12 pb-2 pt-4', isExploringMarketplace && 'bg-background-body',
|
||||
)}
|
||||
>
|
||||
<div className='flex w-full items-center justify-between'>
|
||||
<div className='flex-1'>
|
||||
<TabSlider
|
||||
value={isPluginsTab ? PLUGIN_PAGE_TABS_MAP.plugins : PLUGIN_PAGE_TABS_MAP.marketplace}
|
||||
onChange={setActiveTab}
|
||||
options={options}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex shrink-0 items-center gap-1'>
|
||||
{
|
||||
isExploringMarketplace && (
|
||||
<>
|
||||
<Link
|
||||
href='https://github.com/langgenius/dify-plugins/issues/new?template=plugin_request.yaml'
|
||||
target='_blank'
|
||||
>
|
||||
<Button
|
||||
variant='ghost'
|
||||
className='text-text-tertiary'
|
||||
>
|
||||
{t('plugin.requestAPlugin')}
|
||||
</Button>
|
||||
</Link>
|
||||
<Link
|
||||
href={getDocsUrl(locale, '/plugins/publish-plugins/publish-to-dify-marketplace/README')}
|
||||
target='_blank'
|
||||
>
|
||||
<Button
|
||||
className='px-3'
|
||||
variant='secondary-accent'
|
||||
>
|
||||
<RiBookOpenLine className='mr-1 h-4 w-4' />
|
||||
{t('plugin.publishPlugins')}
|
||||
</Button>
|
||||
</Link>
|
||||
<div className='mx-1 h-3.5 w-[1px] shrink-0 bg-divider-regular'></div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
<PluginTasks />
|
||||
{canManagement && (
|
||||
<InstallPluginDropdown
|
||||
onSwitchToMarketplaceTab={() => setActiveTab('discover')}
|
||||
/>
|
||||
)}
|
||||
{
|
||||
canDebugger && (
|
||||
<DebugInfo />
|
||||
)
|
||||
}
|
||||
{
|
||||
canSetPermissions && (
|
||||
<Tooltip
|
||||
popupContent={t('plugin.privilege.title')}
|
||||
>
|
||||
<Button
|
||||
className='group h-full w-full p-2 text-components-button-secondary-text'
|
||||
onClick={setShowPluginSettingModal}
|
||||
>
|
||||
<RiEqualizer2Line className='h-4 w-4' />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{isPluginsTab && (
|
||||
<>
|
||||
{plugins}
|
||||
{dragging && (
|
||||
<div
|
||||
className="absolute inset-0 m-0.5 rounded-2xl border-2 border-dashed border-components-dropzone-border-accent
|
||||
bg-[rgba(21,90,239,0.14)] p-2">
|
||||
</div>
|
||||
)}
|
||||
<div className={`flex items-center justify-center gap-2 py-4 ${dragging ? 'text-text-accent' : 'text-text-quaternary'}`}>
|
||||
<RiDragDropLine className="h-4 w-4" />
|
||||
<span className="system-xs-regular">{t('plugin.installModal.dropPluginToInstall')}</span>
|
||||
</div>
|
||||
{currentFile && (
|
||||
<InstallFromLocalPackage
|
||||
file={currentFile}
|
||||
onClose={removeFile ?? noop}
|
||||
onSuccess={noop}
|
||||
/>
|
||||
)}
|
||||
<input
|
||||
ref={fileUploader}
|
||||
className="hidden"
|
||||
type="file"
|
||||
id="fileUploader"
|
||||
accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
|
||||
onChange={fileChangeHandle ?? noop}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{
|
||||
isExploringMarketplace && enable_marketplace && marketplace
|
||||
}
|
||||
|
||||
{showPluginSettingModal && (
|
||||
<ReferenceSettingModal
|
||||
payload={referenceSetting!}
|
||||
onHide={setHidePluginSettingModal}
|
||||
onSave={setReferenceSettings}
|
||||
/>
|
||||
)}
|
||||
|
||||
{
|
||||
isShowInstallFromMarketplace && uniqueIdentifier && (
|
||||
<InstallFromMarketplace
|
||||
manifest={manifest! as PluginManifestInMarket}
|
||||
uniqueIdentifier={uniqueIdentifier}
|
||||
isBundle={!!bundleInfo}
|
||||
dependencies={dependencies}
|
||||
onClose={hideInstallFromMarketplace}
|
||||
onSuccess={hideInstallFromMarketplace}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const PluginPageWithContext = (props: PluginPageProps) => {
|
||||
return (
|
||||
<PluginPageContextProvider>
|
||||
<PluginPage {...props} />
|
||||
</PluginPageContextProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default PluginPageWithContext
|
||||
@@ -0,0 +1,155 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { RiAddLine, RiArrowDownSLine } from '@remixicon/react'
|
||||
import Button from '@/app/components/base/button'
|
||||
import { MagicBox } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
|
||||
import { FileZip } from '@/app/components/base/icons/src/vender/solid/files'
|
||||
import { Github } from '@/app/components/base/icons/src/vender/solid/general'
|
||||
import InstallFromGitHub from '@/app/components/plugins/install-plugin/install-from-github'
|
||||
import InstallFromLocalPackage from '@/app/components/plugins/install-plugin/install-from-local-package'
|
||||
import cn from '@/utils/classnames'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
|
||||
import { noop } from 'lodash-es'
|
||||
import { useGlobalPublicStore } from '@/context/global-public-context'
|
||||
|
||||
type Props = {
|
||||
onSwitchToMarketplaceTab: () => void
|
||||
}
|
||||
|
||||
type InstallMethod = {
|
||||
icon: React.FC<{ className?: string }>
|
||||
text: string
|
||||
action: string
|
||||
}
|
||||
|
||||
const InstallPluginDropdown = ({
|
||||
onSwitchToMarketplaceTab,
|
||||
}: Props) => {
|
||||
const { t } = useTranslation()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false)
|
||||
const [selectedAction, setSelectedAction] = useState<string | null>(null)
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const { enable_marketplace, plugin_installation_permission } = useGlobalPublicStore(s => s.systemFeatures)
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (file) {
|
||||
setSelectedFile(file)
|
||||
setSelectedAction('local')
|
||||
setIsMenuOpen(false)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO TEST INSTALL : uninstall
|
||||
// const [pluginLists, setPluginLists] = useState<any>([])
|
||||
// useEffect(() => {
|
||||
// (async () => {
|
||||
// const list: any = await get('workspaces/current/plugin/list')
|
||||
// })()
|
||||
// })
|
||||
|
||||
// const handleUninstall = async (id: string) => {
|
||||
// const res = await post('workspaces/current/plugin/uninstall', { body: { plugin_installation_id: id } })
|
||||
// console.log(res)
|
||||
// }
|
||||
|
||||
const [installMethods, setInstallMethods] = useState<InstallMethod[]>([])
|
||||
useEffect(() => {
|
||||
const methods = []
|
||||
if (enable_marketplace)
|
||||
methods.push({ icon: MagicBox, text: t('plugin.source.marketplace'), action: 'marketplace' })
|
||||
|
||||
if (plugin_installation_permission.restrict_to_marketplace_only) {
|
||||
setInstallMethods(methods)
|
||||
}
|
||||
else {
|
||||
methods.push({ icon: Github, text: t('plugin.source.github'), action: 'github' })
|
||||
methods.push({ icon: FileZip, text: t('plugin.source.local'), action: 'local' })
|
||||
setInstallMethods(methods)
|
||||
}
|
||||
}, [plugin_installation_permission, enable_marketplace, t])
|
||||
|
||||
return (
|
||||
<PortalToFollowElem
|
||||
open={isMenuOpen}
|
||||
onOpenChange={setIsMenuOpen}
|
||||
placement='bottom-start'
|
||||
offset={4}
|
||||
>
|
||||
<div className="relative">
|
||||
<PortalToFollowElemTrigger onClick={() => setIsMenuOpen(v => !v)}>
|
||||
<Button
|
||||
className={cn('h-full w-full p-2 text-components-button-secondary-text', isMenuOpen && 'bg-state-base-hover')}
|
||||
>
|
||||
<RiAddLine className='h-4 w-4' />
|
||||
<span className='pl-1'>{t('plugin.installPlugin')}</span>
|
||||
<RiArrowDownSLine className='ml-1 h-4 w-4' />
|
||||
</Button>
|
||||
</PortalToFollowElemTrigger>
|
||||
<PortalToFollowElemContent className='z-[1002]'>
|
||||
<div className='shadows-shadow-lg flex w-[200px] flex-col items-start rounded-xl border border-components-panel-border bg-components-panel-bg-blur p-1 pb-2'>
|
||||
<span className='system-xs-medium-uppercase flex items-start self-stretch pb-0.5 pl-2 pr-3 pt-1 text-text-tertiary'>
|
||||
{t('plugin.installFrom')}
|
||||
</span>
|
||||
<input
|
||||
type='file'
|
||||
ref={fileInputRef}
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFileChange}
|
||||
accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
|
||||
/>
|
||||
<div className='w-full'>
|
||||
{installMethods.map(({ icon: Icon, text, action }) => (
|
||||
<div
|
||||
key={action}
|
||||
className='flex w-full !cursor-pointer items-center gap-1 rounded-lg px-2 py-1.5 hover:bg-state-base-hover'
|
||||
onClick={() => {
|
||||
if (action === 'local') {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
else if (action === 'marketplace') {
|
||||
onSwitchToMarketplaceTab()
|
||||
setIsMenuOpen(false)
|
||||
}
|
||||
else {
|
||||
setSelectedAction(action)
|
||||
setIsMenuOpen(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Icon className="h-4 w-4 text-text-tertiary" />
|
||||
<span className='system-md-regular px-1 text-text-secondary'>{text}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</PortalToFollowElemContent>
|
||||
</div>
|
||||
{selectedAction === 'github' && <InstallFromGitHub
|
||||
onSuccess={noop}
|
||||
onClose={() => setSelectedAction(null)}
|
||||
/>}
|
||||
{selectedAction === 'local' && selectedFile
|
||||
&& (<InstallFromLocalPackage
|
||||
file={selectedFile}
|
||||
onClose={() => setSelectedAction(null)}
|
||||
onSuccess={noop}
|
||||
/>
|
||||
)
|
||||
}
|
||||
{/* {pluginLists.map((item: any) => (
|
||||
<div key={item.id} onClick={() => handleUninstall(item.id)}>{item.name} 卸载</div>
|
||||
))} */}
|
||||
</PortalToFollowElem>
|
||||
)
|
||||
}
|
||||
|
||||
export default InstallPluginDropdown
|
||||
23
dify/web/app/components/plugins/plugin-page/list/index.tsx
Normal file
23
dify/web/app/components/plugins/plugin-page/list/index.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import type { FC } from 'react'
|
||||
import PluginItem from '../../plugin-item'
|
||||
import type { PluginDetail } from '../../types'
|
||||
|
||||
type IPluginListProps = {
|
||||
pluginList: PluginDetail[]
|
||||
}
|
||||
|
||||
const PluginList: FC<IPluginListProps> = ({ pluginList }) => {
|
||||
return (
|
||||
<div className='pb-3'>
|
||||
<div className='grid grid-cols-2 gap-3'>
|
||||
{pluginList.map(plugin => (
|
||||
<PluginItem
|
||||
key={plugin.plugin_id}
|
||||
plugin={plugin}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default PluginList
|
||||
41
dify/web/app/components/plugins/plugin-page/plugin-info.tsx
Normal file
41
dify/web/app/components/plugins/plugin-page/plugin-info.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import KeyValueItem from '../base/key-value-item'
|
||||
import Modal from '../../base/modal'
|
||||
import { convertRepoToUrl } from '../install-plugin/utils'
|
||||
|
||||
const i18nPrefix = 'plugin.pluginInfoModal'
|
||||
type Props = {
|
||||
repository?: string
|
||||
release?: string
|
||||
packageName?: string
|
||||
onHide: () => void
|
||||
}
|
||||
|
||||
const PlugInfo: FC<Props> = ({
|
||||
repository,
|
||||
release,
|
||||
packageName,
|
||||
onHide,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const labelWidthClassName = 'w-[96px]'
|
||||
return (
|
||||
<Modal
|
||||
title={t(`${i18nPrefix}.title`)}
|
||||
className='w-[480px]'
|
||||
isShow
|
||||
onClose={onHide}
|
||||
closable
|
||||
>
|
||||
<div className='mt-5 space-y-3'>
|
||||
{repository && <KeyValueItem label={t(`${i18nPrefix}.repository`)} labelWidthClassName={labelWidthClassName} value={`${convertRepoToUrl(repository)}`} valueMaxWidthClassName='max-w-[190px]' />}
|
||||
{release && <KeyValueItem label={t(`${i18nPrefix}.release`)} labelWidthClassName={labelWidthClassName} value={release} />}
|
||||
{packageName && <KeyValueItem label={t(`${i18nPrefix}.packageName`)} labelWidthClassName={labelWidthClassName} value={packageName} />}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
export default React.memo(PlugInfo)
|
||||
@@ -0,0 +1,100 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react'
|
||||
import { TaskStatus } from '@/app/components/plugins/types'
|
||||
import type { PluginStatus } from '@/app/components/plugins/types'
|
||||
import {
|
||||
useMutationClearAllTaskPlugin,
|
||||
useMutationClearTaskPlugin,
|
||||
usePluginTaskList,
|
||||
} from '@/service/use-plugins'
|
||||
|
||||
export const usePluginTaskStatus = () => {
|
||||
const {
|
||||
pluginTasks,
|
||||
handleRefetch,
|
||||
} = usePluginTaskList()
|
||||
const { mutateAsync } = useMutationClearTaskPlugin()
|
||||
const { mutateAsync: mutateAsyncClearAll } = useMutationClearAllTaskPlugin()
|
||||
const allPlugins = pluginTasks.map(task => task.plugins.map((plugin) => {
|
||||
return {
|
||||
...plugin,
|
||||
taskId: task.id,
|
||||
}
|
||||
})).flat()
|
||||
const errorPlugins: PluginStatus[] = []
|
||||
const successPlugins: PluginStatus[] = []
|
||||
const runningPlugins: PluginStatus[] = []
|
||||
|
||||
allPlugins.forEach((plugin) => {
|
||||
if (plugin.status === TaskStatus.running)
|
||||
runningPlugins.push(plugin)
|
||||
if (plugin.status === TaskStatus.failed)
|
||||
errorPlugins.push(plugin)
|
||||
if (plugin.status === TaskStatus.success)
|
||||
successPlugins.push(plugin)
|
||||
})
|
||||
|
||||
const handleClearErrorPlugin = useCallback(async (taskId: string, pluginId: string) => {
|
||||
await mutateAsync({
|
||||
taskId,
|
||||
pluginId,
|
||||
})
|
||||
handleRefetch()
|
||||
}, [mutateAsync, handleRefetch])
|
||||
const handleClearAllErrorPlugin = useCallback(async () => {
|
||||
await mutateAsyncClearAll()
|
||||
handleRefetch()
|
||||
}, [mutateAsyncClearAll, handleRefetch])
|
||||
const totalPluginsLength = allPlugins.length
|
||||
const runningPluginsLength = runningPlugins.length
|
||||
const errorPluginsLength = errorPlugins.length
|
||||
const successPluginsLength = successPlugins.length
|
||||
|
||||
const isInstalling = runningPluginsLength > 0 && errorPluginsLength === 0 && successPluginsLength === 0
|
||||
const isInstallingWithSuccess = runningPluginsLength > 0 && successPluginsLength > 0 && errorPluginsLength === 0
|
||||
const isInstallingWithError = runningPluginsLength > 0 && errorPluginsLength > 0
|
||||
const isSuccess = successPluginsLength === totalPluginsLength && totalPluginsLength > 0
|
||||
const isFailed = runningPluginsLength === 0 && (errorPluginsLength + successPluginsLength) === totalPluginsLength && totalPluginsLength > 0 && errorPluginsLength > 0
|
||||
|
||||
const [opacity, setOpacity] = useState(1)
|
||||
const timerRef = useRef<NodeJS.Timeout | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (isSuccess) {
|
||||
if (timerRef.current) {
|
||||
clearTimeout(timerRef.current)
|
||||
timerRef.current = null
|
||||
}
|
||||
if (opacity > 0) {
|
||||
timerRef.current = setTimeout(() => {
|
||||
setOpacity(v => v - 0.1)
|
||||
}, 200)
|
||||
}
|
||||
}
|
||||
|
||||
if (!isSuccess)
|
||||
setOpacity(1)
|
||||
}, [isSuccess, opacity])
|
||||
|
||||
return {
|
||||
errorPlugins,
|
||||
successPlugins,
|
||||
runningPlugins,
|
||||
runningPluginsLength,
|
||||
errorPluginsLength,
|
||||
successPluginsLength,
|
||||
totalPluginsLength,
|
||||
isInstalling,
|
||||
isInstallingWithSuccess,
|
||||
isInstallingWithError,
|
||||
isSuccess,
|
||||
isFailed,
|
||||
handleClearErrorPlugin,
|
||||
handleClearAllErrorPlugin,
|
||||
opacity,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import {
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react'
|
||||
import {
|
||||
RiCheckboxCircleFill,
|
||||
RiErrorWarningFill,
|
||||
RiInstallLine,
|
||||
} from '@remixicon/react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { usePluginTaskStatus } from './hooks'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import Tooltip from '@/app/components/base/tooltip'
|
||||
import Button from '@/app/components/base/button'
|
||||
import ProgressCircle from '@/app/components/base/progress-bar/progress-circle'
|
||||
import CardIcon from '@/app/components/plugins/card/base/card-icon'
|
||||
import cn from '@/utils/classnames'
|
||||
import { useGetLanguage } from '@/context/i18n'
|
||||
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
|
||||
import DownloadingIcon from '@/app/components/header/plugins-nav/downloading-icon'
|
||||
|
||||
const PluginTasks = () => {
|
||||
const { t } = useTranslation()
|
||||
const language = useGetLanguage()
|
||||
const [open, setOpen] = useState(false)
|
||||
const {
|
||||
errorPlugins,
|
||||
runningPluginsLength,
|
||||
successPluginsLength,
|
||||
errorPluginsLength,
|
||||
totalPluginsLength,
|
||||
isInstalling,
|
||||
isInstallingWithSuccess,
|
||||
isInstallingWithError,
|
||||
isSuccess,
|
||||
isFailed,
|
||||
handleClearErrorPlugin,
|
||||
handleClearAllErrorPlugin,
|
||||
opacity,
|
||||
} = usePluginTaskStatus()
|
||||
const { getIconUrl } = useGetIcon()
|
||||
|
||||
const tip = useMemo(() => {
|
||||
if (isInstalling)
|
||||
return t('plugin.task.installing', { installingLength: runningPluginsLength })
|
||||
|
||||
if (isInstallingWithSuccess)
|
||||
return t('plugin.task.installingWithSuccess', { installingLength: runningPluginsLength, successLength: successPluginsLength })
|
||||
|
||||
if (isInstallingWithError)
|
||||
return t('plugin.task.installingWithError', { installingLength: runningPluginsLength, successLength: successPluginsLength, errorLength: errorPluginsLength })
|
||||
|
||||
if (isFailed)
|
||||
return t('plugin.task.installError', { errorLength: errorPluginsLength })
|
||||
}, [isInstalling, isInstallingWithSuccess, isInstallingWithError, isFailed, errorPluginsLength, runningPluginsLength, successPluginsLength, t])
|
||||
|
||||
if (!totalPluginsLength)
|
||||
return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn('flex items-center', opacity < 0 && 'hidden')}
|
||||
style={{ opacity }}
|
||||
>
|
||||
<PortalToFollowElem
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
placement='bottom-start'
|
||||
offset={{
|
||||
mainAxis: 4,
|
||||
crossAxis: 79,
|
||||
}}
|
||||
>
|
||||
<PortalToFollowElemTrigger
|
||||
onClick={() => {
|
||||
if (isFailed)
|
||||
setOpen(v => !v)
|
||||
}}
|
||||
>
|
||||
<Tooltip popupContent={tip}>
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex h-8 w-8 items-center justify-center rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg shadow-xs hover:bg-components-button-secondary-bg-hover',
|
||||
(isInstallingWithError || isFailed) && 'cursor-pointer border-components-button-destructive-secondary-border-hover bg-state-destructive-hover hover:bg-state-destructive-hover-alt',
|
||||
)}
|
||||
id="plugin-task-trigger"
|
||||
>
|
||||
{
|
||||
(isInstalling || isInstallingWithError) && (
|
||||
<DownloadingIcon />
|
||||
)
|
||||
}
|
||||
{
|
||||
!(isInstalling || isInstallingWithError) && (
|
||||
<RiInstallLine
|
||||
className={cn(
|
||||
'h-4 w-4 text-components-button-secondary-text',
|
||||
(isInstallingWithError || isFailed) && 'text-components-button-destructive-secondary-text',
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
<div className='absolute -right-1 -top-1'>
|
||||
{
|
||||
(isInstalling || isInstallingWithSuccess) && (
|
||||
<ProgressCircle
|
||||
percentage={successPluginsLength / totalPluginsLength * 100}
|
||||
circleFillColor='fill-components-progress-brand-bg'
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
isInstallingWithError && (
|
||||
<ProgressCircle
|
||||
percentage={runningPluginsLength / totalPluginsLength * 100}
|
||||
circleFillColor='fill-components-progress-brand-bg'
|
||||
sectorFillColor='fill-components-progress-error-border'
|
||||
circleStrokeColor='stroke-components-progress-error-border'
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
isSuccess && (
|
||||
<RiCheckboxCircleFill className='h-3.5 w-3.5 text-text-success' />
|
||||
)
|
||||
}
|
||||
{
|
||||
isFailed && (
|
||||
<RiErrorWarningFill className='h-3.5 w-3.5 text-text-destructive' />
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
</PortalToFollowElemTrigger>
|
||||
<PortalToFollowElemContent className='z-[11]'>
|
||||
<div className='w-[320px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 pb-2 shadow-lg'>
|
||||
<div className='system-sm-semibold-uppercase sticky top-0 flex h-7 items-center justify-between px-2 pt-1'>
|
||||
{t('plugin.task.installedError', { errorLength: errorPluginsLength })}
|
||||
<Button
|
||||
className='shrink-0'
|
||||
size='small'
|
||||
variant='ghost'
|
||||
onClick={() => handleClearAllErrorPlugin()}
|
||||
>
|
||||
{t('plugin.task.clearAll')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className='max-h-[400px] overflow-y-auto'>
|
||||
{
|
||||
errorPlugins.map(errorPlugin => (
|
||||
<div
|
||||
key={errorPlugin.plugin_unique_identifier}
|
||||
className='flex rounded-lg p-2 hover:bg-state-base-hover'
|
||||
>
|
||||
<div className='relative mr-2 flex h-6 w-6 items-center justify-center rounded-md border-[0.5px] border-components-panel-border-subtle bg-background-default-dodge'>
|
||||
<RiErrorWarningFill className='absolute -bottom-0.5 -right-0.5 z-10 h-3 w-3 text-text-destructive' />
|
||||
<CardIcon
|
||||
size='tiny'
|
||||
src={getIconUrl(errorPlugin.icon)}
|
||||
/>
|
||||
</div>
|
||||
<div className='grow'>
|
||||
<div className='system-md-regular truncate text-text-secondary'>
|
||||
{errorPlugin.labels[language]}
|
||||
</div>
|
||||
<div className='system-xs-regular break-all text-text-destructive'>
|
||||
{errorPlugin.message}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
className='shrink-0'
|
||||
size='small'
|
||||
variant='ghost'
|
||||
onClick={() => handleClearErrorPlugin(errorPlugin.taskId, errorPlugin.plugin_unique_identifier)}
|
||||
>
|
||||
{t('common.operation.clear')}
|
||||
</Button>
|
||||
</div>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</PortalToFollowElemContent>
|
||||
</PortalToFollowElem>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PluginTasks
|
||||
101
dify/web/app/components/plugins/plugin-page/plugins-panel.tsx
Normal file
101
dify/web/app/components/plugins/plugin-page/plugins-panel.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
'use client'
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { FilterState } from './filter-management'
|
||||
import FilterManagement from './filter-management'
|
||||
import List from './list'
|
||||
import { useInstalledLatestVersion, useInstalledPluginList, useInvalidateInstalledPluginList } from '@/service/use-plugins'
|
||||
import PluginDetailPanel from '@/app/components/plugins/plugin-detail-panel'
|
||||
import { usePluginPageContext } from './context'
|
||||
import { useDebounceFn } from 'ahooks'
|
||||
import Button from '@/app/components/base/button'
|
||||
import Empty from './empty'
|
||||
import Loading from '../../base/loading'
|
||||
import { PluginSource } from '../types'
|
||||
|
||||
const PluginsPanel = () => {
|
||||
const { t } = useTranslation()
|
||||
const filters = usePluginPageContext(v => v.filters) as FilterState
|
||||
const setFilters = usePluginPageContext(v => v.setFilters)
|
||||
const { data: pluginList, isLoading: isPluginListLoading, isFetching, isLastPage, loadNextPage } = useInstalledPluginList()
|
||||
const { data: installedLatestVersion } = useInstalledLatestVersion(
|
||||
pluginList?.plugins
|
||||
.filter(plugin => plugin.source === PluginSource.marketplace)
|
||||
.map(plugin => plugin.plugin_id) ?? [],
|
||||
)
|
||||
const invalidateInstalledPluginList = useInvalidateInstalledPluginList()
|
||||
const currentPluginID = usePluginPageContext(v => v.currentPluginID)
|
||||
const setCurrentPluginID = usePluginPageContext(v => v.setCurrentPluginID)
|
||||
|
||||
const { run: handleFilterChange } = useDebounceFn((filters: FilterState) => {
|
||||
setFilters(filters)
|
||||
}, { wait: 500 })
|
||||
|
||||
const pluginListWithLatestVersion = useMemo(() => {
|
||||
return pluginList?.plugins.map(plugin => ({
|
||||
...plugin,
|
||||
latest_version: installedLatestVersion?.versions[plugin.plugin_id]?.version ?? '',
|
||||
latest_unique_identifier: installedLatestVersion?.versions[plugin.plugin_id]?.unique_identifier ?? '',
|
||||
status: installedLatestVersion?.versions[plugin.plugin_id]?.status ?? 'active',
|
||||
deprecated_reason: installedLatestVersion?.versions[plugin.plugin_id]?.deprecated_reason ?? '',
|
||||
alternative_plugin_id: installedLatestVersion?.versions[plugin.plugin_id]?.alternative_plugin_id ?? '',
|
||||
})) || []
|
||||
}, [pluginList, installedLatestVersion])
|
||||
|
||||
const filteredList = useMemo(() => {
|
||||
const { categories, searchQuery, tags } = filters
|
||||
const filteredList = pluginListWithLatestVersion.filter((plugin) => {
|
||||
return (
|
||||
(categories.length === 0 || categories.includes(plugin.declaration.category))
|
||||
&& (tags.length === 0 || tags.some(tag => plugin.declaration.tags.includes(tag)))
|
||||
&& (searchQuery === '' || plugin.plugin_id.toLowerCase().includes(searchQuery.toLowerCase()))
|
||||
)
|
||||
})
|
||||
return filteredList
|
||||
}, [pluginListWithLatestVersion, filters])
|
||||
|
||||
const currentPluginDetail = useMemo(() => {
|
||||
const detail = pluginListWithLatestVersion.find(plugin => plugin.plugin_id === currentPluginID)
|
||||
return detail
|
||||
}, [currentPluginID, pluginListWithLatestVersion])
|
||||
|
||||
const handleHide = () => setCurrentPluginID(undefined)
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='flex flex-col items-start justify-center gap-3 self-stretch px-12 pb-3 pt-1'>
|
||||
<div className='h-px self-stretch bg-divider-subtle'></div>
|
||||
<FilterManagement
|
||||
onFilterChange={handleFilterChange}
|
||||
/>
|
||||
</div>
|
||||
{isPluginListLoading && <Loading type='app' />}
|
||||
{!isPluginListLoading && (
|
||||
<>
|
||||
{(filteredList?.length ?? 0) > 0 ? (
|
||||
<div className='flex grow flex-wrap content-start items-start justify-center gap-2 self-stretch overflow-y-auto px-12'>
|
||||
<div className='w-full'>
|
||||
<List pluginList={filteredList || []} />
|
||||
</div>
|
||||
{!isLastPage && !isFetching && (
|
||||
<Button onClick={loadNextPage}>
|
||||
{t('workflow.common.loadMore')}
|
||||
</Button>
|
||||
)}
|
||||
{isFetching && <div className='system-md-semibold text-text-secondary'>{t('appLog.detail.loading')}</div>}
|
||||
</div>
|
||||
) : (
|
||||
<Empty />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<PluginDetailPanel
|
||||
detail={currentPluginDetail}
|
||||
onUpdate={() => invalidateInstalledPluginList()}
|
||||
onHide={handleHide}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default PluginsPanel
|
||||
@@ -0,0 +1,63 @@
|
||||
import { PermissionType } from '../types'
|
||||
import { useAppContext } from '@/context/app-context'
|
||||
import Toast from '../../base/toast'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useInvalidateReferenceSettings, useMutationReferenceSettings, useReferenceSettings } from '@/service/use-plugins'
|
||||
import { useMemo } from 'react'
|
||||
import { useGlobalPublicStore } from '@/context/global-public-context'
|
||||
|
||||
const hasPermission = (permission: PermissionType | undefined, isAdmin: boolean) => {
|
||||
if (!permission)
|
||||
return false
|
||||
|
||||
if (permission === PermissionType.noOne)
|
||||
return false
|
||||
|
||||
if (permission === PermissionType.everyone)
|
||||
return true
|
||||
|
||||
return isAdmin
|
||||
}
|
||||
|
||||
const useReferenceSetting = () => {
|
||||
const { t } = useTranslation()
|
||||
const { isCurrentWorkspaceManager, isCurrentWorkspaceOwner } = useAppContext()
|
||||
const { data } = useReferenceSettings()
|
||||
// console.log(data)
|
||||
const { permission: permissions } = data || {}
|
||||
const invalidateReferenceSettings = useInvalidateReferenceSettings()
|
||||
const { mutate: updateReferenceSetting, isPending: isUpdatePending } = useMutationReferenceSettings({
|
||||
onSuccess: () => {
|
||||
invalidateReferenceSettings()
|
||||
Toast.notify({
|
||||
type: 'success',
|
||||
message: t('common.api.actionSuccess'),
|
||||
})
|
||||
},
|
||||
})
|
||||
const isAdmin = isCurrentWorkspaceManager || isCurrentWorkspaceOwner
|
||||
|
||||
return {
|
||||
referenceSetting: data,
|
||||
setReferenceSettings: updateReferenceSetting,
|
||||
canManagement: hasPermission(permissions?.install_permission, isAdmin),
|
||||
canDebugger: hasPermission(permissions?.debug_permission, isAdmin),
|
||||
canSetPermissions: isAdmin,
|
||||
isUpdatePending,
|
||||
}
|
||||
}
|
||||
|
||||
export const useCanInstallPluginFromMarketplace = () => {
|
||||
const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
|
||||
const { canManagement } = useReferenceSetting()
|
||||
|
||||
const canInstallPluginFromMarketplace = useMemo(() => {
|
||||
return enable_marketplace && canManagement
|
||||
}, [enable_marketplace, canManagement])
|
||||
|
||||
return {
|
||||
canInstallPluginFromMarketplace,
|
||||
}
|
||||
}
|
||||
|
||||
export default useReferenceSetting
|
||||
87
dify/web/app/components/plugins/plugin-page/use-uploader.ts
Normal file
87
dify/web/app/components/plugins/plugin-page/use-uploader.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { RefObject } from 'react'
|
||||
|
||||
type UploaderHookProps = {
|
||||
onFileChange: (file: File | null) => void
|
||||
containerRef: RefObject<HTMLDivElement | null>
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
export const useUploader = ({ onFileChange, containerRef, enabled = true }: UploaderHookProps) => {
|
||||
const [dragging, setDragging] = useState(false)
|
||||
const fileUploader = useRef<HTMLInputElement>(null)
|
||||
|
||||
const handleDragEnter = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (e.dataTransfer?.types.includes('Files'))
|
||||
setDragging(true)
|
||||
}
|
||||
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
}
|
||||
|
||||
const handleDragLeave = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (e.relatedTarget === null || !containerRef.current?.contains(e.relatedTarget as Node))
|
||||
setDragging(false)
|
||||
}
|
||||
|
||||
const handleDrop = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setDragging(false)
|
||||
if (!e.dataTransfer)
|
||||
return
|
||||
const files = [...e.dataTransfer.files]
|
||||
if (files.length > 0)
|
||||
onFileChange(files[0])
|
||||
}
|
||||
|
||||
const fileChangeHandle = enabled
|
||||
? (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0] || null
|
||||
onFileChange(file)
|
||||
}
|
||||
: null
|
||||
|
||||
const removeFile = enabled
|
||||
? () => {
|
||||
if (fileUploader.current)
|
||||
fileUploader.current.value = ''
|
||||
|
||||
onFileChange(null)
|
||||
}
|
||||
: null
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled)
|
||||
return
|
||||
|
||||
const current = containerRef.current
|
||||
if (current) {
|
||||
current.addEventListener('dragenter', handleDragEnter)
|
||||
current.addEventListener('dragover', handleDragOver)
|
||||
current.addEventListener('dragleave', handleDragLeave)
|
||||
current.addEventListener('drop', handleDrop)
|
||||
}
|
||||
return () => {
|
||||
if (current) {
|
||||
current.removeEventListener('dragenter', handleDragEnter)
|
||||
current.removeEventListener('dragover', handleDragOver)
|
||||
current.removeEventListener('dragleave', handleDragLeave)
|
||||
current.removeEventListener('drop', handleDrop)
|
||||
}
|
||||
}
|
||||
}, [containerRef, enabled])
|
||||
|
||||
return {
|
||||
dragging: enabled ? dragging : false,
|
||||
fileUploader,
|
||||
fileChangeHandle,
|
||||
removeFile,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user