AppCard.tsx 16 KB

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