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.

app-card.tsx 18KB

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