Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(web): preserve focus and align deletion dialog lifecycles (#44743)

yyh12ab116fffd4
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 720eaba11a1..afc44c47642 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1847,9 +1847,6 @@ importers:
'@types/sortablejs':
specifier: 'catalog:'
version: 1.15.9
- '@typescript/native':
- specifier: 'catalog:'
'@vitejs/plugin-react':
specifier: 'catalog:'
diff --git a/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsx b/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsx
index 8f6309ec637..018dcdfd72d 100644
--- a/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsx
+++ b/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsx
@@ -1,5 +1,5 @@
import type { DatasetDetailWithPartialMembersResponse } from '@dify/contracts/api/console/datasets/types.gen'
-import { screen, waitFor } from '@testing-library/react'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { ChunkingMode, DataSourceType } from '@/models/datasets'
@@ -7,6 +7,7 @@ import { PermissionLevel } from '@/models/permission'
import { consoleQuery } from '@/service/console'
import { createHttpError } from '@/service/http-error'
import { createConsoleQueryWrapper, renderWithConsoleQuery } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
import { createDatasetFixture } from '@/test/fixtures/dataset'
import { RETRIEVE_METHOD } from '@/types/app'
import { DatasetACLPermission } from '@/utils/permission'
@@ -118,6 +119,8 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'datasets.byDatasetId.useCheck.get': (input) => mockCheckIsUsedInApp(input),
+ 'datasets.byDatasetId.delete': (input) => mockDeleteDataset(input),
'rag.pipelines.byPipelineId.exports.get': (input) => mockExportPipeline(input),
}),
}
@@ -126,8 +129,6 @@ vi.mock('@/service/console', async (importOriginal) => {
vi.mock('@/service/datasets', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/datasets')>()),
updateDatasetSetting: (...args: unknown[]) => mockUpdateDatasetSetting(...args),
- checkIsUsedInApp: (...args: unknown[]) => mockCheckIsUsedInApp(...args),
- deleteDataset: (...args: unknown[]) => mockDeleteDataset(...args),
}))
vi.mock('@/app/notifications', () => ({
@@ -207,6 +208,26 @@ describe('Dropdown callback coverage', () => {
})
})
+ it('keeps deletion open while pending, then closes and navigates on success', async () => {
+ const user = userEvent.setup()
+ const pending = createDeferred<void>()
+ mockDeleteDataset.mockReturnValueOnce(pending.promise)
+ render(<Dropdown expand />)
+
+ await user.click(screen.getByRole('button'))
+ await user.click(screen.getByText('common.operation.delete'))
+ await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
+ await waitFor(() => expect(mockDeleteDataset).toHaveBeenCalledOnce())
+ expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()
+ await user.keyboard('{Escape}')
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+ expect(mockReplace).not.toHaveBeenCalled()
+
+ await act(async () => pending.resolve())
+ await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/datasets'))
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ })
+
it('should show the used-by-app confirmation copy when the dataset is referenced by apps', async () => {
const user = userEvent.setup()
mockCheckIsUsedInApp.mockResolvedValueOnce({ is_using: true })
@@ -247,7 +268,7 @@ describe('Dropdown callback coverage', () => {
expect(mockExportPipeline).not.toHaveBeenCalled()
})
- it('should surface the backend message when checking app usage fails', async () => {
+ it('keeps failed usage checks in the dialog with a retry action', async () => {
const user = userEvent.setup()
mockCheckIsUsedInApp.mockRejectedValueOnce(
createHttpError(new Response(null, { status: 400 }), { message: 'check failed' }),
@@ -258,9 +279,8 @@ describe('Dropdown callback coverage', () => {
await user.click(screen.getByRole('button'))
await user.click(screen.getByText('common.operation.delete'))
- await waitFor(() => {
- expect(mockToast).toHaveBeenCalledWith('check failed')
- })
- expect(screen.queryByText('dataset.deleteDatasetConfirmTitle')).not.toBeInTheDocument()
+ expect(await screen.findByRole('alert')).toHaveTextContent('common.api.actionFailed')
+ expect(screen.getByRole('button', { name: 'common.operation.retry' })).toBeEnabled()
+ expect(mockDeleteDataset).not.toHaveBeenCalled()
})
})
diff --git a/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx b/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx
index a56edbb4230..d407fb89a16 100644
--- a/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx
+++ b/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx
@@ -134,14 +134,14 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'datasets.byDatasetId.useCheck.get': (input) => mockCheckIsUsedInApp(input),
+ 'datasets.byDatasetId.delete': (input) => mockDeleteDataset(input),
'rag.pipelines.byPipelineId.exports.get': (input) => mockExportPipeline(input),
}),
}
})
vi.mock('@/service/datasets', () => ({
- checkIsUsedInApp: (...args: unknown[]) => mockCheckIsUsedInApp(...args),
- deleteDataset: (...args: unknown[]) => mockDeleteDataset(...args),
updateDatasetSetting: (...args: unknown[]) => mockUpdateDataset(...args),
}))
@@ -342,8 +342,9 @@ describe('Dropdown', () => {
// Assert
await waitFor(() => {
- expect(mockDeleteDataset).toHaveBeenCalledWith('dataset-1')
+ expect(mockDeleteDataset).toHaveBeenCalledWith({ params: { dataset_id: 'dataset-1' } })
})
+ expect(queryClient.getQueryData(datasetListKey)).toMatchObject({ data: [], total: 0 })
expect(queryClient.getQueryState(datasetListKey)?.isInvalidated).toBe(true)
expect(mockReplace).toHaveBeenCalledWith('/datasets')
})
diff --git a/web/app/components/app-sidebar/dataset-info/dropdown.tsx b/web/app/components/app-sidebar/dataset-info/dropdown.tsx
index edf0364bb9f..d4808e80d1a 100644
--- a/web/app/components/app-sidebar/dataset-info/dropdown.tsx
+++ b/web/app/components/app-sidebar/dataset-info/dropdown.tsx
@@ -1,14 +1,5 @@
import type { DatasetDetailWithPartialMembersResponse } from '@dify/contracts/api/console/datasets/types.gen'
-import {
- AlertDialog,
- AlertDialogCancelButton,
- AlertDialogConfirmButton,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from '@langgenius/dify-ui/alert-dialog'
+import { AlertDialog, AlertDialogContent } from '@langgenius/dify-ui/alert-dialog'
import { cn } from '@langgenius/dify-ui/cn'
import {
DropdownMenu,
@@ -30,10 +21,9 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
-import { checkIsUsedInApp, deleteDataset } from '@/service/datasets'
import { downloadBlob } from '@/utils/download'
-import { getErrorMessage } from '@/utils/error-message'
import { getDatasetACLCapabilities } from '@/utils/permission'
+import { DeleteDatasetConfirmation } from '../../datasets/delete-dataset-confirmation'
import RenameDatasetModal from '../../datasets/rename-modal'
type DropDownProps = {
@@ -44,9 +34,11 @@ type DropDownProps = {
const DropDown = ({ expand, triggerClassName }: DropDownProps) => {
const { t } = useTranslation(['app', 'common', 'dataset', 'datasetPipeline', 'navigation'])
const { push, replace } = useRouter()
- const [showRenameModal, setShowRenameModal] = useState(false)
- const [confirmMessage, setConfirmMessage] = useState<string>('')
- const [showConfirmDelete, setShowConfirmDelete] = useState(false)
+ const [renameOpen, setRenameOpen] = useState(false)
+ const [deleteOpen, setDeleteOpen] = useState(false)
+ const deletion = useMutation(
+ consoleQuery.datasets.byDatasetId.delete.mutationOptions({ context: { silent: true } }),
+ )
const dataset = useDatasetDetailContextWithSelector(
(state) => state.dataset,
@@ -97,12 +89,6 @@ const DropDown = ({ expand, triggerClassName }: DropDownProps) => {
invalidDatasetDetail()
}, [invalidDatasetDetail, invalidDatasetList])
- const openRenameModal = useCallback(() => {
- queueMicrotask(() => {
- setShowRenameModal(true)
- })
- }, [])
-
const { mutateAsync: exportPipelineConfig } = useMutation(
consoleQuery.rag.pipelines.byPipelineId.exports.get.mutationOptions(),
)
@@ -125,38 +111,10 @@ const DropDown = ({ expand, triggerClassName }: DropDownProps) => {
[dataset, exportPipelineConfig, t],
)
- const detectIsUsedByApp = useCallback(async () => {
- try {
- const { is_using: isUsedByApp } = await checkIsUsedInApp(dataset.id)
- setConfirmMessage(
- isUsedByApp
- ? t(($) => $.datasetUsedByApp, { ns: 'dataset' })!
- : t(($) => $.deleteDatasetConfirmContent, { ns: 'dataset' })!,
- )
- setShowConfirmDelete(true)
- } catch (e: unknown) {
- toast.error(getErrorMessage(e) ?? 'Unknown error')
- }
- }, [dataset.id, t])
-
const openAccessConfig = useCallback(() => {
push(`/datasets/${dataset.id}/access-config`)
}, [dataset.id, push])
- const onConfirmDelete = useCallback(async () => {
- try {
- await deleteDataset(dataset.id)
- toast(
- t(($) => $.datasetDeleted, { ns: 'dataset' }),
- { type: 'success' },
- )
- invalidDatasetList()
- replace('/datasets')
- } finally {
- setShowConfirmDelete(false)
- }
- }, [dataset.id, replace, invalidDatasetList, t])
-
if (!canShowOperations) return null
return (
@@ -178,7 +136,7 @@ const DropDown = ({ expand, triggerClassName }: DropDownProps) => {
className="w-50"
>
{datasetACLCapabilities.canEdit && (
- <DropdownMenuItem onClick={openRenameModal}>
+ <DropdownMenuItem onClick={() => setRenameOpen(true)}>
<span aria-hidden className="i-ri-edit-line size-4 text-text-tertiary" />
{t(($) => $['operation.edit'], { ns: 'common' })}
</DropdownMenuItem>
@@ -198,40 +156,50 @@ const DropDown = ({ expand, triggerClassName }: DropDownProps) => {
{datasetACLCapabilities.canDelete && (
<>
<DropdownMenuSeparator />
- <DropdownMenuItem variant="destructive" onClick={detectIsUsedByApp}>
+ <DropdownMenuItem variant="destructive" onClick={() => setDeleteOpen(true)}>
<span aria-hidden className="i-ri-delete-bin-line size-4 text-text-tertiary" />
{t(($) => $['operation.delete'], { ns: 'common' })}
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
- {showRenameModal && (
- <RenameDatasetModal
- show={showRenameModal}
- dataset={dataset!}
- onClose={() => setShowRenameModal(false)}
- onSuccess={refreshDataset}
- />
- )}
+ <RenameDatasetModal
+ open={renameOpen}
+ dataset={dataset}
+ onOpenChange={setRenameOpen}
+ onSuccess={refreshDataset}
+ />
<AlertDialog
- open={showConfirmDelete}
- onOpenChange={(open) => !open && setShowConfirmDelete(false)}
+ open={deleteOpen}
+ onOpenChange={(open, details) => {
+ if (!open && deletion.isPending) {
+ details.cancel()
+ return
+ }
+ setDeleteOpen(open)
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) deletion.reset()
+ }}
>
<AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.deleteDatasetConfirmTitle, { ns: 'dataset' })}
- </AlertDialogTitle>
- <AlertDialogDescription>{confirmMessage}</AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton onClick={onConfirmDelete}>
- {t(($) => $['operation.confirm'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
+ <DeleteDatasetConfirmation
+ datasetId={dataset.id}
+ isPending={deletion.isPending}
+ error={deletion.isError ? t(($) => $['api.actionFailed'], { ns: 'common' }) : undefined}
+ onConfirm={() => {
+ if (deletion.isPending) return
+ deletion.mutate(
+ { params: { dataset_id: dataset.id } },
+ {
+ onSuccess: () => {
+ setDeleteOpen(false)
+ replace('/datasets')
+ },
+ },
+ )
+ }}
+ />
</AlertDialogContent>
</AlertDialog>
</DropdownMenu>
diff --git a/web/app/components/apps/app-card/index.tsx b/web/app/components/apps/app-card/index.tsx
index e2ff431daf2..53757dd26f4 100644
--- a/web/app/components/apps/app-card/index.tsx
+++ b/web/app/components/apps/app-card/index.tsx
@@ -1,12 +1,11 @@
'use client'
import type { AppPartial } from '@dify/contracts/api/console/apps/types.gen'
-import type { AppCardInteractionsProps } from './interactions'
import type { WorkflowOnlineUser } from '@/models/app'
import { cn } from '@langgenius/dify-ui/cn'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { memo, useCallback, useId, useMemo } from 'react'
+import { memo, useCallback, useId, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { AppTypeIcon } from '@/app/components/app/type-selector'
import AppIcon from '@/app/components/base/app-icon'
@@ -30,7 +29,7 @@ const EMPTY_ONLINE_USERS: WorkflowOnlineUser[] = []
type AppCardProps = {
app: AppPartial
- onDelete: AppCardInteractionsProps['onDelete']
+ onDelete: (item: HTMLLIElement | null) => void
onlineUsers?: WorkflowOnlineUser[]
onOpenTagManagement?: () => void
stepByStepTourActionMenuOpen?: boolean
@@ -50,6 +49,7 @@ export const AppCard = memo(
stepByStepTourCardHighlightPart,
stepByStepTourActionMenuHighlightPart,
}: AppCardProps) => {
+ const itemRef = useRef<HTMLLIElement>(null)
const { t } = useTranslation(['app', 'common', 'time'])
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { data: currentUserId } = useSuspenseQuery({
@@ -180,6 +180,7 @@ export const AppCard = memo(
return (
<li
+ ref={itemRef}
className={cn(
"group relative isolate col-span-1 h-41.5 min-w-0 overflow-hidden rounded-xl border-[0.5px] border-solid border-components-card-border bg-components-card-bg shadow-xs shadow-shadow-shadow-3 transition-shadow duration-200 ease-in-out after:pointer-events-none after:absolute after:inset-0 after:z-1 after:rounded-xl after:content-[''] focus-within:bg-components-card-bg-alt focus-within:[--color-tag-selector-mask-bg:var(--color-tag-selector-mask-hover-bg)] has-[>a:focus-visible]:after:inset-ring-2 has-[>a:focus-visible]:after:inset-ring-state-accent-solid has-[>button:focus-visible]:after:inset-ring-2 has-[>button:focus-visible]:after:inset-ring-state-accent-solid motion-reduce:transition-none",
!isPreviewOnly &&
@@ -201,7 +202,7 @@ export const AppCard = memo(
) : (
<AppCardInteractions
app={app}
- onDelete={onDelete}
+ onDelete={() => onDelete(itemRef.current)}
stepByStepTourActionMenuOpen={stepByStepTourActionMenuOpen}
stepByStepTourActionMenuHighlightPart={stepByStepTourActionMenuHighlightPart}
>
diff --git a/web/app/components/apps/app-card/interactions.tsx b/web/app/components/apps/app-card/interactions.tsx
index 34778744c47..d74b2f837d7 100644
--- a/web/app/components/apps/app-card/interactions.tsx
+++ b/web/app/components/apps/app-card/interactions.tsx
@@ -237,10 +237,10 @@ function AppCardOperationsMenuItems({
)
}
-export type AppCardInteractionsProps = {
+type AppCardInteractionsProps = {
app: AppPartial
children: ReactElement
- onDelete: (app: Pick<AppPartial, 'id' | 'name'>, trigger: HTMLButtonElement | null) => void
+ onDelete: () => void
stepByStepTourActionMenuOpen?: boolean
stepByStepTourActionMenuHighlightPart?: string
}
@@ -269,7 +269,6 @@ export function AppCardInteractions({
consoleQuery.apps.byAppId.star.delete.mutationOptions(),
)
- const moreButtonRef = useRef<HTMLButtonElement>(null)
const editActionsRef = useRef<DialogActions>(null)
const edit = useMutation(
consoleQuery.apps.byAppId.put.mutationOptions({ context: { silent: true } }),
@@ -425,7 +424,7 @@ export function AppCardInteractions({
onDuplicate: () => setActiveDialog('duplicate'),
onExport: exportCheck,
onSwitch: () => setActiveDialog('switch'),
- onDelete: () => onDelete({ id: app.id, name: app.name }, moreButtonRef.current),
+ onDelete,
onAccessConfig: () => push(`/app/${app.id}/access-config`),
}
@@ -488,7 +487,6 @@ export function AppCardInteractions({
onOpenChange={operationsMenu.onOpenChange}
>
<DropdownMenuTrigger
- ref={moreButtonRef}
render={
<IconButton
size="lg"
diff --git a/web/app/components/apps/app-list-catalog.tsx b/web/app/components/apps/app-list-catalog.tsx
index 19712ede02c..936a937decf 100644
--- a/web/app/components/apps/app-list-catalog.tsx
+++ b/web/app/components/apps/app-list-catalog.tsx
@@ -8,7 +8,6 @@ import type {
import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'
import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'
import type { RefObject } from 'react'
-import type { AppCardInteractionsProps } from './app-card/interactions'
import {
AlertDialog,
AlertDialogContent,
@@ -20,11 +19,11 @@ import { keepPreviousData, useInfiniteQuery, useMutation, useQuery } from '@tans
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { DeleteAppForm } from '@/app/components/app/delete-app-form'
-import { getAdjacentCardFocusTargets } from '@/app/components/base/card-list-focus'
import { InfiniteScrollSentinel } from '@/app/components/base/infinite-scroll-sentinel'
import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { consoleQuery } from '@/service/console'
+import { getAdjacentFocusTargets } from '@/utils/get-adjacent-focus-targets'
import { AppCard } from './app-card'
import { AppCardSkeleton } from './app-card-skeleton'
import { APP_LIST_GRID_CLASS_NAME } from './constants'
@@ -115,11 +114,13 @@ function AppListCatalogContent({
const deletion = useMutation(
consoleQuery.apps.byAppId.delete.mutationOptions({ context: { silent: true } }),
)
- const openDeleteDialog = useCallback<AppCardInteractionsProps['onDelete']>(
- (app, trigger) =>
+ const openDeleteDialog = useCallback(
+ (app: Pick<AppPartial, 'id' | 'name'>, item: HTMLLIElement | null) =>
deleteDialog.openWithPayload({
...app,
- adjacentFocusTargets: getAdjacentCardFocusTargets(trigger),
+ adjacentFocusTargets: getAdjacentFocusTargets(item, (sibling) =>
+ sibling.querySelector<HTMLElement>(':scope > a[href], :scope > button'),
+ ),
fallbackFocus: { current: null },
}),
[deleteDialog],
@@ -220,7 +221,7 @@ function AppListCatalogContent({
<AppCard
key={app.id}
app={app}
- onDelete={openDeleteDialog}
+ onDelete={(item) => openDeleteDialog(app, item)}
onlineUsers={workflowOnlineUsersMap[app.id]}
onOpenTagManagement={onOpenTagManagement}
stepByStepTourActionMenuOpen={
diff --git a/web/app/components/apps/starred-app-card.tsx b/web/app/components/apps/starred-app-card.tsx
index 427f6ebc6e3..46389e76fbc 100644
--- a/web/app/components/apps/starred-app-card.tsx
+++ b/web/app/components/apps/starred-app-card.tsx
@@ -1,11 +1,10 @@
'use client'
import type { AppPartial } from '@dify/contracts/api/console/apps/types.gen'
-import type { AppCardInteractionsProps } from './app-card/interactions'
import { cn } from '@langgenius/dify-ui/cn'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { memo, useCallback, useId, useMemo } from 'react'
+import { memo, useCallback, useId, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { AppTypeIcon } from '@/app/components/app/type-selector'
import AppIcon from '@/app/components/base/app-icon'
@@ -21,7 +20,7 @@ import { StudioListLink } from './list-navigation'
type StarredAppCardProps = {
app: AppPartial
- onDelete: AppCardInteractionsProps['onDelete']
+ onDelete: (item: HTMLLIElement | null) => void
stepByStepTourCardTarget?: string
stepByStepTourCardHighlightPart?: string
}
@@ -33,6 +32,7 @@ export const StarredAppCard = memo(
stepByStepTourCardTarget,
stepByStepTourCardHighlightPart,
}: StarredAppCardProps) => {
+ const itemRef = useRef<HTMLLIElement>(null)
const { t } = useTranslation(['app', 'common', 'time'])
const { data: currentUserId } = useSuspenseQuery({
...userProfileQueryOptions(),
@@ -92,6 +92,7 @@ export const StarredAppCard = memo(
return (
<li
+ ref={itemRef}
className={cn(
"group relative isolate overflow-hidden rounded-xl border-[0.5px] border-components-card-border bg-components-card-bg shadow-xs shadow-shadow-shadow-3 transition-shadow duration-200 after:pointer-events-none after:absolute after:inset-0 after:z-1 after:rounded-xl after:content-[''] focus-within:bg-components-card-bg-alt has-[>a:focus-visible]:after:inset-ring-2 has-[>a:focus-visible]:after:inset-ring-state-accent-solid has-[>button:focus-visible]:after:inset-ring-2 has-[>button:focus-visible]:after:inset-ring-state-accent-solid motion-reduce:transition-none",
!isPreviewOnly &&
@@ -110,7 +111,7 @@ export const StarredAppCard = memo(
{cardContent}
</button>
) : (
- <AppCardInteractions app={app} onDelete={onDelete}>
+ <AppCardInteractions app={app} onDelete={() => onDelete(itemRef.current)}>
<StudioListLink
href={href}
aria-labelledby={appNameId}
diff --git a/web/app/components/apps/starred-app-list.tsx b/web/app/components/apps/starred-app-list.tsx
index c6e3e20d865..ec38d511fb8 100644
--- a/web/app/components/apps/starred-app-list.tsx
+++ b/web/app/components/apps/starred-app-list.tsx
@@ -1,14 +1,13 @@
'use client'
import type { AppPartial } from '@dify/contracts/api/console/apps/types.gen'
-import type { AppCardInteractionsProps } from './app-card/interactions'
import { useTranslation } from 'react-i18next'
import { APP_LIST_GRID_CLASS_NAME } from './constants'
import { StarredAppCard } from './starred-app-card'
type StarredAppListProps = {
apps: AppPartial[]
- onDelete: AppCardInteractionsProps['onDelete']
+ onDelete: (app: Pick<AppPartial, 'id' | 'name'>, item: HTMLLIElement | null) => void
stepByStepTourCardTarget?: string
stepByStepTourCardHighlightPart?: string
stepByStepTourHighlightedCardCount?: number
@@ -57,7 +56,7 @@ export function StarredAppList({
<StarredAppCard
key={app.id}
app={app}
- onDelete={onDelete}
+ onDelete={(item) => onDelete(app, item)}
stepByStepTourCardTarget={index === 0 ? stepByStepTourCardTarget : undefined}
stepByStepTourCardHighlightPart={
index < stepByStepTourHighlightedCardCount
diff --git a/web/app/components/base/card-list-focus.ts b/web/app/components/base/card-list-focus.ts
deleted file mode 100644
index edb240f2fee..00000000000
--- a/web/app/components/base/card-list-focus.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-// Capture the source section before deletion can unmount its card or the whole list.
-export function getAdjacentCardFocusTargets(source: HTMLElement | null): HTMLElement[] {
- const card = source?.closest('li')
- if (!card?.parentElement) return []
-
- const cards = Array.from(card.parentElement.children)
- const index = cards.indexOf(card)
- return [...cards.slice(index + 1), ...cards.slice(0, index).reverse()].flatMap((sibling) => {
- const target = sibling.querySelector<HTMLElement>(':scope > a[href], :scope > button')
- return target ? [target] : []
- })
-}
diff --git a/web/app/components/datasets/delete-dataset-confirmation.tsx b/web/app/components/datasets/delete-dataset-confirmation.tsx
new file mode 100644
index 00000000000..5f3f1303313
--- /dev/null
+++ b/web/app/components/datasets/delete-dataset-confirmation.tsx
@@ -0,0 +1,70 @@
+import {
+ AlertDialogBody,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from '@langgenius/dify-ui/alert-dialog'
+import { Button } from '@langgenius/dify-ui/button'
+import { useQuery } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+import { consoleQuery } from '@/service/console'
+
+export function DeleteDatasetConfirmation({
+ datasetId,
+ isPending,
+ error,
+ onConfirm,
+}: {
+ datasetId: string
+ isPending: boolean
+ error?: string
+ onConfirm: () => void
+}) {
+ const { t } = useTranslation(['common', 'dataset'])
+ const usage = useQuery(
+ consoleQuery.datasets.byDatasetId.useCheck.get.queryOptions({
+ input: { params: { dataset_id: datasetId } },
+ staleTime: 0,
+ retry: false,
+ context: { silent: true },
+ }),
+ )
+
+ return (
+ <>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.deleteDatasetConfirmTitle, { ns: 'dataset' })}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => (usage.data?.is_using ? $.datasetUsedByApp : $.deleteDatasetConfirmContent), {
+ ns: 'dataset',
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {(error || usage.isError) && (
+ <AlertDialogBody className="flex flex-col items-start gap-2">
+ <p role="alert" className="text-text-destructive">
+ {error ?? t(($) => $['api.actionFailed'], { ns: 'common' })}
+ </p>
+ {usage.isError && (
+ <Button size="small" loading={usage.isFetching} onClick={() => void usage.refetch()}>
+ {t(($) => $['operation.retry'], { ns: 'common' })}
+ </Button>
+ )}
+ </AlertDialogBody>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancelButton disabled={isPending}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton loading={isPending} onClick={onConfirm}>
+ {t(($) => $['operation.confirm'], { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </>
+ )
+}
diff --git a/web/app/components/datasets/documents/__tests__/delete-document.browser.spec.tsx b/web/app/components/datasets/documents/__tests__/delete-document.browser.spec.tsx
new file mode 100644
index 00000000000..bc102114aaa
--- /dev/null
+++ b/web/app/components/datasets/documents/__tests__/delete-document.browser.spec.tsx
@@ -0,0 +1,163 @@
+import type { consoleClient } from '@/service/console'
+import { zDocumentWithSegmentsListResponse } from '@dify/contracts/api/console/datasets/zod.gen'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import DatasetDetailContext from '@/context/dataset-detail'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { QueryClientTestProvider } from '@/test/console/query-provider'
+import { createDeferred } from '@/test/deferred'
+import { createDatasetFixture } from '@/test/fixtures/dataset'
+import { DatasetACLPermission } from '@/utils/permission'
+import Documents from '../index'
+
+vi.mock('@/next/navigation', () => ({
+ useRouter: () => ({ push: vi.fn() }),
+ usePathname: () => '/datasets/dataset-1/documents',
+ useParams: () => ({ datasetId: 'dataset-1' }),
+ useSearchParams: () => new URLSearchParams(),
+}))
+
+const api = vi.hoisted(() => ({
+ list: vi.fn<typeof consoleClient.datasets.byDatasetId.documents.get>(),
+ remove: vi.fn<typeof consoleClient.datasets.byDatasetId.documents.delete>(),
+}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'datasets.byDatasetId.documents.get': api.list,
+ 'datasets.byDatasetId.documents.delete': api.remove,
+ 'datasets.byDatasetId.metadata.get': async () => ({
+ doc_metadata: [],
+ built_in_field_enabled: false,
+ }),
+ 'datasets.metadata.builtIn.get': async () => ({ fields: [] }),
+ 'datasets.byDatasetId.autoDisableLogs.get': async () => ({ document_ids: [] }),
+ 'datasets.byDatasetId.errorDocs.get': async () => ({ data: [], total: 0 }),
+ 'tags.get': async () => [],
+ }),
+ }
+})
+beforeEach(() => vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false))
+afterEach(() => vi.unstubAllGlobals())
+async function setup(ids: string[]) {
+ let datasets = zDocumentWithSegmentsListResponse.parse({
+ data: ids.map((id, index) => ({
+ id,
+ name: id,
+ position: index + 1,
+ data_source_type: 'upload_file',
+ indexing_status: 'completed',
+ enabled: true,
+ archived: false,
+ display_status: 'available',
+ created_at: 1700000000,
+ doc_form: 'text_model',
+ data_source_detail_dict: {},
+ })),
+ total: ids.length,
+ page: 1,
+ limit: 10,
+ has_more: false,
+ }).data
+ api.list.mockReset().mockImplementation(async () => ({
+ data: datasets,
+ page: 1,
+ total: datasets.length,
+ limit: 30,
+ has_more: false,
+ }))
+ api.remove.mockReset().mockImplementation(async ({ query }) => {
+ datasets = datasets.filter((item) => !query?.document_id?.includes(item.id))
+ return { result: 'success' }
+ })
+ const { queryClient } = createConsoleQueryWrapper({ systemFeatures: { rbac_enabled: true } })
+ const screen = await render(
+ <QueryClientTestProvider queryClient={queryClient}>
+ <NuqsTestingAdapter hasMemory>
+ {/* oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector requires its Provider component. */}
+ <DatasetDetailContext.Provider
+ value={{
+ dataset: createDatasetFixture({
+ embedding_available: true,
+ permission_keys: [DatasetACLPermission.Use, DatasetACLPermission.DeleteFile],
+ }),
+ }}
+ >
+ <div className="h-screen">
+ <Documents datasetId="dataset-1" />
+ </div>
+ </DatasetDetailContext.Provider>
+ </NuqsTestingAdapter>
+ </QueryClientTestProvider>,
+ )
+ const open = async (id: string) => {
+ const link = screen.getByRole('link', { name: id, exact: true })
+ await link.hover()
+ const card = link.element().closest('tr')!
+ await userEvent.click(card.querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')!)
+ await screen
+ .getByRole('menuitem', { name: 'datasetDocuments.list.action.delete', exact: true })
+ .click()
+ await expect.element(screen.getByRole('alertdialog')).toBeVisible()
+ await expect.element(screen.getByRole('menu')).not.toBeInTheDocument()
+ }
+ return { screen, open }
+}
+describe('Classic document deletion', () => {
+ it('removes the item before a slow list refresh completes', async () => {
+ const { screen, open } = await setup(['Alpha', 'Beta'])
+ await open('Alpha')
+ const list = api.list.getMockImplementation()!
+ const refresh = createDeferred<Awaited<ReturnType<typeof list>>>()
+ api.list.mockReturnValueOnce(refresh.promise)
+ await screen.getByRole('button', { name: 'common.operation.sure' }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('link', { name: 'Alpha', exact: true }))
+ .not.toBeInTheDocument()
+ await expect.element(screen.getByRole('link', { name: 'Beta', exact: true })).toHaveFocus()
+ refresh.resolve(await list({ params: { dataset_id: 'dataset-1' } }))
+ })
+
+ it.each([
+ { ids: ['Alpha', 'Beta', 'Gamma'], remove: 'Beta', next: 'Gamma' },
+ { ids: ['Alpha', 'Beta'], remove: 'Beta', next: 'Alpha' },
+ { ids: ['Alpha'], remove: 'Alpha', next: null },
+ ])('restores focus after deleting $remove from $ids', async ({ ids, remove, next }) => {
+ const { screen, open } = await setup(ids)
+ await open(remove)
+ await screen.getByRole('button', { name: 'common.operation.sure' }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('link', { name: remove, exact: true }))
+ .not.toBeInTheDocument()
+ await expect
+ .element(
+ next ? screen.getByRole('link', { name: next, exact: true }) : screen.getByRole('region'),
+ )
+ .toHaveFocus()
+ })
+ it('retains focus while pending and leaves a failed deletion retryable', async () => {
+ const { screen, open } = await setup(['Alpha'])
+ const request = createDeferred<{ result: string }>()
+ api.remove.mockReturnValueOnce(request.promise)
+ await open('Alpha')
+ const confirm = screen.getByRole('button', { name: 'common.operation.sure' })
+ await confirm.click()
+ await expect.element(confirm).toHaveFocus()
+ await userEvent.keyboard('{Escape}')
+ await expect
+ .element(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ .toBeDisabled()
+ await expect.element(screen.getByRole('alertdialog')).toBeVisible()
+ request.reject(new Error('Failed'))
+ await expect.element(screen.getByRole('alert')).toBeVisible()
+ await confirm.click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect.element(screen.getByRole('region')).toHaveFocus()
+ })
+})
diff --git a/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx b/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx
index e96877ad3b9..390306df181 100644
--- a/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx
+++ b/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx
@@ -21,7 +21,6 @@ const mockArchive = vi.fn<DocumentsClient['status']['byAction']['batch']['patch'
const mockUnArchive = vi.fn<DocumentsClient['status']['byAction']['batch']['patch']>()
const mockEnable = vi.fn<DocumentsClient['status']['byAction']['batch']['patch']>()
const mockDisable = vi.fn<DocumentsClient['status']['byAction']['batch']['patch']>()
-const mockDelete = vi.fn<DocumentsClient['delete']>()
const mockDownload = vi.fn<DocumentsClient['byDocumentId']['download']['get']>()
const mockSync = vi.fn<DocumentsClient['byDocumentId']['notion']['sync']['get']>()
const mockSyncWebsite = vi.fn<DocumentsClient['byDocumentId']['websiteSync']['get']>()
@@ -44,7 +43,6 @@ vi.mock('@/service/console', async (importOriginal) => {
'datasets.byDatasetId.documents.status.byAction.batch.patch': (
input: Parameters<DocumentsClient['status']['byAction']['batch']['patch']>[0],
) => statusMocks[input.params.action]!(input),
- 'datasets.byDatasetId.documents.delete': (input) => mockDelete(input),
'datasets.byDatasetId.documents.byDocumentId.download.get': (input) => mockDownload(input),
'datasets.byDatasetId.documents.byDocumentId.notion.sync.get': (input) => mockSync(input),
'datasets.byDatasetId.documents.byDocumentId.websiteSync.get': (input) =>
@@ -82,7 +80,6 @@ afterEach(async () => {
describe('Operations', () => {
const mockOnUpdate = vi.fn()
- const mockOnSelectedIdChange = vi.fn()
const defaultDetail = {
id: 'doc-1',
@@ -99,6 +96,7 @@ describe('Operations', () => {
datasetId: 'dataset-1',
detail: defaultDetail,
onUpdate: mockOnUpdate,
+ onDelete: vi.fn(),
canEdit: true,
canDownload: true,
canDelete: true,
@@ -110,7 +108,6 @@ describe('Operations', () => {
mockUnArchive.mockReset().mockResolvedValue({ result: 'success' })
mockEnable.mockReset().mockResolvedValue({ result: 'success' })
mockDisable.mockReset().mockResolvedValue({ result: 'success' })
- mockDelete.mockReset().mockResolvedValue({ result: 'success' })
mockDownload.mockResolvedValue({ url: 'https://example.com/download' })
mockSync.mockReset().mockResolvedValue({ result: 'success' })
mockSyncWebsite.mockReset().mockResolvedValue({ result: 'success' })
@@ -308,52 +305,6 @@ describe('Operations', () => {
})
})
- it('should close delete modal when cancel is clicked', async () => {
- const user = userEvent.setup()
- render(<Operations {...defaultProps} />)
- await openPopover(user)
- const deleteButton = screen.getByRole('menuitem', {
- name: 'datasetDocuments.list.action.delete',
- })
- await user.click(deleteButton)
-
- expect(screen.getByText('datasetDocuments.list.delete.title')).toBeInTheDocument()
-
- const cancelButton = screen.getByRole('button', { name: 'common.operation.cancel' })
- await user.click(cancelButton)
-
- await waitFor(() => {
- expect(screen.queryByText('datasetDocuments.list.delete.title')).not.toBeInTheDocument()
- expect(mockDelete).not.toHaveBeenCalled()
- })
- })
-
- it('should update selectedIds after delete operation', async () => {
- const user = userEvent.setup()
- render(
- <Operations
- {...defaultProps}
- selectedIds={['doc-1', 'doc-2']}
- onSelectedIdChange={mockOnSelectedIdChange}
- />,
- )
- await openPopover(user)
- const deleteButton = screen.getByRole('menuitem', {
- name: 'datasetDocuments.list.action.delete',
- })
- await user.click(deleteButton)
- const confirmButton = screen.getByRole('button', { name: 'common.operation.sure' })
- await user.click(confirmButton)
- await waitFor(() => {
- expect(mockOnSelectedIdChange).toHaveBeenCalledWith(['doc-2'])
- expect(mockDelete).toHaveBeenCalledWith({
- params: { dataset_id: 'dataset-1' },
- query: { document_id: ['doc-1'] },
- })
- expect(mockOnUpdate).toHaveBeenCalledWith('delete')
- })
- })
-
it('should call sync for notion data source', async () => {
const user = userEvent.setup()
render(
diff --git a/web/app/components/datasets/documents/components/__tests__/rename-modal.spec.tsx b/web/app/components/datasets/documents/components/__tests__/rename-document-form.spec.tsx
similarity index 64%
rename from web/app/components/datasets/documents/components/__tests__/rename-modal.spec.tsx
rename to web/app/components/datasets/documents/components/__tests__/rename-document-form.spec.tsx
index 2bc4de9c912..b7a1f28045f 100644
--- a/web/app/components/datasets/documents/components/__tests__/rename-modal.spec.tsx
+++ b/web/app/components/datasets/documents/components/__tests__/rename-document-form.spec.tsx
@@ -1,7 +1,9 @@
+import type { RenameDocumentPayload } from '../rename-document-form'
+import { createDialogHandle, Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createDeferred } from '@/test/deferred'
-import RenameModal from '../rename-modal'
+import { RenameDocumentForm } from '../rename-document-form'
const { rename, toastError } = vi.hoisted(() => ({ rename: vi.fn(), toastError: vi.fn() }))
vi.mock('@/service/datasets', () => ({ renameDocumentName: rename }))
@@ -10,16 +12,38 @@ const props = {
datasetId: 'dataset-1',
documentId: 'doc-1',
name: 'Original document',
- onClose: vi.fn(),
onSaved: vi.fn(),
}
const renamed = { id: 'doc-1', name: 'Updated document', data_source_detail_dict: {} }
+function renderRenameDialog() {
+ const handle = createDialogHandle<RenameDocumentPayload>()
+ render(
+ <Dialog handle={handle}>
+ {({ payload }) => (
+ <DialogContent>
+ {payload && (
+ <RenameDocumentForm
+ datasetId={props.datasetId}
+ documentId={payload.id}
+ name={payload.name}
+ onSaved={props.onSaved}
+ onClose={() => handle.close()}
+ />
+ )}
+ </DialogContent>
+ )}
+ </Dialog>,
+ )
+ act(() => handle.openWithPayload({ id: props.documentId, name: props.name }))
+ return handle
+}
+
it('submits the edited document name once while saving and reports completion', async () => {
const user = userEvent.setup()
const pending = createDeferred<typeof renamed>()
rename.mockReturnValue(pending.promise)
- render(<RenameModal {...props} />)
+ renderRenameDialog()
const input = screen.getByRole('textbox', { name: 'datasetDocuments.list.table.name' })
expect(input).toHaveValue(props.name)
await user.clear(input)
@@ -33,16 +57,16 @@ it('submits the edited document name once while saving and reports completion',
name: 'Updated document',
})
expect(props.onSaved).not.toHaveBeenCalled()
- expect(props.onClose).not.toHaveBeenCalled()
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
await act(async () => pending.resolve(renamed))
await waitFor(() => expect(props.onSaved).toHaveBeenCalledOnce())
- expect(props.onClose).toHaveBeenCalledOnce()
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
it('keeps the edited name after a failed save so the user can retry', async () => {
const user = userEvent.setup()
rename.mockRejectedValueOnce(new Error('API Error')).mockResolvedValue(renamed)
- render(<RenameModal {...props} />)
+ renderRenameDialog()
const input = screen.getByRole('textbox', { name: 'datasetDocuments.list.table.name' })
await user.clear(input)
await user.type(input, 'Updated document')
@@ -50,19 +74,23 @@ it('keeps the edited name after a failed save so the user can retry', async () =
await waitFor(() => expect(toastError).toHaveBeenCalledWith('API Error'))
expect(input).toHaveValue('Updated document')
expect(props.onSaved).not.toHaveBeenCalled()
- expect(props.onClose).not.toHaveBeenCalled()
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => expect(props.onSaved).toHaveBeenCalledOnce())
})
it('cancels an edited name without saving', async () => {
const user = userEvent.setup()
- render(<RenameModal {...props} />)
+ const handle = renderRenameDialog()
await user.type(
screen.getByRole('textbox', { name: 'datasetDocuments.list.table.name' }),
' draft',
)
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
- expect(props.onClose).toHaveBeenCalledOnce()
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(rename).not.toHaveBeenCalled()
+ act(() => handle.openWithPayload({ id: props.documentId, name: props.name }))
+ expect(screen.getByRole('textbox', { name: 'datasetDocuments.list.table.name' })).toHaveValue(
+ props.name,
+ )
})
diff --git a/web/app/components/datasets/documents/components/document-list/components/__tests__/document-table-row.spec.tsx b/web/app/components/datasets/documents/components/document-list/components/__tests__/document-table-row.spec.tsx
index 04865576a23..63a77f9772e 100644
--- a/web/app/components/datasets/documents/components/document-list/components/__tests__/document-table-row.spec.tsx
+++ b/web/app/components/datasets/documents/components/document-list/components/__tests__/document-table-row.spec.tsx
@@ -92,10 +92,9 @@ describe('DocumentTableRow', () => {
isGeneralMode: true,
isQAMode: false,
embeddingAvailable: true,
- selectedIds: [],
- onSelectedIdChange: vi.fn(),
onShowRenameModal: vi.fn(),
onUpdate: vi.fn(),
+ onDelete: vi.fn(),
}
beforeEach(() => {
diff --git a/web/app/components/datasets/documents/components/document-list/components/document-table-row.tsx b/web/app/components/datasets/documents/components/document-list/components/document-table-row.tsx
index f1a84106088..024ab352464 100644
--- a/web/app/components/datasets/documents/components/document-list/components/document-table-row.tsx
+++ b/web/app/components/datasets/documents/components/document-list/components/document-table-row.tsx
@@ -33,9 +33,8 @@ type DocumentTableRowProps = {
isGeneralMode: boolean
isQAMode: boolean
embeddingAvailable: boolean
- selectedIds: string[]
- onSelectedIdChange: (ids: string[]) => void
onShowRenameModal: (doc: LocalDoc) => void
+ onDelete: (row: HTMLTableRowElement | null) => void
onUpdate: () => void
}
@@ -55,15 +54,15 @@ const DocumentTableRow = React.memo(
isGeneralMode,
isQAMode,
embeddingAvailable,
- selectedIds,
- onSelectedIdChange,
onShowRenameModal,
onUpdate,
+ onDelete,
}: DocumentTableRowProps) => {
const { t } = useTranslation(['datasetDocuments', 'datasetHitTesting'])
const { formatTime } = useTimestamp()
const router = useRouter()
const searchParams = useSearchParams()
+ const rowRef = React.useRef<HTMLTableRowElement>(null)
const documentNameId = React.useId()
const dataset = useDatasetDetailContextWithSelector((s) => s.dataset)
const { data: currentUserId } = useSuspenseQuery({
@@ -108,6 +107,7 @@ const DocumentTableRow = React.memo(
return (
<tr
+ ref={rowRef}
className="h-8 cursor-pointer border-b border-divider-subtle hover:bg-background-default-hover"
onClick={handleRowClick}
>
@@ -187,8 +187,6 @@ const DocumentTableRow = React.memo(
</td>
<td>
<Operations
- selectedIds={selectedIds}
- onSelectedIdChange={onSelectedIdChange}
embeddingAvailable={embeddingAvailable}
datasetId={datasetId}
detail={pick(doc, [
@@ -201,6 +199,7 @@ const DocumentTableRow = React.memo(
'display_status',
])}
onUpdate={onUpdate}
+ onDelete={() => onDelete(rowRef.current)}
canEdit={datasetACLCapabilities.canEdit}
canDownload={datasetACLCapabilities.canDocumentDownload}
canDelete={datasetACLCapabilities.canDeleteFile}
diff --git a/web/app/components/datasets/documents/components/list.tsx b/web/app/components/datasets/documents/components/list.tsx
index 6f7295bd762..36a5fec9d82 100644
--- a/web/app/components/datasets/documents/components/list.tsx
+++ b/web/app/components/datasets/documents/components/list.tsx
@@ -1,12 +1,13 @@
'use client'
import type { DocumentWithSegmentsResponse } from '@dify/contracts/api/console/datasets/types.gen'
+import type { RenameDocumentPayload } from './rename-document-form'
import type { SortType } from '@/service/datasets'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import { CheckboxGroup } from '@langgenius/dify-ui/checkbox-group'
+import { createDialogHandle, Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { Pagination } from '@langgenius/dify-ui/pagination'
import { useSuspenseQuery } from '@tanstack/react-query'
-import { useBoolean } from 'ahooks'
import { useAtomValue } from 'jotai'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -20,7 +21,7 @@ import { getDatasetACLCapabilities } from '@/utils/permission'
import BatchAction from '../detail/completed/common/batch-action'
import { DocumentTableRow, SortHeader } from './document-list/components'
import { useDocumentActions, useDocumentSelection, useDocumentSort } from './document-list/hooks'
-import RenameModal from './rename-modal'
+import { RenameDocumentForm } from './rename-document-form'
type LocalDoc = DocumentWithSegmentsResponse & { percent?: number }
@@ -40,6 +41,7 @@ type DocumentListProps = {
onSelectedIdChange: (selectedIds: string[]) => void
datasetId: string
pagination: PaginationProps
+ onDelete: (id: string, row: HTMLTableRowElement | null) => void
onUpdate: () => void
onManageMetadata: () => void
remoteSortValue: string
@@ -57,6 +59,7 @@ const DocumentList = ({
datasetId,
pagination,
onUpdate,
+ onDelete,
onManageMetadata,
remoteSortValue,
onSortChange,
@@ -121,20 +124,9 @@ const DocumentList = ({
onUpdate,
})
- // Rename modal
- const [currDocument, setCurrDocument] = useState<LocalDoc | null>(null)
- const [
- isShowRenameModal,
- { setTrue: setShowRenameModalTrue, setFalse: setShowRenameModalFalse },
- ] = useBoolean(false)
-
- const handleShowRenameModal = useCallback(
- (doc: LocalDoc) => {
- setCurrDocument(doc)
- setShowRenameModalTrue()
- },
- [setShowRenameModalTrue],
- )
+ const [renameDialog] = useState(() => createDialogHandle<RenameDocumentPayload>())
+ const handleShowRenameModal = (doc: LocalDoc) =>
+ renameDialog.openWithPayload({ id: doc.id, name: doc.name })
const handleRenamed = useCallback(() => {
onUpdate()
@@ -230,10 +222,9 @@ const DocumentList = ({
isGeneralMode={isGeneralMode}
isQAMode={isQAMode}
embeddingAvailable={embeddingAvailable}
- selectedIds={selectedIds}
- onSelectedIdChange={onSelectedIdChange}
onShowRenameModal={handleShowRenameModal}
onUpdate={onUpdate}
+ onDelete={(row) => onDelete(doc.id, row)}
/>
))}
</tbody>
@@ -303,15 +294,21 @@ const DocumentList = ({
/>
)}
- {isShowRenameModal && currDocument && (
- <RenameModal
- datasetId={datasetId}
- documentId={currDocument.id}
- name={currDocument.name}
- onClose={setShowRenameModalFalse}
- onSaved={handleRenamed}
- />
- )}
+ <Dialog handle={renameDialog}>
+ {({ payload }) => (
+ <DialogContent>
+ {payload && (
+ <RenameDocumentForm
+ datasetId={datasetId}
+ documentId={payload.id}
+ name={payload.name}
+ onSaved={handleRenamed}
+ onClose={() => renameDialog.close()}
+ />
+ )}
+ </DialogContent>
+ )}
+ </Dialog>
{isShowEditModal && (
<EditMetadataBatchModal
diff --git a/web/app/components/datasets/documents/components/operations.tsx b/web/app/components/datasets/documents/components/operations.tsx
index ce729c948ba..f7ead6fe79f 100644
--- a/web/app/components/datasets/documents/components/operations.tsx
+++ b/web/app/components/datasets/documents/components/operations.tsx
@@ -1,15 +1,6 @@
import type { OperationName } from '../types'
-import {
- AlertDialog,
- AlertDialogCancelButton,
- AlertDialogConfirmButton,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from '@langgenius/dify-ui/alert-dialog'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import {
DropdownMenu,
DropdownMenuContent,
@@ -21,7 +12,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/pop
import { Separator } from '@langgenius/dify-ui/separator'
import { Switch } from '@langgenius/dify-ui/switch'
import { useMutation, useSuspenseQuery } from '@tanstack/react-query'
-import { useBoolean, useDebounceFn } from 'ahooks'
+import { useDebounceFn } from 'ahooks'
import { noop } from 'es-toolkit/function'
import * as React from 'react'
import { useCallback, useState } from 'react'
@@ -33,7 +24,7 @@ import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { asyncRunSafe } from '@/utils'
import { downloadUrl } from '@/utils/download'
-import RenameModal from './rename-modal'
+import { RenameDocumentForm } from './rename-document-form'
type OperationsProps = {
embeddingAvailable: boolean
@@ -46,9 +37,8 @@ type OperationsProps = {
doc_form?: string | null
display_status?: string | null
}
- selectedIds?: string[]
- onSelectedIdChange?: (ids: string[]) => void
datasetId: string
+ onDelete: () => void
onUpdate: (operationName?: string) => void
scene?: 'list' | 'detail'
className?: string
@@ -61,9 +51,8 @@ const Operations = ({
embeddingAvailable,
datasetId,
detail,
- selectedIds,
- onSelectedIdChange,
onUpdate,
+ onDelete,
scene = 'list',
className = '',
canEdit,
@@ -79,15 +68,12 @@ const Operations = ({
const { id, name, data_source_type, display_status } = detail
const enabled = detail.enabled ?? false
const archived = detail.archived ?? false
- const [showModal, setShowModal] = useState(false)
- const [deleting, setDeleting] = useState(false)
const { t } = useTranslation(['common', 'datasetDocuments'])
const router = useRouter()
const documents = consoleQuery.datasets.byDatasetId.documents
const { mutateAsync: changeDocumentStatus } = useMutation(
documents.status.byAction.batch.patch.mutationOptions(),
)
- const { mutateAsync: deleteDocuments } = useMutation(documents.delete.mutationOptions())
const { mutateAsync: downloadDocument, isPending: isDownloading } = useMutation(
documents.byDocumentId.download.get.mutationOptions(),
)
@@ -130,17 +116,9 @@ const Operations = ({
canShowPauseAction || canShowResumeAction || canShowArchiveAction || canShowUnarchiveAction
const hasOperationsMenu =
embeddingAvailable && (canShowPrimarySection || canShowStatusSection || canShowDeleteAction)
- const canOperate = useCallback(
- (operationName: OperationName) => {
- if (operationName === DocumentActionType.delete) return canDelete
-
- return canEdit
- },
- [canDelete, canEdit],
- )
const onOperate = useCallback(
- async (operationName: OperationName) => {
- if (!canOperate(operationName)) return
+ async (operationName: Exclude<OperationName, 'delete'>) => {
+ if (!canEdit) return
const documentParams = { dataset_id: datasetId, document_id: id }
const runOperation = (): Promise<unknown> => {
@@ -166,12 +144,6 @@ const Operations = ({
return pauseDocument({ params: documentParams })
case 'resume':
return resumeDocument({ params: documentParams })
- default:
- setDeleting(true)
- return deleteDocuments({
- params: { dataset_id: datasetId },
- query: { document_id: [id] },
- })
}
}
const [e] = await asyncRunSafe(runOperation())
@@ -179,35 +151,28 @@ const Operations = ({
// The switch already shows the result of enable and disable.
if (operationName !== 'enable' && operationName !== 'disable')
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
- // If it is a delete operation, need to update the selectedIds state
- if (selectedIds && onSelectedIdChange && operationName === DocumentActionType.delete)
- onSelectedIdChange(selectedIds.filter((selectedId) => selectedId !== id))
onUpdate(operationName)
} else {
toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
}
- if (operationName === DocumentActionType.delete) setDeleting(false)
},
[
- canOperate,
+ canEdit,
changeDocumentStatus,
data_source_type,
datasetId,
- deleteDocuments,
generateSummary,
id,
- onSelectedIdChange,
onUpdate,
pauseDocument,
resumeDocument,
- selectedIds,
syncNotionDocument,
syncWebsiteDocument,
t,
],
)
const { run: handleSwitch } = useDebounceFn(
- (operationName: OperationName) => {
+ (operationName: Exclude<OperationName, 'delete'>) => {
if (!canEdit) return
if (operationName === DocumentActionType.enable && enabled) return
if (operationName === DocumentActionType.disable && !enabled) return
@@ -215,23 +180,7 @@ const Operations = ({
},
{ wait: 500 },
)
- const [currDocument, setCurrDocument] = useState<{
- id: string
- name: string
- } | null>(null)
- const [
- isShowRenameModal,
- { setTrue: setShowRenameModalTrue, setFalse: setShowRenameModalFalse },
- ] = useBoolean(false)
- const handleShowRenameModal = useCallback(
- (doc: { id: string; name: string }) => {
- if (!canEdit) return
-
- setCurrDocument(doc)
- setShowRenameModalTrue()
- },
- [canEdit, setShowRenameModalTrue],
- )
+ const [renameOpen, setRenameOpen] = useState(false)
const handleRenamed = useCallback(() => {
onUpdate()
}, [onUpdate])
@@ -253,14 +202,11 @@ const Operations = ({
// Trigger download without navigating away (helps avoid duplicate downloads in some browsers).
downloadUrl({ url: res.url, fileName: name ?? undefined })
}, [canDownload, datasetId, downloadDocument, id, isDownloading, name, t])
- const handleShowRename = useCallback(() => {
- handleShowRenameModal({
- id: detail.id,
- name: detail.name ?? '',
- })
- }, [detail.id, detail.name, handleShowRenameModal])
+ const handleShowRename = () => {
+ if (canEdit) setRenameOpen(true)
+ }
const handleMenuOperation = useCallback(
- (operationName: OperationName) => {
+ (operationName: Exclude<OperationName, 'delete'>) => {
void onOperate(operationName)
},
[onOperate],
@@ -268,8 +214,8 @@ const Operations = ({
const handleDeleteClick = useCallback(() => {
if (!canDelete) return
- setShowModal(true)
- }, [canDelete])
+ onDelete()
+ }, [canDelete, onDelete])
const handleDownloadClick = useCallback(
(evt: React.MouseEvent<HTMLElement>) => {
evt.preventDefault()
@@ -512,36 +458,18 @@ const Operations = ({
</DropdownMenu>
</>
)}
- <AlertDialog open={showModal} onOpenChange={(open) => !open && setShowModal(false)}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $['list.delete.title'], { ns: 'datasetDocuments' })}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $['list.delete.content'], { ns: 'datasetDocuments' })}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton loading={deleting} onClick={() => onOperate('delete')}>
- {t(($) => $['operation.sure'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- {isShowRenameModal && currDocument && (
- <RenameModal
- datasetId={datasetId}
- documentId={currDocument.id}
- name={currDocument.name}
- onClose={setShowRenameModalFalse}
- onSaved={handleRenamed}
- />
- )}
+ <Dialog open={renameOpen} onOpenChange={setRenameOpen}>
+ <DialogContent>
+ <RenameDocumentForm
+ datasetId={datasetId}
+ documentId={id}
+ name={name ?? ''}
+ onSaved={handleRenamed}
+ onClose={() => setRenameOpen(false)}
+ />
+ </DialogContent>
+ </Dialog>
</div>
)
}
diff --git a/web/app/components/datasets/documents/components/rename-document-form.tsx b/web/app/components/datasets/documents/components/rename-document-form.tsx
new file mode 100644
index 00000000000..bb711ef3ae5
--- /dev/null
+++ b/web/app/components/datasets/documents/components/rename-document-form.tsx
@@ -0,0 +1,84 @@
+'use client'
+import type { DocumentWithSegmentsResponse } from '@dify/contracts/api/console/datasets/types.gen'
+import { Button } from '@langgenius/dify-ui/button'
+import { DialogBody, DialogFooter, DialogHeader, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { Field, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
+import { Input } from '@langgenius/dify-ui/input'
+import { useBoolean } from 'ahooks'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from '@/app/notifications'
+import { renameDocumentName } from '@/service/datasets'
+
+export type RenameDocumentPayload = Pick<DocumentWithSegmentsResponse, 'id' | 'name'>
+
+export function RenameDocumentForm({
+ documentId,
+ datasetId,
+ name,
+ onClose,
+ onSaved,
+}: {
+ documentId: string
+ datasetId: string
+ name: string
+ onClose: () => void
+ onSaved: () => void
+}) {
+ const { t } = useTranslation(['common', 'datasetDocuments'])
+
+ const [newName, setNewName] = useState(name)
+ const [saveLoading, { setTrue: setSaveLoadingTrue, setFalse: setSaveLoadingFalse }] =
+ useBoolean(false)
+
+ const handleSave = async () => {
+ if (saveLoading) return
+
+ setSaveLoadingTrue()
+ try {
+ await renameDocumentName({
+ datasetId,
+ documentId,
+ name: newName,
+ })
+ onSaved()
+ onClose()
+ } catch (error) {
+ if (error) toast.error(error instanceof Error ? error.message : String(error))
+ } finally {
+ setSaveLoadingFalse()
+ }
+ }
+
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>{t(($) => $['list.table.rename'], { ns: 'datasetDocuments' })}</DialogTitle>
+ </DialogHeader>
+ <Form className="contents" onFormSubmit={() => void handleSave()}>
+ <DialogBody>
+ <Field name="documentName">
+ <FieldLabel className="text-sm leading-5.25 font-medium text-text-primary">
+ {t(($) => $['list.table.name'], { ns: 'datasetDocuments' })}
+ </FieldLabel>
+ <Input
+ className="h-10"
+ value={newName}
+ placeholder={t(($) => $['placeholder.input'], { ns: 'common' }) || ''}
+ onValueChange={setNewName}
+ />
+ </Field>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" className="shrink-0" onClick={onClose}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </Button>
+ <Button type="submit" variant="primary" className="shrink-0" loading={saveLoading}>
+ {t(($) => $['operation.save'], { ns: 'common' })}
+ </Button>
+ </DialogFooter>
+ </Form>
+ </>
+ )
+}
diff --git a/web/app/components/datasets/documents/components/rename-modal.tsx b/web/app/components/datasets/documents/components/rename-modal.tsx
deleted file mode 100644
index 87e2bc8d25c..00000000000
--- a/web/app/components/datasets/documents/components/rename-modal.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-'use client'
-import type { FC } from 'react'
-import { Button } from '@langgenius/dify-ui/button'
-import {
- Dialog,
- DialogBody,
- DialogContent,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@langgenius/dify-ui/dialog'
-import { Field, FieldLabel } from '@langgenius/dify-ui/field'
-import { Form } from '@langgenius/dify-ui/form'
-import { Input } from '@langgenius/dify-ui/input'
-import { useBoolean } from 'ahooks'
-import * as React from 'react'
-import { useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { toast } from '@/app/notifications'
-import { renameDocumentName } from '@/service/datasets'
-
-type Props = Readonly<{
- datasetId: string
- documentId: string
- name: string
- onClose: () => void
- onSaved: () => void
-}>
-
-const RenameModal: FC<Props> = ({ documentId, datasetId, name, onClose, onSaved }) => {
- const { t } = useTranslation(['common', 'datasetDocuments'])
-
- const [newName, setNewName] = useState(name)
- const [saveLoading, { setTrue: setSaveLoadingTrue, setFalse: setSaveLoadingFalse }] =
- useBoolean(false)
-
- const handleSave = async () => {
- if (saveLoading) return
-
- setSaveLoadingTrue()
- try {
- await renameDocumentName({
- datasetId,
- documentId,
- name: newName,
- })
- onSaved()
- onClose()
- } catch (error) {
- if (error) toast.error(error instanceof Error ? error.message : String(error))
- } finally {
- setSaveLoadingFalse()
- }
- }
-
- return (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) onClose()
- }}
- >
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t(($) => $['list.table.rename'], { ns: 'datasetDocuments' })}</DialogTitle>
- </DialogHeader>
- <Form className="contents" onFormSubmit={() => void handleSave()}>
- <DialogBody>
- <Field name="documentName">
- <FieldLabel className="text-sm leading-5.25 font-medium text-text-primary">
- {t(($) => $['list.table.name'], { ns: 'datasetDocuments' })}
- </FieldLabel>
- <Input
- className="h-10"
- value={newName}
- placeholder={t(($) => $['placeholder.input'], { ns: 'common' }) || ''}
- onValueChange={setNewName}
- />
- </Field>
- </DialogBody>
- <DialogFooter>
- <Button type="button" className="shrink-0" onClick={onClose}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- <Button type="submit" variant="primary" className="shrink-0" loading={saveLoading}>
- {t(($) => $['operation.save'], { ns: 'common' })}
- </Button>
- </DialogFooter>
- </Form>
- </DialogContent>
- </Dialog>
- )
-}
-export default React.memo(RenameModal)
diff --git a/web/app/components/datasets/documents/detail/index.tsx b/web/app/components/datasets/documents/detail/index.tsx
index c4b48b91fa9..4c407220add 100644
--- a/web/app/components/datasets/documents/detail/index.tsx
+++ b/web/app/components/datasets/documents/detail/index.tsx
@@ -4,6 +4,16 @@ import type { DocumentDetailResponse } from '@dify/contracts/api/console/dataset
import type { FC } from 'react'
import type { FileItem } from '@/models/datasets'
import type { SegmentImportStatus } from '@/types/dataset'
+import {
+ AlertDialog,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from '@langgenius/dify-ui/alert-dialog'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import {
@@ -52,6 +62,12 @@ const NON_TERMINAL_DISPLAY_STATUSES = new Set<(typeof DisplayStatusList)[number]
)
const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {
+ const [deleteOpen, setDeleteOpen] = useState(false)
+ const deletion = useMutation(
+ consoleQuery.datasets.byDatasetId.documents.delete.mutationOptions({
+ context: { silent: true },
+ }),
+ )
const router = useRouter()
const searchParams = useSearchParams()
const { t } = useTranslation(['common', 'datasetDocuments', 'navigation'])
@@ -358,6 +374,7 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {
detail={operationsDetail}
datasetId={datasetId}
onUpdate={handleOperate}
+ onDelete={() => setDeleteOpen(true)}
className="w-50!"
canEdit={canEditDocument}
canDownload={datasetACLCapabilities.canDocumentDownload}
@@ -444,6 +461,57 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {
onConfirm={runBatch}
docForm={documentDetail?.doc_form as ChunkingMode}
/>
+ <AlertDialog
+ open={deleteOpen}
+ onOpenChange={(open, details) => {
+ if (!open && deletion.isPending) {
+ details.cancel()
+ return
+ }
+ setDeleteOpen(open)
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) deletion.reset()
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $['list.delete.title'], { ns: 'datasetDocuments' })}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $['list.delete.content'], { ns: 'datasetDocuments' })}
+ </AlertDialogDescription>
+ {deletion.isError && (
+ <p role="alert" className="text-text-destructive">
+ {t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' })}
+ </p>
+ )}
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancelButton disabled={deletion.isPending}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton
+ loading={deletion.isPending}
+ onClick={() => {
+ if (deletion.isPending) return
+ deletion.mutate(
+ { params: { dataset_id: datasetId }, query: { document_id: [documentId] } },
+ {
+ onSuccess: () => {
+ setDeleteOpen(false)
+ backToPrev()
+ },
+ },
+ )
+ }}
+ >
+ {t(($) => $['operation.sure'], { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</div>
</DocumentContext.Provider>
)
diff --git a/web/app/components/datasets/documents/index.tsx b/web/app/components/datasets/documents/index.tsx
index 2d9e9db0459..3daf218bc92 100644
--- a/web/app/components/datasets/documents/index.tsx
+++ b/web/app/components/datasets/documents/index.tsx
@@ -1,9 +1,27 @@
'use client'
import type { FC } from 'react'
-import { keepPreviousData, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
+import {
+ AlertDialog,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ createAlertDialogHandle,
+} from '@langgenius/dify-ui/alert-dialog'
+import {
+ keepPreviousData,
+ useMutation,
+ useQuery,
+ useQueryClient,
+ useSuspenseQuery,
+} from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { useCallback } from 'react'
+import { useCallback, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { toCreationDataSourceType } from '@/app/components/datasets/dataset-fields'
import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'
@@ -12,6 +30,7 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'
import { DataSourceType } from '@/models/datasets'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
+import { getAdjacentFocusTargets } from '@/utils/get-adjacent-focus-targets'
import { getDatasetACLCapabilities } from '@/utils/permission'
import useEditDocumentMetadata from '../metadata/hooks/use-edit-dataset-metadata'
import DocumentsHeader from './components/documents-header'
@@ -29,6 +48,20 @@ const TERMINAL_INDEXING_STATUSES = new Set(['completed', 'paused', 'error'])
const FORCED_POLLING_STATUSES = new Set(['queuing', 'indexing', 'paused'])
const Documents: FC<IDocumentsProps> = ({ datasetId }) => {
+ const { t } = useTranslation(['common', 'datasetDocuments'])
+ const listRef = useRef<HTMLDivElement>(null)
+ const [deleteDialog] = useState(() =>
+ createAlertDialogHandle<{
+ id: string
+ adjacentFocusTargets: HTMLElement[]
+ fallbackFocus: { current: HTMLElement | null }
+ }>(),
+ )
+ const deletion = useMutation(
+ consoleQuery.datasets.byDatasetId.documents.delete.mutationOptions({
+ context: { silent: true },
+ }),
+ )
const router = useRouter()
const dataset = useDatasetDetailContextWithSelector((s) => s.dataset)
@@ -166,6 +199,16 @@ const Documents: FC<IDocumentsProps> = ({ datasetId }) => {
documents={documentsList || []}
datasetId={datasetId}
onUpdate={handleUpdate}
+ onDelete={(id, row) => {
+ const adjacentFocusTargets = getAdjacentFocusTargets(row, (sibling) =>
+ sibling.querySelector<HTMLAnchorElement>('a[href]'),
+ )
+ deleteDialog.openWithPayload({
+ id,
+ adjacentFocusTargets,
+ fallbackFocus: { current: null },
+ })
+ }}
selectedIds={selectedIds}
onSelectedIdChange={setSelectedIds}
remoteSortValue={sortValue}
@@ -220,7 +263,75 @@ const Documents: FC<IDocumentsProps> = ({ datasetId }) => {
onBuiltInEnabledChange={setBuiltInEnabled}
onAddDocument={routeToDocCreate}
/>
- <div className="flex h-0 grow flex-col px-6 pt-4">{renderContent()}</div>
+ <div
+ ref={listRef}
+ tabIndex={-1}
+ role="region"
+ aria-label={t(($) => $['list.title'], { ns: 'datasetDocuments' })}
+ className="flex h-0 grow flex-col px-6 pt-4 focus-visible:outline-2 focus-visible:outline-state-accent-solid"
+ >
+ {renderContent()}
+ </div>
+ <AlertDialog
+ handle={deleteDialog}
+ onOpenChange={(open, details) => {
+ if (!open && deletion.isPending && details.reason !== 'imperative-action')
+ details.cancel()
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) deletion.reset()
+ }}
+ >
+ {({ payload }) => (
+ <AlertDialogContent
+ finalFocus={() => {
+ const fallback = payload?.fallbackFocus.current
+ if (!fallback) return true
+ const target =
+ payload.adjacentFocusTargets.find((element) => element.isConnected) ?? fallback
+ target.focus({ preventScroll: true })
+ return false
+ }}
+ >
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $['list.delete.title'], { ns: 'datasetDocuments' })}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $['list.delete.content'], { ns: 'datasetDocuments' })}
+ </AlertDialogDescription>
+ {deletion.isError && (
+ <p role="alert" className="text-text-destructive">
+ {t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' })}
+ </p>
+ )}
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancelButton disabled={deletion.isPending}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton
+ loading={deletion.isPending}
+ onClick={() => {
+ if (!payload || deletion.isPending) return
+ deletion.mutate(
+ { params: { dataset_id: datasetId }, query: { document_id: [payload.id] } },
+ {
+ onSuccess: () => {
+ setSelectedIds(selectedIds.filter((id) => id !== payload.id))
+ payload.fallbackFocus.current = listRef.current
+ deleteDialog.close()
+ },
+ },
+ )
+ }}
+ >
+ {t(($) => $['operation.sure'], { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ )}
+ </AlertDialog>
</div>
)
}
diff --git a/web/app/components/datasets/list/__tests__/delete-dataset.browser.spec.tsx b/web/app/components/datasets/list/__tests__/delete-dataset.browser.spec.tsx
new file mode 100644
index 00000000000..81ba2deb1ee
--- /dev/null
+++ b/web/app/components/datasets/list/__tests__/delete-dataset.browser.spec.tsx
@@ -0,0 +1,194 @@
+import type { consoleClient } from '@/service/console'
+import { useInfiniteQuery } from '@tanstack/react-query'
+import { userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { QueryClientTestProvider } from '@/test/console/query-provider'
+import { createDeferred } from '@/test/deferred'
+import { createDatasetFixture } from '@/test/fixtures/dataset'
+import { DatasetACLPermission } from '@/utils/permission'
+import Datasets from '../datasets'
+
+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }))
+
+const api = vi.hoisted(() => ({
+ list: vi.fn<typeof consoleClient.datasets.get>(),
+ remove: vi.fn<typeof consoleClient.datasets.byDatasetId.delete>(),
+ usage: vi.fn<typeof consoleClient.datasets.byDatasetId.useCheck.get>(),
+}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'datasets.get': api.list,
+ 'datasets.byDatasetId.delete': api.remove,
+ 'datasets.byDatasetId.useCheck.get': api.usage,
+ 'tags.get': async () => [],
+ }),
+ }
+})
+function Catalog() {
+ const query = useInfiniteQuery(
+ consoleQuery.datasets.get.infiniteOptions({
+ input: (page) => ({ query: { page, limit: 30 } }),
+ initialPageParam: 1,
+ getNextPageParam: () => undefined,
+ }),
+ )
+ return (
+ <Datasets
+ datasetList={query.data}
+ fetchNextPage={query.fetchNextPage}
+ hasNextPage={query.hasNextPage}
+ isFetching={query.isFetching}
+ isFetchingNextPage={query.isFetchingNextPage}
+ isLoading={query.isLoading}
+ isPlaceholderData={query.isPlaceholderData}
+ />
+ )
+}
+beforeEach(() => vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false))
+afterEach(() => vi.unstubAllGlobals())
+async function setup(ids: string[]) {
+ let datasets = ids.map((id) =>
+ createDatasetFixture({
+ id,
+ name: id,
+ permission_keys: [DatasetACLPermission.Delete],
+ runtime_mode: 'general',
+ }),
+ )
+ api.list.mockReset().mockImplementation(async () => ({
+ data: datasets,
+ page: 1,
+ total: datasets.length,
+ limit: 30,
+ has_more: false,
+ }))
+ api.remove.mockReset().mockImplementation(async ({ params }) => {
+ datasets = datasets.filter((item) => item.id !== params.dataset_id)
+ })
+ api.usage.mockReset().mockResolvedValue({ is_using: false })
+ const { queryClient } = createConsoleQueryWrapper({ systemFeatures: { rbac_enabled: true } })
+ const screen = await render(
+ <QueryClientTestProvider queryClient={queryClient}>
+ <Catalog />
+ </QueryClientTestProvider>,
+ )
+ const open = async (id: string) => {
+ const link = screen.getByRole('link', { name: id, exact: true })
+ await link.hover()
+ const card = link.element().closest('li')!
+ await userEvent.click(card.querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')!)
+ await screen.getByRole('menuitem', { name: 'common.operation.delete', exact: true }).click()
+ await expect.element(screen.getByRole('alertdialog')).toBeVisible()
+ await expect.element(screen.getByRole('menu')).not.toBeInTheDocument()
+ }
+ return { screen, open }
+}
+describe('Classic dataset deletion', () => {
+ it('removes the confirmed item and restores focus before the list refresh completes', async () => {
+ const { screen, open } = await setup(['Alpha', 'Beta'])
+ await open('Alpha')
+ const list = api.list.getMockImplementation()!
+ const refresh = createDeferred<Awaited<ReturnType<typeof list>>>()
+ api.list.mockReturnValueOnce(refresh.promise)
+ await screen.getByRole('button', { name: 'common.operation.confirm' }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('link', { name: 'Alpha', exact: true }))
+ .not.toBeInTheDocument()
+ await expect.element(screen.getByRole('link', { name: 'Beta', exact: true })).toHaveFocus()
+ refresh.resolve(await list({ query: { page: 1, limit: 30 } }))
+ })
+
+ it('reports a failed usage check without changing the confirmation action', async () => {
+ const { screen, open } = await setup(['Alpha'])
+ api.usage.mockRejectedValueOnce(new Error('Usage check failed'))
+ await open('Alpha')
+ await expect.element(screen.getByRole('alert')).toBeVisible()
+ expect(api.remove).not.toHaveBeenCalled()
+ await screen.getByRole('button', { name: 'common.operation.retry' }).click()
+ await screen.getByRole('button', { name: 'common.operation.confirm' }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ expect(api.remove).toHaveBeenCalledTimes(1)
+ })
+
+ it('ignores an earlier usage check that completes after another deletion opens', async () => {
+ const { screen, open } = await setup(['Alpha', 'Beta'])
+ const earlier = createDeferred<{ is_using: boolean }>()
+ api.usage.mockReturnValueOnce(earlier.promise)
+ await open('Alpha')
+ await expect
+ .element(screen.getByRole('button', { name: 'common.operation.confirm' }))
+ .toBeEnabled()
+ await screen.getByRole('button', { name: 'common.operation.cancel' }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await open('Beta')
+ earlier.resolve({ is_using: true })
+ await earlier.promise
+ await screen.getByRole('button', { name: 'common.operation.confirm' }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ expect(api.remove).toHaveBeenCalledWith(
+ expect.objectContaining({ params: { dataset_id: 'Beta' } }),
+ )
+ await expect.element(screen.getByRole('link', { name: 'Alpha', exact: true })).toBeVisible()
+ })
+
+ it.each([
+ { ids: ['Alpha', 'Beta', 'Gamma'], remove: 'Beta', next: 'Gamma' },
+ { ids: ['Alpha', 'Beta'], remove: 'Beta', next: 'Alpha' },
+ { ids: ['Alpha'], remove: 'Alpha', next: null },
+ ])('restores focus after deleting $remove from $ids', async ({ ids, remove, next }) => {
+ const { screen, open } = await setup(ids)
+ await open(remove)
+ await screen.getByRole('button', { name: 'common.operation.confirm' }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('link', { name: remove, exact: true }))
+ .not.toBeInTheDocument()
+ await expect
+ .element(
+ next ? screen.getByRole('link', { name: next, exact: true }) : screen.getByRole('region'),
+ )
+ .toHaveFocus()
+ })
+ it('retains focus while pending and leaves a failed deletion retryable', async () => {
+ const { screen, open } = await setup(['Alpha'])
+ const request = createDeferred<void>()
+ api.remove.mockReturnValueOnce(request.promise)
+ await open('Alpha')
+ const confirm = screen.getByRole('button', { name: 'common.operation.confirm' })
+ await confirm.click()
+ await expect.element(confirm).toHaveFocus()
+ await userEvent.keyboard('{Escape}')
+ await expect
+ .element(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ .toBeDisabled()
+ await expect.element(screen.getByRole('alertdialog')).toBeVisible()
+ request.reject(new Error('Failed'))
+ await expect.element(screen.getByRole('alert')).toBeVisible()
+ await confirm.click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect.element(screen.getByRole('region')).toHaveFocus()
+ })
+ it('rechecks usage after cancellation and returns focus to the surviving menu button', async () => {
+ const { screen, open } = await setup(['Alpha'])
+ await open('Alpha')
+ await screen.getByRole('button', { name: 'common.operation.cancel' }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('button', { name: 'common.operation.more' }))
+ .toHaveFocus()
+ api.usage.mockResolvedValueOnce({ is_using: true })
+ await open('Alpha')
+ await expect
+ .element(screen.getByText('dataset.datasetUsedByApp', { exact: true }))
+ .toBeVisible()
+ expect(api.usage).toHaveBeenCalledTimes(2)
+ expect(api.remove).not.toHaveBeenCalled()
+ })
+})
diff --git a/web/app/components/datasets/list/dataset-card/__tests__/index.browser.spec.tsx b/web/app/components/datasets/list/dataset-card/__tests__/index.browser.spec.tsx
index 2341e6a2e79..6a54fc3b5ca 100644
--- a/web/app/components/datasets/list/dataset-card/__tests__/index.browser.spec.tsx
+++ b/web/app/components/datasets/list/dataset-card/__tests__/index.browser.spec.tsx
@@ -29,6 +29,7 @@ it('makes the whole card the entry while footer details and tags stay separate c
<button type="button">Before dataset</button>
<ul className="mt-4 grid w-80 p-4">
<DatasetCard
+ onDelete={vi.fn()}
dataset={createDatasetFixture({
permission_keys: [DatasetACLPermission.Edit],
document_count: 3,
@@ -64,3 +65,44 @@ it('makes the whole card the entry while footer details and tags stay separate c
.element(screen.getByRole('dialog', { name: 'common.datasetMenus.documents' }))
.toBeVisible()
})
+
+it('returns focus after renaming is cancelled and resets the draft on reopening', async () => {
+ vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false)
+ const { queryClient, wrapper: Providers } = createConsoleQueryWrapper({
+ accountProfile: { id: 'user-1' },
+ systemFeatures: { rbac_enabled: true },
+ })
+ queryClient.setQueryData(
+ consoleQuery.tags.get.queryOptions({ input: { query: { type: 'knowledge' } } }).queryKey,
+ [],
+ )
+ const screen = await render(
+ <Providers>
+ <ul className="grid w-80 p-4">
+ <DatasetCard
+ onDelete={vi.fn()}
+ dataset={createDatasetFixture({ permission_keys: [DatasetACLPermission.Edit] })}
+ />
+ </ul>
+ </Providers>,
+ )
+ const trigger = screen.getByRole('button', { name: 'common.operation.more' })
+ const open = async () => {
+ await screen.getByRole('link', { name: 'Test Dataset' }).hover()
+ await trigger.click()
+ await screen.getByRole('menuitem', { name: 'common.operation.edit', exact: true }).click()
+ await expect
+ .element(screen.getByRole('dialog', { name: 'datasetSettings.title' }))
+ .toBeVisible()
+ }
+ await open()
+ const name = screen.getByRole('textbox', { name: 'datasetSettings.form.name', exact: true })
+ await name.fill('Unsaved draft')
+ await userEvent.keyboard('{Escape}')
+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()
+ await expect.element(trigger).toHaveFocus()
+ await open()
+ await expect.element(name).toHaveValue('Test Dataset')
+})
+
+afterEach(() => vi.unstubAllGlobals())
diff --git a/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx b/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx
index 89db3758f66..d8927fd0fdc 100644
--- a/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx
@@ -1,6 +1,6 @@
import type { DatasetDetailWithPartialMembersResponse } from '@dify/contracts/api/console/datasets/types.gen'
import type { consoleClient } from '@/service/console'
-import { act, screen, waitFor, within } from '@testing-library/react'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { toast } from '@/app/notifications'
import { AppToaster } from '@/app/notifications/app-toaster'
@@ -12,8 +12,6 @@ import DatasetCard from '../index'
const api = vi.hoisted(() => ({
push: vi.fn(),
bindTags: vi.fn<typeof consoleClient.tagBindings.post>(),
- checkUsage: vi.fn<typeof consoleClient.datasets.byDatasetId.useCheck.get>(),
- deleteDataset: vi.fn<typeof consoleClient.datasets.byDatasetId.delete>(),
}))
vi.mock('@/next/navigation', async (importOriginal) => ({
...(await importOriginal<typeof import('@/next/navigation')>()),
@@ -27,8 +25,6 @@ vi.mock('@/service/console', async (importOriginal) => {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'tags.get': async () => [{ id: 'tag-1', name: 'Research', type: 'knowledge' }],
- 'datasets.byDatasetId.useCheck.get': api.checkUsage,
- 'datasets.byDatasetId.delete': api.deleteDataset,
}),
consoleClient: withConsoleClientResponses(actual.consoleClient, {
'tagBindings.post': api.bindTags,
@@ -39,8 +35,6 @@ vi.mock('@/service/console', async (importOriginal) => {
beforeEach(() => {
api.push.mockReset()
api.bindTags.mockReset().mockResolvedValue({ result: 'success' })
- api.checkUsage.mockReset().mockResolvedValue({ is_using: false })
- api.deleteDataset.mockReset().mockResolvedValue(undefined)
})
afterEach(() => act(() => toast.dismiss()))
@@ -53,7 +47,7 @@ function setup(
renderWithConsoleQuery(
<>
<AppToaster />
- <DatasetCard dataset={dataset} onSuccess={onSuccess} />
+ <DatasetCard onDelete={vi.fn()} dataset={dataset} onSuccess={onSuccess} />
</>,
{
accountProfile: { id: 'user-1' },
@@ -157,33 +151,3 @@ it('opens access configuration from the real card menu', async () => {
)
expect(api.push).toHaveBeenCalledExactlyOnceWith('/datasets/dataset-1/access-config')
})
-
-it('rechecks usage after cancellation and deletes only after confirmation', async () => {
- const { user, onSuccess } = setup({ permission_keys: [DatasetACLPermission.Delete] })
- const openDelete = async () => {
- await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
- await user.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
- return screen.findByRole('alertdialog', { name: 'dataset.deleteDatasetConfirmTitle' })
- }
- const firstDialog = await openDelete()
- expect(firstDialog).toHaveTextContent('dataset.deleteDatasetConfirmContent')
- expect(api.deleteDataset).not.toHaveBeenCalled()
- await user.click(within(firstDialog).getByRole('button', { name: 'common.operation.cancel' }))
- await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
- expect(api.deleteDataset).not.toHaveBeenCalled()
- expect(onSuccess).not.toHaveBeenCalled()
-
- api.checkUsage.mockResolvedValueOnce({ is_using: true })
- const secondDialog = await openDelete()
- expect(secondDialog).toHaveTextContent('dataset.datasetUsedByApp')
- expect(api.checkUsage).toHaveBeenCalledTimes(2)
- expect(api.checkUsage).toHaveBeenLastCalledWith({ params: { dataset_id: 'dataset-1' } })
- await user.click(within(secondDialog).getByRole('button', { name: 'common.operation.confirm' }))
- await waitFor(() =>
- expect(api.deleteDataset).toHaveBeenCalledExactlyOnceWith({
- params: { dataset_id: 'dataset-1' },
- }),
- )
- await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
- expect(onSuccess).toHaveBeenCalledOnce()
-})
diff --git a/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.browser.spec.tsx b/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.browser.spec.tsx
index 44e9d59b7a2..f923fc72d9b 100644
--- a/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.browser.spec.tsx
+++ b/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.browser.spec.tsx
@@ -69,7 +69,7 @@ it('keeps operations visible on keyboard focus without covering the unavailable
<QueryClientProvider client={queryClient}>
<button type="button">Before dataset</button>
<div className="mt-10 w-80">
- <DatasetCard dataset={dataset} />
+ <DatasetCard onDelete={vi.fn()} dataset={dataset} />
</div>
<button type="button">After dataset</button>
</QueryClientProvider>,
@@ -139,7 +139,7 @@ it.each([true, false])(
dataset={dataset}
openRenameModal={openRenameModal}
handleExportPipeline={vi.fn()}
- detectIsUsedByApp={vi.fn()}
+ onDelete={vi.fn()}
openAccessConfig={vi.fn()}
/>
</div>
diff --git a/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.spec.tsx b/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.spec.tsx
index 33605266bd0..8dbb6870f8f 100644
--- a/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.spec.tsx
+++ b/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.spec.tsx
@@ -59,7 +59,7 @@ describe('OperationsDropdown', () => {
dataset: createMockDataset(),
openRenameModal: vi.fn(),
handleExportPipeline: vi.fn(),
- detectIsUsedByApp: vi.fn(),
+ onDelete: vi.fn(),
openAccessConfig: vi.fn(),
}
@@ -248,12 +248,12 @@ describe('OperationsDropdown', () => {
})
it('should keep tour-opened operations menu items from running actions', async () => {
- const detectIsUsedByApp = vi.fn()
+ const onDelete = vi.fn()
render(
<OperationsDropdown
{...defaultProps}
- detectIsUsedByApp={detectIsUsedByApp}
+ onDelete={onDelete}
stepByStepTourHighlightPart="knowledge-card-actions-menu"
stepByStepTourOpen
/>,
@@ -263,7 +263,7 @@ describe('OperationsDropdown', () => {
await screen.findByRole('menuitem', { name: 'common.operation.delete', hidden: true }),
)
- expect(detectIsUsedByApp).not.toHaveBeenCalled()
+ expect(onDelete).not.toHaveBeenCalled()
expect(screen.getByRole('menu', { hidden: true })).toBeInTheDocument()
})
})
diff --git a/web/app/components/datasets/list/dataset-card/components/dataset-card-modals.tsx b/web/app/components/datasets/list/dataset-card/components/dataset-card-modals.tsx
deleted file mode 100644
index 58895120809..00000000000
--- a/web/app/components/datasets/list/dataset-card/components/dataset-card-modals.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import type { DatasetCardItem } from '../types'
-import {
- AlertDialog,
- AlertDialogCancelButton,
- AlertDialogConfirmButton,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from '@langgenius/dify-ui/alert-dialog'
-import * as React from 'react'
-import { useTranslation } from 'react-i18next'
-import RenameDatasetModal from '../../../rename-modal'
-
-type ModalState = {
- showRenameModal: boolean
- showConfirmDelete: boolean
- showAccessConfig: boolean
- confirmMessage: string
-}
-
-type DatasetCardModalsProps = {
- dataset: DatasetCardItem
- modalState: ModalState
- onCloseRename: () => void
- onCloseConfirm: () => void
- onCloseAccessConfig: () => void
- onConfirmDelete: () => void
- onSuccess?: () => void
-}
-
-const DatasetCardModals = ({
- dataset,
- modalState,
- onCloseRename,
- onCloseConfirm,
- onConfirmDelete,
- onSuccess,
-}: DatasetCardModalsProps) => {
- const { t } = useTranslation(['common', 'dataset'])
-
- return (
- <>
- {modalState.showRenameModal && (
- <RenameDatasetModal
- show={modalState.showRenameModal}
- dataset={dataset}
- onClose={onCloseRename}
- onSuccess={onSuccess}
- />
- )}
- <AlertDialog
- open={modalState.showConfirmDelete}
- onOpenChange={(open) => !open && onCloseConfirm()}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.deleteDatasetConfirmTitle, { ns: 'dataset' })}
- </AlertDialogTitle>
- <AlertDialogDescription>{modalState.confirmMessage}</AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton onClick={onConfirmDelete}>
- {t(($) => $['operation.confirm'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </>
- )
-}
-
-export default React.memo(DatasetCardModals)
diff --git a/web/app/components/datasets/list/dataset-card/components/operations-dropdown.tsx b/web/app/components/datasets/list/dataset-card/components/operations-dropdown.tsx
index 7fd63dc1a4a..2e3296be337 100644
--- a/web/app/components/datasets/list/dataset-card/components/operations-dropdown.tsx
+++ b/web/app/components/datasets/list/dataset-card/components/operations-dropdown.tsx
@@ -25,7 +25,7 @@ type OperationsDropdownProps = {
dataset: DatasetCardItem
openRenameModal: () => void
handleExportPipeline: (include?: boolean) => void
- detectIsUsedByApp: () => void
+ onDelete: () => void
openAccessConfig: () => void
stepByStepTourHighlightPart?: string
stepByStepTourOpen?: boolean
@@ -35,7 +35,7 @@ const OperationsDropdown = ({
dataset,
openRenameModal,
handleExportPipeline,
- detectIsUsedByApp,
+ onDelete,
openAccessConfig,
stepByStepTourHighlightPart,
stepByStepTourOpen,
@@ -150,7 +150,7 @@ const OperationsDropdown = ({
{datasetACLCapabilities.canDelete && (
<>
<DropdownMenuSeparator />
- <DropdownMenuItem className="gap-2" variant="destructive" onClick={detectIsUsedByApp}>
+ <DropdownMenuItem className="gap-2" variant="destructive" onClick={onDelete}>
<span aria-hidden className="i-ri-delete-bin-line size-4" />
{t(($) => $['operation.delete'], { ns: 'common' })}
</DropdownMenuItem>
diff --git a/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-actions.ts b/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-actions.ts
new file mode 100644
index 00000000000..ddaf5d1402b
--- /dev/null
+++ b/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-actions.ts
@@ -0,0 +1,46 @@
+import type { DatasetCardItem } from '../types'
+import { useMutation } from '@tanstack/react-query'
+import { useCallback } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from '@/app/notifications'
+import { useRouter } from '@/next/navigation'
+import { consoleQuery } from '@/service/console'
+import { downloadBlob } from '@/utils/download'
+
+type UseDatasetCardActionsOptions = {
+ dataset: DatasetCardItem
+}
+
+export const useDatasetCardActions = ({ dataset }: UseDatasetCardActionsOptions) => {
+ const { t } = useTranslation(['app'])
+ const { push } = useRouter()
+
+ const openAccessConfig = useCallback(() => {
+ push(`/datasets/${dataset.id}/access-config`)
+ }, [dataset.id, push])
+
+ const { mutateAsync: exportPipelineConfig, isPending: exporting } = useMutation(
+ consoleQuery.rag.pipelines.byPipelineId.exports.get.mutationOptions(),
+ )
+
+ const handleExportPipeline = useCallback(
+ async (include: boolean = false) => {
+ const { pipeline_id, name } = dataset
+ if (!pipeline_id || exporting) return
+
+ try {
+ const { data } = await exportPipelineConfig({
+ params: { pipeline_id },
+ query: { include_secret: String(include) },
+ })
+ const file = new Blob([data], { type: 'application/yaml' })
+ downloadBlob({ data: file, fileName: `${name}.pipeline` })
+ } catch {
+ toast.error(t(($) => $.exportFailed, { ns: 'app' }))
+ }
+ },
+ [dataset, exportPipelineConfig, exporting, t],
+ )
+
+ return { openAccessConfig, handleExportPipeline }
+}
diff --git a/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts b/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts
deleted file mode 100644
index 32498feb0a8..00000000000
--- a/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import type { DatasetCardItem } from '../types'
-import { useMutation, useQueryClient } from '@tanstack/react-query'
-import { useCallback, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { toast } from '@/app/notifications'
-import { useRouter } from '@/next/navigation'
-import { consoleQuery } from '@/service/console'
-import { downloadBlob } from '@/utils/download'
-
-type ModalState = {
- showRenameModal: boolean
- showConfirmDelete: boolean
- showAccessConfig: boolean
- confirmMessage: string
-}
-
-type UseDatasetCardStateOptions = {
- dataset: DatasetCardItem
- onSuccess?: () => void
-}
-
-export const useDatasetCardState = ({ dataset, onSuccess }: UseDatasetCardStateOptions) => {
- const { t } = useTranslation(['app', 'dataset'])
- const { push } = useRouter()
- const queryClient = useQueryClient()
-
- // Modal state
- const [modalState, setModalState] = useState<ModalState>({
- showRenameModal: false,
- showConfirmDelete: false,
- showAccessConfig: false,
- confirmMessage: '',
- })
-
- // Export state
- const [exporting, setExporting] = useState(false)
-
- // Modal handlers
- const openRenameModal = useCallback(() => {
- setModalState((prev) => ({ ...prev, showRenameModal: true }))
- }, [])
-
- const closeRenameModal = useCallback(() => {
- setModalState((prev) => ({ ...prev, showRenameModal: false }))
- }, [])
-
- const closeConfirmDelete = useCallback(() => {
- setModalState((prev) => ({ ...prev, showConfirmDelete: false }))
- }, [])
-
- const openAccessConfig = useCallback(() => {
- push(`/datasets/${dataset.id}/access-config`)
- }, [dataset.id, push])
-
- const closeAccessConfig = useCallback(() => {
- setModalState((prev) => ({ ...prev, showAccessConfig: false }))
- }, [])
-
- // API mutations
- const { mutateAsync: deleteDatasetMutation } = useMutation(
- consoleQuery.datasets.byDatasetId.delete.mutationOptions(),
- )
- const { mutateAsync: exportPipelineConfig } = useMutation(
- consoleQuery.rag.pipelines.byPipelineId.exports.get.mutationOptions(),
- )
-
- // Export pipeline handler
- const handleExportPipeline = useCallback(
- async (include: boolean = false) => {
- const { pipeline_id, name } = dataset
- if (!pipeline_id || exporting) return
-
- try {
- setExporting(true)
- const { data } = await exportPipelineConfig({
- params: { pipeline_id },
- query: { include_secret: String(include) },
- })
- const file = new Blob([data], { type: 'application/yaml' })
- downloadBlob({ data: file, fileName: `${name}.pipeline` })
- } catch {
- toast.error(t(($) => $.exportFailed, { ns: 'app' }))
- } finally {
- setExporting(false)
- }
- },
- [dataset, exportPipelineConfig, exporting, t],
- )
-
- // Delete flow handlers
- const detectIsUsedByApp = useCallback(async () => {
- try {
- const { is_using: isUsedByApp } = await queryClient.query(
- consoleQuery.datasets.byDatasetId.useCheck.get.queryOptions({
- input: {
- params: {
- dataset_id: dataset.id,
- },
- },
- staleTime: 0,
- retry: false,
- context: { silent: true },
- }),
- )
- const message = isUsedByApp
- ? t(($) => $.datasetUsedByApp, { ns: 'dataset' })!
- : t(($) => $.deleteDatasetConfirmContent, { ns: 'dataset' })!
- setModalState((prev) => ({
- ...prev,
- confirmMessage: message,
- showConfirmDelete: true,
- }))
- } catch (e: unknown) {
- toast.error(
- (e instanceof Error ? e.message : '') || t(($) => $.unknownError, { ns: 'dataset' }),
- )
- }
- }, [dataset.id, queryClient, t])
-
- const onConfirmDelete = useCallback(async () => {
- try {
- await deleteDatasetMutation({
- params: {
- dataset_id: dataset.id,
- },
- })
- onSuccess?.()
- } finally {
- closeConfirmDelete()
- }
- }, [dataset.id, deleteDatasetMutation, onSuccess, closeConfirmDelete])
-
- return {
- // Modal state
- modalState,
- openRenameModal,
- closeRenameModal,
- closeConfirmDelete,
- openAccessConfig,
- closeAccessConfig,
-
- // Export state
- exporting,
-
- // Handlers
- handleExportPipeline,
- detectIsUsedByApp,
- onConfirmDelete,
- }
-}
diff --git a/web/app/components/datasets/list/dataset-card/index.tsx b/web/app/components/datasets/list/dataset-card/index.tsx
index 1e9ac8dd075..1f24e609c44 100644
--- a/web/app/components/datasets/list/dataset-card/index.tsx
+++ b/web/app/components/datasets/list/dataset-card/index.tsx
@@ -4,7 +4,7 @@ import type { DatasetCardItem } from './types'
import { cn } from '@langgenius/dify-ui/cn'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { useId, useMemo } from 'react'
+import { useId, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
@@ -16,19 +16,20 @@ import {
hasOnlyDatasetPreviewPermission,
hasPermission,
} from '@/utils/permission'
+import RenameDatasetModal from '../../rename-modal'
import CornerLabels from './components/corner-labels'
import DatasetCardFooter from './components/dataset-card-footer'
import DatasetCardHeader from './components/dataset-card-header'
-import DatasetCardModals from './components/dataset-card-modals'
import Description from './components/description'
import OperationsDropdown from './components/operations-dropdown'
-import { useDatasetCardState as useDatasetCardController } from './hooks/use-dataset-card-state'
+import { useDatasetCardActions } from './hooks/use-dataset-card-actions'
const EXTERNAL_PROVIDER = 'external'
type DatasetCardProps = {
dataset: DatasetCardItem
onSuccess?: () => void
+ onDelete: (item: HTMLLIElement | null) => void
onOpenTagManagement?: () => void
stepByStepTourActionMenuHighlightPart?: string
stepByStepTourActionMenuOpen?: boolean
@@ -38,11 +39,13 @@ type DatasetCardProps = {
const DatasetCard = ({
dataset,
onSuccess,
+ onDelete,
onOpenTagManagement = () => {},
stepByStepTourActionMenuHighlightPart,
stepByStepTourActionMenuOpen,
stepByStepTourCardTarget,
}: DatasetCardProps) => {
+ const itemRef = useRef<HTMLLIElement>(null)
const { t } = useTranslation(['app'])
const nameId = useId()
const { data: currentUserId } = useSuspenseQuery({
@@ -51,18 +54,8 @@ const DatasetCard = ({
})
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
- const datasetCard = useDatasetCardController({ dataset, onSuccess })
- const {
- modalState,
- openRenameModal,
- closeRenameModal,
- closeConfirmDelete,
- openAccessConfig,
- closeAccessConfig,
- handleExportPipeline,
- detectIsUsedByApp,
- onConfirmDelete,
- } = datasetCard
+ const [renameOpen, setRenameOpen] = useState(false)
+ const { openAccessConfig, handleExportPipeline } = useDatasetCardActions({ dataset })
const isExternalProvider = dataset.provider === EXTERNAL_PROVIDER
const isPipelineUnpublished = useMemo(() => {
@@ -106,6 +99,7 @@ const DatasetCard = ({
return (
<li
+ ref={itemRef}
className={cn(
"group relative isolate col-span-1 flex min-h-41.5 min-w-0 flex-col overflow-hidden rounded-xl border-[0.5px] border-solid border-components-card-border bg-components-card-bg shadow-xs shadow-shadow-shadow-3 transition-[background-color,box-shadow] duration-200 ease-in-out after:pointer-events-none after:absolute after:inset-0 after:z-1 after:rounded-xl after:content-[''] focus-within:bg-components-card-bg-alt focus-within:[--color-tag-selector-mask-bg:var(--color-tag-selector-mask-hover-bg)] has-[>[data-dataset-card-entry]:focus-visible]:after:inset-ring-2 has-[>[data-dataset-card-entry]:focus-visible]:after:inset-ring-state-accent-solid motion-reduce:transition-none",
isPreviewOnly
@@ -148,21 +142,18 @@ const DatasetCard = ({
{!isPreviewOnly && (
<OperationsDropdown
dataset={dataset}
- openRenameModal={openRenameModal}
+ openRenameModal={() => setRenameOpen(true)}
handleExportPipeline={handleExportPipeline}
- detectIsUsedByApp={detectIsUsedByApp}
+ onDelete={() => onDelete(itemRef.current)}
openAccessConfig={openAccessConfig}
stepByStepTourHighlightPart={stepByStepTourActionMenuHighlightPart}
stepByStepTourOpen={stepByStepTourActionMenuOpen}
/>
)}
- <DatasetCardModals
+ <RenameDatasetModal
dataset={dataset}
- modalState={modalState}
- onCloseRename={closeRenameModal}
- onCloseConfirm={closeConfirmDelete}
- onCloseAccessConfig={closeAccessConfig}
- onConfirmDelete={onConfirmDelete}
+ open={renameOpen}
+ onOpenChange={setRenameOpen}
onSuccess={onSuccess}
/>
</li>
diff --git a/web/app/components/datasets/list/datasets.tsx b/web/app/components/datasets/list/datasets.tsx
index 15605fd1e72..d1b23ac6ee9 100644
--- a/web/app/components/datasets/list/datasets.tsx
+++ b/web/app/components/datasets/list/datasets.tsx
@@ -3,9 +3,18 @@
import type { DatasetListResponse } from '@dify/contracts/api/console/datasets/types.gen'
import type { InfiniteData, UseInfiniteQueryResult } from '@tanstack/react-query'
import type { ReactNode } from 'react'
-import { useEffect, useRef } from 'react'
+import {
+ AlertDialog,
+ AlertDialogContent,
+ createAlertDialogHandle,
+} from '@langgenius/dify-ui/alert-dialog'
+import { useMutation } from '@tanstack/react-query'
+import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
+import { consoleQuery } from '@/service/console'
+import { getAdjacentFocusTargets } from '@/utils/get-adjacent-focus-targets'
+import { DeleteDatasetConfirmation } from '../delete-dataset-confirmation'
import DatasetCard from './dataset-card'
import DatasetCardSkeleton from './dataset-card-skeleton'
import { useInvalidDatasetList } from './use-dataset-list'
@@ -45,6 +54,17 @@ const Datasets = ({
stepByStepTourCardTarget,
}: Props) => {
const { t } = useTranslation(['common', 'dataset'])
+ const listRef = useRef<HTMLDivElement>(null)
+ const [deleteDialog] = useState(() =>
+ createAlertDialogHandle<{
+ id: string
+ adjacentFocusTargets: HTMLElement[]
+ fallbackFocus: { current: HTMLElement | null }
+ }>(),
+ )
+ const deletion = useMutation(
+ consoleQuery.datasets.byDatasetId.delete.mutationOptions({ context: { silent: true } }),
+ )
const invalidDatasetList = useInvalidDatasetList()
const anchorRef = useRef<HTMLDivElement>(null)
const observerRef = useRef<IntersectionObserver>(null)
@@ -74,7 +94,14 @@ const Datasets = ({
!!datasetList?.pages.some(({ data }) => data.length > 0)
return (
- <div aria-busy={isFetching} className="relative grow px-8 pt-2">
+ <div
+ ref={listRef}
+ tabIndex={-1}
+ role="region"
+ aria-label={t(($) => $.knowledge, { ns: 'dataset' })}
+ aria-busy={isFetching}
+ className="relative grow px-8 pt-2 focus-visible:outline-2 focus-visible:outline-state-accent-solid"
+ >
{showDatasetSkeleton ? (
<div role="status" aria-label={t(($) => $.loading, { ns: 'common' })}>
<ul aria-hidden className={DATASET_GRID_CLASS_NAME}>
@@ -94,6 +121,15 @@ const Datasets = ({
<DatasetCard
key={dataset.id}
dataset={dataset}
+ onDelete={(item) =>
+ deleteDialog.openWithPayload({
+ id: dataset.id,
+ adjacentFocusTargets: getAdjacentFocusTargets(item, (sibling) =>
+ sibling.querySelector<HTMLElement>(':scope > a[href], :scope > button'),
+ ),
+ fallbackFocus: { current: null },
+ })
+ }
onSuccess={invalidDatasetList}
onOpenTagManagement={onOpenTagManagement}
stepByStepTourActionMenuHighlightPart={
@@ -112,6 +148,51 @@ const Datasets = ({
)}
{!showDatasetSkeleton && !hasAnyDataset && emptyElement}
{isFetchingNextPage && <LoadingPlaceholder />}
+ <AlertDialog
+ handle={deleteDialog}
+ onOpenChange={(open, details) => {
+ if (!open && deletion.isPending && details.reason !== 'imperative-action')
+ details.cancel()
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) deletion.reset()
+ }}
+ >
+ {({ payload }) => (
+ <AlertDialogContent
+ finalFocus={() => {
+ const fallback = payload?.fallbackFocus.current
+ if (!fallback) return true
+ const target =
+ payload.adjacentFocusTargets.find((element) => element.isConnected) ?? fallback
+ target.focus({ preventScroll: true })
+ return false
+ }}
+ >
+ {payload && (
+ <DeleteDatasetConfirmation
+ datasetId={payload.id}
+ isPending={deletion.isPending}
+ error={
+ deletion.isError ? t(($) => $['api.actionFailed'], { ns: 'common' }) : undefined
+ }
+ onConfirm={() => {
+ if (deletion.isPending) return
+ deletion.mutate(
+ { params: { dataset_id: payload.id } },
+ {
+ onSuccess: () => {
+ payload.fallbackFocus.current = listRef.current
+ deleteDialog.close()
+ },
+ },
+ )
+ }}
+ />
+ )}
+ </AlertDialogContent>
+ )}
+ </AlertDialog>
<div ref={anchorRef} className="h-0" />
</div>
)
diff --git a/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx b/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx
index e618d2eebbb..240f3ee6a90 100644
--- a/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx
@@ -105,10 +105,10 @@ describe('RenameDatasetModal', () => {
})
const defaultProps = {
- show: true,
+ open: true,
dataset: createMockDataset(),
onSuccess: vi.fn(),
- onClose: vi.fn(),
+ onOpenChange: vi.fn(),
}
beforeEach(() => {
@@ -116,18 +116,11 @@ describe('RenameDatasetModal', () => {
mockUpdateDatasetSetting.mockResolvedValue(createMockDataset())
})
- describe('Rendering', () => {
- it('should render a named dialog when show is true', () => {
- render(<RenameDatasetModal {...defaultProps} show={true} />)
- expect(screen.getByRole('dialog', { name: 'datasetSettings.title' })).toBeInTheDocument()
- })
- })
-
describe('User Interactions', () => {
- it('should call onClose when cancel button is clicked', async () => {
+ it('should call onOpenChange when cancel button is clicked', async () => {
const user = userEvent.setup()
const handleClose = vi.fn()
- render(<RenameDatasetModal {...defaultProps} onClose={handleClose} />)
+ render(<RenameDatasetModal {...defaultProps} onOpenChange={handleClose} />)
const cancelButton = screen.getByText('common.operation.cancel')
await user.click(cancelButton)
@@ -135,20 +128,20 @@ describe('RenameDatasetModal', () => {
expect(handleClose).toHaveBeenCalledTimes(1)
})
- it('should call onClose when close icon is clicked', async () => {
+ it('should call onOpenChange when close icon is clicked', async () => {
const user = userEvent.setup()
const handleClose = vi.fn()
- render(<RenameDatasetModal {...defaultProps} onClose={handleClose} />)
+ render(<RenameDatasetModal {...defaultProps} onOpenChange={handleClose} />)
await user.click(screen.getByRole('button', { name: /operation\.close$/ }))
expect(handleClose).toHaveBeenCalledTimes(1)
})
- it('should call onClose when Escape is pressed', async () => {
+ it('should call onOpenChange when Escape is pressed', async () => {
const user = userEvent.setup()
const handleClose = vi.fn()
- render(<RenameDatasetModal {...defaultProps} onClose={handleClose} />)
+ render(<RenameDatasetModal {...defaultProps} onOpenChange={handleClose} />)
await user.keyboard('{Escape}')
@@ -206,7 +199,7 @@ describe('RenameDatasetModal', () => {
})
})
expect(defaultProps.onSuccess).toHaveBeenCalledOnce()
- expect(defaultProps.onClose).toHaveBeenCalledOnce()
+ expect(defaultProps.onOpenChange).toHaveBeenCalledOnce()
})
it('should include external knowledge IDs when present', async () => {
@@ -307,7 +300,7 @@ describe('RenameDatasetModal', () => {
await waitFor(() => {
expect(mockToast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')
})
- expect(defaultProps.onClose).not.toHaveBeenCalled()
+ expect(defaultProps.onOpenChange).not.toHaveBeenCalled()
expect(defaultProps.onSuccess).not.toHaveBeenCalled()
expect(screen.getByRole('dialog', { name: 'datasetSettings.title' })).toBeInTheDocument()
await user.click(saveButton)
@@ -472,17 +465,4 @@ describe('RenameDatasetModal', () => {
})
})
})
-
- describe('Component Re-rendering', () => {
- it('should handle show prop toggle', () => {
- const { rerender } = render(<RenameDatasetModal {...defaultProps} show={true} />)
-
- expect(screen.getByText('datasetSettings.title'))!.toBeInTheDocument()
-
- rerender(<RenameDatasetModal {...defaultProps} show={false} />)
-
- // Modal visibility is controlled by Modal component's isShow prop
- // The modal content may still be in DOM but hidden
- })
- })
})
diff --git a/web/app/components/datasets/rename-modal/index.tsx b/web/app/components/datasets/rename-modal/index.tsx
index 09781bc985c..c2507d5774f 100644
--- a/web/app/components/datasets/rename-modal/index.tsx
+++ b/web/app/components/datasets/rename-modal/index.tsx
@@ -26,7 +26,7 @@ import { toast } from '@/app/notifications'
import { updateDatasetSetting } from '@/service/datasets'
type RenameDatasetModalProps = {
- show: boolean
+ open: boolean
dataset: {
description?: string | null
external_knowledge_info?: {
@@ -43,9 +43,30 @@ type RenameDatasetModalProps = {
name: string
}
onSuccess?: () => void
- onClose: () => void
+ onOpenChange: (open: boolean) => void
}
-const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDatasetModalProps) => {
+const RenameDatasetModal = ({
+ open,
+ onOpenChange,
+ dataset,
+ onSuccess,
+}: RenameDatasetModalProps) => (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="w-130">
+ <RenameDatasetForm
+ dataset={dataset}
+ onSuccess={onSuccess}
+ onClose={() => onOpenChange(false)}
+ />
+ </DialogContent>
+ </Dialog>
+)
+
+function RenameDatasetForm({
+ dataset,
+ onSuccess,
+ onClose,
+}: Pick<RenameDatasetModalProps, 'dataset' | 'onSuccess'> & { onClose: () => void }) {
const { t } = useTranslation(['common', 'datasetSettings'])
const [loading, setLoading] = useState(false)
const [name, setName] = useState<string>(dataset.name)
@@ -112,80 +133,67 @@ const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDataset
t,
])
return (
- <Dialog
- open={show}
- onOpenChange={(open) => {
- if (!open) onClose()
+ <form
+ className="contents"
+ onSubmit={(event) => {
+ event.preventDefault()
+ onConfirm()
}}
>
- <DialogContent className="w-130">
- <form
- className="contents"
- onSubmit={(event) => {
- event.preventDefault()
- onConfirm()
- }}
- >
- <DialogHeader>
- <DialogTitle>{t(($) => $.title, { ns: 'datasetSettings' })}</DialogTitle>
- <DialogHeaderCloseButton
- aria-label={t(($) => $['operation.close'], { ns: 'common' })}
- />
- </DialogHeader>
- <DialogBody>
- <IconPicker value={appIcon} onValueChange={handleSelectAppIcon}>
- <Field name="name" className="gap-0 py-4">
- <FieldLabel className="w-full shrink-0 py-2 text-sm leading-5 font-medium text-text-primary">
- {t(($) => $['form.name'], { ns: 'datasetSettings' })}
- </FieldLabel>
- <div className="flex items-center gap-x-2">
- <IconPickerTrigger
- aria-label={`${t(($) => $['operation.edit'], { ns: 'common' })} ${t(($) => $['form.nameAndIcon'], { ns: 'datasetSettings' })}`}
- className="group/edit-icon relative shrink-0 cursor-pointer rounded-[10px] border-0 bg-transparent p-0"
- >
- <IconPickerIcon size="medium" />
- <span
- aria-hidden="true"
- className="pointer-events-none absolute inset-0 hidden items-center justify-center rounded-[inherit] bg-background-overlay-alt group-hover/edit-icon:flex group-focus-visible/edit-icon:flex"
- >
- <span className="i-ri-edit-line size-5.5 text-text-primary-on-surface" />
- </span>
- </IconPickerTrigger>
- <Input
- value={name}
- onChange={(e) => setName(e.target.value)}
- className="h-9 grow"
- placeholder={
- t(($) => $['form.namePlaceholder'], { ns: 'datasetSettings' }) || ''
- }
- />
- </div>
- </Field>
- <IconPickerContent />
- </IconPicker>
- <Field name="description" className="gap-0 py-4">
- <FieldLabel className="w-full shrink-0 py-2 text-sm leading-5 font-medium text-text-primary">
- {t(($) => $['form.desc'], { ns: 'datasetSettings' })}
- </FieldLabel>
- <Textarea
- value={description}
- onValueChange={(value) => setDescription(value)}
- className="resize-none"
- placeholder={t(($) => $['form.descPlaceholder'], { ns: 'datasetSettings' }) || ''}
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.title, { ns: 'datasetSettings' })}</DialogTitle>
+ <DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
+ </DialogHeader>
+ <DialogBody>
+ <IconPicker value={appIcon} onValueChange={handleSelectAppIcon}>
+ <Field name="name" className="gap-0 py-4">
+ <FieldLabel className="w-full shrink-0 py-2 text-sm leading-5 font-medium text-text-primary">
+ {t(($) => $['form.name'], { ns: 'datasetSettings' })}
+ </FieldLabel>
+ <div className="flex items-center gap-x-2">
+ <IconPickerTrigger
+ aria-label={`${t(($) => $['operation.edit'], { ns: 'common' })} ${t(($) => $['form.nameAndIcon'], { ns: 'datasetSettings' })}`}
+ className="group/edit-icon relative shrink-0 cursor-pointer rounded-[10px] border-0 bg-transparent p-0"
+ >
+ <IconPickerIcon size="medium" />
+ <span
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-0 hidden items-center justify-center rounded-[inherit] bg-background-overlay-alt group-hover/edit-icon:flex group-focus-visible/edit-icon:flex"
+ >
+ <span className="i-ri-edit-line size-5.5 text-text-primary-on-surface" />
+ </span>
+ </IconPickerTrigger>
+ <Input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ className="h-9 grow"
+ placeholder={t(($) => $['form.namePlaceholder'], { ns: 'datasetSettings' }) || ''}
/>
- </Field>
- </DialogBody>
- <DialogFooter>
- <Button type="button" onClick={onClose}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- <Button type="submit" loading={loading} variant="primary">
- {t(($) => $['operation.save'], { ns: 'common' })}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
+ </div>
+ </Field>
+ <IconPickerContent />
+ </IconPicker>
+ <Field name="description" className="gap-0 py-4">
+ <FieldLabel className="w-full shrink-0 py-2 text-sm leading-5 font-medium text-text-primary">
+ {t(($) => $['form.desc'], { ns: 'datasetSettings' })}
+ </FieldLabel>
+ <Textarea
+ value={description}
+ onValueChange={(value) => setDescription(value)}
+ className="resize-none"
+ placeholder={t(($) => $['form.descPlaceholder'], { ns: 'datasetSettings' }) || ''}
+ />
+ </Field>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" onClick={onClose}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </Button>
+ <Button type="submit" loading={loading} variant="primary">
+ {t(($) => $['operation.save'], { ns: 'common' })}
+ </Button>
+ </DialogFooter>
+ </form>
)
}
export default RenameDatasetModal
diff --git a/web/app/components/header/account-setting/members-page/__tests__/delete-member.browser.spec.tsx b/web/app/components/header/account-setting/members-page/__tests__/delete-member.browser.spec.tsx
new file mode 100644
index 00000000000..2535403cddd
--- /dev/null
+++ b/web/app/components/header/account-setting/members-page/__tests__/delete-member.browser.spec.tsx
@@ -0,0 +1,157 @@
+import type { AccountWithRoleResponse } from '@dify/contracts/api/console/workspaces/types.gen'
+import type { consoleClient } from '@/service/console'
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { QueryClientTestProvider } from '@/test/console/query-provider'
+import { createDeferred } from '@/test/deferred'
+import MembersPage from '../index'
+
+const api = vi.hoisted(() => ({
+ features: vi.fn<typeof consoleClient.features.get>(),
+ members: vi.fn<typeof consoleClient.workspaces.current.members.get>(),
+ remove: vi.fn<typeof consoleClient.workspaces.current.members.byMemberId.delete>(),
+}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.members.get': api.members,
+ 'features.get': api.features,
+ 'workspaces.current.members.byMemberId.delete': api.remove,
+ }),
+ }
+})
+const member = (id: string): AccountWithRoleResponse => ({
+ id,
+ name: id,
+ email: `${id}@example.com`,
+ avatar: '',
+ avatar_url: '',
+ role: 'normal',
+ roles: [],
+ last_active_at: 1731000000,
+ last_login_at: 1731000000,
+ created_at: 1731000000,
+ status: 'active',
+})
+beforeEach(() => {
+ vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false)
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input) => {
+ throw new Error(`Unexpected request: ${String(input)}`)
+ }),
+ )
+})
+afterEach(() => {
+ expect(
+ vi
+ .mocked(fetch)
+ .mock.calls.map(([input]) => (input instanceof Request ? input.url : String(input))),
+ ).toEqual([])
+ vi.unstubAllGlobals()
+})
+
+async function setup(ids: string[]) {
+ let accounts = ids.map(member)
+ api.members.mockReset().mockImplementation(async () => ({ accounts }))
+ api.remove.mockReset().mockImplementation(async ({ params }) => {
+ accounts = accounts.filter((item) => item.id !== params.member_id)
+ return { result: 'success', tenant_id: 'tenant-1' }
+ })
+ const { queryClient } = createConsoleQueryWrapper({
+ systemFeatures: { deployment_edition: 'COMMUNITY' },
+ workspacePermissionKeys: ['workspace.member.manage'],
+ })
+ api.features.mockResolvedValue(queryClient.getQueryData(consoleQuery.features.get.queryKey())!)
+ const screen = await render(
+ <QueryClientTestProvider queryClient={queryClient}>
+ <MembersPage />
+ </QueryClientTestProvider>,
+ )
+ const open = async (id: string) => {
+ await screen
+ .getByRole('button', { name: `workspaceMembers.members.memberActions: ${id}`, exact: true })
+ .click()
+ await screen.getByRole('menuitem', { name: /members\.removeFromTeam$/ }).click()
+ await expect.element(screen.getByRole('alertdialog')).toBeVisible()
+ await expect.element(screen.getByRole('menu')).not.toBeInTheDocument()
+ }
+ return { screen, open }
+}
+
+it('removes the member before a slow list refresh completes', async () => {
+ const { screen, open } = await setup(['Alpha', 'Beta'])
+ await open('Alpha')
+ const list = api.members.getMockImplementation()!
+ const refresh = createDeferred<Awaited<ReturnType<typeof list>>>()
+ api.members.mockReturnValueOnce(refresh.promise)
+ await screen.getByRole('button', { name: /operation\.confirm$/ }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('button', { name: 'Alpha', exact: true }))
+ .not.toBeInTheDocument()
+ await expect.element(screen.getByRole('button', { name: 'Beta', exact: true })).toHaveFocus()
+ refresh.resolve(await list())
+})
+
+it.each([
+ { ids: ['Alpha', 'Beta', 'Gamma'], remove: 'Beta', next: 'Gamma' },
+ { ids: ['Alpha', 'Beta'], remove: 'Beta', next: 'Alpha' },
+ { ids: ['Alpha'], remove: 'Alpha', next: null },
+])('returns focus after removing $remove from $ids', async ({ ids, remove, next }) => {
+ const { screen, open } = await setup(ids)
+ await open(remove)
+ await screen.getByRole('button', { name: /operation\.confirm$/ }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('button', { name: remove, exact: true }))
+ .not.toBeInTheDocument()
+ await expect
+ .element(
+ next ? screen.getByRole('button', { name: next, exact: true }) : screen.getByRole('region'),
+ )
+ .toHaveFocus()
+})
+
+it('keeps focus and blocks Escape/cancel during removal, then reports a retryable failure', async () => {
+ const { screen, open } = await setup(['Alpha'])
+ const request =
+ createDeferred<
+ Awaited<ReturnType<typeof consoleClient.workspaces.current.members.byMemberId.delete>>
+ >()
+ api.remove.mockReturnValueOnce(request.promise)
+ await open('Alpha')
+ const confirm = screen.getByRole('button', { name: /operation\.confirm$/ })
+ await confirm.click()
+ await expect.element(confirm).toHaveFocus()
+ await userEvent.keyboard('{Escape}')
+ await expect.element(screen.getByRole('button', { name: /operation\.cancel$/ })).toBeDisabled()
+ await expect.element(screen.getByRole('alertdialog')).toBeVisible()
+ expect(api.remove).toHaveBeenCalledTimes(1)
+ request.reject(new Error('Failed'))
+ await expect.element(screen.getByRole('alert')).toHaveTextContent('common.api.actionFailed')
+ await confirm.click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect.element(screen.getByRole('region')).toHaveFocus()
+})
+
+it('returns to the menu button when cancelled', async () => {
+ const { screen, open } = await setup(['Alpha'])
+ await open('Alpha')
+ await userEvent.keyboard('{Escape}')
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(
+ page.getByRole('button', {
+ name: 'workspaceMembers.members.memberActions: Alpha',
+ exact: true,
+ }),
+ )
+ .toHaveFocus()
+ expect(api.remove).not.toHaveBeenCalled()
+})
diff --git a/web/app/components/header/account-setting/members-page/__tests__/member-menu.spec.tsx b/web/app/components/header/account-setting/members-page/__tests__/member-menu.spec.tsx
index 4021242aa90..66379f9603f 100644
--- a/web/app/components/header/account-setting/members-page/__tests__/member-menu.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/__tests__/member-menu.spec.tsx
@@ -1,9 +1,7 @@
import type { AccountWithRoleResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { Role } from '@/models/access-control'
-import { QueryClient } from '@tanstack/react-query'
-import { act, screen, waitFor, within } from '@testing-library/react'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { consoleClient, consoleQuery } from '@/service/console'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import MemberMenu from '../member-menu'
@@ -17,7 +15,6 @@ vi.mock('@/service/console', async (importOriginal) => {
const { withConsoleResponses } = await import('@/test/console/service-responses')
return {
...actual,
- consoleClient: { workspaces: { current: { members: { byMemberId: { delete: vi.fn() } } } } },
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'workspaces.current.rbac.members.byMemberId.rbacRoles.put': mockUpdateRolesOfMember,
'workspaces.current.rbac.roles.get': mockWorkspaceRoleListHook,
@@ -58,26 +55,9 @@ const member: AccountWithRoleResponse = {
}
describe('MemberMenu', () => {
- const createQueryClient = () =>
- new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- staleTime: Infinity,
- },
- mutations: {
- retry: false,
- },
- },
- })
-
beforeEach(() => {
vi.clearAllMocks()
mockUpdateRolesOfMember.mockResolvedValue(undefined)
- vi.mocked(consoleClient.workspaces.current.members.byMemberId.delete).mockResolvedValue({
- result: 'success',
- tenant_id: 'tenant-1',
- })
mockWorkspaceRoleListHook.mockResolvedValue({
data: roles,
pagination: { total_count: 2, per_page: 20, current_page: 1, total_pages: 1 },
@@ -88,7 +68,12 @@ describe('MemberMenu', () => {
const user = userEvent.setup()
renderWithConsoleQuery(
- <MemberMenu member={member} isCurrentUser={false} allowMultipleRoles={false} />,
+ <MemberMenu
+ onRemove={vi.fn()}
+ member={member}
+ isCurrentUser={false}
+ allowMultipleRoles={false}
+ />,
{
systemFeatures: {
rbac_enabled: false,
@@ -117,7 +102,12 @@ describe('MemberMenu', () => {
}),
)
renderWithConsoleQuery(
- <MemberMenu member={member} isCurrentUser={false} allowMultipleRoles={false} />,
+ <MemberMenu
+ onRemove={vi.fn()}
+ member={member}
+ isCurrentUser={false}
+ allowMultipleRoles={false}
+ />,
)
await user.click(screen.getByRole('button', { name: /members\.memberActions/ }))
await user.click(screen.getByRole('menuitem', { name: /members\.editRole/ }))
@@ -156,7 +146,12 @@ describe('MemberMenu', () => {
}),
)
renderWithConsoleQuery(
- <MemberMenu member={member} isCurrentUser={false} allowMultipleRoles={false} />,
+ <MemberMenu
+ onRemove={vi.fn()}
+ member={member}
+ isCurrentUser={false}
+ allowMultipleRoles={false}
+ />,
)
const more = screen.getByRole('button', { name: /members\.memberActions/ })
await user.click(more)
@@ -187,7 +182,12 @@ describe('MemberMenu', () => {
const user = userEvent.setup()
mockUpdateRolesOfMember.mockRejectedValueOnce(new Error('Save failed'))
renderWithConsoleQuery(
- <MemberMenu member={member} isCurrentUser={false} allowMultipleRoles={false} />,
+ <MemberMenu
+ onRemove={vi.fn()}
+ member={member}
+ isCurrentUser={false}
+ allowMultipleRoles={false}
+ />,
)
const open = async () => {
await user.click(screen.getByRole('button', { name: /members\.memberActions/ }))
@@ -208,34 +208,13 @@ describe('MemberMenu', () => {
)
})
- it('should require confirmation before removing a member', async () => {
+ it('asks the list to confirm removal of this member', async () => {
+ const onRemove = vi.fn()
const user = userEvent.setup()
- const queryClient = createQueryClient()
- const { queryKey: membersQueryKey } = consoleQuery.workspaces.current.members.get.queryOptions({
- input: { query: { language: 'en' } },
- })
- queryClient.setQueryData(membersQueryKey, { accounts: [member] })
-
- renderWithConsoleQuery(<MemberMenu member={member} isCurrentUser={false} />, {
- queryClient,
- })
-
- await user.click(screen.getByRole('button', { name: /members\.memberActions/i }))
+ renderWithConsoleQuery(<MemberMenu member={member} isCurrentUser={false} onRemove={onRemove} />)
+ const trigger = screen.getByRole('button', { name: /members\.memberActions/i })
+ await user.click(trigger)
await user.click(screen.getByRole('menuitem', { name: /members\.removeFromTeam/i }))
-
- const dialog = screen.getByRole('alertdialog', {
- name: /workspaceMembers\.members\.removeFromTeamConfirmTitle:\{"memberName":"Member User"\}/i,
- })
- expect(dialog).toHaveTextContent('workspaceMembers.members.removeFromTeamConfirmDescription')
- expect(consoleClient.workspaces.current.members.byMemberId.delete).not.toHaveBeenCalled()
-
- await user.click(within(dialog).getByRole('button', { name: /common\.operation\.confirm/i }))
-
- await waitFor(() => {
- expect(consoleClient.workspaces.current.members.byMemberId.delete).toHaveBeenCalledWith({
- params: { member_id: 'member-1' },
- })
- })
- expect(queryClient.getQueryState(membersQueryKey)?.isInvalidated).toBe(true)
+ expect(onRemove).toHaveBeenCalledOnce()
})
})
diff --git a/web/app/components/header/account-setting/members-page/__tests__/member-row.spec.tsx b/web/app/components/header/account-setting/members-page/__tests__/member-row.spec.tsx
index 50efabc92a3..f674f968f3a 100644
--- a/web/app/components/header/account-setting/members-page/__tests__/member-row.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/__tests__/member-row.spec.tsx
@@ -19,7 +19,7 @@ const member: AccountWithRoleResponse = {
status: 'active',
}
-const renderMemberRow = () => {
+const renderMemberRow = (onRemove = vi.fn()) => {
renderWithConsoleQuery(
<Dialog<AccountWithRoleResponse>>
{({ payload }) => (
@@ -27,6 +27,7 @@ const renderMemberRow = () => {
<table>
<tbody>
<MemberRow
+ onRemove={onRemove}
member={member}
roles={[{ id: 'role-1', name: 'Editor' }]}
isCurrentUser={false}
@@ -82,24 +83,16 @@ describe('MemberRow details entry points', () => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
- it('keeps member menu and its portaled confirmation separate from details', async () => {
+ it('requests removal without opening member details', async () => {
const user = userEvent.setup()
- renderMemberRow()
- await user.click(
- screen.getByRole('button', { name: /workspaceMembers\.members\.memberActions/ }),
- )
- expect(screen.getByRole('menu')).toBeInTheDocument()
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ const onRemove = vi.fn()
+ renderMemberRow(onRemove)
+ const trigger = screen.getByRole('button', { name: /workspaceMembers\.members\.memberActions/ })
+ await user.click(trigger)
await user.click(
screen.getByRole('menuitem', { name: 'workspaceMembers.members.removeFromTeam' }),
)
- const confirmation = screen.getByRole('alertdialog')
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
- await user.click(
- within(confirmation).getByText('workspaceMembers.members.removeFromTeamConfirmDescription'),
- )
- await user.click(within(confirmation).getByRole('button', { name: 'common.operation.cancel' }))
- expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+ expect(onRemove).toHaveBeenCalledExactlyOnceWith(screen.getByRole('row'))
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/header/account-setting/members-page/index.tsx b/web/app/components/header/account-setting/members-page/index.tsx
index 4d898fa8eec..53129478906 100644
--- a/web/app/components/header/account-setting/members-page/index.tsx
+++ b/web/app/components/header/account-setting/members-page/index.tsx
@@ -4,6 +4,17 @@ import type {
MemberInviteResponse,
} from '@dify/contracts/api/console/workspaces/types.gen'
import type { Role } from '@/models/access-control'
+import {
+ AlertDialog,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ createAlertDialogHandle,
+} from '@langgenius/dify-ui/alert-dialog'
import {
createDialogHandle,
Dialog,
@@ -25,6 +36,7 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { getAccessControlTemplateLanguage, LanguagesSupported } from '@/i18n/language'
import { consoleQuery } from '@/service/console'
+import { getAdjacentFocusTargets } from '@/utils/get-adjacent-focus-targets'
import { hasPermission } from '@/utils/permission'
import EditWorkspaceContent from './edit-workspace-content'
import InvitationResultsContent from './invitation-results-content'
@@ -39,6 +51,7 @@ const MembersPage = () => {
'workspaceMembers',
'accountSettings',
'permission',
+ 'navigation',
])
const locale = useLocale()
const language = getAccessControlTemplateLanguage(locale)
@@ -58,6 +71,19 @@ const MembersPage = () => {
createDialogHandle<MemberInviteResponse['invitation_results']>(),
)
const workspaceNameInputRef = useRef<HTMLInputElement>(null)
+ const listRef = useRef<HTMLDivElement>(null)
+ const [removeDialog] = useState(() =>
+ createAlertDialogHandle<{
+ member: AccountWithRoleResponse
+ adjacentFocusTargets: HTMLElement[]
+ fallbackFocus: { current: HTMLElement | null }
+ }>(),
+ )
+ const removal = useMutation(
+ consoleQuery.workspaces.current.members.byMemberId.delete.mutationOptions({
+ context: { silent: true },
+ }),
+ )
const accounts = data?.accounts || []
const deploymentEdition = systemFeatures.deployment_edition
const { data: features } = useQuery(
@@ -194,7 +220,13 @@ const MembersPage = () => {
)}
</div>
</div>
- <div className="overflow-x-auto">
+ <div
+ ref={listRef}
+ tabIndex={-1}
+ role="region"
+ aria-label={t(($) => $['settings.members'], { ns: 'navigation' })}
+ className="overflow-x-auto focus-visible:outline-2 focus-visible:outline-state-accent-solid"
+ >
<table className="w-full min-w-150 table-fixed text-start">
<colgroup>
<col className="w-65" />
@@ -221,6 +253,18 @@ const MembersPage = () => {
<MemberRow
key={account.id}
member={account}
+ onRemove={(row) => {
+ const adjacentFocusTargets = getAdjacentFocusTargets(row, (sibling) =>
+ sibling.querySelector<HTMLButtonElement>(
+ 'button[aria-haspopup="dialog"]',
+ ),
+ )
+ removeDialog.openWithPayload({
+ member: account,
+ adjacentFocusTargets,
+ fallbackFocus: { current: null },
+ })
+ }}
roles={account.roles ?? []}
isCurrentUser={userProfileEmail === account.email}
canManage={canManageMembers}
@@ -234,6 +278,71 @@ const MembersPage = () => {
</table>
</div>
</div>
+ <AlertDialog
+ handle={removeDialog}
+ onOpenChange={(open, details) => {
+ if (!open && removal.isPending && details.reason !== 'imperative-action')
+ details.cancel()
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) removal.reset()
+ }}
+ >
+ {({ payload }) => (
+ <AlertDialogContent
+ backdropProps={{ forceRender: true }}
+ finalFocus={() => {
+ const fallback = payload?.fallbackFocus.current
+ if (!fallback) return true
+ const target =
+ payload.adjacentFocusTargets.find((element) => element.isConnected) ?? fallback
+ target.focus({ preventScroll: true })
+ return false
+ }}
+ >
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $['members.removeFromTeamConfirmTitle'], {
+ ns: 'workspaceMembers',
+ memberName: payload?.member.name || payload?.member.email || '',
+ })}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $['members.removeFromTeamConfirmDescription'], {
+ ns: 'workspaceMembers',
+ })}
+ </AlertDialogDescription>
+ {removal.isError && (
+ <p role="alert" className="text-text-destructive">
+ {t(($) => $['api.actionFailed'], { ns: 'common' })}
+ </p>
+ )}
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancelButton disabled={removal.isPending}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton
+ loading={removal.isPending}
+ onClick={() => {
+ if (!payload || removal.isPending) return
+ removal.mutate(
+ { params: { member_id: payload.member.id } },
+ {
+ onSuccess: () => {
+ payload.fallbackFocus.current = listRef.current
+ removeDialog.close()
+ },
+ },
+ )
+ }}
+ >
+ {t(($) => $['operation.confirm'], { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ )}
+ </AlertDialog>
<Dialog handle={invitationDialogHandle}>
{({ payload: results }) => (
<DialogContent backdropProps={{ forceRender: true }}>
diff --git a/web/app/components/header/account-setting/members-page/member-menu.tsx b/web/app/components/header/account-setting/members-page/member-menu.tsx
index 3515d0e0700..ec871e33217 100644
--- a/web/app/components/header/account-setting/members-page/member-menu.tsx
+++ b/web/app/components/header/account-setting/members-page/member-menu.tsx
@@ -1,16 +1,6 @@
'use client'
import type { AccountWithRoleResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { Role } from '@/models/access-control'
-import {
- AlertDialog,
- AlertDialogCancelButton,
- AlertDialogConfirmButton,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from '@langgenius/dify-ui/alert-dialog'
import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import {
DropdownMenu,
@@ -20,16 +10,17 @@ import {
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
import { IconButton } from '@langgenius/dify-ui/icon-button'
-import { useMutation, useQueryClient } from '@tanstack/react-query'
-import { memo, useCallback, useMemo, useRef, useState } from 'react'
+import { useMutation } from '@tanstack/react-query'
+import { memo, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { consoleClient, consoleQuery } from '@/service/console'
+import { consoleQuery } from '@/service/console'
import { createSelectedRolePlaceholder } from '../workspace-role-list-query'
import AssignRolesContent from './assign-roles-content'
import TransferOwnershipContent from './transfer-ownership-content'
type MemberMenuProps = {
member: AccountWithRoleResponse
+ onRemove: () => void
isCurrentUser: boolean
canTransferOwnership?: boolean
allowMultipleRoles?: boolean
@@ -37,17 +28,15 @@ type MemberMenuProps = {
const MemberMenu = ({
member,
+ onRemove,
isCurrentUser,
canTransferOwnership = false,
allowMultipleRoles = true,
}: MemberMenuProps) => {
const { t } = useTranslation(['common', 'workspaceMembers'])
- const queryClient = useQueryClient()
const searchInputRef = useRef<HTMLInputElement>(null)
const [transferOpen, setTransferOpen] = useState(false)
const [assignModalOpen, setAssignModalOpen] = useState(false)
- const [removeConfirmOpen, setRemoveConfirmOpen] = useState(false)
- const [removing, setRemoving] = useState(false)
const isOwner = member.role === 'owner'
const canAssignRoles = !isOwner && !isCurrentUser
@@ -91,26 +80,6 @@ const MemberMenu = ({
)
}
- const handleOpenRemoveConfirm = useCallback(() => {
- setRemoveConfirmOpen(true)
- }, [])
-
- const handleRemove = useCallback(async () => {
- setRemoving(true)
- try {
- await consoleClient.workspaces.current.members.byMemberId.delete({
- params: { member_id: member.id },
- })
- void queryClient.invalidateQueries({
- queryKey: consoleQuery.workspaces.current.members.get.key(),
- })
- setRemoveConfirmOpen(false)
- } catch {
- } finally {
- setRemoving(false)
- }
- }, [member.id, queryClient])
-
if (!canAssignRoles && !canRemove && !showTransferOwnership) return null
return (
@@ -147,11 +116,7 @@ const MemberMenu = ({
)}
{(canAssignRoles || showTransferOwnership) && canRemove && <DropdownMenuSeparator />}
{canRemove && (
- <DropdownMenuItem
- variant="destructive"
- className="system-sm-medium"
- onClick={handleOpenRemoveConfirm}
- >
+ <DropdownMenuItem variant="destructive" className="system-sm-medium" onClick={onRemove}>
{t(($) => $['members.removeFromTeam'], { ns: 'workspaceMembers' })}
</DropdownMenuItem>
)}
@@ -162,32 +127,6 @@ const MemberMenu = ({
{t(($) => $['api.actionFailed'], { ns: 'common' })}
</p>
)}
- <AlertDialog
- open={removeConfirmOpen}
- onOpenChange={(open) => !open && setRemoveConfirmOpen(false)}
- >
- <AlertDialogContent backdropProps={{ forceRender: true }}>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $['members.removeFromTeamConfirmTitle'], {
- ns: 'workspaceMembers',
- memberName,
- })}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $['members.removeFromTeamConfirmDescription'], { ns: 'workspaceMembers' })}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton disabled={removing} onClick={handleRemove}>
- {t(($) => $['operation.confirm'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
<Dialog open={assignModalOpen} onOpenChange={setAssignModalOpen}>
<DialogContent
className="h-121"
diff --git a/web/app/components/header/account-setting/members-page/member-row.tsx b/web/app/components/header/account-setting/members-page/member-row.tsx
index c4bddf6e439..2e19c3e956d 100644
--- a/web/app/components/header/account-setting/members-page/member-row.tsx
+++ b/web/app/components/header/account-setting/members-page/member-row.tsx
@@ -12,6 +12,7 @@ import RoleBadges from './role-badges'
type MemberRowProps = {
member: AccountWithRoleResponse
+ onRemove: (row: HTMLTableRowElement | null) => void
roles: Array<{
id: string
name: string
@@ -24,6 +25,7 @@ type MemberRowProps = {
const MemberRow = ({
member,
+ onRemove,
roles,
isCurrentUser,
canManage,
@@ -31,6 +33,7 @@ const MemberRow = ({
allowMultipleRoles,
}: MemberRowProps) => {
const { t } = useTranslation(['workspaceMembers'])
+ const rowRef = useRef<HTMLTableRowElement>(null)
const detailsTriggerRef = useRef<HTMLButtonElement>(null)
const { formatTimeFromNow } = useFormatTimeFromNow()
@@ -52,6 +55,7 @@ const MemberRow = ({
return (
<tr
+ ref={rowRef}
data-testid={`member-row-${member.id}`}
className="cursor-pointer border-b border-divider-subtle hover:bg-state-base-hover has-[[aria-haspopup=dialog]:focus-visible]:bg-state-base-hover has-[[aria-haspopup=dialog]:focus-visible]:inset-ring-2 has-[[aria-haspopup=dialog]:focus-visible]:inset-ring-state-accent-solid has-[[aria-haspopup=dialog]:focus-visible]:outline-hidden has-[[aria-haspopup=menu]:hover]:bg-transparent"
onClick={handleRowClick}
@@ -98,6 +102,7 @@ const MemberRow = ({
<td className="px-3 py-2">
<MemberMenu
member={member}
+ onRemove={() => onRemove(rowRef.current)}
isCurrentUser={isCurrentUser}
canTransferOwnership={canTransferOwnership}
allowMultipleRoles={allowMultipleRoles}
diff --git a/web/features/agent-v2/__tests__/delete-agent.browser.spec.tsx b/web/features/agent-v2/__tests__/delete-agent.browser.spec.tsx
index 3d98b7033d6..6dc5b463912 100644
--- a/web/features/agent-v2/__tests__/delete-agent.browser.spec.tsx
+++ b/web/features/agent-v2/__tests__/delete-agent.browser.spec.tsx
@@ -225,7 +225,7 @@ it.each([
}
})
-it('focuses the next card primary control when that card has no actions', async () => {
+it('focuses the next agent primary control when that agent has no actions', async () => {
const target = agent('target', 'Editable Agent')
const remaining = {
...agent('remaining', 'Preview Agent'),
diff --git a/web/features/agent-v2/roster/components/agent-roster-list.tsx b/web/features/agent-v2/roster/components/agent-roster-list.tsx
index fcf183d1c49..16e367e0c4e 100644
--- a/web/features/agent-v2/roster/components/agent-roster-list.tsx
+++ b/web/features/agent-v2/roster/components/agent-roster-list.tsx
@@ -37,7 +37,6 @@ import { useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useExportAppDsl } from '@/app/components/app/use-export-app-dsl'
import AppIcon from '@/app/components/base/app-icon'
-import { getAdjacentCardFocusTargets } from '@/app/components/base/card-list-focus'
import { SkeletonRectangle } from '@/app/components/base/skeleton'
import { MAIN_NAV_APP_CARD_GRID_CLASS_NAME } from '@/app/components/main-nav/app-card-grid'
import { toast } from '@/app/notifications'
@@ -47,6 +46,7 @@ import { useCanCreateAgents } from '@/features/agent-v2/permissions'
import useTimestamp from '@/hooks/use-timestamp'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
+import { getAdjacentFocusTargets } from '@/utils/get-adjacent-focus-targets'
import { AgentWorkflowReferencesDropdown } from './agent-workflow-references-dropdown'
import { DuplicateAgentDialog } from './duplicate-agent-dialog'
import { EditAgentDialog } from './edit-agent-dialog'
@@ -233,12 +233,12 @@ function AgentRosterItem({
onDelete,
}: {
agent: AgentAppPartial
- onDelete: (agent: AgentAppPartial, trigger: HTMLButtonElement | null) => void
+ onDelete: (item: HTMLLIElement | null) => void
}) {
const { t } = useTranslation(['agentRoster'])
const { t: tApp } = useTranslation(['app'])
const { formatTime } = useTimestamp()
- const moreButtonRef = useRef<HTMLButtonElement>(null)
+ const itemRef = useRef<HTMLLIElement>(null)
const nameId = useId()
const descriptionId = useId()
const draftStatusId = useId()
@@ -336,6 +336,7 @@ function AgentRosterItem({
return (
<li
+ ref={itemRef}
aria-labelledby={nameId}
aria-describedby={defaultSection ? undefined : accessibleDescriptionIds || undefined}
className={cn(
@@ -380,9 +381,7 @@ function AgentRosterItem({
onEdit={capabilities.canEdit ? handleEditOpen : undefined}
onDuplicate={canDuplicate ? handleDuplicateOpen : undefined}
onExport={capabilities.canImportExportDSL ? handleExport : undefined}
- onDelete={
- capabilities.canDelete ? () => onDelete(agent, moreButtonRef.current) : undefined
- }
+ onDelete={capabilities.canDelete ? () => onDelete(itemRef.current) : undefined}
/>
</ContextMenuContent>
)}
@@ -392,7 +391,6 @@ function AgentRosterItem({
<div className="pointer-events-none flex items-center overflow-hidden rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-lg backdrop-blur-xs group-focus-within:pointer-events-auto group-hover:pointer-events-auto has-data-popup-open:pointer-events-auto [@media(hover:none)]:pointer-events-auto">
<DropdownMenu modal={false}>
<DropdownMenuTrigger
- ref={moreButtonRef}
render={
<IconButton
aria-label={t(($) => $['roster.moreActions'], {
@@ -413,11 +411,7 @@ function AgentRosterItem({
onEdit={capabilities.canEdit ? handleEditOpen : undefined}
onDuplicate={canDuplicate ? handleDuplicateOpen : undefined}
onExport={capabilities.canImportExportDSL ? handleExport : undefined}
- onDelete={
- capabilities.canDelete
- ? () => onDelete(agent, moreButtonRef.current)
- : undefined
- }
+ onDelete={capabilities.canDelete ? () => onDelete(itemRef.current) : undefined}
/>
</DropdownMenuContent>
</DropdownMenu>
@@ -535,11 +529,13 @@ export function AgentRosterList({
<AgentRosterItem
key={agent.id}
agent={agent}
- onDelete={(target, trigger) => {
+ onDelete={(item) => {
deleteDialog.openWithPayload({
- id: target.id,
- name: target.name,
- adjacentFocusTargets: getAdjacentCardFocusTargets(trigger),
+ id: agent.id,
+ name: agent.name,
+ adjacentFocusTargets: getAdjacentFocusTargets(item, (sibling) =>
+ sibling.querySelector<HTMLElement>(':scope > a[href], :scope > button'),
+ ),
fallbackFocus: { current: null },
})
}}
diff --git a/web/features/new-rag/documents/__tests__/delete-document.browser.spec.tsx b/web/features/new-rag/documents/__tests__/delete-document.browser.spec.tsx
new file mode 100644
index 00000000000..95c91af3233
--- /dev/null
+++ b/web/features/new-rag/documents/__tests__/delete-document.browser.spec.tsx
@@ -0,0 +1,196 @@
+import type { consoleClient } from '@/service/console'
+import {
+ zKnowledgeFsDurableDeletionAcceptedResponse,
+ zKnowledgeFsLogicalDocumentListResponse,
+} from '@dify/contracts/api/console/knowledge-fs/zod.gen'
+import { userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { AppToaster } from '@/app/notifications/app-toaster'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { QueryClientTestProvider } from '@/test/console/query-provider'
+import { createDeferred } from '@/test/deferred'
+import { KnowledgeSpaceTestProvider } from '@/test/knowledge-space'
+import { QueryTestingAdapter } from '@/test/query-state-testing-adapter'
+import { DocumentResultsSurface } from '../results/surface'
+import { DocumentsStateBoundary } from '../state/boundary'
+
+vi.mock('../../components/knowledge-model-readiness-banner', () => ({
+ KnowledgeModelReadinessBanner: () => null,
+}))
+const api = vi.hoisted(() => ({
+ list: vi.fn<typeof consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.get>(),
+ remove:
+ vi.fn<
+ typeof consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.byDocumentId.delete
+ >(),
+}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses, withConsoleClientResponses } =
+ await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'knowledgeFs.spaces.byControlSpaceId.logicalDocuments.get': api.list,
+ 'knowledgeFs.spaces.byControlSpaceId.sources.get': async () => ({
+ data: [],
+ next_cursor: null,
+ }),
+ 'knowledgeFs.spaces.byControlSpaceId.backgroundTasks.get': async () => ({
+ data: [],
+ next_cursor: null,
+ }),
+ }),
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'knowledgeFs.spaces.byControlSpaceId.logicalDocuments.byDocumentId.delete': api.remove,
+ }),
+ }
+})
+beforeEach(() => vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false))
+afterEach(() => vi.unstubAllGlobals())
+async function setup(ids: string[]) {
+ let documents = zKnowledgeFsLogicalDocumentListResponse.parse({
+ data: ids.map((id) => ({
+ id,
+ title: id,
+ knowledge_space_id: 'space-1',
+ row_version: 1,
+ status: 'ready',
+ enabled: true,
+ active: null,
+ created_at: '2026-07-20T10:00:00Z',
+ updated_at: '2026-07-20T10:00:00Z',
+ user_metadata: {},
+ })),
+ next_cursor: null,
+ }).data
+ api.list.mockReset().mockImplementation(async () => ({ data: documents, next_cursor: null }))
+ api.remove.mockReset().mockImplementation(async ({ params }) => {
+ documents = documents.filter((item) => item.id !== params.document_id)
+ return zKnowledgeFsDurableDeletionAcceptedResponse.parse({
+ status_url: '/deletion',
+ job: {
+ id: 'delete-1',
+ checkpoint: 'requested',
+ created_at: '2026-07-20T10:00:00Z',
+ updated_at: '2026-07-20T10:00:00Z',
+ knowledge_space_id: 'space-1',
+ target_id: params.document_id,
+ target_type: 'logical_document',
+ run_state: 'queued',
+ },
+ })
+ })
+ const { queryClient } = createConsoleQueryWrapper({
+ systemFeatures: { deployment_edition: 'ENTERPRISE' },
+ knowledgeFsFeatures: { enabled: true, upload_enabled: true },
+ })
+ const screen = await render(
+ <QueryClientTestProvider queryClient={queryClient}>
+ <QueryTestingAdapter>
+ <KnowledgeSpaceTestProvider>
+ <DocumentsStateBoundary knowledgeSpaceId="space-1">
+ <DocumentResultsSurface />
+ <AppToaster />
+ </DocumentsStateBoundary>
+ </KnowledgeSpaceTestProvider>
+ </QueryTestingAdapter>
+ </QueryClientTestProvider>,
+ )
+ const actions = (id: string) =>
+ screen.getByRole('button', { name: `knowledgeDocuments.documentActions:{"name":"${id}"}` })
+ const open = async (id: string) => {
+ await actions(id).click()
+ await screen.getByRole('menuitem', { name: 'common.operation.delete', exact: true }).click()
+ await expect.element(screen.getByRole('alertdialog')).toBeVisible()
+ await expect.element(screen.getByRole('menu')).not.toBeInTheDocument()
+ }
+ return {
+ screen,
+ open,
+ actions,
+ removeElsewhere: async () => {
+ documents = []
+ await queryClient.invalidateQueries({
+ queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.get.key(),
+ })
+ },
+ refreshRevision: async () => {
+ documents = documents.map((document) => ({ ...document, row_version: 2 }))
+ await queryClient.invalidateQueries({
+ queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.get.key(),
+ })
+ },
+ }
+}
+describe('Knowledge document deletion', () => {
+ it('closes safely if the document was removed elsewhere while confirmation was open', async () => {
+ const { screen, open, removeElsewhere } = await setup(['Alpha'])
+ await open('Alpha')
+ await removeElsewhere()
+ await screen.getByRole('button', { name: 'common.operation.delete', exact: true }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('region', { name: 'knowledgeSpace.documents', exact: true }))
+ .toHaveFocus()
+ expect(api.remove).not.toHaveBeenCalled()
+ })
+
+ it('uses the latest revision when the list refreshes with confirmation open', async () => {
+ const { screen, open, refreshRevision } = await setup(['Alpha'])
+ await open('Alpha')
+ await refreshRevision()
+ await screen.getByRole('button', { name: 'common.operation.delete', exact: true }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ expect(api.remove).toHaveBeenCalledWith(
+ expect.objectContaining({ body: { expectedRevision: 2 } }),
+ )
+ })
+
+ it.each([
+ { ids: ['Alpha', 'Beta', 'Gamma'], remove: 'Beta', next: 'Gamma' },
+ { ids: ['Alpha', 'Beta'], remove: 'Beta', next: 'Alpha' },
+ { ids: ['Alpha'], remove: 'Alpha', next: null },
+ ])('restores focus after deleting $remove from $ids', async ({ ids, remove, next }) => {
+ const { screen, open, actions } = await setup(ids)
+ await open(remove)
+ await screen.getByRole('button', { name: 'common.operation.delete', exact: true }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect.element(actions(remove)).not.toBeInTheDocument()
+ await expect
+ .element(
+ next
+ ? screen.getByRole('link', { name: next, exact: true })
+ : screen.getByRole('region', { name: 'knowledgeSpace.documents', exact: true }),
+ )
+ .toHaveFocus()
+ })
+ it('holds focus and prevents dismissal while deletion is pending', async () => {
+ const { screen, open } = await setup(['Alpha'])
+ const request =
+ createDeferred<
+ Awaited<
+ ReturnType<
+ typeof consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.byDocumentId.delete
+ >
+ >
+ >()
+ api.remove.mockReturnValueOnce(request.promise)
+ await open('Alpha')
+ const confirm = screen.getByRole('button', { name: 'common.operation.delete', exact: true })
+ await confirm.click()
+ await expect.element(confirm).toHaveFocus()
+ await userEvent.keyboard('{Escape}')
+ await expect.element(screen.getByRole('alertdialog')).toBeVisible()
+ request.reject(new Error('Failed'))
+ await expect
+ .element(screen.getByText('knowledgeSpace.documentsErrorDescription', { exact: true }))
+ .toBeVisible()
+ await confirm.click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('region', { name: 'knowledgeSpace.documents', exact: true }))
+ .toHaveFocus()
+ })
+})
diff --git a/web/features/new-rag/documents/__tests__/page.spec.tsx b/web/features/new-rag/documents/__tests__/page.spec.tsx
index c820e1939a1..1e7c3715e40 100644
--- a/web/features/new-rag/documents/__tests__/page.spec.tsx
+++ b/web/features/new-rag/documents/__tests__/page.spec.tsx
@@ -1937,6 +1937,32 @@ describe('DocumentsPage', () => {
)
})
+ it('discards a cancelled rename draft before reopening', async () => {
+ const user = userEvent.setup()
+ documentsQuery.data = { pages: [{ items: [document()] }] }
+ await render(<DocumentsPage knowledgeSpaceId="space-1" />)
+ const open = async () => {
+ await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
+ await user.click(await screen.findByRole('menuitem', { name: 'common.operation.rename' }))
+ }
+ await open()
+ const name = screen.getByRole('textbox', { name: 'knowledgeSpace.documentColumn' })
+ const original = (name as HTMLInputElement).value
+ await user.clear(name)
+ await user.type(name, 'Unsaved draft')
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('dialog', { name: 'common.operation.rename' }),
+ ).not.toBeInTheDocument(),
+ )
+ await open()
+ expect(screen.getByRole('textbox', { name: 'knowledgeSpace.documentColumn' })).toHaveValue(
+ original,
+ )
+ expect(renameDocumentMutation).not.toHaveBeenCalled()
+ })
+
it('renames a document through its user-facing display metadata', async () => {
const user = userEvent.setup()
documentsQuery.data = { pages: [{ items: [document()] }] }
diff --git a/web/features/new-rag/documents/actions-dropdown.tsx b/web/features/new-rag/documents/actions-dropdown.tsx
index cf19ada043b..df4897aaada 100644
--- a/web/features/new-rag/documents/actions-dropdown.tsx
+++ b/web/features/new-rag/documents/actions-dropdown.tsx
@@ -1,16 +1,6 @@
'use client'
import type { LogicalDocument } from './models'
-import {
- AlertDialog,
- AlertDialogCancelButton,
- AlertDialogConfirmButton,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
@@ -44,7 +34,6 @@ import {
useDocumentRowActionBusy,
useDownloadDocumentAction,
useReindexDocumentAction,
- useRemoveDocumentAction,
useRenameDocumentAction,
useRetryDocumentTaskAction,
useToggleDocumentAvailabilityAction,
@@ -85,14 +74,12 @@ function RenameDocumentMenuItem({
)
}
-function RenameDocumentDialog({
+function RenameDocumentForm({
document,
- onOpenChange,
- open,
+ onClose,
}: {
document: LogicalDocument
- onOpenChange: (open: boolean) => void
- open: boolean
+ onClose: () => void
}) {
const { t } = useTranslation(['knowledgeSpace', 'dataset'])
const { t: tCommon } = useTranslation(['common'])
@@ -102,52 +89,48 @@ function RenameDocumentDialog({
const submit = async () => {
const title = nextTitle.trim()
if (!title || title === document.title || busy) return
- if (await run(title)) onOpenChange(false)
+ if (await run(title)) onClose()
}
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <form
- className="flex min-h-0 flex-col"
- onSubmit={(event) => {
- event.preventDefault()
- void submit()
- }}
+ <form
+ className="flex min-h-0 flex-col"
+ onSubmit={(event) => {
+ event.preventDefault()
+ void submit()
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle>{tCommon(($) => $['operation.rename'])}</DialogTitle>
+ <DialogDescription>{document.title}</DialogDescription>
+ </DialogHeader>
+ <DialogBody>
+ <label className="block system-sm-medium text-text-secondary" htmlFor={inputId}>
+ {t(($) => $.documentColumn)}
+ </label>
+ <Input
+ id={inputId}
+ autoComplete="off"
+ className="mt-2 w-full"
+ disabled={pending}
+ value={nextTitle}
+ onChange={(event) => setNextTitle(event.target.value)}
+ />
+ </DialogBody>
+ <DialogFooter>
+ <Button disabled={pending} onClick={onClose} type="button">
+ {tCommon(($) => $['operation.cancel'])}
+ </Button>
+ <Button
+ disabled={!nextTitle.trim() || nextTitle.trim() === document.title}
+ loading={pending}
+ type="submit"
+ variant="primary"
>
- <DialogHeader>
- <DialogTitle>{tCommon(($) => $['operation.rename'])}</DialogTitle>
- <DialogDescription>{document.title}</DialogDescription>
- </DialogHeader>
- <DialogBody>
- <label className="block system-sm-medium text-text-secondary" htmlFor={inputId}>
- {t(($) => $.documentColumn)}
- </label>
- <Input
- id={inputId}
- autoComplete="off"
- className="mt-2 w-full"
- disabled={pending}
- value={nextTitle}
- onChange={(event) => setNextTitle(event.target.value)}
- />
- </DialogBody>
- <DialogFooter>
- <Button disabled={pending} onClick={() => onOpenChange(false)} type="button">
- {tCommon(($) => $['operation.cancel'])}
- </Button>
- <Button
- disabled={!nextTitle.trim() || nextTitle.trim() === document.title}
- loading={pending}
- type="submit"
- variant="primary"
- >
- {tCommon(($) => $['operation.save'])}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
+ {tCommon(($) => $['operation.save'])}
+ </Button>
+ </DialogFooter>
+ </form>
)
}
@@ -275,58 +258,17 @@ function RemoveDocumentMenuItem({
)
}
-function RemoveDocumentDialog({
- document,
- onOpenChange,
- open,
-}: {
- document: LogicalDocument
- onOpenChange: (open: boolean) => void
- open: boolean
-}) {
- const { t: tCommon } = useTranslation(['common'])
- const { pending, run } = useRemoveDocumentAction(document)
-
- return (
- <AlertDialog open={open} onOpenChange={onOpenChange}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>{tCommon(($) => $['operation.deleteConfirmTitle'])}</AlertDialogTitle>
- <AlertDialogDescription>
- {tCommon(($) => $['operation.confirmAction'])}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancelButton disabled={pending}>
- {tCommon(($) => $['operation.cancel'])}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton
- loading={pending}
- tone="destructive"
- onClick={() =>
- void run().then((removed) => {
- if (removed) onOpenChange(false)
- })
- }
- >
- {tCommon(($) => $['operation.delete'])}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- )
-}
-
export function DocumentActionsDropdown({
className,
document,
+ onRemove,
}: {
className?: string
+ onRemove: () => void
document: LogicalDocument
}) {
const { t } = useTranslation(['dataset', 'knowledgeDocuments'])
const busy = useDocumentRowActionBusy(document.id)
- const [removeDialogOpen, setRemoveDialogOpen] = useState(false)
const [renameDialogOpen, setRenameDialogOpen] = useState(false)
const unavailableReasonId = `new-document-${document.id}-actions-unavailable`
@@ -360,23 +302,17 @@ export function DocumentActionsDropdown({
<DownloadDocumentMenuItem document={document} />
<ToggleDocumentAvailabilityMenuItem document={document} />
<DropdownMenuSeparator className="my-px" />
- <RemoveDocumentMenuItem document={document} onOpen={() => setRemoveDialogOpen(true)} />
+ <RemoveDocumentMenuItem document={document} onOpen={onRemove} />
</DropdownMenuContent>
</DropdownMenu>
<span id={unavailableReasonId} className="sr-only">
{t(($) => $.documentActionsUnavailable, { ns: 'knowledgeDocuments' })}
</span>
- <RenameDocumentDialog
- key={renameDialogOpen ? 'open' : 'closed'}
- document={document}
- open={renameDialogOpen}
- onOpenChange={setRenameDialogOpen}
- />
- <RemoveDocumentDialog
- document={document}
- open={removeDialogOpen}
- onOpenChange={setRemoveDialogOpen}
- />
+ <Dialog open={renameDialogOpen} onOpenChange={setRenameDialogOpen}>
+ <DialogContent>
+ <RenameDocumentForm document={document} onClose={() => setRenameDialogOpen(false)} />
+ </DialogContent>
+ </Dialog>
</>
)
}
diff --git a/web/features/new-rag/documents/list.tsx b/web/features/new-rag/documents/list.tsx
index 47b6495a2e0..673655bff52 100644
--- a/web/features/new-rag/documents/list.tsx
+++ b/web/features/new-rag/documents/list.tsx
@@ -320,18 +320,29 @@ function DocumentUpdatedCell({ updatedAt }: { updatedAt: string }) {
)
}
-const DocumentRow = memo(({ document }: { document: LogicalDocument }) => (
- <tr className="h-12 border-t border-divider-subtle">
- <DocumentSelectionCell document={document} />
- <DocumentTitleCell document={document} />
- <DocumentSourceCell documentId={document.id} />
- <DocumentStatusCell documentId={document.id} />
- <DocumentUpdatedCell updatedAt={document.updatedAt} />
- <td className="w-10 align-middle">
- <DocumentActionsDropdown document={document} />
- </td>
- </tr>
-))
+const DocumentRow = memo(
+ ({
+ document,
+ onRemove,
+ }: {
+ document: LogicalDocument
+ onRemove: (row: HTMLTableRowElement | null) => void
+ }) => {
+ const rowRef = useRef<HTMLTableRowElement>(null)
+ return (
+ <tr ref={rowRef} className="h-12 border-t border-divider-subtle">
+ <DocumentSelectionCell document={document} />
+ <DocumentTitleCell document={document} />
+ <DocumentSourceCell documentId={document.id} />
+ <DocumentStatusCell documentId={document.id} />
+ <DocumentUpdatedCell updatedAt={document.updatedAt} />
+ <td className="w-10 align-middle">
+ <DocumentActionsDropdown document={document} onRemove={() => onRemove(rowRef.current)} />
+ </td>
+ </tr>
+ )
+ },
+)
export function DocumentsEmpty() {
const { t } = useTranslation(['knowledgeSpace', 'knowledgeDocuments'])
@@ -508,7 +519,11 @@ function DocumentsTableHeader() {
)
}
-function DocumentsTable() {
+function DocumentsTable({
+ onRemove,
+}: {
+ onRemove: (documentId: string, row: HTMLTableRowElement | null) => void
+}) {
const { t } = useTranslation(['knowledgeSpace', 'knowledgeDocuments'])
const { t: tCommon } = useTranslation(['common'])
const { documents, resultsIncomplete, sourcesPending, documentSnapshotPending } =
@@ -574,7 +589,11 @@ function DocumentsTable() {
<DocumentsTableHeader />
<tbody>
{visibleDocuments.map((document) => (
- <DocumentRow key={document.id} document={document} />
+ <DocumentRow
+ key={document.id}
+ document={document}
+ onRemove={(row) => onRemove(document.id, row)}
+ />
))}
</tbody>
</table>
@@ -669,14 +688,18 @@ function DocumentsTable() {
)
}
-export function DocumentsList() {
+export function DocumentsList({
+ onRemove,
+}: {
+ onRemove: (documentId: string, row: HTMLTableRowElement | null) => void
+}) {
const { t } = useTranslation(['knowledgeDocuments'])
return (
<>
<div className="min-w-0">
<DocumentsToolbar />
- <DocumentsTable />
+ <DocumentsTable onRemove={onRemove} />
</div>
<p className="flex min-h-4 items-center gap-1.5 system-xs-regular text-text-tertiary">
<span aria-hidden className="i-ri-information-2-line size-3.5" />
diff --git a/web/features/new-rag/documents/results/surface.tsx b/web/features/new-rag/documents/results/surface.tsx
index aceb91791fc..37e7fe35894 100644
--- a/web/features/new-rag/documents/results/surface.tsx
+++ b/web/features/new-rag/documents/results/surface.tsx
@@ -1,17 +1,30 @@
'use client'
+import {
+ AlertDialog,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ createAlertDialogHandle,
+} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { useAtomValueRawSync, useSetAtom } from 'jotai'
-import { useEffect, useRef } from 'react'
+import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { getHttpErrorStatus } from '@/service/http-error'
+import { getAdjacentFocusTargets } from '@/utils/get-adjacent-focus-targets'
import { KnowledgeModelReadinessBanner } from '../../components/knowledge-model-readiness-banner'
import { DocumentsEmpty, DocumentsList } from '../list'
import {
DocumentPermissionRecoveryBoundary,
DocumentReadPermissionRecovery,
} from '../permission-recovery/recovery-boundary'
+import { useRemoveDocumentAction } from '../row-actions/use-document-row-actions'
import { documentsKnowledgeSpaceIdAtom } from '../state/inputs'
import {
documentsAtom,
@@ -212,7 +225,11 @@ function DependencyRecoveryBoundary({ children }: { children: React.ReactNode })
)
}
-function DocumentCollectionState() {
+function DocumentCollectionState({
+ onRemove,
+}: {
+ onRemove: (documentId: string, row: HTMLTableRowElement | null) => void
+}) {
const { t } = useTranslation(['knowledgeSpace', 'knowledgeDocuments'])
const { t: tCommon } = useTranslation(['common'])
const canRead = useAtomValueRawSync(documentCanReadAtom)
@@ -270,21 +287,101 @@ function DocumentCollectionState() {
</Button>
</div>
)
- return documents.length ? <DocumentsList /> : <DocumentsEmpty />
+ return documents.length ? <DocumentsList onRemove={onRemove} /> : <DocumentsEmpty />
}
export function DocumentResultsSurface() {
+ const { t } = useTranslation(['knowledgeSpace'])
+ const { t: tCommon } = useTranslation(['common'])
+ const listRef = useRef<HTMLDivElement>(null)
+ const [deleteDialog] = useState(() =>
+ createAlertDialogHandle<{
+ documentId: string
+ adjacentFocusTargets: HTMLElement[]
+ fallbackFocus: { current: HTMLElement | null }
+ }>(),
+ )
+ const { pending: deleting, run: removeDocument, reset } = useRemoveDocumentAction()
+
const knowledgeSpaceId = useAtomValueRawSync(documentsKnowledgeSpaceIdAtom)
return (
- <DocumentPermissionRecoveryBoundary>
- <DocumentUploadSurface>
- <KnowledgeModelReadinessBanner capability="index" knowledgeSpaceId={knowledgeSpaceId} />
- <ResultsAutoPagination />
- <DocumentQueryRecoveryNotice />
- <DependencyRecoveryBoundary>
- <DocumentCollectionState />
- </DependencyRecoveryBoundary>
- </DocumentUploadSurface>
- </DocumentPermissionRecoveryBoundary>
+ <div
+ ref={listRef}
+ tabIndex={-1}
+ role="region"
+ aria-label={t(($) => $.documents)}
+ className="flex min-h-0 flex-1 flex-col focus-visible:outline-2 focus-visible:outline-state-accent-solid"
+ >
+ <DocumentPermissionRecoveryBoundary>
+ <DocumentUploadSurface>
+ <KnowledgeModelReadinessBanner capability="index" knowledgeSpaceId={knowledgeSpaceId} />
+ <ResultsAutoPagination />
+ <DocumentQueryRecoveryNotice />
+ <DependencyRecoveryBoundary>
+ <DocumentCollectionState
+ onRemove={(documentId, row) => {
+ const adjacentFocusTargets = getAdjacentFocusTargets(row, (sibling) =>
+ sibling.querySelector<HTMLAnchorElement>('a[href]'),
+ )
+ deleteDialog.openWithPayload({
+ documentId,
+ adjacentFocusTargets,
+ fallbackFocus: { current: null },
+ })
+ }}
+ />
+ </DependencyRecoveryBoundary>
+ </DocumentUploadSurface>
+ </DocumentPermissionRecoveryBoundary>
+ <AlertDialog
+ handle={deleteDialog}
+ onOpenChange={(open, details) => {
+ if (!open && deleting && details.reason !== 'imperative-action') details.cancel()
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) reset()
+ }}
+ >
+ {({ payload }) => (
+ <AlertDialogContent
+ finalFocus={() => {
+ const fallback = payload?.fallbackFocus.current
+ if (!fallback) return true
+ const target =
+ payload.adjacentFocusTargets.find((element) => element.isConnected) ?? fallback
+ target.focus({ preventScroll: true })
+ return false
+ }}
+ >
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {tCommon(($) => $['operation.deleteConfirmTitle'])}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {tCommon(($) => $['operation.confirmAction'])}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancelButton disabled={deleting}>
+ {tCommon(($) => $['operation.cancel'])}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton
+ loading={deleting}
+ tone="destructive"
+ onClick={async () => {
+ if (!payload || deleting) return
+ if (await removeDocument(payload.documentId)) {
+ payload.fallbackFocus.current = listRef.current
+ deleteDialog.close()
+ }
+ }}
+ >
+ {tCommon(($) => $['operation.delete'])}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ )}
+ </AlertDialog>
+ </div>
)
}
diff --git a/web/features/new-rag/documents/row-actions/use-document-row-actions.ts b/web/features/new-rag/documents/row-actions/use-document-row-actions.ts
index 0f8b7e696ea..b980b94b31f 100644
--- a/web/features/new-rag/documents/row-actions/use-document-row-actions.ts
+++ b/web/features/new-rag/documents/row-actions/use-document-row-actions.ts
@@ -4,7 +4,7 @@ import type { DocumentDisplayStatus } from '../model'
import type { DocumentProcessingTask, LogicalDocument } from '../models'
import type { DocumentRowAction } from '../state/row-actions'
import { useMutation, useQueryClient } from '@tanstack/react-query'
-import { useAtomValue, useSetAtom } from 'jotai'
+import { useAtomValue, useSetAtom, useStore } from 'jotai'
import { useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
@@ -25,6 +25,7 @@ import {
} from '../model'
import { backgroundTaskFromApi } from '../models'
import { documentsKnowledgeSpaceIdAtom } from '../state/inputs'
+import { documentsByIdAtom } from '../state/queries'
import { createDocumentRowCanEditAtom } from '../state/results'
import {
beginDocumentRowActionAtom,
@@ -228,15 +229,20 @@ export function useToggleDocumentAvailabilityAction(
return { busy, pending, run }
}
-export function useRemoveDocumentAction(document: LogicalDocument) {
+export function useRemoveDocumentAction() {
const { t } = useTranslation(['knowledgeSpace'])
- const canEdit = useDocumentCanEdit(document.id)
+ const store = useStore()
const onDocumentRemoved = useSetAtom(removeDocumentFromSelectionAtom)
const onWriteDenied = useSetAtom(denyDocumentWriteAtom)
- const { begin, busy, finish, pending } = useDocumentActionLock(document.id, 'remove')
+ const begin = useSetAtom(beginDocumentRowActionAtom)
+ const finish = useSetAtom(finishDocumentRowActionAtom)
const { invalidateDocumentsAndTasks, knowledgeSpaceId } = useDocumentInvalidation()
- const { mutateAsync: removeDocument } = useMutation({
- mutationFn: () =>
+ const {
+ mutateAsync: removeDocument,
+ isPending: pending,
+ reset,
+ } = useMutation({
+ mutationFn: (document: LogicalDocument) =>
consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.byDocumentId.delete({
body: { expectedRevision: document.rowVersion },
headers: { 'Idempotency-Key': createRequestId() },
@@ -244,11 +250,18 @@ export function useRemoveDocumentAction(document: LogicalDocument) {
}),
})
- const run = useCallback(async () => {
- if (!canEdit || !begin()) return false
+ const run = async (documentId: string) => {
+ const document = store.get(documentsByIdAtom).get(documentId)
+ if (!document) {
+ onDocumentRemoved(documentId)
+ return true
+ }
+ if (!store.get(createDocumentRowCanEditAtom(documentId))) return false
+ const action = { action: 'remove', documentId } as const
+ if (!begin(action)) return false
try {
- await removeDocument()
- onDocumentRemoved(document.id)
+ await removeDocument(document)
+ onDocumentRemoved(documentId)
invalidateDocumentsAndTasks()
return true
} catch (error) {
@@ -256,21 +269,11 @@ export function useRemoveDocumentAction(document: LogicalDocument) {
else toast.error(t(($) => $.documentsErrorDescription))
return false
} finally {
- finish()
+ finish(action)
}
- }, [
- begin,
- canEdit,
- document.id,
- finish,
- invalidateDocumentsAndTasks,
- onDocumentRemoved,
- onWriteDenied,
- removeDocument,
- t,
- ])
+ }
- return { busy, pending, run }
+ return { pending, run, reset }
}
export function useRetryDocumentTaskAction(
diff --git a/web/features/new-rag/list/__tests__/delete-knowledge-space.browser.spec.tsx b/web/features/new-rag/list/__tests__/delete-knowledge-space.browser.spec.tsx
new file mode 100644
index 00000000000..a0e668ad335
--- /dev/null
+++ b/web/features/new-rag/list/__tests__/delete-knowledge-space.browser.spec.tsx
@@ -0,0 +1,163 @@
+import type { consoleClient } from '@/service/console'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { QueryClientTestProvider } from '@/test/console/query-provider'
+import { createDeferred } from '@/test/deferred'
+import { NewKnowledgeList } from '../new-knowledge-list'
+
+type KnowledgeFsSpaceListItemResponse = Awaited<
+ ReturnType<typeof consoleClient.knowledgeFs.spaces.get>
+>['data'][number]
+
+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }))
+
+const api = vi.hoisted(() => ({
+ list: vi.fn<typeof consoleClient.knowledgeFs.spaces.get>(),
+ remove: vi.fn<typeof consoleClient.knowledgeFs.spaces.byControlSpaceId.delete>(),
+}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'knowledgeFs.spaces.get': api.list,
+ 'knowledgeFs.spaces.byControlSpaceId.delete': api.remove,
+ 'datasets.knowledgeFsUpgradeJobs.get': async () => ({ data: [] }),
+ 'datasets.apiBaseInfo.get': async () => ({ api_base_url: '' }),
+ 'workspaces.current.members.get': async () => ({ accounts: [] }),
+ 'tags.get': async () => [],
+ }),
+ }
+})
+const space = (
+ id: string,
+ name: string,
+ overrides: Partial<KnowledgeFsSpaceListItemResponse> = {},
+): KnowledgeFsSpaceListItemResponse => ({
+ control_space_id: id,
+ created_at: '2026-07-15T00:00:00Z',
+ knowledge_space_id: id,
+ linked_apps: 0,
+ owner_account_id: 'account-1',
+ permission_keys: ['knowledge_space_read'],
+ resource_version: 1,
+ state: 'active',
+ technical_status: 'available',
+ technical_summary: {
+ description: null,
+ document_count: 0,
+ icon: null,
+ knowledge_space_id: id,
+ name,
+ revision: 1,
+ slug: id,
+ },
+ updated_at: '2026-07-18T00:00:00Z',
+ visibility: 'only_me',
+ ...overrides,
+})
+
+beforeEach(() => vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false))
+afterEach(() => vi.unstubAllGlobals())
+async function setup(ids: string[]) {
+ let datasets = ids.map((id) =>
+ space(id, id, { permission_keys: ['knowledge_space_read', 'knowledge_space_delete'] }),
+ )
+ api.list.mockReset().mockImplementation(async () => ({
+ data: datasets,
+ page: 1,
+ total: datasets.length,
+ limit: 30,
+ has_more: false,
+ }))
+ api.remove.mockReset().mockImplementation(async ({ params }) => {
+ datasets = datasets.filter((item) => item.control_space_id !== params.control_space_id)
+ return { result: 'success' }
+ })
+ const { queryClient } = createConsoleQueryWrapper({ systemFeatures: { rbac_enabled: true } })
+ const screen = await render(
+ <QueryClientTestProvider queryClient={queryClient}>
+ <NuqsTestingAdapter>
+ <NewKnowledgeList view="agent" onViewChange={vi.fn()} />
+ </NuqsTestingAdapter>
+ </QueryClientTestProvider>,
+ )
+ const open = async (id: string) => {
+ const link = screen.getByRole('link', { name: id, exact: true })
+ await link.hover()
+ const card = link.element().closest('li')!
+ await userEvent.click(card.querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')!)
+ await screen.getByRole('menuitem', { name: 'common.operation.delete', exact: true }).click()
+ await expect.element(screen.getByRole('alertdialog')).toBeVisible()
+ await expect.element(screen.getByRole('menu')).not.toBeInTheDocument()
+ await screen.getByRole('textbox').fill(id)
+ }
+ return { screen, open }
+}
+describe('Knowledge space deletion', () => {
+ it('removes the confirmed item and restores focus before the list refresh completes', async () => {
+ const { screen, open } = await setup(['Alpha', 'Beta'])
+ await open('Alpha')
+ const list = api.list.getMockImplementation()!
+ const refresh = createDeferred<Awaited<ReturnType<typeof list>>>()
+ api.list.mockReturnValueOnce(refresh.promise)
+ await screen.getByRole('button', { name: 'common.operation.confirm' }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('link', { name: 'Alpha', exact: true }))
+ .not.toBeInTheDocument()
+ await expect.element(screen.getByRole('link', { name: 'Beta', exact: true })).toHaveFocus()
+ refresh.resolve(await list({ query: { page: 1, limit: 30 } }))
+ })
+
+ it.each([
+ { ids: ['Alpha', 'Beta', 'Gamma'], remove: 'Beta', next: 'Gamma' },
+ { ids: ['Alpha', 'Beta'], remove: 'Beta', next: 'Alpha' },
+ { ids: ['Alpha'], remove: 'Alpha', next: null },
+ ])('restores focus after deleting $remove from $ids', async ({ ids, remove, next }) => {
+ const { screen, open } = await setup(ids)
+ await open(remove)
+ await screen.getByRole('button', { name: 'common.operation.confirm' }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('link', { name: remove, exact: true }))
+ .not.toBeInTheDocument()
+ await expect
+ .element(
+ next ? screen.getByRole('link', { name: next, exact: true }) : screen.getByRole('region'),
+ )
+ .toHaveFocus()
+ })
+ it('retains focus while pending and leaves a failed deletion retryable', async () => {
+ const { screen, open } = await setup(['Alpha'])
+ const request = createDeferred<{ result: 'success' }>()
+ api.remove.mockReturnValueOnce(request.promise)
+ await open('Alpha')
+ const confirm = screen.getByRole('button', { name: 'common.operation.confirm' })
+ await confirm.click()
+ await expect.element(confirm).toHaveFocus()
+ await userEvent.keyboard('{Escape}')
+ await expect
+ .element(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ .toBeDisabled()
+ await expect.element(screen.getByRole('alertdialog')).toBeVisible()
+ request.reject(new Error('Failed'))
+ await expect.element(screen.getByRole('alert')).toBeVisible()
+ await confirm.click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect.element(screen.getByRole('region')).toHaveFocus()
+ })
+ it('returns focus to the menu button on cancellation', async () => {
+ const { screen, open } = await setup(['Alpha'])
+ await open('Alpha')
+ await screen.getByRole('button', { name: 'common.operation.cancel' }).click()
+ await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('button', { name: 'common.operation.more' }))
+ .toHaveFocus()
+ expect(api.remove).not.toHaveBeenCalled()
+ })
+})
diff --git a/web/features/new-rag/list/__tests__/knowledge-space-card.browser.spec.tsx b/web/features/new-rag/list/__tests__/knowledge-space-card.browser.spec.tsx
index 1318dcb2518..47a7bafe574 100644
--- a/web/features/new-rag/list/__tests__/knowledge-space-card.browser.spec.tsx
+++ b/web/features/new-rag/list/__tests__/knowledge-space-card.browser.spec.tsx
@@ -46,7 +46,11 @@ const renderCard = async () => {
<QueryClientProvider client={queryClient}>
<button type="button">Before card</button>
<ul className="mt-4 grid w-80 p-4">
- <KnowledgeSpaceCard knowledgeSpace={knowledgeSpace} onOpenTagManagement={vi.fn()} />
+ <KnowledgeSpaceCard
+ onDelete={vi.fn()}
+ knowledgeSpace={knowledgeSpace}
+ onOpenTagManagement={vi.fn()}
+ />
</ul>
</QueryClientProvider>,
)
diff --git a/web/features/new-rag/list/knowledge-space-actions.tsx b/web/features/new-rag/list/knowledge-space-actions.tsx
index 8eb3cce2853..0bbedd4deaf 100644
--- a/web/features/new-rag/list/knowledge-space-actions.tsx
+++ b/web/features/new-rag/list/knowledge-space-actions.tsx
@@ -1,7 +1,6 @@
'use client'
import type { KnowledgeFsSpaceListItemResponse } from '@dify/contracts/api/console/knowledge-fs/types.gen'
-import { AlertDialog, AlertDialogContent } from '@langgenius/dify-ui/alert-dialog'
import {
DropdownMenu,
DropdownMenuContent,
@@ -11,110 +10,58 @@ import {
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
import { IconButton } from '@langgenius/dify-ui/icon-button'
-import { useMutation, useQueryClient } from '@tanstack/react-query'
-import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import Link from '@/next/link'
-import { consoleQuery } from '@/service/console'
-import { getHttpErrorStatus } from '@/service/http-error'
-import { DeleteKnowledgeForm } from '../delete-knowledge-form'
import { newKnowledgeSettingsPath } from '../routes'
export function KnowledgeSpaceActions({
knowledgeSpace,
+ onDelete,
}: {
knowledgeSpace: KnowledgeFsSpaceListItemResponse
+ onDelete: () => void
}) {
const { t: tCommon } = useTranslation(['common'])
- const queryClient = useQueryClient()
- const [deleteOpen, setDeleteOpen] = useState(false)
const canEdit = knowledgeSpace.permission_keys.includes('knowledge_space_edit')
const canDelete = knowledgeSpace.permission_keys.includes('knowledge_space_delete')
- const name = knowledgeSpace.technical_summary?.name ?? knowledgeSpace.control_space_id
-
- const deleteMutation = useMutation(
- consoleQuery.knowledgeFs.spaces.byControlSpaceId.delete.mutationOptions({
- context: { silent: true },
- onSuccess: () => {
- // The card leaves the list once it refreshes; that removal is the success feedback.
- setDeleteOpen(false)
- void queryClient.invalidateQueries({
- queryKey: consoleQuery.knowledgeFs.spaces.get.key(),
- })
- },
- }),
- )
-
if (!canEdit && !canDelete) return null
- const deleteError = deleteMutation.error
- ? getHttpErrorStatus(deleteMutation.error) !== undefined
- ? deleteMutation.error.message
- : tCommon(($) => $['api.actionFailed'])
- : undefined
-
return (
- <>
- <div className="pointer-events-none absolute top-0 right-0 flex h-16 w-30 items-start justify-end bg-linear-65 from-components-card-bg-alt-transparent to-components-card-bg-alt to-75% p-2 opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 has-data-popup-open:opacity-100 [@media(hover:none)]:opacity-100">
- <div className="pointer-events-auto flex items-center overflow-hidden rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-lg backdrop-blur-xs">
- <DropdownMenu modal={false}>
- <DropdownMenuTrigger
- render={
- <IconButton
- aria-label={tCommon(($) => $['operation.more'])}
- size="lg"
- className="data-popup-open:bg-state-base-hover"
- >
- <span aria-hidden className="i-ri-more-fill size-4.5" />
- </IconButton>
- }
- />
- <DropdownMenuContent className="min-w-46.5">
- {canEdit && (
- <DropdownMenuLinkItem
- render={<Link href={newKnowledgeSettingsPath(knowledgeSpace.control_space_id)} />}
- >
- <span aria-hidden className="mr-1 i-ri-edit-line size-4 text-text-tertiary" />
- {tCommon(($) => $['operation.edit'])}
- </DropdownMenuLinkItem>
- )}
- {canDelete && (
- <>
- {canEdit && <DropdownMenuSeparator />}
- <DropdownMenuItem variant="destructive" onClick={() => setDeleteOpen(true)}>
- <span aria-hidden className="mr-1 i-ri-delete-bin-line size-4" />
- {tCommon(($) => $['operation.delete'])}
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
-
- <AlertDialog
- open={deleteOpen}
- onOpenChange={(open, details) => {
- if (!open && deleteMutation.isPending) details.cancel()
- else setDeleteOpen(open)
- }}
- onOpenChangeComplete={(open) => {
- if (!open) deleteMutation.reset()
- }}
- >
- <AlertDialogContent>
- <DeleteKnowledgeForm
- knowledgeName={name}
- isPending={deleteMutation.isPending}
- error={deleteError}
- onSubmit={() =>
- deleteMutation.mutate({
- params: { control_space_id: knowledgeSpace.control_space_id },
- })
+ <div className="pointer-events-none absolute top-0 right-0 flex h-16 w-30 items-start justify-end bg-linear-65 from-components-card-bg-alt-transparent to-components-card-bg-alt to-75% p-2 opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 has-data-popup-open:opacity-100 [@media(hover:none)]:opacity-100">
+ <div className="pointer-events-auto flex items-center overflow-hidden rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-lg backdrop-blur-xs">
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ aria-label={tCommon(($) => $['operation.more'])}
+ size="lg"
+ className="data-popup-open:bg-state-base-hover"
+ >
+ <span aria-hidden className="i-ri-more-fill size-4.5" />
+ </IconButton>
}
/>
- </AlertDialogContent>
- </AlertDialog>
- </>
+ <DropdownMenuContent className="min-w-46.5">
+ {canEdit && (
+ <DropdownMenuLinkItem
+ render={<Link href={newKnowledgeSettingsPath(knowledgeSpace.control_space_id)} />}
+ >
+ <span aria-hidden className="mr-1 i-ri-edit-line size-4 text-text-tertiary" />
+ {tCommon(($) => $['operation.edit'])}
+ </DropdownMenuLinkItem>
+ )}
+ {canDelete && (
+ <>
+ {canEdit && <DropdownMenuSeparator />}
+ <DropdownMenuItem variant="destructive" onClick={onDelete}>
+ <span aria-hidden className="mr-1 i-ri-delete-bin-line size-4" />
+ {tCommon(($) => $['operation.delete'])}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
)
}
diff --git a/web/features/new-rag/list/knowledge-space-card.tsx b/web/features/new-rag/list/knowledge-space-card.tsx
index b688241cfeb..dfb0e29e3e3 100644
--- a/web/features/new-rag/list/knowledge-space-card.tsx
+++ b/web/features/new-rag/list/knowledge-space-card.tsx
@@ -1,6 +1,6 @@
import type { KnowledgeFsSpaceListItemResponse } from '@dify/contracts/api/console/knowledge-fs/types.gen'
import { cn } from '@langgenius/dify-ui/cn'
-import { useId } from 'react'
+import { useId, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import Link from '@/next/link'
@@ -16,15 +16,18 @@ function getBuiltinIconName(iconRef: string | undefined) {
export function KnowledgeSpaceCard({
knowledgeSpace,
+ onDelete,
onOpenTagManagement,
highlighted = false,
}: {
knowledgeSpace: KnowledgeFsSpaceListItemResponse
+ onDelete: (item: HTMLLIElement | null) => void
onOpenTagManagement: () => void
highlighted?: boolean
}) {
const { t } = useTranslation(['knowledgeSpace', 'knowledgeOverview'])
const { formatTimeFromNow } = useFormatTimeFromNow()
+ const itemRef = useRef<HTMLLIElement>(null)
const nameId = useId()
const descriptionId = useId()
const linkedAppsDescriptionId = useId()
@@ -39,6 +42,7 @@ export function KnowledgeSpaceCard({
return (
<li
+ ref={itemRef}
className={cn(
"group relative isolate h-41.5 overflow-hidden rounded-xl bg-components-card-bg text-left transition-[background-color,box-shadow] after:pointer-events-none after:absolute after:inset-0 after:z-1 after:rounded-xl after:content-[''] focus-within:bg-components-card-bg-alt focus-within:[--color-tag-selector-mask-bg:var(--color-tag-selector-mask-hover-bg)] hover:bg-components-card-bg-alt hover:shadow-md hover:[--color-tag-selector-mask-bg:var(--color-tag-selector-mask-hover-bg)] has-data-popup-open:bg-components-card-bg-alt has-data-popup-open:[--color-tag-selector-mask-bg:var(--color-tag-selector-mask-hover-bg)] has-[>a:focus-visible]:after:inset-ring-2 has-[>a:focus-visible]:after:inset-ring-state-accent-solid motion-reduce:transition-none [@media(hover:none)]:bg-components-card-bg-alt [@media(hover:none)]:[--color-tag-selector-mask-bg:var(--color-tag-selector-mask-hover-bg)]",
highlighted
@@ -97,7 +101,10 @@ export function KnowledgeSpaceCard({
onOpenTagManagement={onOpenTagManagement}
/>
</div>
- <KnowledgeSpaceActions knowledgeSpace={knowledgeSpace} />
+ <KnowledgeSpaceActions
+ knowledgeSpace={knowledgeSpace}
+ onDelete={() => onDelete(itemRef.current)}
+ />
</li>
)
}
diff --git a/web/features/new-rag/list/new-knowledge-list.tsx b/web/features/new-rag/list/new-knowledge-list.tsx
index 85450b24309..d65c53c3caf 100644
--- a/web/features/new-rag/list/new-knowledge-list.tsx
+++ b/web/features/new-rag/list/new-knowledge-list.tsx
@@ -1,13 +1,24 @@
'use client'
import type { KnowledgeUpgrade } from '../upgrade/knowledge-upgrade-context-value'
+import {
+ AlertDialog,
+ AlertDialogContent,
+ createAlertDialogHandle,
+} from '@langgenius/dify-ui/alert-dialog'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import { useInfiniteQuery, useQueries, useQuery, useQueryClient } from '@tanstack/react-query'
+import {
+ useInfiniteQuery,
+ useMutation,
+ useQueries,
+ useQuery,
+ useQueryClient,
+} from '@tanstack/react-query'
import { useDebounce } from 'ahooks'
import { useAtomValue } from 'jotai'
import { createParser, parseAsString, useQueryState } from 'nuqs'
-import { useEffect, useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { SearchInput } from '@/app/components/base/search-input'
import { CreatorFilter } from '@/app/components/datasets/creator-filter'
@@ -22,7 +33,9 @@ import { TagManagementModal } from '@/features/tag-management/components/tag-man
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
import { getHttpErrorStatus } from '@/service/http-error'
+import { getAdjacentFocusTargets } from '@/utils/get-adjacent-focus-targets'
import { hasPermission } from '@/utils/permission'
+import { DeleteKnowledgeForm } from '../delete-knowledge-form'
import { KnowledgeUpgradeCard } from '../upgrade/knowledge-upgrade-card'
import { useKnowledgeUpgrade } from '../upgrade/knowledge-upgrade-context-value'
import { matchesKnowledgeUpgradeFilters } from '../upgrade/knowledge-upgrade-filters'
@@ -96,6 +109,20 @@ export function NewKnowledgeList({
const { t } = useTranslation(['knowledgeSpace', 'dataset'])
const { t: tCommon } = useTranslation(['common'])
const queryClient = useQueryClient()
+ const listRef = useRef<HTMLElement>(null)
+ const [deleteDialog] = useState(() =>
+ createAlertDialogHandle<{
+ id: string
+ name: string
+ adjacentFocusTargets: HTMLElement[]
+ fallbackFocus: { current: HTMLElement | null }
+ }>(),
+ )
+ const deletion = useMutation(
+ consoleQuery.knowledgeFs.spaces.byControlSpaceId.delete.mutationOptions({
+ context: { silent: true },
+ }),
+ )
const docLink = useDocLink()
const { data: apiBaseInfo } = useQuery(consoleQuery.datasets.apiBaseInfo.get.queryOptions())
const [showExternalApiPanel, setShowExternalApiPanel] = useState(false)
@@ -241,8 +268,10 @@ export function NewKnowledgeList({
return (
<section
+ ref={listRef}
+ tabIndex={-1}
aria-label={t(($) => $.new)}
- className="relative flex grow flex-col overflow-y-auto bg-background-body"
+ className="relative flex grow flex-col overflow-y-auto bg-background-body focus-visible:outline-2 focus-visible:outline-state-accent-solid"
>
<header className="sticky top-0 z-10 flex flex-col gap-3.5 bg-background-body px-4 pt-4 pb-2 sm:px-8">
<div className="flex min-h-6 flex-wrap items-center justify-between gap-2">
@@ -406,6 +435,17 @@ export function NewKnowledgeList({
<KnowledgeSpaceCard
key={knowledgeSpace.control_space_id}
knowledgeSpace={knowledgeSpace}
+ onDelete={(item) =>
+ deleteDialog.openWithPayload({
+ id: knowledgeSpace.control_space_id,
+ name:
+ knowledgeSpace.technical_summary?.name ?? knowledgeSpace.control_space_id,
+ adjacentFocusTargets: getAdjacentFocusTargets(item, (sibling) =>
+ sibling.querySelector<HTMLElement>(':scope > a[href], :scope > button'),
+ ),
+ fallbackFocus: { current: null },
+ })
+ }
highlighted={highlightedControlSpaceId === knowledgeSpace.control_space_id}
onOpenTagManagement={() => setShowTagManagementModal(true)}
/>
@@ -431,6 +471,55 @@ export function NewKnowledgeList({
</div>
)}
</div>
+ <AlertDialog
+ handle={deleteDialog}
+ onOpenChange={(open, details) => {
+ if (!open && deletion.isPending && details.reason !== 'imperative-action')
+ details.cancel()
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) deletion.reset()
+ }}
+ >
+ {({ payload }) => (
+ <AlertDialogContent
+ finalFocus={() => {
+ const fallback = payload?.fallbackFocus.current
+ if (!fallback) return true
+ const target =
+ payload.adjacentFocusTargets.find((element) => element.isConnected) ?? fallback
+ target.focus({ preventScroll: true })
+ return false
+ }}
+ >
+ {payload && (
+ <DeleteKnowledgeForm
+ knowledgeName={payload.name}
+ isPending={deletion.isPending}
+ error={
+ deletion.error
+ ? getHttpErrorStatus(deletion.error) !== undefined
+ ? deletion.error.message
+ : tCommon(($) => $['api.actionFailed'])
+ : undefined
+ }
+ onSubmit={() => {
+ if (deletion.isPending) return
+ deletion.mutate(
+ { params: { control_space_id: payload.id } },
+ {
+ onSuccess: () => {
+ payload.fallbackFocus.current = listRef.current
+ deleteDialog.close()
+ },
+ },
+ )
+ }}
+ />
+ )}
+ </AlertDialogContent>
+ )}
+ </AlertDialog>
<TagManagementModal
type="knowledge"
show={showTagManagementModal}
diff --git a/web/i18n/locales/ar-TN/dataset.json b/web/i18n/locales/ar-TN/dataset.json
index 69f209f1003..e0b50fd3b99 100644
--- a/web/i18n/locales/ar-TN/dataset.json
+++ b/web/i18n/locales/ar-TN/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "إنشاء واجهة برمجة تطبيقات معرفة خارجية جديدة",
"creatorFilter.creators": "المنشئون",
"creatorFilter.maxCreators": "الحد الأقصى لعدد المنشئين",
- "datasetDeleted": "تم حذف المعرفة",
"datasetUsedByApp": "يتم استخدام المعرفة بواسطة بعض التطبيقات. لن تتمكن التطبيقات بعد الآن من استخدام هذه المعرفة، وسيتم حذف جميع تكوينات الموجه والسجلات بشكل دائم.",
"defaultRetrievalTip": "يستخدم الاسترجاع متعدد المسارات افتراضيًا. يتم استرجاع المعرفة من قواعد معرفة متعددة ثم إعادة ترتيبها.",
"deleteDatasetConfirmContent": "حذف المعرفة لا رجعة فيه. لن يتمكن المستخدمون بعد الآن من الوصول إلى معرفتك، وسيتم حذف جميع تكوينات الموجه والسجلات بشكل دائم.",
diff --git a/web/i18n/locales/az-AZ/dataset.json b/web/i18n/locales/az-AZ/dataset.json
index 040da7d98c4..01c43e5a04f 100644
--- a/web/i18n/locales/az-AZ/dataset.json
+++ b/web/i18n/locales/az-AZ/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Yeni xarici bilik API-si yarat",
"creatorFilter.creators": "Yaradıcılar",
"creatorFilter.maxCreators": "Maksimum yaradıcı sayı",
- "datasetDeleted": "Biliklər silindi",
"datasetUsedByApp": "Bəzi tətbiqlər bu biliklərdən istifadə edir. Tətbiqlər artıq bu biliklərdən istifadə edə bilməyəcək, bütün təlimat konfiqurasiyaları və jurnallar həmişəlik silinəcək.",
"defaultRetrievalTip": "Standart olaraq çoxistiqamətli məlumat axtarışından istifadə edilir. Biliklər bir neçə bilik bazasından əldə edilir və sonra yenidən sıralanır.",
"deleteDatasetConfirmContent": "Biliklərin silinməsi geri qaytarıla bilməz. İstifadəçilər artıq biliklərinizə daxil ola bilməyəcək, bütün təlimat konfiqurasiyaları və jurnallar həmişəlik silinəcək.",
diff --git a/web/i18n/locales/de-DE/dataset.json b/web/i18n/locales/de-DE/dataset.json
index f8f167cf07b..91f316b0ce5 100644
--- a/web/i18n/locales/de-DE/dataset.json
+++ b/web/i18n/locales/de-DE/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Erstellen einer neuen API für externes Wissen",
"creatorFilter.creators": "Ersteller",
"creatorFilter.maxCreators": "Maximale Anzahl an Erstellern",
- "datasetDeleted": "Wissen gelöscht",
"datasetUsedByApp": "Das Wissen wird von einigen Apps verwendet. Apps werden dieses Wissen nicht mehr nutzen können, und alle Prompt-Konfigurationen und Protokolle werden dauerhaft gelöscht.",
"defaultRetrievalTip": "Standardmäßig wird der Multi-Path-Abruf verwendet. Das Wissen wird aus mehreren Wissensdatenbanken abgerufen und dann neu eingestuft.",
"deleteDatasetConfirmContent": "Das Löschen des Wissens ist unwiderruflich. Benutzer werden nicht mehr auf Ihr Wissen zugreifen können und alle Eingabeaufforderungen, Konfigurationen und Protokolle werden dauerhaft gelöscht.",
diff --git a/web/i18n/locales/en-US/dataset.json b/web/i18n/locales/en-US/dataset.json
index 62c1b9772ea..b18230400e4 100644
--- a/web/i18n/locales/en-US/dataset.json
+++ b/web/i18n/locales/en-US/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Create a new External Knowledge API",
"creatorFilter.creators": "Creators",
"creatorFilter.maxCreators": "Maximum creators",
- "datasetDeleted": "Knowledge deleted",
"datasetUsedByApp": "The knowledge is being used by some apps. Apps will no longer be able to use this Knowledge, and all prompt configurations and logs will be permanently deleted.",
"defaultRetrievalTip": "Multi-path retrieval is used by default. Knowledge is retrieved from multiple knowledge bases and then re-ranked.",
"deleteDatasetConfirmContent": "Deleting the Knowledge is irreversible. Users will no longer be able to access your Knowledge, and all prompt configurations and logs will be permanently deleted.",
diff --git a/web/i18n/locales/es-ES/dataset.json b/web/i18n/locales/es-ES/dataset.json
index 0c2637c8bba..56e2d37d381 100644
--- a/web/i18n/locales/es-ES/dataset.json
+++ b/web/i18n/locales/es-ES/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Creación de una nueva API de conocimiento externo",
"creatorFilter.creators": "Creadores",
"creatorFilter.maxCreators": "Máximo de creadores",
- "datasetDeleted": "Conocimiento eliminado",
"datasetUsedByApp": "El conocimiento está siendo utilizado por algunas aplicaciones. Las aplicaciones ya no podrán utilizar este Conocimiento y todas las configuraciones y registros de las sugerencias se eliminarán permanentemente.",
"defaultRetrievalTip": "De forma predeterminada, se utiliza la recuperación de varias rutas. El conocimiento se recupera de múltiples bases de conocimiento y luego se vuelve a clasificar.",
"deleteDatasetConfirmContent": "Eliminar el Conocimiento es irreversible. Los usuarios ya no podrán acceder a tu Conocimiento y todas las configuraciones y registros de las sugerencias se eliminarán permanentemente.",
diff --git a/web/i18n/locales/fa-IR/dataset.json b/web/i18n/locales/fa-IR/dataset.json
index 43b8698dc2e..64ca4f95968 100644
--- a/web/i18n/locales/fa-IR/dataset.json
+++ b/web/i18n/locales/fa-IR/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "ایجاد یک API دانش خارجی جدید",
"creatorFilter.creators": "ایجادکنندگان",
"creatorFilter.maxCreators": "حداکثر سازندگان",
- "datasetDeleted": "دانش حذف شد",
"datasetUsedByApp": "دانش توسط برخی برنامه‌ها استفاده می‌شود. برنامه‌ها دیگر نمی‌توانند از این دانش استفاده کنند و تمام تنظیمات درخواست و گزارش‌ها به طور دائم حذف خواهند شد.",
"defaultRetrievalTip": "بازیابی چند مسیره به طور پیش فرض استفاده می شود. دانش از چندین پایگاه دانش بازیابی می شود و سپس دوباره رتبه بندی می شود.",
"deleteDatasetConfirmContent": "حذف دانش غیر قابل برگشت است. کاربران دیگر نمی‌توانند به دانش شما دسترسی پیدا کنند و تمام تنظیمات درخواست و گزارش‌ها به طور دائم حذف خواهند شد.",
diff --git a/web/i18n/locales/fr-FR/dataset.json b/web/i18n/locales/fr-FR/dataset.json
index a18a832e647..9bd82dd6a3b 100644
--- a/web/i18n/locales/fr-FR/dataset.json
+++ b/web/i18n/locales/fr-FR/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Créer une API de connaissances externe",
"creatorFilter.creators": "Créateurs",
"creatorFilter.maxCreators": "Nombre maximal de créateurs",
- "datasetDeleted": "Connaissance supprimée",
"datasetUsedByApp": "La connaissance est utilisée par certaines applications. Les applications ne pourront plus utiliser cette Connaissance, et toutes les configurations de prompts et les journaux seront définitivement supprimés.",
"defaultRetrievalTip": "La récupération à chemins multiples est utilisée par défaut. Les connaissances sont extraites de plusieurs bases de connaissances, puis reclassées.",
"deleteDatasetConfirmContent": "La suppression de la Connaissance est irréversible. Les utilisateurs ne pourront plus accéder à votre Savoir, et toutes les configurations de prompt et les journaux seront supprimés de façon permanente.",
diff --git a/web/i18n/locales/hi-IN/dataset.json b/web/i18n/locales/hi-IN/dataset.json
index 07aaf66a729..be177f8bf94 100644
--- a/web/i18n/locales/hi-IN/dataset.json
+++ b/web/i18n/locales/hi-IN/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "एक नया बाहरी नॉलेज API बनाएँ",
"creatorFilter.creators": "निर्माता",
"creatorFilter.maxCreators": "अधिकतम निर्माता",
- "datasetDeleted": "ज्ञान हटा दिया गया",
"datasetUsedByApp": "यह ज्ञान कुछ ऐप्स द्वारा उपयोग किया जा रहा है। ऐप्स अब इस ज्ञान का उपयोग नहीं कर पाएंगे, और सभी प्रॉम्प्ट कॉन्फ़िगरेशन और लॉग स्थायी रूप से हटा दिए जाएंगे।",
"defaultRetrievalTip": "मल्टी-पाथ रिट्रीवल का उपयोग डिफ़ॉल्ट रूप से किया जाता है। ज्ञान को कई ज्ञान आधारों से पुनर्प्राप्त किया जाता है और फिर फिर से रैंक किया जाता है।",
"deleteDatasetConfirmContent": "ज्ञान को हटाना अपरिवर्तनीय है। उपयोगकर्ता अब आपके ज्ञान को प्राप्त नहीं कर पाएंगे, और सभी प्रॉम्प्ट कॉन्फ़िगरेशन और लॉग स्थायी रूप से मिटा दिए जाएंगे।",
diff --git a/web/i18n/locales/id-ID/dataset.json b/web/i18n/locales/id-ID/dataset.json
index 640e2ec5409..514df5cea2f 100644
--- a/web/i18n/locales/id-ID/dataset.json
+++ b/web/i18n/locales/id-ID/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Membuat API Pengetahuan Eksternal baru",
"creatorFilter.creators": "Pembuat",
"creatorFilter.maxCreators": "Pembuat maksimum",
- "datasetDeleted": "Pengetahuan dihapus",
"datasetUsedByApp": "Pengetahuan tersebut digunakan oleh beberapa aplikasi. Aplikasi tidak akan lagi dapat menggunakan Pengetahuan ini, dan semua konfigurasi prompt serta log akan dihapus secara permanen.",
"defaultRetrievalTip": "Pengambilan multi-jalur digunakan secara default. Pengetahuan diambil dari beberapa basis pengetahuan dan kemudian diberi peringkat ulang.",
"deleteDatasetConfirmContent": "Menghapus Pengetahuan tidak dapat diubah. Pengguna tidak akan lagi dapat mengakses Pengetahuan Anda, dan semua konfigurasi prompt dan log akan dihapus secara permanen.",
diff --git a/web/i18n/locales/it-IT/dataset.json b/web/i18n/locales/it-IT/dataset.json
index 4678173b0eb..60e78c1a007 100644
--- a/web/i18n/locales/it-IT/dataset.json
+++ b/web/i18n/locales/it-IT/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Creare una nuova API della conoscenza esterna",
"creatorFilter.creators": "Autori",
"creatorFilter.maxCreators": "Numero massimo di autori",
- "datasetDeleted": "Conoscenza eliminata",
"datasetUsedByApp": "La Conoscenza è utilizzata da alcune app. Le app non potranno più utilizzare questa Conoscenza e tutte le configurazioni dei prompt e i log verranno eliminati permanentemente.",
"defaultRetrievalTip": "Per impostazione predefinita, il recupero a percorsi multipli viene utilizzato. Le informazioni vengono recuperate da più knowledge base e quindi riclassificate.",
"deleteDatasetConfirmContent": "L'eliminazione della Conoscenza è irreversibile. Gli utenti non potranno più accedere alla tua Conoscenza e tutte le configurazioni dei prompt e i log verranno eliminati permanentemente.",
diff --git a/web/i18n/locales/ja-JP/dataset.json b/web/i18n/locales/ja-JP/dataset.json
index 3f912b6ce6f..5e962ddcc28 100644
--- a/web/i18n/locales/ja-JP/dataset.json
+++ b/web/i18n/locales/ja-JP/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "新しい外部ナレッジベース連携 API を作成",
"creatorFilter.creators": "作成者",
"creatorFilter.maxCreators": "最大作成者数",
- "datasetDeleted": "ナレッジベースが削除されました",
"datasetUsedByApp": "このナレッジベースは一部のアプリによって使用されています。アプリはこのナレッジベースを使用できなくなり、すべてのプロンプト設定とログは永久に削除されます。",
"defaultRetrievalTip": "デフォルトでは、マルチパス検索が使用されます。複数のナレッジベースから情報を取得した後、再ランキングを行います。",
"deleteDatasetConfirmContent": "ナレッジベースを削除すると元に戻すことはできません。ユーザーはもはやあなたのナレッジベースにアクセスできず、すべてのプロンプトの設定とログが永久に削除されます。",
diff --git a/web/i18n/locales/ko-KR/dataset.json b/web/i18n/locales/ko-KR/dataset.json
index c638a393376..627917c813c 100644
--- a/web/i18n/locales/ko-KR/dataset.json
+++ b/web/i18n/locales/ko-KR/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "새 외부 지식 API 만들기",
"creatorFilter.creators": "생성자",
"creatorFilter.maxCreators": "최대 생성자 수",
- "datasetDeleted": "지식이 삭제되었습니다",
"datasetUsedByApp": "이 지식은 일부 앱에서 사용 중입니다. 앱에서 더 이상 이 지식을 사용할 수 없게 되며, 모든 프롬프트 구성 및 로그가 영구적으로 삭제됩니다.",
"defaultRetrievalTip": "다중 경로 검색이 기본적으로 사용됩니다. 지식은 여러 기술 자료에서 검색된 다음 순위가 다시 매겨집니다.",
"deleteDatasetConfirmContent": "지식을 삭제하면 다시 되돌릴 수 없습니다. 사용자는 더 이상 귀하의 지식에 액세스할 수 없으며 모든 프롬프트 설정과 로그가 영구적으로 삭제됩니다.",
diff --git a/web/i18n/locales/lo-LA/dataset.json b/web/i18n/locales/lo-LA/dataset.json
index c887af19143..ba3ae2f39f1 100644
--- a/web/i18n/locales/lo-LA/dataset.json
+++ b/web/i18n/locales/lo-LA/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "ສ້າງ API ຄວາມຮູ້ພາຍນອກໃໝ່",
"creatorFilter.creators": "ຜູ້ສ້າງ",
"creatorFilter.maxCreators": "ຈຳນວນຜູ້ສ້າງສູງສຸດ",
- "datasetDeleted": "ລຶບຄວາມຮູ້ແລ້ວ",
"datasetUsedByApp": "ຄວາມຮູ້ນີ້ກຳລັງຖືກນຳໃຊ້ໂດຍບາງແອັບ. ແອັບຕ່າງໆຈະບໍ່ສາມາດໃຊ້ຄວາມຮູ້ນີ້ໄດ້ອີກຕໍ່ໄປ, ແລະ ການຕັ້ງຄ່າຄຳສັ່ງ (prompt) ພ້ອມທັງບັນທຶກທັງໝົດຈະຖືກລຶບຖາວອນ.",
"defaultRetrievalTip": "ການດຶງຂໍ້ມູນແບບຫຼາຍທາງ (Multi-path) ຖືກໃຊ້ເປັນຄ່າເລີ່ມຕົ້ນ. ຄວາມຮູ້ຈະຖືກດຶງມາຈາກຫຼາຍຖານຄວາມຮູ້ແລ້ວຈຶ່ງຈັດລໍາດັບໃໝ່.",
"deleteDatasetConfirmContent": "ການລຶບຄວາມຮູ້ແມ່ນບໍ່ສາມາດເອົາຄືນໄດ້. ຜູ້ໃຊ້ຈະບໍ່ສາມາດເຂົ້າເຖິງຄວາມຮູ້ຂອງທ່ານໄດ້ອີກຕໍ່ໄປ, ແລະ ການຕັ້ງຄ່າຄຳສັ່ງ (prompt) ພ້ອມທັງບັນທຶກທັງໝົດຈະຖືກລຶບຖາວອນ.",
diff --git a/web/i18n/locales/nl-NL/dataset.json b/web/i18n/locales/nl-NL/dataset.json
index 57a1947fae3..b33e756c019 100644
--- a/web/i18n/locales/nl-NL/dataset.json
+++ b/web/i18n/locales/nl-NL/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Create a new External Knowledge API",
"creatorFilter.creators": "Makers",
"creatorFilter.maxCreators": "Maximumaantal makers",
- "datasetDeleted": "Knowledge deleted",
"datasetUsedByApp": "The knowledge is being used by some apps. Apps will no longer be able to use this Knowledge, and all prompt configurations and logs will be permanently deleted.",
"defaultRetrievalTip": "Multi-path retrieval is used by default. Knowledge is retrieved from multiple knowledge bases and then re-ranked.",
"deleteDatasetConfirmContent": "Deleting the Knowledge is irreversible. Users will no longer be able to access your Knowledge, and all prompt configurations and logs will be permanently deleted.",
diff --git a/web/i18n/locales/pl-PL/dataset.json b/web/i18n/locales/pl-PL/dataset.json
index f1c929c5915..9d705eefe36 100644
--- a/web/i18n/locales/pl-PL/dataset.json
+++ b/web/i18n/locales/pl-PL/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Tworzenie nowego interfejsu API wiedzy zewnętrznej",
"creatorFilter.creators": "Twórcy",
"creatorFilter.maxCreators": "Maksymalna liczba twórców",
- "datasetDeleted": "Wiedza usunięta",
"datasetUsedByApp": "Ta wiedza jest wykorzystywana przez niektóre aplikacje. Aplikacje nie będą już mogły korzystać z tej Wiedzy, a wszystkie konfiguracje podpowiedzi i logi zostaną trwale usunięte.",
"defaultRetrievalTip": "Pobieranie wielu ścieżek jest używane domyślnie. Wiedza jest pobierana z wielu baz wiedzy, a następnie ponownie klasyfikowana.",
"deleteDatasetConfirmContent": "Usunięcie Wiedzy jest nieodwracalne. Użytkownicy nie będą już mieli dostępu do Twojej Wiedzy, a wszystkie konfiguracje i logi zostaną trwale usunięte.",
diff --git a/web/i18n/locales/pt-BR/dataset.json b/web/i18n/locales/pt-BR/dataset.json
index d2255741f7b..30322cb4171 100644
--- a/web/i18n/locales/pt-BR/dataset.json
+++ b/web/i18n/locales/pt-BR/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Criar uma nova API de conhecimento externo",
"creatorFilter.creators": "Criadores",
"creatorFilter.maxCreators": "Máximo de criadores",
- "datasetDeleted": "Conhecimento excluído",
"datasetUsedByApp": "O conhecimento está sendo usado por alguns aplicativos. Os aplicativos não poderão mais usar esse Conhecimento, e todas as configurações de prompt e logs serão excluídos permanentemente.",
"defaultRetrievalTip": "A recuperação de vários caminhos é usada por padrão. O conhecimento é recuperado de várias bases de dados de conhecimento e, em seguida, reclassificado.",
"deleteDatasetConfirmContent": "A exclusão do Conhecimento é irreversível. Os usuários não poderão mais acessar seu Conhecimento e todas as configurações e registros de prompt serão excluídos permanentemente.",
diff --git a/web/i18n/locales/ro-RO/dataset.json b/web/i18n/locales/ro-RO/dataset.json
index 25540a19569..4ffbede33e4 100644
--- a/web/i18n/locales/ro-RO/dataset.json
+++ b/web/i18n/locales/ro-RO/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Creați un nou API de cunoștințe externe",
"creatorFilter.creators": "Creatori",
"creatorFilter.maxCreators": "Număr maxim de creatori",
- "datasetDeleted": "Cunoștințe șterse",
"datasetUsedByApp": "Cunoștințele sunt utilizate de unele aplicații. Aplicațiile nu vor mai putea utiliza aceste Cunoștințe, iar toate configurațiile de prompt și jurnalele vor fi șterse definitiv.",
"defaultRetrievalTip": "Recuperarea pe mai multe căi este utilizată în mod implicit. Cunoștințele sunt preluate din mai multe baze de cunoștințe și apoi reclasificate.",
"deleteDatasetConfirmContent": "Ștergerea Cunoștințelor este ireversibilă. Utilizatorii nu vor mai putea accesa Cunoștințele, iar toate configurațiile și jurnalele prompt vor fi șterse permanent.",
diff --git a/web/i18n/locales/ru-RU/dataset.json b/web/i18n/locales/ru-RU/dataset.json
index 7194cc79bcf..6264b748a10 100644
--- a/web/i18n/locales/ru-RU/dataset.json
+++ b/web/i18n/locales/ru-RU/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Создание нового API внешних знаний",
"creatorFilter.creators": "Создатели",
"creatorFilter.maxCreators": "Максимум создателей",
- "datasetDeleted": "База знаний удалена",
"datasetUsedByApp": "База знаний используется некоторыми приложениями. Приложения больше не смогут использовать эту базу знаний, и все настройки подсказок и журналы будут безвозвратно удалены.",
"defaultRetrievalTip": "По умолчанию используется многоканальная проверка. Знания извлекаются из нескольких баз знаний, а затем повторно ранжируются.",
"deleteDatasetConfirmContent": "Удаление базы знаний необратимо. Пользователи больше не смогут получить доступ к вашей базе знаний, и все настройки подсказок и журналы будут безвозвратно удалены.",
diff --git a/web/i18n/locales/sl-SI/dataset.json b/web/i18n/locales/sl-SI/dataset.json
index 71caf17837a..3e448f2192f 100644
--- a/web/i18n/locales/sl-SI/dataset.json
+++ b/web/i18n/locales/sl-SI/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Ustvari nov zunanji API za znanje",
"creatorFilter.creators": "Ustvarjalci",
"creatorFilter.maxCreators": "Največje število ustvarjalcev",
- "datasetDeleted": "Znanje izbrisano",
"datasetUsedByApp": "Znanje se uporablja v nekaterih aplikacijah. Aplikacije ne bodo več mogle uporabljati tega znanja, vse nastavitve pozivov in dnevniki bodo trajno izbrisani.",
"defaultRetrievalTip": "Privzeto se uporablja večpotno pridobivanje. Znanje se pridobiva iz več baz znanja in nato ponovno razvrsti.",
"deleteDatasetConfirmContent": "Brisanje znanja je nepovratno. Uporabniki do vašega znanja ne bodo več imeli dostopa, vse nastavitve pozivov in dnevniki bodo trajno izbrisani.",
diff --git a/web/i18n/locales/th-TH/dataset.json b/web/i18n/locales/th-TH/dataset.json
index 85e58bdb0c3..5e5cb415ad0 100644
--- a/web/i18n/locales/th-TH/dataset.json
+++ b/web/i18n/locales/th-TH/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "สร้าง API ความรู้ภายนอกใหม่",
"creatorFilter.creators": "ผู้สร้าง",
"creatorFilter.maxCreators": "จำนวนผู้สร้างสูงสุด",
- "datasetDeleted": "ลบความรู้",
"datasetUsedByApp": "ความรู้นี้ถูกใช้โดยบางแอป แอปจะไม่สามารถใช้ความรู้นี้ได้อีกต่อไป และการกําหนดค่าพร้อมท์และบันทึกทั้งหมดจะถูกลบอย่างถาวร",
"defaultRetrievalTip": "การดึงข้อมูลหลายเส้นทางจะถูกใช้โดยค่าเริ่มต้น ความรู้จะถูกดึงมาจากฐานความรู้หลายแห่งแล้วจัดอันดับใหม่",
"deleteDatasetConfirmContent": "การลบความรู้นั้นไม่สามารถย้อนกลับได้ ผู้ใช้จะไม่สามารถเข้าถึงความรู้ของคุณอีกต่อไป และการกําหนดค่าพร้อมท์และบันทึกทั้งหมดจะถูกลบอย่างถาวร",
diff --git a/web/i18n/locales/tr-TR/dataset.json b/web/i18n/locales/tr-TR/dataset.json
index a902b4a320c..bc1466d7734 100644
--- a/web/i18n/locales/tr-TR/dataset.json
+++ b/web/i18n/locales/tr-TR/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Yeni bir Harici Bilgi API'si oluşturma",
"creatorFilter.creators": "Oluşturanlar",
"creatorFilter.maxCreators": "En fazla oluşturan",
- "datasetDeleted": "Bilgi silindi",
"datasetUsedByApp": "Bilgi bazı uygulamalar tarafından kullanılıyor. Uygulamalar artık bu Bilgiyi kullanamayacak ve tüm prompt yapılandırmaları ve günlükler kalıcı olarak silinecektir.",
"defaultRetrievalTip": "Varsayılan olarak çok alma kullanılır. Bilgi, birden fazla bilgi tabanından alınır ve ardından yeniden sıralanır.",
"deleteDatasetConfirmContent": "Bilginin silinmesi geri alınamaz. Kullanıcılar artık Bilginize erişemeyecek ve tüm prompt yapılandırmaları ve günlükler kalıcı olarak silinecektir.",
diff --git a/web/i18n/locales/uk-UA/dataset.json b/web/i18n/locales/uk-UA/dataset.json
index 0c693488321..6bd623ca288 100644
--- a/web/i18n/locales/uk-UA/dataset.json
+++ b/web/i18n/locales/uk-UA/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Створення нового API зовнішніх знань",
"creatorFilter.creators": "Автори",
"creatorFilter.maxCreators": "Максимум авторів",
- "datasetDeleted": "Знання видалено",
"datasetUsedByApp": "Ці знання використовуються деякими додатками. Додатки більше не зможуть використовувати ці Знання, а всі конфігурації підказок та журнали будуть остаточно видалені.",
"defaultRetrievalTip": "За замовчуванням використовується отримання кількома шляхами. Знання витягуються з кількох баз знань, а потім заново ранжуються.",
"deleteDatasetConfirmContent": "Видалення \"Знання\" є незворотнім. Користувачі більше не матимуть доступу до Знань, а всі конфігурації підказок і журнали будуть безповоротно видалені.",
diff --git a/web/i18n/locales/vi-VN/dataset.json b/web/i18n/locales/vi-VN/dataset.json
index 792c2abadd3..c83bcf54231 100644
--- a/web/i18n/locales/vi-VN/dataset.json
+++ b/web/i18n/locales/vi-VN/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "Tạo API Kiến thức Bên ngoài mới",
"creatorFilter.creators": "Người tạo",
"creatorFilter.maxCreators": "Số người tạo tối đa",
- "datasetDeleted": "Bộ kiến thức đã được xóa",
"datasetUsedByApp": "Bộ kiến thức này đang được sử dụng bởi một số ứng dụng. Các ứng dụng sẽ không thể sử dụng bộ kiến thức này nữa, và tất cả cấu hình lời nhắc cùng nhật ký sẽ bị xóa vĩnh viễn.",
"defaultRetrievalTip": "Truy xuất nhiều đường dẫn được sử dụng theo mặc định. Kiến thức được lấy từ nhiều cơ sở kiến thức và sau đó được xếp hạng lại.",
"deleteDatasetConfirmContent": "Việc xóa bộ kiến thức là không thể hoàn tác. Người dùng sẽ không còn truy cập được vào bộ kiến thức của bạn, và tất cả cấu hình cùng nhật ký lời nhắc sẽ bị xóa vĩnh viễn.",
diff --git a/web/i18n/locales/zh-Hans/dataset.json b/web/i18n/locales/zh-Hans/dataset.json
index d72bda4e523..5e4329b59b9 100644
--- a/web/i18n/locales/zh-Hans/dataset.json
+++ b/web/i18n/locales/zh-Hans/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "创建新的外部知识库 API",
"creatorFilter.creators": "创建者",
"creatorFilter.maxCreators": "最大创建者数",
- "datasetDeleted": "知识库已删除",
"datasetUsedByApp": "某些应用正在使用该知识库。应用将无法再使用该知识库,所有的提示配置和日志将被永久删除。",
"defaultRetrievalTip": "默认情况下使用多路召回。从多个知识库中检索知识,然后重新排序。",
"deleteDatasetConfirmContent": "删除知识库是不可逆的。用户将无法再访问您的知识库,所有的提示配置和日志将被永久删除。",
diff --git a/web/i18n/locales/zh-Hant/dataset.json b/web/i18n/locales/zh-Hant/dataset.json
index 8767dd67db3..673338f8e81 100644
--- a/web/i18n/locales/zh-Hant/dataset.json
+++ b/web/i18n/locales/zh-Hant/dataset.json
@@ -32,7 +32,6 @@
"createNewExternalAPI": "創建新的外部知識 API",
"creatorFilter.creators": "建立者",
"creatorFilter.maxCreators": "建立者數上限",
- "datasetDeleted": "知識庫已刪除",
"datasetUsedByApp": "這些知識正被一些應用程序使用。應用程序將無法再使用這些知識,所有提示配置和日誌將被永久刪除。",
"defaultRetrievalTip": "默認情況下,使用多路徑檢索。從多個知識庫中檢索知識,然後重新排名。",
"deleteDatasetConfirmContent": "刪除知識庫是不可逆的。使用者將無法再訪問您的知識庫,所有的提示配置和日誌將被永久刪除。",
diff --git a/web/i18n/resources.generated.d.ts b/web/i18n/resources.generated.d.ts
index fb61075bf09..8cd543849c5 100644
--- a/web/i18n/resources.generated.d.ts
+++ b/web/i18n/resources.generated.d.ts
@@ -2077,7 +2077,6 @@ export default interface Resources {
createNewExternalAPI: 'Create a new External Knowledge API'
'creatorFilter.creators': 'Creators'
'creatorFilter.maxCreators': 'Maximum creators'
- datasetDeleted: 'Knowledge deleted'
datasetUsedByApp: 'The knowledge is being used by some apps. Apps will no longer be able to use this Knowledge, and all prompt configurations and logs will be permanently deleted.'
defaultRetrievalTip: 'Multi-path retrieval is used by default. Knowledge is retrieved from multiple knowledge bases and then re-ranked.'
deleteDatasetConfirmContent: 'Deleting the Knowledge is irreversible. Users will no longer be able to access your Knowledge, and all prompt configurations and logs will be permanently deleted.'
diff --git a/web/package.json b/web/package.json
index 208cd658c11..5f304fcbdaf 100644
--- a/web/package.json
+++ b/web/package.json
@@ -173,7 +173,6 @@
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"@types/sortablejs": "catalog:",
- "@typescript/native": "catalog:",
"@vitejs/plugin-react": "catalog:",
"@vitejs/plugin-rsc": "catalog:",
"@vitest/browser-playwright": "catalog:",
diff --git a/web/service/console/query-policies.ts b/web/service/console/query-policies.ts
index e43f78c25d6..3f4abaabe2b 100644
--- a/web/service/console/query-policies.ts
+++ b/web/service/console/query-policies.ts
@@ -4,8 +4,14 @@ import type {
} from '@dify/contracts/api/console/agent/types.gen'
import type { ApiBasedExtensionResponse } from '@dify/contracts/api/console/api-based-extension/types.gen'
import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'
+import type {
+ DatasetListResponse,
+ DocumentWithSegmentsListResponse,
+} from '@dify/contracts/api/console/datasets/types.gen'
+import type { KnowledgeFsSpaceListResponse } from '@dify/contracts/api/console/knowledge-fs/types.gen'
import type { TagResponse as Tag } from '@dify/contracts/api/console/tags/types.gen'
import type { GetWorkflowRunArchivesResponse } from '@dify/contracts/api/console/workflow-run-archives/types.gen'
+import type { AccountWithRoleListResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { RouterUtils } from '@orpc/tanstack-query'
import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/react-query'
import type { ConsoleClient } from './index'
@@ -347,6 +353,29 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
workspaces: {
current: {
+ members: {
+ byMemberId: {
+ delete: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) => {
+ context.client.setQueriesData(
+ { queryKey: consoleQuery.workspaces.current.members.get.key() },
+ (members: AccountWithRoleListResponse | undefined) =>
+ members && {
+ ...members,
+ accounts: members.accounts.filter(
+ (member) => member.id !== variables.params.member_id,
+ ),
+ },
+ )
+ void context.client.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.members.get.key(),
+ })
+ },
+ },
+ },
+ },
+ },
toolProvider: {
builtin: {
byProvider: {
@@ -1497,10 +1526,108 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
},
},
+ knowledgeFs: {
+ spaces: {
+ byControlSpaceId: {
+ delete: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) => {
+ context.client.setQueriesData(
+ { queryKey: consoleQuery.knowledgeFs.spaces.get.key({ type: 'query' }) },
+ (list: KnowledgeFsSpaceListResponse | undefined) => {
+ if (
+ !list?.data.some(
+ (item) => item.control_space_id === variables.params.control_space_id,
+ )
+ )
+ return list
+ return {
+ ...list,
+ data: list.data.filter(
+ (item) => item.control_space_id !== variables.params.control_space_id,
+ ),
+ }
+ },
+ )
+ context.client.setQueriesData(
+ { queryKey: consoleQuery.knowledgeFs.spaces.get.key({ type: 'infinite' }) },
+ (list: InfiniteData<KnowledgeFsSpaceListResponse, unknown> | undefined) => {
+ if (
+ !list?.pages.some((page) =>
+ page.data.some(
+ (item) => item.control_space_id === variables.params.control_space_id,
+ ),
+ )
+ )
+ return list
+ return {
+ ...list,
+ pages: list.pages.map((page) => ({
+ ...page,
+ data: page.data.filter(
+ (item) => item.control_space_id !== variables.params.control_space_id,
+ ),
+ })),
+ }
+ },
+ )
+ void context.client.invalidateQueries({
+ queryKey: consoleQuery.knowledgeFs.spaces.get.key(),
+ })
+ },
+ },
+ },
+ },
+ },
+ },
datasets: {
// Process rules are read once to describe a running import.
processRule: { get: { queryOptions: { refetchOnWindowFocus: false } } },
byDatasetId: {
+ delete: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) => {
+ context.client.setQueriesData(
+ { queryKey: consoleQuery.datasets.get.key({ type: 'query' }) },
+ (list: DatasetListResponse | undefined) => {
+ if (!list?.data.some((item) => item.id === variables.params.dataset_id))
+ return list
+ const total = Math.max(0, list.total - 1)
+ return {
+ ...list,
+ data: list.data.filter((item) => item.id !== variables.params.dataset_id),
+ total,
+ has_more: list.page * list.limit < total,
+ }
+ },
+ )
+ context.client.setQueriesData(
+ { queryKey: consoleQuery.datasets.get.key({ type: 'infinite' }) },
+ (list: InfiniteData<DatasetListResponse, unknown> | undefined) => {
+ if (
+ !list?.pages.some((page) =>
+ page.data.some((item) => item.id === variables.params.dataset_id),
+ )
+ )
+ return list
+ return {
+ ...list,
+ pages: list.pages.map((page) => {
+ const total = Math.max(0, page.total - 1)
+ return {
+ ...page,
+ data: page.data.filter((item) => item.id !== variables.params.dataset_id),
+ total,
+ has_more: page.page * page.limit < total,
+ }
+ }),
+ }
+ },
+ )
+ void context.client.invalidateQueries({ queryKey: consoleQuery.datasets.get.key() })
+ },
+ },
+ },
get: {
queryOptions: {
// A missing or inaccessible dataset sends the detail page back to the list.
@@ -1513,6 +1640,32 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
},
documents: {
+ delete: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) => {
+ const documentIds = new Set(variables.query?.document_id ?? [])
+ const input = { params: variables.params }
+ context.client.setQueriesData(
+ {
+ queryKey: consoleQuery.datasets.byDatasetId.documents.get.key({
+ type: 'query',
+ input,
+ }),
+ },
+ (list: DocumentWithSegmentsListResponse | undefined) => {
+ if (!list) return list
+ const data = list.data.filter((document) => !documentIds.has(document.id))
+ if (data.length === list.data.length) return list
+ const total = Math.max(0, list.total - (list.data.length - data.length))
+ return { ...list, data, total, has_more: list.page * list.limit < total }
+ },
+ )
+ void context.client.invalidateQueries({
+ queryKey: consoleQuery.datasets.byDatasetId.documents.get.key({ input }),
+ })
+ },
+ },
+ },
byDocumentId: {
pipelineExecutionLog: { get: { queryOptions: { staleTime: 0 } } },
},
diff --git a/web/service/datasets.ts b/web/service/datasets.ts
index c0c9ecfc95a..b9d301aff2d 100644
--- a/web/service/datasets.ts
+++ b/web/service/datasets.ts
@@ -44,17 +44,6 @@ export const createEmptyDataset = ({ name }: { name: string }) => {
return consoleClient.datasets.post({ body: { name } })
}
-export const checkIsUsedInApp = (id: string) => {
- return consoleClient.datasets.byDatasetId.useCheck.get(
- { params: { dataset_id: id } },
- { context: { silent: true } },
- )
-}
-
-export const deleteDataset = (datasetID: string) => {
- return consoleClient.datasets.byDatasetId.delete({ params: { dataset_id: datasetID } })
-}
-
export const fetchExternalAPI = ({ apiTemplateId }: { apiTemplateId: string }) => {
return consoleClient.datasets.externalKnowledgeApi.byExternalKnowledgeApiId.get({
params: { external_knowledge_api_id: apiTemplateId },
diff --git a/web/utils/get-adjacent-focus-targets.spec.ts b/web/utils/get-adjacent-focus-targets.spec.ts
new file mode 100644
index 00000000000..1d12013a233
--- /dev/null
+++ b/web/utils/get-adjacent-focus-targets.spec.ts
@@ -0,0 +1,35 @@
+import { getAdjacentFocusTargets } from './get-adjacent-focus-targets'
+
+it('orders sibling targets after the source first, then before it from nearest to farthest', () => {
+ const list = document.createElement('div')
+ list.innerHTML =
+ '<section><button>A</button></section><section><button>B</button></section><section><button>C</button></section><section><button>D</button></section><section><button>E</button></section>'
+ const source = list.children[2]!
+ const targets = getAdjacentFocusTargets(source, (item) => item.querySelector('button'))
+
+ expectTypeOf(targets).toEqualTypeOf<HTMLButtonElement[]>()
+ expect(targets.map((target) => target.textContent)).toEqual(['D', 'E', 'B', 'A'])
+})
+
+it('lets the owner choose targets and skip siblings without one, without leaving the parent', () => {
+ const container = document.createElement('div')
+ container.innerHTML =
+ '<a href="/outside">Outside</a><table><tbody><tr><td><a href="/a">A</a></td></tr><tr><td>Source</td></tr><tr><td><button>Action</button></td></tr><tr><td><a href="/b">B</a></td></tr></tbody></table>'
+ const rows = container.querySelectorAll('tr')
+ const targets = getAdjacentFocusTargets(rows[1], (row) =>
+ row.querySelector<HTMLAnchorElement>('a[href]'),
+ )
+
+ expectTypeOf(targets).toEqualTypeOf<HTMLAnchorElement[]>()
+ expect(targets.map((target) => target.textContent)).toEqual(['B', 'A'])
+})
+
+it('returns no candidates for a missing source or one without siblings', () => {
+ const getTarget = (element: Element) => element.querySelector('button')
+ expect(getAdjacentFocusTargets(null, getTarget)).toEqual([])
+ expect(getAdjacentFocusTargets(undefined, getTarget)).toEqual([])
+ expect(getAdjacentFocusTargets(document.createElement('div'), getTarget)).toEqual([])
+ const parent = document.createElement('div')
+ parent.innerHTML = '<section><button>Only item</button></section>'
+ expect(getAdjacentFocusTargets(parent.firstElementChild, getTarget)).toEqual([])
+})
diff --git a/web/utils/get-adjacent-focus-targets.ts b/web/utils/get-adjacent-focus-targets.ts
new file mode 100644
index 00000000000..8aef4848ba3
--- /dev/null
+++ b/web/utils/get-adjacent-focus-targets.ts
@@ -0,0 +1,16 @@
+/** Capture candidates before the source item unmounts: following siblings, then preceding siblings in reverse. */
+export function getAdjacentFocusTargets<T extends HTMLElement>(
+ item: Element | null | undefined,
+ getTarget: (sibling: Element) => T | null,
+): T[] {
+ if (!item?.parentElement) return []
+
+ const siblings = Array.from(item.parentElement.children)
+ const index = siblings.indexOf(item)
+ const targets: T[] = []
+ for (const sibling of [...siblings.slice(index + 1), ...siblings.slice(0, index).reverse()]) {
+ const target = getTarget(sibling)
+ if (target) targets.push(target)
+ }
+ return targets
+}