Introduce Plugins (#13836)

Signed-off-by: yihong0618 <zouzou0208@gmail.com>
Signed-off-by: -LAN- <laipz8200@outlook.com>
Signed-off-by: xhe <xw897002528@gmail.com>
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: takatost <takatost@gmail.com>
Co-authored-by: kurokobo <kuro664@gmail.com>
Co-authored-by: Novice Lee <novicelee@NoviPro.local>
Co-authored-by: zxhlyh <jasonapring2015@outlook.com>
Co-authored-by: AkaraChen <akarachen@outlook.com>
Co-authored-by: Yi <yxiaoisme@gmail.com>
Co-authored-by: Joel <iamjoel007@gmail.com>
Co-authored-by: JzoNg <jzongcode@gmail.com>
Co-authored-by: twwu <twwu@dify.ai>
Co-authored-by: Hiroshi Fujita <fujita-h@users.noreply.github.com>
Co-authored-by: AkaraChen <85140972+AkaraChen@users.noreply.github.com>
Co-authored-by: NFish <douxc512@gmail.com>
Co-authored-by: Wu Tianwei <30284043+WTW0313@users.noreply.github.com>
Co-authored-by: 非法操作 <hjlarry@163.com>
Co-authored-by: Novice <857526207@qq.com>
Co-authored-by: Hiroki Nagai <82458324+nagaihiroki-git@users.noreply.github.com>
Co-authored-by: Gen Sato <52241300+halogen22@users.noreply.github.com>
Co-authored-by: eux <euxuuu@gmail.com>
Co-authored-by: huangzhuo1949 <167434202+huangzhuo1949@users.noreply.github.com>
Co-authored-by: huangzhuo <huangzhuo1@xiaomi.com>
Co-authored-by: lotsik <lotsik@mail.ru>
Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com>
Co-authored-by: nite-knite <nkCoding@gmail.com>
Co-authored-by: Jyong <76649700+JohnJyong@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: gakkiyomi <gakkiyomi@aliyun.com>
Co-authored-by: CN-P5 <heibai2006@gmail.com>
Co-authored-by: CN-P5 <heibai2006@qq.com>
Co-authored-by: Chuehnone <1897025+chuehnone@users.noreply.github.com>
Co-authored-by: yihong <zouzou0208@gmail.com>
Co-authored-by: Kevin9703 <51311316+Kevin9703@users.noreply.github.com>
Co-authored-by: -LAN- <laipz8200@outlook.com>
Co-authored-by: Boris Feld <lothiraldan@gmail.com>
Co-authored-by: mbo <himabo@gmail.com>
Co-authored-by: mabo <mabo@aeyes.ai>
Co-authored-by: Warren Chen <warren.chen830@gmail.com>
Co-authored-by: JzoNgKVO <27049666+JzoNgKVO@users.noreply.github.com>
Co-authored-by: jiandanfeng <chenjh3@wangsu.com>
Co-authored-by: zhu-an <70234959+xhdd123321@users.noreply.github.com>
Co-authored-by: zhaoqingyu.1075 <zhaoqingyu.1075@bytedance.com>
Co-authored-by: 海狸大師 <86974027+yenslife@users.noreply.github.com>
Co-authored-by: Xu Song <xusong.vip@gmail.com>
Co-authored-by: rayshaw001 <396301947@163.com>
Co-authored-by: Ding Jiatong <dingjiatong@gmail.com>
Co-authored-by: Bowen Liang <liangbowen@gf.com.cn>
Co-authored-by: JasonVV <jasonwangiii@outlook.com>
Co-authored-by: le0zh <newlight@qq.com>
Co-authored-by: zhuxinliang <zhuxinliang@didiglobal.com>
Co-authored-by: k-zaku <zaku99@outlook.jp>
Co-authored-by: luckylhb90 <luckylhb90@gmail.com>
Co-authored-by: hobo.l <hobo.l@binance.com>
Co-authored-by: jiangbo721 <365065261@qq.com>
Co-authored-by: 刘江波 <jiangbo721@163.com>
Co-authored-by: Shun Miyazawa <34241526+miya@users.noreply.github.com>
Co-authored-by: EricPan <30651140+Egfly@users.noreply.github.com>
Co-authored-by: crazywoola <427733928@qq.com>
Co-authored-by: sino <sino2322@gmail.com>
Co-authored-by: Jhvcc <37662342+Jhvcc@users.noreply.github.com>
Co-authored-by: lowell <lowell.hu@zkteco.in>
Co-authored-by: Boris Polonsky <BorisPolonsky@users.noreply.github.com>
Co-authored-by: Ademílson Tonato <ademilsonft@outlook.com>
Co-authored-by: Ademílson Tonato <ademilson.tonato@refurbed.com>
Co-authored-by: IWAI, Masaharu <iwaim.sub@gmail.com>
Co-authored-by: Yueh-Po Peng (Yabi) <94939112+y10ab1@users.noreply.github.com>
Co-authored-by: Jason <ggbbddjm@gmail.com>
Co-authored-by: Xin Zhang <sjhpzx@gmail.com>
Co-authored-by: yjc980121 <3898524+yjc980121@users.noreply.github.com>
Co-authored-by: heyszt <36215648+hieheihei@users.noreply.github.com>
Co-authored-by: Abdullah AlOsaimi <osaimiacc@gmail.com>
Co-authored-by: Abdullah AlOsaimi <189027247+osaimi@users.noreply.github.com>
Co-authored-by: Yingchun Lai <laiyingchun@apache.org>
Co-authored-by: Hash Brown <hi@xzd.me>
Co-authored-by: zuodongxu <192560071+zuodongxu@users.noreply.github.com>
Co-authored-by: Masashi Tomooka <tmokmss@users.noreply.github.com>
Co-authored-by: aplio <ryo.091219@gmail.com>
Co-authored-by: Obada Khalili <54270856+obadakhalili@users.noreply.github.com>
Co-authored-by: Nam Vu <zuzoovn@gmail.com>
Co-authored-by: Kei YAMAZAKI <1715090+kei-yamazaki@users.noreply.github.com>
Co-authored-by: TechnoHouse <13776377+deephbz@users.noreply.github.com>
Co-authored-by: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com>
Co-authored-by: MaFee921 <31881301+2284730142@users.noreply.github.com>
Co-authored-by: te-chan <t-nakanome@sakura-is.co.jp>
Co-authored-by: HQidea <HQidea@users.noreply.github.com>
Co-authored-by: Joshbly <36315710+Joshbly@users.noreply.github.com>
Co-authored-by: xhe <xw897002528@gmail.com>
Co-authored-by: weiwenyan-dev <154779315+weiwenyan-dev@users.noreply.github.com>
Co-authored-by: ex_wenyan.wei <ex_wenyan.wei@tcl.com>
Co-authored-by: engchina <12236799+engchina@users.noreply.github.com>
Co-authored-by: engchina <atjapan2015@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: 呆萌闷油瓶 <253605712@qq.com>
Co-authored-by: Kemal <kemalmeler@outlook.com>
Co-authored-by: Lazy_Frog <4590648+lazyFrogLOL@users.noreply.github.com>
Co-authored-by: Yi Xiao <54782454+YIXIAO0@users.noreply.github.com>
Co-authored-by: Steven sun <98230804+Tuyohai@users.noreply.github.com>
Co-authored-by: steven <sunzwj@digitalchina.com>
Co-authored-by: Kalo Chin <91766386+fdb02983rhy@users.noreply.github.com>
Co-authored-by: Katy Tao <34019945+KatyTao@users.noreply.github.com>
Co-authored-by: depy <42985524+h4ckdepy@users.noreply.github.com>
Co-authored-by: 胡春东 <gycm520@gmail.com>
Co-authored-by: Junjie.M <118170653@qq.com>
Co-authored-by: MuYu <mr.muzea@gmail.com>
Co-authored-by: Naoki Takashima <39912547+takatea@users.noreply.github.com>
Co-authored-by: Summer-Gu <37869445+gubinjie@users.noreply.github.com>
Co-authored-by: Fei He <droxer.he@gmail.com>
Co-authored-by: ybalbert001 <120714773+ybalbert001@users.noreply.github.com>
Co-authored-by: Yuanbo Li <ybalbert@amazon.com>
Co-authored-by: douxc <7553076+douxc@users.noreply.github.com>
Co-authored-by: liuzhenghua <1090179900@qq.com>
Co-authored-by: Wu Jiayang <62842862+Wu-Jiayang@users.noreply.github.com>
Co-authored-by: Your Name <you@example.com>
Co-authored-by: kimjion <45935338+kimjion@users.noreply.github.com>
Co-authored-by: AugNSo <song.tiankai@icloud.com>
Co-authored-by: llinvokerl <38915183+llinvokerl@users.noreply.github.com>
Co-authored-by: liusurong.lsr <liusurong.lsr@alibaba-inc.com>
Co-authored-by: Vasu Negi <vasu-negi@users.noreply.github.com>
Co-authored-by: Hundredwz <1808096180@qq.com>
Co-authored-by: Xiyuan Chen <52963600+GareArc@users.noreply.github.com>
This commit is contained in:
Yeuoly
2025-02-17 17:05:13 +08:00
committed by GitHub
parent 222df44d21
commit 403e2d58b9
3272 changed files with 66339 additions and 281594 deletions

View File

@@ -0,0 +1,95 @@
'use client'
import type { ReactNode } from 'react'
import {
useMemo,
useRef,
useState,
} from 'react'
import {
createContext,
useContextSelector,
} from 'use-context-selector'
import { useSelector as useAppContextSelector } from '@/context/app-context'
import type { FilterState } from './filter-management'
import { useTranslation } from 'react-i18next'
import { useTabSearchParams } from '@/hooks/use-tab-searchparams'
export type PluginPageContextValue = {
containerRef: React.RefObject<HTMLDivElement>
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 }>
}
export const PluginPageContext = createContext<PluginPageContextValue>({
containerRef: { current: null },
currentPluginID: undefined,
setCurrentPluginID: () => { },
filters: {
categories: [],
tags: [],
searchQuery: '',
},
setFilters: () => { },
activeTab: '',
setActiveTab: () => { },
options: [],
})
type PluginPageContextProviderProps = {
children: ReactNode
}
export function usePluginPageContext(selector: (value: PluginPageContextValue) => any) {
return useContextSelector(PluginPageContext, selector)
}
export const PluginPageContextProvider = ({
children,
}: PluginPageContextProviderProps) => {
const { t } = useTranslation()
const containerRef = useRef<HTMLDivElement>(null)
const [filters, setFilters] = useState<FilterState>({
categories: [],
tags: [],
searchQuery: '',
})
const [currentPluginID, setCurrentPluginID] = useState<string | undefined>()
const { enable_marketplace } = useAppContextSelector(s => s.systemFeatures)
const options = useMemo(() => {
return [
{ value: 'plugins', text: t('common.menus.plugins') },
...(
enable_marketplace
? [{ value: 'discover', text: t('common.menus.exploreMarketplace') }]
: []
),
]
}, [t, 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>
)
}

View File

@@ -0,0 +1,63 @@
'use client'
import type { FC } from 'react'
import React from 'react'
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 { useDebugKey } from '@/service/use-plugins'
const i18nPrefix = 'plugin.debugInfo'
const DebugInfo: FC = () => {
const { t } = useTranslation()
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='flex flex-col justify-center items-start grow shrink-0 basis-0 text-text-secondary system-sm-semibold'>{t(`${i18nPrefix}.title`)}</span>
<a href='https://docs.dify.ai/plugins/quick-start/develop-plugins/debug-plugin' target='_blank' className='flex items-center gap-0.5 text-text-accent-light-mode-only cursor-pointer'>
<span className='system-xs-medium'>{t(`${i18nPrefix}.viewDocs`)}</span>
<RiArrowRightUpLine className='w-3 h-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='w-full h-full p-2 text-components-button-secondary-text'>
<RiBugLine className='w-4 h-4' />
</Button>
</Tooltip>
)
}
export default React.memo(DebugInfo)

