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

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