您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

AppCard.tsx 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. 'use client'
  2. import { useContext, useContextSelector } from 'use-context-selector'
  3. import { useRouter } from 'next/navigation'
  4. import { useCallback, useEffect, useState } from 'react'
  5. import { useTranslation } from 'react-i18next'
  6. import { RiBuildingLine, RiGlobalLine, RiLockLine, RiMoreFill } from '@remixicon/react'
  7. import cn from '@/utils/classnames'
  8. import type { App } from '@/types/app'
  9. import Confirm from '@/app/components/base/confirm'
  10. import Toast, { ToastContext } from '@/app/components/base/toast'
  11. import { copyApp, deleteApp, exportAppConfig, updateAppInfo } from '@/service/apps'
  12. import DuplicateAppModal from '@/app/components/app/duplicate-modal'
  13. import type { DuplicateAppModalProps } from '@/app/components/app/duplicate-modal'
  14. import AppIcon from '@/app/components/base/app-icon'
  15. import AppsContext, { useAppContext } from '@/context/app-context'
  16. import type { HtmlContentProps } from '@/app/components/base/popover'
  17. import CustomPopover from '@/app/components/base/popover'
  18. import Divider from '@/app/components/base/divider'
  19. import { basePath } from '@/utils/var'
  20. import { getRedirection } from '@/utils/app-redirection'
  21. import { useProviderContext } from '@/context/provider-context'
  22. import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
  23. import type { CreateAppModalProps } from '@/app/components/explore/create-app-modal'
  24. import EditAppModal from '@/app/components/explore/create-app-modal'
  25. import SwitchAppModal from '@/app/components/app/switch-app-modal'
  26. import type { Tag } from '@/app/components/base/tag-management/constant'
  27. import TagSelector from '@/app/components/base/tag-management/selector'
  28. import type { EnvironmentVariable } from '@/app/components/workflow/types'
  29. import DSLExportConfirmModal from '@/app/components/workflow/dsl-export-confirm-modal'
  30. import { fetchWorkflowDraft } from '@/service/workflow'
  31. import { fetchInstalledAppList } from '@/service/explore'
  32. import { AppTypeIcon } from '@/app/components/app/type-selector'
  33. import Tooltip from '@/app/components/base/tooltip'
  34. import AccessControl from '@/app/components/app/app-access-control'
  35. import { AccessMode } from '@/models/access-control'
  36. import { useGlobalPublicStore } from '@/context/global-public-context'
  37. export type AppCardProps = {
  38. app: App
  39. onRefresh?: () => void
  40. }
  41. const AppCard = ({ app, onRefresh }: AppCardProps) => {
  42. const { t } = useTranslation()
  43. const { notify } = useContext(ToastContext)
  44. const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
  45. const { isCurrentWorkspaceEditor } = useAppContext()
  46. const { onPlanInfoChanged } = useProviderContext()
  47. const { push } = useRouter()
  48. const mutateApps = useContextSelector(
  49. AppsContext,
  50. state => state.mutateApps,
  51. )
  52. const [showEditModal, setShowEditModal] = useState(false)
  53. const [showDuplicateModal, setShowDuplicateModal] = useState(false)
  54. const [showSwitchModal, setShowSwitchModal] = useState<boolean>(false)
  55. const [showConfirmDelete, setShowConfirmDelete] = useState(false)
  56. const [showAccessControl, setShowAccessControl] = useState(false)
  57. const [secretEnvList, setSecretEnvList] = useState<EnvironmentVariable[]>([])
  58. const onConfirmDelete = useCallback(async () => {
  59. try {
  60. await deleteApp(app.id)
  61. notify({ type: 'success', message: t('app.appDeleted') })
  62. if (onRefresh)
  63. onRefresh()
  64. mutateApps()
  65. onPlanInfoChanged()
  66. }
  67. catch (e: any) {
  68. notify({
  69. type: 'error',
  70. message: `${t('app.appDeleteFailed')}${'message' in e ? `: ${e.message}` : ''}`,
  71. })
  72. }
  73. setShowConfirmDelete(false)
  74. }, [app.id, mutateApps, notify, onPlanInfoChanged, onRefresh, t])
  75. const onEdit: CreateAppModalProps['onConfirm'] = useCallback(async ({
  76. name,
  77. icon_type,
  78. icon,
  79. icon_background,
  80. description,
  81. use_icon_as_answer_icon,
  82. }) => {
  83. try {
  84. await updateAppInfo({
  85. appID: app.id,
  86. name,
  87. icon_type,
  88. icon,
  89. icon_background,
  90. description,
  91. use_icon_as_answer_icon,
  92. })
  93. setShowEditModal(false)
  94. notify({
  95. type: 'success',
  96. message: t('app.editDone'),
  97. })
  98. if (onRefresh)
  99. onRefresh()
  100. mutateApps()
  101. }
  102. catch {
  103. notify({ type: 'error', message: t('app.editFailed') })
  104. }
  105. }, [app.id, mutateApps, notify, onRefresh, t])
  106. const onCopy: DuplicateAppModalProps['onConfirm'] = async ({ name, icon_type, icon, icon_background }) => {
  107. try {
  108. const newApp = await copyApp({
  109. appID: app.id,
  110. name,
  111. icon_type,
  112. icon,
  113. icon_background,
  114. mode: app.mode,
  115. })
  116. setShowDuplicateModal(false)
  117. notify({
  118. type: 'success',
  119. message: t('app.newApp.appCreated'),
  120. })
  121. localStorage.setItem(NEED_REFRESH_APP_LIST_KEY, '1')
  122. if (onRefresh)
  123. onRefresh()
  124. mutateApps()
  125. onPlanInfoChanged()
  126. getRedirection(isCurrentWorkspaceEditor, newApp, push)
  127. }
  128. catch {
  129. notify({ type: 'error', message: t('app.newApp.appCreateFailed') })
  130. }
  131. }
  132. const onExport = async (include = false) => {
  133. try {
  134. const { data } = await exportAppConfig({
  135. appID: app.id,
  136. include,
  137. })
  138. const a = document.createElement('a')
  139. const file = new Blob([data], { type: 'application/yaml' })
  140. a.href = URL.createObjectURL(file)
  141. a.download = `${app.name}.yml`
  142. a.click()
  143. }
  144. catch {
  145. notify({ type: 'error', message: t('app.exportFailed') })
  146. }
  147. }
  148. const exportCheck = async () => {
  149. if (app.mode !== 'workflow' && app.mode !== 'advanced-chat') {
  150. onExport()
  151. return
  152. }
  153. try {
  154. const workflowDraft = await fetchWorkflowDraft(`/apps/${app.id}/workflows/draft`)
  155. const list = (workflowDraft.environment_variables || []).filter(env => env.value_type === 'secret')
  156. if (list.length === 0) {
  157. onExport()
  158. return
  159. }
  160. setSecretEnvList(list)
  161. }
  162. catch {
  163. notify({ type: 'error', message: t('app.exportFailed') })
  164. }
  165. }
  166. const onSwitch = () => {
  167. if (onRefresh)
  168. onRefresh()
  169. mutateApps()
  170. setShowSwitchModal(false)
  171. }
  172. const onUpdateAccessControl = useCallback(() => {
  173. if (onRefresh)
  174. onRefresh()
  175. mutateApps()
  176. setShowAccessControl(false)
  177. }, [onRefresh, mutateApps, setShowAccessControl])
  178. const Operations = (props: HtmlContentProps) => {
  179. const onMouseLeave = async () => {
  180. props.onClose?.()
  181. }
  182. const onClickSettings = async (e: React.MouseEvent<HTMLButtonElement>) => {
  183. e.stopPropagation()
  184. props.onClick?.()
  185. e.preventDefault()
  186. setShowEditModal(true)
  187. }
  188. const onClickDuplicate = async (e: React.MouseEvent<HTMLButtonElement>) => {
  189. e.stopPropagation()
  190. props.onClick?.()
  191. e.preventDefault()
  192. setShowDuplicateModal(true)
  193. }
  194. const onClickExport = async (e: React.MouseEvent<HTMLButtonElement>) => {
  195. e.stopPropagation()
  196. props.onClick?.()
  197. e.preventDefault()
  198. exportCheck()
  199. }
  200. const onClickSwitch = async (e: React.MouseEvent<HTMLButtonElement>) => {
  201. e.stopPropagation()
  202. props.onClick?.()
  203. e.preventDefault()
  204. setShowSwitchModal(true)
  205. }
  206. const onClickDelete = async (e: React.MouseEvent<HTMLButtonElement>) => {
  207. e.stopPropagation()
  208. props.onClick?.()
  209. e.preventDefault()
  210. setShowConfirmDelete(true)
  211. }
  212. const onClickAccessControl = async (e: React.MouseEvent<HTMLButtonElement>) => {
  213. e.stopPropagation()
  214. props.onClick?.()
  215. e.preventDefault()
  216. setShowAccessControl(true)
  217. }
  218. const onClickInstalledApp = async (e: React.MouseEvent<HTMLButtonElement>) => {
  219. e.stopPropagation()
  220. props.onClick?.()
  221. e.preventDefault()
  222. try {
  223. const { installed_apps }: any = await fetchInstalledAppList(app.id) || {}
  224. if (installed_apps?.length > 0)
  225. window.open(`${basePath}/explore/installed/${installed_apps[0].id}`, '_blank')
  226. else
  227. throw new Error('No app found in Explore')
  228. }
  229. catch (e: any) {
  230. Toast.notify({ type: 'error', message: `${e.message || e}` })
  231. }
  232. }
  233. return (
  234. <div className="relative flex w-full flex-col py-1" onMouseLeave={onMouseLeave}>
  235. <button className='mx-1 flex h-8 cursor-pointer items-center gap-2 rounded-lg px-3 hover:bg-state-base-hover' onClick={onClickSettings}>
  236. <span className='system-sm-regular text-text-secondary'>{t('app.editApp')}</span>
  237. </button>
  238. <Divider className="my-1" />
  239. <button className='mx-1 flex h-8 cursor-pointer items-center gap-2 rounded-lg px-3 hover:bg-state-base-hover' onClick={onClickDuplicate}>
  240. <span className='system-sm-regular text-text-secondary'>{t('app.duplicate')}</span>
  241. </button>
  242. <button className='mx-1 flex h-8 cursor-pointer items-center gap-2 rounded-lg px-3 hover:bg-state-base-hover' onClick={onClickExport}>
  243. <span className='system-sm-regular text-text-secondary'>{t('app.export')}</span>
  244. </button>
  245. {(app.mode === 'completion' || app.mode === 'chat') && (
  246. <>
  247. <Divider className="my-1" />
  248. <button
  249. className='mx-1 flex h-8 cursor-pointer items-center rounded-lg px-3 hover:bg-state-base-hover'
  250. onClick={onClickSwitch}
  251. >
  252. <span className='text-sm leading-5 text-text-secondary'>{t('app.switch')}</span>
  253. </button>
  254. </>
  255. )}
  256. <Divider className="my-1" />
  257. <button className='mx-1 flex h-8 cursor-pointer items-center gap-2 rounded-lg px-3 hover:bg-state-base-hover' onClick={onClickInstalledApp}>
  258. <span className='system-sm-regular text-text-secondary'>{t('app.openInExplore')}</span>
  259. </button>
  260. <Divider className="my-1" />
  261. {
  262. systemFeatures.webapp_auth.enabled && isCurrentWorkspaceEditor && <>
  263. <button className='mx-1 flex h-8 cursor-pointer items-center rounded-lg px-3 hover:bg-state-base-hover' onClick={onClickAccessControl}>
  264. <span className='text-sm leading-5 text-text-secondary'>{t('app.accessControl')}</span>
  265. </button>
  266. <Divider className='my-1' />
  267. </>
  268. }
  269. <button
  270. className='group mx-1 flex h-8 cursor-pointer items-center gap-2 rounded-lg px-3 py-[6px] hover:bg-state-destructive-hover'
  271. onClick={onClickDelete}
  272. >
  273. <span className='system-sm-regular text-text-secondary group-hover:text-text-destructive'>
  274. {t('common.operation.delete')}
  275. </span>
  276. </button>
  277. </div>
  278. )
  279. }
  280. const [tags, setTags] = useState<Tag[]>(app.tags)
  281. useEffect(() => {
  282. setTags(app.tags)
  283. }, [app.tags])
  284. return (
  285. <>
  286. <div
  287. onClick={(e) => {
  288. e.preventDefault()
  289. getRedirection(isCurrentWorkspaceEditor, app, push)
  290. }}
  291. className='group relative col-span-1 inline-flex h-[160px] cursor-pointer flex-col rounded-xl border-[1px] border-solid border-components-card-border bg-components-card-bg shadow-sm transition-all duration-200 ease-in-out hover:shadow-lg'
  292. >
  293. <div className='flex h-[66px] shrink-0 grow-0 items-center gap-3 px-[14px] pb-3 pt-[14px]'>
  294. <div className='relative shrink-0'>
  295. <AppIcon
  296. size="large"
  297. iconType={app.icon_type}
  298. icon={app.icon}
  299. background={app.icon_background}
  300. imageUrl={app.icon_url}
  301. />
  302. <AppTypeIcon type={app.mode} wrapperClassName='absolute -bottom-0.5 -right-0.5 w-4 h-4 shadow-sm' className='h-3 w-3' />
  303. </div>
  304. <div className='w-0 grow py-[1px]'>
  305. <div className='flex items-center text-sm font-semibold leading-5 text-text-secondary'>
  306. <div className='truncate' title={app.name}>{app.name}</div>
  307. </div>
  308. <div className='flex items-center text-[10px] font-medium leading-[18px] text-text-tertiary'>
  309. {app.mode === 'advanced-chat' && <div className='truncate'>{t('app.types.advanced').toUpperCase()}</div>}
  310. {app.mode === 'chat' && <div className='truncate'>{t('app.types.chatbot').toUpperCase()}</div>}
  311. {app.mode === 'agent-chat' && <div className='truncate'>{t('app.types.agent').toUpperCase()}</div>}
  312. {app.mode === 'workflow' && <div className='truncate'>{t('app.types.workflow').toUpperCase()}</div>}
  313. {app.mode === 'completion' && <div className='truncate'>{t('app.types.completion').toUpperCase()}</div>}
  314. </div>
  315. </div>
  316. <div className='flex h-5 w-5 shrink-0 items-center justify-center'>
  317. {app.access_mode === AccessMode.PUBLIC && <Tooltip asChild={false} popupContent={t('app.accessItemsDescription.anyone')}>
  318. <RiGlobalLine className='h-4 w-4 text-text-accent' />
  319. </Tooltip>}
  320. {app.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS && <Tooltip asChild={false} popupContent={t('app.accessItemsDescription.specific')}>
  321. <RiLockLine className='h-4 w-4 text-text-quaternary' />
  322. </Tooltip>}
  323. {app.access_mode === AccessMode.ORGANIZATION && <Tooltip asChild={false} popupContent={t('app.accessItemsDescription.organization')}>
  324. <RiBuildingLine className='h-4 w-4 text-text-quaternary' />
  325. </Tooltip>}
  326. </div>
  327. </div>
  328. <div className='title-wrapper h-[90px] px-[14px] text-xs leading-normal text-text-tertiary'>
  329. <div
  330. className={cn(tags.length ? 'line-clamp-2' : 'line-clamp-4', 'group-hover:line-clamp-2')}
  331. title={app.description}
  332. >
  333. {app.description}
  334. </div>
  335. </div>
  336. <div className={cn(
  337. 'absolute bottom-1 left-0 right-0 h-[42px] shrink-0 items-center pb-[6px] pl-[14px] pr-[6px] pt-1',
  338. tags.length ? 'flex' : '!hidden group-hover:!flex',
  339. )}>
  340. {isCurrentWorkspaceEditor && (
  341. <>
  342. <div className={cn('flex w-0 grow items-center gap-1')} onClick={(e) => {
  343. e.stopPropagation()
  344. e.preventDefault()
  345. }}>
  346. <div className={cn(
  347. 'mr-[41px] w-full grow group-hover:!mr-0 group-hover:!block',
  348. tags.length ? '!block' : '!hidden',
  349. )}>
  350. <TagSelector
  351. position='bl'
  352. type='app'
  353. targetID={app.id}
  354. value={tags.map(tag => tag.id)}
  355. selectedTags={tags}
  356. onCacheUpdate={setTags}
  357. onChange={onRefresh}
  358. />
  359. </div>
  360. </div>
  361. <div className='mx-1 !hidden h-[14px] w-[1px] shrink-0 group-hover:!flex' />
  362. <div className='!hidden shrink-0 group-hover:!flex'>
  363. <CustomPopover
  364. htmlContent={<Operations />}
  365. position="br"
  366. trigger="click"
  367. btnElement={
  368. <div
  369. className='flex h-8 w-8 cursor-pointer items-center justify-center rounded-md'
  370. >
  371. <RiMoreFill className='h-4 w-4 text-text-tertiary' />
  372. </div>
  373. }
  374. btnClassName={open =>
  375. cn(
  376. open ? '!bg-black/5 !shadow-none' : '!bg-transparent',
  377. 'h-8 w-8 rounded-md border-none !p-2 hover:!bg-black/5',
  378. )
  379. }
  380. popupClassName={
  381. (app.mode === 'completion' || app.mode === 'chat')
  382. ? '!w-[256px] translate-x-[-224px]'
  383. : '!w-[216px] translate-x-[-128px]'
  384. }
  385. className={'!z-20 h-fit'}
  386. />
  387. </div>
  388. </>
  389. )}
  390. </div>
  391. </div>
  392. {showEditModal && (
  393. <EditAppModal
  394. isEditModal
  395. appName={app.name}
  396. appIconType={app.icon_type}
  397. appIcon={app.icon}
  398. appIconBackground={app.icon_background}
  399. appIconUrl={app.icon_url}
  400. appDescription={app.description}
  401. appMode={app.mode}
  402. appUseIconAsAnswerIcon={app.use_icon_as_answer_icon}
  403. show={showEditModal}
  404. onConfirm={onEdit}
  405. onHide={() => setShowEditModal(false)}
  406. />
  407. )}
  408. {showDuplicateModal && (
  409. <DuplicateAppModal
  410. appName={app.name}
  411. icon_type={app.icon_type}
  412. icon={app.icon}
  413. icon_background={app.icon_background}
  414. icon_url={app.icon_url}
  415. show={showDuplicateModal}
  416. onConfirm={onCopy}
  417. onHide={() => setShowDuplicateModal(false)}
  418. />
  419. )}
  420. {showSwitchModal && (
  421. <SwitchAppModal
  422. show={showSwitchModal}
  423. appDetail={app}
  424. onClose={() => setShowSwitchModal(false)}
  425. onSuccess={onSwitch}
  426. />
  427. )}
  428. {showConfirmDelete && (
  429. <Confirm
  430. title={t('app.deleteAppConfirmTitle')}
  431. content={t('app.deleteAppConfirmContent')}
  432. isShow={showConfirmDelete}
  433. onConfirm={onConfirmDelete}
  434. onCancel={() => setShowConfirmDelete(false)}
  435. />
  436. )}
  437. {secretEnvList.length > 0 && (
  438. <DSLExportConfirmModal
  439. envList={secretEnvList}
  440. onConfirm={onExport}
  441. onClose={() => setSecretEnvList([])}
  442. />
  443. )}
  444. {showAccessControl && (
  445. <AccessControl app={app} onConfirm={onUpdateAccessControl} onClose={() => setShowAccessControl(false)} />
  446. )}
  447. </>
  448. )
  449. }
  450. export default AppCard