View File

@@ -0,0 +1,120 @@
import React, { 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 { useSelector as useAppContextSelector } from '@/context/app-context'
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'
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 } = useAppContextSelector(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])
return (
<div className='grow w-full relative z-0'>
{/* skeleton */}
<div className='h-full w-full px-12 absolute top-0 grid grid-cols-2 gap-2 overflow-hidden z-10'>
{Array.from({ length: 20 }).fill(0).map((_, i) => (
<div key={i} className='h-[100px] bg-components-card-bg rounded-xl' />
))}
</div>
{/* mask */}
<div className='h-full w-full absolute z-20 bg-gradient-to-b from-background-gradient-mask-transparent to-white' />
<div className='flex items-center justify-center h-full relative z-30'>
<div className='flex flex-col items-center gap-y-3'>
<div className='relative -z-10 flex items-center justify-center w-[52px] h-[52px] rounded-xl
bg-components-card-bg border-[1px] border-dashed border-divider-deep shadow-xl shadow-shadow-shadow-5'>
<Group className='text-text-tertiary w-5 h-5' />
<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 top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 rotate-90' />
<Line className='absolute top-full left-1/2 -translate-x-1/2 -translate-y-1/2 rotate-90' />
</div>
<div className='text-text-tertiary text-sm font-normal'>
{text}
</div>
<div className='flex flex-col w-[240px]'>
<input
type='file'
ref={fileInputRef}
style={{ display: 'none' }}
onChange={handleFileChange}
accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
/>
<div className='w-full flex flex-col gap-y-1'>
{[
...(
(enable_marketplace || true)
? [{ icon: MagicBox, text: t('plugin.list.source.marketplace'), action: 'marketplace' }]
: []
),
{ icon: Github, text: t('plugin.list.source.github'), action: 'github' },
{ icon: FileZip, text: t('plugin.list.source.local'), action: 'local' },
].map(({ icon: Icon, text, action }) => (
<div
key={action}
className='flex items-center px-3 py-2 gap-x-1 rounded-lg bg-components-button-secondary-bg
hover:bg-state-base-hover cursor-pointer border-[0.5px] shadow-shadow-shadow-3 shadow-xs'
onClick={() => {
if (action === 'local')
fileInputRef.current?.click()
else if (action === 'marketplace')
setActiveTab('discover')
else
setSelectedAction(action)
}}
>
<Icon className="w-4 h-4 text-text-tertiary" />
<span className='text-text-secondary system-md-regular'>{text}</span>
</div>
))}
</div>
</div>
</div>
{selectedAction === 'github' && <InstallFromGitHub
onSuccess={() => { }}
onClose={() => setSelectedAction(null)}
/>}
{selectedAction === 'local' && selectedFile
&& (<InstallFromLocalPackage
file={selectedFile}
onClose={() => setSelectedAction(null)}
onSuccess={() => { }}
/>
)
}
</div>
</div>
)
}
Empty.displayName = 'Empty'
export default React.memo(Empty)

