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.

13.2 KB
Raw Blame
'use client'
import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
import type { FC } from 'react'
import type { BuiltInMetadataItem, MetadataItemWithValueLength } from '../types'
import {
  AlertDialog,
  AlertDialogCancelButton,
  AlertDialogConfirmButton,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@langgenius/dify-ui/dialog'
import {
  Drawer,
  DrawerBackdrop,
  DrawerClose,
  DrawerContent,
  DrawerPopup,
  DrawerPortal,
  DrawerTitle,
  DrawerViewport,
} from '@langgenius/dify-ui/drawer'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import { Input } from '@langgenius/dify-ui/input'
import { Switch } from '@langgenius/dify-ui/switch'
import { useHover } from 'ahooks'
import * as React from 'react'
import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { CreateMetadataModal } from '@/app/components/datasets/metadata/metadata-dataset/create-metadata-modal'
import { toast } from '@/app/notifications'
import { getIconClassName } from '../utils/get-icon'
import Field from './field'

const i18nPrefix = 'metadata.datasetMetadata'

type Props = Readonly<{
  userMetadata: MetadataItemWithValueLength[]
  builtInMetadata: BuiltInMetadataItem[]
  isBuiltInEnabled: boolean
  onIsBuiltInEnabledChange: (value: boolean) => void
  onClose: () => void
  onAdd: (payload: BuiltInMetadataItem) => void
  onRename: (payload: MetadataItemWithValueLength) => void
  onRemove: (metaDataId: string) => void
}>

type ItemProps = {
  readonly?: boolean
  disabled?: boolean
  payload: MetadataItemWithValueLength
  onRename?: () => void
  onDelete?: () => Promise<void>
}
const Item: FC<ItemProps> = ({ readonly, disabled, payload, onRename, onDelete }) => {
  const { t } = useTranslation(['common', 'dataset'])
  const iconClassName = getIconClassName(payload.type)

  const handleRename = useCallback(() => {
    onRename?.()
  }, [onRename])

  const deleteBtnRef = useRef<HTMLButtonElement>(null)
  const isDeleteHovering = useHover(deleteBtnRef)
  const deleteActionsRef = useRef<AlertDialogActions>(null)
  const [isDeleting, setIsDeleting] = useState(false)
  const handleDelete = useCallback(async () => {
    if (isDeleting) return
    setIsDeleting(true)
    try {
      await onDelete?.()
      deleteActionsRef.current?.close()
    } catch {
      // The owner reports the failure; keep the dialog open so the user can retry.
    } finally {
      setIsDeleting(false)
    }
  }, [isDeleting, onDelete])

  return (
    <div
      key={payload.name}
      className={cn(
        !readonly && !disabled && 'group/item cursor-pointer hover:shadow-xs',
        'rounded-md border border-components-panel-border-subtle bg-components-panel-on-panel-item-bg',
        isDeleteHovering && 'border border-state-destructive-border bg-state-destructive-hover',
      )}
    >
      <div
        className={cn(
          'flex h-8 items-center justify-between px-2',
          disabled && 'opacity-30', // not include border and bg
        )}
      >
        <div className="flex h-full min-w-0 items-center space-x-1 text-text-tertiary">
          <span className={cn(iconClassName, 'size-4 shrink-0')} aria-hidden="true" />
          <div className="max-w-62.5 truncate system-sm-medium text-text-primary">
            {payload.name}
          </div>
          <div className="shrink-0 system-xs-regular">{payload.type}</div>
        </div>
        {(!readonly || disabled) && (
          <div className="ms-2 shrink-0 system-xs-regular text-text-tertiary">
            {disabled
              ? t(($) => $[`${i18nPrefix}.disabled`], { ns: 'dataset' })
              : t(($) => $[`${i18nPrefix}.values`], { ns: 'dataset', num: payload.count || 0 })}
          </div>
        )}
        {!readonly && !disabled && (
          <div className="ms-2 flex shrink-0 items-center space-x-1 text-text-tertiary">
            <IconButton
              size="sm"
              aria-label={t(($) => $['operation.edit'], { ns: 'common' })}
              onClick={handleRename}
            >
              <span className="i-ri-edit-line size-4" aria-hidden="true" />
            </IconButton>
            <AlertDialog
              actionsRef={deleteActionsRef}
              onOpenChange={(open, details) => {
                if (!open && isDeleting && details.reason !== 'imperative-action') details.cancel()
              }}
            >
              <AlertDialogTrigger
                ref={deleteBtnRef}
                render={
                  <IconButton
                    aria-label={t(($) => $['operation.remove'], { ns: 'common' })}
                    size="sm"
                    tone="destructive"
                  >
                    <span className="i-ri-delete-bin-line size-4" aria-hidden="true" />
                  </IconButton>
                }
              />
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>
                    {t(($) => $['metadata.datasetMetadata.deleteTitle'], { ns: 'dataset' })}
                  </AlertDialogTitle>
                  <AlertDialogDescription>
                    {t(($) => $['metadata.datasetMetadata.deleteContent'], {
                      ns: 'dataset',
                      name: payload.name,
                    })}
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancelButton disabled={isDeleting}>
                    {t(($) => $['operation.cancel'], { ns: 'common' })}
                  </AlertDialogCancelButton>
                  <AlertDialogConfirmButton loading={isDeleting} onClick={handleDelete}>
                    {t(($) => $['operation.confirm'], { ns: 'common' })}
                  </AlertDialogConfirmButton>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </div>
        )}
      </div>
    </div>
  )
}

const DatasetMetadataDrawer: FC<Props> = ({
  userMetadata,
  builtInMetadata,
  isBuiltInEnabled,
  onIsBuiltInEnabledChange,
  onClose,
  onAdd,
  onRename,
  onRemove,
}) => {
  const builtInLabelId = React.useId()

  const { t } = useTranslation(['common', 'dataset'])
  const [isShowRenameModal, setIsShowRenameModal] = useState(false)
  const [currPayload, setCurrPayload] = useState<MetadataItemWithValueLength | null>(null)
  const [templeName, setTempleName] = useState('')
  const handleRename = useCallback(
    (payload: MetadataItemWithValueLength) => {
      return () => {
        setCurrPayload(payload)
        setTempleName(payload.name)
        setIsShowRenameModal(true)
      }
    },
    [setCurrPayload, setIsShowRenameModal],
  )

  const [open, setOpen] = useState(false)
  const handleAdd = useCallback(
    async (data: BuiltInMetadataItem) => {
      await onAdd(data)
      setOpen(false)
    },
    [onAdd],
  )

  const handleRenamed = useCallback(async () => {
    const item = userMetadata.find((p) => p.id === currPayload?.id)
    if (item) {
      await onRename({
        ...item,
        name: templeName,
      })
    }
    setIsShowRenameModal(false)
  }, [userMetadata, currPayload?.id, onRename, templeName])

  const handleDelete = useCallback(
    (payload: MetadataItemWithValueLength) => {
      return async () => {
        await onRemove(payload.id)
        toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
      }
    },
    [onRemove, t],
  )

  return (
    <Drawer
      open
      modal
      swipeDirection="right"
      onOpenChange={(open) => {
        if (!open) onClose()
      }}
    >
      <DrawerPortal>
        <DrawerBackdrop />
        <DrawerViewport>
          <DrawerPopup className="data-[swipe-direction=right]:top-2 data-[swipe-direction=right]:bottom-2 data-[swipe-direction=right]:h-[calc(100dvh-16px)] data-[swipe-direction=right]:w-full data-[swipe-direction=right]:max-w-105">
            <DrawerContent>
              <div className="flex shrink-0 justify-between px-4 pt-6 pb-4">
                <DrawerTitle className="text-lg/6 font-medium text-text-primary">
                  {t(($) => $['metadata.metadata'], { ns: 'dataset' })}
                </DrawerTitle>
                <DrawerClose
                  render={
                    <IconButton
                      aria-label={t(($) => $['operation.close'], { ns: 'common' })}
                      size="md"
                    >
                      <span aria-hidden="true" className="i-ri-close-line size-4" />
                    </IconButton>
                  }
                />
              </div>
              <div className="min-h-0 flex-1 overflow-y-auto px-4 pb-6">
                <div className="system-sm-regular text-text-tertiary">
                  {t(($) => $[`${i18nPrefix}.description`], { ns: 'dataset' })}
                </div>
                <CreateMetadataModal
                  open={open}
                  setOpen={setOpen}
                  trigger={
                    <Button variant="primary" className="mt-3">
                      <span aria-hidden="true" className="i-ri-add-line size-4" />
                      {t(($) => $[`${i18nPrefix}.addMetaData`], { ns: 'dataset' })}
                    </Button>
                  }
                  hasBack
                  onSave={handleAdd}
                />

                <div className="mt-3 space-y-1">
                  {userMetadata.map((payload) => (
                    <Item
                      key={payload.id}
                      payload={payload}
                      onRename={handleRename(payload)}
                      onDelete={handleDelete(payload)}
                    />
                  ))}
                </div>

                <div className="mt-3 flex h-6 items-center">
                  <Switch
                    aria-labelledby={builtInLabelId}
                    checked={isBuiltInEnabled}
                    onCheckedChange={onIsBuiltInEnabledChange}
                  />
                  <div
                    id={builtInLabelId}
                    className="ms-2 me-0.5 system-sm-semibold text-text-secondary"
                  >
                    {t(($) => $[`${i18nPrefix}.builtIn`], { ns: 'dataset' })}
                  </div>
                  <Infotip>
                    <InfotipTrigger aria-labelledby={builtInLabelId} />
                    <InfotipContent aria-labelledby={builtInLabelId} className="max-w-25">
                      {t(($) => $[`${i18nPrefix}.builtInDescription`], { ns: 'dataset' })}
                    </InfotipContent>
                  </Infotip>
                </div>

                <div className="mt-1 space-y-1">
                  {builtInMetadata.map((payload) => (
                    <Item
                      key={payload.name}
                      readonly
                      disabled={!isBuiltInEnabled}
                      payload={payload as MetadataItemWithValueLength}
                    />
                  ))}
                </div>

                {isShowRenameModal && (
                  <Dialog
                    open
                    onOpenChange={(open) => {
                      if (!open) setIsShowRenameModal(false)
                    }}
                  >
                    <DialogContent>
                      <DialogHeader>
                        <DialogTitle>
                          {t(($) => $[`${i18nPrefix}.rename`], { ns: 'dataset' })}
                        </DialogTitle>
                      </DialogHeader>

                      <DialogBody>
                        <Field label={t(($) => $[`${i18nPrefix}.name`], { ns: 'dataset' })}>
                          <Input
                            aria-label={t(($) => $[`${i18nPrefix}.name`], { ns: 'dataset' })}
                            value={templeName}
                            onValueChange={setTempleName}
                            placeholder={t(($) => $[`${i18nPrefix}.namePlaceholder`], {
                              ns: 'dataset',
                            })}
                          />
                        </Field>
                      </DialogBody>
                      <DialogFooter>
                        <Button
                          onClick={() => {
                            setIsShowRenameModal(false)
                            setTempleName(currPayload!.name)
                          }}
                        >
                          {t(($) => $['operation.cancel'], { ns: 'common' })}
                        </Button>
                        <Button onClick={handleRenamed} variant="primary" disabled={!templeName}>
                          {t(($) => $['operation.save'], { ns: 'common' })}
                        </Button>
                      </DialogFooter>
                    </DialogContent>
                  </Dialog>
                )}
              </div>
            </DrawerContent>
          </DrawerPopup>
        </DrawerViewport>
      </DrawerPortal>
    </Drawer>
  )
}
export default React.memo(DatasetMetadataDrawer)