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.

8.1 KB
Raw Blame
import type { Ref } from 'react'
import type { ConversationItem } from '@/models/share'
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 { IconButton } from '@langgenius/dify-ui/icon-button'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import List from '@/app/components/base/chat/chat-with-history/sidebar/list'
import RenameModal from '@/app/components/base/chat/chat-with-history/sidebar/rename-modal'
import { DifyLogo } from '@/app/components/base/logo/dify-logo'
import TextGenerationMenu from '@/app/components/share/text-generation/text-generation-menu'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useChatWithHistoryContext } from '../context'

type Props = Readonly<{
  toggleButtonRef?: Ref<HTMLButtonElement>
  isPanel?: boolean
  panelVisible?: boolean
}>

const Sidebar = ({ isPanel, toggleButtonRef }: Props) => {
  const { t } = useTranslation(['common', 'layout', 'share'])
  const {
    isInstalledApp,
    appData,
    handleNewConversation,
    pinnedConversationList,
    conversationList,
    currentConversationId,
    handleChangeConversation,
    handlePinConversation,
    handleUnpinConversation,
    conversationRenaming,
    handleRenameConversation,
    handleDeleteConversation,
    sidebarCollapseState,
    handleSidebarCollapse,
    isBelowSm,
    isResponding,
  } = useChatWithHistoryContext()
  const isSidebarCollapsed = sidebarCollapseState
  const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
  const [showConfirm, setShowConfirm] = useState<ConversationItem | null>(null)
  const [showRename, setShowRename] = useState<ConversationItem | null>(null)

  const handleOperate = useCallback(
    (type: string, item: ConversationItem) => {
      if (type === 'pin') handlePinConversation(item.id)

      if (type === 'unpin') handleUnpinConversation(item.id)

      if (type === 'delete') setShowConfirm(item)

      if (type === 'rename') setShowRename(item)
    },
    [handlePinConversation, handleUnpinConversation],
  )
  const handleCancelConfirm = useCallback(() => {
    setShowConfirm(null)
  }, [])
  const handleDelete = useCallback(() => {
    if (showConfirm) handleDeleteConversation(showConfirm.id, { onSuccess: handleCancelConfirm })
  }, [showConfirm, handleDeleteConversation, handleCancelConfirm])
  const handleCancelRename = useCallback(() => {
    setShowRename(null)
  }, [])
  const handleRename = useCallback(
    (newName: string) => {
      if (showRename)
        handleRenameConversation(showRename.id, newName, { onSuccess: handleCancelRename })
    },
    [showRename, handleRenameConversation, handleCancelRename],
  )
  const pinnedTitle = t(($) => $['chat.pinnedTitle'], { ns: 'share' })
  const deleteConversationContent = t(($) => $['chat.deleteConversation.content'], { ns: 'share' })

  return (
    <div
      className={cn(
        'flex w-full grow flex-col',
        isPanel &&
          'rounded-xl border-[0.5px] border-components-panel-border-subtle bg-components-panel-bg shadow-lg',
      )}
    >
      <div className={cn('flex shrink-0 items-center gap-3 p-3 pe-2')}>
        <div className="shrink-0">
          <AppIcon size="large" icon={appData?.site} />
        </div>
        <div className={cn('grow truncate system-md-semibold text-text-secondary')}>
          {appData?.site.title}
        </div>
        {!isBelowSm && isSidebarCollapsed && (
          <IconButton
            aria-label={t(($) => $['sidebar.expandSidebar'], { ns: 'layout' })}
            size="lg"
            onClick={() => handleSidebarCollapse(false)}
          >
            <span aria-hidden className="i-ri-expand-right-line h-4.5 w-4.5" />
          </IconButton>
        )}
        {!isBelowSm && !isSidebarCollapsed && (
          <IconButton
            ref={toggleButtonRef}
            aria-label={t(($) => $['sidebar.collapseSidebar'], { ns: 'layout' })}
            size="lg"
            onClick={() => handleSidebarCollapse(true)}
          >
            <span aria-hidden className="i-ri-layout-left-2-line h-4.5 w-4.5" />
          </IconButton>
        )}
      </div>
      <div className="shrink-0 px-3 py-4">
        <Button
          variant="secondary-accent"
          disabled={isResponding}
          className="w-full justify-center"
          onClick={handleNewConversation}
        >
          <span aria-hidden className="i-ri-edit-box-line size-4" />
          {t(($) => $['chat.newChat'], { ns: 'share' })}
        </Button>
      </div>
      <div className="h-0 grow space-y-2 overflow-y-auto px-3 pt-4">
        {/* pinned list */}
        {!!pinnedConversationList.length && (
          <div className="mb-4">
            <List
              isPin
              title={pinnedTitle}
              list={pinnedConversationList}
              onChangeConversation={handleChangeConversation}
              onOperate={handleOperate}
              currentConversationId={currentConversationId}
            />
          </div>
        )}
        {!!conversationList.length && (
          <List
            title={
              (pinnedConversationList.length &&
                t(($) => $['chat.unpinnedTitle'], { ns: 'share' })) ||
              ''
            }
            list={conversationList}
            onChangeConversation={handleChangeConversation}
            onOperate={handleOperate}
            currentConversationId={currentConversationId}
          />
        )}
      </div>
      <div className="flex shrink-0 items-center justify-between p-3">
        <TextGenerationMenu
          hideLogout={isInstalledApp}
          side="top"
          align="start"
          data={appData?.site}
        />
        {/* powered by */}
        <div className="shrink-0">
          {!appData?.custom_config?.remove_webapp_brand && (
            <div className={cn('flex shrink-0 items-center gap-1.5 px-1')}>
              <div className="system-2xs-medium-uppercase text-text-tertiary">
                {t(($) => $['chat.poweredBy'], { ns: 'share' })}
              </div>
              {systemFeatures.branding.enabled && systemFeatures.branding.workspace_logo ? (
                <img
                  src={systemFeatures.branding.workspace_logo}
                  alt="logo"
                  className="block h-5 w-auto"
                />
              ) : appData?.custom_config?.replace_webapp_logo ? (
                <img
                  src={`${appData?.custom_config?.replace_webapp_logo}`}
                  alt="logo"
                  className="block h-5 w-auto"
                />
              ) : (
                <DifyLogo alt="Dify" size="small" />
              )}
            </div>
          )}
        </div>
        <AlertDialog open={!!showConfirm} onOpenChange={(open) => !open && handleCancelConfirm()}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>
                {t(($) => $['chat.deleteConversation.title'], { ns: 'share' })}
              </AlertDialogTitle>
              <AlertDialogDescription>{deleteConversationContent}</AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancelButton>
                {t(($) => $['operation.cancel'], { ns: 'common' })}
              </AlertDialogCancelButton>
              <AlertDialogConfirmButton onClick={handleDelete}>
                {t(($) => $['operation.confirm'], { ns: 'common' })}
              </AlertDialogConfirmButton>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
        {showRename && (
          <RenameModal
            isShow
            onClose={handleCancelRename}
            saveLoading={conversationRenaming}
            name={showRename?.name || ''}
            onSave={handleRename}
          />
        )}
      </div>
    </div>
  )
}

export default Sidebar