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.

19.2 KB
Raw Blame
'use client'

import type { SkillVersionResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
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 {
  Dialog,
  DialogBody,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogHeaderCloseButton,
  DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from '@langgenius/dify-ui/menu'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import useTimestamp from '@/hooks/use-timestamp'
import { consoleQuery } from '@/service/console'
import { getErrorMessage } from '@/utils/error-message'
import { RestoreVersionDialogContent } from './restore-version-dialog-content'
import { getSkillVersionTitle, invalidateSkillDetail } from './shared'

type VersionFilterValue = 'all' | 'onlyNamed'

function VersionTimelineDot({
  isActive,
  isFirst,
  isLast,
}: {
  isActive: boolean
  isFirst: boolean
  isLast: boolean
}) {
  return (
    <div className="relative flex w-4.5 shrink-0 justify-center pt-1.5">
      {!isFirst && <div className="absolute top-0 h-2 w-0.5 bg-divider-subtle" />}
      <span
        aria-hidden
        className={cn(
          'relative z-1 size-2 rounded-full border-2 bg-components-panel-bg',
          isActive ? 'border-text-accent' : 'border-text-quaternary',
        )}
      />
      {!isLast && <div className="absolute top-3 -bottom-4.5 w-0.5 bg-divider-subtle" />}
    </div>
  )
}

function CurrentDraftItem({
  isActive,
  isLast,
  onSelect,
}: {
  isActive: boolean
  isLast: boolean
  onSelect: () => void
}) {
  const { t } = useTranslation(['skill'])

  return (
    <button
      type="button"
      aria-current={isActive ? 'true' : undefined}
      onClick={onSelect}
      className={cn(
        'flex w-full items-start gap-1 rounded-lg py-1 pr-1.25 pl-2 text-left outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid',
        isActive ? 'bg-state-accent-active' : 'hover:bg-state-base-hover',
      )}
    >
      <VersionTimelineDot isActive={isActive} isFirst isLast={isLast} />
      <span
        className={cn(
          'min-w-0 flex-1 truncate py-1 system-sm-semibold',
          isActive ? 'text-text-accent' : 'text-text-secondary',
        )}
      >
        {t(($) => $['skillManagement.detail.currentDraft'])}
      </span>
    </button>
  )
}

function VersionFilter({
  value,
  onChange,
}: {
  value: VersionFilterValue
  onChange: (value: VersionFilterValue) => void
}) {
  const { t } = useTranslation(['skill'])
  const { t: tWorkflow } = useTranslation(['workflowHistory'])
  const [open, setOpen] = useState(false)
  const isFiltering = value !== 'all'

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger
        nativeButton={false}
        render={
          <button
            type="button"
            aria-label={`${t(($) => $['skillManagement.detail.versions'])}: ${
              value === 'all'
                ? tWorkflow(($) => $['versionHistory.filter.all'], { ns: 'workflowHistory' })
                : tWorkflow(($) => $['versionHistory.filter.onlyShowNamedVersions'], {
                    ns: 'workflowHistory',
                  })
            }`}
            className={cn(
              'flex size-6 shrink-0 items-center justify-center rounded-md p-0.5',
              isFiltering
                ? 'bg-state-accent-active-alt text-text-accent'
                : 'text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary',
            )}
          >
            <span aria-hidden className="i-ri-filter-3-line size-4" />
          </button>
        }
      />
      <PopoverContent
        align="end"
        sideOffset={4}
        alignOffset={55}
        className="border-none bg-transparent shadow-none"
      >
        <div className="flex w-62 flex-col rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 shadow-lg shadow-shadow-shadow-5 backdrop-blur-[5px]">
          {(['all', 'onlyNamed'] as const).map((filterValue) => (
            <button
              key={filterValue}
              type="button"
              className="flex h-8 w-full cursor-pointer items-center justify-between gap-1 rounded-lg px-2 text-left outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid"
              onClick={() => {
                onChange(filterValue)
                setOpen(false)
              }}
            >
              <span className="min-w-0 flex-1 truncate system-md-regular text-text-primary">
                {filterValue === 'all'
                  ? tWorkflow(($) => $['versionHistory.filter.all'], { ns: 'workflowHistory' })
                  : tWorkflow(($) => $['versionHistory.filter.onlyShowNamedVersions'], {
                      ns: 'workflowHistory',
                    })}
              </span>
              {value === filterValue && (
                <span aria-hidden className="i-ri-check-line size-4 shrink-0 text-text-accent" />
              )}
            </button>
          ))}
        </div>
      </PopoverContent>
    </Popover>
  )
}

function VersionRow({
  isFirst,
  isLast,
  onSelect,
  selected,
  skillId,
  version,
}: {
  isFirst: boolean
  isLast: boolean
  onSelect: (versionId: string | null) => void
  selected: boolean
  skillId: string
  version: SkillVersionResponse
}) {
  const { t } = useTranslation(['skill'])
  const { t: tCommon } = useTranslation(['common'])
  const { formatTime } = useTimestamp()
  const queryClient = useQueryClient()
  const [renameOpen, setRenameOpen] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [restoreOpen, setRestoreOpen] = useState(false)
  const restoreActionsRef = useRef<AlertDialogActions>(null)
  const deleteActionsRef = useRef<AlertDialogActions>(null)
  const [versionName, setVersionName] = useState(version.version_name)
  const [publishNote, setPublishNote] = useState(version.publish_note)
  const renameMutation = useMutation(
    consoleQuery.workspaces.current.skills.bySkillId.versions.byVersionId.patch.mutationOptions({
      context: { silent: true },
    }),
  )
  const restoreMutation = useMutation(
    consoleQuery.workspaces.current.skills.bySkillId.restore.post.mutationOptions({
      onSuccess: () => {
        restoreActionsRef.current?.close()
        onSelect(null)
      },
    }),
  )
  const deleteMutation = useMutation(
    consoleQuery.workspaces.current.skills.bySkillId.versions.byVersionId.delete.mutationOptions({
      onSuccess: () => {
        deleteActionsRef.current?.close()
        onSelect(null)
      },
    }),
  )
  const publishedBy = version.published_by_name ?? version.published_by ?? '-'
  const versionTitle = getSkillVersionTitle(version)
  const versionInfoLabel = version.is_latest
    ? t(($) => $['skillManagement.detail.editVersionInfo'])
    : t(($) => $['skillManagement.detail.nameThisVersion'])

  const invalidateVersions = () => invalidateSkillDetail(queryClient, skillId)

  const handleRename = () => {
    const trimmedName = versionName.trim()

    renameMutation.mutate(
      {
        params: {
          skill_id: skillId,
          version_id: version.id,
        },
        body: {
          publish_note: publishNote,
          version_name: trimmedName,
        },
      },
      {
        onSuccess: () => {
          setRenameOpen(false)
          invalidateVersions()
        },
        onError: (error) => {
          toast.error(
            getErrorMessage(error) ?? t(($) => $['skillManagement.detail.renameVersionFailed']),
          )
        },
      },
    )
  }

  const handleRestore = () => {
    restoreMutation.mutate({
      params: { skill_id: skillId },
      body: { version_id: version.id, version_name: version.version_name },
    })
  }

  const handleDelete = () => {
    deleteMutation.mutate({ params: { skill_id: skillId, version_id: version.id } })
  }

  return (
    <>
      <li className="group relative">
        <div
          className={cn(
            'relative flex w-full items-start gap-1 rounded-lg py-1 pr-1.25 pl-2 text-left outline-hidden focus-within:ring-2 focus-within:ring-state-accent-solid',
            selected ? 'bg-state-accent-active' : 'hover:bg-state-base-hover',
          )}
        >
          <VersionTimelineDot isActive={selected} isFirst={isFirst} isLast={isLast} />
          <button
            type="button"
            aria-current={selected ? 'true' : undefined}
            className="min-w-0 flex-1 cursor-pointer py-0.5 text-left outline-hidden"
            onClick={() => onSelect(version.id)}
          >
            <span className="flex min-w-0 flex-col gap-0.5">
              <span className="flex min-w-0 items-center gap-1 py-px pr-6">
                <span
                  className={cn(
                    'min-w-0 flex-1 truncate system-sm-semibold',
                    selected ? 'text-text-accent' : 'text-text-secondary',
                  )}
                >
                  {versionTitle}
                </span>
                {version.is_latest && (
                  <span className="shrink-0 rounded-[5px] border border-text-accent-secondary bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-accent-secondary">
                    {t(($) => $['skillManagement.detail.latest'])}
                  </span>
                )}
              </span>
              {version.publish_note && (
                <span className="block system-xs-regular wrap-break-word text-text-secondary">
                  {version.publish_note}
                </span>
              )}
              <span className="block truncate pt-0.5 system-xs-regular text-text-tertiary">
                {t(($) => $['skillManagement.detail.versionPublishedMeta'], {
                  name: publishedBy,
                  time: formatTime(
                    version.created_at,
                    t(($) => $['skillManagement.dateTimeFormat']),
                  ),
                })}
              </span>
            </span>
          </button>
          <Menu modal={false}>
            <MenuTrigger
              aria-label={tCommon(($) => $['operation.more'])}
              className="absolute top-1 right-1 flex size-6 shrink-0 cursor-pointer items-center justify-center overflow-hidden rounded-md border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg p-1 opacity-0 shadow-xs group-hover:opacity-100 focus-visible:opacity-100 data-popup-open:opacity-100"
            >
              <span aria-hidden className="i-ri-more-fill size-4 text-text-tertiary" />
            </MenuTrigger>
            <MenuContent align="end" className="w-46">
              <MenuItem onClick={() => setRestoreOpen(true)}>
                {t(($) => $['skillManagement.detail.restoreVersion'])}
              </MenuItem>
              <MenuItem
                onClick={() => {
                  setVersionName(version.version_name)
                  setPublishNote(version.publish_note)
                  setRenameOpen(true)
                }}
              >
                {versionInfoLabel}
              </MenuItem>
              {!version.is_latest && (
                <>
                  <MenuSeparator />
                  <MenuItem variant="destructive" onClick={() => setDeleteOpen(true)}>
                    {tCommon(($) => $['operation.delete'])}
                  </MenuItem>
                </>
              )}
            </MenuContent>
          </Menu>
        </div>
      </li>
      <Dialog open={renameOpen} onOpenChange={setRenameOpen}>
        <DialogContent className="w-120">
          <DialogHeader>
            <DialogTitle>{versionInfoLabel}</DialogTitle>
            <DialogDescription className="sr-only">
              {t(($) => $['skillManagement.detail.renameVersionPrompt'])}
            </DialogDescription>
            <DialogHeaderCloseButton aria-label={tCommon(($) => $['operation.close'])} />
          </DialogHeader>
          <DialogBody className="flex flex-col gap-y-4">
            <Field name="versionTitle">
              <FieldLabel className="system-sm-semibold">
                {t(($) => $['skillManagement.detail.versionTitle'])}
              </FieldLabel>
              <Input
                value={versionName}
                placeholder={t(($) => $['skillManagement.detail.nameThisVersion'])}
                onValueChange={setVersionName}
              />
            </Field>
            <Field name="publishNote">
              <FieldLabel className="system-sm-semibold">
                {t(($) => $['skillManagement.detail.versionPublishNote'])}
              </FieldLabel>
              <Textarea
                value={publishNote}
                placeholder={t(($) => $['skillManagement.detail.versionPublishNotePlaceholder'])}
                onValueChange={setPublishNote}
              />
            </Field>
          </DialogBody>
          <DialogFooter>
            <DialogClose render={<Button disabled={renameMutation.isPending} />}>
              {tCommon(($) => $['operation.cancel'])}
            </DialogClose>
            <Button variant="primary" loading={renameMutation.isPending} onClick={handleRename}>
              {t(($) => $['skillManagement.detail.publish'])}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      <AlertDialog
        actionsRef={restoreActionsRef}
        open={restoreOpen}
        onOpenChange={(open, details) => {
          if (!open && restoreMutation.isPending && details.reason !== 'imperative-action') {
            details.cancel()
            return
          }
          setRestoreOpen(open)
        }}
      >
        <RestoreVersionDialogContent
          isPending={restoreMutation.isPending}
          versionTitle={versionTitle}
          onConfirm={handleRestore}
        />
      </AlertDialog>
      <AlertDialog
        actionsRef={deleteActionsRef}
        open={deleteOpen}
        onOpenChange={(open, details) => {
          if (!open && deleteMutation.isPending && details.reason !== 'imperative-action') {
            details.cancel()
            return
          }
          setDeleteOpen(open)
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t(($) => $['skillManagement.detail.deleteVersionConfirm'])}
            </AlertDialogTitle>
            <AlertDialogDescription>{versionTitle}</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancelButton disabled={deleteMutation.isPending}>
              {tCommon(($) => $['operation.cancel'])}
            </AlertDialogCancelButton>
            <AlertDialogConfirmButton loading={deleteMutation.isPending} onClick={handleDelete}>
              {tCommon(($) => $['operation.delete'])}
            </AlertDialogConfirmButton>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}

export function VersionPanel({
  onClose,
  onSelect,
  selectedVersionId,
  skillId,
  versions,
}: {
  onClose: () => void
  onSelect: (versionId: string | null) => void
  selectedVersionId: string | null
  skillId: string
  versions: SkillVersionResponse[]
}) {
  const { t } = useTranslation(['skill'])
  const { t: tWorkflow } = useTranslation(['workflowHistory'])
  const [filterValue, setFilterValue] = useState<VersionFilterValue>('all')
  const titleId = useId()
  const filteredVersions = versions.filter((version) => {
    if (filterValue === 'onlyNamed') return !!version.version_name

    return true
  })

  return (
    <section aria-labelledby={titleId} className="flex w-67 shrink-0 flex-col py-1">
      <div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-l-lg bg-components-panel-bg">
        <div className="flex shrink-0 items-center gap-2 pt-3 pr-3 pl-4">
          <h2 id={titleId} className="min-w-0 flex-1 truncate system-xl-semibold text-text-primary">
            {t(($) => $['skillManagement.detail.versions'])}
          </h2>
          <VersionFilter value={filterValue} onChange={setFilterValue} />
          <div className="h-3.5 w-px shrink-0 bg-divider-regular" />
          <button
            type="button"
            aria-label={t(($) => $['skillManagement.detail.closeVersions'])}
            className="flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md p-0.5 text-text-tertiary outline-hidden hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid"
            onClick={onClose}
          >
            <span aria-hidden className="i-ri-close-line size-4" />
          </button>
        </div>
        <div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-3 py-2">
          <div className="flex min-w-0 flex-col gap-px">
            <CurrentDraftItem
              isActive={selectedVersionId === null}
              isLast={filteredVersions.length === 0}
              onSelect={() => onSelect(null)}
            />
            {versions.length === 0 && (
              <p className="rounded-lg px-3 py-6 text-center system-sm-regular text-text-tertiary">
                {t(($) => $['skillManagement.detail.noVersions'])}
              </p>
            )}
            {versions.length > 0 && filteredVersions.length === 0 && (
              <div className="rounded-lg px-3 py-6 text-center">
                <p className="system-sm-regular text-text-tertiary">
                  {tWorkflow(($) => $['versionHistory.filter.empty'], { ns: 'workflowHistory' })}
                </p>
                <button
                  type="button"
                  className="mt-2 rounded-md px-2 py-1 system-xs-medium text-text-accent outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid"
                  onClick={() => setFilterValue('all')}
                >
                  {tWorkflow(($) => $['versionHistory.filter.reset'], { ns: 'workflowHistory' })}
                </button>
              </div>
            )}
            {filteredVersions.length > 0 && (
              <ul className="flex flex-col gap-px">
                {filteredVersions.map((version, index) => (
                  <VersionRow
                    key={version.id}
                    isFirst={false}
                    isLast={index === filteredVersions.length - 1}
                    version={version}
                    skillId={skillId}
                    selected={selectedVersionId === version.id}
                    onSelect={onSelect}
                  />
                ))}
              </ul>
            )}
          </div>
        </div>
      </div>
    </section>
  )
}