use-show-dialog.ts
Overview
The use-show-dialog.ts file provides a collection of React custom hooks primarily focused on managing system API keys (tokens) and previewing chat sessions in a web application. It encapsulates logic for creating, listing, and deleting API tokens, preparing chart statistics for visualization, and generating shareable URLs to preview chat dialogs. These hooks facilitate user interactions with tokens and chat previews, abstracting asynchronous operations and UI confirmations into reusable, declarative APIs.
Key functionalities include:
Managing system tokens: creation, removal, and listing.
Preparing chat statistics data formatted for charting components.
Opening shareable chat previews in new browser windows or tabs.
Integration with global query cache (via React Query) and shared dialog/token workflows.
Detailed Explanation of Exports
1. useOperateApiKey
A custom React hook designed to operate on API keys (tokens) related to a specific dialog or context. It provides methods to create and remove tokens, along with status flags and the current list of tokens.
Signature
useOperateApiKey(idKey: string, dialogId?: string): {
removeToken: (token: string) => void;
createToken: () => void;
tokenList: SystemToken[] | undefined;
creatingLoading: boolean;
listLoading: boolean;
}
Parameters
idKey: string
The key representing the identifier type, e.g.,"chatId"or"canvasId", which is used when creating a token.dialogId?: string
Optional identifier of the dialog or entity for which the token is created.
Returns
An object containing:
removeToken(token: string): void
Triggers a confirmation dialog and removes the specified token upon confirmation.createToken(): void
Creates a new token associated with the givenidKeyanddialogId.tokenList: SystemToken[] | undefined
The current list of system tokens fetched from the server.creatingLoading: boolean
Flag indicating whether a token creation request is in progress.listLoading: boolean
Flag indicating whether the token list is currently being fetched.
Usage Example
const {
removeToken,
createToken,
tokenList,
creatingLoading,
listLoading,
} = useOperateApiKey('chatId', '1234');
// Create a new token
createToken();
// Remove an existing token after confirmation
removeToken('token_abc123');
Implementation Details
Uses hooks from
@/hooks/user-setting-hooksto interact with backend APIs for token CRUD operations.Utilizes
useShowDeleteConfirmto display confirmation dialogs before deletion.Reactively updates loading states and token list data.
2. useSelectChartStatsList
A hook that extracts and formats chat statistics from the React Query cache for use in chart components.
Signature
useSelectChartStatsList(): ChartStatsType
Return Type
ChartStatsTypeis a mapped type where each key corresponds to a property ofIStats, and the value is an array of objects withxAxisandyAxisproperties, suitable for charting libraries.
type ChartStatsType = {
[k in keyof IStats]: Array<{ xAxis: string; yAxis: number }>;
};
Functionality
Reads cached data from React Query with the key
'fetchStats'.Converts raw statistics arrays (tuples) into objects with explicit property names for easier consumption by UI components.
Returns an empty object if no stats are cached.
Usage Example
const chartData = useSelectChartStatsList();
// chartData might look like:
// {
// messages: [{ xAxis: '2024-06-01', yAxis: 10 }, { xAxis: '2024-06-02', yAxis: 15 }],
// users: [{ xAxis: '2024-06-01', yAxis: 5 }, { xAxis: '2024-06-02', yAxis: 8 }],
// }
3. usePreviewChat
A hook enabling previewing a chat dialog by opening a shareable chat URL in a new browser tab/window.
Signature
usePreviewChat(idKey: string): {
handlePreview: () => Promise<void>;
}
Parameters
idKey: string
Identifier key that determines the context of the chat preview, affecting URL parameters.
Returns
handlePreview(): Promise<void>
Asynchronously obtains a token and opens the corresponding chat preview URL in a new tab.
Usage Example
const { handlePreview } = usePreviewChat('canvasId');
<button onClick={handlePreview}>Preview Chat</button>
Implementation Details
Utilizes
useFetchTokenListBeforeOtherStephook to ensure tokens are fetched/prepared before preview.Determines the source ("from") parameter in the URL based on the
idKeyto distinguish between different chat contexts (e.g., Agent vs Chat).Constructs the URL dynamically using the current window location and the share token.
Opens the generated URL in a new browser tab using
window.open.
Internal Utility Function: getUrlWithToken
Generates a shareable URL for a chat session based on a token and source.
getUrlWithToken(token: string, from: string = 'chat'): string
Constructs a URL using the current page's protocol and host.
Appends query parameters
shared_id(the token) andfrom(the source).Example output:
https://example.com/chat/share?shared_id=token123&from=chat
Important Implementation Details and Algorithms
Confirmation Dialog Before Deletion:
TheonRemoveTokenmethod uses a confirmation dialog hook (useShowDeleteConfirm) to prevent accidental token deletion, enhancing UX safety.React Query Integration:
TheuseSelectChartStatsListhook accesses cached queries directly viauseQueryClientto avoid redundant API calls and efficiently reformat data.Token Context Awareness:
TheusePreviewChathook smartly selects the "from" query parameter based on theidKey(canvasIdusesSharedFrom.Agent, otherwiseSharedFrom.Chat). This allows the backend or frontend to handle shared chats differently depending on their source.Hook Memoization:
useCallbackis used in critical functions (onCreateToken,open,handlePreview) to memoize callbacks and prevent unnecessary re-renders or effect re-executions.
Interaction with Other Parts of the System
Hooks Dependency:
useCreateSystemToken,useRemoveSystemToken, anduseFetchSystemTokenListare imported from@/hooks/user-setting-hooksand handle the actual API integrations for token management.useShowDeleteConfirmprovides UI confirmation dialogs.useFetchTokenListBeforeOtherStep(from@/components/embed-dialog/use-show-embed-dialog) ensures tokens are fetched before certain actions, indicating shared logic between embedded dialogs and token management.
Constants and Interfaces:
SharedFrom(from@/constants/chat) defines source identifiers for chat sharing URLs.IStats(from@/interfaces/database/chat) defines the shape of chat statistics data.
React Query:
Utilized for caching and querying asynchronous data, promoting performance and state consistency.Window Location and Navigation:
The preview feature depends onwindow.locationandwindow.opento generate and open URLs for shared chat sessions.
Visual Diagram
flowchart TD
A[useOperateApiKey] --> B[useRemoveSystemToken]
A --> C[useCreateSystemToken]
A --> D[useFetchSystemTokenList]
A --> E[useShowDeleteConfirm]
F[useSelectChartStatsList] --> G[useQueryClient]
H[usePreviewChat] --> I[useFetchTokenListBeforeOtherStep]
H --> J[getUrlWithToken]
H --> K[window.open]
classDef hook fill:#f9f,stroke:#333,stroke-width:1px,color:#000;
class A,F,H hook;
Summary
The use-show-dialog.ts file encapsulates reusable hooks that manage API keys (tokens) related to chat dialogs, facilitate safe deletion with confirmation, prepare chat statistics for visualization, and enable chat preview functionalities through shareable URLs. This file acts as a bridge between user interface components and backend services, leveraging React Query for efficient data management and React hooks for declarative asynchronous operations.
These hooks enhance modularity and maintainability by abstracting common operations related to token and chat preview workflows, making them easy to integrate into various parts of the application dealing with user settings, chat sharing, or analytics visualization.