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.

12.3 KB
Raw Blame
'use client'
import type { FC } from 'react'
import type { PluginDetail } from '../types'
import { cn } from '@langgenius/dify-ui/cn'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import {
  RiArrowRightUpLine,
  RiBugLine,
  RiErrorWarningLine,
  RiHardDrive3Line,
  RiLoginCircleLine,
} from '@remixicon/react'
import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import useRefreshPluginList from '@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list'
import { API_PREFIX } from '@/config'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { useMarketplace } from '@/features/marketplace/client'
import { useResolvedTheme } from '@/features/theme/hooks'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import { isEqualOrLaterThanVersion } from '@/utils/semver'
import Badge from '../../base/badge'
import Verified from '../base/badges/verified'
import Description from '../card/base/description'
import OrgInfo from '../card/base/org-info'
import Title from '../card/base/title'
import { usePluginPageContext } from '../plugin-page/context'
import { PluginSource } from '../types'
import Action from './action'

type Props = Readonly<{
  canDeletePlugin?: boolean
  canUpdatePlugin?: boolean
  className?: string
  plugin: PluginDetail
}>

const PluginItem: FC<Props> = ({
  canDeletePlugin = true,
  canUpdatePlugin = true,
  className,
  plugin,
}) => {
  const { t } = useTranslation(['plugin'])
  const theme = useResolvedTheme()
  const selectedPluginID = usePluginPageContext((v) =>
    v.selectedItem?.type === 'plugin' ? v.selectedItem.id : undefined,
  )
  const setSelectedItem = usePluginPageContext((v) => v.setSelectedItem)
  const { refreshPluginList } = useRefreshPluginList()

  const {
    source,
    tenant_id,
    installation_id,
    plugin_unique_identifier,
    meta,
    plugin_id,
    status,
    deprecated_reason,
  } = plugin
  const {
    category,
    author,
    name,
    label,
    description,
    icon,
    icon_dark,
    verified,
    meta: declarationMeta,
  } = plugin.declaration
  const endpointCount =
    plugin.declaration.endpoint?.endpoints?.filter((endpoint) => !endpoint.hidden).length ?? 0
  const hasEndpointDeclaration = !!plugin.declaration.endpoint

  const orgName = useMemo(() => {
    const sourcesWithAuthor: PluginSource[] = [PluginSource.github, PluginSource.marketplace]
    return sourcesWithAuthor.includes(source) ? author : ''
  }, [source, author])

  const { data: currentVersion } = useSuspenseQuery({
    ...userProfileQueryOptions(),
    select: (data) => data.meta.currentVersion ?? '',
  })

  const isDifyVersionCompatible = useMemo(() => {
    if (!currentVersion) return true
    return isEqualOrLaterThanVersion(
      currentVersion,
      declarationMeta.minimum_dify_version ?? '0.0.0',
    )
  }, [currentVersion, declarationMeta.minimum_dify_version])

  const isDeprecated = useMemo(() => {
    return status === 'deleted' && !!deprecated_reason
  }, [status, deprecated_reason])

  const handleDelete = useCallback(() => {
    refreshPluginList({ category } as any)
  }, [category, refreshPluginList])

  const getValueFromI18nObject = useRenderI18nObject()
  const title = getValueFromI18nObject(label)
  const titleId = React.useId()
  const descriptionText = getValueFromI18nObject(description)
  const marketplace = useMarketplace()
  const iconFileName = theme === 'dark' && icon_dark ? icon_dark : icon
  const iconSrc = iconFileName
    ? iconFileName.startsWith('http')
      ? iconFileName
      : `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${tenant_id}&filename=${iconFileName}`
    : ''

  return (
    <div
      className={cn(
        'group/plugin-item relative flex min-w-[min(100%,496px)] flex-1 flex-col overflow-hidden rounded-xl p-0.75',
        selectedPluginID === plugin_id &&
          "after:pointer-events-none after:absolute after:inset-0 after:rounded-xl after:inset-ring-[1.5px] after:inset-ring-components-option-card-option-selected-border after:content-['']",
        source === PluginSource.debugging
          ? 'bg-[repeating-linear-gradient(-45deg,rgba(16,24,40,0.04),rgba(16,24,40,0.04)_5px,rgba(0,0,0,0.02)_5px,rgba(0,0,0,0.02)_10px)]'
          : 'bg-background-section-burn',
      )}
    >
      <button
        type="button"
        aria-labelledby={titleId}
        className="absolute inset-0 z-10 cursor-pointer rounded-xl border-0 bg-transparent p-0 outline-hidden focus-visible:inset-ring-2 focus-visible:inset-ring-state-accent-solid"
        onClick={() => setSelectedItem({ type: 'plugin', id: plugin.plugin_id })}
      />
      <div
        className={cn(
          'relative rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-3',
          className,
        )}
      >
        {/* Header */}
        <div className="flex">
          <div className="flex size-10 items-center justify-center overflow-hidden rounded-xl border border-components-panel-border-subtle">
            <img
              className="size-full"
              decoding="async"
              height={40}
              loading="lazy"
              src={iconSrc}
              alt=""
              width={40}
            />
          </div>
          <div className="ms-3 w-0 grow">
            <div className="flex h-5 items-center">
              <div id={titleId} className="min-w-0">
                <Title title={title} />
              </div>
              {verified && (
                <Verified
                  className="ms-0.5 size-4"
                  text={t(($) => $['marketplace.verifiedTip'], { ns: 'plugin' })}
                />
              )}
              {!isDifyVersionCompatible && (
                <Popover>
                  <PopoverTrigger
                    openOnHover
                    aria-label={t(($) => $.difyVersionNotCompatible, {
                      ns: 'plugin',
                      minimalDifyVersion: declarationMeta.minimum_dify_version ?? '0.0.0',
                    })}
                    className="relative z-20 ms-0.5 inline-flex size-4 shrink-0 border-0 bg-transparent p-0"
                  >
                    <RiErrorWarningLine color="red" className="size-4 text-text-accent" />
                  </PopoverTrigger>
                  <PopoverContent className="px-3 py-2 system-xs-regular text-text-tertiary">
                    {t(($) => $.difyVersionNotCompatible, {
                      ns: 'plugin',
                      minimalDifyVersion: declarationMeta.minimum_dify_version ?? '0.0.0',
                    })}
                  </PopoverContent>
                </Popover>
              )}
              <Badge
                className="ms-1 shrink-0"
                text={source === PluginSource.github ? plugin.meta!.version : plugin.version}
                hasRedCornerMark={
                  source === PluginSource.marketplace &&
                  !!plugin.latest_version &&
                  plugin.latest_version !== plugin.version
                }
              />
            </div>
            <div className="relative flex h-4 min-w-0 items-center">
              <Description
                className="min-w-0 flex-1 group-focus-within/plugin-item:pe-20 group-hover/plugin-item:pe-20 [@media(hover:none)]:pe-20"
                text={descriptionText}
                descriptionLineRows={1}
              />
              <div className="pointer-events-none absolute inset-e-0 top-1/2 z-20 -translate-y-1/2 opacity-0 transition-opacity group-focus-within/plugin-item:pointer-events-auto group-focus-within/plugin-item:opacity-100 group-hover/plugin-item:pointer-events-auto group-hover/plugin-item:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100">
                <Action
                  pluginUniqueIdentifier={plugin_unique_identifier}
                  installationId={installation_id}
                  author={author}
                  pluginName={name}
                  usedInApps={5}
                  isShowFetchNewVersion={canUpdatePlugin && source === PluginSource.github}
                  isShowInfo={source === PluginSource.github}
                  isShowDelete={canDeletePlugin}
                  meta={meta}
                  onDelete={handleDelete}
                  category={category}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="flex h-6.5 items-center gap-x-2 px-3 pt-1.5 pb-1">
        {/* Organization & Name */}
        <div className="flex grow items-center overflow-hidden">
          <OrgInfo
            orgName={orgName}
            packageName={name}
            packageNameClassName="w-auto max-w-[150px]"
          />
          {hasEndpointDeclaration && (
            <>
              <div className="mx-2 system-xs-regular text-text-quaternary">·</div>
              <div className="flex items-center gap-x-1 overflow-hidden system-xs-regular text-text-tertiary">
                <RiLoginCircleLine className="size-3 shrink-0" />
                <span
                  className="truncate"
                  title={t(($) => $.endpointsEnabled, { ns: 'plugin', num: endpointCount })}
                >
                  {t(($) => $.endpointsEnabled, { ns: 'plugin', num: endpointCount })}
                </span>
              </div>
            </>
          )}
        </div>
        {/* Source */}
        <div className="flex shrink-0 items-center">
          {source === PluginSource.github && (
            <>
              <a
                href={`https://github.com/${meta!.repo}`}
                target="_blank"
                className="relative z-20 flex items-center gap-1"
              >
                <div className="system-2xs-medium-uppercase text-text-tertiary">
                  {t(($) => $.from, { ns: 'plugin' })}
                </div>
                <div className="flex items-center space-x-0.5 text-text-secondary">
                  <span aria-hidden className="i-custom-public-common-github size-3" />
                  <div className="system-2xs-semibold-uppercase">GitHub</div>
                  <RiArrowRightUpLine className="size-3" />
                </div>
              </a>
            </>
          )}
          {source === PluginSource.marketplace && marketplace && (
            <>
              <a
                href={marketplace.plugin({ org: author, name }, { theme })}
                target="_blank"
                className="relative z-20 flex items-center gap-0.5"
              >
                <div className="system-2xs-medium-uppercase text-text-tertiary">
                  {t(($) => $.from, { ns: 'plugin' })}{' '}
                  <span className="text-text-secondary">marketplace</span>
                </div>
                <RiArrowRightUpLine className="size-3 text-text-secondary" />
              </a>
            </>
          )}
          {source === PluginSource.local && (
            <>
              <div className="flex items-center gap-1">
                <RiHardDrive3Line className="size-3 text-text-tertiary" />
                <div className="system-2xs-medium-uppercase text-text-tertiary">Local Plugin</div>
              </div>
            </>
          )}
          {source === PluginSource.debugging && (
            <>
              <div className="flex items-center gap-1">
                <RiBugLine className="size-3 text-text-warning" />
                <div className="system-2xs-medium-uppercase text-text-warning">
                  Debugging Plugin
                </div>
              </div>
            </>
          )}
        </div>
        {/* Deprecated */}
        {source === PluginSource.marketplace && marketplace && isDeprecated && (
          <div className="flex shrink-0 items-center gap-x-2 system-2xs-medium-uppercase">
            <span className="text-text-tertiary">·</span>
            <span className="text-text-warning">{t(($) => $.deprecated, { ns: 'plugin' })}</span>
          </div>
        )}
      </div>
      {/* BG Effect for Deprecated Plugin */}
      {source === PluginSource.marketplace && marketplace && isDeprecated && (
        <div className="absolute -inset-e-11.25 -bottom-17.75 z-0 size-40 bg-components-badge-status-light-warning-halo opacity-60 blur-[120px]" />
      )}
    </div>
  )
}

export default React.memo(PluginItem)