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.

AppCard.tsx 18KB

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