View File

@@ -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 items-center px-2 py-1 h-8 text-text-tertiary rounded-lg bg-components-input-bg-normal hover:bg-state-base-hover-alt cursor-pointer',
selectedTagsLength && 'text-text-secondary',
open && 'bg-state-base-hover',
)}>
<div className={cn(
'flex items-center p-1 system-sm-medium',
)}>
{
!selectedTagsLength && t('plugin.allCategories')
}
{
!!selectedTagsLength && value.map(val => categoriesMap[val].label).slice(0, 2).join(',')
}
{
selectedTagsLength > 2 && (
<div className='ml-1 system-xs-medium text-text-tertiary'>
+{selectedTagsLength - 2}
</div>
)
}
</div>
{
!!selectedTagsLength && (
<RiCloseCircleFill
className='w-4 h-4 text-text-quaternary cursor-pointer'
onClick={
(e) => {
e.stopPropagation()
onChange([])
}
}
/>
)
}
{
!selectedTagsLength && (
<RiArrowDownSLine className='w-4 h-4' />
)
}
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-10'>
<div className='w-[240px] border-[0.5px] border-components-panel-border bg-components-panel-bg-blur rounded-xl shadow-lg'>
<div className='p-2 pb-1'>
<Input
showLeftIcon
value={searchText}
onChange={e => setSearchText(e.target.value)}
placeholder={t('plugin.searchCategories')}
/>
</div>
<div className='p-1 max-h-[448px] overflow-y-auto'>
{
filteredOptions.map(option => (
<div
key={option.name}
className='flex items-center px-2 py-1.5 h-7 rounded-lg cursor-pointer hover:bg-state-base-hover'
onClick={() => handleCheck(option.name)}
>
<Checkbox
className='mr-1'
checked={value.includes(option.name)}
/>
<div className='px-1 system-sm-medium text-text-secondary'>
{option.label}
</div>
</div>
))
}
</div>
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default CategoriesFilter

