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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 useReferenceSetting from './use-reference-setting'
  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 ReferenceSettingModal from '@/app/components/plugins/reference-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. }, [packageId, bundleInfo])
  113. const {
  114. referenceSetting,
  115. canManagement,
  116. canDebugger,
  117. canSetPermissions,
  118. setReferenceSettings,
  119. } = useReferenceSetting()
  120. const [showPluginSettingModal, {
  121. setTrue: setShowPluginSettingModal,
  122. setFalse: setHidePluginSettingModal,
  123. }] = useBoolean(false)
  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 } = useGlobalPublicStore(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://github.com/langgenius/dify-plugins/issues/new?template=plugin_request.yaml'
  177. target='_blank'
  178. >
  179. <Button
  180. variant='ghost'
  181. className='text-text-tertiary'
  182. >
  183. {t('plugin.requestAPlugin')}
  184. </Button>
  185. </Link>
  186. <Link
  187. href={getDocsUrl(locale, '/plugins/publish-plugins/publish-to-dify-marketplace/README')}
  188. target='_blank'
  189. >
  190. <Button
  191. className='px-3'
  192. variant='secondary-accent'
  193. >
  194. <RiBookOpenLine className='mr-1 h-4 w-4' />
  195. {t('plugin.publishPlugins')}
  196. </Button>
  197. </Link>
  198. <div className='mx-1 h-3.5 w-[1px] shrink-0 bg-divider-regular'></div>
  199. </>
  200. )
  201. }
  202. <PluginTasks />
  203. {canManagement && (
  204. <InstallPluginDropdown
  205. onSwitchToMarketplaceTab={() => setActiveTab('discover')}
  206. />
  207. )}
  208. {
  209. canDebugger && (
  210. <DebugInfo />
  211. )
  212. }
  213. {
  214. canSetPermissions && (
  215. <Tooltip
  216. popupContent={t('plugin.privilege.title')}
  217. >
  218. <Button
  219. className='group h-full w-full p-2 text-components-button-secondary-text'
  220. onClick={setShowPluginSettingModal}
  221. >
  222. <RiEqualizer2Line className='h-4 w-4' />
  223. </Button>
  224. </Tooltip>
  225. )
  226. }
  227. </div>
  228. </div>
  229. </div>
  230. {isPluginsTab && (
  231. <>
  232. {plugins}
  233. {dragging && (
  234. <div
  235. className="absolute inset-0 m-0.5 rounded-2xl border-2 border-dashed border-components-dropzone-border-accent
  236. bg-[rgba(21,90,239,0.14)] p-2">
  237. </div>
  238. )}
  239. <div className={`flex items-center justify-center gap-2 py-4 ${dragging ? 'text-text-accent' : 'text-text-quaternary'}`}>
  240. <RiDragDropLine className="h-4 w-4" />
  241. <span className="system-xs-regular">{t('plugin.installModal.dropPluginToInstall')}</span>
  242. </div>
  243. {currentFile && (
  244. <InstallFromLocalPackage
  245. file={currentFile}
  246. onClose={removeFile ?? noop}
  247. onSuccess={noop}
  248. />
  249. )}
  250. <input
  251. ref={fileUploader}
  252. className="hidden"
  253. type="file"
  254. id="fileUploader"
  255. accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
  256. onChange={fileChangeHandle ?? noop}
  257. />
  258. </>
  259. )}
  260. {
  261. isExploringMarketplace && enable_marketplace && marketplace
  262. }
  263. {showPluginSettingModal && (
  264. <ReferenceSettingModal
  265. payload={referenceSetting!}
  266. onHide={setHidePluginSettingModal}
  267. onSave={setReferenceSettings}
  268. />
  269. )}
  270. {
  271. isShowInstallFromMarketplace && (
  272. <InstallFromMarketplace
  273. manifest={manifest! as PluginManifestInMarket}
  274. uniqueIdentifier={packageId}
  275. isBundle={!!bundleInfo}
  276. dependencies={dependencies}
  277. onClose={hideInstallFromMarketplace}
  278. onSuccess={hideInstallFromMarketplace}
  279. />
  280. )
  281. }
  282. </div>
  283. )
  284. }
  285. const PluginPageWithContext = (props: PluginPageProps) => {
  286. return (
  287. <PluginPageContextProvider>
  288. <PluginPage {...props} />
  289. </PluginPageContextProvider>
  290. )
  291. }
  292. export default PluginPageWithContext