chat-context.tsx 1.41 KB
'use client'

import { useCallback, useMemo } from 'react'
import { createContext, useContext } from 'use-context-selector'
import { noop } from 'lodash-es'
import type { ChatItem, Feedback, InputMessageType, OnRegenerate } from '@/app/components/base/chat/types'
import { FileEntity } from '@/app/components/base/file-uploader/types'
export type OnSendMessage = (
  message: string,
  type?: InputMessageType,
  files?: FileEntity[],
  parentMessageId?: string,
) => void
export type ChatContextValue = {
  onSend: OnSendMessage
  onRegenerate?: OnRegenerate
  onRestart: () => void
  onFeedback?: (messageId: string, feedback: Feedback) => void
  onStopResponding?: () => void
}

const ChatContext = createContext<ChatContextValue>({
  onRestart: noop,
  onSend: noop,
  onFeedback: noop,
  onStopResponding: noop,
})

type ChatContextProviderProps = {
  children: React.ReactNode
} & ChatContextValue

export const ChatContextProvider = ({
  children,
  onSend,
  onRegenerate,
  onRestart,
  onFeedback,
  onStopResponding,
}: ChatContextProviderProps) => {
  const value = useMemo(
    () => ({
      onSend,
      onRegenerate,
      onRestart,
      onFeedback,
      onStopResponding,
    }),
    [onSend, onRegenerate, onRestart, onFeedback, onStopResponding],
  )
  return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>
}

export const useChatContext = () => useContext(ChatContext)
export default ChatContext