Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

app-card.tsx 19KB

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