View File

@@ -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
}

View File

@@ -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

View File

@@ -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

View File

@@ -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 })),
}))

View File

@@ -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, tagsMap } = 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 items-center px-2 py-1 h-8 text-text-tertiary rounded-lg bg-components-input-bg-normal hover:bg-state-base-hover-alt cursor-pointer',
selectedTagsLength && 'text-text-secondary',
open && 'bg-state-base-hover',
)}>
<div className={cn(
'flex items-center p-1 system-sm-medium',
)}>
{
!selectedTagsLength && t('pluginTags.allTags')
}
{
!!selectedTagsLength && value.map(val => tagsMap[val].label).slice(0, 2).join(',')
}
{
selectedTagsLength > 2 && (
<div className='ml-1 system-xs-medium text-text-tertiary'>
+{selectedTagsLength - 2}
</div>
)
}
</div>
{
!!selectedTagsLength && (
<RiCloseCircleFill
className='w-4 h-4 text-text-quaternary cursor-pointer'
onClick={() => onChange([])}
/>
)
}
{
!selectedTagsLength && (
<RiArrowDownSLine className='w-4 h-4' />
)
}
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-10'>
<div className='w-[240px] border-[0.5px] border-components-panel-border bg-components-panel-bg-blur rounded-xl shadow-lg'>
<div className='p-2 pb-1'>
<Input
showLeftIcon
value={searchText}
onChange={e => setSearchText(e.target.value)}
placeholder={t('pluginTags.searchTags')}
/>
</div>
<div className='p-1 max-h-[448px] overflow-y-auto'>
{
filteredOptions.map(option => (
<div
key={option.name}
className='flex items-center px-2 py-1.5 h-7 rounded-lg cursor-pointer hover:bg-state-base-hover'
onClick={() => handleCheck(option.name)}
>
<Checkbox
className='mr-1'
checked={value.includes(option.name)}
/>
<div className='px-1 system-sm-medium text-text-secondary'>
{option.label}
</div>
</div>
))
}
</div>
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default TagsFilter

