use-send-shared-message.ts


Overview

use-send-shared-message.ts is a custom React hook module designed to facilitate sending and managing chat messages within a "shared chat" context, typically involving conversations shared between users and agents or chatbots. It handles message input, sending messages to a backend API via Server-Sent Events (SSE), managing message states, and retrieving chat session parameters from the URL.

This file integrates multiple hooks and utilities to provide a seamless chat experience by managing message lifecycle events (input, send, receive, error handling) and maintaining UI state such as loading indicators and message lists.


Exports and Main Functionalities

1. useSendButtonDisabled(value: string): boolean

Purpose:
Determines whether the send button should be disabled based on the current input value.

Parameters:

Returns:

Usage Example:

const isDisabled = useSendButtonDisabled(inputValue);
<button disabled={isDisabled}>Send</button>

2. useGetSharedChatSearchParams(): SharedChatParams

Purpose:
Parses and returns relevant chat-related parameters from the URL search parameters.

Returns:
An object containing:

Property

Type

Description

from

SharedFrom

Source identifier of shared chat (agent or chatbot)

sharedId

`string \

null`

locale

`string \

null`

data

Record<string, string>

Additional data prefixed by data_ in the URL params

visibleAvatar

boolean

Whether avatar display is visible

Usage Example:

const { from, sharedId, locale, data, visibleAvatar } = useGetSharedChatSearchParams();

3. useSendSharedMessage(): UseSendSharedMessageReturn

Purpose:
Primary hook that manages the sending of shared chat messages, message input state, message list management, error handling, and session initialization.

Returns:
An object with properties and methods for chat UI interaction:

Property / Method

Type

Description

handlePressEnter

(documentIds: string[]) => void

Sends the message when Enter key is pressed, appending document IDs

handleInputChange

(event: React.ChangeEvent<HTMLInputElement>) => void (from hook)

Handler for text input change

value

string

Current message input value

sendLoading

boolean

Indicates if a send request is in progress

loading

boolean

Placeholder loading indicator (always false here)

derivedMessages

Message[]

List of chat messages, including both questions and answers

hasError

boolean

Indicates if an error occurred during message sending or session initiation

stopOutputMessage

() => void

Stops the SSE message output stream

scrollRef

React.RefObject<HTMLElement>

Ref to the scroll container for messages

messageContainerRef

React.RefObject<HTMLElement>

Ref to the message container

removeAllMessages

() => void

Removes all messages from the message list

removeAllMessagesExceptFirst

() => void

Removes all messages except the first one


Detailed Explanation of useSendSharedMessage

Internal Dependencies and Hooks Used

Key Internal Functions

sendMessage(message: Message, id?: string): Promise<void>

handleSendMessage(message: Message): Promise<void>

fetchSessionId(): Promise<void>

handlePressEnter(documentIds: string[]): void

React Effects


Important Implementation Details


Interaction with Other System Components


Usage Example

import React from 'react';
import { useSendSharedMessage, useSendButtonDisabled } from './use-send-shared-message';

const SharedChatComponent = () => {
  const {
    value,
    handleInputChange,
    handlePressEnter,
    sendLoading,
    derivedMessages,
    hasError,
    stopOutputMessage,
    scrollRef,
    messageContainerRef,
  } = useSendSharedMessage();

  const isDisabled = useSendButtonDisabled(value);

  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handlePressEnter([]);
    }
  };

  return (
    <div ref={messageContainerRef}>
      <div ref={scrollRef}>
        {derivedMessages.map(msg => (
          <div key={msg.id}>{msg.content}</div>
        ))}
      </div>
      <input
        value={value}
        onChange={handleInputChange}
        onKeyDown={onKeyDown}
        disabled={sendLoading}
      />
      <button onClick={() => handlePressEnter([])} disabled={isDisabled || sendLoading}>
        Send
      </button>
      {hasError && <div>Error sending message.</div>}
    </div>
  );
};

Mermaid Diagram: Flowchart of Main Functions and Their Relationships

flowchart TD
    A[useSendSharedMessage] --> B[useGetSharedChatSearchParams]
    A --> C[useCreateNextSharedConversation]
    A --> D[useHandleMessageInputChange]
    A --> E[useSendMessageWithSse]
    A --> F[useSelectDerivedMessages]

    A --> G[fetchSessionId]
    A --> H[sendMessage]
    A --> I[handleSendMessage]
    A --> J[handlePressEnter]

    G --> E
    H --> E
    I --> H
    J --> I
    J --> F
    J --> D

Summary

This file encapsulates the core logic for a shared chat message sending feature within a React application, using hooks to coordinate UI state, backend communication, and session management. It supports seamless message streaming, error handling, and conversation lifecycle management, enabling rich chat experiences in shared or embedded chat scenarios.