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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. 'use client'
  2. import { useEffect, useMemo, useState } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import { useContext } from 'use-context-selector'
  5. import Link from 'next/link'
  6. import {
  7. RiBookOpenLine,
  8. RiDragDropLine,
  9. RiEqualizer2Line,
  10. } from '@remixicon/react'
  11. import { useBoolean } from 'ahooks'
  12. import InstallFromLocalPackage from '../install-plugin/install-from-local-package'
  13. import {
  14. PluginPageContextProvider,
  15. usePluginPageContext,
  16. } from './context'
  17. import InstallPluginDropdown from './install-plugin-dropdown'
  18. import { useUploader } from './use-uploader'
  19. import usePermission from './use-permission'
  20. import DebugInfo from './debug-info'
  21. import PluginTasks from './plugin-tasks'
  22. import Button from '@/app/components/base/button'
  23. import TabSlider from '@/app/components/base/tab-slider'
  24. import Tooltip from '@/app/components/base/tooltip'
  25. import cn from '@/utils/classnames'
  26. import PermissionSetModal from '@/app/components/plugins/permission-setting-modal/modal'
  27. import { useSelector as useAppContextSelector } from '@/context/app-context'
  28. import InstallFromMarketplace from '../install-plugin/install-from-marketplace'
  29. import {
  30. useRouter,
  31. useSearchParams,
  32. } from 'next/navigation'
  33. import type { Dependency } from '../types'
  34. import type { PluginDeclaration, PluginManifestInMarket } from '../types'
  35. import { sleep } from '@/utils'
  36. import { fetchBundleInfoFromMarketPlace, fetchManifestFromMarketPlace } from '@/service/plugins'
  37. import { marketplaceApiPrefix } from '@/config'
  38. import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
  39. import { LanguagesSupported } from '@/i18n/language'
  40. import I18n from '@/context/i18n'
  41. import { noop } from 'lodash-es'
  42. import { PLUGIN_TYPE_SEARCH_MAP } from '../marketplace/plugin-type-switch'
  43. import { PLUGIN_PAGE_TABS_MAP } from '../hooks'
  44. const PACKAGE_IDS_KEY = 'package-ids'
  45. const BUNDLE_INFO_KEY = 'bundle-info'
  46. export type PluginPageProps = {
  47. plugins: React.ReactNode
  48. marketplace: React.ReactNode
  49. }
  50. const PluginPage = ({
  51. plugins,
  52. marketplace,
  53. }: PluginPageProps) => {
  54. const { t } = useTranslation()
  55. const { locale } = useContext(I18n)
  56. const searchParams = useSearchParams()
  57. const { replace } = useRouter()
  58. document.title = `${t('plugin.metadata.title')} - Dify`
  59. // just support install one package now
  60. const packageId = useMemo(() => {
  61. const idStrings = searchParams.get(PACKAGE_IDS_KEY)
  62. try {
  63. return idStrings ? JSON.parse(idStrings)[0] : ''
  64. }
  65. catch {
  66. return ''
  67. }
  68. }, [searchParams])
  69. const [dependencies, setDependencies] = useState<Dependency[]>([])
  70. const bundleInfo = useMemo(() => {
  71. const info = searchParams.get(BUNDLE_INFO_KEY)
  72. try {
  73. return info ? JSON.parse(info) : undefined
  74. }
  75. catch {
  76. return undefined
  77. }
  78. }, [searchParams])
  79. const [isShowInstallFromMarketplace, {
  80. setTrue: showInstallFromMarketplace,
  81. setFalse: doHideInstallFromMarketplace,
  82. }] = useBoolean(false)
  83. const hideInstallFromMarketplace = () => {
  84. doHideInstallFromMarketplace()
  85. const url = new URL(window.location.href)
  86. url.searchParams.delete(PACKAGE_IDS_KEY)
  87. url.searchParams.delete(BUNDLE_INFO_KEY)
  88. replace(url.toString())
  89. }
  90. const [manifest, setManifest] = useState<PluginDeclaration | PluginManifestInMarket | null>(null)
  91. useEffect(() => {
  92. (async () => {
  93. await sleep(100)
  94. if (packageId) {
  95. const { data } = await fetchManifestFromMarketPlace(encodeURIComponent(packageId))
  96. const { plugin, version } = data
  97. setManifest({
  98. ...plugin,
  99. version: version.version,
  100. icon: `${marketplaceApiPrefix}/plugins/${plugin.org}/${plugin.name}/icon`,
  101. })
  102. showInstallFromMarketplace()
  103. return
  104. }
  105. if (bundleInfo) {
  106. const { data } = await fetchBundleInfoFromMarketPlace(bundleInfo)
  107. setDependencies(data.version.dependencies)
  108. showInstallFromMarketplace()
  109. }
  110. })()
  111. // eslint-disable-next-line react-hooks/exhaustive-deps
  112. }, [packageId, bundleInfo])
  113. const {
  114. canManagement,
  115. canDebugger,
  116. canSetPermissions,
  117. permissions,
  118. setPermissions,
  119. } = usePermission()
  120. const [showPluginSettingModal, {
  121. setTrue: setShowPluginSettingModal,
  122. setFalse: setHidePluginSettingModal,
  123. }] = useBoolean()
  124. const [currentFile, setCurrentFile] = useState<File | null>(null)
  125. const containerRef = usePluginPageContext(v => v.containerRef)
  126. const options = usePluginPageContext(v => v.options)
  127. const activeTab = usePluginPageContext(v => v.activeTab)
  128. const setActiveTab = usePluginPageContext(v => v.setActiveTab)
  129. const { enable_marketplace } = useAppContextSelector(s => s.systemFeatures)
  130. const isPluginsTab = useMemo(() => activeTab === PLUGIN_PAGE_TABS_MAP.plugins, [activeTab])
  131. const isExploringMarketplace = useMemo(() => {
  132. const values = Object.values(PLUGIN_TYPE_SEARCH_MAP)
  133. return activeTab === PLUGIN_PAGE_TABS_MAP.marketplace || values.includes(activeTab)
  134. }, [activeTab])
  135. const handleFileChange = (file: File | null) => {
  136. if (!file || !file.name.endsWith('.difypkg')) {
  137. setCurrentFile(null)
  138. return
  139. }
  140. setCurrentFile(file)
  141. }
  142. const uploaderProps = useUploader({
  143. onFileChange: handleFileChange,
  144. containerRef,
  145. enabled: isPluginsTab && canManagement,
  146. })
  147. const { dragging, fileUploader, fileChangeHandle, removeFile } = uploaderProps
  148. return (
  149. <div
  150. id='marketplace-container'
  151. ref={containerRef}
  152. style={{ scrollbarGutter: 'stable' }}
  153. className={cn('relative flex grow flex-col overflow-y-auto border-t border-divider-subtle', isPluginsTab
  154. ? 'rounded-t-xl bg-components-panel-bg'
  155. : 'bg-background-body',
  156. )}
  157. >
  158. <div
  159. className={cn(
  160. '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',
  161. )}
  162. >
  163. <div className='flex w-full items-center justify-between'>
  164. <div className='flex-1'>
  165. <TabSlider
  166. value={isPluginsTab ? PLUGIN_PAGE_TABS_MAP.plugins : PLUGIN_PAGE_TABS_MAP.marketplace}
  167. onChange={setActiveTab}
  168. options={options}
  169. />
  170. </div>
  171. <div className='flex shrink-0 items-center gap-1'>
  172. {
  173. isExploringMarketplace && (
  174. <>
  175. <Link
  176. href={`https://docs.dify.ai/${locale === LanguagesSupported[1] ? 'v/zh-hans/' : ''}plugins/publish-plugins/publish-to-dify-marketplace`}
  177. target='_blank'
  178. >
  179. <Button
  180. className='px-3'
  181. variant='secondary-accent'
  182. >
  183. <RiBookOpenLine className='mr-1 h-4 w-4' />
  184. {t('plugin.submitPlugin')}
  185. </Button>
  186. </Link>
  187. <div className='mx-2 h-3.5 w-[1px] bg-divider-regular'></div>
  188. </>
  189. )
  190. }
  191. <PluginTasks />
  192. {canManagement && (
  193. <InstallPluginDropdown
  194. onSwitchToMarketplaceTab={() => setActiveTab('discover')}
  195. />
  196. )}
  197. {
  198. canDebugger && (
  199. <DebugInfo />
  200. )
  201. }
  202. {
  203. canSetPermissions && (
  204. <Tooltip
  205. popupContent={t('plugin.privilege.title')}
  206. >
  207. <Button
  208. className='group h-full w-full p-2 text-components-button-secondary-text'
  209. onClick={setShowPluginSettingModal}
  210. >
  211. <RiEqualizer2Line className='h-4 w-4' />
  212. </Button>
  213. </Tooltip>
  214. )
  215. }
  216. </div>
  217. </div>
  218. </div>
  219. {isPluginsTab && (
  220. <>
  221. {plugins}
  222. {dragging && (
  223. <div
  224. className="absolute inset-0 m-0.5 rounded-2xl border-2 border-dashed border-components-dropzone-border-accent
  225. bg-[rgba(21,90,239,0.14)] p-2">
  226. </div>
  227. )}
  228. <div className={`flex items-center justify-center gap-2 py-4 ${dragging ? 'text-text-accent' : 'text-text-quaternary'}`}>
  229. <RiDragDropLine className="h-4 w-4" />
  230. <span className="system-xs-regular">{t('plugin.installModal.dropPluginToInstall')}</span>
  231. </div>
  232. {currentFile && (
  233. <InstallFromLocalPackage
  234. file={currentFile}
  235. onClose={removeFile ?? noop}
  236. onSuccess={noop}
  237. />
  238. )}
  239. <input
  240. ref={fileUploader}
  241. className="hidden"
  242. type="file"
  243. id="fileUploader"
  244. accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
  245. onChange={fileChangeHandle ?? noop}
  246. />
  247. </>
  248. )}
  249. {
  250. isExploringMarketplace && enable_marketplace && marketplace
  251. }
  252. {showPluginSettingModal && (
  253. <PermissionSetModal
  254. payload={permissions!}
  255. onHide={setHidePluginSettingModal}
  256. onSave={setPermissions}
  257. />
  258. )}
  259. {
  260. isShowInstallFromMarketplace && (
  261. <InstallFromMarketplace
  262. manifest={manifest! as PluginManifestInMarket}
  263. uniqueIdentifier={packageId}
  264. isBundle={!!bundleInfo}
  265. dependencies={dependencies}
  266. onClose={hideInstallFromMarketplace}
  267. onSuccess={hideInstallFromMarketplace}
  268. />
  269. )
  270. }
  271. </div>
  272. )
  273. }
  274. const PluginPageWithContext = (props: PluginPageProps) => {
  275. return (
  276. <PluginPageContextProvider>
  277. <PluginPage {...props} />
  278. </PluginPageContextProvider>
  279. )
  280. }
  281. export default PluginPageWithContext