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.

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