View File

@@ -0,0 +1,276 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
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 usePermission from './use-permission'
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 PermissionSetModal from '@/app/components/plugins/permission-setting-modal/modal'
import { useSelector as useAppContextSelector } from '@/context/app-context'
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 { fetchBundleInfoFromMarketPlace, fetchManifestFromMarketPlace } from '@/service/plugins'
import { marketplaceApiPrefix } from '@/config'
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
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 searchParams = useSearchParams()
const { replace } = useRouter()
// just support install one package now
const packageId = useMemo(() => {
const idStrings = searchParams.get(PACKAGE_IDS_KEY)
try {
return idStrings ? JSON.parse(idStrings)[0] : ''
}
catch (e) {
return ''
}
}, [searchParams])
const [dependencies, setDependencies] = useState<Dependency[]>([])
const bundleInfo = useMemo(() => {
const info = searchParams.get(BUNDLE_INFO_KEY)
try {
return info ? JSON.parse(info) : undefined
}
catch (e) {
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 () => {
await sleep(100)
if (packageId) {
const { data } = await fetchManifestFromMarketPlace(encodeURIComponent(packageId))
const { plugin, version } = data
setManifest({
...plugin,
version: version.version,
icon: `${marketplaceApiPrefix}/plugins/${plugin.org}/${plugin.name}/icon`,
})
showInstallFromMarketplace()
return
}
if (bundleInfo) {
const { data } = await fetchBundleInfoFromMarketPlace(bundleInfo)
setDependencies(data.version.dependencies)
showInstallFromMarketplace()
}
})()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [packageId, bundleInfo])
const {
canManagement,
canDebugger,
canSetPermissions,
permissions,
setPermissions,
} = usePermission()
const [showPluginSettingModal, {
setTrue: setShowPluginSettingModal,
setFalse: setHidePluginSettingModal,
}] = useBoolean()
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 } = useAppContextSelector(s => s.systemFeatures)
const uploaderProps = useUploader({
onFileChange: setCurrentFile,
containerRef,
enabled: activeTab === 'plugins',
})
const { dragging, fileUploader, fileChangeHandle, removeFile } = uploaderProps
return (
<div
id='marketplace-container'
ref={containerRef}
className={cn('grow relative flex flex-col overflow-y-auto border-t border-divider-subtle', activeTab === 'plugins'
? 'rounded-t-xl bg-components-panel-bg'
: 'bg-background-body',
)}
>
<div
className={cn(
'sticky top-0 flex min-h-[60px] px-12 pt-4 pb-2 items-center self-stretch gap-1 z-10 bg-components-panel-bg', activeTab === 'discover' && 'bg-background-body',
)}
>
<div className='flex justify-between items-center w-full'>
<div className='flex-1'>
<TabSlider
value={activeTab}
onChange={setActiveTab}
options={options}
/>
</div>
<div className='flex shrink-0 items-center gap-1'>
{
activeTab === 'discover' && (
<>
<Link
href='https://docs.dify.ai/plugins/publish-plugins/publish-to-dify-marketplace'
target='_blank'
>
<Button
className='px-3'
variant='secondary-accent'
>
<RiBookOpenLine className='mr-1 w-4 h-4' />
{t('plugin.submitPlugin')}
</Button>
</Link>
<div className='mx-2 w-[1px] h-3.5 bg-divider-regular'></div>
</>
)
}
<PluginTasks />
{canManagement && (
<InstallPluginDropdown
onSwitchToMarketplaceTab={() => setActiveTab('discover')}
/>
)}
{
canDebugger && (
<DebugInfo />
)
}
{
canSetPermissions && (
<Tooltip
popupContent={t('plugin.privilege.title')}
>
<Button
className='w-full h-full p-2 text-components-button-secondary-text group'
onClick={setShowPluginSettingModal}
>
<RiEqualizer2Line className='w-4 h-4' />
</Button>
</Tooltip>
)
}
</div>
</div>
</div>
{activeTab === 'plugins' && (
<>
{plugins}
{dragging && (
<div
className="absolute inset-0 m-0.5 p-2 rounded-2xl bg-[rgba(21,90,239,0.14)] border-2
border-dashed border-components-dropzone-border-accent">
</div>
)}
<div className={`flex py-4 justify-center items-center gap-2 ${dragging ? 'text-text-accent' : 'text-text-quaternary'}`}>
<RiDragDropLine className="w-4 h-4" />
<span className="system-xs-regular">{t('plugin.installModal.dropPluginToInstall')}</span>
</div>
{currentFile && (
<InstallFromLocalPackage
file={currentFile}
onClose={removeFile ?? (() => { })}
onSuccess={() => { }}
/>
)}
<input
ref={fileUploader}
className="hidden"
type="file"
id="fileUploader"
accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
onChange={fileChangeHandle ?? (() => { })}
/>
</>
)}
{
activeTab === 'discover' && enable_marketplace && marketplace
}
{showPluginSettingModal && (
<PermissionSetModal
payload={permissions!}
onHide={setHidePluginSettingModal}
onSave={setPermissions}
/>
)}
{
isShowInstallFromMarketplace && (
<InstallFromMarketplace
manifest={manifest! as PluginManifestInMarket}
uniqueIdentifier={packageId}
isBundle={!!bundleInfo}
dependencies={dependencies}
onClose={hideInstallFromMarketplace}
onSuccess={hideInstallFromMarketplace}
/>
)
}
</div>
)
}
const PluginPageWithContext = (props: PluginPageProps) => {
return (
<PluginPageContextProvider>
<PluginPage {...props} />
</PluginPageContextProvider>
)
}
export default PluginPageWithContext

