use-chat-logic.ts
Overview
use-chat-logic.ts defines a custom React hook, useAwaitCompentData, that encapsulates the logic for managing and processing chat messages that require user inputs before proceeding. This hook primarily supports chat components or interfaces where the chat assistant sends a message containing form-like inputs, waits for user responses, and then processes those responses to continue the conversation.
The hook manages the extraction and transformation of input data from chat messages, provides handlers to process user submissions, and determines whether the chat is currently waiting for user input based on the latest messages.
This file is part of a chat system that integrates with UI components rendering chat messages, forms, or input interfaces, and it interacts with data structures representing chat messages and queries.
Detailed Explanation
Types and Imports
Imports:
MessageType— Constants defining message roles/types (e.g., Assistant).Message— Interface representing a chat message from the database.IMessage— Interface representing a chat message used in the UI.getfromlodash— Utility for safe property access.React hooks:
useCallbackanduseMemo.BeginQuery— Interface representing a query/input structure.buildBeginQueryWithObject— Utility to build a structured query object from input values.
Type Aliases:
IAwaitCompentData: Defines the props accepted by the hook:derivedMessages: Array ofIMessagerepresenting the current chat messages.sendFormMessage: Function to send form input data back to the chat system.canvasId: A string identifier associated with the current chat canvas/session.
Hook: useAwaitCompentData
const useAwaitCompentData = (props: IAwaitCompentData) => { ... }
This hook returns utility functions and state related to handling assistant messages that require user input.
Parameters
props: IAwaitCompentDataderivedMessages: IMessage[]— List of chat messages currently displayed or processed.sendFormMessage: (params: { inputs: Record<string, BeginQuery>; id: string; }) => void— Callback to send user input data back to the system.canvasId: string— Unique identifier for the chat session/context.
Returned Object
getInputs(message: Message): Record<string, BeginQuery>Extracts the
inputsobject from a message'sdataproperty.Returns a record mapping input keys to
BeginQueryobjects.
buildInputList(message: Message): Array<BeginQuery & { key: string }>Converts the inputs record into an array of input objects, each augmented with their key.
Useful for rendering inputs dynamically in UI components.
handleOk(message: Message): (values: BeginQuery[]) => voidReturns a handler function that processes user-submitted values for a given message.
It:
Retrieves current inputs from the message.
Uses
buildBeginQueryWithObjectto merge inputs with submitted values.Calls
sendFormMessagewith the updated inputs and currentcanvasIdto forward the data.
isWaitting: booleanA memoized boolean flag indicating if the system is currently waiting for user input.
Determined by checking if the last message in
derivedMessagesis from the assistant and containsdata(implying input fields to be filled).
Usage Example
import { useAwaitCompentData } from './use-chat-logic';
import { Message, IMessage } from '@/interfaces/database/chat';
const ChatComponent = ({ messages, sendFormMessage, canvasId }) => {
const { getInputs, buildInputList, handleOk, isWaitting } = useAwaitCompentData({
derivedMessages: messages,
sendFormMessage,
canvasId,
});
// Find the latest assistant message with inputs
const lastAssistantMessage = messages.findLast(
(msg) => msg.role === MessageType.Assistant && msg.data?.inputs
);
if (!lastAssistantMessage) {
return <div>No inputs required</div>;
}
const inputs = buildInputList(lastAssistantMessage);
const onSubmit = handleOk(lastAssistantMessage);
return (
<Form inputs={inputs} onSubmit={onSubmit} disabled={!isWaitting} />
);
};
Important Implementation Details
Use of
lodash.get: Safely accesses deeply nesteddata.inputsin message objects without throwing errors if intermediate properties are missing.React Hooks:
useCallbackmemoizes functions to prevent unnecessary re-renders and maintain stable references.useMemocalculates theisWaittingflag efficiently based on dependent messages.
Input Handling Logic:
The hook assumes that assistant messages may carry a
data.inputsobject representing the form fields required from the user.Upon user submission, inputs are merged and forwarded with context (
canvasId) for further backend processing or chat progression.
Interaction with Other Parts of the System
Chat UI Components: This hook typically supports UI components rendering chat messages and interactive forms, providing them with necessary logic to interpret inputs and handle submissions.
Message Data Layer: Depends on message structures defined in the system (
Message,IMessage) and constants likeMessageType.Utility Functions: Uses
buildBeginQueryWithObjectto transform raw input values into structured queries compatible with backend APIs or chat logic.Sending Data: The
sendFormMessagefunction is an external callback, likely connected to Redux actions, React context, or direct API calls to send user input data back to the chat service.
Mermaid Diagram - Flowchart of Main Functions and Their Relationships
flowchart TD
A[useAwaitCompentData(props)] --> B[getInputs(message)]
A --> C[buildInputList(message)]
A --> D[handleOk(message)]
A --> E[isWaitting]
D --> F[buildBeginQueryWithObject(inputs, values)]
D --> G[sendFormMessage({inputs, id})]
B --> H[Extract inputs from message.data.inputs]
C --> I[Convert inputs object to array with keys]
E --> J[Check last message role and data presence]
style A fill:#f9f,stroke:#333,stroke-width:2px
style B fill:#bbf,stroke:#333
style C fill:#bbf,stroke:#333
style D fill:#bbf,stroke:#333
style E fill:#bbf,stroke:#333
style F fill:#afa,stroke:#333
style G fill:#afa,stroke:#333
style H fill:#eee,stroke:#333,stroke-dasharray: 4 2
style I fill:#eee,stroke:#333,stroke-dasharray: 4 2
style J fill:#eee,stroke:#333,stroke-dasharray: 4 2
Summary
The use-chat-logic.ts file provides a reusable hook to process chat messages that require user input before continuing the conversation. By encapsulating input extraction, transformation, submission handling, and waiting state determination, it abstracts complex chat form logic, enhancing maintainability and UI integration. This hook is a key part of the interactive chat flow handling user-driven data submission in the system.