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

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