use-show-dialog.ts
Overview
The use-show-dialog.ts file provides a set of React hooks and utility functions designed to manage API keys (tokens) and display preview dialogs in a chat or canvas application context. It facilitates operations such as creating, removing, and listing system tokens, presenting confirmation dialogs for deletions, fetching statistical data for chart display, and opening preview windows for shared chat or canvas sessions.
This file primarily interacts with user settings hooks, dialog components, and React Query for asynchronous data fetching and caching. It encapsulates complex behaviors related to token lifecycle management and UI interaction workflows into reusable hooks, promoting modularity and clean separation of concerns.
Exports and Their Details
1. useOperateApiKey
Purpose
A custom React hook to manage system tokens related to a specific dialog or entity identified by idKey and optionally dialogId. It supports token creation, removal with user confirmation, and fetching the current list of tokens.
Parameters
idKey: string— The key identifying the type of entity (e.g.,'chatId','canvasId') for which the token is created or managed.dialogId?: string — Optional identifier representing a specific dialog or entity instance.
Returns
An object containing:
removeToken(token: string): void — Function to prompt the user with a confirmation dialog before removing the specified token.
createToken(): void — Function to create a new token associated with the provided
idKeyanddialogId.tokenList: Array — Array of tokens fetched from the system.
creatingLoading: boolean— Loading state flag for token creation.listLoading: boolean— Loading state flag for fetching the token list.
Usage Example
const { removeToken, createToken, tokenList, creatingLoading, listLoading } = useOperateApiKey('chatId', '12345');
// Create new token
createToken();
// Remove a token after confirmation
removeToken('token-string');
Implementation Details
Uses hooks
useRemoveSystemToken,useCreateSystemToken, anduseFetchSystemTokenListfor API interactions.Leverages
useShowDeleteConfirmto display a modal confirmation dialog before deletion.Uses
useCallbackto memoize the token creation function.
2. useSelectChartStatsList
Purpose
A custom React hook that retrieves and formats statistical data (of type IStats) from the React Query client cache, specifically for chart rendering.
Returns
An object (ChartStatsType) where each key corresponds to a stat category from IStats, and the value is an array of objects containing:
xAxis: string— The label for the X-axis (e.g., time or category).yAxis: number— The corresponding numeric value for the Y-axis.
type ChartStatsType = {
[k in keyof IStats]: Array<{ xAxis: string; yAxis: number }>;
};
Usage Example
const chartData = useSelectChartStatsList();
// chartData['someStat'] = [{ xAxis: "2023-06-01", yAxis: 10 }, ...]
Implementation Details
Uses
useQueryClientfrom React Query to access cached query data with key'fetchStats'.Transforms the raw stats array
[string, number][]into objects{xAxis, yAxis}.Returns an empty object if no stats are available.
3. getUrlWithToken
Purpose
A utility function that constructs a URL embedding a shared token and the source identifier, pointing to a shareable chat or canvas page.
Parameters
token: string— The shared token to embed in the URL.from?: string— The source context string, defaults to'chat'.
Returns
string— A URL string constructed based on the current window location, with query parameters for sharing.
Usage Example
const url = getUrlWithToken('abc123', 'canvas');
console.log(url); // e.g., "https://example.com/chat/share?shared_id=abc123&from=canvas"
4. usePreviewChat
Purpose
A custom React hook that manages the previewing of a chat or canvas session by opening a new browser tab/window with the appropriate shared URL.
Parameters
idKey: string— Identifier to distinguish between chat or canvas contexts.
Returns
An object with:
handlePreview(): Promise<void>— An async function that fetches a token and opens the preview URL in a new tab.
Usage Example
const { handlePreview } = usePreviewChat('canvasId');
<button onClick={handlePreview}>Preview</button>;
Implementation Details
Uses
useFetchTokenListBeforeOtherStepto retrieve or generate a token before preview.Uses
window.opento open the constructed URL in a new tab.Determines the
fromparameter in the URL based onidKey('Agent'for canvas,'Chat'otherwise).
Important Implementation Details and Algorithms
Token Management: The hook
useOperateApiKeyintegrates with backend APIs abstracted byuseCreateSystemToken,useRemoveSystemToken, anduseFetchSystemTokenListto provide a seamless token lifecycle.Confirmation Dialog: Before removing a token,
useShowDeleteConfirmpresents a confirmation UI, preventing accidental deletions.Data Transformation for Charts:
useSelectChartStatsListreshapes raw statistics data into a format optimized for charting libraries, transforming tuple arrays into objects with descriptive keys.Dynamic URL Construction:
getUrlWithTokenbuilds share URLs dynamically based on the current environment and token, ensuring correctness across different deployment contexts.Preview Workflow:
usePreviewChatensures a token is ready viahandleOperatebefore opening the preview window, preventing unauthorized or invalid previews.
Interaction with Other System Parts
Hooks from Other Modules: The file imports and utilizes multiple hooks (
useCreateSystemToken,useRemoveSystemToken,useFetchSystemTokenList,useShowDeleteConfirm,useFetchTokenListBeforeOtherStep) which likely interface with backend APIs or UI dialogs.Constants and Interfaces: Uses
SharedFromconstants to differentiate sharing contexts andIStatsinterface to type-check statistical data.React Query: Integrates with React Query (
useQueryClient) to access cached data, indicating this file participates in a broader data-fetching and state management strategy.Window Object: Uses browser
window.locationandwindow.openAPIs for URL construction and opening preview tabs.
Visual Diagram
flowchart TD
A[useOperateApiKey]
B[useSelectChartStatsList]
C[getUrlWithToken]
D[usePreviewChat]
A -->|calls| useRemoveSystemToken
A -->|calls| useCreateSystemToken
A -->|calls| useFetchSystemTokenList
A -->|calls| useShowDeleteConfirm
B -->|uses| useQueryClient
D -->|calls| useFetchTokenListBeforeOtherStep
D -->|calls| getUrlWithToken
classDef hook fill:#f9f,stroke:#333,stroke-width:1px;
class A,B,D hook;
Summary
use-show-dialog.ts is a utility and hook collection focused on managing system API tokens and enabling preview dialogs for chat or canvas entities. It centralizes token CRUD operations, confirmation dialogs, data formatting for charts, and URL generation for sharing. It leverages React Query for state caching and integrates with modular hooks for backend communication and UI interactions. This design supports maintainability, reusability, and clear separation of concerns within the application's token and preview management features.