AppCard.tsx 15 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, { 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 { AiText, ChatBot, CuteRobot } from '@/app/components/base/icons/src/vender/solid/communication'
  24. import { Route } from '@/app/components/base/icons/src/vender/solid/mapsAndTravel'
  25. import type { CreateAppModalProps } from '@/app/components/explore/create-app-modal'
  26. import EditAppModal from '@/app/components/explore/create-app-modal'
  27. import SwitchAppModal from '@/app/components/app/switch-app-modal'
  28. import type { Tag } from '@/app/components/base/tag-management/constant'
  29. import TagSelector from '@/app/components/base/tag-management/selector'
  30. import type { EnvironmentVariable } from '@/app/components/workflow/types'
  31. import DSLExportConfirmModal from '@/app/components/workflow/dsl-export-confirm-modal'
  32. import { fetchWorkflowDraft } from '@/service/workflow'
  33. import { fetchInstalledAppList } from '@/service/explore'
  34. export type AppCardProps = {
  35. app: App
  36. onRefresh?: () => void
  37. }
  38. const AppCard = ({ app, onRefresh }: AppCardProps) => {
  39. const { t } = useTranslation()
  40. const { notify } = useContext(ToastContext)
  41. const { isCurrentWorkspaceEditor } = useAppContext()
  42. const { onPlanInfoChanged } = useProviderContext()
  43. const { push } = useRouter()
  44. const mutateApps = useContextSelector(
  45. AppsContext,
  46. state => state.mutateApps,
  47. )
  48. const [showEditModal, setShowEditModal] = useState(false)
  49. const [showDuplicateModal, setShowDuplicateModal] = useState(false)
  50. const [showSwitchModal, setShowSwitchModal] = useState<boolean>(false)
  51. const [showConfirmDelete, setShowConfirmDelete] = useState(false)
  52. const [secretEnvList, setSecretEnvList] = useState<EnvironmentVariable[]>([])
  53. const onConfirmDelete = useCallback(async () => {
  54. try {
  55. await deleteApp(app.id)
  56. notify({ type: 'success', message: t('app.appDeleted') })
  57. if (onRefresh)
  58. onRefresh()
  59. mutateApps()
  60. onPlanInfoChanged()
  61. }
  62. catch (e: any) {
  63. notify({
  64. type: 'error',
  65. message: `${t('app.appDeleteFailed')}${'message' in e ? `: ${e.message}` : ''}`,
  66. })
  67. }
  68. setShowConfirmDelete(false)
  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 (e) {
  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 (e) {
  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 (e) {
  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 (e) {
  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 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'
  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. <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'>
  278. {app.mode === 'advanced-chat' && (
  279. <ChatBot className='w-3 h-3 text-[#1570EF]' />
  280. )}
  281. {app.mode === 'agent-chat' && (
  282. <CuteRobot className='w-3 h-3 text-indigo-600' />
  283. )}
  284. {app.mode === 'chat' && (
  285. <ChatBot className='w-3 h-3 text-[#1570EF]' />
  286. )}
  287. {app.mode === 'completion' && (
  288. <AiText className='w-3 h-3 text-[#0E9384]' />
  289. )}
  290. {app.mode === 'workflow' && (
  291. <Route className='w-3 h-3 text-[#f79009]' />
  292. )}
  293. </span>
  294. </div>
  295. <div className='grow w-0 py-[1px]'>
  296. <div className='flex items-center text-sm leading-5 font-semibold text-gray-800'>
  297. <div className='truncate' title={app.name}>{app.name}</div>
  298. </div>
  299. <div className='flex items-center text-[10px] leading-[18px] text-gray-500 font-medium'>
  300. {app.mode === 'advanced-chat' && <div className='truncate'>{t('app.types.chatbot').toUpperCase()}</div>}
  301. {app.mode === 'chat' && <div className='truncate'>{t('app.types.chatbot').toUpperCase()}</div>}
  302. {app.mode === 'agent-chat' && <div className='truncate'>{t('app.types.agent').toUpperCase()}</div>}
  303. {app.mode === 'workflow' && <div className='truncate'>{t('app.types.workflow').toUpperCase()}</div>}
  304. {app.mode === 'completion' && <div className='truncate'>{t('app.types.completion').toUpperCase()}</div>}
  305. </div>
  306. </div>
  307. </div>
  308. <div className='title-wrapper h-[90px] px-[14px] text-xs leading-normal text-gray-500'>
  309. <div
  310. className={cn(tags.length ? 'line-clamp-2' : 'line-clamp-4', 'group-hover:line-clamp-2')}
  311. title={app.description}
  312. >
  313. {app.description}
  314. </div>
  315. </div>
  316. <div className={cn(
  317. 'absolute bottom-1 left-0 right-0 items-center shrink-0 pt-1 pl-[14px] pr-[6px] pb-[6px] h-[42px]',
  318. tags.length ? 'flex' : '!hidden group-hover:!flex',
  319. )}>
  320. {isCurrentWorkspaceEditor && (
  321. <>
  322. <div className={cn('grow flex items-center gap-1 w-0')} onClick={(e) => {
  323. e.stopPropagation()
  324. e.preventDefault()
  325. }}>
  326. <div className={cn(
  327. 'group-hover:!block group-hover:!mr-0 mr-[41px] grow w-full',
  328. tags.length ? '!block' : '!hidden',
  329. )}>
  330. <TagSelector
  331. position='bl'
  332. type='app'
  333. targetID={app.id}
  334. value={tags.map(tag => tag.id)}
  335. selectedTags={tags}
  336. onCacheUpdate={setTags}
  337. onChange={onRefresh}
  338. />
  339. </div>
  340. </div>
  341. <div className='!hidden group-hover:!flex shrink-0 mx-1 w-[1px] h-[14px] bg-gray-200' />
  342. <div className='!hidden group-hover:!flex shrink-0'>
  343. <CustomPopover
  344. htmlContent={<Operations />}
  345. position="br"
  346. trigger="click"
  347. btnElement={
  348. <div
  349. className='flex items-center justify-center w-8 h-8 cursor-pointer rounded-md'
  350. >
  351. <RiMoreFill className='w-4 h-4 text-gray-700' />
  352. </div>
  353. }
  354. btnClassName={open =>
  355. cn(
  356. open ? '!bg-black/5 !shadow-none' : '!bg-transparent',
  357. 'h-8 w-8 !p-2 rounded-md border-none hover:!bg-black/5',
  358. )
  359. }
  360. popupClassName={
  361. (app.mode === 'completion' || app.mode === 'chat')
  362. ? '!w-[256px] translate-x-[-224px]'
  363. : '!w-[160px] translate-x-[-128px]'
  364. }
  365. className={'h-fit !z-20'}
  366. />
  367. </div>
  368. </>
  369. )}
  370. </div>
  371. </div>
  372. {showEditModal && (
  373. <EditAppModal
  374. isEditModal
  375. appName={app.name}
  376. appIconType={app.icon_type}
  377. appIcon={app.icon}
  378. appIconBackground={app.icon_background}
  379. appIconUrl={app.icon_url}
  380. appDescription={app.description}
  381. appMode={app.mode}
  382. appUseIconAsAnswerIcon={app.use_icon_as_answer_icon}
  383. show={showEditModal}
  384. onConfirm={onEdit}
  385. onHide={() => setShowEditModal(false)}
  386. />
  387. )}
  388. {showDuplicateModal && (
  389. <DuplicateAppModal
  390. appName={app.name}
  391. icon_type={app.icon_type}
  392. icon={app.icon}
  393. icon_background={app.icon_background}
  394. icon_url={app.icon_url}
  395. show={showDuplicateModal}
  396. onConfirm={onCopy}
  397. onHide={() => setShowDuplicateModal(false)}
  398. />
  399. )}
  400. {showSwitchModal && (
  401. <SwitchAppModal
  402. show={showSwitchModal}
  403. appDetail={app}
  404. onClose={() => setShowSwitchModal(false)}
  405. onSuccess={onSwitch}
  406. />
  407. )}
  408. {showConfirmDelete && (
  409. <Confirm
  410. title={t('app.deleteAppConfirmTitle')}
  411. content={t('app.deleteAppConfirmContent')}
  412. isShow={showConfirmDelete}
  413. onConfirm={onConfirmDelete}
  414. onCancel={() => setShowConfirmDelete(false)}
  415. />
  416. )}
  417. {secretEnvList.length > 0 && (
  418. <DSLExportConfirmModal
  419. envList={secretEnvList}
  420. onConfirm={onExport}
  421. onClose={() => setSecretEnvList([])}
  422. />
  423. )}
  424. </>
  425. )
  426. }
  427. export default AppCard