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


Custom Hooks


1. useOperateApiKey

Manages creation and removal of system tokens with loading states and token list data.

useOperateApiKey(idKey: string, dialogId?: string)
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

2. useSelectChartStatsList

Transforms raw chat statistics from the React Query cache into a chart-friendly format.

useSelectChartStatsList(): ChartStatsType
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()
const { showTokenEmptyError } = useShowTokenEmptyError();
showTokenEmptyError(); // Displays "Token error" message

4. useShowBetaEmptyError

Similar to useShowTokenEmptyError, but for beta feature related errors.

useShowBetaEmptyError()
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()
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()
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)
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
{protocol}//{host}/chat/share?shared_id={token}&from={from}
const url = getUrlWithToken('abc123', 'agent');
// e.g. "https://example.com/chat/share?shared_id=abc123&from=agent"

Important Implementation Details & Algorithms


Interaction With Other Parts of the System

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.