hooks.ts
Overview
The hooks.ts file provides a collection of custom React hooks that manage API key operations, token handling, chat statistics data transformation, error notifications, modal visibility, and chat preview functionalities in a chat application. These hooks abstract common logic related to system tokens, such as creating, removing, fetching system tokens, and handling user interactions linked to tokens (e.g., showing modals or previewing chats). They leverage React Query for data caching and antd for user notifications, integrating translation support and modal state management.
This file acts as a bridge connecting UI components with backend token-related APIs and local UI states, encapsulating reusable logic to improve maintainability and clarity across the application.
Detailed Documentation
Imports
Constants and Hooks
SharedFrom- Enum or constants indicating the source of shared content (Agent vs Chat).Common hooks:
useSetModalState,useShowDeleteConfirm,useTranslatefor modal control, confirmation dialogs, and translations.User setting hooks for system token operations:
useCreateSystemToken,useFetchManualSystemTokenList,useFetchSystemTokenList,useRemoveSystemToken.
Third-party
useQueryClientfrom React Query for accessing cached query data.messagefrom Ant Design for displaying feedback messages.useCallbackfrom React for memoizing callbacks.
Custom Hooks
1. useOperateApiKey
Manages creation and removal of system tokens with loading states and token list data.
useOperateApiKey(idKey: string, dialogId?: string)
Parameters:
idKey(string): Key name used in the token creation payload, e.g.,'canvasId'or other identifier keys.dialogId(optional string): Value associated withidKeyto specify the dialog or entity the token relates to.
Returns:
An object containing:removeToken(token: string): void— Prompts a confirmation dialog and removes the token if confirmed.createToken(): void— Creates a new system token associated with the providedidKeyanddialogId.tokenList— Current list of system tokens.creatingLoading(boolean) — Loading state for token creation operation.listLoading(boolean) — Loading state for fetching the token list.
Usage Example:
const {
removeToken,
createToken,
tokenList,
creatingLoading,
listLoading,
} = useOperateApiKey('canvasId', 'dialog123');
createToken(); // Creates a new token for canvasId=dialog123
removeToken('token_abc'); // Shows confirm dialog before removing token_abc
Implementation Details:
Uses hooks from user setting modules to perform API operations. Removal is guarded with a confirmation dialog viauseShowDeleteConfirm. Creation usesuseCallbackto memoize the creation function.
2. useSelectChartStatsList
Transforms raw chat statistics from the React Query cache into a chart-friendly format.
useSelectChartStatsList(): ChartStatsType
Returns:
An object where keys correspond to different statistics types (matching keys inIStats), and values are arrays of objects each with:xAxis(string) — The label or timestamp for the chart's X-axis.yAxis(number) — The numerical value for the chart's Y-axis.
Implementation Details:
Uses
useQueryClientto extract cached data from queries with the key'fetchStats'.Converts each statistic from a tuple array
[string, number]into{ xAxis, yAxis }objects for charting.Returns an empty object if no data is present.
Usage Example:
const chartData = useSelectChartStatsList();
// chartData might be:
// { messages: [{ xAxis: "2024-01-01", yAxis: 10 }, ...], users: [...] }
3. useShowTokenEmptyError
Provides a callback to show an error message when no token is found.
useShowTokenEmptyError()
Returns:
showTokenEmptyError(): void— Shows a localized error message for empty tokens usingantd's message component.
Usage Example:
const { showTokenEmptyError } = useShowTokenEmptyError();
showTokenEmptyError(); // Displays "Token error" message
4. useShowBetaEmptyError
Similar to useShowTokenEmptyError, but for beta feature related errors.
useShowBetaEmptyError()
Returns:
showBetaEmptyError(): void— Shows a localized error message indicating a beta-related problem.
Usage Example:
const { showBetaEmptyError } = useShowBetaEmptyError();
showBetaEmptyError(); // Displays "Beta error" message
5. useFetchTokenListBeforeOtherStep
Fetches the system token list manually and provides a handler to validate token availability before performing other actions.
useFetchTokenListBeforeOtherStep()
Returns:
token(string) — The first token in the list or empty string if none.beta(string) — The beta status of the first token or empty string if none.handleOperate(): Promise<string | false>— Async function that fetches the system token list and:Returns the first token if available and beta is true.
Shows appropriate error messages otherwise and returns
false.
Implementation Details:
Uses
useFetchManualSystemTokenListfor manual fetching.Uses
useShowTokenEmptyErroranduseShowBetaEmptyErrorhooks for error notifications.The
handleOperatefunction is memoized withuseCallback.
Usage Example:
const { token, beta, handleOperate } = useFetchTokenListBeforeOtherStep();
const proceed = await handleOperate();
if(proceed) {
// Proceed with token-based operation
}
6. useShowEmbedModal
Manages the visibility of an embed modal, showing it only if token requirements are met.
useShowEmbedModal()
Returns:
showEmbedModal(): Promise<void>— Validates tokens and shows the embed modal if validation succeeds.hideEmbedModal(): void— Hides the embed modal.embedVisible(boolean) — Current visibility state of the embed modal.embedToken(string) — The token used for embedding (first token in the list).beta(string) — Beta status of the token.
Implementation Details:
Uses
useSetModalStateto control modal visibility.Relies on
useFetchTokenListBeforeOtherStepto validate tokens before opening the modal.
Usage Example:
const {
showEmbedModal,
hideEmbedModal,
embedVisible,
embedToken,
beta,
} = useShowEmbedModal();
<button onClick={showEmbedModal}>Open Embed</button>
{embedVisible && <EmbedModal token={embedToken} />}
7. usePreviewChat
Provides functionality to open a preview window for a chat or agent canvas using a token.
usePreviewChat(idKey: string)
Parameters:
idKey(string): Key to determine the source for the share URL (e.g.,'canvasId'indicates an Agent share, otherwise Chat).
Returns:
handlePreview(): Promise<void>— Validates token availability and opens a new browser tab/window with a share URL constructed from the token.
Implementation Details:
Uses
useFetchTokenListBeforeOtherStepfor token validation and fetching.Constructs the URL with
getUrlWithTokenhelper function, which builds a share URL based on current browser location and token.
Usage Example:
const { handlePreview } = usePreviewChat('canvasId');
<button onClick={handlePreview}>Preview Chat</button>;
Helper Functions
getUrlWithToken
Constructs a URL for sharing chat sessions via token.
getUrlWithToken(token: string, from: string = 'chat'): string
Parameters:
token(string): The system token to include in the URL query.from(string, optional): The source type, defaults to'chat'.
Returns:
A fully qualified URL string pointing to the shared chat page with query parameters:
{protocol}//{host}/chat/share?shared_id={token}&from={from}
Usage Example:
const url = getUrlWithToken('abc123', 'agent');
// e.g. "https://example.com/chat/share?shared_id=abc123&from=agent"
Important Implementation Details & Algorithms
Token Management: The hooks abstract token creation and removal operations, ensuring UI feedback and confirmation dialogs are handled consistently. Token lists are fetched and cached using React Query for efficiency.
Data Transformation for Charts: Raw stats data stored as tuples are transformed into objects with explicit
xAxisandyAxiskeys, making them compatible with chart components.Error Handling: User-visible error messages for missing tokens or beta features use translation hooks and standard UI notification components for consistency.
Modal Control: Modal visibility is managed via
useSetModalState, providing an encapsulated way to show/hide modals triggered by token validation.Token Validation Workflow: Before performing sensitive operations (e.g., showing embed modals or previewing chats), tokens are validated for presence and beta status to ensure correct application behavior and user feedback.
Window Open Behavior: Opening share URLs in new tabs/windows is carefully constructed based on token and source, enhancing user experience for previewing shared chats or agents.
Interaction With Other Parts of the System
User Setting API Hooks: Relies on hooks like
useCreateSystemToken,useFetchSystemTokenList,useRemoveSystemTokenfrom user-setting modules for API communication.Chat Constants: Uses
SharedFromconstants to define the source of shared chats (Agent vs Chat).Common UI Hooks: Uses
useSetModalStateanduseShowDeleteConfirmfor modal and confirmation dialogs.Internationalization: Uses
useTranslateto fetch localized strings for error messages.React Query: Interfaces with the React Query cache for efficient data retrieval and synchronization.
Ant Design Message: Uses
message.errorfor displaying error notifications.
These hooks are intended to be used in React components related to user settings, chat sharing, embed modals, and chat preview features.
Visual Diagram
flowchart TD
A[useOperateApiKey] -->|calls| B[useRemoveSystemToken]
A -->|calls| C[useCreateSystemToken]
A -->|calls| D[useFetchSystemTokenList]
A -->|uses| E[useShowDeleteConfirm]
F[useSelectChartStatsList] -->|uses| G[useQueryClient]
H[useShowTokenEmptyError] -->|uses| I[useTranslate]
H -->|calls| J[message.error]
K[useShowBetaEmptyError] -->|uses| I
K -->|calls| J
L[useFetchTokenListBeforeOtherStep] -->|uses| M[useShowTokenEmptyError]
L -->|uses| N[useShowBetaEmptyError]
L -->|uses| O[useFetchManualSystemTokenList]
P[useShowEmbedModal] -->|uses| Q[useSetModalState]
P -->|uses| L
R[usePreviewChat] -->|uses| L
R -->|calls| S[getUrlWithToken]
classDef hooks fill:#f9f,stroke:#333,stroke-width:1px;
class A,F,H,K,L,P,R hooks;
Summary
The hooks.ts file is a utility layer that encapsulates complex token-related logic and UI state management for a chat application. It improves component simplicity by providing focused, reusable hooks for token operations, error handling, chart data prep, modal display control, and chat previewing functionality. This design promotes separation of concerns and integrates closely with backend APIs, React Query caching, and UI libraries.