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.

7.0 KB
Raw Blame
'use client'

import type { DatasetDetailWithPartialMembersResponse } from '@dify/contracts/api/console/datasets/types.gen'
import type { FC } from 'react'
import { cn } from '@langgenius/dify-ui/cn'
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import * as React from 'react'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import DatasetDetailContext from '@/context/dataset-detail'
import {
  workspacePermissionKeysAtom,
  workspacePermissionKeysLoadingAtom,
} from '@/context/permission-state'
import { currentWorkspaceLoadingAtom } from '@/context/workspace-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import useDocumentTitle from '@/hooks/use-document-title'
import { usePathname, useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { getHttpErrorStatus } from '@/service/http-error'
import { getDatasetACLCapabilities } from '@/utils/permission'

type IAppDetailLayoutProps = {
  children: React.ReactNode
  datasetId: string
}

const shouldRedirectToDatasetList = (error: unknown) => {
  const status = getHttpErrorStatus(error)
  return status === 403 || status === 404
}

const datasetDetailPageTitle = (pathname: string, t: ReturnType<typeof useTranslation>['t']) => {
  if (
    pathname.endsWith('/documents/create') ||
    pathname.endsWith('/documents/create-from-pipeline')
  )
    return t(($) => $['addDocuments.title'], { ns: 'datasetPipeline' })
  if (pathname.includes('/documents'))
    return t(($) => $['datasetMenus.documents'], { ns: 'common' })
  if (pathname.endsWith('/pipeline')) return t(($) => $['datasetMenus.pipeline'], { ns: 'common' })
  if (pathname.endsWith('/hitTesting'))
    return t(($) => $['datasetMenus.hitTesting'], { ns: 'common' })
  if (pathname.endsWith('/settings')) return t(($) => $['datasetMenus.settings'], { ns: 'common' })
  if (pathname.endsWith('/access-config'))
    return t(($) => $['settings.resourceAccess'], { ns: 'navigation' })
  if (pathname.endsWith('/api')) return t(($) => $['appMenus.apiAccess'], { ns: 'common' })

  return t(($) => $['menus.datasets'], { ns: 'navigation' })
}

const isDocumentDetailPath = (pathname: string) =>
  /^\/datasets\/[^/]+\/documents\/(?!create(?:-from-pipeline)?\/?$)[^/]+(?:\/settings)?\/?$/.test(
    pathname,
  )

const DatasetDetailPageTitle = ({ title }: { title: string }) => {
  useDocumentTitle(title)

  return null
}

const getDatasetRedirectionPath = (
  dataset: DatasetDetailWithPartialMembersResponse,
  datasetACLCapabilities: ReturnType<typeof getDatasetACLCapabilities>,
) => {
  if (dataset.provider === 'external') {
    if (datasetACLCapabilities.canRetrievalRecall) return `/datasets/${dataset.id}/hitTesting`

    return `/datasets/${dataset.id}/settings`
  }

  if (dataset.runtime_mode === 'rag_pipeline' && !dataset.is_published)
    return `/datasets/${dataset.id}/pipeline`

  return `/datasets/${dataset.id}/documents`
}

const DatasetDetailLayout: FC<IAppDetailLayoutProps> = (props) => {
  const { children, datasetId } = props
  const { t } = useTranslation(['common', 'datasetPipeline', 'navigation'])
  const router = useRouter()
  const pathname = usePathname()
  const isLoadingCurrentWorkspace = useAtomValue(currentWorkspaceLoadingAtom)
  const isLoadingWorkspacePermissionKeys = useAtomValue(workspacePermissionKeysLoadingAtom)
  const { data: isRbacEnabled } = useSuspenseQuery({
    ...systemFeaturesQueryOptions(),
    select: ({ rbac_enabled }) => rbac_enabled,
  })
  const { data: currentUserId } = useSuspenseQuery({
    ...userProfileQueryOptions(),
    select: (data) => data.profile.id,
  })
  const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)

  const {
    data: datasetRes,
    error,
    refetch: mutateDatasetRes,
  } = useQuery(
    consoleQuery.datasets.byDatasetId.get.queryOptions({
      input: { params: { dataset_id: datasetId } },
      enabled: !!datasetId,
    }),
  )
  const shouldRedirect = shouldRedirectToDatasetList(error)
  const datasetACLCapabilities = React.useMemo(
    () =>
      getDatasetACLCapabilities(datasetRes?.permission_keys, {
        currentUserId,
        resourceMaintainer: datasetRes?.maintainer,
        workspacePermissionKeys,
        isRbacEnabled,
      }),
    [
      datasetRes?.maintainer,
      datasetRes?.permission_keys,
      isRbacEnabled,
      currentUserId,
      workspacePermissionKeys,
    ],
  )
  const isAccessConfigPath = pathname.endsWith('/access-config')
  const isHitTestingPath = pathname.endsWith('/hitTesting')
  const isPermissionControlledPath = isAccessConfigPath || isHitTestingPath
  const isCheckingRouteAccess =
    !!datasetRes &&
    isPermissionControlledPath &&
    (isLoadingCurrentWorkspace || !!isLoadingWorkspacePermissionKeys)
  const shouldRedirectUnauthorizedRoute =
    !!datasetRes &&
    !isCheckingRouteAccess &&
    ((isAccessConfigPath && !datasetACLCapabilities.canAccessConfig) ||
      (isHitTestingPath && !datasetACLCapabilities.canRetrievalRecall))
  const pageTitle = datasetDetailPageTitle(pathname, t)
  const documentTitle = `${pageTitle} · ${datasetRes?.name || t(($) => $['menus.datasets'], { ns: 'navigation' })}`

  useEffect(() => {
    if (shouldRedirect) router.replace('/datasets')
  }, [router, shouldRedirect])

  useEffect(() => {
    if (!datasetRes || !shouldRedirectUnauthorizedRoute) return

    router.replace(getDatasetRedirectionPath(datasetRes, datasetACLCapabilities))
  }, [datasetACLCapabilities, datasetRes, router, shouldRedirectUnauthorizedRoute])

  const isPipelinePage =
    pathname.endsWith('/pipeline') || pathname.includes('/create-from-pipeline')
  const shouldShowLoading =
    (!datasetRes && !error) ||
    shouldRedirect ||
    isCheckingRouteAccess ||
    shouldRedirectUnauthorizedRoute
  const documentTitleOwnedByChild = isDocumentDetailPath(pathname) && !shouldShowLoading
  const content = shouldShowLoading ? (
    <LoadingPlaceholder className="h-full" />
  ) : (
    <div
      className={cn(
        'relative flex h-0 min-h-0 min-w-0 grow overflow-hidden',
        !isPipelinePage && 'pt-1 pr-1 pb-1',
      )}
    >
      <DatasetDetailContext.Provider
        value={{
          indexingTechnique: datasetRes?.indexing_technique ?? undefined,
          dataset: datasetRes,
          mutateDatasetRes,
        }}
      >
        <div
          className={cn(
            'min-w-0 grow overflow-hidden bg-components-panel-bg',
            !isPipelinePage && 'rounded-lg shadow-xs shadow-shadow-shadow-3',
          )}
        >
          {children}
        </div>
      </DatasetDetailContext.Provider>
    </div>
  )

  return (
    <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background-body">
      {!documentTitleOwnedByChild && <DatasetDetailPageTitle title={documentTitle} />}
      {content}
    </div>
  )
}
export default React.memo(DatasetDetailLayout)