View File

@@ -0,0 +1,139 @@
'use client'
import { 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 { useSelector as useAppContextSelector } from '@/context/app-context'
import { useTranslation } from 'react-i18next'
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
type Props = {
onSwitchToMarketplaceTab: () => void
}
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 } = useAppContextSelector(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)
// }
return (
<PortalToFollowElem
open={isMenuOpen}
onOpenChange={setIsMenuOpen}
placement='bottom-start'
offset={4}
>
<div className="relative">
<PortalToFollowElemTrigger onClick={() => setIsMenuOpen(v => !v)}>
<Button
className={cn('w-full h-full p-2 text-components-button-secondary-text', isMenuOpen && 'bg-state-base-hover')}
>
<RiAddLine className='w-4 h-4' />
<span className='pl-1'>{t('plugin.installPlugin')}</span>
<RiArrowDownSLine className='w-4 h-4 ml-1' />
</Button>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-[1002]'>
<div className='flex flex-col p-1 pb-2 items-start w-[200px] bg-components-panel-bg-blur border border-components-panel-border rounded-xl shadows-shadow-lg'>
<span className='flex pt-1 pb-0.5 pl-2 pr-3 items-start self-stretch text-text-tertiary system-xs-medium-uppercase'>
{t('plugin.installFrom')}
</span>
<input
type='file'
ref={fileInputRef}
style={{ display: 'none' }}
onChange={handleFileChange}
accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
/>
<div className='w-full'>
{[
...(
(enable_marketplace || true)
? [{ icon: MagicBox, text: t('plugin.source.marketplace'), action: 'marketplace' }]
: []
),
{ icon: Github, text: t('plugin.source.github'), action: 'github' },
{ icon: FileZip, text: t('plugin.source.local'), action: 'local' },
].map(({ icon: Icon, text, action }) => (
<div
key={action}
className='flex items-center w-full px-2 py-1.5 gap-1 rounded-lg hover:bg-state-base-hover !cursor-pointer'
onClick={() => {
if (action === 'local') {
fileInputRef.current?.click()
}
else if (action === 'marketplace') {
onSwitchToMarketplaceTab()
setIsMenuOpen(false)
}
else {
setSelectedAction(action)
setIsMenuOpen(false)
}
}}
>
<Icon className="w-4 h-4 text-text-tertiary" />
<span className='px-1 text-text-secondary system-md-regular'>{text}</span>
</div>
))}
</div>
</div>
</PortalToFollowElemContent>
</div>
{selectedAction === 'github' && <InstallFromGitHub
onSuccess={() => { }}
onClose={() => setSelectedAction(null)}
/>}
{selectedAction === 'local' && selectedFile
&& (<InstallFromLocalPackage
file={selectedFile}
onClose={() => setSelectedAction(null)}
onSuccess={() => { }}
/>
)
}
{/* {pluginLists.map((item: any) => (
<div key={item.id} onClick={() => handleUninstall(item.id)}>{item.name} 卸载</div>
))} */}
</PortalToFollowElem>
)
}
export default InstallPluginDropdown

