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.

10.1 KB
Raw Blame
import type { EndpointListItemResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
import type { PluginDetail } from '../types'
import {
  AlertDialog,
  AlertDialogCancelButton,
  AlertDialogConfirmButton,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@langgenius/dify-ui/alert-dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { Switch } from '@langgenius/dify-ui/switch'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { useMutation } from '@tanstack/react-query'
import { useBoolean } from 'ahooks'
import copy from 'copy-to-clipboard'
import * as React from 'react'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { getErrorMessage } from '@/utils/error-message'
import EndpointModal from './endpoint-modal'

type Props = Readonly<{
  pluginDetail: PluginDetail
  data: EndpointListItemResponse
}>

const EndpointCard = ({ pluginDetail, data }: Props) => {
  const { t } = useTranslation(['common', 'plugin'])
  const endpointNameId = React.useId()
  const endpointID = data.id
  const [isShowDisableConfirm, { setTrue: showDisableConfirm, setFalse: hideDisableConfirm }] =
    useBoolean(false)
  const deleteActionsRef = useRef<AlertDialogActions>(null)
  const [
    isShowEndpointModal,
    { setTrue: showEndpointModalConfirm, setFalse: hideEndpointModalConfirm },
  ] = useBoolean(false)
  const showSaveError = (error: unknown) => {
    toast.error(
      getErrorMessage(error) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
    )
  }
  const { mutate: enableEndpoint, isPending: isEnabling } = useMutation(
    consoleQuery.workspaces.current.endpoints.enable.post.mutationOptions({
      context: { silent: true },
      onError: showSaveError,
    }),
  )
  const { mutate: disableEndpoint, isPending: isDisabling } = useMutation(
    consoleQuery.workspaces.current.endpoints.disable.post.mutationOptions({
      context: { silent: true },
      onSuccess: hideDisableConfirm,
      onError: showSaveError,
    }),
  )
  const { mutate: deleteEndpoint, isPending: isDeleting } = useMutation(
    consoleQuery.workspaces.current.endpoints.byId.delete.mutationOptions({
      context: { silent: true },
      onSuccess: () => deleteActionsRef.current?.close(),
      onError: showSaveError,
    }),
  )
  const { mutate: updateEndpoint, isPending: isUpdating } = useMutation(
    consoleQuery.workspaces.current.endpoints.byId.patch.mutationOptions({
      context: { silent: true },
      onSuccess: hideEndpointModalConfirm,
      onError: showSaveError,
    }),
  )
  const handleSwitch = (enabled: boolean) => {
    if (enabled) enableEndpoint({ body: { endpoint_id: endpointID } })
    else showDisableConfirm()
  }

  const [isCopied, setIsCopied] = useState(false)
  const handleCopy = (value: string) => {
    copy(value)
    setIsCopied(true)
  }

  useEffect(() => {
    if (isCopied) {
      const timer = setTimeout(() => {
        setIsCopied(false)
      }, 2000)
      return () => {
        clearTimeout(timer)
      }
    }
  }, [isCopied])

  const copyLabel = t(($) => $[`operation.${isCopied ? 'copied' : 'copy'}`], { ns: 'common' })

  return (
    <div className="rounded-xl bg-background-section-burn p-0.5">
      <div className="group rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-2.5 pl-3">
        <div className="flex items-center">
          <div className="mb-1 flex h-6 grow items-center gap-1 system-md-semibold text-text-secondary">
            <span aria-hidden className="i-ri-login-circle-line size-4" />
            <div id={endpointNameId}>{data.name}</div>
          </div>
          <div className="flex w-0 items-center overflow-hidden opacity-0 group-hover:w-auto group-hover:overflow-visible group-hover:opacity-100 focus-within:w-auto focus-within:overflow-visible focus-within:opacity-100">
            <IconButton
              aria-label={`${t(($) => $['operation.edit'], { ns: 'common' })} ${data.name}`}
              onClick={showEndpointModalConfirm}
            >
              <span aria-hidden className="i-ri-edit-line size-4" />
            </IconButton>
            <AlertDialog actionsRef={deleteActionsRef}>
              <AlertDialogTrigger
                render={
                  <IconButton
                    aria-label={`${t(($) => $['operation.delete'], { ns: 'common' })} ${data.name}`}
                    tone="destructive"
                  >
                    <span aria-hidden className="i-ri-delete-bin-line size-4" />
                  </IconButton>
                }
              />
              <AlertDialogContent backdropProps={{ forceRender: true }}>
                <AlertDialogHeader>
                  <AlertDialogTitle>
                    {t(($) => $['detailPanel.endpointDeleteTip'], { ns: 'plugin' })}
                  </AlertDialogTitle>
                  <AlertDialogDescription>
                    {t(($) => $['detailPanel.endpointDeleteContent'], {
                      ns: 'plugin',
                      name: data.name,
                    })}
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancelButton>
                    {t(($) => $['operation.cancel'], { ns: 'common' })}
                  </AlertDialogCancelButton>
                  <AlertDialogConfirmButton
                    loading={isDeleting}
                    onClick={() => deleteEndpoint({ params: { id: endpointID } })}
                  >
                    {t(($) => $['operation.confirm'], { ns: 'common' })}
                  </AlertDialogConfirmButton>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </div>
        </div>
        {(data.declaration?.endpoints ?? [])
          .filter((endpoint) => !endpoint.hidden)
          .map((endpoint) => (
            <div key={`${endpoint.method}:${endpoint.path}`} className="flex h-6 items-center">
              <div className="w-12 shrink-0 system-xs-regular text-text-tertiary">
                {endpoint.method}
              </div>
              <div className="group/item flex grow items-center truncate system-xs-regular text-text-secondary">
                <div className="truncate">{`${data.url}${endpoint.path}`}</div>
                <Tooltip>
                  <TooltipTrigger
                    render={
                      <IconButton
                        aria-label={`${copyLabel} ${data.url}${endpoint.path}`}
                        className="ml-2 shrink-0 opacity-0 group-focus-within/item:opacity-100 group-hover/item:opacity-100"
                        onClick={() => handleCopy(`${data.url}${endpoint.path}`)}
                      >
                        {isCopied ? (
                          <span
                            aria-hidden
                            className="i-custom-vender-line-files-copy-check size-3.5 text-text-tertiary"
                          />
                        ) : (
                          <span
                            aria-hidden
                            className="i-ri-clipboard-line size-3.5 text-text-tertiary"
                          />
                        )}
                      </IconButton>
                    }
                  />
                  <TooltipContent>{copyLabel}</TooltipContent>
                </Tooltip>
              </div>
            </div>
          ))}
      </div>
      <div className="flex items-center justify-between p-2 pl-3">
        {data.enabled && (
          <div className="flex items-center gap-1 system-xs-semibold-uppercase text-util-colors-green-green-600">
            <StatusDot status="success" />
            {t(($) => $['detailPanel.serviceOk'], { ns: 'plugin' })}
          </div>
        )}
        {!data.enabled && (
          <div className="flex items-center gap-1 system-xs-semibold-uppercase text-text-tertiary">
            <StatusDot status="disabled" />
            {t(($) => $['detailPanel.disabled'], { ns: 'plugin' })}
          </div>
        )}
        <Switch
          aria-labelledby={endpointNameId}
          className="ml-3"
          checked={data.enabled}
          onCheckedChange={handleSwitch}
          disabled={isEnabling || isDisabling}
          size="sm"
        />
      </div>
      <AlertDialog
        open={isShowDisableConfirm}
        onOpenChange={(open) => !open && hideDisableConfirm()}
      >
        <AlertDialogContent backdropProps={{ forceRender: true }}>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t(($) => $['detailPanel.endpointDisableTip'], { ns: 'plugin' })}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t(($) => $['detailPanel.endpointDisableContent'], { ns: 'plugin', name: data.name })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancelButton>
              {t(($) => $['operation.cancel'], { ns: 'common' })}
            </AlertDialogCancelButton>
            <AlertDialogConfirmButton
              loading={isDisabling}
              onClick={() => disableEndpoint({ body: { endpoint_id: endpointID } })}
            >
              {t(($) => $['operation.confirm'], { ns: 'common' })}
            </AlertDialogConfirmButton>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {isShowEndpointModal && (
        <EndpointModal
          settings={data.declaration?.settings ?? []}
          defaultValues={{ ...data.settings, name: data.name }}
          onCancel={hideEndpointModalConfirm}
          onSaved={(body) => updateEndpoint({ params: { id: endpointID }, body })}
          isPending={isUpdating}
          pluginDetail={pluginDetail}
        />
      )}
    </div>
  )
}

export default EndpointCard