AppCard.tsx 15 KB

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