View 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

View 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)

View File

@@ -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.filter(task => task.status !== TaskStatus.success).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,
}
}

View File

@@ -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='flex items-center'
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 items-center justify-center w-8 h-8 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) && 'border-components-button-destructive-secondary-border-hover bg-state-destructive-hover hover:bg-state-destructive-hover-alt cursor-pointer',
)}
id="plugin-task-trigger"
>
{
(isInstalling || isInstallingWithError) && (
<DownloadingIcon />
)
}
{
!(isInstalling || isInstallingWithError) && (
<RiInstallLine
className={cn(
'w-4 h-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='w-3.5 h-3.5 text-text-success' />
)
}
{
isFailed && (
<RiErrorWarningFill className='w-3.5 h-3.5 text-text-destructive' />
)
}
</div>
</div>
</Tooltip>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-[11]'>
<div className='p-1 pb-2 w-[320px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg'>
<div className='sticky top-0 flex items-center justify-between px-2 pt-1 h-7 system-sm-semibold-uppercase'>
{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 p-2 rounded-lg hover:bg-state-base-hover'
>
<div className='relative flex items-center justify-center mr-2 w-6 h-6 rounded-md border-[0.5px] border-components-panel-border-subtle bg-background-default-dodge'>
<RiErrorWarningFill className='absolute -right-0.5 -bottom-0.5 z-10 w-3 h-3 text-text-destructive' />
<CardIcon
size='tiny'
src={getIconUrl(errorPlugin.icon)}
/>
</div>
<div className='grow'>
<div className='system-md-regular text-text-secondary truncate'>
{errorPlugin.labels[language]}
</div>
<div className='system-xs-regular text-text-destructive break-all'>
{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

View File

@@ -0,0 +1,70 @@
'use client'
import { useMemo } from 'react'
import type { FilterState } from './filter-management'
import FilterManagement from './filter-management'
import List from './list'
import { useInstalledPluginList, useInvalidateInstalledPluginList } from '@/service/use-plugins'
import PluginDetailPanel from '@/app/components/plugins/plugin-detail-panel'
import { usePluginPageContext } from './context'
import { useDebounceFn } from 'ahooks'
import Empty from './empty'
import Loading from '../../base/loading'
const PluginsPanel = () => {
const filters = usePluginPageContext(v => v.filters) as FilterState
const setFilters = usePluginPageContext(v => v.setFilters)
const { data: pluginList, isLoading: isPluginListLoading } = useInstalledPluginList()
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 filteredList = useMemo(() => {
const { categories, searchQuery, tags } = filters
const filteredList = pluginList?.plugins.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
}, [pluginList, filters])
const currentPluginDetail = useMemo(() => {
const detail = pluginList?.plugins.find(plugin => plugin.plugin_id === currentPluginID)
return detail
}, [currentPluginID, pluginList?.plugins])
const handleHide = () => setCurrentPluginID(undefined)
return (
<>
<div className='flex flex-col pt-1 pb-3 px-12 justify-center items-start gap-3 self-stretch'>
<div className='h-px self-stretch bg-divider-subtle'></div>
<FilterManagement
onFilterChange={handleFilterChange}
/>
</div>
{isPluginListLoading ? <Loading type='app' /> : (filteredList?.length ?? 0) > 0 ? (
<div className='flex px-12 items-start content-start gap-2 grow self-stretch flex-wrap'>
<div className='w-full'>
<List pluginList={filteredList || []} />
</div>
</div>
) : (
<Empty />
)}
<PluginDetailPanel
detail={currentPluginDetail}
onUpdate={() => invalidateInstalledPluginList()}
onHide={handleHide}
/>
</>
)
}
export default PluginsPanel

View File

@@ -0,0 +1,45 @@
import { PermissionType } from '../types'
import { useAppContext } from '@/context/app-context'
import Toast from '../../base/toast'
import { useTranslation } from 'react-i18next'
import { useInvalidatePermissions, useMutationPermissions, usePermissions } from '@/service/use-plugins'
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 usePermission = () => {
const { t } = useTranslation()
const { isCurrentWorkspaceManager, isCurrentWorkspaceOwner } = useAppContext()
const { data: permissions } = usePermissions()
const invalidatePermissions = useInvalidatePermissions()
const { mutate: updatePermission, isPending: isUpdatePending } = useMutationPermissions({
onSuccess: () => {
invalidatePermissions()
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
},
})
const isAdmin = isCurrentWorkspaceManager || isCurrentWorkspaceOwner
return {
canManagement: hasPermission(permissions?.install_permission, isAdmin),
canDebugger: hasPermission(permissions?.debug_permission, isAdmin),
canSetPermissions: isAdmin,
permissions,
setPermissions: updatePermission,
isUpdatePending,
}
}
export default usePermission

View File

@@ -0,0 +1,86 @@
import { useEffect, useRef, useState } from 'react'
type UploaderHookProps = {
onFileChange: (file: File | null) => void
containerRef: React.RefObject<HTMLDivElement>
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,
}
}